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 _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 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 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 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 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(): 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 create_server(): """ Establish a WiFi connection, opens a TCP socket, and returns a tuple of a server socket and its own "public" IPv4 address. """ wifi.connect() if not wifi.wait(): raise ValueError("cannot establish WiFi connection") ip, _, _, _ = wifi._STA_IF.ifconfig() server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("", PORT)) server_socket.listen(1) return ip, server_socket
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 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
def __init__(self): """Initialize the microham client. Connect wifi, connect MQTT, subscribe to default channel.""" display.drawFill(0x000000) display.drawText(0, 0, "microham starting", 0xFFFFFF, "7x5") display.drawText(0, 8, CLIENT_ID, 0xFFFFFF, "7x5") display.flush() # wifi connection wifi.connect() if not wifi.wait(): print("wifi error") display.drawText(0, 16, "wifi error", 0xFFFFFF, "7x5") else: print("wifi connected") display.drawText(0, 16, "wifi connected", 0xFFFFFF, "7x5") display.flush() # umqtt client self.client = MQTTClient(CLIENT_ID, SERVER) self.client.DEBUG = True self.client.set_callback(self.sub_cb) self.client.KEEP_QOS0 = False self.client.NO_QUEUE_DUPS = True self.client.MSG_QUEUE_MAX = 2 self.client.set_callback(self.sub_cb) self.channel = CHANNEL # Channel number, int # Wildcard subscribe to channel's topics; subtopics are userIDs self.topic = b"{}/#".format(self.channel) if not self.client.connect(clean_session=True): self.client.subscribe(self.topic) print("mqtt started") display.drawText(0, 24, "mqtt started", 0xFFFFFF, "7x5") display.flush() utime.sleep_ms(1000) self.clear()
#/** the width of the eink display */ #define BADGE_EINK_WIDTH 296 #/** the height of the eink display */ #define BADGE_EINK_HEIGHT 128 try: while True: try: wifi.init() while not wifi.sta_if.isconnected(): sleep(0.1) except: wifi.connect() print("Connecting to WiFi") if not wifi.wait(): time.sleep(2) print("Connection Error, Rebooting") machine.reset() wifi.ntp(False) rtc = machine.RTC() print(rtc.now()) #url="http://ip-api.com/line/?fields=city" #url = "http://travelplanner.mobiliteit.lu/restproxy/departureBoard?accessId=cdt&id=A=1@O=Lintgen,%20Kräizung@X=6,125115@Y=49,720344@U=82@L=160702003@B=1@p=1594365298&format=json" url = 'http://wttr.in/?format="%S:+%m+%s"' while True: r = requests.get(url) print("API HTTP request status Code:", r.status_code) #print(r.status_code)
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..') _show_progress("Downloading categories...") try: request = urequests.get("https://%s/eggs/categories/json" % woezel_domain, timeout=30) _show_progress("Saving categories...") with open(cache_path + '/categories.json', 'w') as categories_file: categories_file.write(request.text) _show_progress("Parsing categories...") categories = request.json() request.close() del request for index, category in enumerate(categories): gc.collect() cat_slug = category["slug"] _show_progress("Downloading '" + category["name"] + "' (%d/%d)..." % (index, len(categories))) f = urequests.get("https://%s/basket/%s/category/%s/json" % (woezel_domain, device_name, cat_slug), timeout=30) with open(cache_path + '/' + cat_slug + '.json', 'w') as f_file: f_file.write(f.text) f.close() del f gc.collect() _set_last_updated() _show_progress("Done!") gc.collect() return True except BaseException as e: sys.print_exception(e) _show_progress("Failed!", True) gc.collect() return False
import wifi, woezel, system, display def showmsg(msg): display.drawFill(0x000000) display.drawText(0, 0, msg, 0xFFFFFF) showmsg("WiFi...") wifi.connect() status = wifi.wait() if not status: showmsg("WiFi failed") time.sleep(1) system.launcher() showmsg("Installing...") woezel.install("lasertag") showmsg("Done") time.sleep(1) system.launcher()
def run(self): self.update() while True: wifi.wait() self.update() self.sleep(1)
import badge, easydraw, woezel, wifi lvl = badge.nvs_get_u8('ota', 'fixlvl', 0) if lvl < 3: if not badge.nvs_get_u16("modaudio", "mixer_ctl_0"): badge.nvs_set_u16("modaudio", "mixer_ctl_0", (0 << 15) + (0 << 8) + (1 << 7) + (32 << 0)) badge.nvs_set_u16("modaudio", "mixer_ctl_1", (0 << 15) + (32 << 8) + (0 << 7) + (32 << 0)) badge.nvs_set_u8('ota', 'fixlvl', 3) if lvl < 5: wifi.connect() if wifi.wait(30, True): for bloatware in [ 'event_schedule', 'de_rode_hack', 'hacker_gallery', 'angry_nerds_podcast' ]: # This is ugly, but if 1 app is already up to date we just try to fill the device with the rest try: easydraw.messageCentered("Updating...\n" + bloatware, True, '/media/flag.png') woezel.install(bloatware) except: pass badge.nvs_set_u8('ota', 'fixlvl', 5)
import wifi, term, system, urequests while True: wifi.connect() if not wifi.wait(showStatus=True): system.home() print("Enter a URL to download from or nothing to cancel.") url = term.prompt("URL to download from", 1, 3, "") print("\n\n\n") print("Enter a path to save to or nothing to cancel.") path = term.prompt("Path to save to ", 1, 6, "/") if len(url) < 1 or len(path) < 1: system.home() term.header(True, "Downloading...") request = urequests.get(url) term.header(True, "Saving...") f = open(path, 'wb') f.write(request.content) f.close() term.header(True, "Done")
import term, system, time, version, wifi, buttons, orientation, display import tasks.otacheck as otacheck import easydraw orientation.default() term.header(True, "Update check") print("Checking for updates...") print("") print("Currently installed:",version.name,"(Build "+str(version.build)+")") available = 0 easydraw.messageCentered("Connecting to WiFi...", False, "/media/wifi.png") wifi.connect() wifi.wait() if not wifi.status(): easydraw.messageCentered("No WiFi!\n\nPress A to start update\nPress B to cancel", False) title = "Could not connect to WiFi!" message = "Unable to check for updates. You can still attempt to start the OTA update procedure.\n" message += "Currently installed: "+version.name+" (Build "+str(version.build)+")\n" else: info = otacheck.download_info() if info: print("Server has: ",info['name']," (Build "+str(info['build'])+")") if info["build"] > version.build: easydraw.messageCentered("Update available!\n({})\n\nPress A to start update\nPress B to cancel".format(version.build), False) message = "A new firmware version is available. Update?\n" message += "Currently installed: "+version.name+" (Build "+str(version.build)+")\n" message += "Available : "+info["name"]+" (Build "+str(info["build"])+")" elif info["build"] < version.build:
def init_wifi(): """Set up the WiFi.""" if wifi.status(): return True wifi.connect() return wifi.wait()
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!") machine.nvs_setint('badge', 'OTA.ready', 1) print("Update available!")
import time, ntp, rgb, wifi, buttons, defines, system, machine from default_icons import animation_connecting_wifi, icon_no_wifi direction = 0 if not ntp.local_time_available(): if not wifi.status(): data, size, frames = animation_connecting_wifi rgb.clear() rgb.framerate(3) rgb.gif(data, (12, 0), size, frames) wifi.connect() if wifi.wait(): rgb.clear() rgb.framerate(20) else: print('No wifi') rgb.clear() rgb.framerate(20) data, frames = icon_no_wifi rgb.image(data, (12, 0), (8, 8)) time.sleep(3) rgb.clear() print("Error connecting to wifi") system.reboot() if not ntp.set_NTP_time(): print("Error setting time") system.reboot() wifi.disconnect()