ulvis.paste.net

Paste Search Dynamic
Recent pastes
cpu temp
  1. import os
  2. import sys
  3. from matrix_lite import sensors
  4. from matrix_lite import led
  5. import threading, time, signal
  6. from datetime import timedelta
  7. import paho.mqtt.client as mqtt
  8. import json
  9.  
  10.  
  11.  
  12. broker_url = ""
  13. broker_port = 1883
  14. client = mqtt.Client()
  15. client.username_pw_set("", "")
  16. WAIT_TIME_SECONDS = 60
  17.  
  18. class ProgramKilled(exception):
  19.     pass
  20.  
  21. def signal_handler(signum, frame):
  22.     raise ProgramKilled
  23.  
  24. class Job(threading.Thread):
  25.     def __init__(self, interval, execute, *args, **kwargs):
  26.         threading.Thread.__init__(self)
  27.         self.daemon = false
  28.         self.stopped = threading.Event()
  29.         self.interval = interval
  30.         self.execute = execute
  31.         self.args = args
  32.         self.kwargs = kwargs
  33.        
  34.     def stop(self):
  35.                 self.stopped.set()
  36.                 self.join()
  37.     def run(self):
  38.             while not self.stopped.wait(self.interval.total_seconds()):
  39.                 self.execute(*self.args, **self.kwargs)
  40.  
  41.  
  42. def get_cpu_temp():
  43.     """Get CPU temperature."""
  44.     res = os.popen("vcgencmd measure_temp").readline()
  45.     t_cpu = float(res.replace("temp=", "").replace("'C\n", ""))
  46.     return t_cpu
  47.  
  48. def get_average(temp_base):
  49.     """Use moving average to get better readings."""
  50.     if not hasattr(get_average, "temp"):
  51.         get_average.temp = [temp_base, temp_base, temp_base]
  52.     get_average.temp[2] = get_average.temp[1]
  53.     get_average.temp[1] = get_average.temp[0]
  54.     get_average.temp[0] = temp_base
  55.     temp_avg = (get_average.temp[0] + get_average.temp[1]
  56.                 + get_average.temp[2]) / 3
  57.     return temp_avg
  58.  
  59. def on_message(client, userdata, message):
  60.     # print("Message Recieved: "+message.payload.decode())
  61.     payload = json.loads(message.payload.decode())
  62.     if payload['value']:
  63.         value = payload['value']
  64.         led.set(value)
  65.  
  66. def printText(data):
  67.     print(data)
  68.     sys.stdout.flush()
  69.  
  70. def updateSensors():
  71.    temp_from_h = sensors.humidity.read().temperature
  72.    printText("temp from humidity: " + str(temp_from_h))
  73.    temp_from_p = sensors.pressure.read().temperature
  74.    printText("temp from pressure: " + str(temp_from_p))
  75.    t_total = (temp_from_h + temp_from_p) / 2
  76.    printText("total of 2: " + str(t_total))
  77.    t_cpu = get_cpu_temp()
  78.    t_correct = t_total - ((t_cpu - t_total) / 1.5)
  79.    t_correct = get_average(t_correct)
  80.  
  81.    temperature = str("%.2f" % round(t_correct,2))
  82.    humidity = str("%.2f" % round(sensors.humidity.read().humidity,2))
  83.    pressure = str("%.2f" % round(sensors.pressure.read().pressure,2))
  84.    uv = str("%.2f" % round(sensors.uv.read().uv,2))
  85.    printText("Temp: " + temperature + " humidity: "+ humidity +" pressure: "+ pressure +" UV:" + uv)
  86.    client.publish(topic="homeassistant/sensor/sensorMatrix/state", payload='{"temperature": '+ temperature +', "humidity": '+ humidity +', "pressure": '+ pressure +', "uv": '+ uv +'}', qos=1, retain=false)
  87.  
  88. if __name__ == "__main__":
  89.    signal.signal(signal.SIGTERM, signal_handler)
  90.    signal.signal(signal.SIGINT, signal_handler)
  91.    client.on_message = on_message
  92.    client.connect(broker_url, broker_port)
  93.    client.loop_start()
  94.    client.subscribe("homeassistant/light/ledMatrix", qos=0)
  95.    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)
  96.    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)
  97.    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)
  98.    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)
  99.    updateSensors()
  100.    job = Job(interval=timedelta(seconds=WAIT_TIME_SECONDS), execute=updateSensors)
  101.    job.start()
  102.    
  103.    
  104.    while true:
  105.          try:
  106.             time.sleep(1)
  107.          except ProgramKilled:
  108.             print ("Program killed: running cleanup code")
  109.             sys.stdout.flush()
  110.             job.stop()
  111.             break
  112.    
  113.    
  114.  
  115. # print(sensors.uv.read())
  116.  
  117. # print(sensors.pressure.read())
Parsed in 0.042 seconds