#!/usr/bin/env python
# Log wifi strength for our routers
# 2020-04-14 Original version

from __future__ import print_function
import sys
import subprocess
import time
import MySQLdb

interface = "wlan0"         # Used Wifi connection
RPi = "pi-test"             # Name of this RPi
Server="localhost"          # Server for database
Version="0.99 14-04-2020"   # Version of program
Program="wifistrength.py"   # Name of program
DoPrint=0                   # Print Debug information
DoSleep=1                   # Wait for database to start up
osec=0

#
# print to console or error device
#
def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

# Open database connection
def db_connect() :
  return MySQLdb.connect(Server,"verbruik","Verbruik1","wifi" )

# write to error database
def log_fout_pi(fout, var1, var2) :
  sql="INSERT INTO fout_pi(datum,program,fout,var1,var2) VALUES('%s','%s','%s','%s','%s')" % (timestr,Program,fout,var1,var2);
  # Open database connection, do the insert, and close the connection
  try:
    db = db_connect()
    cursor = db.cursor()
    cursor.execute(sql)
    db.commit()
    db.close()
  except:
    eprint(timestr,'\t', Program, '\tVersie  ',Version, '\tError writing to database\t',sql)

#
# Process parameters
#
def Do_Parameters():
  global DoPrint
  global DoSleep
  global RPi
  i=0
  toonhelp=0
  c=' ' 

  # Check command line for next argument
  i=1
  while i<len(sys.argv):
    parameter=sys.argv[i] # next possible switch
    j=0; c=' '
    if len(parameter)>0:
      c=parameter[0]
      j=1
      if (c=='-'): # skip possible '-' before switch
        if len(parameter) >1:
          c=parameter[1] # first char is switch command
          j=2
      tekst = parameter[j:] # remainder is switch value
      try:
        waarde = int(tekst) # check whether value is numeric
      except:
        waarde=0  
      if DoPrint>1: print(sys.argv[i],"=[",c,",tekst=[",tekst,"(",len(tekst),")], waarde=[",waarde,"]") # show results

      # Process switch if command is recognised
      if ((c=='d') or (c=='D')):        
        if waarde>=0 and waarde<=3: 
          DoPrint=waarde
          if (len(tekst)==0): DoPrint=1; 
          print("DoPrint=",DoPrint)
      elif  ((c=='q') or (c=='Q')):
        if ((waarde>=0) and (waarde<=1)): 
          DoSleep=1-waarde; 
          if (len(tekst)==0): DoSleep=0; 
          print("DoSleep=",DoSleep)
      elif ((c=='s') or (c=='S')):
          if (len(tekst)>0): RPi=tekst
          print("RPi=",RPi)
      else:  
        if (DoPrint>0): print("Unknown argument ",sys.argv[i],"=[",c,",[",tekst,"],",waarde,"]") # unrecognised switch, show help info
        toonhelp=1
    i+=1
   
  if (toonhelp==1):
     print(Program," -d(Debug) -q(Quickstart) -s(Server) -h(Help)")
# End Do_Parameters

def match(line,keyword):
    line=line.lstrip()
    length=len(keyword)
    if line[:length] == keyword:
        return line[length:]
    else:
        return None

def check():
    
    cells=[[]]

    proc = subprocess.Popen(["iwlist", interface, "scan"],stdout=subprocess.PIPE, universal_newlines=True)
    out, err = proc.communicate()

    for line in out.split("\n"):
        cell_line = match(line,"Cell ")
        if cell_line != None:
            cells.append([])
            line = cell_line[-27:]
        cells[-1].append(line.strip())

    cells=cells[1:]

    # Open database connection
    sql=""
    try:
      db=db_connect()
      cursor=db.cursor()
      # save the signal strengths
      for cell in cells:
         if ( (0<=cell[5].find("RouterGang")) or (0<=cell[5].find("SitecomBeneden")) ) : 
           Name=cell[5][7:-1]
           Strength=cell[3][-7:-4]
           sql="INSERT INTO wifi_pi(Datum,RPi,SSID,Strength) VALUES('%s','%s','%s','%s')" % (timestr,RPi,Name,Strength)
           cursor.execute(sql)
           db.commit()
           print(sql)
    except:
      eprint(timestr,"\tWifistrength\tError writing to database\t",sql) 
    # close the connection
    db.close()
    

#------------------------------------------------------------------------------
# Start program
#------------------------------------------------------------------------------

# Time of program start
lt = time.localtime(time.time())
timestr='%4i-%02i-%02i %02i:%02i:%02i' % (lt.tm_year,lt.tm_mon,lt.tm_mday,lt.tm_hour,lt.tm_min,lt.tm_sec)

# Print start of program to console or logfile
eprint(timestr,'\t',Program,'\tVersie  ',Version)

# Process command line arguments
Do_Parameters()

# Geef de database tijd om wakker te worden
if DoSleep==1:  time.sleep(60)

log_fout_pi("Started",Version,timestr)


DBOpen=0

# Loop reading and saving, end by pressing ^C.
try: 
  while True :  
    
    if (DBOpen==0):
      # Open database connection
      try:
        db = db_connect()
        cursor = db.cursor()
        DBOpen=1
        if DoPrint>0: print (timestr, '\t', "Opening Database")
      except:
        print (timestr, '\t', "Error Opening Database on " , Server)

    # Current time
    lt = time.localtime(time.time())
    timestr='%4i-%02i-%02i %02i:%02i:%02i' % (lt.tm_year,lt.tm_mon,lt.tm_mday,lt.tm_hour,lt.tm_min,lt.tm_sec)
    sec=1440*lt.tm_hour+60*lt.tm_min+lt.tm_sec # tel seconden van de huidige dag

    # Save and show measured values
    if (sec<osec) or (sec-osec>=60): 
      check()
      osec=1440*lt.tm_hour+60*lt.tm_min # triggerwaarde saven is begin van de minuut. 

    # Wait 20 seconds for next read
    time.sleep(20)

except KeyboardInterrupt:
    if DoPrint>0:
      print(" Pressed... Ending program.")

#Einde programma
db.close()
if DoPrint>0:
   print ('Program ended')
