def connect_wifi(duration=None): if wifi.status(): return True rgb.clear() data, size, frames = animation_connecting_wifi rgb.framerate(3) rgb.gif(data, (12, 0), size, frames) wifi.connect() if duration is not None: wifi.wait(duration=duration) else: wifi.wait() if not wifi.status(): data, frames = icon_no_wifi rgb.gif(data, (12, 0), (8, 8), frames) time.sleep(3) rgb.clear() rgb.framerate(20) del data, size, frames gc.collect() return wifi.status()
def install_app(i): system.serialWarning() global category slug = category[i]["slug"] category = None gc.collect() if not wifi.status(): wifi.connect() wifi.wait() if not wifi.status(): showMessage("Unable to connect to WiFi.") time.sleep(2) return showMessage("Installing "+slug+"...") try: woezel.install(slug) except woezel.LatestInstalledError: showMessage("Latest version is already installed.") time.sleep(2) return except: showMessage("Failed to install "+slug+"!") time.sleep(2) return showMessage(slug+" has been installed!") return
def install_app(i, fromcat): system.serialWarning() global category slug = category[i]["slug"] category = None gc.collect() if not wifi.status(): wifi.connect() wifi.wait() if not wifi.status(): showMessage("Unable to connect to WiFi.") time.sleep(2) show_category(fromcat) showMessage("Installing " + slug + "...") uinstaller.install(slug)
def main(): try: global mqtt_hostname, mqtt_server, wifi_ap _thread.start_new_thread("led-animation", ledThread, ()) _buttons.register(0) _buttons.attach(0, buttonHandler) mqtt = MQTTClient(mqtt_hostname, mqtt_server) mqtt.set_callback(mqttHandler) while True: if wifi_ap: mqtt.disconnect() break if not wifi.status(): connectToWiFi() mqtt.connect() mqtt.subscribe(b"hoera10jaar/+") else: mqtt.check_msg() time.sleep(0.1) except BaseException as e: print("MAIN THREAD CRASHED") print(e) time.sleep(2) system.home()
def _connect_wifi(self): dp.drawPixel(0, 0, 0x0044BB) dp.flush() if not wifi.status(): audio.play('/cache/system/wifi_connecting.mp3') wifi.connect() dp.drawPixel(1, 0, 0x0044BB) dp.flush() wifi.wait() if not wifi.status(): dp.drawLine(0, 0, 1, 0, 0xFF0000) dp.flush() audio.play('/cache/system/wifi_failed.mp3', on_finished=system.launcher)
def update_cache(): # Check if RTC has been synced over NTP if not rtc.isSet(): _show_progress("Connecting to WiFi...", False) wifi.connect() if not wifi.wait(): _show_progress("Failed to connect to WiFi.", True) return False while wifi.status() and (time.time() < 1482192000): wifi.ntp() last_update = _get_last_updated() if last_update > 0 and time.time() < last_update + (600): return True if not wifi.status(): _show_progress("Connecting to WiFi...", False) wifi.connect() if not wifi.wait(): _show_progress("Failed to connect to WiFi.", True) return False print('Updating woezel cache..') #os.remove(cache_path + '/categories.json') _show_progress("Downloading package list...") packages = get_pkg_list() categories = set(item['category'] for item in packages) with open(cache_path + '/categories.json', 'w') as categories_file: categories_file.write(json.dumps([{'name': _slug_to_name(cat), 'slug': cat} for cat in categories])) _show_progress("Saving lists...") for cat in categories: gc.collect() with open(cache_path + '/' + cat + '.json', 'w') as category_file: category_file.write(json.dumps([app for app in packages if app['category'] == cat])) gc.collect() _set_last_updated() _show_progress("Done!") gc.collect() return True
def hotspot_connect(ssid, password, ssid_is_prefix=False): if not badgehelper.on_badge(): return False sta_if = network.WLAN(network.STA_IF) ap_if = network.WLAN(network.AP_IF) if ap_if.active(): ap_if.active(False) sta_if.active(True) if not sta_if.isconnected(): if ssid_is_prefix: # we need to scan first to get all latest ssid's ssids = sta_if.scan() ssids_left = [] for ssid_item in ssids: ssid_name = ssid_item[0].decode("ascii") if ssid_name.startswith(ssid): ssids_left.append(ssid_name) if len(ssids_left) == 0: animate_no_wifi() animate_end() return False # get latest ssids_left.sort(reverse=True) ssid = ssids_left[0] print("Connecting to HOTSPOT network " + ssid + "...") animate_wifi() sta_if.connect(ssid, password) wifi.wait() if not wifi.status(): animate_no_wifi() animate_end() return wifi.status()
def connect_wifi(): if wifi.status(): return True rgb.clear() data, size, frames = animation_connecting_wifi rgb.framerate(3) rgb.gif(data, (12, 0), size, frames) wifi.connect() wifi.wait() if not wifi.status(): data, frames = icon_no_wifi rgb.gif(data, (12, 0), (8, 8), frames) time.sleep(3) rgb.clear() rgb.framerate(20) return wifi.status()
def available(update=False, show=False): if update: if not wifi.status(): return machine.nvs_get_u8('system', 'OTA.ready') == 1 info = download_info(show) if info: if info["build"] > consts.INFO_FIRMWARE_BUILD: machine.nvs_set_u8('system', 'OTA.ready', 1) return True machine.nvs_set_u8('system', 'OTA.ready', 0) return machine.nvs_get_u8('system', 'OTA.ready') == 1
def install_app(pressed=True): global category if pressed: slug = category[category_list.selected_index()]["slug"] gc.collect() category_list.visible(False) category_list.enabled(False) #Input handling ugfx.input_attach(ugfx.BTN_START, btn_unhandled) ugfx.input_attach(ugfx.BTN_SELECT, btn_unhandled) ugfx.input_attach(ugfx.BTN_A, btn_unhandled) ugfx.input_attach(ugfx.BTN_B, btn_unhandled) ugfx.input_attach(ugfx.JOY_UP, btn_unhandled) ugfx.input_attach(ugfx.JOY_DOWN, btn_unhandled) ugfx.input_attach(ugfx.JOY_LEFT, btn_unhandled) ugfx.input_attach(ugfx.JOY_RIGHT, btn_unhandled) if not wifi.status(): wifi.connect() wifi.wait() if not wifi.status(): showMessage("Unable to connect to WiFi.") time.sleep(2) show_category() showMessage("Installing " + slug + "...") try: woezel.install(slug) except woezel.LatestInstalledError: showMessage("NOTICE\n\nLatest version is already installed.", False, False, True) time.sleep(2) show_category() except: showMessage("Failed to install " + slug + "!", True) time.sleep(2) show_category() showMessage("OK\n\n" + slug + " has been installed!", False, False, True) time.sleep(2) show_category()
def wifiTask(): global wifi_status_prev, wifi_status_curr, gui_redraw, ota_available wifi_status_prev = wifi_status_curr wifi_status_curr = wifi.status() if wifi_status_curr: wifi.ntp(True) if wifi_status_curr != wifi_status_prev: #pm.feed() wifi_status_prev = wifi_status_curr gui_redraw = True if wifi_status_curr: ota_available = otacheck.available(True) return 1000
def available(update=False, show=False): if update: if not wifi.status(): return badge.nvs_get_u8('badge', 'OTA.ready', 0) info = download_info(show) if info: if info["build"] > consts.INFO_FIRMWARE_BUILD: badge.nvs_set_u8('badge', 'OTA.ready', 1) return True badge.nvs_set_u8('badge', 'OTA.ready', 0) return badge.nvs_get_u8('badge', 'OTA.ready', 0)
def available(update=False, show=False): if update: if not wifi.status(): return badge.nvs_get_u8('badge', 'OTA.ready', 0) info = download_info(show) if info: if info["build"] > version.build: badge.nvs_set_u8('badge', 'OTA.ready', 1) return True badge.nvs_set_u8('badge', 'OTA.ready', 0) return badge.nvs_get_u8('badge', 'OTA.ready', 0)
def install_app(pressed=True): global category slug = category[category_list.selected_index()]["slug"] category = None gc.collect() if pressed: category_list.visible(False) category_list.enabled(False) #Input handling ugfx.input_attach(ugfx.BTN_START, btn_unhandled) ugfx.input_attach(ugfx.BTN_SELECT, btn_unhandled) ugfx.input_attach(ugfx.BTN_A, btn_unhandled) ugfx.input_attach(ugfx.BTN_B, btn_unhandled) ugfx.input_attach(ugfx.JOY_UP, btn_unhandled) ugfx.input_attach(ugfx.JOY_DOWN, btn_unhandled) ugfx.input_attach(ugfx.JOY_LEFT, btn_unhandled) ugfx.input_attach(ugfx.JOY_RIGHT, btn_unhandled) if not wifi.status(): wifi.connect() wifi.wait() if not wifi.status(): easydraw.msg("No WiFi.") time.sleep(2) show_category() easydraw.msg(slug,"Installing...", True) try: woezel.install(slug) except woezel.LatestInstalledError: easydraw.msg("Already on latest.") time.sleep(2) show_category() except: easydraw.msg("Failed.") time.sleep(2) show_category() easydraw.msg("Done.") show_category()
def update_cache(): last_update = get_last_updated() if last_update > 0 and utime.time() < last_update + (600): global activities try: filestream = open(cache_path + cache_file, 'r') activities = sorted(ujson.load(filestream), key=lambda x: int(x['time'])) filestream.close() parse_activities() except: print("Err reading") return True print("Update required") try: os.mkdir(cache_path) except: pass print('Updating activities cache..') if not wifi.status(): uinterface.connect_wifi() if not wifi.wait(): print("Failed to connect to WiFi.") return False show_progress("Downloading activities...") try: request = urequests.get(url, timeout=5) show_progress("Saving activities...") with open(cache_path + cache_file, 'w') as activities_file: activities_file.write(request.text) request.close() show_progress("Parsing activities...") global activities filestream = open(cache_path + cache_file, 'r') activities = sorted(ujson.load(filestream), key=lambda x: int(x['time'])) filestream.close() parse_activities() set_last_updated() show_progress("Done!") gc.collect() return True except BaseException as e: sys.print_exception(e) show_progress("Failed!") gc.collect() return False
def connect_wifi(duration=None): if wifi.status(): return True display.drawFill(0) display.drawText(0, 0, "Connecting to wifi") display.flush() wifi.connect() if duration is not None: wifi.wait(duration=duration) else: wifi.wait() if not wifi.status(): display.drawFill(0) display.drawText(0, 0, "Connecting to wifi failed") display.flush() time.sleep(3) display.drawFill(0) display.flush() return wifi.status()
def connect_wifi(): rgb.pixel((255, 255, 0), (31, 0)) # yellow connecting to wifi if not wifi.status(): wifi.connect() if wifi.wait(): rgb.pixel((0, 255, 0), (31, 0)) # green for wifi rgb.framerate(20) else: rgb.clear() rgb.framerate(20) data, frames = icon_no_wifi rgb.image(data, (12, 0), (8, 8)) time.sleep(3) rgb.clear() machine.reboot()
def wifiTask(): global wifi_status_prev, wifi_status_curr, gui_redraw, ota_available wifi_status_prev = wifi_status_curr wifi_status_curr = wifi.status() if wifi_status_curr: wifi.ntp(True) if wifi_status_curr != wifi_status_prev: print("WiFi status changed", wifi_status_curr) pm.feed() wifi_status_prev = wifi_status_curr gui_redraw = True if wifi_status_curr: ota_available = otacheck.available(True) print("Check OTA", ota_available) return 1000
def connectToWiFi(): global wifi_ap connecting = True while connecting: print("Connecting to WiFi...") wifi.connect() for i in range(10): if i & 1: setAll(0) else: setAll(3) time.sleep(0.5) if wifi.status() or wifi_ap: connecting = False break if not wifi.status(): setAll(1) time.sleep(2) setAll(0) time.sleep(2) #setAll(2) #time.sleep(1) setAll(0) return wifi.status()
def switch(self, type): if not badgehelper.on_badge(): return True if type == GAME_HOST_NETWORK_TYPE_NORMAL or type == GAME_CLIENT_NETWORK_TYPE_NORMAL: if not wifi.status(): print("Connecting to Wi-Fi...") return uinterface.connect_wifi() elif type == GAME_HOST_NETWORK_TYPE_HOTSPOT: # define unique hotspot return wifi_extended.hotspot_setup(GAME_NETWORK_TYPE_HOTSPOT_SSID, GAME_NETWORK_TYPE_HOTSPOT_CHANNEL, GAME_NETWORK_TYPE_HOTSPOT_HIDDEN, GAME_NETWORK_TYPE_HOTSPOT_PASSWD, GAME_NETWORK_TYPE_HOTSPOT_AUTHMODE, True) elif type == GAME_CLIENT_NETWORK_TYPE_HOTSPOT: return wifi_extended.hotspot_connect(GAME_NETWORK_TYPE_HOTSPOT_SSID, GAME_NETWORK_TYPE_HOTSPOT_PASSWD, True) pass
def network_diag(self): """Perform a diagnostic of the connection.""" err_percent = self.err_percent() logging.debug("Percentage of network errors (global): %s" % err_percent) for i in range(2): wifi_info = wifi.status() wpa_state = wifi_info['wpa_state'] # Return 'None' if no bssid or ip address bssid = wifi_info.get('bssid') ip = wifi_info.get('ip_address') if i == 0: if wpa_state != "COMPLETED": logging.warning("Lost association with the hotspot!") logging.info("Trying to reassociate...") wifi.reassociate() time.sleep(30) continue if ip == None or ip.startswith("169.254"): logging.warning("The current ip address is invalid") logging.info("Trying to obtain a valid ip...") wifi.reattach() time.sleep(20) continue # Sometimes, like for instance when the signal is too weak, # the connection can be broken even if everything seems ok. break if wpa_state == "COMPLETED" and ip and ip.startswith("10."): logging.info("Everything seems back to normal") return logging.warning("Unable to fix the connection!") break if bssid: logging.info("The current hotspot seems faulty, blacklisting.") self.faulty_ap.append(bssid) logging.info("Looking for another candidate...") self.manual_mode()
def available(update=False): if update: if not wifi.status(): wifi.connect() if not wifi.wait(): return machine.nvs_getint('system', 'OTA.ready') or 0 info = download_info() current_build = int(consts.INFO_FIRMWARE_BUILD) if info: if info["build"] > current_build: machine.nvs_setint('system', 'OTA.ready', 1) return True machine.nvs_setint('system', 'OTA.ready', 0) return machine.nvs_getint('system', 'OTA.ready') or 0
def __init__(self): self.running = True self.dimmer = 2 self.rtc = machine.RTC() display_connecting() wifi.connect() if not wifi.wait(): system.launcher() if wifi.status(): display_connected(["Dimmer: %d (lf,rt)" % self.dimmer]) self.sync_ntp(True) self.is_initialized = True else: ledData = [0x00, 0x00, 0x00, 0x00, 0x79, 0x00] * 6 neopixel.send(bytes(ledData)) system.launcher()
def update(): global path, categories, lastUpdate if not wifi.status(): _showProgress("Connecting to WiFi...", False, True) wifi.connect() if not wifi.wait(): _showProgress("Failed to connect to WiFi.", True, False) return False _showProgress("Downloading categories...") try: request = urequests.get("https://{}/basket/{}/categories/json".format( consts.WOEZEL_WEB_SERVER, consts.INFO_HARDWARE_WOEZEL_NAME), timeout=30) _showProgress("Saving categories...") categories_file = open(path + '/categories.json', 'w') categories_file.write(request.text) categories_file.close() _showProgress("Parsing categories...") categories = request.json() for category in categories: gc.collect() slug = category["slug"] _showProgress("Downloading '" + category["name"] + "'...") f = urequests.get("https://{}/basket/{}/category/{}/json".format( consts.WOEZEL_WEB_SERVER, consts.INFO_HARDWARE_WOEZEL_NAME, slug), timeout=30) f_file = open(path + '/' + slug + '.json', 'w') f_file.write(f.text) f_file.close() lastUpdate = int(time.time()) f = open(path + "/lastUpdate", 'w') f.write(str(lastUpdate)) f.close() _showProgress("Done!") gc.collect() return True except BaseException as e: _showProgress("Failed.", True) sys.print_exception(e) gc.collect() return False
def manual_mode(self): """Manually choose which AP to use.""" wifi.disconnect() wifi.scan() time.sleep(5) avail_ap = wifi.scan_results() logging.debug("List of available ap : %s" % avail_ap) logging.debug("List of faulty ap : %s" % self.faulty_ap) for ap in avail_ap: if ap not in self.faulty_ap: wifi.set_pref(ap) logging.info("New candidate found") logging.debug("Preffered bssid is now set to %s" % ap) logging.info("Associating...") wifi.reassociate() time.sleep(30) wifi_info = wifi.status() if wifi_info['wpa_state'] != "COMPLETED": logging.warning("Association failed!") logging.info("Looking for another candidate...") self.faulty_ap.append(ap) continue logging.info("Association successful") logging.info("bssid : %s" % ap) signal = wifi.signal_strength() logging.info("signal : -%s dBm" % signal) return logging.error( "Tested all available hotspots but none of them work :-(") self.faulty_ap = [] wifi.disconnect() self.sleep_mode()
def available(update=False, show=False): if update: if not wifi.status(): try: return nvs.get_i32('OTA.ready') == 1 except Exception: return False info = download_info(show) if info: if info["build"] > consts.INFO_FIRMWARE_BUILD: nvs.set_i32('OTA.ready', 1) nvs.commit() return True nvs.set_i32('OTA.ready', 0) nvs.commit() try: return nvs.get_i32('OTA.ready') == 1 except Exception: return False
def update(self): import wifi if not wifi.status(): self._showProgress("Connecting to WiFi...", False, True) wifi.connect() if not wifi.wait(): self._showProgress("Failed to connect to WiFi.", True, False) return False self._showProgress("Downloading categories...") try: request = urequests.get("https://badge.team/eggs/categories/json", timeout=30) self._showProgress("Saving categories...") categories_file = open(self.path + '/categories.json', 'w') categories_file.write(request.text) categories_file.close() self._showProgress("Parsing categories...") self.categories = request.json() for category in self.categories: gc.collect() slug = category["slug"] self._showProgress("Downloading '" + category["name"] + "'...") f = urequests.get( "https://badge.team/basket/hackerhotel2019/category/%s/json" % slug, timeout=30) f_file = open(self.path + '/' + slug + '.json', 'w') f_file.write(f.text) f_file.close() self.lastUpdate = int(time.time()) f = open(self.path + "/lastUpdate", 'w') f.write(str(self.lastUpdate)) f.close() self._showProgress("Done!") gc.collect() return True except BaseException as e: sys.print_exception(e) self._showProgress("Failed!", True) gc.collect() return False
print("Currently installed:", current_name, "(Build " + str(current_build) + ")") print("Current version:", "Update check", True) print(str(current_build) + ") " + current_name) available = 0 machine.nvs_setint('badge', 'OTA.ready', 0) def start(pressed): if pressed: system.ota() if not wifi.status(): wifi.connect() if not wifi.wait(): print("Error: could not connect to WiFi!") title = "Update check" message = "?? Unknown state ??" if wifi.status(): info = otacheck.download_info() if info: print("Server has: ", info['name'], " (Build " + str(info['build']) + ")") if info["build"] > current_build: machine.nvs_setint('badge', 'OTA.ready', 0) print("Update available!")
def request(method, url, data=None, json=None, headers={}, stream=None, timeout=10, redirect=5): if not wifi.status(): raise ValueError("WiFi not connected") try: proto, dummy, host, path = url.split("/", 3) except ValueError: proto, dummy, host = url.split("/", 2) path = "" if proto == "http:": port = 80 elif proto == "https:": import ussl port = 443 else: raise ValueError("Unsupported protocol: " + proto) if ":" in host: host, port = host.split(":", 1) port = int(port) ai = usocket.getaddrinfo(host, port) addr = ai[0][-1] s = usocket.socket() if timeout: s.settimeout(timeout) s.connect(addr) if proto == "https:": s = ussl.wrap_socket(s, server_hostname=host) s.write(b"%s /%s HTTP/1.0\r\n" % (method, path)) if not "Host" in headers: s.write(b"Host: %s\r\n" % host) # Iterate over keys to avoid tuple alloc for k in headers: s.write(k) s.write(b": ") s.write(headers[k]) s.write(b"\r\n") if json is not None: assert data is None import ujson data = ujson.dumps(json) if data: s.write(b"Content-Length: %d\r\n" % len(data)) s.write(b"\r\n") if data: s.write(data) l = s.readline() protover, status, msg = l.split(None, 2) status = int(status) #print(protover, status, msg) while True: l = s.readline() if not l or l == b"\r\n": break #print(l) if l.lower().startswith(b"transfer-encoding:"): if b"chunked" in l: s.close() raise ValueError("Unsupported " + l.decode("utf-8")) elif l.lower().startswith(b"location:") and 300 <= status <= 399: s.close() if redirect <= 0: raise ValueError("Too many redirects") else: return request(method, l[9:len(l)].decode().strip(), data, json, headers, stream, timeout, redirect - 1) resp = Response(s) resp.status_code = status resp.reason = msg.rstrip() return resp
def disconnect_wifi(): if wifi.status(): wifi.disconnect() rgb.pixel((255, 0, 0), (31, 0)) # red for no wifi