#!usr/bin/python # arduino_stream_PMS3.py # service to write the arduino measuring data from USB input # to a file, processing.. can read to show scope graph # KLL engineering 2013 11 20 import serial import time import glob # _________________________________________________________________ def scan(): """scan for available ports. return a list of device names.""" return glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*') # _________________________________________________________________ def read_save(): batchcount = -1 # init maxfile = 10 batchfull = 0 # init batchline = 0 # init lastlinecount = 0 foldtime = time.time() fnewtime = time.time() CSVpath = '/run/shm/' CSVname = 'PMS3_' CSVext = '.csv' pointfilename = '/run/shm/current.txt' filename = 'not saved' temp_list = [] # prepare array of recordlines while ser.isOpen() : sline = ser.readline() sline = sline.strip('\r') # arduino send CR + NL if len(sline) >5: # 0,0,0, shortest good line batchline = batchline +1 #print ( str(batchline) + ': ' + sline) temp_list.append(sline) if len(sline) > 15: # must be the header line new batch foldtime = fnewtime fnewtime = time.time() lastlinecount = batchline batchline = 0 # reset batchcount = batchcount +1 if batchcount > 0: # must be following batch after prog start filename = CSVpath + CSVname + str(batchcount) + CSVext fdat = open(filename,"w") # open w file for write only a for append for tline in temp_list: fdat.write(tline) fdat.close() # close the file fdatp = open(pointfilename,"w") fdatp.write(filename) # points to the actual datafile in ringbuffer fdatp.close() if batchcount == maxfile: batchcount = 0 pass # not very first headerline / fullbatch temp_list = [] # empty array? print ('batch finished see: ' +str(lastlinecount) +' lines, need ' + str(fnewtime-foldtime) + ' sec, saved to: ' + filename) #print temp_list pass # len>5 pass #while # _________________________________________________________________ if __name__=='__main__': print "Found ports:" for name in scan(): print name time.sleep(1) # give time to free ports sport = "/dev/ttyACM0" for inum in range(1,7): # try 3 times if inum == 4: sport = "/dev/ttyUSB0" # try 3 times # print str(inum) + " we test " + sport ser = serial.Serial(sport, 115200, timeout=60) # arduino is reset! # try to open try: ser.open() read_save() ser.close() except Exception as ex: print "Failed to connect to port on: ", ser raise ex ser.close() pass time.sleep(1) # give time print "end" # _________________________________________________________________