Advertisement
Guest User

Untitled

a guest
Sep 15th, 2017
512
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.01 KB | None | 0 0
  1. import serial # serial library
  2. import MySQLdb # MySQL library
  3. import time # Library containing time related functions. For example sleep()
  4. import Gnuplot # Library to interface with Gnuplot.
  5. import smtplib # Library for connecting to an smtp server to send email.
  6.  
  7.  
  8. ser = serial.Serial() #create serial connection
  9. ser.baudrate = 19200 # set baudrate
  10. device = "/dev/serial/by-id/usb-Silicon_Labs_Telegesis_USB_Device_02000F5E-if00-port0" #device name
  11. ser.port = device # set device name
  12. ser.timeout = 1 # Set a 1 second timeout. This must be set or communication wont work.
  13. ser.xonxoff = 0 # Disable flow control because our device does not use it.
  14. ser.open() # Open the serial port
  15.  
  16. sendamail = 0 #Initialize a variable for sending email
  17.  
  18. db = MySQLdb.connect(host="localhost", user="root", passwd="", db="zig") # Create connection to MySQL database at "localhost" as "root" user and with password. The database is also chosen to "zig"
  19. cursor = db.cursor()# Create a cursor for python to interface with the database
  20.  
  21. while 1==1:# Loop to make the program run for ever
  22.     #for runs in range(1, 3): # Performs two scans and writes before drawing graph and checking numbers. This is for debugging.
  23.  
  24.         readout = list()# Initialize list as a buffer for the serial port.
  25.         sqldata = list() # Initialize a list as a buffer for the SQL data.
  26.  
  27.         ser.write("AT+ESCAN\r\n") # Send a command. \r\n resemples the stop signs for the command and have to be there. Every thing ends with that also output.
  28.  
  29.         while len(readout) <= 1: # Run while the list is smaller than or equal to 1 to extend the 1 second timeout. Without this slow output will not be read. fx AT$
  30.                 readout = ser.readlines() # Write lines to buffer list.
  31.         print "escan " + str(runs) + " complete." # Debugging line to see that the program is working
  32.         #for item in readout: # Print each line in the list.
  33.                 #print item
  34.  
  35.  
  36.         for item in readout: # Runs for each item in the readout list.
  37.                 for I in range(11, 27): # Counts between 11 to 26
  38.                         if item.startswith(str(I)): # checks if I from for loop is equal to the first two characters in the item from readout.
  39.                                 #print item[3:]
  40.                     sqldata.append(int(item[3:], 16)-127)# If the item starts with one of the numbers in the for loop, the channelname will be filtered our and the energy will be converted from hex to dec and -127 to get the absolute value. It is then stored in SQL buffer.
  41.  
  42.         cursor.execute("insert into escan_data (ch_11, ch_12, ch_13, ch_14, ch_15, ch_16, ch_17, ch_18, ch_19, ch_20, ch_21, ch_22, ch_23, ch_24, ch_25, ch_26) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" ,(sqldata[0], sqldata[1], sqldata[2], sqldata[3], sqldata[4], sqldata[5], sqldata[6], sqldata[7], sqldata[8], sqldata[9], sqldata[10], sqldata[11], sqldata[12], sqldata[13], sqldata[14], sqldata[15]))
  43.         # Query to SQL to save the recorded data from sqldata. First part is SQL, second part is the reference to python variables. Third part is the python variables (sqldata)
  44.         del readout# Remove readout to clear the list.
  45.         del sqldata # Remove sqldata to clear the list     
  46.    
  47.         #time.sleep(10)  # Delay before continuing. This is done to make sure that the dongle is ready again and that all data have been wread to the database. Only used for debugging.
  48.    
  49.     gp = Gnuplot.Gnuplot(persist=1)  # Initialize Gnuplot
  50.     gp('set style data lines') # Set the style to plot. In this case it will use lines. Could also be histogram and more.
  51.     gp('set term png') # Set Gnuplot to generate a png file instread of displaying the graph.
  52.     gp('set output "/var/www/escan_graph.png"') # Sets output directory. In this case it writes to a webserver.
  53.     gp('set yrange [0:100]') # Limits y axis from 0 to 100 because we do not go above or below.
  54.    
  55.    
  56.     cursor.execute("select * from escan_data order by scan_id desc limit 20") # Read database but only take the 20 highest scan_ids. We only want to graph the latest data.
  57.     numrows = int(cursor.rowcount) # Count how many rows of data we have.
  58.    
  59.     xa = list() # Initialize x axis data
  60.     ya = list() # Initialize y axis data
  61.  
  62.     for x in range(0,numrows): # Loop for number of rows.
  63.         row = cursor.fetchone() # Read a row from database
  64.         xa.append(row[0]) # Adds scan_is as x coordinate
  65.         ya.append(row[1]) # Adds energy level as y coordinate.
  66.         if x == 0:              # Check the first value fetched from the database. This will alsways be the latest update from escan and therefor the newest value because we fetch and sort by 20.
  67.             if int(row[1]) < 55: # Check if data is below a predefined limit.
  68.                 sendamail = 1   # set sendmail = 1 if data value is below preset point.
  69.                 print "Something is wrong" # Debugging to see íf the program works.
  70.                 print int(row[1])   # Prints the number that have triggered the alarm.
  71.  
  72.     databuff = Gnuplot.Data(xa, ya, title = "ESCAN") # Converts the data into Gnuplot data. Also sets title for the graph.
  73.     gp.plot(databuff) # Tells Gnuplot to plot the data.
  74.  
  75.     # Removes a bunch of variables here to reset them.
  76.     del xa
  77.     del ya
  78.     del databuff
  79.     del row
  80.    
  81.     print "Graph generated" # Debugging message
  82.    
  83.     if sendamail == 1: # Initiate smtp client if sendmail = 1
  84.         print "mail" # Debugging message
  85.  
  86.         fromaddr = 'theblahblah2001@gmail.com' # Sender address
  87.         toaddrs  = 'blazehook@gmail.com' # Reciever address
  88.         msg = 'Testing python to send mail through gmail!' # Message content
  89.        
  90.         username = 'theblahblah2001' # Username
  91.         password = ''                           # Password
  92.  
  93.         server = smtplib.SMTP('smtp.gmail.com:587') # address to the smtp server. Here we use gmail.
  94.         server.starttls()   # Start tls (Transport Layer Security). Enables secure connection.
  95.         server.login(username,password) # logs in with previously set username and password.
  96.         server.sendmail(fromaddr, toaddrs, msg) # Sends mail with previously set sender, reciever and message.
  97.         server.quit() # Quits the smtp connection.
  98.  
  99.         sendamail = 0 # Sets sendmail to 0 to prevent email loop.
  100.  
  101. ser.close() # Close the serial connection. Currently unused because the program never ends.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement