# -*- coding: utf-8 -*-

from machine import Pin, I2C
import ssd1306
from time import sleep, sleep_ms
import onewire, ds18x20
import urequests
import ConnectWiFi

# ESP8266 Pin assignment 
i2c = I2C(-1, scl=Pin(5), sda=Pin(4))
ds18b20 = ds18x20.DS18X20(onewire.OneWire(Pin(0)))

oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.contrast(100)

roms = ds18b20.scan()
print('Found DS devices: ', roms)

errortemp = 99
inner_temp_default = 22
outer_temp_default = 18

bar_height = 20
bar_center = 40
tick_height = 6
outer_bar_offset = oled_height-30
inner_bar_offset = 0
log_length = 120
outer_refresh_interval = 15

outer_temp = errortemp
inner_temp = errortemp

inner_msg = ""
outer_msg = ""

inner_templog_buffer = []
outer_templog_buffer = []
inner_templog = []
outer_templog = []

refresh_counter = 1
burn_in_counter = 0

def cleanedlist(list):
    return [i for i in list if i != errortemp]

def drawoutlinetext(string, x, y, color):
    oled.text(string, x+1, y, not color)
    oled.text(string, x-1, y, not color)
    oled.text(string, x, y+1, not color)
    oled.text(string, x, y-1, not color)
    oled.text(string, x+1, y+1, not color)
    oled.text(string, x-1, y+1, not color)
    oled.text(string, x+1, y-1, not color)
    oled.text(string, x-1, y-1, not color)
    oled.text(string, x+2, y, not color)
    oled.text(string, x-2, y, not color)
    oled.text(string, x+2, y+1, not color)
    oled.text(string, x-2, y+1, not color)
    oled.text(string, x+2, y-1, not color)
    oled.text(string, x-2, y-1, not color)
    oled.text(string, x, y+2, not color)
    oled.text(string, x+1, y+2, not color)
    oled.text(string, x-1, y+2, not color)

    oled.text(string, x, y, color)

def drawlabels(minval, maxval, inner_templog_clean, outer_templog_clean, inner_temp, outer_temp):
    label_height = 13
    label_width = 8*4

    inner_temp_label = inner_temp
    outer_temp_label = outer_temp

    if inner_temp == errortemp:
        if len(inner_templog_clean) > 0:
            inner_temp = inner_templog_clean[-1]
        else:
            inner_temp = inner_temp_default
    if outer_temp == errortemp:
        if len(outer_templog_clean) > 0:
            outer_temp = outer_templog_clean[-1]
        else:
            outer_temp = outer_temp_default

    inner_label_y = oled_height-int((float(inner_temp)-minval)/(maxval-minval)*(oled_height))
    outer_label_y = oled_height-int((float(outer_temp)-minval)/(maxval-minval)*(oled_height))

    label_xpos = oled_width-label_width-4
    inner_label_ypos = max(min(int(inner_label_y-(label_height/2)), oled_height-label_height), 0)-1
    outer_label_ypos = max(min(int(outer_label_y-(label_height/2)), oled_height-label_height), 0)-1

    if inner_label_ypos > outer_label_ypos:
        while inner_label_ypos-outer_label_ypos < label_height:
            inner_label_ypos = min(inner_label_ypos+1, oled_height-label_height)
            outer_label_ypos = max(outer_label_ypos-1, 0)

    if inner_label_ypos <= outer_label_ypos:
        while outer_label_ypos-inner_label_ypos < label_height:

            inner_label_ypos = max(inner_label_ypos-1, 0)
            outer_label_ypos = min(outer_label_ypos+1, oled_height-label_height)
    
    inner_temp_pad = " "
    outer_temp_pad = " "

    if int(round(inner_temp, 0)) >= 0 and int(round(inner_temp, 0)) < 10:
        inner_temp_pad = "  "
    elif int(round(inner_temp, 0)) < -9:
        inner_temp_pad = ""
    if int(round(outer_temp, 0)) >= 0 and int(round(outer_temp, 0)) < 10:
        outer_temp_pad = "  "
    elif int(round(outer_temp, 0)) < -9:
        outer_temp_pad = ""

    if (inner_temp_label == errortemp):
        inner_temp_string = " --"
    else:
        inner_temp_string = inner_temp_pad+str(int(round(inner_temp, 0)))

    if (outer_temp_label == errortemp):
        outer_temp_string = " --"
    else:
        outer_temp_string = outer_temp_pad+str(int(round(outer_temp, 0)))

    drawoutlinetext(inner_temp_string, label_xpos+4, inner_label_ypos+3, 1)
    drawoutlinetext(outer_temp_string, label_xpos+4, outer_label_ypos+3, 1)

def drawgraph(tempdata, temp, minval, maxval, x, y, width, height, style):

    tempdata = tempdata + [temp]

    if (len(tempdata) > 1):

        normalized = [int((float(i)-minval)/(maxval-minval)*(height)) for i in tempdata]
        stepwidth = width/(len(normalized)-1)

        for i in range(0, len(normalized)-1):
            if tempdata[i] == errortemp or tempdata[i+1] == errortemp:
                pass
            else:
                if style == 'line':
                    oled.line(x+int(i*stepwidth), y+height-normalized[i]-1, x+int(i*stepwidth+stepwidth), y+height-normalized[i+1]-1, 0)
                    oled.line(x+int(i*stepwidth), y+height-normalized[i]+1, x+int(i*stepwidth+stepwidth), y+height-normalized[i+1]+1, 0)
                    oled.line(x+int(i*stepwidth), y+height-normalized[i], x+int(i*stepwidth+stepwidth), y+height-normalized[i+1], 1)
                elif style == 'dashed':
                    for j in range(0, int(stepwidth)+1):
                        localx = x+int(i*stepwidth)+j
                        if (localx+4) % 9 < 6:
                            value = int( normalized[i] + (normalized[i+1]-normalized[i]) * (j/stepwidth) )
                            oled.pixel(localx, y+height-value-1, 0)
                            oled.pixel(localx, y+height-value+1, 0)
                            oled.pixel(localx, y+height-value, 1)
                elif style == 'solid':
                    for j in range(0, int(stepwidth)+1):
                        localx = x+int(i*stepwidth)+j
                        if (localx+3)%4 == 2:
                            value = int( normalized[i] + (normalized[i+1]-normalized[i]) * (j/stepwidth) )
                            for localy in range(y+height-value+2, y+height):
                                if (localy+localx/2+burn_in_counter) % 4 > 2:
                                    oled.pixel(localx, localy, 1)
                elif style == 'halfsolid':
                    for j in range(0, int(stepwidth)+1):
                        localx = x+int(i*stepwidth)+j
                        if (localx+1)%4 == 2:
                            value = int( normalized[i] + (normalized[i+1]-normalized[i]) * (j/stepwidth) )
                            for localy in range(y+height-value+2, y+height):
                                if (localy+localx/2+burn_in_counter) % 4 > 3:
                                    oled.pixel(localx, localy, 1)

def refresh_inner():
    global inner_msg
    global inner_temp

    inner_msg = "Temp Read Error"

    for rom in roms:
        inner_temp = ds18b20.read_temp(rom)
        inner_msg = ""
        #print('DS: '+str(inner_temp))

def refresh_outer():
    global outer_msg
    global outer_temp

    outer_msg = ""

    connection_success = ConnectWiFi.connect()
    
    if connection_success:
        try:
            response = urequests.get('http://api.openweathermap.org/data/2.5/weather?zip=---your-zip---,de&appid=---your-app-id---')
            parsed = response.json()

            if 'cod' in parsed:
                if parsed["cod"] != 200:
                    outer_msg = "Error "+str(parsed["cod"])
                    outer_temp = errortemp
            if 'main' in parsed and 'temp' in parsed["main"]:
                outer_temp = float(parsed["main"]["temp"]) - 273.15
            else:
                outer_msg = "No Temperature"
                outer_temp = errortemp
        except:
            outer_msg = "No Response"
            print("no response")
            outer_temp = errortemp
    else:
        outer_msg = "No WiFi"
        outer_temp = errortemp

def showgraph():
    oled.fill(0)
    graphmin = outer_temp_default
    graphmax = inner_temp_default

    inner_templog_clean = cleanedlist(inner_templog+[inner_temp])
    outer_templog_clean = cleanedlist(outer_templog+[outer_temp])

    if len(inner_templog_clean) >= 1 and len(outer_templog_clean) >= 1:
        graphmin = min(min(inner_templog_clean), min(outer_templog_clean))
        graphmax = max(max(inner_templog_clean), max(outer_templog_clean))
    
    graphmin -= 5
    graphmax += 5

    drawgraph(inner_templog, inner_temp, graphmin, graphmax, 0, 0, oled_width-1, oled_height-1, 'halfsolid')
    drawgraph(outer_templog, outer_temp, graphmin, graphmax, 0, 0, oled_width-1, oled_height-1, 'solid')

    drawgraph(inner_templog, inner_temp, graphmin, graphmax, 0, 0, oled_width-1, oled_height-1, 'dashed')
    drawgraph(outer_templog, outer_temp, graphmin, graphmax, 0, 0, oled_width-1, oled_height-1, 'line')

    drawlabels(graphmin, graphmax, inner_templog_clean, outer_templog_clean, inner_temp, outer_temp)

    if inner_msg != "" and outer_msg == "":
        drawoutlinetext(inner_msg, 5, oled_height-15, 1)
    elif inner_msg != "" and outer_msg != "":
        drawoutlinetext(inner_msg, 5, oled_height-25, 1)
    if outer_msg != "":
        drawoutlinetext(outer_msg, 5, oled_height-15, 1)

    oled.show()

#setup/init
ds18b20.convert_temp()
sleep_ms(750)

refresh_inner()
inner_templog_buffer.append(inner_temp)
inner_templog.append(inner_temp)
showgraph()

refresh_outer()
if outer_temp != errortemp:
    outer_templog_buffer.append(outer_temp)
outer_templog.append(outer_temp)
showgraph()

while True:

    refresh_counter += 1
    burn_in_counter = burn_in_counter+1 % 4*9
    do_refresh_outer = False

    ds18b20.convert_temp() # refresh value ahead of time for minimum latency
    sleep(1) # refresh inner temp every second

    print('.', end='')

    if refresh_counter >= outer_refresh_interval: # refresh outer temp every 30 sec
        do_refresh_outer = True
        refresh_counter = 0

    refresh_inner()
    inner_templog_buffer.append(inner_temp)

    if do_refresh_outer:

        print('#')

        inner_templog.append(sum(inner_templog_buffer)/len(inner_templog_buffer))
        inner_templog = inner_templog[(0-log_length):]
        inner_templog_buffer = []
        
        refresh_outer()

        if outer_temp != errortemp:
            outer_templog_buffer.append(outer_temp)
            outer_templog.append(sum(outer_templog_buffer)/len(outer_templog_buffer))
            outer_templog_buffer = outer_templog_buffer[-6:]
        else:
            outer_templog.append(errortemp)
            outer_templog_buffer = []
        outer_templog = outer_templog[(0-log_length):]
 
    showgraph()