#!/usr/bin/env python ## Process to read serial output from ES642 Dust Monitor ## Data is stored in daily files within the data directory ## Original code base written by Joe Young (University of Utah) for ceilometer use ## Slightly modified for air quality sensor use by Alex Jacques (University of Utah - April 2018) ## Code contact email: alexander.jacques@utah.edu ## Import Modules import serial, time, os, sys, datetime, subprocess ## Configurations for serial and output files configs = { "CODEDIR":"/home/pi/es642/code/", "DATADIR":"/home/pi/es642/data/", "BAUDRATE":9600, "BYTESIZE":8, "PORT":0, "FILENAME":"ES642", "DATEFMT":"%Y%m%d", "DELAY":0.5 } ## Check if process had been previously running, don't restart if it is running! statuscheck = subprocess.check_output("ps -ef | grep es642_data_read",shell=True).splitlines() stringcheck = 'python /home/pi/es642/code/es642_data_read.py' totalproc = 0 for eachproc in statuscheck: if(eachproc.find(stringcheck) == -1): skip = 1 else: print "Found process: "+eachproc+"\n" totalproc = totalproc + 1 print "Total processes: "+str(totalproc) if(totalproc > 1): print "Exiting" sys.exit() ## The dust monitor should be connected to the Pi using a USB-RS232 cable ## Loop through serial USB port listings and attempt to open port connection to USB-RS232 cable ser = serial.Serial() ser.baudrate = configs["BAUDRATE"] ser.bytesize = configs["BYTESIZE"] port = configs["PORT"] while port < 20: try: ser.port = '/dev/ttyUSB%i' % port print ser.port if not os.path.exists(ser.port): port += 1 continue ser.open() break # try no more! except serial.serialutil.SerialException as e: print e port += 1 if port == 20: print 'No valid USB serial port identified so exiting' sys.exit() print "Connected to a USB device on {}".format(ser.port) ## Now keep the USB port connection constantly open ## When a new serial message is received from the dust monitor, output the current UTC timestamp and the data message into the data file ob = '' while 1: ln = ser.readline() time.sleep(configs["DELAY"]) if not ln: continue if(len(ln) > 7): fileoutname = ("%s%s_%s.dat" % (configs["DATADIR"],configs["FILENAME"],datetime.datetime.utcnow().strftime(configs["DATEFMT"]))) fouthandle = open(fileoutname,'a') fouthandle.write(str(datetime.datetime.utcnow().strftime('%Y-%m-%d,%H:%M:%S,'))+str(ln)) fouthandle.close() sys.exit()