def selectVList(title, items, sel=0, optional=0): N = len(items) rdw=1 while btn.A.value(): if not btn.U.value(): sel=(sel-1)%N rdw=1 if not btn.D.value(): sel=(sel+1)%N rdw=1 if (not btn.B.value()) and optional: sleep_ms(300) return -1 if rdw: oled.fill(0) oled.fill_rect(0,31,128,10,1) for dy,item in enumerate(items): if abs(dy-sel) > 2: continue if type(item) == tuple: item = item[0] oled.hctext(item,10*(dy-sel)+32,dy!=sel) oled.fill_rect(0,0,128,10,1) oled.hctext(title,1,0) oled.show() rdw=0 sleep_ms(300) sleep_ms(300) if type(items[sel]) == tuple: return items[sel][1] return sel
def app_start(): oled.fill(0) sprites = loadPBM('./sprites.pbm') oled.blit(sprites, 0, 0) sprites = [] for i in range(6): # split sprites fbuf = framebuf.FrameBuffer(bytearray(32), 16, 16, framebuf.MONO_HLSB) for yy in range(16): for xx in range(16): if oled.pixel(i * 16 + xx, yy): fbuf.pixel(xx, yy, 1) sprites.append(fbuf) objs = [] for i in range(randint(5, 15)): objs.append([0, 0, 65, 1]) # sprite,x,y,vy while btn.B.value(): oled.fill(0) for o in objs: o[2] += o[3] if o[2] > 64: # reset obj o[0] = randint(0, 5) o[1] = randint(0, 110) o[2] = -16 o[3] = randint(1, 10) oled.blit(sprites[o[0]], o[1], o[2], 0) oled.fill_rect(20, 55, 90, 8, 0) oled.hctext('[B] to Quit', 56, 1) oled.show() sleep_ms(10)
def app_start(): g = 0.1 jerk = 0.3 ball = [64, -10, 1, 0, 7] #x,y,vx,vy,r while btn.B.value(): if not btn.A.value(): ball[0] = randint(ball[4], 128 - ball[4]) ball[1] = randint(ball[4], 63 - ball[4]) ball[2] = 3 * (random() - 0.5) ball[3] = 3 * (random() - 0.5) sleep_ms(250) oled.fill(0) if ball[1] > 60 - ball[4] and ball[2]**2 + ball[3]**2 < 0.1: oled.hctext("Press [A]", 30, 1) oled.fill_circle(round(ball[0]), round(ball[1]), ball[4], 1) oled.show() if not btn.U.value(): ball[3] -= jerk if not btn.D.value(): ball[3] += jerk if not btn.L.value(): ball[2] -= jerk if not btn.R.value(): ball[2] += jerk ball[3] += g ball[0] += ball[2] ball[1] += ball[3] ball[2] *= 0.999 ball[3] *= 0.999 if ball[1] > 63 - ball[4]: ball[3] *= -0.9 ball[1] = 64 - ball[4] if ball[0] > 128 - ball[4]: ball[2] *= -0.9 ball[0] = 127 - ball[4] if ball[0] < ball[4]: ball[2] *= -0.9 ball[0] = ball[4]
def performScan(): oled.fill(0) oled.fill_rect(0, 0, 128, 9, 1) oled.hctext('WiFi Scan', 1, 0) oled.hctext('Scanning...', 30, 1) oled.show() wifis = wlan.scan() wifis.sort() return wifis
def app_start(): oled.fill(0) oled.text('Hello', 0, 0, 1) oled.text('World', 0, 8, 1) oled.show() for y in range(2 * 8, -1, -1): oled.invert(y % 2) for x in range(5 * 8, -1, -1): oled.fill_rect(x * 3, y * 3, 3, 3, oled.pixel(x, y)) oled.show() oled.hctext('[B] to Quit', 56, 1) oled.show() while btn.B.value(): sleep_ms(20)
def app_start(): banner = "Government\tTechnology\tAgency\nRagul Balaji\tWizard\nHo Jie Feng\tV4P0R\nAndre Ng\tTopkek\nC01N\t(C) 2019\nThank You\tfor Playing" for text in banner.split('\n'): lines = text.split('\t') lineh = 10 blockh = lineh * len(lines) midy = int((64 - blockh) / 2) stopped = False for y in range(64, -blockh, -3): if y < midy and not stopped: stopped = True sleep_ms(3000) oled.fill(0) for dy, line in enumerate(lines): oled.hctext(line, y + dy * lineh, 1) oled.show() return 0
def getDualButton(title, lefttext, righttext, default): sel = default hasUpdates = 1 while(btn.A.value()): if hasUpdates: oled.fill(0) oled.hctext(title, 0,1) drawDualButton(lefttext, righttext, 1-sel, sel) oled.hctext("A: Select", 64 - 20,1) oled.show() hasUpdates = 0 if(btn.L.value() == 0): sel = 0 hasUpdates = 1 if(btn.R.value() == 0): sel = 1 hasUpdates = 1 return sel
def inputAlphanumeric(): selRow = 0 selCol = 0 ans = "" heldDown = False while True: oled.fill(0) oled.hctext(ans[-15:]+('_' if (ticks_ms()>>9)%2 else ' '),0,1) oled.hline(0,9,128,1) for row in range(4): for col in range(16): color = (row == selRow and col == selCol) oled.fill_rect(1+col*8,20+row*10-1,8,10,color) oled.text(keyboard[row][col],1+col*8,20+row*10,not color) oled.show() if not btn.U.value(): selRow = (selRow + 4 - 1)%4 if not btn.D.value(): selRow = (selRow + 4 + 1)%4 if not btn.L.value(): selCol = (selCol + 16 - 1)%16 if not btn.R.value(): selCol = (selCol + 16 + 1)%16 if not btn.A.value(): if selRow == 3 and selCol == 15: return ans ans += keyboard[selRow][selCol] if not btn.B.value(): ans = ans[:-1] holdCnt = 0 while((not btn.U.value()) or (not btn.D.value()) or (not btn.L.value()) or (not btn.R.value()) or (not btn.A.value()) or (not btn.B.value())): sleep_ms(10) holdCnt += 1 if heldDown: if holdCnt >= 5: break else: if holdCnt >= 50: heldDown = True if holdCnt < 5: heldDown = False
def installApp(REPO_URL, manifest, APP_ROOT='/apps'): import upip_utarfile as tarfile import uzlib, os, gc from upip import url_open gc.collect() oled.fill(0) oled.text('Installing...', 0, 0, 1) oled.text(manifest['name'], 0, 8, 1) oled.text(manifest['version'], 0, 16, 1) oled.show() count = 0 try: s1 = url_open(REPO_URL + manifest['url']) f2 = uzlib.DecompIO(s1, 30) t3 = tarfile.TarFile(fileobj=f2) for x in t3: print(x) count += 1 oled.fill_rect(0, 32, 128, 16, 0) oled.hctext('File #%d' % count, 32, 1) oled.hctext(x.name[-16:], 40, 1) oled.show() if x.type == tarfile.DIRTYPE: # a dir FOLDER_PATH = APP_ROOT + '/' + x.name[:-1] print(FOLDER_PATH) if x.name[:-1] in os.listdir(APP_ROOT): deleteFolder(FOLDER_PATH) # delete if exists os.mkdir(FOLDER_PATH) else: # a file f4 = open(APP_ROOT + '/' + x.name, 'wb') f4.write(t3.extractfile(x).read()) f4.close() finally: s1.close() rebuildAppsIndex(APP_ROOT) oled.text('Done :) Reboot!', 0, 56, 1) oled.show() sleep_ms(500) import machine machine.reset()
def viewAppDetail(manifest): oled.fill(0) oled.fill_rect(0, 0, 128, 10, 1) oled.text(manifest['name'], 0, 1, 0) oled.hctext('V:%s' % manifest['version'], 21, 1) oled.hctext(manifest['author'], 31, 1) oled.text('[R] to Install', 0, 48, 1) oled.text('[B] to Cancel', 0, 56, 1) desc = manifest['desc'] + ' ' while True: ticknow = ticks_ms() oled.fill_rect(0, 11, 128, 9, 0) for i in range(16): oled.text(desc[(i + ticknow // 150) % len(desc)], 8 * i, 11, 1) oled.show() if not btn.R.value(): sleep_ms(300) return True if not btn.B.value(): sleep_ms(300) return False sleep_ms(20)
def inputDPAD(Qn='Give Input!',minChar=0): oled.fill(0) oled.fill_rect(0,0,128,9,1) oled.hctext('DPAD INPUT',1,0) oled.hctext(Qn,12,1) oled.hctext('( need %d keys )'%minChar if minChar > 0 else '[A] to Submit',56,1) val = '' rdw=1 while len(val) < minChar or minChar < 1: if not btn.A.value() and minChar < 1: break sleep_ms(200) if not btn.B.value(): val = val[:-1] rdw=1 if not btn.U.value(): val += 'U' rdw=1 if not btn.D.value(): val += 'D' rdw=1 if not btn.L.value(): val += 'L' rdw=1 if not btn.R.value(): val += 'R' rdw=1 if rdw: rdw=0 oled.fill_rect(0,29,128,9,0) oled.hctext(val+('_' if (ticks_ms()>>9)%2 else ' '),30,1) oled.show() sleep_ms(200) oled.hctext('INPUT OK!',42,1) oled.show() return val
def newGame(): global ball, playerPaddle, enemyPaddle, score ball = [64, 32, 3, randSpeed(1, 4, 1), randSpeed(2, 3, 1)] playerPaddle = [125, 22, 3, 20, 2] enemyPaddle = [0, 22, 3, 20, 1.5] oled.hctext('ENEMY PLAYER', 25, 1) oled.hctext('%d %d' % (score[1], score[0]), 35, 1) oled.hctext('[A] to Play', 56, 1) oled.show() while btn.A.value(): if not btn.B.value(): return -1 sleep_ms(100) drawObjects() sleep_ms(500) return 0
from badge import oled,np,connectWifi,btn,BAT from utils import hsv_to_rgb,loadPBM from random import random,randint import machine import sys sys.path.append('/systemapps') #Check for battery level avg = 0 for i in range(100): avg += BAT.voltage() if avg/100 < 3.2: bypass = False for i in range(50): oled.fill(0) oled.hctext("BATTERY LOW", 0, 1) oled.fill_rect(0,32-8,int(128*((50-i)/50)),16,1) #TODO: bypass warning oled.show() sleep_ms(100) oled.fill(0) oled.hctext("Deep Sleeping", 32-4, 1) oled.show() sleep_ms(1000) oled.poweroff() machine.deepsleep() print('C01N Started!') connectWifi() oled.fill(0)
def app_start(): connectWifi() oled.fill(0) oled.fill_rect(0, 0, 128, 10, 1) oled.hctext('SGP Environment', 1, 0) if not wlan.isconnected(): oled.hctext('No WiFi :(', 24, 1) oled.hctext('Connection', 32, 1) oled.hctext('[B] to Quit', 56, 1) oled.show() while (btn.B.value()): sleep_ms(100) return 1 oled.hctext('Connecting to', 24, 1) oled.hctext('data.gov.sg', 32, 1) oled.show() psi = urequests.get('https://api.data.gov.sg/v1/environment/psi') psi = psi.json() psi_24 = psi['items'][0]['readings']['psi_twenty_four_hourly'] pm10_24 = psi['items'][0]['readings']['pm10_twenty_four_hourly'] pm25_24 = psi['items'][0]['readings']['pm25_twenty_four_hourly'] #psi3 = psi['items'][0]['readings']['psi_three_hourly'] oled.fill(0) oled.fill_rect(0, 0, 128, 10, 1) oled.hctext('SGP Environment', 1, 0) oled.hctext('24 hour values:', 17, 1) oled.text('PSI ' + str(psi_24['national']), 0, 32, 1) oled.hctext('(%s)' % psidescriptor(psi_24['national']), 40, 1) oled.text('PM10 %d ug/m^3' % pm10_24['national'], 0, 48, 1) oled.text('PM2.5 %d ug/m^3' % pm25_24['national'], 0, 56, 1) #oled.text(' @ '+str(wind['speed']['low'])+'-'+str(wind['speed']['high'])+' km/h',0,56,1) oled.show() while btn.A.value() and btn.B.value(): sleep_ms(100) sleep_ms(200) return
def app_start(): apps = [] apps_manifest = ujson.load(open('/apps/apps.json')) # User Apps for app in apps_manifest['list']: apps.append((app['name'], '/apps/%s' % app['dir'], app['start'])) apps.extend([ # System Apps ('App Store', '/systemapps', 'appstore'), ('System Info', '/systemapps', 'sysinfo'), ('File Explorer', '/systemapps', 'fileexplorer'), ('WiFi Scan', '/systemapps', 'wifiscan'), ('C01N Config', '/systemapps', 'coinconfig'), ('Credits', '/systemapps', 'credits') ]) sidx = 0 lastbat = BAT.percentage() needredraw = 1 while True: sleep_ms(10) batnow = BAT.percentage() if abs(lastbat - batnow) > 0.1: needredraw = 1 lastbat = batnow if btn.L.value() == 0: sleep_ms(200) sidx = (sidx - 1) % len(apps) needredraw = 1 if btn.R.value() == 0: sleep_ms(200) sidx = (sidx + 1) % len(apps) needredraw = 1 if btn.A.value() == 0: sleep_ms(200) originalSysModules = set() for mod in sys.modules: originalSysModules.add(mod) # Hacky Launch Code exec( 'try:\n\tos.chdir("%s")\n\timport %s as curapp\n\tcurapp.app_start()\nexcept:\n\toled.hctext("App Launch Fail",30,1)\n\toled.show()\nfinally:\n\tos.chdir("/")' % (apps[sidx][1], apps[sidx][2])) # Efficient Cleanup of Userspace for mod in sys.modules: if mod not in originalSysModules: del sys.modules[mod] gc.collect() needredraw = 1 if needredraw: needredraw = 0 oled.fill(0) oled.text('Apps', 0, 1, 1) oled.fill_rect(108, 2, int(16 * max(min(batnow, 1), 0)), 5, 1) oled.fill_rect(126, 2, 2, 5, 1) oled.rect(106, 0, 20, 9, 1) batstatus = 'USB' if batnow > 1 else '%d%%' % (batnow * 100) oled.text(batstatus, 104 - len(batstatus) * 8, 1, 1) oled.hline(0, 10, 128, 1) oled.hctext(apps[sidx][0], 20, 1) oled.hctext('[A] to Launch', 45, 1) oled.hctext('< %d/%d >' % (sidx + 1, len(apps)), 56, 1) oled.show() np[0] = hsv_to_rgb(sidx / len(apps), 1, 7) np.write() sleep_ms(20)
def app_start(): oled.fill(0) oled.hctext('C01N Config', 0, 1) oled.fill_rect(0, 55, 128, 9, 1) oled.hctext('Restart to Exit', 56, 0) oled.show() webhtml = open('/systemapps/coinconfig.html').read() config = readConfig() outpacket = [['c01n_name', 'Device Name', config['name']], ['c01n_ssid', 'WiFi SSID', config['wifi'][0]], ['c01n_pass', 'WiFi Password', config['wifi'][1]], ['c01n_repo', 'App Repo URL', config['apprepourl']]] ap_if = network.WLAN(network.AP_IF) AP_SSID = 'C01N-%s' % hexlify(ap_if.config('mac')).decode('utf-8')[-6:] AP_PASS = bytearray(5) for p in range(5): AP_PASS[p] = getrandbits(8) AP_PASS = hexlify(AP_PASS) ap_if.active(1) ap_if.config(essid=AP_SSID, authmode=network.AUTH_WPA_WPA2_PSK, password=AP_PASS) oled.hctext('SSID:%s' % AP_SSID, 11, 1) oled.hctext('PASS:%s' % AP_PASS.decode('utf-8'), 20, 1) oled.show() port = 8000 + getrandbits(10) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', port)) s.listen(5) oled.hctext('Web Page @', 32, 1) oled.hctext('%s:%d' % (ap_if.ifconfig()[0], port), 41, 1) oled.show() try: while True: conn, addr = s.accept() print('Connection from %s' % str(addr)) request = conn.recv(1024) request = request.decode('utf-8') if 'GET / ' in request: conn.send( 'HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close\n\n' ) conn.sendall( webhtml % b2a_base64(ujson.dumps(outpacket)).decode('utf-8')[:-1]) elif 'UPDATE /?c=' in request: lines = request.split('\r\n') for line in lines: if 'UPDATE /?c=' in line: b64 = line.split('UPDATE /?c=')[1].split(' ')[0] packet = ujson.loads(a2b_base64(b64)) if 'c01n_name' in packet: config.update({'name': packet['c01n_name']}) if 'c01n_ssid' in packet and 'c01n_pass' in packet: config.update({ 'wifi': [packet['c01n_ssid'], packet['c01n_pass']] }) if 'c01n_repo' in packet: config.update({'apprepourl': packet['c01n_repo']}) #config.update({'virginboot':0}) writeConfig(config) oled.fill(0) oled.hctext('REBOOTING', 30, 1) oled.show() machine.reset() break conn.send( 'HTTP/1.1 200 OK\nContent-Type: application/json\nConnection: close\n\n' ) conn.sendall('{"Status":"OK"}') conn.close() except KeyboardInterrupt: pass finally: s.close() gc.collect() machine.reset()
def app_start(): connectWifi() oled.fill(0) oled.fill_rect(0, 0, 128, 10, 1) oled.hctext('App Store', 1, 0) if not wlan.isconnected(): oled.hctext('No WiFi :(', 24, 1) oled.hctext('Connection', 32, 1) oled.hctext('[B] to Quit', 56, 1) oled.show() while (btn.B.value()): sleep_ms(100) return 1 REPO_URL = readConfig()['apprepourl'] oled.hctext('Connecting to', 24, 1) oled.hctext('Repository', 34, 1) oled.show() listing = (urequests.get("%slisting.json" % REPO_URL)).json() s0id = 0 while True: s0id = selectVList('Apps Available', list(map(lambda a: a['name'], listing['apps'])), s0id, 1) if s0id == -1: return 0 if viewAppDetail(listing['apps'][s0id]): installApp(REPO_URL, listing['apps'][s0id]) return 0
def app_start(): connectWifi() oled.fill(0) oled.fill_rect(0, 0, 128, 10, 1) oled.hctext('SGP Weather', 1, 0) if not wlan.isconnected(): oled.hctext('No WiFi :(', 24, 1) oled.hctext('Connection', 32, 1) oled.hctext('[B] to Quit', 56, 1) oled.show() while (btn.B.value()): sleep_ms(100) return 1 oled.hctext('Connecting to', 24, 1) oled.hctext('data.gov.sg', 32, 1) oled.show() r1 = urequests.get( 'https://api.data.gov.sg/v1/environment/24-hour-weather-forecast') r2 = urequests.get( 'https://api.data.gov.sg/v1/environment/2-hour-weather-forecast') d1 = r1.json() d2 = r2.json() forecast = d1['items'][0]['general']['forecast'] rhumid = d1['items'][0]['general']['relative_humidity'] temp = d1['items'][0]['general']['temperature'] wind = d1['items'][0]['general']['wind'] oled.fill(0) oled.fill_rect(0, 0, 128, 10, 1) oled.hctext('24 Hour Forecast', 1, 0) oled.text(forecast, 0, 17, 1) oled.text('RH ' + str(rhumid['low']) + '-' + str(rhumid['high']) + ' %', 0, 32, 1) oled.text('Temp ' + str(temp['low']) + '-' + str(temp['high']) + ' C', 0, 40, 1) oled.text('Wind Dir ' + str(wind['direction']), 0, 48, 1) oled.text( ' @ ' + str(wind['speed']['low']) + '-' + str(wind['speed']['high']) + ' km/h', 0, 56, 1) oled.show() while btn.A.value() and btn.B.value(): sleep_ms(100) sleep_ms(200) forecasts = [] for area in d2['items'][0]['forecasts']: forecasts.extend([area['area'][:16], area['forecast'][:16], '']) sid = 0 while True: sid = selectVList('2 Hour Nowcast', forecasts, sid, 1) if sid == -1: return 0
def startMultiPlayer(isClient): import network import usocket as socket global gameSocket, gameSocket, clientAddr import uos prefixlen = len("CoinGame-Checkers") if not isClient: gameName = ubinascii.hexlify(uos.urandom(4)).upper().decode() wlanAP.active(True) # activate the interface wlanAP.config(essid='CoinGame-Checkers-' + gameName) # set the ESSID of the access point #ap.setNoDelay(1); sleep_ms(1000) gameSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) gameSocket.bind(('', 52354)) oled.fill(0) oled.hctext("Waiting", 32-12, 1) oled.hctext("Checkers", 32-4, 1) oled.hctext("Game: " + gameName, 32+4, 1) oled.show() data, clientAddr = gameSocket.recvfrom(1) else: #wlan = network.WLAN(network.STA_IF) # create station interface wlan.active(True) dotcnt = 0 validGames = [] while len(validGames) == 0: oled.fill(0) oled.hctext("Scanning" + "."*(dotcnt+1), 32-4, 1) oled.show() dotcnt = (dotcnt+1)%3 wlan.active(True) scanResults = wlan.scan() for ap in scanResults: ssid, bssid, channel, RSSI, authmode, hidden = ap if ssid.startswith("CoinGame-Checkers-"): validGames.append(ssid[18:]) ap_name = validGames[selectVList("Select Game", validGames, 0)].decode() wlan.active(True) wlan.connect('CoinGame-Checkers-' + ap_name, '') # connect to an AP #wlan.setNoDelay(1); dotcnt = 0 while not wlan.isconnected(): oled.fill(0) oled.hctext("Connecting" + "."*(dotcnt+1), 22, 1) #oled.hctext("Channel: " + str(wlan.config("channel")), 32, 1) oled.hctext("Game: " + ap_name, 42, 1) oled.show() sleep_ms(500) dotcnt = (dotcnt+1)%3 oled.fill(0) oled.hctext("WIFI: OK", 32, 1) oled.hctext("Game: ...", 42, 1) oled.show() gameSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sockaddr = socket.getaddrinfo('192.168.4.1', 52354)[0][-1] gameSocket.connect(sockaddr) gameSocket.send(numToBin(0)) #TODO: exchange names between devices oled.fill(0) oled.hctext("CONNECTED", 32, 1) oled.show() startSession(isClient)
def drawWifiScreen(wifis, sidx): oled.fill(0) if len(wifis) < 1: #for a in range(360): oled.hctext('o_O', 10, 1) oled.hctext('No WiFi Found', 25, 1) oled.hctext('[A] to Re-Scan', 56, 1) np[0] = (10, 10, 10) else: ssid, bssid, channel, rssi, authmode, hidden = wifis[sidx] oled.hctext(hexlify(bssid), 0, 1) oled.hline(0, 8, 128, 1) oled.hctext(ssid, 12, 1) oled.hctext('Ch %d RSSI %d' % (channel, rssi), 25, 1) oled.hctext(authmodes[authmode], 35, 1) if hidden: oled.hctext('Hidden', 45, 1) oled.hctext('< %d/%d >' % (sidx + 1, len(wifis)), 56, 1) np[0] = hsv_to_rgb(sidx / len(wifis), 1, 12) oled.show() np.write()