def local(): wifi = Wifi( ssid=CONFIG["WIFI_SSID"], password=CONFIG["WIFI_PASSWORD"], gmt=CONFIG["GMT"], ) wifi.connect(1)
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 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 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 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 cwifi(): from wifi import Wifi w = Wifi() w.active(True) w.connect()
class wifi(Command): def __init__(self): super().__init__('Handle Wifi connection and settings', {'-init': ['Run initialize sequence'], '-sta, --station': ['<ssid>', '<pass>', 'Disadle AP and try to connect to Wifi network. Uses knowns list if no SSID provided, if no connection estabilished - enables AP. If network has no password, type in only SSID argument'], '-ap, --startAP': ['Disadle STA and activate AP'], '-i, --info': ['Show STA and AP state and IP\'s'], '-s, --scan': ['Show available Wifi networks'], '-cap, --changeAP': ['<ssid>', '<password>', 'Change AP SSID and password'], '-a, --add': ['<ssid>', '<password>', 'Add new Wifi network to knowns list'], '-d, --delete': ['<ssid>', 'Delete Wifi network from knowns list'], '-t, --timeout': ['<timeout>', 'Get or set Wifi connection timeout (10 seconds by default)'],}) 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()
from button import Button from fan import Fan from wifi import Wifi from config import * import socket def dbg(msg): print("Info: " + msg) # Connect Wifi wifi = Wifi() wifi.connect(SSID, PWD) # Init Button btn = Button(BTN_PIN, BTN_IDLE) # Init Fan fan = Fan(FAN_PIN, FAN_DEFAULT_FREQ, FAN_DEFAULT_DUTY) # Server addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] s = socket.socket() s.bind(addr) s.listen(5) while True: cl, addr = s.accept() cl_file = cl.makefile('rwb', 0)
def buildMap(data): pass # start mode = 'prod' for i, arg in enumerate(sys.argv): if arg == 'test': mode = 'test' log('eyes starting ' + mode) # connect to tello wifi = Wifi(tello_ssid) connected = wifi.connect() if not connected: quit() # Create cmd socket as UDP client cmdsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) cmdsock.settimeout(cmdsock_timeout) #sock.bind(locaddr) # bind is for server ??? log('cmdsock open') # Create telemetry socket as UDP server telemetrysock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) telemetrysock.settimeout(telemetrysock_timeout) telemetrysock.bind(telemetry_address) # bind is for server, not client log('telemetrysock open')
class Main: """ Main class for full logic this program. Run this class by call 'main' """ 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 _send_data(self): """ Meas dht22 data and publish temperature and humidity via mqtt. """ try: local_time = localtime()[:-2] # remove mili and micro seconds self.dht22.measure() # important for take actual values temp = { "name": CONFIG["NAME_DEVICE"], "date": local_time, "value": str(self.dht22.temperature()), } hum = { "name": CONFIG["NAME_DEVICE"], "date": local_time, "value": str(self.dht22.humidity()), } self.mqtt.publish(CONFIG["TOPIC_TEMP"], ujson.dumps(temp), retain=True) self.mqtt.publish(CONFIG["TOPIC_HUM"], ujson.dumps(hum), retain=True) except Exception as ex: print("\t_send_data unable to send `{}`".format(ex)) pass # Main loop def main(self): """ Main loop. """ start = ticks_ms() first_start = True # defined for timing interval while True: sleep_ms(50) ######## WIFI CHECK if not self.wifi.is_connected(): self.is_sending_synchronizate = False self.mqtt.disconnect() self.wifi.connect() # infinity loop for connecting to wifi ######## MQTT CHECK if not self.mqtt.is_connected(): self.is_sending_synchronizate = False if not self.mqtt.connect(): sleep(10) continue else: # on connect self.mqtt.publish( CONFIG["LW_TOPIC"], ujson.dumps(CONFIG["LW_MSG_ONLINE"]), retain=True, ) ######## INTERVAL & SEND DATA ### check sending data with synchro time if CONFIG["SYNC_SEND_DATA"]: # if synchronizate sending setted # waiting on whole minute with 0 seconds if not self.is_sending_synchronizate: second = localtime()[5] if second != 0: # if not synchronizated continue self.is_sending_synchronizate = True #### Sending data # timing sending data this way is not the best solution # if you want excelent timig. Find better solution. diff = ticks_diff(ticks_ms(), start) # ms if first_start or diff >= CONFIG["INTERVAL_SEND_DATA"] * 1000: first_start = False start = ticks_ms() self._send_data()
import picoweb from renderer import Renderer from wifi import Wifi from machine import Pin wifi = Wifi() wifi.connect() renderer = Renderer('templates') app = picoweb.WebApp('onAir') pins = [Pin(18, Pin.OUT), Pin(5, Pin.OUT), Pin(33, Pin.OUT), Pin(25, Pin.OUT)] state = False for pin in pins: pin.value(0) @app.route('/') def index(req, resp): yield from picoweb.start_response(resp) yield from resp.awrite(renderer.render_template('template.html')) @app.route('/recording') def recording(req, resp): if req.method == 'POST': yield from req.read_form_data() else: yield from resp.awrite('Invalid Method') if req.form['on'] == "ON": for cpin in pins: cpin.value(1)
print(''.join(['random seed: ', str(seed)])) return seed if __name__ == '__main__': # holder for the cheerlight objects cheerlights = [ Cheerlight(Pin(pin, Pin.OUT), NUM_PIXELS) for pin in PIXEL_PINS ] # seed the random generator from the analog pin urandom.seed(generate_seed()) # connect wifi wifi = Wifi() online = wifi.connect() cheerlights_confirm(cheerlights, online) # holders for colour name prev_color = '' count = 0 last_update = time.time() - INTERVAL # immediate update while True: if time.time() > last_update + INTERVAL: if online: received_color = api_request(API) else: received_color = 'blue' # received_color = Cheerlight.random_color()
class Drone: def __init__(self, telemetry_callback=empty, video_callback=empty): self.state = 'start', # start, ready, takeoff, airborne, land, down self.wifi = False # create three objects, one for each socket self.telemetry = Telemetry(telemetry_callback) self.cmd = Cmd() self.video = Video(video_callback) 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 wait(self): # BLOCKING until sub threads stopped logging.info('start join') self.video.join() self.telemetry.join() logging.info('end join') def stop(self): if self.state == 'airborne': self.do('land') self.telemetry.stop() self.video.stop() self.cmd.close() logging.info('drone shutdown') logging.info('restoring wifi') self.wifi.restore() def do(self, cmd): if 'takeoff' in cmd: self.state = 'takeoff' if 'land' in cmd: self.state = 'land' result = self.cmd.sendCommand(cmd) if 'takeoff' in cmd: self.state = 'airborne' if 'land' in cmd: self.state = 'down'