#!/usr/bin/python import time import datetime from subprocess import Popen, PIPE import serial import os import urllib2 import ftplib #0=Program #1=Upload Data #2=Update Programmer #3=Show IP #4=Shut Down mode = 0 count_good = 0 count_bad = 0 running = False path = "/media/" dir_location = 0 dirs = [] primary = "" ser = serial.Serial("/dev/ttyACM0") ser.baudrate = 57600 time.sleep(1) ser.write("#DC\n") ser.write("#D000Starting...\n") time.sleep(1) def printMode(): ser.write("#DC\n") if (mode == 0): ser.write("#D000Program Device\n") elif (mode == 1): ser.write("#D000Upload Data\n") ser.write("#D001(Press Select)\n") elif (mode == 2): ser.write("#D000Update Programmr\n") ser.write("#D001(Press Select)\n") elif (mode == 3): ser.write("#D000IP Address:\n") cmd = "ip addr show eth0 | grep inet | awk '{print $2}' | cut -d/ -f1" p=Popen(cmd, shell=True, stdout=PIPE) output = p.communicate()[0] buf = "%s" %(output) ser.write("#D001") ser.write(buf) ser.write("\n") elif (mode == 4): ser.write("#D000Shut Down\n") ser.write("#D001(Press Select)\n") def readDir(): global dirs items = os.listdir( path ) newlist = [] for names in items: if names.endswith(".hex"): newlist.append(names) dirs = newlist def programDevice(): global primary global running global count_good global count_bad if (running == False): time.sleep(1) running = True ser.write("#L00\n") ser.write("#L21\n") ser.write("#D001Reading \n") p = Popen(["cc-tool", '-f', '-a'], stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() print stdout split_results = stdout.split('\n') if (split_results[1].find("No target detected")>=0): #need to try resetting the cc debugger? ser.write("#D000Reset\n") ser.write("#D001Programmer\n") p= Popen(["cc-tool", '--reset'], stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() print stdout pass elif (split_results[2].find("Unable to communicate")>=0): #device is screwed up? print "Unable to communicate" pass split2 = (split_results[2]).split(', ') primary = split2[1].split()[1] secondary = split2[2].split()[1] ser.write("#D001Writing to unit \n") p = Popen(["cc-tool", '-f', '-e', '-w', path + dirs[dir_location], '-v'], stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() print stdout split_results = stdout.split('\n') result = "1" ser.write("#L00\n") if (split_results[7].find("Completed")>=0): count_good += 1 ser.write("#L31\n") ser.write("#OP\n") else: result = "0" count_bad += 1 ser.write("#L11\n") f = open('/home/pi/programmer/db.txt','a') buf = "%s, %s, %s, %s\n" %(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'),primary, result,dirs[dir_location]) f.write(buf) f.close() buf = "Complete+%3d-%3d" %(count_good, count_bad) ser.write("#D001") ser.write(buf) ser.write("\n") def finishProgramming(): global running running = False ser.write("#L00\n") buf = " Ready +%3d-%3d" %(count_good, count_bad) ser.write("#D001") ser.write(buf) ser.write("\n") found_drive = False while found_drive == False: ser.write("#D001Insert Drive\n") items = os.listdir( "/media" ) for names in items: if(names!="SETTINGS" and names!="LM PNP" and names!="." and names!=".." and found_drive == False): path = path+names+"/" found_drive = True ser.write("#D001 \n") if (found_drive == False): time.sleep(5) try: printMode() readDir() ser.write("#D001") ser.write(dirs[dir_location]) ser.write("\n") while 1: try: data_raw = ser.readline(); #bytesToRead = ser.inWaiting() #if (bytesToRead>1): if (len(data_raw.strip())>0): #data_raw = ser.read(bytesToRead) print (data_raw.strip()) if (data_raw.strip() == "#BR"): mode = mode + 1 if (mode>4): mode = 0 readDir() printMode() elif (data_raw.strip() == "#BL"): mode = mode - 1 if (mode<0): mode = 4 if (mode == 0): readDir() printMode() elif (data_raw.strip() == "#BU" and mode==0): dir_location = dir_location + 1 if (dir_location >= len(dirs)): dir_location = 0 ser.write("#D000Program Device \n") ser.write("#D001") ser.write(dirs[dir_location]) for i in range(0,16-len(dirs[dir_location])): ser.write(" ") ser.write("\n") elif (data_raw.strip() == "#BD" and mode==0): dir_location = dir_location - 1 if (dir_location <0): dir_location = len(dirs)-1 ser.write("#D000Program Device \n") ser.write("#D001") ser.write(dirs[dir_location]) for i in range(0,16-len(dirs[dir_location])): ser.write(" ") ser.write("\n") elif (data_raw.strip() == "#OP1"): f = open('/home/pi/programmer/mac.txt','w') f.write(primary[-8:]) f.close() p = Popen(["lpr", '-P', 'DYMO', '-o', 'landscape', '-o', 'fit-to-page', '/home/pi/programmer/mac.txt'], stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() elif (data_raw.strip() == "#BS"): if (mode==4): ser.write("#DC\n") ser.write("#D001 Shutting Down\n") p=Popen(["shutdown",'-h','now'], stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate() ser.close() exit(0) elif (mode==2): ser.write("#D001 Downloading... \n") try: ser.write("#L00\n") ser.write("#L21\n") response = urllib2.urlopen("http://test.wyzgyz.com/quietyme/programmer/programmer.txt", timeout = 5) content = response.read() script_file = open("/home/pi/programmer/programmer.py",'w') script_file.write(content) script_file.close() ser.write("#D001 Arduino... \n") response = urllib2.urlopen("http://test.wyzgyz.com/quietyme/programmer/arduino.txt", timeout = 5) content = response.read() script_file = open("/home/pi/programmer/programmer.ino",'w') script_file.write(content) script_file.close() p = Popen(["make", 'upload'], stdout=PIPE, stderr=PIPE, cwd=r'/home/pi/programmer') stdout, stderr = p.communicate() time.sleep(2) ser.write("#L00\n") ser.write("#D000Update Programmr\n") ser.write("#D001Success.Reboot.\n") except urllib2.URLError as e: ser.write("#D001") ser.write(str(e)) ser.write("\n") elif (mode==1): try: session = ftplib.FTP('wyzgyz.com', 'quietyme', 'wonKAwonKA123') file = open('/home/pi/programmer/db.txt','rb') session.storbinary('STOR programmer/db-'+str(int(time.time()))+'.txt', file) file.close() session.quit() ser.write("#D001Success. \n") except Exception,e: ser.write("#D001") ser.write(str(e)) ser.write("\n") elif (mode==0): programDevice() finishProgramming() elif (data_raw.strip() == "#BP1"): if (mode==0): if (running==True): finishProgramming() programDevice() elif (data_raw.strip() == "#BP0"): if (mode==0): finishProgramming() else: print (data_raw.strip()) except KeyboardInterrupt: ser.close() exit(0) except Exception,e: print str(e) ser.write("#D000 Unknown Error\n") ser.write("#L00\n") ser.write("#L11\n") if (running == True): count_bad+=1 running = False print "Error" continue except Exception,e: print str(e) ser.close()