Skip to content

Instantly share code, notes, and snippets.

@Sennevds
Created August 12, 2019 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sennevds/fad29710d30a6ee481ce2bf7d3629eb1 to your computer and use it in GitHub Desktop.
Save Sennevds/fad29710d30a6ee481ce2bf7d3629eb1 to your computer and use it in GitHub Desktop.
import os
import sys
from matrix_lite import sensors
from matrix_lite import led
import threading, time, signal
from datetime import timedelta
import paho.mqtt.client as mqtt
import json
broker_url = ""
broker_port = 1883
client = mqtt.Client()
client.username_pw_set("", "")
WAIT_TIME_SECONDS = 60
class ProgramKilled(Exception):
pass
def signal_handler(signum, frame):
raise ProgramKilled
class Job(threading.Thread):
def __init__(self, interval, execute, *args, **kwargs):
threading.Thread.__init__(self)
self.daemon = False
self.stopped = threading.Event()
self.interval = interval
self.execute = execute
self.args = args
self.kwargs = kwargs
def stop(self):
self.stopped.set()
self.join()
def run(self):
while not self.stopped.wait(self.interval.total_seconds()):
self.execute(*self.args, **self.kwargs)
def get_cpu_temp():
"""Get CPU temperature."""
res = os.popen("vcgencmd measure_temp").readline()
t_cpu = float(res.replace("temp=", "").replace("'C\n", ""))
return t_cpu
def get_average(temp_base):
"""Use moving average to get better readings."""
if not hasattr(get_average, "temp"):
get_average.temp = [temp_base, temp_base, temp_base]
get_average.temp[2] = get_average.temp[1]
get_average.temp[1] = get_average.temp[0]
get_average.temp[0] = temp_base
temp_avg = (get_average.temp[0] + get_average.temp[1]
+ get_average.temp[2]) / 3
return temp_avg
def on_message(client, userdata, message):
# print("Message Recieved: "+message.payload.decode())
payload = json.loads(message.payload.decode())
if payload['value']:
value = payload['value']
led.set(value)
def printText(data):
print(data)
sys.stdout.flush()
def updateSensors():
temp_from_h = sensors.humidity.read().temperature
printText("temp from humidity: " + str(temp_from_h))
temp_from_p = sensors.pressure.read().temperature
printText("temp from pressure: " + str(temp_from_p))
t_total = (temp_from_h + temp_from_p) / 2
printText("total of 2: " + str(t_total))
t_cpu = get_cpu_temp()
t_correct = t_total - ((t_cpu - t_total) / 1.5)
t_correct = get_average(t_correct)
temperature = str("%.2f" % round(t_correct,2))
humidity = str("%.2f" % round(sensors.humidity.read().humidity,2))
pressure = str("%.2f" % round(sensors.pressure.read().pressure,2))
uv = str("%.2f" % round(sensors.uv.read().uv,2))
printText("Temp: " + temperature + " humidity: "+ humidity +" pressure: "+ pressure +" UV:" + uv)
client.publish(topic="homeassistant/sensor/sensorMatrix/state", payload='{"temperature": '+ temperature +', "humidity": '+ humidity +', "pressure": '+ pressure +', "uv": '+ uv +'}', qos=1, retain=False)
if __name__ == "__main__":
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
client.on_message = on_message
client.connect(broker_url, broker_port)
client.loop_start()
client.subscribe("homeassistant/light/ledMatrix", qos=0)
client.publish(topic="homeassistant/sensor/sensorMatrixTemp/config", payload='{"device_class": "temperature", "name": "Temperature", "state_topic": "homeassistant/sensor/sensorMatrix/state", "unit_of_measurement": "°C", "value_template": "{{ value_json.temperature}}" }', qos=1, retain=True)
client.publish(topic="homeassistant/sensor/sensorMatrixHum/config", payload='{"device_class": "humidity", "name": "Humidity", "state_topic": "homeassistant/sensor/sensorMatrix/state", "unit_of_measurement": "%", "value_template": "{{ value_json.humidity}}" }', qos=1, retain=True)
client.publish(topic="homeassistant/sensor/sensorMatrixPres/config", payload='{"device_class": "pressure", "name": "Pressure", "state_topic": "homeassistant/sensor/sensorMatrix/state", "unit_of_measurement": "Pa", "value_template": "{{ value_json.pressure}}" }', qos=1, retain=True)
client.publish(topic="homeassistant/sensor/sensorMatrixUv/config", payload='{"name": "UV", "state_topic": "homeassistant/sensor/sensorMatrix/state", "value_template": "{{ value_json.uv}}" }', qos=1, retain=True)
updateSensors()
job = Job(interval=timedelta(seconds=WAIT_TIME_SECONDS), execute=updateSensors)
job.start()
while True:
try:
time.sleep(1)
except ProgramKilled:
print ("Program killed: running cleanup code")
sys.stdout.flush()
job.stop()
break
# print(sensors.uv.read())
# print(sensors.pressure.read())
@supermaz
Copy link

supermaz commented Jan 6, 2021

Thank you. I will try with a cable to get the board at some distance to the RPi and see what the difference is then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment