Skip to content

Instantly share code, notes, and snippets.

@vittodevit
Created January 25, 2021 18:34
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 vittodevit/3fb30320fd4ae3b68c3c34199feaf13b to your computer and use it in GitHub Desktop.
Save vittodevit/3fb30320fd4ae3b68c3c34199feaf13b to your computer and use it in GitHub Desktop.
Prende i dati di un sensore e li inserisce in un database
#File di configurazione, inserisci intervallo in secondi
db_address: localhost
db_port: 3306
db_user: root
db_pass: root
db_name: database
db_table: meteo
read_interval: 30
sensor_endpoint: http://sample.com/
#!/usr/bin/python3
import yaml
import mysql.connector
import time
import requests
from dateutil.parser import parse
from xml.dom import minidom
with open('config.yaml', 'r') as ymlconfig:
config = yaml.load(ymlconfig, Loader=yaml.FullLoader)
print("[i] Letto file di configurazione")
sqlink = mysql.connector.connect(
host=config["db_address"],
port=config["db_port"],
user=config["db_user"],
password=config["db_pass"],
database=config["db_name"]
)
q = sqlink.cursor()
q.execute("CREATE TABLE IF NOT EXISTS `" + config["db_table"] + "` (id_meteo int(10) NOT NULL auto_increment, date date NOT NULL, time time NOT NULL, temp float NOT NULL, press float NOT NULL, umidit float NOT NULL, PRIMARY KEY (id_meteo));")
print("[i] Connesso al database...")
def fetch():
xmldata = requests.get(config["sensor_endpoint"])
xdp = minidom.parseString(xmldata.text)
xml_date = xdp.getElementsByTagName("date")[0].firstChild.nodeValue
xml_time = xdp.getElementsByTagName("time")[0].firstChild.nodeValue
xml_temp = xdp.getElementsByTagName("temp")[0].firstChild.nodeValue
xml_press = xdp.getElementsByTagName("press")[0].firstChild.nodeValue
xml_umidit = xdp.getElementsByTagName("umidit")[0].firstChild.nodeValue
dt = parse(xml_date + ", " + xml_time)
insert = ("INSERT INTO `" + config["db_table"] + "` (date, time, temp, press, umidit) VALUES (%s, %s, %s, %s, %s);")
insertdata = (dt.date(), dt.time(), float(xml_temp), float(xml_press), float(xml_umidit))
q = sqlink.cursor()
q.execute(insert, insertdata)
sqlink.commit()
log = "[{}][{}] - Nuova lettura dal sensore: Temperatura={} C°, Pressione={} Kpa, Umidità={} %".format(xml_date, xml_time, xml_temp, xml_press, xml_umidit)
print(log)
while True:
fetch()
time.sleep(config["read_interval"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment