#!usr/bin/python # arduino_stream.py # service to write the arduino measuring data from USB input # to a file, webserver can show by PHP # KLL engineering 2013 01 08 # change 1 minute file to ramdisk # change database filename arduinodb year month day .csv ( new day, new file ) # except statement still not work??? 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(): sfiledata="/run/shm/arduinodata.csv" # one actual record syear = time.strftime("%Y") smonth = time.strftime("%m") sday = time.strftime("%d") sfiledb="/var/www/arduinodb" + syear + smonth + sday + ".csv" # of max 1440 minute values foldtime = time.time() fnewtime = time.time() fstore = 100.0 # sec while ser.isOpen() : measureline = ser.readline() stime=time.strftime(",%Y,%m,%d,%H,%M,%S,") # get timing for store data to file fnewtime = time.time() fdtime = fnewtime-foldtime sdatline = stime + measureline # print sdatline + " dt: " + str(fdtime) # diagnostic if fdtime >= fstore: # only store every "fstore" seconds foldtime = fnewtime fdat = open(sfiledata,"w") # open w file for write only one line fdat.write(sdatline) fdat.close() # close the file fdatb = open(sfiledb,"a") # open a file for append fdatb.write(sdatline) fdatb.close() # close the file # print sdatline # temporary show 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() # print " looks good" read_save() ser.close() # except serial.SerialException: except Exception as ex: print "Failed to connect to port on: ", ser raise ex # print " serial problem " ser.close() pass time.sleep(1) # give time print "end"