Advertisement
Guest User

firstpasta

a guest
Dec 13th, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.60 KB | None | 0 0
  1. # coding: UTF-8
  2. # *************************************************************************************************************** #
  3. #                                  ************  Project by CGO & AL  ************                                #
  4. #                                          ******    all Rights    ******                                         #
  5. #                                                     reserved                                                    #
  6. #                                        ------->   Super project   <-------                                      #
  7. #                                                < Wedda Stäschion >                                              #
  8. # *************************************************************************************************************** #
  9.  
  10. # *************************************************************************************************************** #
  11. # Logging - Optionen:  "True" wenn die Ausgabe erwünscht ist, "False" wenn nicht
  12. LOG_CELSIUS = True          # Temperatur und evtl. Hitzeindex in °C
  13. LOG_FAHRENHEIT = False      # Temperatur und evtl. Hitzeindex in °F
  14. LOG_HEATINDEX = True        # Ausgabe des Hitzeindexes
  15. LOG_TO_STDIO = True         # Ausgabe in der Standardausgabe (Kommandozeile)
  16. LOG_TO_FILE = True          # Ausgabe in ein Log-File
  17. LOG_TO_SQL = True           # Ausgabe in die MySQL Datenbank
  18. LOG_FILE = "./Log.txt"      # Pfad und Dateinamen für das Logfile
  19. LOG_DIFFERENCE = 1          # Differenz in °C ab denen Geloggt wird
  20. LOG_TO_SYSLOG = True        # Ausgabe ins Systemlog
  21. LOG_SQL_HOST = "127.0.0.1"  # Ort Der MySQL Datenbank
  22. LOG_SQL_DBNAME = "HOTNWET"  # Datenbankname
  23. LOG_SQL_USER = "tempuser"   # Datenbankbenutzer
  24. LOG_SQL_PW = "allessuper"   # Nutzerpasswort
  25.  
  26. # SMS - Optionen:
  27. SMS_WHEN_HOT = True         # SMS Versand wenn HOT_TEMP überschritten wird
  28. HOT_TEMP = 30.00            # Ab dieser Temperatur ist es zu heiß, und es wird evtl. eine Warnung per SMS versendet
  29. SMS_WHEN_COLD = True        # SMS Versand wenn HOT_TEMP unterschritten wird
  30. COLD_TEMP = 24.00           # Ab dieser Temperatur ist es zu kalt, und es wird evtl. eine Warnung per SMS versendet
  31. PHONE_NUMBER = "+436643504618"  # An diese Nummer wird die SMS versandt
  32. # *************************************************************************************************************** #
  33.  
  34. import serial
  35. import os
  36. import datetime
  37. import mysql.connector
  38. import syslog
  39. from mysql.connector import errorcode
  40.  
  41.                                                 # Parsefunktion die float werte aus einem CSV-String "inpstr"
  42.                                                 # (Comma Seperated Value (comma=;))ausließt,
  43. def parseinput(inpstr, values):                 # und in das übergebene Werte-Array "values" schreibt                                             
  44.                                                
  45.     if (len(inpstr) < 1):                       #prüfen ob inpstr leer ist
  46.         return False                            #wenn ja, abbruch mit False
  47.     i = 0
  48.     readdata=True    
  49.     while (readdata and (i < len(values))):     #lese ein, solange Daten vorhanden sind
  50.                                                 #und noch Platz im values array ist
  51.         try:
  52.             x = inpstr.index(";")               #suche den nächsten ;
  53.  
  54.             values[i]=float(inpstr[0:x])        #alles vor dem ersten Strichpunkt wird
  55.                                                 #extrahiert und in float umgewandelt
  56.  
  57.             inpstr=inpstr[x+1:len(inpstr)]      #gerade eingelesene Daten und der ;                                            
  58.                                                 #werden aus dem inpstr gelöscht
  59.             i+=1
  60.         except ValueError:                      #wenn ein Fehler auftritt (z.B: kein ; mehr gefunden)                                    
  61.             readdata = False                    #wird der Lesevorgang abgebrochen und mit True beendet
  62.     return True
  63.        
  64. def createlogline(values, timestamp=False, tabs=True):  # Erzeugt einen Ausgabestring aus dem Wertearray und gibt diesen zurück
  65.     output = ""
  66.    
  67.     if timestamp:
  68.         dt = datetime.datetime.now();
  69.         output += dt.strftime("%d.%m.%y %H:%M:%S")
  70.         if tabs:
  71.             output += "\t"
  72.         else:
  73.             output += ", "
  74.            
  75.     if LOG_CELSIUS or LOG_FAHRENHEIT:
  76.         output += "Temperatur:"
  77.         if LOG_CELSIUS:
  78.             output += " " + str(values[1]) + "°C"         
  79.         if LOG_FAHRENHEIT:
  80.             output += " " + str(values[2]) + "°F"         
  81.         if tabs:
  82.             output += "\t"
  83.         else:
  84.             output += ", "
  85.            
  86.     output += "Luftfeuchtigkeit: " + str(values[0])
  87.            
  88.     if LOG_HEATINDEX and (LOG_CELSIUS or LOG_FAHRENHEIT):
  89.         if tabs:
  90.             output += "\t"
  91.         else:
  92.             output += ", "
  93.         output += "Hitzeindex:"
  94.         if LOG_CELSIUS:
  95.             output += " " + str(values[3]) + "°C"
  96.         if LOG_FAHRENHEIT:
  97.             output += " " + str(values[4]) + "°F"
  98.    
  99.     return output
  100.        
  101. def logtofile(values):                          # Loggt die Werte in eine Datei
  102.     file = open(LOG_FILE, "a")
  103.     file.write(createlogline(values, True)+"\n")
  104.     file.close()
  105.    
  106.  
  107.     return True
  108.  
  109. def logtosys(values):                           # Loggt die Werte in das System-Log
  110.     print ("logging to syslog")
  111.     syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_LOCAL0)
  112.    
  113.     syslog.syslog(syslog.LOG_INFO, createlogline(values, False, False))
  114.     syslog.closelog()
  115.     print ("syslog complete")
  116.     return True
  117.    
  118. def logtosql(con, Values):                      # Log die Werte in eine My-SQL Datenbank
  119.  
  120.     cursor = con.cursor()  
  121.     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])+");"
  122.     cursor.execute(querry)
  123.     con.commit()               
  124.     return True
  125.  
  126. def logtostdio(values):                         # Gibt die Werte über die Standardausgabe (Kommandozeile) aus
  127.     print (createlogline(values, True))
  128.        
  129.     return True
  130.    
  131. def connecttosql():                             # Baut die Verbindung zur MySQL-Datenbank auftritt
  132.     OK = True
  133.    
  134.     try:
  135.         cnx = mysql.connector.connect(user=LOG_SQL_USER, password=LOG_SQL_PW, host=LOG_SQL_HOST, database=LOG_SQL_DBNAME)
  136.         return cnx                              # Alles Super, Mit MySQL-Datenbank verbunden, Datenbank vorhanden
  137.     except mysql.connector.Error as err:       
  138.         if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:   # Falscher Benutzer/Passwort
  139.             print("Falscher MySQL Benutzer/Passwort, fahre fort ohne SQL-LOG-Funktion\n\n")
  140.             LOG_TO_SQL = False
  141.         elif err.errno == errorcode.ER_BAD_DB_ERROR:        # Datenbank nicht vorhanden
  142.             print("Datenbank existiert nicht, erstelle Database '"+ LOG_SQL_DBNAME + "'")
  143.             try:                                            # Erstelle Datenbank
  144.                 cnx = mysql.connector.connect(user=LOG_SQL_USER, password=LOG_SQL_PW, host=LOG_SQL_HOST)
  145.                 cur = cnx.cursor()
  146.                 cur.execute("CREATE DATABASE "+ LOG_SQL_DBNAME)
  147.                 print("Datenbank wurde erfolgreich erstellt")
  148.                 cur.close()
  149.            
  150.             except ValueError:                              # Datenbank Erstellung nicht erfolgreich
  151.                 print("Ein Fehler bei der Erstellung der Datenbank ist aufgetreten:")
  152.                 print (ValueError)
  153.                 print ("Setze Fort ohne SQL-LOG-Funktion")
  154.                 OK=False
  155.         else:                                               # Sonstige Fehler
  156.             print ("Ein Fehler beim Verbindungsaufbau zur MySQL-Datanbank ist aufgetreten, wahrscheinlich hat der Benutzer '"+LOG_SQL_USER+"' nicht die erfolderlichen Berechtigungen:\n")
  157.             print(err)
  158.             print ("\nSetze Fort ohne SQL-LOG-Funktion\n\n")           
  159.             OK = False
  160.    
  161.     if OK:
  162.         cur = cnx.cursor()
  163.         try:                                                # Prüfe ob Tabelle bereits vorhanden
  164.             cur.execute("select * from HOTNWET_LOG")
  165.             return cnx                                      # Wenn Ja alles Super :)
  166.         except mysql.connector.Error as err:                # Wenn nein, Tabelle anlegen
  167.             print ("\nTabelle HOTNWET_LOG nicht gefunden, erstelle Tabelle...")
  168.            
  169.             try:
  170.                 cur.execute("Create Table HOTNWET_LOG("+
  171.                 "\nLOG_ID BIGINT NOT NULL AUTO_INCREMENT, "+
  172.                 "\nLOG_TIMESTAMP DATETIME NOT NULL,"+
  173.                 "\nLOG_HUM FLOAT, "+
  174.                 "\nLOG_TEMPC FLOAT, "+
  175.                 "\nLOG_TEMPF FLOAT, "+
  176.                 "\nLOG_HIC FLOAT, "+
  177.                 "\nLOG_HIF FLOAT, "+
  178.                 "\nPRIMARY KEY (LOG_ID));")
  179.                 print ("\nTabelle HOTNWET_LOG wurde erfolgreich erstellt\n")       
  180.                 return cnx
  181.             except ValueError:                              # Fehler beim Erstellen der Tabelle
  182.                 print ("\nKeine Berechtigung zum Erstellen von Tabellen, setze fort ohne n       SQL-LOG-Funktion")
  183.                 LOG_TO_SQL = False
  184.     else:
  185.         LOG_TO_SQL = False
  186.                
  187.                    
  188.     return
  189.          
  190. def sendsms(smstext):                       #sendet eine SMS an die in der Konfiguraton eingetragene Nummer
  191.     try:
  192.         command = "sudo gammu sendsms TEXT "+ PHONE_NUMBER+" -text \""+smstext+"\""    
  193.         os.system(command)
  194.     except ValueError:
  195.         print ("Fehler beim SMS-Versand")
  196.    
  197.  
  198.  
  199.  
  200. # ---< Valar Morghulis! >---
  201.  
  202.  
  203. # *************************************************************************************************************** #
  204. # * Main Function Starts here                                                                                   * #
  205. # *************************************************************************************************************** #
  206.  
  207.  
  208. ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1,xonxoff=False, rtscts=False, dsrdtr=False)
  209. ser.flushInput()                                #Setup für die Serielle Kommunikation
  210. ser.flushOutput()          
  211. werte=[0,0,0,0,0]                               #Initialisierung des Werte-Arrays
  212. lasttemp = -200000.0;
  213. cooleddown = True
  214. warmedup = True
  215.  
  216. if LOG_TO_SQL:
  217.     sqlcon=connecttosql()
  218.  
  219. while True:
  220.  
  221.     rd = ser.readline().decode('utf-8')[:-1]    #Zeile von Seriellen port einlesen
  222.     if parseinput(rd, werte):                   #Zeile wird geparsed, und die Floatwerte in das Werte-Array gespeichert
  223.         if lasttemp != werte[1] and (werte[1]- lasttemp >= LOG_DIFFERENCE or lasttemp - werte[1] >= LOG_DIFFERENCE):
  224.             if LOG_TO_FILE:
  225.                 logtofile(werte)
  226.             if LOG_TO_SQL:
  227.                 logtosql(sqlcon, werte)
  228.             if LOG_TO_SYSLOG:
  229.                 logtosys(werte)
  230.             if LOG_TO_STDIO:
  231.                 logtostdio(werte)              
  232.             if werte[1] >= HOT_TEMP:    #Prüfen ob die Temperatur zu heiss ist
  233.                 if LOG_TO_STDIO:               
  234.                     print("Warnung, HOT IN HERE!")      
  235.                 if cooleddown and SMS_WHEN_HOT:         # Is ist gerade erst zu heiß geworden, eine SMS wird versandt
  236.                     sendsms("Achtung, es ist zu heiß")
  237.                     cooleddown = False
  238.             elif cooleddown == False and SMS_WHEN_HOT:      # Es ist gerade erst wieder kühler geworden
  239.                 sendsms("Temperatur wieder normal, alles ist gut :)")
  240.                 cooleddown = True
  241.                                        
  242.             if werte[1] <= COLD_TEMP:   #Prüfen ob die Temperatur zu kalt ist
  243.                 if LOG_TO_STDIO:
  244.                     print "Heat me UP, I'm Freezing"   
  245.                 if warmedup and SMS_WHEN_COLD:                  # Is ist gerade erst zu kalt geworden, eine SMS wird versandt
  246.                     sendsms("Achtung, es ist zu kalt")
  247.                     warmedup = False
  248.             elif warmedup == False and SMS_WHEN_COLD:               # Es ist gerade erst wieder wärmer geworden
  249.                 sendsms("Temperatur wieder normal, alles ist gut :)")
  250.                 warmedup = True
  251.             lasttemp = werte[1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement