def main(): arguments = docopt(__doc__, version='PyTach 0.1') config.arguments = arguments if arguments['--web']: web() elif arguments['--arduino']: arduino(arguments) elif arguments['--discover']: itach.discover() elif arguments['--devices']: list_devices() elif arguments['--activities']: list_activities() else: activity_device(arguments)
def __init__(self,com,speed,master=None): Frame.__init__(self, master) #runs the master object's init function self.grid(sticky=N+S+E+W) #allows the app to change shape self.ard = arduino.arduino(com,speed) self.master = master self.master.title("Zeroing") self.createWidgets() self.zeroes = []
def __init__(self,isCalibrated,com,speed,calibratedPath=None,master=None): Frame.__init__(self, master) #runs the master object's init function self.grid(sticky=N+S+E+W) #allows the app to change shape self.isCalibrated = isCalibrated self.calibratedPath = calibratedPath self.ard = arduino.arduino(com,speed,calibratedPath) self.nSensors = self.ard.nSensors() self.isQuit = False self.createWidgets() #creates all the pieces
def dance(self): import arduino from random import randint from time import sleep ard = arduino.arduino() for i in range(20): ard.send(randint(1, 5)) sleep(randint(2, 7)) ard.send(randint(50, 54)) sleep(randint(4, 10))
def __init__(self,nSensor,firstHeight,secondHeight,com,speed,master=None): Frame.__init__(self, master) #runs the master object's init function self.grid(sticky=N+S+E+W) #allows the app to change shape self.createWidgets() #creates all the pieces self.i = nSensor #which sensor to read self.firstHeight = firstHeight self.secondHeight = secondHeight self.firstReading = None self.secondReading = None self.kG = None self.kO = None self.arduino = arduino.arduino(com,speed)
def __init__(self, parent=None, device=None, *args, **kwargs): #Initialize TkInter frame and define parent tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent # variable for whether or not device is connected if device: self.device = device else: self.device = arduino() #generate UI elements self.create_serial_widgets(parent, "Instrument")
def main(noteValueEntries,sensorEntries,closeEvent,isWinSound,com,speed,zeros,debug=False): '''the main show. This is run in parallel to the gui when the start button is pressed. This thread has control of multiple threads (one per sensor). When the gui sends a signal through event, it ends this thread''' numberSensors = len(sensorEntries) taskDoneEvents = [] distanceQueues = [] noteThreads = [] #the thread on which the note waits for the event for i in xrange(numberSensors): #creates all the threads and events taskDoneEvents.append(threading.Event()) distanceQueues.append(Queue.Queue()) taskDoneEvents[i].set() #must start set newThread = threading.Thread(target=playNote, args=(sensorEntries[i], noteValueEntries, distanceQueues[i], taskDoneEvents[i], isWinSound, debug)) noteThreads.append(newThread) for thread in noteThreads: thread.start() #starts each thread ard = arduino.arduino(com,speed) while not closeEvent.isSet(): #this runs as long as the event is not set #the event comes from the thread that started this #thread. ## if debug: print 'getting ranges...', sensorReading = ard.getRawRanges() #calibration for i in xrange(len(sensorReading)): sensorReading[i] = sensorReading[i] - zeros[i] ## if debug: print 'got' #runs for every sensor ## if debug: print 'sending...', for i in xrange(numberSensors): if sensorReading[i] > 50: #if it picks up a reading between 0 and 40 ## if debug: print 'sensor',i,sensorReading[i] if taskDoneEvents[i].isSet(): #checks to see if the thread has finished playing the last note taskDoneEvents[i].clear() #says that the thread is busy distanceQueues[i].put(sensorReading[i]) #sends the distance data through the queue to the thread ## if debug: print 'sent' ard.close()
def __init__(self, parent = None, *args, **kwargs): # Initialize TkInter frame and define parent tk.Frame.__init__(self, parent ) self.parent = parent #initialize a starting deque size and poll rate self.pollRate = POLL_RATE_ms self.dequeSize = 100 # Create arduino device and datadeque as object parameters self.device = arduino() self.dataHandler = DataHandler(dequeLength=DATA_POINTS_PER_PLOT) # Create serial port frame, data handling frame, and plot frame self.sH = sH.SerialHandlerUI( parent = parent, device = self.device ) self.dH = dH.DataHandlerUI( parent = parent, dataHandler = self.dataHandler ) self.pH = pH.PlotHandlerUI( parent = parent, dataHandler = self.dataHandler ) # place into UI self.sH.grid(row=0, column=0, columnspan=6) self.dH.grid(row=1, column=0, columnspan=6) self.pH.grid(row=2, column=0, columnspan=6) # create poll rate menu and deque size slector self.create_poll_rate_menu() #create deque size selector # currently disabled because larger deque size == longer loop evaluation, undesirable #self.create_deque_size_selector() # generate quit button tk.Button(master=self.parent, text='Quit', command=self._quit).grid(row=5, column=2, columnspan=2) # start updating that data self.update_frequency = POLL_RATE_ms self.update_data()
status_json = file_stat.read() cmd_json = file_cmd.read() except: log("Read files json error. Script is close") raise SystemExit(1) try: status = json.loads(status_json) cmd = json.loads(cmd_json) except: log("Error decode json files. Script is close") raise SystemExit(1) web = socket_to_web.LinkToWeb(status, cmd) inputs = raspi.RPi(status) output = arduino.arduino(status) try: t1 = threading.Thread(target = web.start) log("Socket Threading start") t1.start() while True: status = web.read(status) #read commands for webserver inputs.read() #read raspberry pi inputs output.write() #send command to arduino on USB if status['start']: if time.localtime(time.time() - status['time']).tm_min > 0: status = web.reset(status) #time.sleep(1) except: web.stop()
def main(): global rec rec = recorder("sound", None, 1) play = player("sound", None, 1) #GLOBAL STATE state = 0 stories = [] # IS THERE A FILE AT START stories.append(1) stories.append(0) stories.append(0) stories.append(0) stories.append(0) stories.append(0) stories.append(0) stories.append(0) #ard = arduino("/dev/tty.usbserial-AH06LA61", 115200) ard = arduino("/dev/ttyUSB0", 115200) ard.connect() #THREADING run_event = threading.Event() run_event.set() threadSerial = threading.Thread(target=arduino.loopReadSerial, args=(ard, run_event)) threadSerial.start() #rec.recordFile(nameFile) ##play the same file # PLAYER # threadPlayer = threading.Thread(target=player.playFile, args=(play, nameFile) ) # threadPlayer.start() #rec.recordFile(nameFile) # Wait for arduino to initialize arduino serial time.sleep(4) # ard.setLedState(0, 2) # ard.setLedState(1, 2) # ard.sendLedState() # time.sleep(2) test = True # time.sleep(7) print "READY" try: while True: #print "READ buttons" if (not (ard.allowRead)): for i in range(8): ard.setLedState(i, stories[i] * 2) ard.sendLedState() ard.allowRead = True # WAITING if (state == 0): but = ard.getLastButtonPressed() # if (test): # rec.recordFileForIndex(5) # state = 2 # test = False # IF new button if (but > -1 and but < 8): # IF THERE IS A STORY if (stories[but] == 1): play.playFileFromIndex(but) state = 1 else: #rec print "REC" # threadRecorder = threading.Thread(target=rec.recordFileForIndex, args=(rec, but) ) # threadRecorder.start() # print "STARTED" rec.recordFileForIndex(but) state = 2 #PLAYING elif (state == 1): if (ard.getLastButtonPressed() > -1): play.stop() state = 0 #RECORDING elif (state == 2): print "STOP REC" index = rec.getLastRecordedIndex() if (index > -1): stories[index] = 1 state = 0 time.sleep(0.1) except KeyboardInterrupt: play.stop() print "killing all thread" run_event.clear() threadSerial.join()
def main(): for i in range(len(sys.argv)): if sys.argv[i] == '-t': if len(sys.argv) < i + 2: print(_('device needed for option') + ' -t') exit(1) test(sys.argv[i + 1]) print('pypilot Servo') from server import pypilotServer server = pypilotServer() from client import pypilotClient client = pypilotClient(server) from sensors import Sensors # for rudder feedback sensors = Sensors(client) servo = Servo(client, sensors) print('initializing arduino') config = { 'host': 'localhost', 'hat': { 'arduino': { 'device': '/dev/spidev0.1', 'resetpin': '16' } }, 'arduino.nmea.baud': 4800, 'arduino.nmea.in': False, 'arduino.nmea.out': False, 'arduino.ir': True, 'arduino.debug': True } a = arduino(config) dt = 0 period = 0.0 start = lastt = time.monotonic() while True: events = a.poll() if events: print(events) for key, count in events: if key != 'voltage': #print('go', time.monotonic()) if count: servo.command.set(1) else: servo.command.set(0) servo.poll() sensors.poll() client.poll() server.poll() dt = period - time.monotonic() + lastt if dt > 0 and dt < period: time.sleep(dt) lastt += period else: lastt = time.monotonic()
def __init__(self): # default config self.config = { 'host': 'localhost', 'actions': {}, 'pi.ir': True, 'arduino.ir': False, 'arduino.nmea.in': False, 'arduino.nmea.out': False, 'arduino.nmea.baud': 4800, 'lcd': {} } self.configfilename = os.getenv('HOME') + '/.pypilot/hat.conf' # read config print('loading config file:', self.configfilename) try: file = open(self.configfilename) config = pyjson.loads(file.read()) file.close() for name in config: self.config[name] = config[name] except Exception as e: print('config failed:', e) # read hardware config try: configfile = '/proc/device-tree/hat/custom_0' f = open(configfile) hat_config = pyjson.loads(f.read()) f.close() print('loaded device tree hat config') if not 'hat' in self.config or hat_config != self.config['hat']: self.config['hat'] = hat_config print('writing device tree hat to hat.conf') self.write_config() except Exception as e: print('failed to load', configfile, ':', e) if not 'hat' in self.config: print('assuming original 26 pin tinypilot with nokia5110 display') self.config['hat'] = { 'lcd': { 'driver': 'default', 'port': '/dev/spidev0.0' }, 'lirc': 'gpio4' } self.write_config() self.servo_timeout = time.monotonic() + 1 self.last_msg = {} self.last_msg['ap.enabled'] = False self.last_msg['ap.heading_command'] = 0 self.last_msg['ap.mode'] = '' if len(sys.argv) > 1: self.config['host'] = sys.argv[1] self.write_config() host = self.config['host'] print('host', host) if 'arduino' in self.config['hat']: import arduino arduino.arduino(config).firmware() self.poller = select.poll() self.gpio = gpio.gpio() self.lcd = LCD(self) time.sleep(1) self.client = pypilotClient(host) self.client.registered = False self.watchlist = ['ap.enabled', 'ap.heading_command', 'ap.mode'] for name in self.watchlist: self.client.watch(name) self.lcd.poll() if 'arduino' in self.config['hat']: self.arduino = Arduino(self) self.poller.register(self.arduino.pipe, select.POLLIN) else: self.arduino = False self.lirc = lircd.lirc(self.config) self.lirc.registered = False self.keytimes = {} self.keytimeouts = {} # keypad for lcd interface self.actions = [] keypadnames = [ 'auto', 'menu', 'port1', 'starboard1', 'select', 'port10', 'starboard10', 'tack', 'dodge_port', 'dodge_starboard' ] for i in range(len(keypadnames)): self.actions.append(ActionKeypad(self.lcd, i, keypadnames[i])) # stateless actions for autopilot control self.actions += [ ActionEngage(self), ActionPypilot(self, 'disengage', 'ap.enabled', False), ActionHeading(self, 1), ActionHeading(self, -1), ActionHeading(self, 2), ActionHeading(self, -2), ActionHeading(self, 5), ActionHeading(self, -5), ActionHeading(self, 10), ActionHeading(self, -10), ActionPypilot(self, 'compassmode', 'ap.mode', 'compass'), ActionPypilot(self, 'gpsmode', 'ap.mode', 'gps'), ActionPypilot(self, 'windmode', 'ap.mode', 'wind'), ActionPypilot(self, 'truewindmode', 'ap.mode', 'truewind'), ActionPypilot(self, 'center', 'servo.position', 0), ActionTack(self, 'tackport', 'port'), ActionTack(self, 'tackstarboard', 'starboard') ] # actions determined by the server (different pilots) not yet populated here for name in self.config['actions']: if name.startswith('pilot_'): self.actions.append( ActionPypilot(self, name, 'ap.pilot', name.replace('pilot_', '', 1))) # useful to unassign a key self.actions.append(ActionNone()) for action in self.actions: if not action.name in self.config['actions']: self.config['actions'][action.name] = [] self.web = Web(self) def cleanup(signal_number, frame=None): print('got signal', signal_number, 'cleaning up', os.getpid()) childpids = [] processes = [self.arduino, self.web, self.lcd] for process in processes: if process and process.process: childpids.append(process.process.pid) if signal_number == signal.SIGCHLD: pid = os.waitpid(-1, os.WNOHANG) if not pid[0] in childpids: print('subprocess returned', pid, childpids) # flask or system makes process at startup that dies return print('child process', pid, childpids) while childpids: pid = childpids.pop() #print('kill!', pid, childpids, os.getpid()) try: os.kill(pid, signal.SIGTERM) # get backtrace except ProcessLookupError: pass # ok, process is already terminated #os.waitpid(pid, 0) try: sys.stdout.flush() except Exception as e: print('failed to flush stdout', e) for process in processes: if process: process.process = False raise KeyboardInterrupt # to get backtrace on all processes try: sys.stdout.flush() except Exception as e: print('failed to flush stdout2', e) for s in range(1, 16): if s != 9 and s != 13: signal.signal(s, cleanup) signal.signal(signal.SIGCHLD, cleanup)
# poopWizard controls the robot reads (arduino.py) and writes to Brainstems (robotDrive.py) # poop # importing arduino & robot drives [check paths of cwd!] import time import sys sys.path.append('C:\\Documents and Settings\\nub\\My Documents\\roboscoop\\arduino') #sys.path.append('C:\\Documents and Settings\\wbosworth\\My Documents\\newPoop\\arduino') from arduino import arduino global a a = arduino() sys.path.append('C:\\Documents and Settings\\nub\\My Documents\\roboscoop\\brainstem') #sys.path.append('C:\\Documents and Settings\\wbosworth\\My Documents\\newPoop\\brainstem') from robotDrive import robotDrive global bob bob = robotDrive() time.sleep(5) # give everythging a few seconds to settle down!!!! def straightUntil(): ''' Set the robot to go straight until hitting an obstacle or until sensing poop. Exit modes designate whether it hit an obstacle or hit poop ''' desiredVel = 10 # encoder clicks/sec bob.velocity(desiredVel) while(1):
def __init__(self): # read config try: configfile = '/proc/device-tree/hat/custom_0' f = open(configfile) self.hatconfig = json.loads(f.read()) f.close() except Exception as e: print('failed to load', configfile, ':', e) print('assuming original 26 pin tinypilot') self.hatconfig = False self.config = { 'remote': False, 'host': 'pypilot', 'actions': {}, 'lcd': {} } self.configfilename = os.getenv('HOME') + '/.pypilot/hat.conf' print('loading config file:', self.configfilename) try: file = open(self.configfilename) config = json.loads(file.read()) file.close() for name in config: self.config[name] = config[name] except Exception as e: print('config failed:', e) self.lastpollheading = time.time() self.servo_timeout = time.time() + 1 self.longsleep = 30 self.last_msg = {} self.client = False self.lcd = lcd.LCD(self) self.gpio = gpio.gpio() self.arduino = arduino.arduino(self.hatconfig) self.lirc = lirc.lirc() self.buzzer = buzzer.buzzer(self.hatconfig) # keypad for lcd interface self.actions = [] keypadnames = ['auto', 'menu', 'up', 'down', 'select', 'left', 'right'] for i in range(7): self.actions.append(ActionKeypad(self.lcd, i, keypadnames[i])) # stateless actions for autopilot control self.actions += [ ActionEngage(self), ActionPypilot(self, 'disengage', 'ap.enabled', False), ActionHeading(self, 1), ActionHeading(self, -1), ActionHeading(self, 2), ActionHeading(self, -2), ActionHeading(self, 10), ActionHeading(self, -10), ActionPypilot(self, 'compassmode', 'ap.mode', 'compass'), ActionPypilot(self, 'gpsmode', 'ap.mode', 'gps'), ActionPypilot(self, 'windmode', 'ap.mode', 'wind'), ActionTack(self, 'tackport', 'port'), ActionTack(self, 'tackstarboard', 'starboard') ] for action in self.actions: if action.name in self.config['actions']: action.keys = self.config['actions'][action.name] self.web = Web(self)