Advertisement
evenjc

Raspberry Pi [Master node]

Apr 3rd, 2019
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.25 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # Importing modules
  4. import serial
  5. import time
  6. import datetime
  7.  
  8. # Definition of UNIX shell colors
  9. class bcolors:
  10.     HEADER = '\033[95m'
  11.     OKBLUE = '\033[94m'
  12.     OKGREEN = '\033[93m'
  13.     TEST = '\033[92m'
  14.     ENDC = '\033[0m'
  15.  
  16.  
  17. # Holder for active serial ports
  18. serialPorts = []
  19.  
  20. # Populated by the Ardunios by either "TIL" or "PUST"
  21. # This decides the name of the logfile for this arduino.
  22. typeOfSensorNode = []
  23.  
  24. # Holder for generated files
  25. filenames = []
  26. files = []
  27.  
  28. # messages[0] = '1' is used to ask the Arduino's for sensor data
  29. # messages[1] = '2' is used for probing each active serial port and checking for an answer 'PUST' or 'TIL'
  30. messages = ['1', '2']
  31.  
  32. # Time between each sensor log.
  33. # Change this if you want to alter the frequency of data transfers.
  34. timeBetweenDataTransfers = 10
  35.  
  36. # Number of connected devices.
  37. # Change if you want to add more or less sensor nodes.
  38. numberOfArduinoDevices = 2
  39.  
  40. # Serial Connection settings.
  41. # Do not change.
  42. baudrate = 9600
  43. parity = serial.PARITY_NONE
  44. stopbits = serial.STOPBITS_ONE
  45. bytesize = serial.EIGHTBITS
  46. timeout = 1
  47.  
  48. # Routine that probes the first 100 possible Arduino-COMs.
  49. # This routine populates serialPorts.
  50. def establishSerialConnections():
  51.     counter = 0
  52.     print(bcolors.OKGREEN + "\n--- Establishing serial connections ---" + bcolors.ENDC)
  53.     while (counter < 100):
  54.         try:
  55.             ser = serial.Serial(
  56.                 port= "/dev/ttyACM" + counter.__str__(),
  57.                 baudrate = baudrate,
  58.                 parity = parity,
  59.                 stopbits = stopbits,
  60.                 bytesize = bytesize,
  61.                 timeout = 1
  62.             )
  63.             serialPorts.append(ser)
  64.             ser.close()
  65.             ser.open()
  66.             print ("Found open device at /dev/ttyACM" + counter.__str__())
  67.            
  68.         except IOError:
  69.             None
  70.        
  71.         counter += 1
  72.     print(bcolors.OKGREEN + "--- Serial connections established --- \n\n" + bcolors.ENDC)
  73.    
  74. # Routine checking what type of sensorNode we found.
  75. # This routine populates typeOfSensoNodes.
  76. # It is also detrimental to ensure established connection.
  77. # If the number of established connections is not the number of expected Arduinos, the program will shut down.
  78. def checkDeviceConnectivity():
  79.     print(bcolors.OKGREEN + "--- Checking if devices are sensor nodes ---" + bcolors.ENDC)
  80.     establishedConnections = 0
  81.     for portNumber in range(0, numberOfArduinoDevices):
  82.         print ('Writing to Arduino at ' + serialPorts[portNumber].port.__str__())        
  83.         serialPorts[portNumber].write(messages[1])
  84.         recievedData = serialPorts[portNumber].readline()
  85.                
  86.        
  87.        
  88.         print("First package from Arduino is: " + recievedData)
  89.         if (recievedData == "TIL" or recievedData == "PUST"):
  90.             print ('We found a sensor node')
  91.             typeOfSensorNode.append(recievedData)
  92.             establishedConnections += 1
  93.        
  94.     print(bcolors.OKGREEN + "--- Done checking if devices are sensor nodes --- \n\n" + bcolors.ENDC)
  95.     if (establishedConnections == numberOfArduinoDevices):
  96.         return True
  97.     else:
  98.         return False
  99.  
  100. # Routine generating filenames, using typeOfSensorNode.
  101. # File names are hard coded to /home/pi/Desktop/log/filename.csv.
  102. # Each file is named with millisecond precision, meaning files will never generate the same names.
  103. def generateFileNames():
  104.     for device in range(0, numberOfArduinoDevices):
  105.         filenames.append("/home/pi/Desktop/log/"+typeOfSensorNode[device].__str__()+'_Arduino_nr_'+device.__str__()+'_'+datetime.datetime.now().__str__()+'.csv')
  106.         print ("Created file: " + filenames[device].__str__())
  107.  
  108. # Routine creating actual measurement files and fills in first two rows.
  109. def createMeasurementFiles():
  110.     print(bcolors.OKGREEN + "--- Generating measurement files ---" + bcolors.ENDC)
  111.     generateFileNames()
  112.     for device in range(0, numberOfArduinoDevices):
  113.         files.append(open(filenames[device], "w+"))
  114.         files[device].write('Date;Time;Temperature;Relative Humidity;CO2;Formaldehyde Start;Control;High bit;Low bit;Reserved;Reserved;High bit;Low bit;Checksum;PM1.0;PM2.5;PM4.0;PM10;NCPM0.5;NCPM1.0;NCPM2.5;NCPM4.0;NCPM10.0;Typical Particle Size')
  115.         files[device].write("\r\n")
  116.         files[device].close()
  117.     print(bcolors.OKGREEN + "--- Done generating measurement files --- \n\n" + bcolors.ENDC)
  118.  
  119.  
  120. # Function for reading from the nodes.
  121. # All write functionality here should at a later point be written in a writeToFile-routine.
  122. def readFromArduino_writeToFile():
  123.     for device in range(0, numberOfArduinoDevices):
  124.         print ('Reading from Arduino at ' + serialPorts[device].port.__str__())
  125.         recievedData = serialPorts[device].readline()
  126.         #print ("Recieved: " + recievedData.__str__())
  127.         if (recievedData != None):
  128.             print ('Read successfully from ' + serialPorts[device].port.__str__())
  129.         else:
  130.             print ('Failed')
  131.         files[device] = open(filenames[device], "a")
  132.         files[device].write(datetime.datetime.now().date().__str__())
  133.         files[device].write(";")
  134.         files[device].write(datetime.datetime.now().time().__str__())
  135.         files[device].write(recievedData)
  136.         files[device].write("\r\n")
  137.         files[device].close()
  138.  
  139. # Routine for writing a message to all the sensor nodes.    
  140. def writeToArduino(message):
  141.     for device in range(0, numberOfArduinoDevices):
  142.         serialPorts[device].write(message)
  143.        
  144.      
  145. establishSerialConnections()
  146. connection_established = checkDeviceConnectivity()
  147. createMeasurementFiles()
  148.  
  149. if connection_established:
  150.     print(bcolors.HEADER + "Connection is established, going into measurement mode \n \n" + bcolors.ENDC)
  151.     while True:
  152.         print(bcolors.OKGREEN + "--- Performing measurement ---" + bcolors.ENDC)
  153.         writeToArduino(messages[0])
  154.         readFromArduino_writeToFile()
  155.         print(bcolors.OKGREEN + "--- Measurement done --- \n\n" + bcolors.ENDC)
  156.         print((bcolors.TEST + "Waiting between measurements. Press CTRL+Z to exit \n\n" + bcolors.ENDC))
  157.         time.sleep(timeBetweenDataTransfers)
  158. else:
  159.     print ('Failed finding enough Arduino Devices, shutting down')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement