Raspberry Pi - Pi Sensor Client Project

From myWiki
Revision as of 12:33, 9 August 2020 by Stevet (talk | contribs)

pi-sensor-client.py

import os
import glob
import datetime
import requests
import time
import sqlite3
from sqlite3 import Error

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

DEBUG = False
VER_MAJOR = 1
VER_MINOR = 1

if DEBUG:
    fout = open("temp_log.txt", "a+")

url = 'http://wiki.alexzilla.com/sensors/s.php'
local_db = r"/opt/pi-sensor-client/sensordata.db"

print(f'Version {VER_MAJOR}.{VER_MINOR}')

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c, temp_f

def putDb(tmp_c):
    conn = None

    try:
        conn = sqlite3.connect(local_db)
        vals = (tmp_c, 'C', 1, 1)
        sql = """INSERT INTO temperature(degrees, units, ts, station_id, active) values(?, ?, datetime('now'), ?, ?);"""

        cursor = conn.cursor()
        cursor.execute(sql, vals)
        conn.commit()
        if DEBUG:
            print("temperature ", tmp_c, "C row_id -> ", cursor.lastrowid)
    except sqlite3.Error as e:
        print("Database error: %s" % e)
    except Exception as e:
        print("Exception in _query: %s" % e)

    finally:
        if conn:
            conn.close()
#return cursor.lastrowid

def main():
    while True:
        ts = datetime.datetime.utcnow().strftime("%Y-%m-%d %X")
        tmp_c = str(read_temp()[0])
        rv = None

        try:
            data = {
                'VER': '1.0',
                'TYPE': '1010',
                'SENSOR_DATA': ['2', tmp_c, 'C', ts]
            }
            rv = requests.post(url, json=data)
            print(rv.text)
        except requests.exceptions.HTTPError as errh:
            print("Http Error:", errh)
        except requests.exceptions.ConnectionError as errc:
            print("Error Connecting:", errc)
        except requests.exceptions.Timeout as errt:
            print("Timeout Error:", errt)
        except requests.exceptions.RequestException as err:
            print("OOps: Something Else", err)

        if DEBUG:
            fout.write(f'data: {data} [{rv.text}]\n')
            fout.flush()

        # if posted to remote server then do not save to local db
        if rv:
            putDb(tmp_c)

        time.sleep(60)

if __name__ == '__main__':
    main()

Create a service to start the client at boot and restart the client on failure.

$ sudo nano /etc/systemd/system/pi-sensor.service
[Unit]
Description=Pi Sensor Client Service.

[Service]
Type=simple
WorkingDirectory=/opt/pi-sensor-client
ExecStart=/opt/pi-sensor-client/venv/bin/python3 /opt/pi-sensor-client/pi-sensor-client.py
Restart=on-failure
RestartSec=15s

[Install]
WantedBy=multi-user.target

Enable the service

$ sudo systemctl enable pi-sensor.service

Start the service

$ sudo systemctl start pi-sensor.service

Check the status of the service

$ sudo systemctl status pi-sensor.service


If the service file is edited then systemctl loads updates with

$ sudo systemctl daemon-reload