def show_temperature(delay):
    clear()
    temp = weather.temperature()
    write_string("%.2f" % temp + "c", kerning=False)
    show()
    time.sleep(delay)
    g.labels(host=host).set(temp)
def display():
    global roomTemp
    global systemTemp
    if ON_PI:
        write_string(str(systemTemp)[0:2] + "  " + str(roomTemp)[0:2],
                     kerning=False)
        show()
def update_display(cost, trend):
    ''' Function to update the display '''
    if (len(cost) > 1) and (len(cost) < 7):
        # Start with a clear buffer
        md.clear()

        # Right justify string
        char_offset = 6 - len(cost)
        md.write_string(cost, offset_x=(8 * char_offset), kerning=False)

        # Add trend - character set here: https://github.com/pimoroni/microdot-phat/blob/master/library/microdotphat/font.py
        if trend == 'UP':
            # Solid upwards triangle
            md.write_char(chr(9650), offset_x=0)
        elif trend == 'up':
            # Open upwards triangle
            md.write_char(chr(9651), offset_x=0)
        elif trend == 'down':
            # Open downwards triangle
            md.write_char(chr(9661), offset_x=0)
        elif trend == 'DOWN':
            # Solid downwards triangle
            md.write_char(chr(9660), offset_x=0)

        # Write the buffer to the display
        md.show()
Ejemplo n.º 4
0
def withPhat():
    # global prevLevel #can remove next
    while True:
        tijd = time.localtime()  #create a struct_time object
        if tijd[4] in interval_List:  #and check if the number of minutes is in the interval_List
            currTime = time.asctime()[
                11:16]  #if yes create an hour and minute string using .asctime
            currTime = currTime + ':00'  #add the zeros

            getNap()  #get and set current nap_list
            # walk through it searching match with currTime nap_list[i][1]
            # for i in nap_list: doesn't work in this case (because I need the index number?)
            for i in range(len(nap_list)):
                if nap_list[i][1] == currTime:
                    currLevel = int(nap_list[i][5])  #currLevel is an int
                    prevLevel = int(nap_list[i - 1][5])
                    diffLevel = currLevel - prevLevel
                    #print(str('%+d' % diffLevel)) #+d formatting for pos and neg numbers
                    print(currTime, str(currLevel), str('%+d' % diffLevel))
                    #prevLevel = currLevel
                    # Microdot Phat code follows
                    display = str(currLevel) + str('%+d' % diffLevel)
                    microdotphat.clear()
                    microdotphat.write_string(display, kerning=False)
                    microdotphat.show()
            time.sleep(65)  # waits a bit more than a minute
        time.sleep(5)
Ejemplo n.º 5
0
def feedme(feed):
    feed = feedparser.parse(feed.encode('utf-8'))
    for i in range(1):
        print(feed['entries'][i]['title'])
    write_string(feed['entries'][0]['title'], offset_x=1)
    scroll()
    show()
    time.sleep(0.05)
Ejemplo n.º 6
0
def write_to_display(message, brightness=1):
    if i2c_present:
        clear()
        set_brightness(brightness)
        write_string(message.rjust(6), kerning=False)
        show()
    else:
        print(message)
Ejemplo n.º 7
0
def DisplayTemp(NextDisplayTime, SensorVal, unitstr):
    TimeNow = time.time()
    if TimeNow > NextDisplayTime:
        NextDisplayTime = NextDisplayTime + DisplayInterval
        #print("Displaying Temperature on MicroDot Phat...")
        write_string("%.1f" % SensorVal + unitstr, kerning=False)
        show()

    return NextDisplayTime
Ejemplo n.º 8
0
def microdot():
    clear()
    write_string( "%.1f" % temperature + "C", kerning=False)
    show()
    time.sleep(5)
    clear()
    write_string( "%.0f" % humidity + "% RH", kerning=False)
    show()
    time.sleep(5)
Ejemplo n.º 9
0
def logic(state, backend_change):
    if backend_change:
        print("BACKEND CHANGE")
        return None

    config = state["config"]

    # Update values
    state["driftPause"] = max(state["driftPause"] - 1.0 / CALLS_PER_SECOND, 0)
    if state["driftPause"] == 0:
        state["value"] += state["drift"] / CALLS_PER_SECOND / 60
    state["rndMagnitude"] = state["rndMagnitude"] * config["rndMagnitudeDecay"]
    bnSpeed = config["brownNoiseSpeed"]
    bnValue = state["brownNoiseValue"] + random.uniform(-bnSpeed, bnSpeed)
    bnMax = config["brownNoiseMax"]
    state["brownNoiseValue"] = min(bnMax, max(-bnMax, bnValue))
    state[
        "sinePosition"] += 2 * math.pi / config["sineSpeed"] / CALLS_PER_SECOND
    if state["sinePosition"] > 2 * math.pi:
        state["sinePosition"] -= 2 * math.pi

    # Check whether we are adjusting the value
    adjustment = getAdjustment(config)
    if adjustment:
        state["value"] += adjustment
        state["driftPause"] = config["driftDelayAfterAdjust"]
        state["rndMagnitude"] = config["maxRndMagnitude"]
        state["drift"] = random.uniform(state["minDriftPerMinute"],
                                        state["maxDriftPerMinute"])
        if random.random() < config["probDriftDown"]:
            state["drift"] = -state["drift"]

    # Limits
    if state["value"] < config.get("safeRangeMin", 0) / 2:
        state["value"] = config.get("safeRangeMin", 0) / 2
    if state["value"] > config.get("safeRangeMax", 1000) * 2:
        state["value"] = config.get("safeRangeMax", 1000) * 2

    # Print value
    sine = math.sin(state["sinePosition"]) * config["sineMagnitude"]
    #rnd = random.uniform(-state["rndMagnitude"], state["rndMagnitude"])
    rnd = random.gauss(0, state["rndMagnitude"])
    value = state["value"] + state["brownNoiseValue"] + rnd + sine
    state["displayValue"] = value

    # display  actual  brown  sine  white-mag
    #print("{:.1f}\t{:.2f}\t{:+.2f}\t{:+.2f}\t{:.2f}".format(value, state["value"], state["brownNoiseValue"], sine, state["rndMagnitude"]))

    microdotphat.write_string("{:.2f}".format(value), kerning=False)
    microdotphat.show()

    return state
Ejemplo n.º 10
0
def mostra_data():
    tempo_data = 0
    while tempo_data < tempo_switch:
        clear()
        t = datetime.datetime.now()
        if t.second % 2 == 0:
            set_decimal(3, 1)
        else:
            set_decimal(3, 0)
        write_string(t.strftime('%a %d').upper(), kerning=False)
        show()
        time.sleep(0.05)
        tempo_data = tempo_data + 1
Ejemplo n.º 11
0
def show_time(duration=10):
    repeat_in = 0.05
    repeat_times = int(duration / repeat_in)

    for counter in range(0, repeat_times):
        microdotphat.clear()
        t = datetime.datetime.now()
        if t.second % 2 == 0:
            microdotphat.set_decimal(3, 1)
        else:
            microdotphat.set_decimal(3, 0)
        microdotphat.write_string(t.strftime(' %H%M'), kerning=False)
        microdotphat.show()
        time.sleep(repeat_in)
Ejemplo n.º 12
0
def main():

    key = 'cc8047a5-a693-417a-9721-c6213690acbb'
    ely = '324249'
    cambridge = '350731'
    #fcDataType = wxfcs or wxobs
    weatherType = {
    'NA': 'Huh?', '1': 'Sunny', '2': 'Cloudy', '3': 'Cloudy', '4': 'Huh?', '5': 'Misty', '6': 'Foggy', '7': 'Cloudy',
    '8':"O'cast", '9': 'L-Shwr', '10': 'L-Shwr', '11': 'Drizzl', '12': 'L-Rain', '13': 'H-Shwr', '14': 'H-Shwr',
    '15': 'H-Rain', '16': 'L-Sleet', '17': 'L-Sleet', '18': 'Sleet', '19': 'L-Hail', '20': 'L-Hail', '21': 'Hail!!',
    '22': 'L-Snow', '23': 'L-Snow', '24': 'L-Snow', '25': 'Snow', '26': 'Snow', '27': 'H-Snow', '28': 'Stormy',
    '29': 'Stormy', '30': 'Stormy'
	}
    
    while True:
        response = urllib2.urlopen('http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json/' + ely + '?res=3hourly&key=' + key)
        fcData = response.read()
        fcDataStr = fcData.decode('utf-8')
        fcDataDict = json.loads(fcDataStr)
        dataDate = (fcDataDict['SiteRep']['DV']['dataDate'])
        fcDate = (fcDataDict['SiteRep']['DV']['Location']['Period'][1]['value'])
        fcTime = (fcDataDict['SiteRep']['DV']['Location']['Period'][1]['Rep'][3]['$'])
        fcTemp = (fcDataDict['SiteRep']['DV']['Location']['Period'][1]['Rep'][3]['T'])
        fcPp = (fcDataDict['SiteRep']['DV']['Location']['Period'][1]['Rep'][3]['Pp'])
        fcWeather = (fcDataDict['SiteRep']['DV']['Location']['Period'][1]['Rep'][3]['W'])
        
        print '\n'
        print '**** New Data ****'
        print 'Forecast Date = ' + fcDate
        print 'Forecast time = ' + fcTime
        print 'Temp DegC = ' + fcTemp
        print 'Rain % = '+ fcPp
        print 'Weather type = ' + fcWeather
        weather = weatherType[fcWeather]
        print weather
        
        msg = 'Forecast: 9AM tomorrow'
        #write_string(msg, offset_x = 7, kerning = False)      
        write_string(weather, offset_y = 0, kerning = False)
        write_string('T: ' + fcTemp, offset_y = 7, kerning = False)
        write_string('R% ' + fcPp, offset_y = 14, kerning = False)
   
        for updateInterval in range(900):
            show()
            time.sleep(4)       
            for pixelRow in range(7):
                scroll_vertical()
                show()
                time.sleep(0.03)
        clear()
Ejemplo n.º 13
0
def microdot():
    clear()
    write_string("%.1f" % temperature + "C", kerning=False)
    show()
    time.sleep(5)
    # Uncomment to display pressure if needed
    #clear()
    #write_string( "%.0f" % pressure + "hPa", kerning=False)
    #show()
    #time.sleep(5)
    clear()
    write_string("%.0f" % humidity + "% RH", kerning=False)
    show()
    time.sleep(5)
Ejemplo n.º 14
0
def clock():
    while True:
        clockEndTime = time.time() + showClock
        while time.time() < clockEndTime:
            clear()
            t = datetime.datetime.now()
            if t.second % 2 == 0:
                set_decimal(2, 1)
                set_decimal(4, 1)
            else:
                set_decimal(2, 0)
                set_decimal(4, 0)
            write_string(t.strftime('%H%M%S'), kerning=False)
            show()
            time.sleep(0.05)
Ejemplo n.º 15
0
def mostra_saldo():
    tempo_saldo = 0
    saldo_euro = leggehttp()
    while tempo_saldo < tempo_switch:
        clear()
        char_euro()
        t = datetime.datetime.now()
        if t.second % 2 == 0:
            set_decimal(3, 1)
        else:
            set_decimal(3, 0)
        write_string(saldo_euro, offset_x=8, kerning=False)
        show()
        time.sleep(0.05)
        tempo_saldo = tempo_saldo + 1
Ejemplo n.º 16
0
def drawMatrix(matrix):

    gamma = 1.5
    MDP_HEIGHT = 6

    mdp.clear()

    for x in range(len(matrix)):
        buf_x = x + ((x / 5) * 3)

        for y in xrange(7):
            if matrix[x] > pow(gamma, y):
                mdp.set_pixel(buf_x, MDP_HEIGHT - y, 1)
            else:
                break

    mdp.show()
Ejemplo n.º 17
0
def main():
    """asdasd"""
    try:
        vala = int(sys.argv[1])
        valb = int(sys.argv[2])
        valc = int(sys.argv[3])
    except:
        print("Exception reading input")

    counter = 1.0
    soundon = is_sound_on()

    stride, Note_Freq = boop_beeps(vala, valb, valc)

    for val in range(vala, valb + stride, stride):
        sleep_time = min((counter / (abs(vala - valb) + 1.000))**1.8 *
                         (10.0 / (abs(vala - valb) + 1.0)), 3.000)
        if soundon:
            try:
                #            bus.read_byte(112)         #check to see if rainbow hat is connected
                rainbowhat.buzzer.midi_note(Note_Freq, .05)
            except:
                pass
        try:
            if valc > 29:
                mystring = "0" + (
                    str(val).rjust(len(str(val)))[0:2 + len(str(val)) - 5] +
                    str(val)[-3 + len(str(val).rjust(5)) - 5:]).rjust(5)
                rainbow_show_message('{:04.2f}'.format(val / 100))
                rainbow_led_pricechange(valc - 100)  #100 for curve currency
                microdotphat.set_decimal(1, 1)
            else:
                mystring = (
                    str(val).rjust(len(str(val)))[0:2 + len(str(val)) - 5] +
                    "," + str(val)[-3 + len(str(val).rjust(5)) - 5:]).rjust(6)
                rainbow_show_message(str(val))
                rainbow_led_pricechange(valc)
            microdotphat.write_string(mystring, offset_x=0, kerning=False)
            microdotphat.show()
        except:
            pass

        counter = counter + 1.0
        sleep(sleep_time)

    sleep(.4)  #needed so we can hear the last sound effect
Ejemplo n.º 18
0
def getNap():
    global nap_list
    try:
        with requests.Session() as s:
            download = s.get(csv_url)
            decoded_content = download.content.decode('utf-8')
            cr = csv.reader(decoded_content.splitlines(), delimiter=';')
            nap_list = list(cr)
            return nap_list
    except IndexError:
        microdotphat.clear()
        microdotphat.write_string('IndEr1', kerning=False)
        microdotphat.show()
        print('IndexError 1: getNAP')
    except ConnectionError:
        microdotphat.clear()
        microdotphat.write_string('ConErr', kerning=False)
        microdotphat.show()
        print('ConnectionError: getNAP')
Ejemplo n.º 19
0
    def render_string(s,
                      scroll_x=8,
                      scroll_y=0,
                      scroll_sleep=1,
                      kerning_flag=False):
        # init view
        clear()

        # render string
        write_string(s, kerning=kerning_flag)
        show()
        time.sleep(scroll_sleep)

        # render to end
        for i in range(len(s)):
            # scroll -> render
            scroll(scroll_x, scroll_y)
            show()
            time.sleep(scroll_sleep)
Ejemplo n.º 20
0
def print_string_fade(text):
    start = time.time()
    speed = 3
    shown = True

    b = 0
    while shown:
        b = (math.sin((time.time() - start) * speed) + 1) / 2
        microdotphat.set_brightness(b)

        if b < 0.002 and shown:
            microdotphat.clear()
            microdotphat.write_string(text, kerning=False)

            microdotphat.show()
            shown = False

        if b > 0.998:
            shown = True

        time.sleep(0.01)
Ejemplo n.º 21
0
def mostra_orologio():
    #verifico se c'e' connessione ad Internet
    connesso_internet = 0
    connesso_internet = connessione()

    tempo_orologio = 0
    while tempo_orologio < tempo_switch:
        clear()
        t = datetime.datetime.now()
        if t.second % 2 == 0:
            set_decimal(3, 1)
        else:
            set_decimal(3, 0)
        # se manca la connessione ad internet, durante la visualizzazione dell'ora viene anteposto un asterisco
        if (connesso_internet == 0):
            write_string(t.strftime(' %H%M'), kerning=False)
        else:
            write_string(t.strftime('*%H%M'), kerning=False)

        show()
        time.sleep(0.05)
        tempo_orologio = tempo_orologio + 1
async def initLogger():
    print("Start logger...")

    await asyncio.sleep(1) 
    
    while True:    
        if len(cache) == 0:
            await asyncio.sleep(2) 
            
        else:
            try:
                for key in cache:
                    print(cache[key])
                    
                    # Write to PHAT
                    clear()
                    write_string(cache[key], kerning=False)
                    show()
                    await asyncio.sleep(2) 
                
            except Exception:
               pass
Ejemplo n.º 23
0
def job():
    with urllib.request.urlopen(
            "https://api.nasa.gov/insight_weather/?api_key=YOUR-API-KEY-HERE&feedtype=json&ver=1.0"
    ) as url:
        data = json.loads(url.read())
        days = list(data.keys())
        res = []
        for el in days:
            try:
                res.append(int(el))
            except ValueError:
                pass
            print(res)

            for i in data[str(res[-1])].values():
                mn = int((i["mn"]))
                mx = int(i["mx"])
                break
    text = "The live temp on Mars on day " + str(res[-1]) + " is max: " + str(
        mx) + "c and min: " + str(mn) + "c          "
    print(text)
    write_string(text, offset_x=0, kerning=False)
    show()
Ejemplo n.º 24
0
def withPhat():
    while True:
        tijd = time.localtime()  #create a struct_time object
        if tijd[4] in interval_List:  #and check if the number of minutes is in the interval_List
            currTime = time.asctime()[
                11:16]  #if yes create an hour and minute string using .asctime
            currTime = currTime + ':00'  #add the zeros

            getNap()  #get and set current nap_list
            # walk through it searching match with currTime nap_list[i][1]
            # for i in nap_list: doesn't work in this case (because I need the index number?)
            for i in range(len(nap_list)):
                try:
                    if nap_list[i][1] == currTime:
                        currLevel = int(nap_list[i][5])  #currLevel is an int
                        prevLevel = int(nap_list[i - 1][5])
                        diffLevel = currLevel - prevLevel
                        #print(str('%+d' % diffLevel)) #+d formatting for pos and neg numbers
                        print(currTime, str(currLevel), str('%+d' % diffLevel))
                        # Microdot Phat code follows
                        display = str(currLevel) + str('%+d' % diffLevel)
                        microdotphat.clear()
                        microdotphat.write_string(display, kerning=False)
                        microdotphat.show()
                        lookAhead(nap_list,
                                  currTime)  #send nap_list to lookAhead
                except IndexError:
                    microdotphat.clear()
                    microdotphat.write_string('IndEr2', kerning=False)
                    microdotphat.show()
                    logging.info('IndexError 2 in withPhat')
                    print('IndexError 2 in withPhat')
                    time.sleep(65)  #not sure how long to wait
                    continue  #does this work here?

        time.sleep(65)  # waits a bit more than a minute to escape if = true
    time.sleep(5)
Ejemplo n.º 25
0
def display_strings_array(lines):
    delay = 0.03

    line_height = microdotphat.HEIGHT + 2

    lengths = [0] * len(lines)

    offset_left = 0

    for line, text in enumerate(lines):
        lengths[line] = microdotphat.write_string(text,
                                                  offset_x=offset_left,
                                                  offset_y=line_height * line,
                                                  kerning=False)
        offset_left += lengths[line]

    microdotphat.set_pixel(0, (len(lines) * line_height) - 1, 0)

    current_line = 0

    microdotphat.show()

    pos_x = 0
    pos_y = 0
    for current_line in range(len(lines)):
        time.sleep(delay * 10)
        for y in range(lengths[current_line]):
            microdotphat.scroll(1, 0)
            pos_x += 1
            time.sleep(delay)
            microdotphat.show()
        if current_line == len(lines) - 1:
            microdotphat.scroll_to(0, 0)
        else:
            for x in range(line_height):
                microdotphat.scroll(0, 1)
                pos_y += 1
                microdotphat.show()
                time.sleep(delay)
 def updateDisplay(self):
     write_string( str(self.systemTemp)[0:2]+"  " + str(self.roomTemp)[0:2] , kerning=False)
     show()
Ejemplo n.º 27
0
def phat():
    while True:
        microdotphat.scroll()
        microdotphat.show()
        time.sleep(0.01)
Ejemplo n.º 28
0
#!/usr/bin/env python

import datetime
import time

from microdotphat import write_string, set_decimal, clear, show

print("""Thermal

Displays the temperature measured from thermal zone 0, using
/sys/class/thermal/thermal_zone0/temp

Press Ctrl+C to exit.
""")

delay = 1

while True:
    clear()
    path="/sys/class/thermal/thermal_zone0/temp"
    f = open(path, "r")
    temp_raw = int(f.read().strip())
    temp = float(temp_raw / 1000.0)
    write_string( "%.2f" % temp + "c", kerning=False)
    show()
    time.sleep(delay)
Ejemplo n.º 29
0
def DisplayTemp(temp, unitstr):
    print("Displaying Temperature on MicroDot Phat...")
    write_string("%.1f" % temp + unitstr, kerning=False)
    show()
Ejemplo n.º 30
0
def print_string(text):
    microdotphat.write_string(text, kerning=False)
    microdotphat.show()
Ejemplo n.º 31
0
def reset():
    microdotphat.clear()
    microdotphat.show()
Ejemplo n.º 32
0
import time
from microdotphat import write_string, scroll, clear, show

clear()
write_string('Forecast, SNOWCATS!   ')

while True:
    scroll()
    show()
    time.sleep(0.01)
Ejemplo n.º 33
0
#!/usr/bin/env python

import time
import sys

import microdotphat             


print("""Scrolling Text

Scrolls a single word char by char across the screen.

Usage: {name} "your message"

Press Ctrl+C to exit.
""".format(name=sys.argv[0]))

text = "Ninja"

if len(sys.argv) > 1:
    text = sys.argv[1]

microdotphat.write_string(text, offset_x=0, kerning=False)
microdotphat.show()
time.sleep(0.5)

while True:
    microdotphat.scroll(amount_x=8)
    microdotphat.show()
    time.sleep(0.5)