Example #1
0
def renameFiles(i):
    oled.display0('renaming files')
    image_location = i

    print "image_location " + image_location
    # global resize_location
    os.chdir(image_location)  # go to where the images are
    lst = os.listdir(".")
    lst.sort()
    print lst
    a = 1  # the counter for images
    for i in lst:  # for each file in the dir

        if i[-4:] == ".JPG":
            picCount = "%03d" % a  # make the counter 3 decimal places and integrate
            newName = picCount + ".jpg"
            a += 1
            newName = newName.replace(":", ".")
            newName = newName.replace(" ", "_")

            os.rename(i, newName)
            print "Renamed %r to %r" % (i, newName)

            # oldLoc = image_location + "/" + newName
            # newLoc = rename_location + "/" + newName

            oled.display1(newName)
    oled.clear()
Example #2
0
async def shutdown(loop):
    """Shutdowns the program as gracefully as possible."""
    # Make sure we always disconnect from the mqtt broker
    await client.disconnect()

    # And clear the displays
    oled.clear()
    peripherals.led_key.segments[0] = ' ' * 8
    for i in range(8):
        peripherals.led_key.leds[i] = False

    # Make sure we're completely done with async stuff
    # See https://www.roguelynn.com/words/asyncio-exception-handling/
    # Gather tasks
    tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]

    # Cancel them
    for task in tasks:
        task.cancel()
    # Wait for them to finish up
    await asyncio.gather(*tasks, return_exceptions=True)

    # Then shutdown the event loop
    loop.stop()

    exit()
Example #3
0
File: gui.py Project: uniite/imd
def imd_playback ():
	global mode
	mode = "play"
	song = menu.imd_db.record(cursong)
	oled.clear()
	oled.flush()
	n = isnum
	bc = border_color
	y = offset
	for i in range(0, 12):
		oled.fill(0, y + i, 129, y + i+1, [bc.r - (n(bc.r) * i), bc.g - (n(bc.g) * i), bc.b - (n(bc.b) * i)])
		oled.flush()
	oled.textbox(x = 65, y = 4, text = "Now Playing", color = black, align = 2)
	oled.flush()
	tcolor = blue
	oled.textbox(x = 65, y = 35, text = song.title, color = tcolor, mode = 1, align = 2)
	oled.flush()
	oled.textbox(x = 65, y = 50, text = song.artist, color = tcolor, mode = 1, align = 2)
	oled.flush()
	oled.textbox(x = 65, y = 65, text = song.album, color = tcolor, mode = 1, align = 2)
	oled.flush()
	oled.redraw()
	oled.flush()
	timer().start()
	return song
Example #4
0
def makeGif(a, b):
    oled.display0("making Gif")
    imageLocation = a
    shot_date = b
    imagesToUse = imageLocation + "/" + "%03d" + ".jpg"
    saveLocation = imageLocation[:-8]  # get out of the resize folder
    gifName = saveLocation + "/" + shot_date + '.gif'
    subprocess.call([
        "ffmpeg", "-framerate", "10", "-i", imagesToUse, "-vf",
        "scale=iw/2:-1", gifName
    ])
    oled.clear()
Example #5
0
def makeVid(a, b):
    oled.display0("making Vid")
    imageLocation = a
    shot_date = b
    saveLocation = imageLocation[:-8]  # get out of the ogs folder
    print saveLocation
    movName = saveLocation + "/" + shot_date + '.mp4'
    print "movName = %r" % movName
    imagesToUse = imageLocation + "/" + "%03d" + ".jpg"
    subprocess.call(["ffmpeg", "-f", "image2", "-r", "30", "-i", imagesToUse, \
    "-vcodec", "h264", "-y", movName])
    oled.clear()
    return (movName)
Example #6
0
File: gui.py Project: uniite/imd
def calibrate ():
	i = 1
	while i > -1:
		oled.clear()
		oled.flush()
		oled.textbox(x = 65, y = 50, text = "Calibrating in %s" % i, align = 2)
		oled.flush()
		oled.redraw()
		oled.flush()
		sleep(1)
		i -= 1
	tty.write("c")
	sleep(.4)
Example #7
0
def monitor(state, value1, value2):
    if (state == "motor"):
        import machine
        a1 = machine.Pin(4, machine.Pin.OUT, value=0)
        a2 = machine.Pin(15, machine.Pin.OUT, value=0)
        b1 = machine.Pin(14, machine.Pin.OUT, value=0)
        b2 = machine.Pin(12, machine.Pin.OUT, value=0)
        if (value1 == "A"):
            if (value2 == "1"):
                a1.value(0)
                a2.value(1)
            elif (value2 == "2"):
                a1.value(1)
                a2.value(0)
            else:
                a1.value(0)
                a2.value(0)
        elif (value1 == "B"):
            if (value2 == "1"):
                b1.value(0)
                b2.value(1)
            elif (value2 == "2"):
                b1.value(1)
                b2.value(0)
            else:
                b1.value(0)
                b2.value(0)
        del machine, a1, a2, b1, b2
    elif (state == "oled"):
        import oled
        if value1 != '' or value2 != '':
            oled.clear()
            oled.header(value1)
            oled.body(value2)
            oled.show()
            del oled
        else:
            oled.clear()
            oled.finished('OLED Monitor')
            del oled
    elif (state == "beep"):
        import beeper
        beeper.speaker(int(value1), int(value2))
        del beeper
    elif (state == "sensor"):
        import machine, time
        adc = machine.ADC(0)
        while (True):
            send("monitor:sensor:" + str(adc.read()))
            time.sleep_ms(500)
        del machine, time, adc
Example #8
0
File: gui.py Project: uniite/imd
def menu_draw ():
	# Clear the frame buffer first
	oled.clear()
	oled.flush()
	# Draw blue bars at top and bottom of screen
	n = isnum
	bc = border_color
	y = offset
	for i in range(0, 12):
		oled.fill(0, y + i, 129, y + i+1, [bc.r - (n(bc.r) * i), bc.g - (n(bc.g) * i), bc.b - (n(bc.b) * i)])
		oled.flush()
	y = 116 + offset
	for i in range(0, 12):
		oled.fill(0, y + i, 129, y + i+1, [bc.r - (n(bc.r) * i), bc.g - (n(bc.g) * i), bc.b - (n(bc.b) * i)])
		oled.flush()
	# Show title of menu on the top blue bar that was just drawn
	oled.textbox(x=65, y=4, text=curmenu.name, color=[0, 0, 0], align=2)
	oled.flush()
	# Show current item index and total on bottom blue bar
	oled.textbox(x=65, y=119, text="%s/%s" % (curmenu.index + 1, curmenu.len), color=[0, 0, 0], align=2)
	oled.flush()
	# Redraw the counter (bottom blue bar)
	oled.redraw(116 + offset)
	for y in range(menu_start, curmenu.end, row_height):
		if y == curmenu.cursor:
			# Fill the row of the center menu item because for the selection cursor, iPod-ish style :)
			h = highlight_color
			for i in range(0, 6):
				oled.fill(0, y + i, 129, y + i+1, [h.r - (n(h.r) * i), h.g - (n(h.g) * i), h.b - (n(h.b) * i)])
				oled.flush()
			i2 = 0
			for i in range(6, 11):
				oled.fill(0, y + i, 129, y + i+1, [h.r - (10 * n(h.r)) + i2, h.g - (10 * n(h.r)) + i2, h.b - (10 * n(h.r)) + i2])
				oled.flush()
				i2 += 1
			# Also invert selected item's text color
			oled.textbox (x = 1, y = y + 2, text = curmenu.items[curmenu.top + ((y - menu_start) / row_height)][0], color=texth_color, mode=2)
		else:
			# Plain menu items (but they might get selected later!)
			oled.textbox (x = 1, y = y + 2, text = curmenu.items[curmenu.top + ((y - menu_start) / row_height)][0], color=text_color, mode=2)
		oled.flush()
Example #9
0
def resizeImages(a, b):  # going to resize images from a, save to b
    oled.display0("resizing images")
    print "resizeImages()"
    image_location = a
    resize_location = b
    os.chdir(image_location)
    lst = os.listdir(".")
    lst.sort()
    lstLen = len(lst)
    print lst

    for i in lst:
        oled.display1(str(i))
        # print "gonna resize it"
        img = Image.open(i)
        img = img.crop(
            (603, 600, 603 + 4058, 600 + 2706))  # this is the new line!
        imgResized = img.resize((1080, 720))
        resizedName = resize_location + "/" + i
        print "resizing " + resizedName[-7:] + " / " + str(lstLen)
        imgResized.save(resizedName, "JPEG", optimize=True)
    oled.clear()
Example #10
0
def takePictures(n, d):
    shotDelay = d
    print "finna take %r pics" % n
    oled.display0("taking picture")
    totalWait = 0
    adjustedDelay = shotDelay + 0.0
    print "ADJUSTED DELAY = " + str(adjustedDelay)
    for i in range(0, n):
        shotStart = datetime.now()
        oled.display1("    " + str(i + 1) + "/" + str(n))
        print "photo " + str(i)

        # sleep(shotDelay)
        # initialize variable
        if i > 0:
            t = datetime.now()  # this does the timing instead of sleep
            while (t -
                   shotEnd).seconds < adjustedDelay:  # previously shotDelay
                # print (t - shotEnd)
                t = datetime.now()

            interval = shotEnd - lastShotStart
            intinterval = interval.seconds + round(
                float(interval.microseconds) / 1000000, 3)
            print "interval = " + str(intinterval)
            totalWait += intinterval
            averageInterval = totalWait / i
            print "averageInterval = " + str(averageInterval)
            averageDifference = averageInterval - shotDelay
            adjustedDelay = shotDelay - averageDifference
            print "averageDifference = " + str(averageDifference)
            print "ADJUSTED DELAY = " + str(adjustedDelay)

        shot_time = takePicture()
        print "shot_time = " + str(shot_time)
        lastShotStart = shotStart
        shotEnd = datetime.now()

    oled.clear()
Example #11
0
def init(state, value1, value2):
    if (state == "10"):
        send('step1:ok')
    elif (state == "20"):
        import network, oled
        sta_if = network.WLAN(network.STA_IF)
        sta_if.active(1)
        sta_if.connect(value1, value2)
        while not sta_if.isconnected():
            pass
        send('step2:ok')
        send('step2:res:' + str(sta_if.ifconfig()[0]))
        oled.clear()
        oled.text('IP Address ..', 0, 32)
        oled.text(str(sta_if.ifconfig()[0]), 0, 48)
        del network, sta_if, oled
    elif (state == "30"):
        send('step3:ok')
        with open('./webrepl_cfg.py', "w") as f:
            f.write("PASS = %r\n" % value1)

        # __import__('machine').reset()
    elif (state == "40"):
        send('step4:ok')
Example #12
0
def main():
    sensor = machine.Pin(4, machine.Pin.IN, machine.Pin.PULL_UP)
    while True:
        value = sensor.value()
        oled.text(str(value), 0, 40)
        oled.clear()
        if value:
            urequests.put(
                'https://api.netpie.io/topic/Testeiei/Test?retain&auth=wd37U6RPWfA0Ku3:en3QR4Emkz8EsWlMNXEAX3Xgc',
                data=str(value))
            time.sleep_ms(200)
            oled.clear()
        else:
            urequests.put(
                'https://api.netpie.io/topic/Testeiei/Test?retain&auth=wd37U6RPWfA0Ku3:en3QR4Emkz8EsWlMNXEAX3Xgc',
                data=str(value))
            time.sleep_ms(200)
            oled.clear()
Example #13
0
import dht12,machine,oled,time,gc,urequests
from machine import I2C,Pin
# from umqtt.simple import MQTTClient

i2c = I2C(scl=Pin(13),sda=Pin(5))
d = dht12.DHT12(i2c)
# thingspeakChannelId = "224710"  # <--- replace with your Thingspeak Channel ID
# thingspeakChannelWriteapi = "QEAXQACRL1LZHN46" # <--- replace with your Thingspeak Write API Key
#
# myMqttClient = "my-mqtt-client"  # can be anything unique
# thingspeakIoUrl = "mqtt.thingspeak.com"
# c = MQTTClient(myMqttClient, thingspeakIoUrl, 1883)  # uses unsecure TCP connection
# c.connect()

while True:
    d.measure()
    oled.clear()
    oled.text(str(gc.mem_free()),0,8)
    oled.text('Temp '+str(d.temperature()),0,24)
    oled.text('Humid '+str(d.humidity()),0,40)
    urequests.post('http://api.thingspeak.com/update?api_key=QEAXQACRL1LZHN46&field1='+str(d.temperature()))
    gc.collect()
    time.sleep(1)
#     credentials = "channels/{:s}/publish/{:s}".format(thingspeakChannelId, thingspeakChannelWriteapi)
#     payload = "field1={:.1f}&field2={:d}\n".format(d.temperature(), gc.mem_free())
#     c.publish(credentials, payload)
#
#     time.sleep(5)
#
# c.disconnect()
Example #14
0
def downloadImages():
    oled.display0("downloading images")
    print "downloading"
    gp(downloadCommand)
    gp(clearCommand)
    oled.clear()
Example #15
0
def targetTime(
    a, b
):  # a will be time in advance of the event to start shooting. b 1 for sunrise, 2 for sunset
    ''' this function gets the time of sunrise/set, subtracts the lead up time to 
    calculate the target time, then waits until that time.
    a is the time ahead of sunrise/set
    set b to 1 for sunrise, 2 for sunset
    '''
    oled.clear()
    oled.display0("GETTING START TIME")
    if b == 1:
        oled.display1("getting SUNRISE")
        print "calculating the time %r minutes before SUNRISE" % a
        zeroTime = getSunriseTime(
        )  # zero time is the time of the event, either sunset or rise
        oled.display1("sunrise:" + zeroTime)
        msgL2 = "sunrise was at " + str(zeroTime)
    elif b == 2:
        oled.display1("getting SUNSET")
        print "calculating the time %r minutes before SUNSET" % a
        zeroTime = getSunsetTime()
        oled.display1("sunset:" + zeroTime)
        msgL2 = "sunset was at " + str(zeroTime)
    elif b == 3:
        oled.display1("going in 1")
        print "waiting for next minute"
        d = datetime.datetime.now() + datetime.timedelta(minutes=1)
        d = d.strftime("%H:%M")
        zeroTime = str(d)
        a = 1  # set offset to 1
        msgL2 = "started manually"

    else:
        print """error, b needs to either be 1 for sunrise or 2 for sunset or 3 for test
        for all day enter 4"""
        oled.display0("ERROR")
    zeroHour = int(zeroTime[0:2])
    zeroMin = int(zeroTime[3:5])
    zeroDelta = datetime.timedelta(hours=zeroHour, minutes=zeroMin)

    now = datetime.datetime.now()
    nowDelta = datetime.timedelta(minutes=now.minute, hours=now.hour)
    # print "nowDelta", nowDelta
    # print "now" , now
    offset = datetime.timedelta(minutes=a)
    # print "offset", offset

    targetTime = zeroDelta - offset
    wait(targetTime)

    # following commmented out section was replaced by wait()
    #     print "targetTime", targetTime
    #     secondsTillTarget = (targetTime - nowDelta).seconds
    #     # print "secondsTillTarget", secondsTillTarget
    #     hoursTillTarget = secondsTillTarget // 3600
    #     targetHour = targetTime.seconds // 3600
    #     targetMin = ((targetTime.seconds)//60)%60

    #     oled.display0("starting at " + str(targetHour) + ":" + str(targetMin))

    #     print "waiting for the %rth hour" % targetHour
    #     while now.hour != targetHour:
    # #        print "waiting for the right hour"
    #         now = datetime.datetime.now()
    #         nowHour = now.hour
    #         nowMin = now.minute
    #         oled.display1("now it's " + str(nowHour) + ":" + str(nowMin))
    #         sleep(60)

    #     print "hour matched!"
    #     print "waiting for the %rth minute" % targetMin
    #     prevNow = now
    #     while now.minute != targetMin:
    #         now = datetime.datetime.now()
    #         nowHour = now.hour
    #         nowMin = now.minute

    #         if prevNow != now:
    #             oled.display1("now it's " + str(nowHour) + ":" + str(nowMin))
    #             if now.minute == targetMin:
    #                 oled.display1("bout to start")
    #         sleep(15)
    #         prevNow = now

    print "it is time"
    msgL1 = "started shooting at " + str(targetTime)
    return msgL1 + "\n" + msgL2