def get_version(com: comm.Comm): """Get Host controller version""" com.write(CMD_VERSION) ver = com.read_line() return ver.decode('utf-8').rstrip()
def on_btn_open_clicked(self): if self.comm: self.comm_thread_running = False self.comm_thread.join() self.comm_thread = None self.comm.close() self.comm = None self.ui.btn_open.setText("&OPEN") else: try: if _POS_UPLOAD: self.comm = CommPosUpload(self.ui.cb_port.currentText(), int(self.ui.cb_speed.currentText())) else: self.comm = Comm(self.ui.cb_port.currentText(), int(self.ui.cb_speed.currentText())) self.comm.open() self.comm_thread_running = True self.comm_thread = threading.Thread(target=self.run_comm_thread, daemon=True) self.comm_thread.start() self.ui.btn_open.setText("CL&OSE") except Exception as ex: self.comm = None QMessageBox.warning(self, "OPEN", str(ex))
class Wiki(): def __init__(self, logger, exc_cb): self.logger = logger self.comm = Comm(5006, "wiki", {"wiki": self.wiki}, self.logger, exc_cb) def wiki(self, params): query = params["query"][0] resp0 = requests.get( "https://en.wikipedia.org/w/api.php?action=opensearch&limit=1&namespace=0&format=json&search=%s" % query) json0 = json.loads(resp0.text) if len(json0) < 2: return (404, "no search") if len(json0[1]) < 1: return (404, "no result") title = json0[1][0] resp1 = requests.get( "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=%s" % title) json1 = json.loads(resp1.text) try: extract = next(iter(json1['query']['pages'].values()))['extract'] except KeyError: return (404, "wiki Error") return (200, extract) def shut_down(self): print("wiki shutting down!") self.comm.shut_down() print("wiki shutted down!")
def get_status(com: comm.Comm): """Get Host controller version""" com.write(CMD_STATUS) count, status = com.read(8) return status
def debugSend(): Comm.setPort('/dev/cu.usbmodemM4321001') ser = Comm.getSerial() print ser.name ser.write('Hello world!') #ser.write('Hello world?') # negative test print 'Done sending.'
def __init__(self, logger, exc_cb): self.logger = logger ip_list = self.load_obj("ip_list") alarms = self.load_obj("alarms") self.comm = Comm(5002, "ping_server", { "status": self.status, "log": self.log, "reset": self.reset }, self.logger, exc_cb) self.ping_thread = PingThread(60, None) for ip in ip_list: self.ping_thread.add_ip(ip["name"], ip["ip"]) for a in alarms: if a["type"] == "timeofday": self.ping_thread.add_alarm_timeofday( a["user"], lambda alarm: self.alarm_received(alarm, a["to"]), a["start"], a["end"], a["weekdays"]) elif a["type"] == "dayamount": self.ping_thread.add_alarm_dayamount( a["user"], lambda alarm: self.alarm_received(alarm, a["to"]), a["amount"], a["weekdays"]) elif a["type"] == "onoffline": self.ping_thread.add_alarm_onoffline( a["user"], lambda alarm: self.alarm_received(alarm, a["to"]), a["onoff"], a["weekdays"])
def run(): daemon = DaemonManager() daemon.start() # Stuff that should clearly be elsewhere. subprocess.call(['aconnect', '130:0', '129:1']) subprocess.call(['aconnect', '24:0', '129:1']) subprocess.call(['jack_connect', 'fluidsynth:l_00', 'system:playback_1']) subprocess.call(['jack_connect', 'fluidsynth:r_00', 'system:playback_2']) comm = Comm() # Start the proactor thread. We do this after Comm() has been created so # there are connections to manage, otherwise the proactor will just # immediately terminate. proactorThread = threading.Thread(target = getProactor().run) proactorThread.start() try: commands = Commands(comm) win = MyWin(Tk(), commands) win.mainloop() finally: comm.close() proactorThread.join()
def main(): # Parse command line args parser = argparse.ArgumentParser( description='Connect to MSP and play chess.') parser.add_argument('-e', '--engine', default='./stockfish-7-64', help='Path to a UCI compatible chess engine exe') parser.add_argument('-p', '--port', default='/dev/cu.usbmodemM4321001', help='Name of a COM port connected to (MSP) client') parser.add_argument('-d', '--depth', default='1', help='Integer depth of search space for computer move') args = vars(parser.parse_args(sys.argv[1:])) Comm.setPort(args['port']) # Setup board = chess.Board() engine = chess.uci.popen_engine(args['engine']) engine.uci() difficulty = int(args['depth']) board.reset() # Create a game and set headers. game = chess.pgn.Game() game.headers["Black"] = engine.name game.headers["White"] = engine.name game.setup(board) node = game print board while True: node = player_move(node, board) print board # player won game, so send a game over signal if board.is_game_over(): ser = Comm.getSerial() ser.write( '\x40\x00' ) # 2nd MSB set; empty move indicates nothing to do client side break node = computer_move(node, board, engine, difficulty) #node = debug_shell_move(node, board, True) print board if board.is_game_over(): break print board print board.fen() game.headers["Result"] = board.result() print game
def __init__(self, logger, exc_cb): self.logger = logger self.comm = Comm(5003, "sms_portal", {"send_sms": self.send_sms}, self.logger, exc_cb) self.external_port = 5100 self.unicast_listener = UnicastListener(self.sms_received, self.external_port, self.logger, exc_cb) self.sms_password = self.load_obj("sms_password")[0] parser = argparse.ArgumentParser() parser.add_argument('--pay', action='store_true') self.args = parser.parse_args() if self.args.pay: self.logger.log("you must pay!") else: self.logger.log("WARNING, you can't send SMS'es") self.sms_cmds = { "p": self.Cmd_p(self.logger, self.comm, 0, False, 0), "py": self.Cmd_py(self.logger, self.comm, 0, False, 0), "pl": self.Cmd_pl(self.logger, self.comm, 0, False, 0), "stop": self.Cmd_stop(self.logger, self.comm, 0, False, 0), "er": self.Cmd_emoji_receive(self.logger, self.comm, 1, False, 0), "es": self.Cmd_emoji_send(self.logger, self.comm, 1, False, 0), "ping": self.Cmd_ping(self.logger, self.comm, 1, True, 0), "pinglog": self.Cmd_pinglog(self.logger, self.comm, 1, True, 0), "radio": self.Cmd_radio(self.logger, self.comm, 0, False, 0), "skip": self.Cmd_skip(self.logger, self.comm, 0, False, 0), "pod": self.Cmd_podcast(self.logger, self.comm, 0, False, 0), "wiki": self.Cmd_wiki(self.logger, self.comm, 1, False, 0) }
class Emoji(): def __init__(self, logger, exc_cb): self.logger = logger self.comm = Comm(5004, "emoji", { "receive": self.receive, "send": self.send }, self.logger, exc_cb) self.emoji_parser = EmojiParser(self.logger.log) # http://127.0.0.1:5004/receive?text=uni%F0%9F%A6%84corn def receive(self, params): if "text" not in params: return (404, "function 'receive' requires 'text'") text = params["text"][0] ret = "" for c in text: if ord(c) >= 32 and ord(c) < 254: ret += c else: ret += ',' + unicodedata.name(c) + ',' return (200, "%s" % ret) # http://127.0.0.1:5004/send?text=See this. uni.UNICORN FACE.corn. I know you liked it. def send(self, params): if "text" not in params: return (404, "function 'send' requires 'text'") text = params["text"][0] ret = self.emoji_parser.send(text) self.logger.log("emoji send %s" % ret) return (200, "%s" % ret) def shut_down(self): self.comm.shut_down()
def __init__(self, logger, exc_cb): self.logger = logger self.comm = Comm(5004, "emoji", { "receive": self.receive, "send": self.send }, self.logger, exc_cb) self.emoji_parser = EmojiParser(self.logger.log)
def reset(com: comm.Comm): """ reset the target """ time.sleep(0.050) com.pulse_dtr(0.250) time.sleep(0.050) return
def read_page(com: comm.Comm, cmd_code: bytes, req_count: int) -> bytes: """read next program or data page""" cmd = cmd_code + req_count.to_bytes(2, 'little') com.write(cmd) count, data = com.read(req_count * 2) if count != req_count * 2: raise RuntimeError(f"Error [c={count}|d={data}") return data
def main(): client = Comm() client.connect('localhost', 8089) client.send(b'hello') data = client.receive() print('data:', data) client.disconnect()
class StreamReceiver(): def __init__(self, logger, exc_cb): self.logger = logger self.comm = Comm(5005, "stream_receiver", { "multicast": self.multicast, "radio": self.radio, "off": self.off }, self.logger, exc_cb) self.radio = RadioReceiver() self.multicast_receiver = MulticastReceiver() self.running = True self.source = None # http://127.0.0.1:5005/radio # http://127.0.0.1:5005/radio 24syv def radio(self, params): if "channel" in params: channel = params["channel"][0] self.radio.set_channel(channel) self.set_source("radio") return (200, "switched to radio ok") # http://127.0.0.1:5005/multicast def multicast(self, params): self.set_source("multicast") return (200, "switched to multicast ok") # http://127.0.0.1:5005/off def off(self, params): self.set_source(None) return (200, "switched off") def shut_down(self): self.set_source(None) self.comm.shut_down() self.running = False def set_source(self, source): print("setting source: '%s'" % source) if source == self.source: return self.source = source if source == "radio": self.multicast_receiver.stop() self.radio.start() elif source == "multicast": self.radio.stop() self.multicast_receiver.start() else: self.radio.stop() self.multicast_receiver.stop()
def __init__(self, logger, exc_cb): self.logger = logger self.comm = Comm(5005, "stream_receiver", { "multicast": self.multicast, "radio": self.radio, "off": self.off }, self.logger, exc_cb) self.radio = RadioReceiver() self.multicast_receiver = MulticastReceiver() self.running = True self.source = None
def sync(com: comm.Comm): """sync commands stream""" com.write(CMD_SYNC) prompt = wait_k(com) if prompt != b'K': raise RuntimeError(f'Error [{prompt}] command:{CMD_SYNC} ICSP') # There should be no characters waiting at this point avail = com.avail() if avail > 0: raise RuntimeError(f'Sync Error. {avail} bytes still waiting')
def __init__(self, x, y, heading): self.x = x self.y = y self.heading = heading self.weed_volume = 0 self.manual_control = True self.auto_turn_chance = 0.1 self.auto_turn_amount = 15 self.auto_move_amount = 10 self.auto_col_turn_max = 90 self.communicator = Comm(12345, 12346) self.start()
def debugReceive(): Comm.setPort('/dev/cu.usbmodemM4321001') ser = Comm.getSerial() print ser.name received = '' while not received: while ser.inWaiting() > 0: received += ser.read(13) if len(received) == 0: pass #print 'Nothing received.' else: print received
def __init__(self, renderer=None, width=None, height=None, frame=True, camera_distance=10.0, background=None, foreground=None, **ignored): """ INPUT: - renderer -- None (automatic), 'canvas2d', or 'webgl' - width -- None (automatic) or an integer - height -- None (automatic) or an integer - frame -- bool (default: True); draw a frame that includes every object. - camera_distance -- float (default: 10); default camera distance. - background -- None (transparent); otherwise a color such as 'black' or 'white' - foreground -- None (automatic = black if transparent; otherwise opposite of background); or a color; this is used for drawing the frame and axes labels. """ self.id = uuid() self.comm = Comm(data={ 'renderer': renderer, 'width': noneint(width), 'height': noneint(height), 'camera_distance': float(camera_distance), 'background': background, 'foreground': foreground }, target_name='threejs') self.comm.on_msg(self.on_msg) self._graphics = []
def get(attraction): url = "{}{}".format("/attraction/get/", attraction['id']) res = Http.get(url, True) json = res.json() status = '' if json['ShortWaitTimeDisplay'] == 'Closed': status = attraction['closed_message'] else: status = "{} {} minutes".format(attraction['open_message'], json['PostedWaitTime']) if 'twitter_cfg' in attraction: Comm.tweet(status, attraction['twitter_cfg']) else: print status
def main(): #Creating a State Machine Container rospy.init_node("AcousticMaster") rospy.loginfo("Initialised") sm = smach.StateMachine(outcomes=['failed', 'surface']) sm_server = smach_ros.IntrospectionServer("/acoustic/master", sm, "/PING") sm_server.start() acoustic = Comm() rospy.loginfo("Done with comm") with sm: smach.StateMachine.add("DISENGAGE", Disengage(acoustic), transitions={ 'init': 'STOP_LISTEN', 'completed': 'surface', 'aborted': 'failed' }) smach.StateMachine.add("STOP_LISTEN", StopListen(acoustic), transitions={ 'calculated': 'MOVING', 'aborted': 'DISENGAGE' }) smach.StateMachine.add("MOVING", Moving(acoustic), transitions={ 'aborted': 'DISENGAGE', 'holdPosition': 'STOP_LISTEN', 'done': 'DISENGAGE' }) outcomes = sm.execute() rospy.loginfo(outcomes)
def main(): #Creating a State Machine Container rospy.init_node("acoustic_master") rospy.loginfo("Initialised") sm = smach.StateMachine(outcomes=['foundPinger', 'surface']) acoustic = Comm() rospy.loginfo("Done with comm") with sm: smach.StateMachine.add("DISENGAGE", Disengage(acoustic), transitions={ 'init': 'STOP_LISTEN', 'completed': 'surface' }) smach.StateMachine.add("STOP_LISTEN", StopListen(acoustic), transitions={ 'calculated': 'MOVING', 'aborted': 'DISENGAGE' }) smach.StateMachine.add("MOVING", Moving(acoustic), transitions={ 'aborted': 'DISENGAGE', 'holdPosition': 'STOP_LISTEN', 'done': 'DISENGAGE' }) outcomes = sm.execute() rospy.loginfo(outcomes)
def __init__(self, logger, exc_cb, dt, host_mode): self.dt = dt self.host_mode = host_mode self.logger = logger self.logger.log("host_mode = %s" % host_mode) self.comm = Comm(5008, "led", { "set": self.set_leds, }, self.logger, exc_cb) self.startup_timer = None self.num_leds = 8 self.num_layers = 3 self.leds = [[self.Led() for i in range(self.num_layers)] for i in range(self.num_leds)] self.meta_led = self.Led() self.color = { "user_k": (0, 255, 0, 0, 255), "user_r": (0, 100, 255, 0, 255), "user_c": (0, 255, 255, 0, 255), "user_h": (0, 100, 0, 100, 255), "user_a": (0, 0, 0, 140, 255), "user_s": (0, 20, 160, 255, 255) } if self.host_mode: pygame.display.init() self.rect = 30 self.display = pygame.display.set_mode( (self.rect * self.num_leds, 100)) else: # We only have SPI bus 0 available to us on the Pi bus = 0 #Device is the chip select pin. Set to 0 or 1, depending on the connections device = 1 # Enable SPI self.spi = spidev.SpiDev() # Open a connection to a specific bus and device (chip select pin) self.spi.open(bus, device) # Set SPI speed and mode self.spi.max_speed_hz = 500000 self.spi.mode = 0 self.set_leds({"anim": ["boot"]})
def __init__(self, logger, exc_cb): self.logger = logger self.comm = Comm(5009, "web_app", {}, self.logger, exc_cb) self.loop = asyncio.get_event_loop() app = web.Application() app.add_routes([web.get('/', self.main_menu), web.get('/stop', self.stop), web.get('/search', self.search), web.get('/get_search_result', self.get_search_result), web.get('/play', self.play), web.get('/radio', self.radio), web.get('/music', self.music_menu), web.get('/assets/apple-touch-icon.png', self.png)]) handler = app.make_handler() self.server = self.loop.create_server(handler, port=8080) self.loop.run_until_complete(self.server)
def init_port(self): items = Comm.scan_ports() item = self.ui.cb_port.currentText() if len(item) == 0 and len(items) > 0: item = items[0] self.ui.cb_port.clear() self.ui.cb_port.addItems(items) self.ui.cb_port.setCurrentText(item)
def __init__(self, logger, exc_cb): self.logger = logger self.logger.log("loading music collection...") self.music_collection = MusicCollection(self.logger, load_collection(self.logger)) self.playlists = load_playlists(self.logger) self.vlc_thread = VlcThread(self.logger) self.podcaster = Podcaster() self.comm = Comm( 5001, "music_server", { "play": self.play, "search": self.search, "get_search_result": self.get_search_result, "debug_playlist": self.debug_playlist, "podcast": self.podcast, "skip": self.skip, "stop": self.stop, "tag": self.tag }, self.logger, exc_cb) self.mode = "stopped"
def write_move_to_serial(board, move): ser = Comm.getSerial() # push move temporarily to see if it causes game over board.push(move) game_over = board.is_game_over() board.pop() # Write auxilary moves, e.g. for capture or special move if board.is_capture(move): capture_tile = '' if board.is_en_passant(move): uci = str(move) if uci[3] == '6': capture_tile = uci[2] + '5' elif uci[3] == '3': capture_tile = uci[2] + '4' else: raise Exception('unknown en passant command ' + str(move)) else: capture_tile = str(move)[2:4] code = encode_uci(capture_tile, True, game_over) if game_over: game_over = False # prevent next move from setting bit ser.write(code) elif board.is_castling(move): king_dest = str(move)[2:4] rook_uci = '' if king_dest == 'c1': rook_uci = 'a1d1' elif king_dest == 'c8': rook_uci = 'a8d8' elif king_dest == 'g1': rook_uci = 'h1f1' elif king_dest == 'g8': rook_uci = 'h8f8' else: raise Exception('unknown castling command ' + str(move)) code = encode_uci(rook_uci, True, game_over) if game_over: game_over = False # prevent next move from setting bit ser.write(code) # write the main move code = encode_uci(str(move), False, game_over) ser.write(code)
def main(): #Creating a State Machine Container rospy.init_node("acoustic_master") rospy.loginfo("Initialised") sm = smach.StateMachine(outcomes=['foundPinger', 'surface']) sm_server = smach_ros.IntrospectionServer("/acoustic/master", sm, "/PING") sm_server.start() acoustic = Comm() signal.signal(signal.SIGINT, acoustic.quit) rospy.loginfo("Done with comm") with sm: smach.StateMachine.add("DISENGAGE", Disengage(acoustic), transitions={'init':'MOVING','completed':'surface' }) smach.StateMachine.add("MOVING", Moving(acoustic), transitions={'aborted':'DISENGAGE','done':'DISENGAGE'}) outcomes = sm.execute() rospy.loginfo(outcomes)
def show_sage(self, **kwds): fig = self.figure(**kwds) from matplotlib.backends.backend_agg import FigureCanvasAgg canvas = FigureCanvasAgg(fig) fig.set_canvas(canvas) fig.tight_layout( ) # critical, since sage does this -- if not, coords all wrong ax = fig.axes[0] # upper left data coordinates xmin, ymax = ax.transData.inverted().transform( fig.transFigure.transform((0, 1))) # lower right data coordinates xmax, ymin = ax.transData.inverted().transform( fig.transFigure.transform((1, 0))) def to_data_coords(p): # 0<=x,y<=1 return ((xmax - xmin) * p[0] + xmin, (ymax - ymin) * (1 - p[1]) + ymin) def on_msg(msg): data = msg['content']['data'] x, y = data['x'], data['y'] eventType = data['eventType'] if eventType in self._events: self._events[eventType](to_data_coords([x, y])) file_id = uuid() if kwds.get('svg', False): filename = '%s.svg' % file_id del kwds['svg'] else: filename = '%s.png' % file_id fig.savefig(filename) from comm import SageCellComm as Comm self.comm = Comm(data={"filename": filename}, target_name='graphicswidget') import sys sys._sage_.sent_files[filename] = os.path.getmtime(filename) self.comm.on_msg(on_msg)
def player_move(node, board): # Obtain the player's move by continuously polling player_moved = False ser = Comm.getSerial() while not player_moved: # throttle the read requests time.sleep(0.05) # Read from serial buffer received = '' while ser.inWaiting() > 0: received += ser.read(2) if len(received) == 0: continue # did not receive anything uci = decode_uci(received) print "Player move: " + uci move = chess.Move.from_uci(uci) if move in board.legal_moves: board.push(move) player_moved = True else: # check if promotion is valid by appending 'q' promotion = chess.Move.from_uci(uci + 'q') if promotion in board.legal_moves: board.push(promotion) player_moved = True # received an illegal move if not player_moved: ser.write( '\xff\xff') # write the error code back to player and wait node = node.add_variation(move) return node
def main(): global ELEVATION, DOA, step_size, depth_default, count, duration acoustic_pub = rospy.Publisher("/acoustic/pingData", pingData) com = Comm() rospy.loginfo("Ready to go") generateVec() rospy.loginfo("Steering vector generated") while True: adjustStep(ELEVATION) if ELEVATION < 30 and count > 1: rospy.loginfo("surfacing") com.sendMovement(depth=-0.1) break elif overShotPinger(DOA) and count > 1: rospy.loginfo("overshot") com.sendMovement(forward=-(step_size/2)) com.sendMovement(depth=-0.1) break else: if count > 1: duration = 2 time.sleep(duration) complexList = [] while len(complexList) is not sampleAmt: message, clientAddress = serverSocket.recvfrom(BUFFER_SIZE) print message splitted = splitMsg(message) if not splitted: continue else: print "Number of Ping: %d" % (len(complexList)+1) complexList.append(splitted) count += 1 DOA, ELEVATION = music(complexList) acoustic_pub.publish(doa, elevation) com.sendMovement(turn=DOA, depth=depth_default) com.sendMovement(forward=step_size, depth=depth_default) #music_3d(complexList) rospy.loginfo("Next")