' This program is intended to read the temperature, humidity and pressure values form a RuuviTag '
' and to display the temperature and humidity values as binary numbers on a Pimorini blinkt! HAT. '
''
' It is based on the print_to_screen.py example from the ruuvitag library at github. '
' Requires a Pi Zero W, Pi 3 or any other RPi equiped with bluetooth and all neccessary libraries installed.'

import time
import os
from datetime import datetime

from ruuvitag_sensor.ruuvi import RuuviTagSensor

from blinkt import *


def temp_blinkt(bt):
    # this routine takes the temperature value and displays it as a binary number on blinkt!

    clear ()

    # color and intensity of "1" pixels : bright white
    r1 = 64
    g1 = 64
    b1 = 64

    #color and intensity of "0" pixels : dim white
    r0 = 3
    g0 = 3
    b0 = 3


    # Round and convert into integer
    r = round (bt)

    # vz represents algebraic sign for indicator pixel
    if (r>0): vz = 1    # positive
    elif (r<0): vz= 2   # negative
    else: vz= 0         # zero
    # print (vz)

    # Set indicator pixel
    if (vz==1):
            set_pixel (0, 64, 0, 0) # red for positive values
    elif (vz==2):
            set_pixel (0, 0, 0, 64) # blue for negative values
    else:
            set_pixel (0, 64, 0, 64)  # purple if zero
            

    # transform to absolute, 7-digit binary number
    i = abs(r)
    #print (i)

    b7 = '{:07b}'.format(i)
    # transforms a decimal number into a binary number with at least 7 digits,
    # filled left with 0s

    print (bt, " °C" )        # print on screen
    print ("temperature as binary number: ", b7)
    print()

    # Set pixels on blinkt!

    # set binary number
    for h in range (0,7):
        f = (h+1)
        if (b7[h] == "1"):
            set_pixel (f, r1, g1, b1)
            # print ("bit ", h, " is 1, pixel ", f)
        else:
            set_pixel (f, r0, g0, b0)

    show() # write to blinkt!

# end of temp_blinkt()


def hum_blinkt(bh):
    # this takes the humidity value and displays it as a binary number on blinkt!

    clear()

    # Set indicator pixel
    set_pixel (0, 0, 64, 0) # green for humidity 

    #set color and intensity of "1" pixels: yellow
    r1 = 64
    g1 = 64
    b1 = 0

    #set color and intensity of "0" pixels : dim yellow
    r0 = 3
    g0 = 3
    b0 = 0

    # Round and transform into integer
    r = round (bh)

    # transform to an absolute, 7-digit binary number
    i = abs(r)
    #print (i)

    # transforms a decimal number into a binary number with at least 7 digits,
    # filled left with 0s
    b7 = '{:07b}'.format(i)

    print (bh, " %")
    print ("humidity as binary number: ", b7)
    print()
    
    # Set pixels on blinkt!

    # set binary number to pixels
    for h in range (0,7):
        f = (h+1)
        if (b7[h] == "1"):
            set_pixel (f, r1, g1, b1)
        else:                            
            set_pixel (f, r0, g0, b0)    

    show()

# end of hum_blinkt()


# changing parameter "bright" allows to define brightness of the pixels, max =1
bright = (0.3) 
set_brightness(bright)

set_clear_on_exit()

mac = 'EC:6D:59:6D:01:1C' # Change to the mac-address of your ruuvitag

# Reading data from the RuuviTag

print('Starting')

sensor = RuuviTagSensor(mac)

while True:
    data = sensor.update()
    
    bt = data['temperature']    # get temperature 
    bh = data['humidity']       # get humidity
    bp = data['pressure']       # get pressure

    line_sen = str.format('Sensor - {0}', mac)
    line_tem = str.format('Temperature: {0} C', bt)
    line_hum = str.format('Humidity:    {0} %', bh)
    line_pre = str.format('Pressure:    {0}', bp)

    print()
    
    # Clear screen and print sensor data to screen
    os.system('clear')

    print(str(datetime.now()))
    print(line_sen)
    print(line_tem)
    print(line_hum)
    print(line_pre)
    print('\n\r.......\n')

     # display temperature on blinkt!
    
    temp_blinkt (bt)    # display temperature value on blinkt!
    time.sleep (9)      # display temperature for 9 seconds

    # display humidity on blinkt!
  
    hum_blinkt (bh)     # display humidity value on blinkt!

    print ('Press Ctrl+C to quit.\n')
    
    # Wait for a few seconds and start over again
    try:
        time.sleep(5)
        
    except KeyboardInterrupt:
        # When Ctrl+C is pressed execution of the while loop is stopped
        print('Exit')
        clear()
        show ()
        break
