
# weather3 use RPi as publisher of temp and humi
# hwd 2018-07-24
# 2021-05-06 re-code to Domoticz
# get weather from sensor

# changes needed:
# Change MQTT_SERVER to your Domoticz IP address
# In three places, change the number following "idx" to match the idx number for your device

# https://tutorials-raspberrypi.com/raspberry-pi-mqtt-broker-client-wireless-communication/
# https://luma-oled.readthedocs.io/en/latest/python-usage.html

import paho.mqtt.publish as publish
import os, sys, Adafruit_DHT, time
from datetime import datetime, date
# set up display
from luma.core.interface.serial import i2c, spi
from luma.core.render import canvas
from luma.oled.device import sh1106
from PIL import ImageFont

# GND Pin 6
# VCC Pin 1
# SCL Pin 5
# SDA Pin 3
try :
    serial = i2c(port=1, address=0x3C)

    # substitute ssd1331(...) or sh1106(...) below if using that device
    device = sh1106(serial)
except:
    print ('no i2c device')
    pass

MQTT_SERVER = "192.168.8.112"
MQTT_HUMIDITY = "domoticz/in"
MQTT_TEMPERATURE = "domoticz/in"

# add for using pin as power
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(19,GPIO.OUT)
GPIO.output(19,GPIO.HIGH)  # pin 35, gnd = pin 34

sensor                       = Adafruit_DHT.AM2302 #DHT11/DHT22/AM2302
pin                          = 6  # pin 31
latest_humidity_0            = 0.0
latest_temperature_0         = 0.0
diff                         = 0.2
time_delay                   = 0

#start main program

print ("Ignoring first 2 sensor values to improve quality...")
for x in range(2):
  Adafruit_DHT.read_retry(sensor, pin)

while True:
    try:
      while True:
        hum, temp = Adafruit_DHT.read_retry(sensor, pin)
        timenow = time.strftime("%a, %b %d, %Y %I:%M:%S %p") # for print when value changes
        now = datetime.now() # for clock display
        today_date = now.strftime("%d %b %y")
        today_time = now.strftime("%H:%M:%S")
        #print ("Time="+today_time)
        #print ("Temp=" + str(temp) +" hum=" + str(hum))
        if hum is not None and temp is not None:
          # convert temp to F
          # temp = (temp * 1.8) + 32
          if (hum > latest_humidity_0 + diff or hum < latest_humidity_0 - diff) :
              latest_humidity_0 = hum
              #publish.single(MQTT_HUMIDITY, str(hum), hostname=MQTT_SERVER)
              msg='{"idx":69,"nvalue":0,"svalue":"' + str(temp) + ';' + str(hum) + ';0"}'
              print (msg)
              publish.single(MQTT_HUMIDITY, msg, hostname=MQTT_SERVER)
              print ("hum = " + str(hum) + " " + timenow)
          if (temp > latest_temperature_0 + diff or temp < latest_temperature_0 - diff) :
              latest_temperature_0 = temp
              # publish.single(MQTT_TEMPERATURE, str(temp), hostname=MQTT_SERVER)
              msg='{"idx":69,"nvalue":0,"svalue":"' + str(temp) + ';' + str(hum) + ';0"}'
              print (msg)
              publish.single(MQTT_TEMPERATURE, msg, hostname=MQTT_SERVER)
              print ("temp = " + str(temp) + " " + timenow)
              time_delay = 0  # reset so we don't publish twice

        try :
            # use custom font
            #font = ImageFont.truetype('C&C Red Alert [INET].ttf', 40)
            font = ImageFont.truetype('code2000.ttf', 40)
            with canvas(device) as draw:
              margin = 4
              cx = 30
              cy = min(device.height, 64) / 2
              if (temp is not None):
                  ftemp=(temp*1.8)+32
              else :
                  ftemp=0.0
              draw.text(((cx), 0), str(round(ftemp))+'\u00b0F', fill="yellow", font=font)
              draw.text(((cx + margin), cy + 8), today_date, fill="yellow")
              draw.text(((cx + margin), cy + 16), today_time, fill="yellow")
        except :
            pass
        
        if time_delay > 300 and temp is not None:
            # republish temp once every 5 minutes to address WiFi problem
            # publish.single(MQTT_TEMPERATURE, str(temp), hostname=MQTT_SERVER)
            msg='{"idx":69,"nvalue":0,"svalue":"' + str(temp) + ';' + str(hum) + ';0"}'
            print (msg)
            publish.single('domoticz/in', msg, hostname=MQTT_SERVER)
            print ("re-temp = " + str(temp) + " " + timenow)
            time_delay = 0
        time_delay += 1            
        time.sleep(1)  # wait a second
    except :
      print ("exception while true " + timenow)
      pass
    