Skip to content

Instantly share code, notes, and snippets.

@mag1art
Last active May 3, 2023 12:29
Show Gist options
  • Save mag1art/0d9435954df1bdc4a44b92e53597b0cb to your computer and use it in GitHub Desktop.
Save mag1art/0d9435954df1bdc4a44b92e53597b0cb to your computer and use it in GitHub Desktop.
Orange Pi 5 sensors web app for monitoring temperature

Orange Pi 5 sensors web app for monitoring temperature

how to run?

python orange_pi_sensors_web.py

how it works?

each 3 second ask json by command "sensors -j", split and write to temps.csv file.
when client make request, create image with line diagram from csv file.
import json
import time
import csv
import datetime
from flask import Flask, render_template, send_file
app = Flask(__name__)
data = {}
def save_temps_to_csv(data):
with open('temps.csv', mode='a+') as csv_file:
fieldnames = list(data.keys())
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
# if headers is empty, write them first
csv_file.seek(0)
first_char = csv_file.read(1)
if not first_char:
writer.writeheader()
#write to file
writer.writerow(data)
def get_temperatures():
while True:
cmd = "sensors -j"
output = os.popen(cmd).read()
try:
temps = json.loads(output)
data.clear()
date_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
data['time']=date_time
for key, value in temps.items():
if 'temp1' in value and 'temp1_input' in value['temp1']:
data[key] = value['temp1']['temp1_input']
except Exception as e:
print(e)
save_temps_to_csv(data)
time.sleep(3)
@app.route('/')
def temp1_history_png():
data = {
'gpu_thermal-virtual-0': [],
'littlecore_thermal-virtual-0': [],
'bigcore0_thermal-virtual-0': [],
'npu_thermal-virtual-0': [],
'center_thermal-virtual-0': [],
'bigcore1_thermal-virtual-0': [],
'soc_thermal-virtual-0': []
}
with open('temps.csv') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
for key in data.keys():
if key != 'time':
if key in row:
data[key].append(float(row[key]))
return generate_chart(data)
def generate_chart(data):
import matplotlib.pyplot as plt
import io
import base64
plt.style.use('ggplot')
plt.figure(figsize=(12, 6))
for key, values in data.items():
plt.plot(values, label=key)
plt.legend()
plt.title('Temperature history')
plt.xlabel('Time (3 sec interval)')
plt.ylabel('Temperature (Celsius)')
img = io.BytesIO()
plt.savefig(img)
img.seek(0)
chart_data = base64.b64encode(img.getvalue()).decode('utf-8')
plt.close()
return f'<img src="data:image/png;base64,{chart_data}">'
if __name__ == '__main__':
import threading
import os
t = threading.Thread(target=get_temperatures)
t.daemon = True
t.start()
app.run(host='0.0.0.0', port=5000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment