Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # coding: UTF-8
- # *************************************************************************************************************** #
- # ************ Project by CGO & AL ************ #
- # ****** all Rights ****** #
- # reserved #
- # -------> Super project <------- #
- # < Wedda Stäschion > #
- # *************************************************************************************************************** #
- # *************************************************************************************************************** #
- # Logging - Optionen: "True" wenn die Ausgabe erwünscht ist, "False" wenn nicht
- LOG_CELSIUS = True # Temperatur und evtl. Hitzeindex in °C
- LOG_FAHRENHEIT = False # Temperatur und evtl. Hitzeindex in °F
- LOG_HEATINDEX = True # Ausgabe des Hitzeindexes
- LOG_TO_STDIO = True # Ausgabe in der Standardausgabe (Kommandozeile)
- LOG_TO_FILE = True # Ausgabe in ein Log-File
- LOG_TO_SQL = True # Ausgabe in die MySQL Datenbank
- LOG_FILE = "./Log.txt" # Pfad und Dateinamen für das Logfile
- LOG_DIFFERENCE = 1 # Differenz in °C ab denen Geloggt wird
- LOG_TO_SYSLOG = True # Ausgabe ins Systemlog
- LOG_SQL_HOST = "127.0.0.1" # Ort Der MySQL Datenbank
- LOG_SQL_DBNAME = "HOTNWET" # Datenbankname
- LOG_SQL_USER = "tempuser" # Datenbankbenutzer
- LOG_SQL_PW = "allessuper" # Nutzerpasswort
- # SMS - Optionen:
- SMS_WHEN_HOT = True # SMS Versand wenn HOT_TEMP überschritten wird
- HOT_TEMP = 30.00 # Ab dieser Temperatur ist es zu heiß, und es wird evtl. eine Warnung per SMS versendet
- SMS_WHEN_COLD = True # SMS Versand wenn HOT_TEMP unterschritten wird
- COLD_TEMP = 24.00 # Ab dieser Temperatur ist es zu kalt, und es wird evtl. eine Warnung per SMS versendet
- PHONE_NUMBER = "+436643504618" # An diese Nummer wird die SMS versandt
- # *************************************************************************************************************** #
- import serial
- import os
- import datetime
- import mysql.connector
- import syslog
- from mysql.connector import errorcode
- # Parsefunktion die float werte aus einem CSV-String "inpstr"
- # (Comma Seperated Value (comma=;))ausließt,
- def parseinput(inpstr, values): # und in das übergebene Werte-Array "values" schreibt
- if (len(inpstr) < 1): #prüfen ob inpstr leer ist
- return False #wenn ja, abbruch mit False
- i = 0
- readdata=True
- while (readdata and (i < len(values))): #lese ein, solange Daten vorhanden sind
- #und noch Platz im values array ist
- try:
- x = inpstr.index(";") #suche den nächsten ;
- values[i]=float(inpstr[0:x]) #alles vor dem ersten Strichpunkt wird
- #extrahiert und in float umgewandelt
- inpstr=inpstr[x+1:len(inpstr)] #gerade eingelesene Daten und der ;
- #werden aus dem inpstr gelöscht
- i+=1
- except ValueError: #wenn ein Fehler auftritt (z.B: kein ; mehr gefunden)
- readdata = False #wird der Lesevorgang abgebrochen und mit True beendet
- return True
- def createlogline(values, timestamp=False, tabs=True): # Erzeugt einen Ausgabestring aus dem Wertearray und gibt diesen zurück
- output = ""
- if timestamp:
- dt = datetime.datetime.now();
- output += dt.strftime("%d.%m.%y %H:%M:%S")
- if tabs:
- output += "\t"
- else:
- output += ", "
- if LOG_CELSIUS or LOG_FAHRENHEIT:
- output += "Temperatur:"
- if LOG_CELSIUS:
- output += " " + str(values[1]) + "°C"
- if LOG_FAHRENHEIT:
- output += " " + str(values[2]) + "°F"
- if tabs:
- output += "\t"
- else:
- output += ", "
- output += "Luftfeuchtigkeit: " + str(values[0])
- if LOG_HEATINDEX and (LOG_CELSIUS or LOG_FAHRENHEIT):
- if tabs:
- output += "\t"
- else:
- output += ", "
- output += "Hitzeindex:"
- if LOG_CELSIUS:
- output += " " + str(values[3]) + "°C"
- if LOG_FAHRENHEIT:
- output += " " + str(values[4]) + "°F"
- return output
- def logtofile(values): # Loggt die Werte in eine Datei
- file = open(LOG_FILE, "a")
- file.write(createlogline(values, True)+"\n")
- file.close()
- return True
- def logtosys(values): # Loggt die Werte in das System-Log
- print ("logging to syslog")
- syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_LOCAL0)
- syslog.syslog(syslog.LOG_INFO, createlogline(values, False, False))
- syslog.closelog()
- print ("syslog complete")
- return True
- def logtosql(con, Values): # Log die Werte in eine My-SQL Datenbank
- cursor = con.cursor()
- querry = "INSERT INTO HOTNWET_LOG (LOG_TIMESTAMP, LOG_HUM, LOG_TEMPC, LOG_TEMPF, LOG_HIC, LOG_HIF)"+"\nVALUES(NOW(), "+str(Values[0])+", "+str(Values[1])+", "+str(Values[2])+", "+str(Values[3])+", "+str(Values[4])+");"
- cursor.execute(querry)
- con.commit()
- return True
- def logtostdio(values): # Gibt die Werte über die Standardausgabe (Kommandozeile) aus
- print (createlogline(values, True))
- return True
- def connecttosql(): # Baut die Verbindung zur MySQL-Datenbank auftritt
- OK = True
- try:
- cnx = mysql.connector.connect(user=LOG_SQL_USER, password=LOG_SQL_PW, host=LOG_SQL_HOST, database=LOG_SQL_DBNAME)
- return cnx # Alles Super, Mit MySQL-Datenbank verbunden, Datenbank vorhanden
- except mysql.connector.Error as err:
- if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: # Falscher Benutzer/Passwort
- print("Falscher MySQL Benutzer/Passwort, fahre fort ohne SQL-LOG-Funktion\n\n")
- LOG_TO_SQL = False
- elif err.errno == errorcode.ER_BAD_DB_ERROR: # Datenbank nicht vorhanden
- print("Datenbank existiert nicht, erstelle Database '"+ LOG_SQL_DBNAME + "'")
- try: # Erstelle Datenbank
- cnx = mysql.connector.connect(user=LOG_SQL_USER, password=LOG_SQL_PW, host=LOG_SQL_HOST)
- cur = cnx.cursor()
- cur.execute("CREATE DATABASE "+ LOG_SQL_DBNAME)
- print("Datenbank wurde erfolgreich erstellt")
- cur.close()
- except ValueError: # Datenbank Erstellung nicht erfolgreich
- print("Ein Fehler bei der Erstellung der Datenbank ist aufgetreten:")
- print (ValueError)
- print ("Setze Fort ohne SQL-LOG-Funktion")
- OK=False
- else: # Sonstige Fehler
- print ("Ein Fehler beim Verbindungsaufbau zur MySQL-Datanbank ist aufgetreten, wahrscheinlich hat der Benutzer '"+LOG_SQL_USER+"' nicht die erfolderlichen Berechtigungen:\n")
- print(err)
- print ("\nSetze Fort ohne SQL-LOG-Funktion\n\n")
- OK = False
- if OK:
- cur = cnx.cursor()
- try: # Prüfe ob Tabelle bereits vorhanden
- cur.execute("select * from HOTNWET_LOG")
- return cnx # Wenn Ja alles Super :)
- except mysql.connector.Error as err: # Wenn nein, Tabelle anlegen
- print ("\nTabelle HOTNWET_LOG nicht gefunden, erstelle Tabelle...")
- try:
- cur.execute("Create Table HOTNWET_LOG("+
- "\nLOG_ID BIGINT NOT NULL AUTO_INCREMENT, "+
- "\nLOG_TIMESTAMP DATETIME NOT NULL,"+
- "\nLOG_HUM FLOAT, "+
- "\nLOG_TEMPC FLOAT, "+
- "\nLOG_TEMPF FLOAT, "+
- "\nLOG_HIC FLOAT, "+
- "\nLOG_HIF FLOAT, "+
- "\nPRIMARY KEY (LOG_ID));")
- print ("\nTabelle HOTNWET_LOG wurde erfolgreich erstellt\n")
- return cnx
- except ValueError: # Fehler beim Erstellen der Tabelle
- print ("\nKeine Berechtigung zum Erstellen von Tabellen, setze fort ohne n SQL-LOG-Funktion")
- LOG_TO_SQL = False
- else:
- LOG_TO_SQL = False
- return
- def sendsms(smstext): #sendet eine SMS an die in der Konfiguraton eingetragene Nummer
- try:
- command = "sudo gammu sendsms TEXT "+ PHONE_NUMBER+" -text \""+smstext+"\""
- os.system(command)
- except ValueError:
- print ("Fehler beim SMS-Versand")
- # ---< Valar Morghulis! >---
- # *************************************************************************************************************** #
- # * Main Function Starts here * #
- # *************************************************************************************************************** #
- ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1,xonxoff=False, rtscts=False, dsrdtr=False)
- ser.flushInput() #Setup für die Serielle Kommunikation
- ser.flushOutput()
- werte=[0,0,0,0,0] #Initialisierung des Werte-Arrays
- lasttemp = -200000.0;
- cooleddown = True
- warmedup = True
- if LOG_TO_SQL:
- sqlcon=connecttosql()
- while True:
- rd = ser.readline().decode('utf-8')[:-1] #Zeile von Seriellen port einlesen
- if parseinput(rd, werte): #Zeile wird geparsed, und die Floatwerte in das Werte-Array gespeichert
- if lasttemp != werte[1] and (werte[1]- lasttemp >= LOG_DIFFERENCE or lasttemp - werte[1] >= LOG_DIFFERENCE):
- if LOG_TO_FILE:
- logtofile(werte)
- if LOG_TO_SQL:
- logtosql(sqlcon, werte)
- if LOG_TO_SYSLOG:
- logtosys(werte)
- if LOG_TO_STDIO:
- logtostdio(werte)
- if werte[1] >= HOT_TEMP: #Prüfen ob die Temperatur zu heiss ist
- if LOG_TO_STDIO:
- print("Warnung, HOT IN HERE!")
- if cooleddown and SMS_WHEN_HOT: # Is ist gerade erst zu heiß geworden, eine SMS wird versandt
- sendsms("Achtung, es ist zu heiß")
- cooleddown = False
- elif cooleddown == False and SMS_WHEN_HOT: # Es ist gerade erst wieder kühler geworden
- sendsms("Temperatur wieder normal, alles ist gut :)")
- cooleddown = True
- if werte[1] <= COLD_TEMP: #Prüfen ob die Temperatur zu kalt ist
- if LOG_TO_STDIO:
- print "Heat me UP, I'm Freezing"
- if warmedup and SMS_WHEN_COLD: # Is ist gerade erst zu kalt geworden, eine SMS wird versandt
- sendsms("Achtung, es ist zu kalt")
- warmedup = False
- elif warmedup == False and SMS_WHEN_COLD: # Es ist gerade erst wieder wärmer geworden
- sendsms("Temperatur wieder normal, alles ist gut :)")
- warmedup = True
- lasttemp = werte[1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement