from dht import DHT11
from machine import Pin, SPI
from ssd1306 import SSD1306_SPI
from time import sleep

# DHT Sensor
DHT_PIN = DHT11(Pin(26))

# SPI PINS
MISO_PIN = Pin(19)
MOSI_PIN = Pin(23)
SCK_PIN = Pin(18)
DC_PIN = Pin(4, Pin.OUT)
CS_PIN = Pin(5, Pin.OUT)
RST_PIN = Pin(2, Pin.OUT)

# VSPI Hardware channel. 80 MHz signal rate
vspi = SPI(2, baudrate=2600000, polarity=0, phase=0, bits=8, firstbit=0, sck=SCK_PIN, mosi=MOSI_PIN, miso=MISO_PIN)

oled = SSD1306_SPI(128, 64, vspi, DC_PIN, RST_PIN, CS_PIN)


class DisplayWriter:

    def __init__(self, spi):
        self.spi = spi
        self.height = spi.height
        self.width = spi.width

    def msg(self, msg: str, l_offset=0, top_offset=0) -> None:
        """Writes a message to an OLED display.

        Will wrap text as needed.
        """
        self.spi.fill(0)
        formatted_msg = self._split_msg(msg, l_offset, top_offset)
        for s, left, top in formatted_msg:
            self.spi.text(s, left, top)
        self.spi.show()

    # Todo make this a generator
    def _split_msg(self, msg, l_offset, top_offset) -> list:
        """Splits a message at screen width to be used for text wrapping."""
        _top_offset = top_offset
        result = []
        for e in msg.split('\n'):
            result.append((e, l_offset, _top_offset))
            _top_offset += 10
        return result


def dht_report(dht_pin):
    dht_pin.measure()
    _temp = dht_pin.temperature()
    _hum = dht_pin.humidity()
    return _temp, _hum


def celsius_to_fahrenheit(celsius: int):
    return (celsius * (9 / 5)) + 32


display = DisplayWriter(oled)

while True:
    cel, hum = dht_report(DHT_PIN)
    fahr = celsius_to_fahrenheit(cel)
    report = "Temp: {}C/{}F\nHum: {}%".format(cel, fahr, hum)
    print(report)
    display.msg(report)
    sleep(1)
