#!/usr/bin/env python
# Log wifi strength for our routers
# 2020-04-14 Original version
# 2020-04-23 changed name to start with PI_
# 2020-07-01 Option to run once or continuously
# 2020-11-12 Save strength and address
# 2020-11-17 Show adress of connected access point
# 2020-11-28 Save line if no connection found

from __future__ import print_function
import sys
import subprocess
import time
import MySQLdb

interface = "wlan0"          # Used Wifi connection
Server="localhost"           # Server for database
Version="1.0 28-11-2020"     # Version of program
Program="PI_wifistrength.py" # Name of program
WaitSec=360                  # Number of seconds to wait between scans
RPi = "RPi"                  # Name of this RPi
DoPrint=0                    # Print Debug information
DoSleep=1                    # Wait for database to start up
DoLoop=0                     # Continue to run
CurrentAccessPoint=""        # Access point currently in use
#
# 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
  global DoLoop
  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=='t') or (c=='T')):        
        if waarde>=0 and waarde<=1: 
          DoLoop=waarde
          if (len(tekst)==0): DoLoop=1; 
          print("DoLoop=",DoLoop)
      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) -t(Timeloop) -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 FindAccessPoints():

    NumberFound=0
    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()
    except:
      eprint(timestr,"\tWifistrength\tError opening database\t",sql) 
      # save the signal strengths
    for cell in cells:
       Name=cell[5][7:-1]
       if ( (0<=cell[5].find("RouterGang")) or (0<=cell[5].find("SitecomBeneden")) or (0<=cell[5].find("wifipr")) ) : 
         NumberFound=NumberFound+1
         Address=cell[0][-17:]
         Channel=cell[1][8:]
         Frequency=cell[2][21:-1]
         Strength=cell[3][-7:-4]
         Encryption=cell[4][15:]
         Bitrates=cell[6][10:]
         #eprint("Address: ",Address);
         #eprint("Channel: ",Channel);
         #eprint("Frequency: ",Frequency);
         #eprint("Strength: ",Strength);
         #eprint("Encryption: ",Encryption);
         #eprint("Name: ",Name);
         #eprint("Bitrates: ",Bitrates);
         Current=""
         if (Address==CurrentAccessPoint) : Current="*"
         sql="INSERT INTO wifi_pi(Datum,RPi,SSID,Strength,Address,Current) VALUES('%s','%s','%s','%s','%s','%s')" % (timestr,RPi,Name,Strength,Address,Current)
         try:
           cursor.execute(sql)
           db.commit()
           if (Address==CurrentAccessPoint) : 
             print (sql,"*")
           else : print(sql)
         except :
           eprint(timestr,"\tWifistrength\tError writing to database\t",sql) 
       else :
         if (DoPrint>1) and (len(Name)>1) : eprint("Found ", Name) 
    # Save line if none found
    if (NumberFound==0):
       sql="INSERT INTO wifi_pi(Datum,RPi,SSID,Strength,Address,Current) VALUES('%s','%s','%s','%s','%s','%s')" % (timestr,RPi,"None","0","None","")
       try:
         cursor.execute(sql)
         db.commit()
       except :
         eprint(timestr,"\tWifistrength\tError writing to database\t",sql) 
    # close the connection
    db.close()
    

def FindCurrentAccessPoint():
    global CurrentAccessPoint  
    proc = subprocess.Popen(["iwgetid", interface, "-a"],stdout=subprocess.PIPE, universal_newlines=True)
    out, err = proc.communicate()
    CurrentAccessPoint="None"
    
    for line in out.split("\n"):
        if (len(line)>0): 
          CurrentAccessPoint=line[-17:]
          eprint("Connected to =",CurrentAccessPoint)

  
    
#------------------------------------------------------------------------------
# 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)


# Loop reading and saving, end by pressing ^C.
try: 
  while True :  
    
    # 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)

    # Save and show measured values
    FindCurrentAccessPoint()
    FindAccessPoints()

    if (DoLoop==0) : 
      if DoPrint>0: print('Not looping.')
      break;
    
    # Wait WaitSec seconds for next read
    if DoPrint>0: print(timestr,'\tWaiting ',WaitSec,' seconds...')
    time.sleep(WaitSec)

except KeyboardInterrupt:
    if (DoPrint>0) :
      print(" Pressed... Ending program.")
      DoLoop=0;

#Einde programma
if DoPrint>0: print ('Program ended')
