Esempio n. 1
0
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
Esempio n. 2
0
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]
Esempio n. 3
0
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)
Esempio n. 4
0
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
Esempio n. 5
0
def drawBoard():
    oled.fill(0)
    for i in range(boardHeight):
        for j in range(boardWidth):
            oled.fill_rect(j * blkSize, i * blkSize, blkSize, blkSize,
                           board1[i][j])
    oled.show()
Esempio n. 6
0
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
Esempio n. 7
0
def msgBox(header, lines):
	oled.fill(0)
	oled.fill_rect(0,0,128,10,1)
	oled.text(header,0,1,0)
	if type(lines) != list: lines = [lines[i:i+16] for i in range(0, len(lines), 16)]
	for y, line in enumerate(lines):
		oled.text(line,0,11+y*8,1)
	oled.show()
	while btn.B.value():
		sleep_ms(100)
	sleep_ms(300)
Esempio n. 8
0
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
Esempio n. 9
0
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
Esempio n. 10
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
Esempio n. 11
0
def inputDrawing(width=8, height=8, _S=8, buffer=-1):
	import framebuf
	if buffer == -1: buffer = bytearray(width*height//8)
	fbuf = framebuf.FrameBuffer(buffer, width, height, framebuf.MONO_HLSB)
	cx,cy=0,0
	rdw=1
	while btn.B.value():
		if not btn.U.value():
			while not btn.U.value(): sleep_ms(10)
			cy=(cy-1)%height
			rdw=1
		if not btn.D.value():
			while not btn.D.value(): sleep_ms(10)
			cy=(cy+1)%height
			rdw=1
		if not btn.L.value():
			while not btn.L.value(): sleep_ms(10)
			cx=(cx-1)%width
			rdw=1
		if not btn.R.value():
			while not btn.R.value(): sleep_ms(10)
			cx=(cx+1)%width
			rdw=1
		if not btn.A.value():
			while not btn.A.value(): sleep_ms(10)
			fbuf.pixel(cx,cy,not fbuf.pixel(cx,cy))
			rdw=1
		if rdw:
			rdw=0
			oled.fill(0)
			for x in range(width):
				for y in range(width):
					if fbuf.pixel(x,y): oled.fill_rect(x*_S,y*_S,_S,_S,1)
			oled.rect(cx*_S,cy*_S,_S,_S,not fbuf.pixel(cx,cy))
			oled.text('Draw',80,0,1)
			oled.text('Cursor:',68,16,1)
			curstat='(%s,%s)'%(cx,cy)
			oled.text(curstat,96-len(curstat)*4,26,1)
			oled.text("[B] to",72,47,1)
			oled.text("Finish",72,56,1)
			oled.show()
		sleep_ms(20)
	return (width,height,buffer)
Esempio n. 12
0
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()
Esempio n. 13
0
File: name.py Progetto: lweikit/apps
def app_start():
    msgBox('Name Badge', [
        '', '[B] will launch', 'a keyboard to', 'enter name', '',
        '[\n] to Submit'
    ])
    name = ' %s ' % inputAlphanumeric()
    _W = len(name) * 8
    _H = 8
    fbuf = fb.FrameBuffer(bytearray(_W * _H // 8), _W, _H, fb.MONO_HLSB)
    fbuf.text(name, 0, 0, 1)
    ix = 0
    while btn.B.value():
        oled.fill(0)
        for x in range(16):
            for y in range(8):
                if fbuf.pixel((x + ix) % _W, y):
                    oled.fill_rect(x * 8, y * 8, 8, 8, 1)
        oled.show()
        ix += 1
        sleep_ms(50)
Esempio n. 14
0
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
Esempio n. 15
0
def app_start():
	px = 64
	py = 32
	oled.fill(0)
	oled.show()
	fbuf = fb.FrameBuffer(bytearray(1024),128,64,fb.MONO_HLSB)
	sleep_ms(200)
	while True:
		oled.blit(fbuf,0,0)
		if(btn.A.value() == 0):
			fbuf.fill_rect(px,py,3,3,1)
		else:
			oled.fill_rect(px,py,3,3,int(ticks_ms()/100)%2)
		if(btn.B.value() == 0): 
			#urequests.get('http://ragulbalaji.com:3073/c01nsketch?g=%s'%hexlify(oled.buffer))
			return 0
		if(btn.U.value() == 0): py=(py-1)%64
		if(btn.D.value() == 0): py=(py+1)%64
		if(btn.L.value() == 0): px=(px-1)%128
		if(btn.R.value() == 0): px=(px+1)%128
		oled.show()
Esempio n. 16
0
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)
Esempio n. 17
0
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
Esempio n. 18
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
Esempio n. 19
0
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)
Esempio n. 20
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
Esempio n. 21
0
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()
Esempio n. 22
0
def startSession(isClient):
	import uselect
	poller = uselect.poll()
	poller.register(gameSocket, uselect.POLLIN)
	heldDown = False
	turn = 2
	if isClient:
		board = [[0 for x in range(8)] for y in range(8)]
		selx = 0
		sely = 0
	else:
		board = initBoard
		selx = 0
		sely = 7
	found = False
	pieceSelected = (-1, -1)


	if not isClient:
		for i in range(10):
			gameSocket.sendto(numToBin(1) + boardToBinary(board), clientAddr)



	while True:
		while poller.poll(1):
			data, _ = gameSocket.recvfrom(200)
			cmd = binToNum(data[:1])
			data = data[1:]

			if cmd == 1:
				board = binaryToBoard(data)
			elif cmd == 2:
				turn = binToNum(data)

		'''
		for i in range(8):
			for j in range(8):
				if board[i][j] == turn:
					selx = i
					sely = j
					found = True
					break
			if found:
				break
		'''

			#board = binaryToBoard(boardData[1:])

		#find the first one if nothing is selected

		if isClient:
			boardDraw = flipBoard(board)
		else:
			boardDraw = board

		oled.fill(0)
		if isCurrentTurn(turn, isClient):
			if isClient:
				drawBoard(boardDraw, 7-selx, 7-sely)
			else:
				drawBoard(boardDraw, selx, sely)
			oled.text("GO", 102, 52, 1)
		else:
			drawBoard(boardDraw, -1, -1)
		oled.show()

		if isClient:
			if not btn.U.value():
				sely = min(7, sely + 1)
			if not btn.D.value():
				sely = max(0, sely - 1)
			if not btn.L.value():
				selx = min(7, selx + 1)
			if not btn.R.value():
				selx = max(0, selx - 1)
		else:
			if not btn.U.value():
				sely = max(0, sely - 1)
			if not btn.D.value():
				sely = min(7, sely + 1)
			if not btn.L.value():
				selx = max(0, selx - 1)
			if not btn.R.value():
				selx = min(7, selx + 1)


		if (not btn.A.value()) and isCurrentTurn(turn, isClient): #turn locked
            #selecting a piece
			if isFriendly(turn, board[sely][selx]):
				for i in range(8):
					for j in range(8):
						if board[i][j] == 5:
							board[i][j] = 0
				moves = getValidMoves(board, selx, sely)
				if len(moves) == 0:
					continue
				for move in moves:
					x = move[0]
					y = move[1]
					board[y][x] = 5
				pieceSelected = (selx, sely)

            #selecting a movement
			if board[sely][selx] == 5:
				for i in range(8):
					for j in range(8):
						if board[i][j] == 5:
							board[i][j] = 0
				x, y = pieceSelected
				board[sely][selx] = board[y][x]
				board[y][x] = 0

				if canPromote(turn, selx, sely):
					board[sely][selx] += 2

				enemyCaptured = False
				for move in moves:
					if len(move) > 2 and move[0] == selx and move[1] == sely:
						enemyx = move[2]
						enemyy = move[3]
						board[enemyy][enemyx] = 0
						enemyCaptured = True
						break

				if enemyCaptured:
					canCaptureMore = False
					moves = getValidMoves(board, selx, sely)
					for move in moves:
						if len(move) > 2:
							canCaptureMore = True

					if canCaptureMore:
						for move in moves:
							if len(move) > 2:
								x = move[0]
								y = move[1]
								board[y][x] = 5
						pieceSelected = (selx, sely)
					else:
						turn = 3 - turn
						for i in range(20):
							if isClient:
								gameSocket.send(numToBin(1) + boardToBinary(board))
								gameSocket.send(numToBin(2) + numToBin(turn))
							else:
								gameSocket.sendto(numToBin(1) + boardToBinary(board), clientAddr)
								gameSocket.sendto(numToBin(2) + numToBin(turn), clientAddr)
				else:
					turn = 3 - turn
					for i in range(20):
						if isClient:
							gameSocket.send(numToBin(1) + boardToBinary(board))
							gameSocket.send(numToBin(2) + numToBin(turn))
						else:
							gameSocket.sendto(numToBin(1) + boardToBinary(board), clientAddr)
							gameSocket.sendto(numToBin(2) + numToBin(turn), clientAddr)

		if not btn.B.value():
			for i in range(8):
				for j in range(8):
					if board[i][j] == 5:
						board[i][j] = 0
		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
Esempio n. 23
0
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)
Esempio n. 24
0
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()
Esempio n. 25
0
def drawObjects():
    oled.fill(0)
    drawPaddle(playerPaddle)
    drawPaddle(enemyPaddle)
    drawBall(ball)
    oled.show()
Esempio n. 26
0
def startSinglePlayer():
	selx = 0
	sely = 7
	turn = 2 #
	heldDown = False
	board = initBoard
	found = False
	pieceSelected = (-1, -1)
	while True:

		#find the first one if nothing is selected
		if selx == -1 and sely == -1:
			for i in range(8):
				for j in range(8):
					if board[i][j] == turn:
						selx = i
						sely = j
						found = True
						break
				if found:
					break

		oled.fill(0)
		drawBoard(initBoard, selx, sely)
		oled.show()

		if not btn.U.value():
			sely = max(0, sely - 1)
		if not btn.D.value():
			sely = min(7, sely + 1)
		if not btn.L.value():
			selx = max(0, selx - 1)
		if not btn.R.value():
			selx = min(7, selx + 1)


		if not btn.A.value():
            #selecting a piece
			if isFriendly(turn, board[sely][selx]):
				for i in range(8):
					for j in range(8):
						if board[i][j] == 5:
							board[i][j] = 0
				moves = getValidMoves(board, selx, sely)
				if len(moves) == 0:
					continue
				for move in moves:
					x = move[0]
					y = move[1]
					board[y][x] = 5
				pieceSelected = (selx, sely)

            #selecting a movement
			if board[sely][selx] == 5:
				for i in range(8):
					for j in range(8):
						if board[i][j] == 5:
							board[i][j] = 0
				x, y = pieceSelected
				board[sely][selx] = board[y][x]
				board[y][x] = 0

				if canPromote(turn, selx, sely):
					board[sely][selx] += 2

				enemyCaptured = False
				for move in moves:
					if len(move) > 2 and move[0] == selx and move[1] == sely:
						enemyx = move[2]
						enemyy = move[3]
						board[enemyy][enemyx] = 0
						enemyCaptured = True
						break

				if enemyCaptured:
					canCaptureMore = False
					moves = getValidMoves(board, selx, sely)
					for move in moves:
						if len(move) > 2:
							canCaptureMore = True

					if canCaptureMore:
						for move in moves:
							if len(move) > 2:
								x = move[0]
								y = move[1]
								board[y][x] = 5
						pieceSelected = (selx, sely)
					else:
						turn = 3 - turn
				else:
					turn = 3 - turn

		if not btn.B.value():
			for i in range(8):
				for j in range(8):
					if board[i][j] == 5:
						board[i][j] = 0
		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
Esempio n. 27
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)
Esempio n. 28
0
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)

badgelogo = loadPBM('/badge.pbm')
hue = 0
particles = []