# /var/www/py/flora001.py *****************************************************
# Created by: HARB rboek2@gmail.com august 2018 GPL copyrights                
# Prepaired and optimized for use with Python 3


# IMPORT LIBRARIES install like: pip install --upgrade psycopg2 --user ********
import platform                        #needed to check if we are using Python3
import psycopg2             #Needed to communicate with any PostgreSQL database
import datetime                #Needed to create a timestamp for the datarecord
import time           #Needed to be able to perform the request every 5 minutes
import requests                           #Simplest internet reader for Python3

python_version=platform.python_version()                #Actual version request
print ("De gebruikte versie van Python is:", python_version)      #Show to user




while True: #Meaning this loop will run forever *******************************
   # This is a list of all the data that will be written into the database when
   # stations are not activated.    All stations must be asked in one sequence.

   now = datetime.datetime.now()                          #Read the system time
   stampz    = now.strftime("%Y-%m-%d %H:%M:%S")   #Format to a database format

   conn = psycopg2.connect(host="localhost",database="robotigs", 
      user="richard", password="Ha-8-H+")        #Create a database connection
   cur1 = conn.cursor()                       #Create a thread to the database
   cur1.execute("""SELECT *  
                     FROM florastations 
                 ORDER BY name""")                     #Define database action
   rows = cur1.fetchall()                             #Perform database action

   print ("\n" + stampz)
   for row in rows:                  #Scan all the stations listed in the file
      print (" ",  row[3], " ",  row[2], " ", row[1],  " ",  row[4])



      #*** COUVEUSE ***********************************************************
      if row[2]==True and row[0]==1:   #Meaning this station is set to be activ
         myfile = "2005-08-01 01:01:01 -1 0 0 0 0 0"
         link = "http://" + row[3]                   #Calculate the entire link
         try:     #Make a provision for if the station does not answer properly
            r = requests.get(link)            
            myfile = (r.text)
         except:                       #If the station does not answer properly
            myfile = "2005-08-01 01:01:01 -1 0 0 0 0 0"
         datalist = myfile.split(' ')          #Splice the answer into an array
         propklokz = datalist[0] + " " + datalist[1]           #Assign the data
         proptmpz  = datalist[2]                               #Assign the data
         prophumz  = datalist[3]                               #Assign the data
         proprel1z = datalist[4]                               #Assign the data
         proprel2z = datalist[5]                               #Assign the data
         proprel3z = datalist[6]                               #Assign the data
         proprel4z = datalist[7]                               #Assign the data
         print (" t1=", proptmpz, " h1=", prophumz, " kl=", propklokz, " r1=",
                proprel1z, " r2=", proprel2z, " r3=", proprel3z, " r4=",
                proprel4z)




      #*** VOORDEUR ***********************************************************
      if row[2]==True and row[0]==2:   #Meaning this station is set to be activ
         myfile = "0 -1 0 0 0"
         link = "http://" + row[3] + ":9000"         #Calculate the entire link
         try:     #Make a provision for if the station does not answer properly
            r = requests.get(link)            
            myfile = (r.text)
         except:                       #If the station does not answer properly
            myfile = "0 -1 0 0 0"
         datalist = myfile.split(' ')          #Splice the answer into an array
         voorpir1z = datalist[0]                               #Assign the data
         voortmp1z = datalist[1]                               #Assign the data
         voorldr1z = datalist[2]                               #Assign the data
         voorhum1z = datalist[3]                               #Assign the data
         voorprg1z = datalist[4]                               #Assign the data
         if voortmp1z == "":
            voortmp1z = -1

         print (" p1=", voorpir1z, " t1=", voortmp1z, " ld=", voorldr1z, 
                " h1=", voorhum1z, " pg=", voorprg1z)




      #*** KWEEKKAS ***********************************************************
      if row[0]==3:                    #Station number 3 will be processed here  
         if row[2]==True:              #Meaning this station is set to be activ
            myfile = "2005-08-01 13:48:18 -1 -1 0 0 2 2 1 1 1 2 2 2"
            link = "http://" + row[3]                #Calculate the entire link
            try:  #Make a provision for if the station does not answer properly
               r = requests.get(link)            
               myfile = (r.text)
            except:                    #If the station does not answer properly
               myfile = "2012-08-01 13:48:18 -1 -1 0 0 2 2 1 1 1 2 2 2"

            datalist = myfile.split(' ')       #Splice the answer into an array
            kasklokz = datalist[0] + " " + datalist[1]         #Assign the data
            kastmpz  = datalist[2]                             #Assign the data
            kashumz  = datalist[3]                             #Assign the data
            kasldrz  = datalist[4]                             #Assign the data
            kaswatz  = datalist[5]                             #Assign the data
            kasrl2z  = datalist[6]                             #Assign the data
            kasrl3z  = datalist[7]                             #Assign the data
            kasmo1z  = datalist[8]                             #Assign the data
            mo1minz  = datalist[9]                             #Assign the data
            mo1maxz  = datalist[10]                            #Assign the data
            mo2valz  = datalist[11]                            #Assign the data
            mo2minz  = datalist[12]                            #Assign the data
            mo2maxz  = datalist[13]                            #Assign the data
            print (" t1=", kastmpz, " h1=", kashumz,  " ld=", kasldrz, 
                   " r1=", kaswatz, " kl=", kasklokz, " v1=", kasmo1z,
                   " i1=", mo1minz, " a1=", mo1maxz,  " v2=", mo2valz,
                   " i2=", mo2minz, " a2=", mo2maxz)
         else:
            kasklokz = "2005-08-01 13:48:18"                  #Assign fake data
            kastmpz  = -1                                     #Assign fake data
            kashumz  = -1                                     #Assign fake data
            kasldrz  = -1                                     #Assign fake data
            kaswatz  = -1                                     #Assign fake data           
            kasmo1z  = -1                                     #Assign fake data

         print (" =", myfile, "=  ")
         if kastmpz  == "":                            #Check for sensor errors
            kastmpz  = -2  



      #*** TUIN ***************************************************************
      if row[2]==True and row[0]==4:   #Meaning this station is set to be activ
         myfile = "2005-08-01 13:48:18 -1 524 0"
         link = "http://" + row[3] + ":9000"         #Calculate the entire link
         try:     #Make a provision for if the station does not answer properly
            r = requests.get(link)            
            myfile = (r.text)
         except:                       #If the station does not answer properly
            myfile = "2005-08-01 13:48:18 -1 524 0"
         datalist = myfile.split(' ')          #Splice the answer into an array
         tuinklokz = datalist[0] + " " + datalist[1]           #Assign the data
         tuintmpz  = datalist[2]                               #Assign the data
         tuinldrz  = datalist[3]                               #Assign the data
         tuinwatz  = datalist[4]                               #Assign the data
         print ("    ", tuintmpz, "    ", tuinldrz, "    ", tuinwatz, "    ", 
                tuinklokz)




      #*** SMELLY *************************************************************
      if row[2]==True and row[0]==5:   #Meaning this station is set to be activ
         myfile = "0 0 0 0"
         link = "http://" + row[3] + ":9000"         #Calculate the entire link
         try:     #Make a provision for if the station does not answer properly
            r = requests.get(link)            
            myfile = (r.text)
         except:                       #If the station does not answer properly
            myfile = "0 0 0 0"
         datalist = myfile.split(' ')          #Splice the answer into an array
         mq2z  = datalist[0]                                   #Assign the data
         mq3z  = datalist[1]                                   #Assign the data
         mq5z  = datalist[2]                                   #Assign the data
         mq9z  = datalist[3]                                   #Assign the data
         print ("    " , mq2z, "    ", mq3z, "    " , mq5z, "    " , mq9z)



   # WRITE DATA INTO DATABASE FLORAMEAS ***************************************
   #Now we have read all stations we can write the data into the database
   #First determin the first available free key in the file florameas
   cur2 = conn.cursor()
   cur2.execute("""SELECT mesid  
                     FROM florameas 
                 ORDER BY mesid DESC
                    LIMIT 1""")                         #Define database action
   rows2 = cur2.fetchall()	           #Read the latest entry of this table
   nextkey = 1                     #Just to cath an empty table of measurements
   for row2 in rows2:
      nextkey = row2[0]
      nextkey += 1
   #Now we can create a new measurement in the database table florameas
   cur2.execute(""" INSERT INTO florameas (
                   mesid
                 , stamp
                 , kastmp
                 , kashum
                 , kasldr
                 , kaswat
                 , kasklok
                 , tuintmp
                 , tuinldr
                 , tuinwat
                 , tuinklok
                 , proptmp
                 , prophum
                 , propklok
                 , proprel1
                 , proprel2
                 , proprel3
                 , proprel4
                 , voorpir1
                 , voortmp1
                 , voorldr1
                 , voorhum1
                 , mq5
                 , mq7
                 , mq8
                 , mq135
                 , moi1val
                 , moi1min
                 , moi1max
                 , moi2val
                 , moi2min
                 , moi2max
                 ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",(nextkey, stampz, kastmpz, kashumz, kasldrz, kaswatz, kasklokz, tuintmpz, tuinldrz, tuinwatz, tuinklokz, proptmpz, prophumz, propklokz, proprel1z, proprel2z, proprel3z, proprel4z, voorpir1z, voortmp1z, voorldr1z, voorhum1z, mq2z, mq3z, mq5z, mq9z, kasmo1z, mo1minz, mo1maxz, mo2valz, mo2minz, mo2maxz))
   conn.commit()

   cur2.close()                              #Close this thread to the database
   cur1.close()                              #Close this thread to the database
   conn.close()                          #Close this connection to the database
   print ("We gaan 5 minuten slapen")
   time.sleep(300)   #Just wait 5 minutes before performing this read out again
