def sd(self): lcd.println('Write into SD...') with open('/sd/'+self.DNAME_ROOT+'/'+self.fname_save, 'a') as o: for ds in self.dataBuffer: o.write('%f,%f,%f,%f,%f,%f,%f\n' % ds) lcd.println('OK.') return 0
def conn_cb(bt_o): events = bt_o.events( ) # this method returns the flags and clears the internal registry if events & Bluetooth.CLIENT_CONNECTED: lcd.println("Client connected") elif events & Bluetooth.CLIENT_DISCONNECTED: lcd.println("Client disconnected")
def read_json(filename): 'read json from specified filename' try: lcd.println('reading {}'.format(filename)) with open(filename, 'r') as f: return ujson.load(f) except: lcd.println('Error in reading json: ' + str(e))
def download_image(image_url): try: r = urequests.get(image_url) write_file('tmp.jpg', r.content) except Exception as e: lcd.println('Exception(download_image): ' + str(e)) raise e finally: r.close()
def connect(): station = network.WLAN(network.STA_IF) station.active(True) station.connect("nstudents", "nnnedjpwireless") while station.isconnected() == False: lcd.print(".") time.sleep(0.5) pass lcd.print("\n") lcd.println("connected") lcd.println(str(station.ifconfig()))
def wifiCheck(): sta_if = network.WLAN(network.STA_IF) if sta_if.active() == False: sta_if.active(True) wifi = json.load(open('/flash/etc/wlan.json', 'r')) ssid = wifi['wifi']['ssid'] pwd = wifi['wifi']['password'] sta_if.connect(ssid, pwd) while sta_if.ifconfig()[0] == '0.0.0.0': time.sleep(.5) lcd.println('Connect to WLAN.')
def sync_rtc(interval=11, max_count=100): print("Try to synchronize network time") rtc = RTC() rtc.ntp_sync('ntp.nict.jp', tz='JST-9') count = 0 while count < max_count: if rtc.synced(): message = 'RTC synced. {}'.format(utime.localtime()) print(message) lcd.println(message, color=lcd.GREEN) break utime.sleep_ms(interval) #print('.') count += 1
def download_image_to_file(image_url, filename, step_size=1024): r = urequests.get(image_url) try: with open(filename, 'wb') as f: while True: c = r.raw.read(step_size) if c: f.write(c) else: return except Exception as e: lcd.println('Exception(download_image): ' + str(e)) raise e finally: r.close()
def app_txtReader(self, fname): lcd.clear() f = Framework('txtReader') f.drawNaviButton(strC='EXIT') lcd.font(lcd.FONT_DefaultSmall, transparent=False, fixedwidth=True) idx = 0 idx_s = [0] page = 0 while True: letter_current_page = 0 lcd.setCursor(0, 0) lcd.rect(0, 0, 320, 240 - f.h_bottom, lcd.BLACK, lcd.BLACK) with open(fname, 'r') as o: o.seek(idx) flag_end = False for row in range(20): for col in range(29): c = o.read(1) if not c: lcd.println('--- END ---') flag_end = True break if c != '\n': lcd.print(c) letter_current_page += 1 else: letter_current_page += 1 break lcd.print('\n') if flag_end: break while True: time.sleep(0.1) if buttonA.isPressed(): if page != 0: page -= 1 del (idx_s[-1]) idx = idx_s[-1] break elif buttonB.isPressed(): if c: idx += letter_current_page idx_s.append(idx) page += 1 break elif buttonC.isPressed(): return 0
def run(self): if self.fileCheck() < 0: return -1 self.drawNaviButton() lcd.setCursor(0,0) lcd.println('Press START to start') while not buttonA.isPressed(): if buttonC.isPressed(): return 0 time.sleep(.5) self.fname_save = self.fnameGen() lcd.println('Record into %s' % self.fname_save) self.scanner()
def printMenu(self): self._menuItems = self.__filterMenuItems(self.getMenuItems()) self._min = 1 self._max = len(self._menuItems) lcd.font(lcd.FONT_DejaVu24, transparent=True) lcd.rect(self.cursor[0], self.cursor[1], 320, 240, lcd.WHITE, lcd.WHITE) lcd.setCursor(self.cursor[0], self.cursor[1]) for i in range(self._max): selectedPrefix = ' ' if (i + 1) == self.value: selectedPrefix = '>' lcd.println('{} {}'.format(selectedPrefix, self._menuItems[i][0]))
def app_pyLauncher(self, fname): print('Launch %s...' % uos.getcwd() + '/' + fname) lcd.setCursor(self.upleft[0] + 1, self.upleft[1] + 1) lcd.println('Now loading...') with open(fname, 'rb') as o: code = o.read() with open(PATH_CACHE, 'wb') as o: o.write(code) if 'cache' in sys.modules.keys(): del sys.modules['cache'] lcd.clear() import cache if code[:18] == b'# -*- advanced -*-': print('-*- This is an advanced program -*-') cache.Main().run() else: cache.main()
def __guiUpdate(self): lcd.setCursor(self.upleft[0] + 1, self.upleft[1] + 1) cp = int(self.index / self.MIOP) + 1 # Current page if self.currentPage != cp: # Which means that it is time to flip over self.currentPage = cp self.__drawBackground() self.__drawNaviBar(cp) sru = (cp - 1) * self.MIOP if len(self.selections) - sru >= self.MIOP: srd = sru + self.MIOP else: srd = len(self.selections) for i in range(sru, srd): if i == self.index: lcd.println(self.selections[i], color=lcd.GREEN) else: lcd.println(self.selections[i], color=lcd.WHITE)
def fileCheck(self): try: uos.stat('/sd') lcd.println('SD card has already been mounted.') except: try: uos.mountsd() lcd.println('SD card is mounted.') except: lcd.println('No SD card is found.') return -1 try: sdFiles = uos.listdir('/sd') if self.DNAME_ROOT not in sdFiles: uos.mkdir('/sd/' + self.DNAME_ROOT) lcd.println('mkdir /sd/%s/' % self.DNAME_ROOT) except: lcd.println('The SD card is not writable.') return -2 return 0
def clock(): rtc = machine.RTC() print("Synchronize time from NTP server ...") lcd.println("Synchronize time from NTP server ...") rtc.ntp_sync( server="ru.pool.ntp.org", tz="CET-3CEST,M3.5.0,M10.5.0/3") # Часовой пояс меняется в CET-3CEST lcd.clear(lcd.BLUE) lcd.setColor(lcd.BLACK, lcd.BLUE) lcd.font(lcd.FONT_Comic, fixedwidth=True, dist=16, width=2) while True: d = time.strftime("%d-%m-%Y", time.localtime()) t = time.strftime("%H:%M:%S", time.localtime()) lcd.print(d, lcd.CENTER, 50) lcd.print(t, lcd.CENTER, 130) time.sleep(0.02) if buttonA.isPressed(): break if buttonС.isPressed(): break
def show(self): super().show() lcd.font(lcd.FONT_DejaVu18, transparent=True) self.resetScreen() lcd.print('Connecting to wifi...') import network sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect(secrets.WIFI_SSID, secrets.WIFI_PASSWORD) startTime = utime.time() while not sta_if.isconnected(): if startTime + 45 < utime.time(): break lcd.print('.') utime.sleep(2) sta_if.connect(secrets.WIFI_SSID, secrets.WIFI_PASSWORD) if sta_if.isconnected(): self.resetScreen() lcd.println('Connected to WIFI...') lcd.println('Machine will reboot!') lcd.println('Stay until update done') with open('.updateRequested', mode='a'): pass utime.sleep(5) machine.reset() else: self.resetScreen() lcd.print('Could not connect to WIFI!') utime.sleep(5) super().back()
def main(): from m5stack import lcd, buttonA import network import json import time try: isConnected = False lcd.setCursor(0,0) sta_if = network.WLAN(network.STA_IF) if sta_if.active() == False: lcd.println('Connecting...') sta_if.active(True) wifi = json.load(open('/flash/etc/wlan.json', 'r')) ssid = wifi['wifi']['ssid'] pwd = wifi['wifi']['password'] sta_if.connect(ssid, pwd) # time.sleep(3) while not buttonA.isPressed(): ni = sta_if.ifconfig() if ni[0] == '0.0.0.0': time.sleep(1) else: isConnected = True lcd.println('ip: %s' % ni[0]) lcd.println('mask: %s' % ni[1]) lcd.println('gate: %s' % ni[2]) lcd.println('dns: %s' % ni[3]) break if isConnected: while not buttonA.isPressed(): time.sleep(.2) except: pass
def main(): import network from m5stack import lcd, buttonA import time try: while not buttonA.isPressed(): lcd.setCursor(0, 0) network.ftp.start(user="******", password="******", buffsize=1024, timeout=300) fs = network.ftp.status() lcd.println('Server IP: %s' % fs[4]) lcd.println('Server status: %s' % fs[2]) lcd.println('Data status: %s' % fs[3]) time.sleep(1) network.ftp.stop() except: pass
def main(): try: lcd.println('main') if not connect_wifi(WIFI_CONFIG): lcd.println('Failed to connect') return except Exception as e: lcd.println(str(e)) return expires_date = 0 lcd.clear() lcd.setCursor(0, 0) while True: try: gc.collect() expires_date = task(expires_date) utime.sleep(10) except Exception as e: lcd.println('Exception(main): ' + str(e)) import sys sys.print_exception(e) expires_date = 0 # Force to refresh key # anyway, retry connect connect_wifi(WIFI_CONFIG)
def get_current_playing_track(): global g_spotify_token headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(g_spotify_token), } try: r = urequests.get(SPOTIFY_API_CURRENTLY_PLAYING_URL, headers=headers) if len(r.content) == 0: # if status code is 204, no track is played. It's not error if r.status_code == 204: return None else: # warn about status_code lcd.println('header status is: {}'.format(r.status_code)) return None return r.json() except Exception as e: lcd.println('Exception(get_current_playing_track): ' + str(e)) lcd.println('Error: ' + str(r.content)) raise e finally: r.close()
def connect_wifi(wifi_configs, timeout_sec=10): 'Connect to wifi described in wifi_configs' wlan = network.WLAN(network.STA_IF) # create station interface wlan.active(True) # activate the interface for net in wlan.scan(): ssid = net[0].decode() for candidate_config in wifi_configs: if ssid == str(candidate_config['SSID']): lcd.println('Connecting to ' + ssid) wlan.connect(ssid, candidate_config['PASSWD']) start_date = utime.time() while not wlan.isconnected(): now = utime.time() lcd.print('.') if now - start_date > timeout_sec: break utime.sleep(1) if wlan.isconnected(): lcd.println('Success to connect') return True else: lcd.println('Failed to connect') return False return False
def do_connect(ntwrk_ssid, netwrk_pass): if not wlan_sta.isconnected(): print('Connect WiFi: SSID:' + ntwrk_ssid + ' PASSWD:' + netwrk_pass + ' network...') lcd.println('Connect WiFi: \r\nWiFi SSID:' + ntwrk_ssid) # lcd.println('Connect WiFi: \r\nWiFi SSID:'+ntwrk_ssid+' \t\nPASSWD:'+netwrk_pass) # wlan_sta.eventCB(wifi_cb) wlan_sta.connect(ntwrk_ssid, netwrk_pass) lcd.print('Connecting.') a = 0 while not wlan_sta.isconnected() | (a > 50): time.sleep_ms(500) a += 1 print('.', end='') lcd.print('.', wrap=1) if wlan_sta.isconnected(): print('\nConnected. Network config:', wlan_sta.ifconfig()) lcd.println("Connected! \r\nNetwork config:\r\n" + wlan_sta.ifconfig()[0] + ', ' + wlan_sta.ifconfig()[3]) return (True) else: print('\nProblem. Not Connected to :' + ntwrk_ssid) lcd.println('Problem. Not Connected to :' + ntwrk_ssid) return (False)
# This file is executed on every boot (including wake-boot from deepsleep) import sys sys.path[1] = '/flash/lib' from m5stack import lcd, speaker, buttonA, buttonB, buttonC # ---------- M5Cloud ------------ if True: if buttonB.isPressed(): lcd.println('On: OFF-LINE Mode', color=lcd.ORANGE) else: import wifisetup import m5cloud
lcd.init(lcd.M5STACK, width=320, height=240, mosi=23, miso=12, clk=18, cs=27, dc=26, rst_pin=5, invrot=0, bgr=True) lcd.orient(3) sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.scan() # Scan for available access points sta_if.connect("login", "password") # Connect to an AP sta_if.isconnected() # Check for successful connection #rez = str(sta_if.ifconfig()) if not sta_if.isconnected(): sta_if.connect() print("Waiting for connection...") while not sta_if.isconnected(): utime.sleep(1) lcd.setCursor(0, 40) lcd.setColor() lcd.println(str(sta_if.ifconfig()))
for net in wlan.scan(): ssid = net[0].decode('utf-8') if ssid == MY_SSID: wlan.connect(MY_SSID, MY_SSID_PASSWORD) while not wlan.isconnected(): time.sleep_ms(100) def rtc_setup(): rtc = machine.RTC() rtc.ntp_sync(server="ntp.jst.mfeed.ad.jp", tz="JST-9") while not rtc.synced(): time.sleep_ms(100) lcd.println("WiFi connecting...") wifi_connect() lcd.println("RTC setup...") rtc_setup() lcd.clear() lcd.setTextColor(lcd.ORANGE, lcd.BLACK) lcd.font(lcd.FONT_7seg, fixedwidth=True, dist=16, width=2) while True: d = time.strftime("%Y-%m-%d", time.localtime()) t = time.strftime("%H:%M:%S", time.localtime()) lcd.print(d, lcd.CENTER, 50) lcd.print(t, lcd.CENTER, 130) time.sleep_ms(1000)
uart.write(_ls) time.sleep_ms(100) #play _ls= bytes([0xF0, 0x43, 0X73, 0x01, 0x33, 0x01, 0x00, 0x08, 0x01, 0x00, 0x00, 0x00, 0x00, 0xF7]) uart.write(_ls) time.sleep_ms(100) layer=0x01 #current_layer _ls=bytes([0xF0, 0x43, 0X73, 0x01, 0x33, 0x01, 0x00, 0x10, layer, 0x00, 0x00, 0x00, 0x00, 0xF7]) uart.write(_ls) time.sleep_ms(100) led_mode=0x00 #on x=0x02 y=0x02 _ls =bytes([0xF0, 0x43, 0X73, 0x01, 0x33, 0x01, 0x00, 0x06, x, y, layer, led_mode, 0x00, 0xF7]) uart.write(_ls) time.sleep_ms(100) #remote off _ls=bytes([0xF0, 0x43, 0X73, 0x01, 0x33, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF7]) uart.write(_ls) time.sleep_ms(100) except Exception as e: #print(str(e)) lcd.println(str(e))
def alert(self, text): lcd.rect(0, 0, 320, 240, lcd.DARKGREY, lcd.DARKGREY) lcd.println(text, lcd.CENTER, color=lcd.RED) lcd.println('Long press \"A\" to exit', lcd.CENTER, color=lcd.BLACK) while not buttonA.isPressed(): time.sleep(1)
from network import Bluetooth # そもそもライブラリ無い説 from m5stack import lcd lcd.println("start") bluetooth = Bluetooth() bluetooth.set_advertisement(name='ESP32', service_uuid=b'1234567890123456') def conn_cb(bt_o): events = bt_o.events( ) # this method returns the flags and clears the internal registry if events & Bluetooth.CLIENT_CONNECTED: lcd.println("Client connected") elif events & Bluetooth.CLIENT_DISCONNECTED: lcd.println("Client disconnected") def main(): bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb) bluetooth.advertise(True)
# ライブラリ導入 from m5stack import lcd # 初期化 lcd.clear() # フォント指定 lcd.font(lcd.FONT_Dejavu24) # フォント FONT_Dejavu24 に設定 # 画像挿入 lcd.image(lcd.CENTER, lcd.BOTTOM, file="/flash/icon.jpg") # 見出し lcd.setCursor(0, 0) lcd.setColor(lcd.WHITE, lcd.BLUE) fw, fh = lcd.fontSize() ww, wh = lcd.winsize() lcd.rect(0, 0, ww, fh + 1, lcd.BLUE, lcd.BLUE) lcd.println("N High School students Card") # 文字 lcd.setColor(lcd.WHITE, lcd.BLACK) lcd.print('Waricoma', 10, 30)
def main(): import time import uos from m5stack import lcd, buttonA, buttonB, buttonC import network import binascii DNAME_ROOT = 'wifi_analyzer' def drawNaviButton(strA='START', strB='STOP', strC='EXIT'): lcd.text(40, 215, strA, lcd.WHITE) lcd.text(135, 215, strB, lcd.WHITE) lcd.text(240, 215, strC, lcd.WHITE) def fnameGen(): currentFileList = list( filter(lambda x: 'WA_' in x, uos.listdir('/sd/' + DNAME_ROOT))) currentFileList = list(map(lambda x: x.lower(), currentFileList)) if 'wa_0001.csv' not in currentFileList: return 'WA_0001.csv' else: currentFileList.sort() newestFileName = currentFileList[-1] no = int(newestFileName[3:7]) return 'WA_%s.csv' % (('%4d' % (no + 1)).replace(' ', '0')) def resdisplay(apresults, n, time): lcd.rect(0, 0, 320, 24, lcd.BLUE, lcd.BLUE) lcd.font(lcd.FONT_Ubuntu, transparent=True) lcd.text(0, 2, 'N_AP:%d N_SCAN:%d TIME:%d' % (len(apresults), n, time), lcd.WHITE) lcd.rect(0, 24, 320, 186, lcd.BLACK, lcd.BLACK) lcd.setCursor(0, 24) lcd.font(lcd.FONT_DefaultSmall) if len(apresults) < 15: i = 0 for apresult in apresults: resstr = '%02d, ch: %02d, rs: %d, %s\n' % ( i + 1, apresult[2], apresult[3], apresult[0].decode()) lcd.print(resstr, color=lcd.WHITE) i = i + 1 else: for i in range(0, 15): apresult = apresults[i] resstr = '%02d, ch: %02d, rs: %d, %s\n' % ( i + 1, apresult[2], apresult[3], apresult[0].decode()) lcd.print(resstr, color=lcd.WHITE) try: uos.stat('/sd') except: try: uos.mountsd() except: lcd.println('No SD card is found.') return -1 try: sdFiles = uos.listdir('/sd') if DNAME_ROOT not in sdFiles: uos.mkdir('/sd/' + DNAME_ROOT) except: lcd.println('The SD card is not writable.') return -2 try: drawNaviButton() lcd.setCursor(0, 0) lcd.println('Press START to start') while not buttonA.isPressed(): time.sleep(.5) if buttonC.isPressed(): return 0 wlan = network.WLAN(network.STA_IF) wlan.active(True) fname = fnameGen() lcd.println('Recording into %s...' % fname) ts = time.time() n = 0 while not buttonB.isPressed(): buf = '' aps = wlan.scan() n += 1 te = time.time() - ts for ap in aps: # (ssid, bssid, primary_chan, rssi, auth_mode, auth_mode_string, hidden) mac = (binascii.hexlify(ap[1])).decode() mac = ':'.join([ mac[:2], mac[2:4], mac[4:6], mac[6:8], mac[8:10], mac[10:12] ]) buf += '%.3f,%s,%s,%d,%s\n' % (te, mac, ap[0].decode(), ap[3], ap[2]) print(buf + '---------------------') resdisplay(aps, n, int(te)) with open('/sd/' + DNAME_ROOT + '/' + fname, 'a') as o: o.write(buf) lcd.println('Exit.') except: print('Exit since error.') pass