def parse_wifi_scan(self, scan_result, current_freq=0): lines = scan_result.split('\n') result = [] mac = False strength = False ssid = False last_seen = False frequency = False for line in lines: if not mac: if line.startswith('BSS'): mac = re.search(self.macfilter, line).group(0) elif not strength: if line.lstrip().startswith('signal'): strength = line.split(' ')[1] elif not ssid: if line.lstrip().startswith('SSID'): ssid = line.split(' ')[1] elif not last_seen: if line.lstrip().startswith('last'): last_seen = line.split(' ')[2] elif not frequency: if line.lstrip().startswith('freq'): frequency = line.split(' ')[1] if (int(current_freq) == int(frequency) or int(current_freq) == 0) and ( int(last_seen) <= self.discard_data_thresh_ms): result.append( Wifi(mac, ssid, strength, last_seen, frequency)) mac = False ssid = False strength = False last_seen = False frequency = False return result
def main(): if len(sys.argv) >= 2: if sys.argv[1] == "--ssid" or sys.argv[1] == "-s": listWifi() elif (sys.argv[1] == "--connect" or sys.argv[1] == "-c") and len( sys.argv) == 4: ssid = sys.argv[2] psk = sys.argv[3] wifi = Wifi() p = scanWifi() wifi = next((x for x in wifis if x.ssid == ssid), None) if wifi != None: wifi.password = psk wifi.connect() print(wifi.ssid) print(wifi.channel) print(wifi.signal) print(wifi.encryption_type) else: print("SSID not found.") else: print("Wrong command.")
def should_have_printed_usage_instructions(monkeypatch) -> None: print_coloured_calls = [] mock_parse_argv(MODULE_NAME, 'Wifi', monkeypatch) monkeypatch.setattr(f"{MODULE_NAME}.print_coloured", lambda *a, **k: print_coloured_calls.append('')) Wifi().usage() assert len(print_coloured_calls) == 2
def main(): zoom = 15 tft = m5stack.Display() tft.text(10, 10, "> Reading settings.\n") with open("/flash/settings.json") as fp: settings = json.loads(fp.read()) tft.text(10, tft.LASTY, "> Connecting to wifi.\n") wifi = Wifi(settings["username"], settings["password"]) tft.text(10, tft.LASTY, "> Scanning networks.\n") networks = wifi.scan() tft.text(10, tft.LASTY, "> Locating current position.\n") geolocation = Geolocation(settings["api_key"], networks) coordinates = geolocation.coordinates() tft.text(10, tft.LASTY, "> Downloading the map.\n") map = Map(coordinates) map.save("/flash/map.jpg") tft.image(0, 0, "/flash/map.jpg") button_a = DigitalInput(Pin(m5stack.BUTTON_A_PIN, Pin.IN), callback=lambda pin: zoom_in_handler(map, tft)) button_c = DigitalInput(Pin(m5stack.BUTTON_C_PIN, Pin.IN), callback=lambda pin: zoom_out_handler(map, tft))
def __init__(self, *args, **kwargs): print("Starting installer...") settings = Settings() from wifi import Wifi w = Wifi(parent=self, settings=settings.modules[0]["settings"]) w.connect()
def local(): wifi = Wifi( ssid=CONFIG["WIFI_SSID"], password=CONFIG["WIFI_PASSWORD"], gmt=CONFIG["GMT"], ) wifi.connect(1)
def __call__(self, *args): if len(args[1]) > 0: key = args[1][0] file = open('/flash/etc/settings.txt') settings = json.loads(file.read()) file.close() if key == '-init': self.wifi_handler = Wifi() elif key in ['-sta', '--station']: if len(args[1]) > 1: password = '' ssid = args[1][1] if len(args[1])> 2: password = args[1][2] self.wifi_handler.connect_given(ssid, password) else: self.wifi_handler.connect() elif key in ['-ap', '--startAP']: self.wifi_handler.startAP() elif key in ['-i', '--info']: sta_ssid = self.wifi_handler.current_ssid sta_ip = self.wifi_handler.sta.ifconfig()[0] ap_ssid = self.wifi_handler.ap.config('essid') if self.wifi_handler.ap.active() else 'N/A' ap_ip = self.wifi_handler.ap.ifconfig()[0] print('STA:', sta_ssid, makeTab(sta_ssid, 15), sta_ip + makeTab(sta_ip, 15), green('Connected') if self.wifi_handler.sta.isconnected() else red('Not connected')) print('AP: ', ap_ssid, makeTab(ap_ssid, 15), ap_ip + makeTab(ap_ip, 15), green('Active') if self.wifi_handler.ap.active() else red('Inactive')) elif key in ['-s', '--scan']: self.wifi_handler.scan() print(*[i[0] + makeTab(i[0], 20) + str(i[1]) + ' dBm \t' + i[2] for i in self.wifi_handler.scanned], sep ='\n') elif key in ['-cap', '--changeAP'] and len(args[1]) > 1: settings['network']['ap'][0] = args[1][1] if len(args[1]) > 2: settings['network']['ap'][1] = args[1][2] else: settings['network']['ap'][1] = '' elif key in ['-a', '--add'] and len(args[1]) > 1: if len(args[1]) > 2: settings['network']['wifi'][args[1][1]] = args[1][2] else: settings['network']['wifi'][args[1][1]] = '' elif key in ['-d', '--delete'] and len(args[1]) > 1: res = settings['network']['wifi'].pop(args[1][1], -1) if res == -1: print(red('No such SSID found')) elif key in ['-t', '--timeout']: if len(args[1]) > 1 and args[1][1].isdigit(): timeout = int(args[1][1]) if timeout != 0: settings['network']['wifiConnectionTimeout'] = timeout print('Timeout:', settings['network']['wifiConnectionTimeout']) else: print(red('No valid key provided or arguments are missing')) file = open('/flash/etc/settings.txt', 'w') file.write(json.dumps(settings)) file.close()
def should_have_executed(monkeypatch, argv: List[str], on: bool) -> None: def mock_set_wifi(*args: tuple, **kwargs: dict) -> str: assert args[1] == on return '' mock_parse_argv(MODULE_NAME, 'Wifi', monkeypatch, argv) monkeypatch.setattr(f"{MODULE_NAME}.Wifi.set_wifi", mock_set_wifi) assert Wifi().execute() == ''
def setup_wifi(): try: w = Wifi() w.set_hostname(MY_HOST) except OSError as ose: logger.print_error("WIFI Setup Failed!") raise return w
def execute(self) -> str: log('Hello!') automations = [ Bluetooth(['on']), Wifi(['on']), ] for automation in automations: automation.execute() return ''
def main(): display = None wifi = None weather = None adc = ADC(0) try: display = DisplayMax(sck_pin=14, mosi_pin=13, miso_pin=12, ss_pin=16, brightness=15) display.set_brightness( map_value(adc_read_oversample(adc, 32), 50, 1024, 0, 15)) config = Config(file_name='config.json') weather = Weather(api_key=config.api_key, location=config.location) wifi = Wifi(config.wifi_ssid, config.wifi_password) except OSError as e: print(e) display.show('E 01') log_error(e) return except KeyError as e: print(e) display.show('E 02') log_error(e) return except Exception as e: print(e) display.show('E 09') log_error(e) return while True: try: if not wifi.is_connected(): wifi.connect() weather.update() display.set_brightness( map_value(adc_read_oversample(adc, 32), 50, 1024, 0, 15)) display.number(weather.temperature) sleep(60) display.show('UP ') sleep(1) except WifiConnectError as e: print(e) display.show('E 11') sleep(10) except WeatherUpdateError as e: print(e) display.show('E 12') sleep(10) except Exception as e: print(e) display.show('E 19') log_error(e) break
def readWifiFromFile(self, f): line = f.readline() while line and line[0] != "#": if not line.isspace(): info = re.findall(r'^(.+),(.+)$', line)[0] self.addWifi(Wifi(info[0], info[1])) line = f.readline() return line
def setup_wifi(): try: w = Wifi() w.set_hostname(MY_HOST) w.connect(WIFI_SSID, WIFI_PASS) w.info() except OSError as ose: logger.print_error("WIFI Setup Failed!") raise return w
def execute(self) -> str: log('Good night!') automations = [ Volume(['0.0']), Bluetooth(['off']), Wifi(['off']), Sleep(), ] for automation in automations: automation.execute() return ''
def should_not_have_parsed_argv_with_wrong_or_no_option( monkeypatch, argv: List[str]) -> None: def mock_raise_error(*args: tuple, **kwargs: dict) -> None: assert kwargs['usage'] is not None raise SystemExit(0) # Controlled early exit monkeypatch.setattr(f"{MODULE_NAME}.raise_error", mock_raise_error) with pytest.raises(SystemExit) as e: Wifi(argv) assert e.type == SystemExit assert e.value.code == 0
async def __setup_wifi(self): hw.log.debug("Setting up wifi ...") if hw.WIFI: from wifi import Wifi wifi = Wifi(hostname=hw.DEVICE_NAME, pin=hw.WIFI_LED_PIN) dev.OPERATORS.append(wifi) if await wifi.async_connect(): hw.log.debug(wifi.get_info()) else: hw.log.error("Wifi connectionf failed") create_task(wifi.monitor())
def test_string(self): # Get the string out correctly ''' String-ify the wifi configuration according to the definition found here: http://code.google.com/p/zxing/wiki/BarcodeContents#Wifi_Network_config_(Android) The result is like this: WIFI:T:WPA;S:mynetwork;P:mypass;; Parameter Example Description T WPA Authentication type; can be WEP or WPA S mynetwork Network SSID P mypass Password''' uut = Wifi(password='******', ssid='mynetwork', auth='WPA') self.assertEqual(uut.__str__(), 'WIFI:T:WPA;S:mynetwork;P:mypass;;')
async def demo_async(): wifi = Wifi('ybb-home') print(wifi.check_wifi_config()) print(await wifi.async_connect()) await asyncio.sleep(1) print(wifi.get_info()) asyncio.create_task(wifi.monitor()) for i in range(0, 50): print(i) if i == 15: print("test disconnection") wifi.disconnect() await asyncio.sleep(1)
def init_transform(data): print('main_state: init') data['config'] = Config() data['config_server'] = ConfigServer() data['mqtt_server'] = None data['smart_plug'] = SmartPlug() data['wifi'] = Wifi() reset_counter = ResetCounter() smart_plug = data['smart_plug'] smart_plug.on_toggle(reset_counter.push) return 'config/load'
def scanWifi(): content = iw_parse.scan(interface='wlan0') cells = iw_parse.parse(content) isFirstWifi = True wifi = Wifi() for cell in cells: if re.search('channel', str(cell)) is not None: if isFirstWifi == True: isFirstWifi = False if isFirstWifi == False: wifis.append(wifi) wifi = Wifi() tempchannel = re.search("'channel': '(.*)', 'signal_quality':", str(cell)) wifi.channel = tempchannel.group(1).strip("\'") #print(wifi.channel) if re.search('signal_level_dBm', str(cell)) is not None: tempsignal_level = re.search( "'signal_level_dBm': '(.*)', 'encryption':", str(cell)) wifi.signal = tempsignal_level.group(1).strip("\'") #print(wifi.signal) if re.search('encryption', str(cell)) is not None: tempencryption = re.search("'encryption': '(.*)', 'essid':", str(cell)) wifi.encryption_type = tempencryption.group(1).strip("\'") #print(wifi.encryption_type) if re.search('essid', str(cell)) is not None: tempssid = re.search("'essid': '(.*)'}", str(cell)) wifi.ssid = tempssid.group(1).strip("\'")
def prepareForTakeoff(self): logging.info('drone starting') timestart = time.time() # connect to tello self.wifi = Wifi(tello_ssid, retry=15) connected = self.wifi.connect() if not connected: return False # open cmd socket self.cmd.open() # put the Tello into "command" mode, which starts the telemetry stream result = self.cmd.sendCommand("command") if result != 'ok': logging.info('Tello failed to enter "command" mode. abort.') return False logging.info('Tello is in "command" mode') # open telemetry socket and start thread self.telemetry.open() self.telemetry.start() # check battery batt = self.cmd.sendCommand("battery?") if int(batt) < safe_battery: logging.error('battery low. aborting.') return False logging.info('battery check goahead') # start video so = self.cmd.sendCommand("streamon") if so != 'ok': logging.error('tello streamon failed. aborting.') return False # open video socket and start thread self.video.open() # blocks until started, about 5 seconds self.video.start() # can we wait for video thread to start here? # ready for takeoff: # command mode, good battery, video running, telemetry running, ui open self.state = 'ready' logging.info(f'ready for takeoff, elapsed={time.time()-timestart}') return True
def __init__(self, *args, **kwargs): super(Iot, self).__init__(*args, **kwargs) try: print('mqtt running') self.client = MQTTClient(self.client_id, "mqtt.eclipse.org", keepalive=0) self.client.connect() self.client.set_callback(self.on_message) self.client.subscribe(b"sooko/lampu") while True: self.client.wait_msg() except: print('mqtt stoped') Wifi().disconnect() machine.reset()
def should_have_set_wifi(monkeypatch, on: bool) -> None: def mock_execute_cmd(*args: tuple, **kwargs: dict) -> str: if args[0] == ['networksetup', '-listallhardwareports']: return f"\nHardware Port: Wi-Fi\nDevice: {device_name}\n" else: assert args[0] == [ 'networksetup', '-setairportpower', device_name, ('on' if on else 'off') ] return '' device_name = next_alphabetic(10) mock_parse_argv(MODULE_NAME, 'Wifi', monkeypatch) monkeypatch.setattr(f"{MODULE_NAME}.execute_cmd", mock_execute_cmd) mute_logs(MODULE_NAME, monkeypatch) assert Wifi().set_wifi(on) == ''
class Mqtt(object): pwm = PWM(led_board) wifi = Wifi() wifi.connect() client_id = ubinascii.hexlify(machine.unique_id()) server = "192.168.43.165" topic = b"ruang_tamu" def __init__(self, *args, **kwargs): super(Mqtt, self).__init__(*args, **kwargs) self.client = MQTTClient(self.client_id, self.server) # self.client = MQTTClient(self.client_id,"m16.cloudmqtt.com",port=10490 ,user='******', password='******') try: led_green.value(1) print( "mqtt sedang berjalan dan menunggu message dengan topic= {} ". format(self.topic)) self.client.connect() self.client.set_callback(self.sub_cb) self.client.subscribe(self.topic) while True: self.client.wait_msg() except: print("koneksi wifi atau server terputus") led_green.value(0) time.sleep(5) machine.reset() def sub_cb(self, topic, msg): print("topic ={}".format(topic.decode())) print("message = {}".format(msg.decode())) if msg == b"led_on": led_blue.value(1) if msg == b"led_off": led_blue.value(0) if msg.isdigit(): self.pwm.freq(1024) self.pwm.duty(1024 - int(msg))
def __init__(self): self.wifi = Wifi( ssid=CONFIG["WIFI_SSID"], password=CONFIG["WIFI_PASSWORD"], gmt=CONFIG["GMT"], ) self.mqtt = Mqtt( ip=CONFIG["MQTT_IP"], user=CONFIG["MQTT_USER"], password=CONFIG["MQTT_PASS"], keepalive=CONFIG["MQTT_KEEPALIVE"], ) self.mqtt.set_last_will( topic=CONFIG["LW_TOPIC"], msg=ujson.dumps(CONFIG["LW_MSG_OFFLINE"]), retain=CONFIG["LW_RETAIN"], qos=CONFIG["LW_QOS"], ) self.dht22 = DHT22(Pin(CONFIG["DHT22_PIN"])) self.is_sending_synchronizate = False
def cwifi(): from wifi import Wifi w = Wifi() w.active(True) w.connect()
from mqtt import Mqtt from wifi import Wifi from sys_op import SysOp from op import Controller import uasyncio as asyncio from sensor import SensorProcess from consumer import DefaultConsumer import dev logging._level = logging.DEBUG opc = Controller() sp = SensorProcess() def_consumer = DefaultConsumer() ops = [] wifi = Wifi('ybb-home') ops.append(wifi) ops.append(SysOp(opc)) ops.append(def_consumer) mqtt = Mqtt(opc) ops.append(mqtt) opc.setup(ops) opc.set_mqtt(mqtt) consumers = [] consumers.append(def_consumer) consumers.append(mqtt) print(opc.commands.keys())
async def test(): wifi = Wifi('ybb-home') await wifi.async_connect() await http_run(opc, True)
from wifi import Wifi from hw import log from scheduler import Scheduler from sys_op import SysOp from consumer import DefaultConsumer from relay import Relay from http import http_run from op import Controller import uasyncio as asyncio logging._level = logging.DEBUG opc = Controller() ops = [] sch = Scheduler(opc) sch.setup() ops.append(Wifi('ybb-home')) ops.append(sch) ops.append(Relay(2)) ops.append(SysOp(opc)) ops.append(DefaultConsumer()) opc.setup(ops) print(opc.commands.keys()) async def test(): wifi = Wifi('ybb-home') await wifi.async_connect() await http_run(opc, True) if __name__ == '__main__':
empty_group_string="Desktop", mouse_callbacks={ "Button3": next_window(), }, ), Spotify( mouse_callbacks={ "Button1": lazy.spawn(f"{MUSIC_CTRL}PlayPause"), "Button3": spawn_or_focus("spotify"), } ), widget.Systray(padding=10, background=colors["background"]), widget.Sep(padding=8, foreground=colors["background"]), Wifi( foreground=colors["primary"], mouse_callbacks={"Button1": notification("wifi")}, padding=10, ), VolumeCtrl( padding=10, foreground=colors["primary"], ), widget.Clock( foreground=colors["text"], format="%H:%M", padding=10, mouse_callbacks={ "Button1": notification("date"), "Button3": lazy.spawn("python -m webbrowser https://kalender.se"), }, ),