Initial node
This commit is contained in:
1
config.json
Normal file
1
config.json
Normal file
@@ -0,0 +1 @@
|
||||
{"name": "Blue", "server_address": "http://192.168.1.239:5000", "id": 1, "delay": 5}
|
||||
@@ -1 +1,2 @@
|
||||
Adafruit-DHT==1.4.0
|
||||
requests==2.28.1
|
||||
|
||||
57
src/main.py
57
src/main.py
@@ -1,17 +1,68 @@
|
||||
import Adafruit_DHT
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import requests
|
||||
import time
|
||||
|
||||
DHT_SENSOR = Adafruit_DHT.DHT11
|
||||
DHT_PIN = 4
|
||||
|
||||
CONFIG_PATH = "./config.json"
|
||||
|
||||
def register_id(config: dict) -> int:
|
||||
url = f"{config['server_address']}/api/register"
|
||||
register_data = {"name": config["name"]}
|
||||
|
||||
response = requests.post(url, json = register_data)
|
||||
if not response.ok:
|
||||
raise Exception(f"Register: server returned {response.status_code}: {response.reason}")
|
||||
|
||||
return int(response.text)
|
||||
|
||||
def load_config() -> dict:
|
||||
with open(CONFIG_PATH, "rt") as config_file:
|
||||
return json.load(config_file)
|
||||
|
||||
def update_config(config: dict):
|
||||
with open(CONFIG_PATH, "wt") as config_file:
|
||||
json.dump(config, config_file)
|
||||
|
||||
def post_reading(config: dict, humidity: float, temperature: float):
|
||||
url = f"{config['server_address']}/api/{config['id']}/reading"
|
||||
reading_data = {"humidity": humidity, "temperature": temperature}
|
||||
|
||||
response = requests.post(url, json = reading_data)
|
||||
if not response.ok:
|
||||
if response.status_code == 403:
|
||||
print("Unauthorised: Trying to re-register")
|
||||
config["id"] = register_id(config)
|
||||
update_config(config)
|
||||
raise Exception(f"Reading: server returned {response.status_code}: {response.reason}")
|
||||
|
||||
def main():
|
||||
config = load_config()
|
||||
|
||||
if config["id"] == 0:
|
||||
config["id"] = register_id(config)
|
||||
|
||||
update_config(config)
|
||||
|
||||
sensor_fail_count = 0
|
||||
post_fail_count = 0
|
||||
while True:
|
||||
humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
|
||||
if humidity is not None and temperature is not None:
|
||||
print(f"Temperature: {temperature}C, Humidity: {humidity}%")
|
||||
try:
|
||||
post_reading(config, humidity, temperature)
|
||||
except Exception as e:
|
||||
print(e.message) # Continue for now
|
||||
sensor_fail_count = 0
|
||||
else:
|
||||
print("Sensor failure")
|
||||
time.sleep(3)
|
||||
sensor_fail_count = sensor_fail_count + 1
|
||||
print(f"Sensor reading failed {sensor_fail_count} times.")
|
||||
|
||||
time.sleep(config["delay"])
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user