Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import subprocess
- import shlex
- import time
- from RPi import GPIO
- CLIENT_MODE = 19
- AP_MODE = 26
- def run(program):
- proc = subprocess.Popen(shlex.split(program), stderr=subprocess.PIPE, stdout=subprocess.PIPE)
- return proc.communicate()[0].decode()
- def is_connected(dev):
- data = run('/bin/ip link show').splitlines()
- for line in data:
- if '{}:'.format(dev) in line:
- return True
- else:
- return False
- def remove_ip(dev):
- run('/bin/ip addr flush dev {}'.format(dev))
- def set_ip(dev, ip):
- run('/bin/ip add add dev {dev} {ip}/24'.format(dev=dev, ip=ip))
- def kill_wpa():
- run('/usr/bin/pkill -9 wpa_supplicant')
- def start_dhclient(dev):
- run('/sbin/dhclient -nw {}'.format(dev))
- def kill_dhclient():
- run('pkill -9 dhclient')
- def kill_hostapd():
- run('/bin/systemctl stop hostapd')
- def dnsmasq(action):
- run('/bin/systemctl {} dnsmasq'.format(action))
- def kill(dev):
- dnsmasq('stop')
- kill_dhclient()
- kill_wpa()
- kill_hostapd()
- remove_ip(dev)
- def client(dev, conf):
- if is_connected(dev):
- kill(dev)
- time.sleep(1)
- cmd = '/sbin/wpa_supplicant -Dnl80211 -i{dev} -c {conf} -B'.format(dev=dev, conf=conf)
- run(cmd)
- start_dhclient(dev)
- def ap(dev):
- if is_connected(dev):
- kill(dev)
- #cmd = '/usr/sbin/hostapd /etc/hostapd/hostapd.conf -B'
- cmd = '/bin/systemctl start hostapd'
- run(cmd)
- set_ip(dev, '192.168.0.254')
- dnsmasq('start')
- def status(ap_mode, client_mode):
- if ap_mode:
- print("Activating Access Point Mode")
- ap('wlan0')
- elif client_mode:
- print("Activating Client Mode")
- client('wlan0', '/home/server/China2.conf')
- else:
- print('Switch is not connected')
- print('Starting Access Point Mode')
- ap('wlan0')
- class Switch:
- def __init__(self, callback):
- GPIO.setmode(GPIO.BCM)
- GPIO.setup(AP_MODE, GPIO.IN, GPIO.PUD_UP)
- GPIO.setup(CLIENT_MODE, GPIO.IN, GPIO.PUD_UP)
- self.ap_mode = GPIO.input(AP_MODE)
- self.client_mode = GPIO.input(CLIENT_MODE)
- self.callback = callback
- self.callback(self.ap_mode, self.client_mode)
- def update(self):
- ap_mode = GPIO.input(AP_MODE)
- client_mode = GPIO.input(CLIENT_MODE)
- #print('AP: {}\tCLIENT: {}'.format(ap_mode, client_mode))
- if ap_mode != client_mode:
- if ap_mode != self.ap_mode or client_mode != self.client_mode:
- self.ap_mode = ap_mode
- self.client_mode = client_mode
- self.callback(ap_mode, client_mode)
- def run(self):
- while True:
- self.update()
- time.sleep(2)
- if __name__ == '__main__':
- switch = Switch(status)
- switch.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement