def connectWiFi(ssid=None, password=None, showProgress=False): if showProgress: tft.font(tft.FONT_DefaultSmall, transparent=True) tft.clear(tft.BLACK) tft.text(tft.CENTER, tft.CENTER, "Connecting to WiFi: " + WIFI['ssid'], tft.GREEN) wifiSta = network.WLAN(network.STA_IF) wifiSta.active(True) print("\n=== Activate STA ===\n") if ssid is not None: wifiSta.connect(ssid, password) if showProgress: tft.clear(tft.BLACK) tft.text(tft.CENTER, tft.CENTER, "Connected to WiFi: " + WIFI['ssid'], tft.GREEN) return wifiSta else: if machine.nvs_getstr('wifissid') is None: from wifiConfig import setupWifi setupWifi() else: wifiSta.connect(machine.nvs_getstr('wifissid'), machine.nvs_getstr('wifipassword')) while not wifiSta.isconnected(): utime.sleep_ms(100) print(wifiSta.ifconfig()) if showProgress: tft.clear(tft.BLACK) tft.text(tft.CENTER, tft.CENTER, "Connected to WiFi: " + WIFI['ssid'], tft.GREEN) return wifiSta
def load(): cfg_term_menu = machine.nvs_get_u8('splash', 'term_menu') if cfg_term_menu == None: cfg_term_menu = True cfg_wifi = machine.nvs_get_u8('splash', 'wifi') # Allow the use of WiFi on the splash screen if cfg_wifi == None: cfg_wifi = False # If not set the use of WiFi is not allowed cfg_services = machine.nvs_get_u8('splash', 'services') # Enable splash screen services (fun but dangerous) if cfg_services == None: cfg_services = False # If not set services are disabled cfg_logo = machine.nvs_getstr('splash', 'logo') # Filename of a PNG image to show on the splash screen cfg_nickname = machine.nvs_get_u8('splash', 'nickname') # Show the nickname of the user on the splash screen if cfg_nickname == None: cfg_nickname = True # If not set we want to show the nickname cfg_greyscale = machine.nvs_get_u8('splash', 'greyscale') # Use greyscale mode if cfg_greyscale == None: cfg_greyscale = False # Disabled by default cfg_led_animation = machine.nvs_getstr('splash', 'ledApp') # Application which shows a LED animation while the splash screen is visible return cfg_term_menu, cfg_wifi, cfg_services, cfg_logo, cfg_nickname, cfg_greyscale, cfg_led_animation
def getToken(self, newToken=False): try: if machine.nvs_getstr(self.tokenKey) is None or newToken: print("Getting a New Token") payload = { "method": "login", "params": { "appType": "Kasa_Android", "cloudUserName": self.username, "cloudPassword": self.password, "terminalUUID": str(uuid.uuid4()) } } _token = requests.post('https://wap.tplinkcloud.com/', json=payload).json()['result']['token'] machine.nvs_setstr(self.tokenKey, _token) self.isTokenPresent = True self.token = _token return _token else: print("Using Stored Token") _token = machine.nvs_getstr(self.tokenKey) self.isTokenPresent = True self.token = _token return machine.nvs_setstr(self.tokenKey, _token) except Exception as e: print(e)
def setPara(key, value): params = machine.nvs_getstr('params') if params == None: machine.nvs_setstr('params', '') params = machine.nvs_getstr('params') if str(key) not in params: params += "," + str(key) machine.nvs_setstr('params', params) machine.nvs_setstr(str(key), str(value))
def getAllPara(par=None): params = machine.nvs_getstr('params') if params == None: machine.nvs_setstr('params', '') if par == None: return machine.nvs_getstr('params') else: if machine.nvs_getstr(par) is not None: return machine.nvs_getstr(par).split(',') else: return ''.split(',')
def _update(self): user = machine.nvs_getstr("networkLogin") password = machine.nvs_getstr("networkPassword") if(machine.nvs_getint("ftpEnabled")): network.ftp.start(user = user, password = password) else: network.ftp.stop() if(machine.nvs_getint("telnetEnabled")): network.telnet.start(user = user, password = password) else: network.telnet.stop()
def set_NTP_time(): import time from machine import RTC print("Setting time from NTP") t = get_NTP_time() if t is None: print("Could not set time from NTP") return False tm = time.localtime(t) tm = tm[0:6] offset = machine.nvs_getstr("badge", "time.offset") if not offset: offset = 1 if tm[1] > 3 and tm[1] < 11: offset = 2 tm = time.localtime(t + offset * 3600) tm = tm[0:6] rtc = RTC() rtc.init(tm) #rtc.datetime(tm) return True
def nvs_get_str(space, item, default=None): if space == "badge": space = "system" res = machine.nvs_getstr(space, item) if res == None: res = default return res
def drawNickname(): owner = machine.nvs_getstr("owner", "name") or "BADGE.TEAM" display.drawFill(0xFFFF00) x = (display.width()-display.getTextWidth(owner, "ocra16"))//2 y = (display.height()-display.getTextHeight(owner, "ocra16"))//2 display.drawText(x,y,owner,0x000000,"ocra16") display.flush() # Send the new buffer to the display display.backlight(0xFF) # Turn on backlight
def startWifi(): import network import utime import machine machine.loglevel("wifi", machine.LOG_ERROR) wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(machine.nvs_getstr("wifiSSID"), machine.nvs_getstr("wifiPass")) while (not wlan.isconnected()): utime.sleep_ms(50) user = machine.nvs_getstr("networkLogin") password = machine.nvs_getstr("networkPassword") network.ftp.start(user=user, password=password) network.telnet.start(user=user, password=password)
def __init__(self, default_timezone=EUROPE_LONDON): if utime.time() < 1585235437: # RTC is unset. wifi.ntp() self._rtc = machine.RTC() timezone = machine.nvs_getstr('system', 'timezone') if not timezone: timezone = default_timezone self._rtc.timezone(timezone)
def connectWiFi(): nw = network.WLAN(network.STA_IF) if not nw.isconnected(): nw.active(True) ssid = machine.nvs_getstr('system', 'wifi.ssid') or '' password = machine.nvs_getstr('system', 'wifi.password') nw.connect(ssid, password) if password else nw.connect(ssid) print("Connecting to '" + ssid + "'...") timeout = 150 while not nw.isconnected(): time.sleep(0.1) timeout = timeout - 1 if (timeout < 1): print("Timeout while connecting!") nw.active(True) return False return True
def __init__(self): self.servos = [Servo(32, timer=0), Servo(25, timer=1), Servo(26, timer=2), Servo(27, timer=3)] for i in range(4): settings = machine.nvs_getstr('servo_' + str(i)) if settings is None: continue print("initializing servo " + str(i) + " with settings " + settings) s = settings.split() self.servos[i].tune(float(s[0]), float(s[1]))
def __init__(self, data_cb=None, enable_eyes=False, enable_buzzer=False, enable_accelero=False): self.id = machine.nvs_getstr('token') self.wifi_ssid = machine.nvs_getstr('ssid') self.wifi_password = machine.nvs_getstr('pwd') self.mqtt_server = machine.nvs_getstr('mqtt_server') self.mqtt_user = machine.nvs_getstr('mqtt_user') self.mqtt_password = machine.nvs_getstr('mqtt_password') self.wifi = network.WLAN(network.STA_IF) self.mqtt = network.mqtt(self.id, self.mqtt_server, user=self.mqtt_user, password=self.mqtt_password, cleansession=True, data_cb=data_cb) self.button_0 = Button(machine.Pin(36)) self.button_1 = Button(machine.Pin(39)) self.touch_0 = machine.TouchPad(machine.Pin(12)) self.touch_1 = machine.TouchPad(machine.Pin(14)) i2c_bus = machine.I2C(id=0, scl=machine.Pin(22), sda=machine.Pin(21), freq=100000) if enable_eyes: self.eyes = Eyes() print(Feedback.INF_EYES_ENABLED) if enable_buzzer: self.buzzer = Buzzer() print(Feedback.INF_BUZZER_ENABLED) if enable_accelero: self.accelero = AcceleroMeter(i2c_bus) print(Feedback.INF_ACCELERO_ENABLED)
def run(): server = self.server while(True): cl = server.accept()[0] self.client = cl try: cl.send(options_user) cl.send(b"Login: "******"Password: "******"networkLogin") or password != machine.nvs_getstr("networkPassword")): self.client = None cl.close() continue except: self.client = None cl.close() continue cl.send(options) try: while(True): c = cl.recv(1) keyDown(ord(c)) keyUp(ord(c)) except OSError as e: print(e) self.client = None cl.close()
def nickname(y=5, font="freesansbold12", color=0x000000, unusedParameter=None): nick = machine.nvs_getstr("owner", "name") if not nick: return y lines = lineSplit(nick, display.width(), font) for i in range(len(lines)): line = lines[len(lines) - i - 1] display.font(font) pos_x = int((display.width() - display.get_string_width(line)) / 2) lineHeight = display.get_string_height(line) display.cursor(pos_x, y + lineHeight * (len(lines) - i - 1)) display.textColor(color) display.print(line) return len(lines) * lineHeight
def nickname(y = 5, font = "Roboto_Regular18", color = 0x000000, unusedParameter=None): nick = machine.nvs_getstr("owner", "name") if not nick: return y lines = lineSplit(nick, display.width(), font) for i in range(len(lines)): line = lines[len(lines)-i-1] pos_x = int((display.width()-display.getTextWidth(line, font)) / 2) lineHeight = display.getTextHeight(line, font) if font: display.drawText(pos_x, y+lineHeight*(len(lines)-i-1), line, color, font) else: display.drawText(pos_x, y+lineHeight*(len(lines)-i-1), line, color) return len(lines) * lineHeight
def __init__(self, parent): super().__init__(parent, 20, 4) self.telnetEnable = self.add(uui.CheckBox(self, self.onTelnetChange, machine.nvs_getint("telnetEnabled"), format = b"Telnet [%s]")) self.telnetEnable.setPos(1, 0) self.telnetEnable = self.add(uui.CheckBox(self, self.onFTPChange, machine.nvs_getint("ftpEnabled"), format = b"FTP [%s]")) self.telnetEnable.setPos(1, 1) log = self.add(uui.TextEntry(self, self.onLogin, 20, name = b"L:"), False) log.setPos(1, 2) log.setValue(machine.nvs_getstr("networkLogin").encode()) pas = self.add(uui.TextEntry(self, self.onPassword, 20, name = b"P:"), False) pas.setPos(1, 3)
import term, system, machine system.serialWarning() term.header(True, "Configure nickname") nickname = machine.nvs_getstr("owner", "name") if not nickname: nickname = "" nickname = term.prompt("Nickname", 1, 3, nickname) machine.nvs_setstr("owner", "name", nickname) system.home()
recovery_button = buttons.BTN_B __chk_recovery = machine.wake_reason() == ( 7, 0) and buttons.value(recovery_button) except: pass #Application starting if __chk_recovery: app = "dashboard.recovery" else: app = rtc.read_string() if not app: if fc_level < 3: app = "factory_checks" else: app = machine.nvs_getstr("system", 'default_app') if not app: app = 'dashboard.home' del fc_level del __chk_recovery del rtc del recovery_button if app and not app == "shell": try: print("Starting app '%s'..." % app) system.__current_app__ = app if app: __import__(app) except KeyboardInterrupt:
import network, time, machine, consts _STA_IF = network.WLAN(network.STA_IF) _AP_IF = network.WLAN(network.AP_IF) _DEFAULT_TIMEOUT = machine.nvs_getint("system", "wifi.timeout") or 10 _DEFAULT_SSID = machine.nvs_getstr("system", "wifi.ssid") _DEFAULT_PASSWORD = machine.nvs_getstr("system", "wifi.password") if not _DEFAULT_SSID: _DEFAULT_SSID = consts.WIFI_SSID _DEFAULT_PASSWORD = consts.WIFI_PASSWORD # STATION MODE # ------------ def connect(*args): ''' Connect to a WiFi network :param ssid: optional, ssid of network to connect to :param password: optional, password of network to connect to ''' _STA_IF.active(True) if len(args) == 0: if _DEFAULT_PASSWORD: _STA_IF.connect(_DEFAULT_SSID, _DEFAULT_PASSWORD) else: _STA_IF.connect(_DEFAULT_SSID) elif len(args) == 1: _STA_IF.connect(args[0])
stopThreads = False # Read configuration from NVS or apply default values cfg_term_menu = machine.nvs_get_u8('splash', 'term_menu') # Show a menu on the serial port instead of a prompt if cfg_term_menu == None: cfg_term_menu = True # If not set the menu is shown cfg_wifi = machine.nvs_get_u8('splash', 'wifi') # Allow the use of WiFi on the splash screen if cfg_wifi == None: cfg_wifi = False # If not set the use of WiFi is not allowed cfg_services = machine.nvs_get_u8('splash', 'services') # Enable splash screen services (fun but dangerous) if cfg_services == None: cfg_services = False # If not set services are disabled cfg_logo = machine.nvs_getstr('splash', 'logo') # Filename of a PNG image to show on the splash screen cfg_nickname = machine.nvs_get_u8('splash', 'nickname') # Show the nickname of the user on the splash screen if cfg_nickname == None: cfg_nickname = True # If not set we want to show the nickname cfg_greyscale = machine.nvs_get_u8('splash', 'greyscale') # Use greyscale mode if cfg_greyscale == None: cfg_greyscale = False # Disabled by default cfg_led_animation = machine.nvs_getstr('splash', 'ledApp') # Application which shows a LED animation while the splash screen is visible cfg_nick_text = machine.nvs_getstr("owner", "name") if not cfg_nick_text: cfg_nick_text = "Welcome to Disobey 2020!"
import machine import neopixel import system import utime import version import wifi import term # the badge has the umqtt.robust2 library renamed in this way # to keep the support for legacy umqtt some apps depend on from umqtt2.robust2 import MQTTClient SERVER = "disobey.hilla.io" CLIENT_ID = board_id = "{}".format( binascii.hexlify(machine.unique_id()).decode("ascii")) NICKNAME = machine.nvs_getstr("owner", "name") CHANNEL = 0 class microham: """microham: a virtual amateur radio client, using MQTT""" 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():
# Connect network import wifisetup wifisetup.auto_connect() # rtc = machine.RTC() # rtc.ntp_sync(server="cn.ntp.org.cn", tz="CET-8CEST") # Reset apikey if buttonA.isPressed(): try: machine.nvs_erase('apikey.pem') except: pass # Read apikey apikey = machine.nvs_getstr('apikey.pem') if apikey == None: apikey = ubinascii.hexlify(os.urandom(4)).decode('utf8') #Random APIKEY apikey = apikey.upper() machine.nvs_setstr('apikey.pem', apikey) # M5Cloud import ujson as json from config import server_map with open('modeconfig.json', 'r') as f: mode = json.loads(f.read()) lcd.clear() # Display # lcd.clear(lcd.BLACK)
files = uos.listdir('/media') for f in files: if f.endswith('.png'): pictures.append("/media/" + f) try: apps = uos.listdir('/lib') for app in apps: files = uos.listdir('/lib/' + app) for f in files: if f.endswith('.png'): pictures.append("/lib/" + app + "/" + f) except: pass current = machine.nvs_getstr('splash', 'logo') while True: options = [] for f in pictures: title = f if f == current: title += " [Enabled]" options.append(title) options.append("Default logo") options.append("< Exit") selected = term.menu("Picture", options, 0, "") if selected > len(pictures): system.home(True) if selected == len(pictures):
import woezel, rgb, wifi, uinterface, machine, system, gc, time from default_icons import icon_no_wifi, animation_connecting_wifi def install(app_name): machine.nvs_setstr('uinstaller', 'to_install', app_name) system.start('uinstaller') if system.__current_app__ == 'uinstaller': to_install = machine.nvs_getstr('uinstaller', 'to_install') machine.nvs_setstr('uinstaller', 'to_install', '') print('Installing %s' % to_install) if not to_install: system.reboot() ### For some reason normal uinterface.connect_wifi() doesn't ### work from dashboard.terminal.installer, so we have to do this ### odd workaround of connecting twice. wifi.connect() rgb.clear() data, size, frames = animation_connecting_wifi rgb.framerate(3) rgb.gif(data, (12, 0), size, frames) del data, size, frames, animation_connecting_wifi gc.collect() wifi.wait() wifi.connect() wifi.wait()
def drawTask(onSleep=False): global gui_redraw, cfg_nickname, gui_apps, gui_app_current, ota_available if gui_redraw or onSleep: gui_redraw = False display.drawFill(COLOR_BG) currHeight = 0 noLine = False if gui_app_current < 0: if cfg_logo: #Print logo app_height = display.height() - 16 - currHeight logoHeight = drawLogo(currHeight, app_height, True) if logoHeight > 0: noLine = True if logoHeight < 1: #Logo enabled but failed to display title = "BADGE.TEAM" subtitle = "PLATFORM" logoHeight = display.getTextHeight( title, "permanentmarker22") + display.getTextHeight( subtitle, "fairlight12") display.drawText( (display.width() - display.getTextWidth(title, "permanentmarker22")) // 2, currHeight + (app_height - logoHeight) // 2, title, COLOR_FG, "permanentmarker22") currHeight += display.getTextHeight( title, "permanentmarker22") display.drawText( (display.width() - display.getTextWidth(subtitle, "fairlight12")) // 2, currHeight + (app_height - logoHeight) // 2, subtitle, COLOR_FG, "fairlight12") currHeight += display.getTextHeight( subtitle, "fairlight12") else: noLine = True display.drawPng(0, 0, LOGO) else: display_app(currHeight) if onSleep: info = 'Sleeping...' owner = machine.nvs_getstr("owner", "name") fontlist = [ "permanentmarker22", "Roboto_Regular18", "Roboto_Regular12" ] if (owner): display.drawFill(COLOR_BG) for font in fontlist: if font == fontlist[-1]: display.drawText(0, 0, owner, COLOR_FG, font) elif display.getTextWidth(owner, font) <= display.width(): display.drawText( (display.width() - display.getTextWidth(owner, font)) // 2, 0, owner, COLOR_FG, font) break #elif not rtc.isSet(): # info = "RTC not available" elif ota_available: info = "Update available!" #elif wifi_status_curr: # info = "WiFi connected" else: info = "" #'Press START' if not noLine: display.drawLine(0, display.height() - 16, display.width(), display.height() - 16, COLOR_FG) easydraw.disp_string_right_bottom(0, info) if len(gui_apps) > 0: drawPageIndicator(len(gui_apps), gui_app_current) if cfg_greyscale: display.flush(display.FLAG_LUT_GREYSCALE) else: display.flush(display.FLAG_LUT_NORMAL) return 1000
display.flush() time.sleep(2) # Check if we have upgraded from a legacy firmware legacy_mpr0 = machine.nvs_get_u16("badge", "mpr121.base.0") if legacy_mpr0: display.drawFill(0xFFFFFF) display.drawText(0, 0, "Welcome to the BADGE.TEAM platform firmware!", 0x000000, "7x5") display.drawText(0, 6, "You have upgraded from an older firmware,", 0x000000, "7x5") display.drawText(0, 12, "now migrating your settings...", 0x000000, "7x5") display.flush() legacy_wifi_ssid = machine.nvs_getstr("badge", "wifi.ssid") legacy_wifi_password = machine.nvs_getstr("badge", "wifi.password") legacy_eink_type = machine.nvs_getstr("badge", "eink.dev.type") if currentState != 1: print( "Badge was upgraded from 2017 firmware. Move WiFi settings...") if legacy_wifi_ssid: machine.nvs_setstr("system", "wifi.ssid", legacy_wifi_ssid) if legacy_wifi_password: machine.nvs_setstr("system", "wifi.password", legacy_wifi_password) if legacy_eink_type: machine.nvs_setstr("system", "eink.dev.type", legacy_eink_type) else: print(
import term, orientation, system, time, uos, json, machine system.serialWarning() term.header(True, "Services") print("Loading...") apps = uos.listdir('/lib') services = [] for app in apps: if "ledsrv.py" in uos.listdir('/lib/' + app): services.append(app) current = machine.nvs_getstr('splash', 'ledApp') while True: options = [] for service in services: title = service if service == current: title += " [Enabled]" options.append(title) options.append(" None (disable LED services)") options.append("< Exit") selected = term.menu("Services", options, 0, "") if selected > len(services): system.home(True) if selected == len(services): current = None try: machine.nvs_erase('splash', 'ledApp') except:
def drawTask(onSleep=False): global gui_redraw, cfg_nickname, gui_apps, gui_app_current, ota_available if gui_redraw or onSleep: gui_redraw = False display.drawFill(0xFFFFFF) currHeight = 0 noLine = False if gui_app_current < 0: if cfg_logo and cfg_nickname: currHeight += easydraw.nickname() currHeight += 4 display.drawLine(0, currHeight, display.width() - 1, currHeight, 0x000000) currHeight += 4 app_height = display.height() - 16 - currHeight logoHeight = drawLogo(currHeight, app_height, True) if logoHeight > 0: noLine = True if logoHeight < 1 and cfg_logo: title = "BADGE.TEAM" subtitle = "PLATFORM" logoHeight = display.getTextHeight( title, "permanentmarker22") + display.getTextHeight( subtitle, "fairlight12") display.drawText( (display.width() - display.getTextWidth(title, "permanentmarker22")) // 2, currHeight + (app_height - logoHeight) // 2, title, 0x000000, "permanentmarker22") currHeight += display.getTextHeight(title, "permanentmarker22") display.drawText( (display.width() - display.getTextWidth(subtitle, "fairlight12")) // 2, currHeight + (app_height - logoHeight) // 2, subtitle, 0x000000, "fairlight12") currHeight += display.getTextHeight(subtitle, "fairlight12") if (not cfg_logo) and cfg_nickname: noLine = True nick = machine.nvs_getstr("owner", "name") if nick == None: nick = "BADGE.TEAM" currHeight += ( display.getTextHeight(nick, "permanentmarker22") // 2) - 8 display.drawText( (display.width() - display.getTextWidth(nick, "permanentmarker22")) // 2, currHeight, nick, 0x000000, "permanentmarker22") currHeight += display.getTextHeight(nick, "permanentmarker22") else: display_app(currHeight) if onSleep: info = 'Sleeping...' #elif not rtc.isSet(): # info = "RTC not available" elif ota_available: info = "Update available!" #elif wifi_status_curr: # info = "WiFi connected" else: info = 'Press START' if not noLine: display.drawLine(0, display.height() - 16, display.width(), display.height() - 16, 0x000000) easydraw.disp_string_right_bottom(0, info) if len(gui_apps) > 0: drawPageIndicator(len(gui_apps), gui_app_current) if cfg_greyscale: display.flush(display.FLAG_LUT_GREYSCALE) else: display.flush(display.FLAG_LUT_NORMAL) return 1000