def main(): global running, core, core_lock match_id = int(sys.argv[1]) listen_addr = sys.argv[2] listen_port = int(sys.argv[3]) core = SubottoCore(match_id) with core_lock: core.update() # Initialize ConnectionServer server = ThreadedTCPServer((listen_addr, listen_port), Connection) server_thread = threading.Thread(target=server.serve_forever) server_thread.start() # Do things try: while True: with core_lock: core.update() time.sleep(1.0) except KeyboardInterrupt: running = False running = False server.shutdown() server.server_close() server_thread.join()
def main(): match_id = int(sys.argv[1]) serial_port = sys.argv[2] ss = SubottoSerial(serial_port, 115200) # Here we wait for the SUB_READY command, otherwise we risk to # send commands before the unit is ready print ss.wait_for_ready() core = SubottoCore(match_id) # Run a test match ss.set_slave_mode() score = [0, 0] cached_score = [None, None] try: while True: events = ss.receive_events() for ev in events: team, var, desc, source = SubottoSerial.ASYNC_DESC[ev] score[team] += var print "%s; result is %d -- %d" % (desc, score[0], score[1]) if var > 0: core.act_goal(core.order[team], source) elif var < 0: core.act_goal_undo(core.order[team], source) core.update() for i in [0, 1]: this_score = core.score[core.detect_team(core.order[i])] if this_score != cached_score[i]: ss.set_score(this_score, i) cached_score[i] = this_score time.sleep(0.2) except KeyboardInterrupt: pass
def main(): global running, core, core_lock, allowed_IPs, dry_run parser = argparse.ArgumentParser(description='Arduino interface') parser.add_argument('match_id', type=int, help='The id of the match to connect to') parser.add_argument('--listen_addr', default='0.0.0.0', help='The address the listener server listens to') parser.add_argument('--listen_port', default=2204, type=int, help='The address the listener server listens to') parser.add_argument('arduino_ip', help='The ip of the allowed Arduino') parser.add_argument('--dry-run', action='store_true', help='Test run') args = parser.parse_args() allowed_IPs.append(args.arduino_ip) dry_run = args.dry_run core = SubottoCore(args.match_id) with core_lock: core.update() # Initialize ConnectionServer server = ThreadedTCPServer((args.listen_addr, args.listen_port), Connection) server_thread = threading.Thread(target=server.serve_forever) server_thread.start() print >> sys.stdout, "Started server on {}:{}".format(args.listen_addr, args.listen_port) # Do things try: while True: with core_lock: core.update() time.sleep(1.0) except KeyboardInterrupt: running = False running = False server.shutdown() server.server_close() server_thread.join()
self.order[i].box.reparent(self.team_slot[i]) def on_window_destroy (self, widget): self.core.close() Gtk.main_quit() def on_btn_switch_clicked (self, widget): debug("Cambio!", 2) self.switch_teams() def regenerate(self): debug("Updating!",20) self.update_teams() def new_player_match(self, player_match): pass def new_event(self, event): pass if __name__ == "__main__": match_id = int(sys.argv[1]) core = SubottoCore(match_id) main_window = Subotto24GTK(core) core.update() gi.repository.GObject.timeout_add(1000, core.update) Gtk.main()
class Interface: _numDebugebugLines = 0 DEVICE = ["arduino","core"] MAX_NUM_CONSOLE_ROWS = 100 connected = False toDisconnect = False score = {dev:[0,0] for dev in DEVICE} lastToScore = {dev:None for dev in DEVICE} # === init function === def __init__(self): filename = "main.glade" self.builder = Gtk.Builder() self.builder.add_from_file(filename) self.builder.connect_signals(self) self.mainWindow = self.builder.get_object("mainWindow") self.connectionWindow = self.builder.get_object("connectionWindow") self.debugConsole = Gtk.ListStore(str) self.consoleView = self.builder.get_object("console") self.consoleView.set_model(self.debugConsole) self.consoleView.insert_column(Gtk.TreeViewColumn("Debug Log", Gtk.CellRendererText(), text=0),0) self.scoreTextView = { "arduino":{"RED":self.builder.get_object("redArduinoScore"), "BLUE":self.builder.get_object("blueArduinoScore")}, "core":{"RED":self.builder.get_object("redCoreScore"), "BLUE":self.builder.get_object("blueCoreScore")} } self.lastToScoreBar = { "arduino":{"RED":self.builder.get_object("redArduinoLastToScore"), "BLUE":self.builder.get_object("blueArduinoLastToScore")}, "core":{"RED":self.builder.get_object("redCoreLastToScore"), "BLUE":self.builder.get_object("blueCoreLastToScore")}, } self.sensorSwitch = { "RED":{ "VOID":None, "GOAL":self.builder.get_object("redGoalSwitch"), "SUPERGOAL":self.builder.get_object("redSupergoalSwitch"), "PLUS_ONE":self.builder.get_object("redAddButtonSwitch"), "MINUS_ONE":self.builder.get_object("redUndoButtonSwitch") }, "BLUE":{ "VOID":None, "GOAL":self.builder.get_object("blueGoalSwitch"), "SUPERGOAL":self.builder.get_object("blueSupergoalSwitch"), "PLUS_ONE":self.builder.get_object("blueAddButtonSwitch"), "MINUS_ONE":self.builder.get_object("blueUndoButtonSwitch") } } self.core = SubottoCore(int(sys.argv[1])) for i in [0,1]: self.score["core"][i] = self.getCoreScore(i) GObject.timeout_add(300, self.loopFunction) self.core = SubottoCore(int(sys.argv[1])) # === control functions === # write on the console def debugLog(self,string): self._numDebugebugLines += 1 self.debugConsole.append([string]) #if len(self.debugConsole) > self.MAX_NUM_CONSOLE_ROWS: # self.debugConsole.remove(self.debugConsole.get_iter_first()) # === main loop === def loopFunction(self,*args): if self.connected: self.updateScore() elif self.toDisconnect: self.disconnect() else: self.debugLog("Not connected") self.core.update() return True # === connection/disconnection functions === # connect to socket def connect(self): if not self.connected: try: self.debugLog("Getting data..") TCP_IP = self.builder.get_object("tcpipText").get_text() TCP_PORT = int(self.builder.get_object("tcpportText").get_text()) PWD = self.builder.get_object("pwdText").get_text() self.debugLog("Connecting to socket...") self.debugLog("TCP_IP: " + TCP_IP) self.debugLog("TCP_PORT: " + str(TCP_PORT)) self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.connect((TCP_IP, TCP_PORT)) self.debugLog("Connected!") self.s.send(PWD) self.connected = True self.debugLog("Creating arduino controller object...") self.ac = ArdCon(self.s,self.debugLog) self.debugLog("Arduino controller object Created!") self.debugLog("Asking Arduino data...") for i in [0,1]: self.getArduinoScore(i) self.connectionWindow.hide() except: traceback.print_exc() self.debugLog("Connection failed\n") else: self.connected = True self.debugLog("Connection successful\n") # disconnect from socket def disconnect(self): self.toDisconnect = False #if not self.connected: try: self.s.close() except: pass self.connectionWindow.show() self.connected = False self.debugLog("Disconnected\n") def readEvents(self): try: rcv = self.ac.receiveData() while rcv is not None: self.debugLog(str(rcv)) self.sendEventToCore(rcv) rcv = self.ac.receiveData() except: traceback.print_exc() self.connected = False self.toDisconnect = True self.debugLog("Disconnected") # === update functions === # asks the score to arduino and the core; updates arduino score def updateScore(self): self.readEvents() for i in [0,1]: self.score["core"][i] = self.getCoreScore(i) if self.score["arduino"][i] == None: self.debugLog("Arduino score unknown") self.lastToScore["arduino"] = None else: if self.score["core"][i] != self.score["arduino"][i]: # server takes priority over arduino self.setArduinoScore(i,self.score["core"][i]) self.lastToScore["arduino"] = None self.updateView(i) # update scores on the main window def updateView(self,team): for dev in self.DEVICE: score = self.score[dev][team] if score == None: self.scoreTextView[dev][self.ac.ARD_TEAM[team]].set_text("Unknown") else: self.scoreTextView[dev][self.ac.ARD_TEAM[team]].set_text(str(score)) if self.lastToScore[dev] == team: self.lastToScoreBar[dev][self.ac.ARD_TEAM[team]].set_fraction(1) else: self.lastToScoreBar[dev][self.ac.ARD_TEAM[team]].set_fraction(0) # === core communication === # get score from the core def getCoreScore(self,i): return self.core.score[self.core.detect_team(self.core.order[i])] # send an event received from arduino def sendEventToCore(self,data): team = self.ac.ARD_TEAM.index(data["team"]) self.score["arduino"][team] = data["score"] event = self.ac.CORE_EVENT[data["team"]][data["event"]] if event is None: pass elif event in self.ac.UNDO_EVENT: self.core.act_goal_undo(self.core.order[team], event) else: self.core.act_goal(self.core.order[team], event) self.lastToScore["core"] = team self.lastToScore["arduino"] = team # === arduino communication === # get arduino score def getArduinoScore(self,i): self.ac.askData(self.ac.ARD_TEAM[i]) # set arduino score def setArduinoScore(self,team,score): scoreChange = score - self.score["arduino"][team] self.ac.sendScoreCommand(self.ac.ARD_TEAM[team],scoreChange) self.getArduinoScore(team) # === event handlers === # called when the console shows def onConsoleShow(self,*args): adj = self.consoleView.get_vadjustment() adj.set_value( adj.get_page_size() ) # called when a new line is added to the console def onSizeAllocate(self,*args): numDebugLines = self._numDebugebugLines self._numDebugebugLines = 0 adj = self.consoleView.get_vadjustment() if adj.get_value() >= adj.get_upper() - adj.get_page_size() - numDebugLines * adj.get_step_increment(): adj.set_value( adj.get_upper() - adj.get_page_size() ) # called when a switch is switched def onSwitchNotify(self,*args): if self.connected: for team in self.ac.ARD_TEAM: for event in self.ac.EVENT: if args[0] == self.sensorSwitch[team][event]: toActivate = self.sensorSwitch[team][event].get_active() self.ac.sendSensorCommand(team,event,toActivate) self.debugLog("switch " + str(team) + " " + str(event) + " was turned " + str(toActivate)) # called when the connection button is hit def onConnection(self,*args): self.debugLog("Connecting...") self.connect() # called when the main window is closed def onDestroyWindow(self,*args): try: del(self.ac) self.disconnect() except: traceback.print_exc() pass sys.exit(0)