def main(): # TODO: parse configuration file to retreive # sender's and receiver's ip addresses config_dict = parse_config() if not config_dict: print 'no config params' return sender_name = config_dict['IP'] + '_sender' recv_name = config_dict['IP'] + '_receiver' print 'sender name: ' + sender_name print 'receiver name: ' + recv_name s_obj = Sender() r_obj = Receiver() s_obj.ip_address = config_dict['IP'] r_obj.ip_address = config_dict['IP'] s_obj.multicast_address = config_dict['multicast'] r_obj.multicast_address = config_dict['multicast'] Pyro4.Daemon.serveSimple( { s_obj: sender_name, r_obj: recv_name }, ns=False, port=45000, host=config_dict["IP"] )
def __init__(self, rx_queue): Thread.__init__(self) self.rcv = Receiver() self.rcv.set_timeout(1000) self.rx_queue = rx_queue self._stop_event = Event() self.logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
def test1(key, sent): # Initialize Sender and Receiver with key S = Sender(key) R = Receiver(key) print '### SEND ###' print sent print '############' # Loops if there is an error with the transfer while True: # Builds & encrypts packets to send C = S.send(sent) print '### ENCRYPTED PACKETS ###' for c in C: print repr(c) print '#########################' # Decrypts & rebuilds packets in correct order err, received = R.receive(C) if (err == None): break else: print 'Uh Oh' sys.exit(1) print '### RECEIVE ###' print received print '###############' test = sent == received print 'sent = received? ' + str(test) print '###############\n' return test
def __init__(self, ser): self._last_angles = np.ndarray self._last_imu = np.ndarray # https://www.pieter-jan.com/node/11 self.pitch_acc = 0 self.roll_acc = 0 self.pitch = 0 self.roll = 0 self._tx_thread = Transmitter(name="tx_th", ser=ser) self._rx_thread = Receiver(name="rx_th", ser=ser) self._rx_thread.set_timeout(0.010) self._rx_thread.bind(self.receive_callback) self._pub_imu = rp.Publisher('imu_raw', Imu, queue_size=1) self._pub_joint_states = rp.Publisher('joint_states', JointState, queue_size=1) self._motor_map = rp.get_param("~motor_mapping") self._imu_calibration = rp.get_param("~imu_calibration") for motor in self._motor_map: self._motor_map[motor]["subscriber"] = rp.Subscriber( motor + "/command", Float64, self.trajectory_callback, motor) self._motor_map[motor]["publisher"] = rp.Publisher( motor + "/state", JointControllerState, queue_size=1) self._motor_map[motor]["value"] = 0.0 self._publish_timer = rp.Timer(rp.Duration(nsecs=10000000), self.send_angles)
def start_proxy(): sender = Sender(GENERIC_GATEWAY_IP_ADDRESS, GENERIC_GATEWAY_IP_PORT, GENERIC_GATEWAY_PAGE_NAME, GENERIC_GATEWAY_TIMEOUT) receiver = Receiver(RF_ENGINE_IP_ADDRESS, RF_ENGINE_IP_PORT, TIMEOUT_IN_SECOND, CONNECTION_RETRY_INTERVAL, sender.send_message) receiver.start_listening()
def __init__(self, config=None): """Initialise the Connector and starts to listen to incoming messages. :param config: Configuration to use (default config if None). """ self.log = logging.getLogger(self.__class__.__name__) if config is None: config = ConnConfig() self.log.info("Falling back to default configuration.") # errors up to here are allowed to terminate the program mappings = self._read_mappings(config.mappings) self.mapper = Mapper(mappings) self.log.debug("Mappings read.") self.sender = Sender(config.send.address, config.send.port, config.broker.endpoint_prefix + config.connector_id, config.broker.topic, config.connector_id) self.log.info("Sender created.") self.receiver = Receiver(self.RECEIVER_NAME, config.listen.address, config.listen.port) self.log.info("Receiver created.") self.receiver.listen("/", self.handle_receive)
def run_mirror(coord, transmission_protocol, identifier, sender_ipc_focus, receiver_ipc_focus, receiver_ipc_light, senders_ipc_mirrors, receivers_ipc_mirrors): mirror = Mirror(identifier=identifier, coord=coord) mirror.sender_focus_ = Sender(sender_ipc_focus, transmission_protocol, verbose=False) mirror.receiver_focus_ = Receiver(receiver_ipc_focus, transmission_protocol, verbose=False) mirror.receiver_light_src_ = Receiver(receiver_ipc_light, transmission_protocol, verbose=False) for i, ipc in senders_ipc_mirrors.items(): mirror.senders_mirrors_[i] = Sender(ipc, transmission_protocol, verbose=False) for i, ipc in receivers_ipc_mirrors.items(): mirror.receivers_mirrors_[i] = Receiver(ipc, transmission_protocol, verbose=False) if identifier == 0: mirror.run(is_first_to_adjust=True) else: mirror.run()
def main(): nrx=3 # Create a tx ntx=3 ta = None #ta = SampleRate() transmitter = Transmitter(ntx,ta) # Create a channel chan = TraceChan() num_chans=1 length = chan.create_chan(transmitter.Ntx,nrx) #ta = OracleRA(chan) #transmitter.set_transmit_ra(ta) #receiver = Receiver(MaxTputRA(),nrx) #receiver = Receiver(MinEngRA(),nrx) receiver = Receiver(EngTputRA(),nrx) #receiver = Receiver(EffSnrRA(),nrx) #receiver = Receiver(RxSampleRate(),nrx) #receiver = Receiver(RxOracle(),nrx) #length =10 for num in range(0,length): pkt = transmitter.transmit_pkt() chan.apply_channel(pkt) #print chan.curr_chan #print pkt # Create receiver receiver.receive_pkt(pkt) ack_pkt = receiver.get_feedback_pkt() transmitter.process_ack(ack_pkt)
def __init__(self, f): self.logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) self.emitter = Emitter(f) self.logger.info("Emitter is set") self.receiver = Receiver(f) self.logger.info("Receiver is set")
def __init__(self, numOfInputs): self.transmitter = Transmitter() self.receiver = Receiver() self.wirelessChannel = wireless_channel(0.1) self.numOfInputs = numOfInputs self.sigmaValues = [10, 1, 0.1] self.generated_Points = [] self.colors = ['purple', 'yellow', 'orange']
def ncd_loop(doInit, dlThreadNum): ndutil.setTimezone() #read config cnfManager = CnfManager() cnfManager.load('./ndc.cnf') cnfData = cnfManager.getCnfData() #check dirs ndutil.enableDir(cnfData['dirWorking']) ndutil.enableDir(cnfData['dirStore']) #ndlcom logger = Logger('nDroid-Crawler', cnfData['ndlComHost'], cnfData['ndlComPort']) logger.logger('Initiating') dbManager = DbManager(cnfData['dbHost'], cnfData['dbUser'], cnfData['dbPass'], cnfData['dbName']) if doInit: dbManager.create_table() os.system('rm -f %s/*' % cnfData['dirWorking']) os.system('rm -f %s/*' % cnfData['dirStore']) #logger.logger('Customizing Spiders') #spiderGenerator = SpiderGenerator('template', 'spider/spiders') #for spider in cnfData['spiders']: # spiderGenerator.gen_spider(spider, cnfData[spider]['startPage'], cnfData[spider]['stopPage']) rpQueue = Queue() pdQueue = Queue() dpQueue = Queue() pdLock = threading.Lock() rpcMonitor = RpcMonitor(logger, cnfData['rpcPort'], cnfData['rpcAuth'], 'RpcMonitor') rpcMonitor.setGlobalInfo(ndutil.getCurrentTimeStr(), 'Standalone', dlThreadNum) rpcMonitor.setDownloadTotal(pdQueue.qsize()) rpcMonitor.setPdQueueSize(pdQueue.qsize()) botScheduler = BotScheduler(logger, rpcMonitor, cnfData['spiders'], cnfData['spiderCnfs'], 'BotScheduler') receiver = Receiver(logger, rpcMonitor, rpQueue, cnfData['receiverPort'], 'Receiver') preProcessor = PreProcessor(logger, rpcMonitor, rpQueue, pdQueue, pdLock, dbManager, 'PreProcessor') downloader = Downloader([logger, rpcMonitor, pdQueue, dpQueue, pdLock, dlThreadNum, cnfData['dirWorking']], 'Downloader') processor = Processor(logger, rpcMonitor, dpQueue, pdLock, pdQueue, dbManager, cnfData['dirWorking'], cnfData['dirStore'], 'Processor') logger.logger('Starting Threads') rpcMonitor.start() botScheduler.start() receiver.start() preProcessor.start() downloader.start() processor.start() processor.join() downloader.join() preProcessor.join() receiver.join() botScheduler.join() rpcMonitor.join()
def __init__(self, *, port: str, baudrate: int, path: str = 'db', bs: int = 32, to: int = 5, http: int = 8080): super().__init__() pid = os.getpid() logger.info('*** NMEA Recorder startup (%d)' % pid) self.process: Dict[str, int] = {} self.process['main'] = pid self.ppp: Dict[str, Patrol] = {} self.ppp['main'] = Patrol(pid=pid) self.ready: bool = True self.g = GPS() self.ws = WebsocketServer(debug=True) self.qp = Queue() self.dbsession = DBSession(path=pathlib.Path(path), buffersize=bs, timeout=to) self.dbsession.start() self.process[self.dbsession.name] = self.dbsession.pid self.ppp[self.dbsession.name] = Patrol(pid=self.dbsession.pid) self.receiver = Receiver(port=port, baudrate=baudrate, qp=self.qp) self.receiver.start() self.process[self.receiver.name] = self.receiver.pid self.ppp[self.receiver.name] = Patrol(pid=self.receiver.pid) self.mc = fromUDP(quePoint=self.qp, mcip='239.192.0.1', mcport=60001) self.mc.start() self.process[self.mc.name] = self.mc.pid self.ppp[self.mc.name] = Patrol(pid=self.mc.pid) self.main = Thread(target=self.collector, name='MainLoop', daemon=True) self.main.start() self.p = Thread(target=self.patrol, name='Patrol', daemon=True) self.p.start() for k, v in self.ppp.items(): v.start() self.add_route('/ws', self.ws.wsserver, websocket=True) self.add_route('/', self.top) self.add_route('/main.js', self.mainJS) self.add_route('/classes.js', self.classes) self.add_event_handler('shutdown', self.cleanup) # notice! self.run(address='0.0.0.0', port=http)
def bootstrap_connection(self): """ Initializes the receiver and sender threads """ self.receiver = Receiver(self.conn_socket, self.receiver_q, self.config.debug_token) self.receiver.start() self.sender = Sender(self.conn_socket, self.sender_q, self.config.debug_token) self.sender.start() self.config.state = State.UNSECURED_CONN
def verify(self, plain_text): sender = Sender(self) receiver = Receiver(self) self.generate_keys(sender, receiver) cypher_text = self.encode(plain_text, sender.get_key()) decoded_text = self.decode(cypher_text, receiver.get_key()) if plain_text == decoded_text: return True return False
def run_node(transmission_protocol, identifier, sender_ipc_topology, receiver_ipc_topology, senders_ipc_neighbor, receivers_ipc_neighbor): node = Node(identifier=identifier) node.sender_des_node_ = Sender(sender_ipc_topology, transmission_protocol, verbose=False) node.receiver_des_node_ = Receiver(receiver_ipc_topology, transmission_protocol, verbose=False) for i, ipc in senders_ipc_neighbor.items(): node.senders_neighbors_[i] = Sender(ipc, transmission_protocol, verbose=False) for i, ipc in receivers_ipc_neighbor.items(): node.receivers_neighbors_[i] = Receiver(ipc, transmission_protocol, verbose=False) node.run()
def __init__(self, packet_sender): print 'Init Connection' self.ee = EventEmitter() self._sender = Sender(packet_sender) self._receiver = Receiver(packet_sender) @self._receiver.ee.on('data') def on_data(data): self.ee.emit('data', data)
def main(): setting.init() host = input("Your IP or hostname: ") port = int(input("Your port: ")) receiver = Receiver(host, port) partner_host = input("Partner's IP or hostname: ") partner_port = int(input("Partner's port: ")) sender = Sender(partner_host, partner_port) threads = [receiver.start(), sender.start()]
def run(self): self.done = Event() while not self.done.isSet(): print('Waiting for clients') client_sock, client_info = self.server_sock.accept() r = Receiver(self, client_sock, client_info) r.daemon = True r.start() self.server_sock.close() print('The server socket has been closed')
def __init__(self, port): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(0.05) self.sock.connect(('localhost', port)) self.receiver = Receiver(self.sock) self.name = f'({port})' attributes = self.req('attributes') self.name = attributes['name'] color = attributes['color'] self.color = (color['r'], color['g'], color['b']) self.points = 0
def start_recvers(self): for port in self.cl_port_list: addr = (self.cl_ip, port) recver = Receiver(in_queue = self.queue_torecvers, laddr = addr, proto = self.proto, rx_type = self.rx_type, file_url = 'rx_over_%s.dat' % port, logto = self.logto ) recver.start() self.recver_thread_list.append(recver)
def main(): if len(sys.argv) == 5: filename = sys.argv[1] card_type = sys.argv[2] energy_constraint = sys.argv[3] chan_pred = eval(sys.argv[4]) increment = 1 print "filename: "+str(filename) elif len(sys.argv) == 6: filename = sys.argv[1] card_type = sys.argv[2] energy_constraint = sys.argv[3] chan_pred = eval(sys.argv[4]) increment = eval(sys.argv[5]) print "filename: "+str(filename) else: print "Correct usage: python simulate_maxtput.py trace_file card_type tx/rx pred(True/False) chan_increment" sys.exit(1) nrx=3 # Create a tx ntx=3 ta = None transmitter = Transmitter(ntx,ta) # Create a channel chan = TraceChan(filename, increment) length = chan.create_chan(transmitter.Ntx,nrx) extname=filename.split('/')[-1].split('.')[0]+"_"+card_type+"_"+energy_constraint+"_pred"+str(chan_pred)+"_inc"+str(increment) print extname receiver = Receiver(MaxTputRA(card_type,energy_constraint,chan_pred),nrx,extname) #length =22 if length > 10000: length = 10000 for num in range(0,length): itr_tic = time.clock() pkt = transmitter.transmit_pkt() chan.apply_channel(pkt) #print chan.curr_chan #print pkt # Create receiver receiver.receive_pkt(pkt) ack_pkt = receiver.get_feedback_pkt() transmitter.process_ack(ack_pkt) itr_toc = time.clock() print "one itr: "+str(itr_toc - itr_tic)
def verify_cipher(cipher_name, key_word=''): """ Main method to test ciphers """ # Instantiate cipher cipher = None if cipher_name == 'caesar': cipher = Caesar() elif cipher_name == 'multiplication': cipher = Multiplication() elif cipher_name == 'affine': cipher = Affine() elif cipher_name == 'unbreakable': cipher = Unbreakable() elif cipher_name == 'rsa': cipher = RSA() else: raise Exception('Cipher name not recognised') print(('\nTesting %s cipher:\n' % cipher_name).upper()) # Define sender and receiver sender = Sender(cipher) receiver = Receiver(cipher) # Distribute key(s) if cipher_name == 'unbreakable': encryption_key, decryption_key = cipher.generate_keys(key_word) else: encryption_key, decryption_key = cipher.generate_keys() sender.set_key(encryption_key) receiver.set_key(decryption_key) # Create message and send it message = "Hello world" # message = "aaaaaaaaaaa" sender.send(message, receiver) print("\nSender message: ", sender.message) print("Sender encoded: ", sender.encoded_message) print("Receiver encoded:", receiver.encoded_message) print("Receiver decoded:", receiver.message) hack = input('\nDo you want to try and hack this message? (y/n): ') if hack == 'y': hacker = Hacker(cipher) if cipher_name in ('caesar', 'multiplication'): hacker.hack_caesar_or_multiplication(sender.encoded_message) elif cipher_name == 'affine': hacker.hack_affine(sender.encoded_message) elif cipher_name == 'unbreakable': hacker.hack_unbreakable(sender.encoded_message) else: print('No can do :P')
def __init__(self, source_addr, dest_addr): self.source_addr = source_addr self.dest_addr = dest_addr self.q = Queue() self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(source_addr) self.connections = {} self.users = self.get_users() self.r = Receiver(self.sock, self.q, self.connections) self.s = Sender(self.sock, self.q) self.r.start() self.s.start()
def prepare_email_content(email_address, subject): #construct Receiver, Content and Attachment Class r = Receiver() c = Content() a = Attachment() msg = EmailMessage() msg['Subject'] = subject msg['To'] = ', '.join(r.get_receiver()) msg['From'] = email_address msg.set_content(c.get_content()) set_attachment(msg, a.get_attachments()) return msg
class Conversation: def __init__(self, user, replier): self.user = user self.conversation_id = start_conversation() self.sender = Sender(self.conversation_id, user.username) self.receiver = Receiver(user.username, self.conversation_id, replier) self.last_used_time = time.time() def dispose(self): self.receiver.dispose() def is_overdue(self, now): return now - self.last_used_time > config.overdue_time
def setUp(self): streamers = ["alice", "bob", "carlos", "davis", "egbert"] self.oqdict = { "alice": 0, "bob": 1, "carlos": 2, "davis": 3, "egbert": 4 } self.receiverFull = Receiver(queues=[Queue(s) for s in streamers], fps=30) self.receiverSimple = Receiver( queues=[Queue(s) for s in streamers[:2]], fps=30)
def main(): users = Users() receiver = Receiver() sender = Sender() while True: receiver.read_emails(users) for user in users.users_map.values(): if user.modified: sender.send_news(user.email, list(user.topics_set)) user.modified = False print ('Sleeping') sleep(10) print ('Waking up')
def run(): pygame.init ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) receiver = Receiver(ai_settings, screen) ball = Ball(ai_settings,screen) while True: gf.check_events(receiver) if ball.game_active: gf.update_balls(ai_settings,screen,ball,receiver) receiver.update() gf.update_screen(ai_settings,screen,receiver,ball)
def __init__(self): self.socket_object = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket_object.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) self._connect() self.input_service = InputManager() self.sender_service = Sender() self.protocol = Client2Server() self.receiver_service = Receiver() self.username = None self.is_authenticated = False self._authenticate()
def main(): if len(sys.argv) == 5: filename = sys.argv[1] card_type = sys.argv[2] energy_constraint = sys.argv[3] chan_pred = eval(sys.argv[4]) increment = 1 print "filename: "+str(filename) elif len(sys.argv) == 6: filename = sys.argv[1] card_type = sys.argv[2] energy_constraint = sys.argv[3] chan_pred = False increment = eval(sys.argv[5]) print "filename: "+str(filename) else: print "Correct usage: python simulate_effsnr.py trace_file card_type tx/rx pred(True/False)" sys.exit(1) nrx=3 # Create a tx ntx=3 ta = None transmitter = Transmitter(ntx,ta) # Create a channel chan = TraceChan(filename, increment) num_chans=1 length = chan.create_chan(transmitter.Ntx,nrx) ta = OracleEffSnrRA(card_type,energy_constraint,chan) transmitter.set_transmit_ra(ta) extname=ta.name+"_"+filename.split('/')[-1].split('.')[0]+"_"+card_type+"_"+energy_constraint+"_pred"+str(chan_pred)+"_inc"+str(increment) receiver = Receiver(RxOracle(card_type,energy_constraint),nrx,extname) if length > 10000: length = 10000 #length =10 for num in range(0,length): pkt = transmitter.transmit_pkt() chan.apply_channel(pkt) #print chan.curr_chan #print pkt # Create receiver receiver.receive_pkt(pkt) ack_pkt = receiver.get_feedback_pkt() transmitter.process_ack(ack_pkt)
class Broadcaster(object): def __init__(self): self._receiver = None def register(self, receiver): self._receiver = Receiver(receiver) def has_receivers(self): if self._receiver: return True else: return False def broadcast(self): self._receiver.notify()
def list_of_receivers_creation(room, len_x, len_y): """ ajout des recepteurs dans toute la piece. Sur l'axe horizontal un recepteur tous les (1/len_x) metre, sur l'axe vertical un recepteur tous les (1/len_y) metre """ x_min = x_max = y_min = y_max = 0 for wall in room.list_of_walls: if x_max < wall.list_of_points[0][0]: x_max = wall.list_of_points[0][0] if x_max < wall.list_of_points[1][0]: x_max = wall.list_of_points[1][0] if x_min > wall.list_of_points[0][0]: x_min = wall.list_of_points[0][0] if x_min > wall.list_of_points[1][0]: x_min = wall.list_of_points[1][0] if y_max < wall.list_of_points[0][1]: y_max = wall.list_of_points[0][1] if y_max < wall.list_of_points[1][1]: y_max = wall.list_of_points[1][1] if y_min > wall.list_of_points[0][1]: y_min = wall.list_of_points[0][1] if y_min > wall.list_of_points[1][1]: y_min = wall.list_of_points[1][1] len_x = len_x len_y = len_y for i in range(x_min, len_x * (x_max - x_min)): for j in range(y_min, len_y * (y_max - y_min)): room.list_of_receivers.append( Receiver((x_min + (i + 1) / len_x, y_min + (j + 1) / len_y), "lambda-demi")) return 0
def main(): receiver = Receiver() sender = Sender() thread.start_new_thread(receiver.listen, ()) time.sleep(1) sender.send()
def on_message(self, ws, message): try: message = json.loads(message) logging.debug("Received message from server:") logging.debug(message) except: logging.debug("[Error] Couldn't read message: %s" % (message, )) return if not self.receive: return logging.debug("Running receivers: {}".format(Receiver.receivers)) for client in message["clients"]: name = client["name"] if name in Receiver.receivers: logging.debug("Receiver for {} already running".format(name)) continue elif name != self.name: logging.debug("Starting receiver for {}".format(name)) receiver = Receiver(**client) receiver() # Check connected receivers and disconnect any that is not # on the client list obtained from server connected_client_names = [ client["name"] for client in message["clients"] if client["name"] != self.name ] for client_name in Receiver.receivers.copy(): if client_name not in connected_client_names: Receiver.receivers[client_name].stop() logging.info( "Receiver for {} disconnected".format(client_name)) if "message" in message: logging.debug(message["message"]) else: logging.debug(message)
async def _verify_tcp_req(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> Receiver: conn = TcpReceiverConn(writer=writer, reader=reader) try: json_data = await conn.recv_json() if json_data is not None: orig_key = json_data['data']['key'] key = sql.is_key_verified(orig_key) if key is not None: if self._broadcaster.can_pass_max_users_test( key.key_index, key.key_max_users): user = Receiver(user_conn=conn, user_key_index=key.key_index) return user else: info(f'KEY({key.key_index[:5]}***...)用户过多') raise tcp_req_exception.MaxError(conn) else: info('有人恶意尝试KEY') raise tcp_req_exception.VerificationError(conn) else: raise tcp_req_exception.DataError(conn) except tcp_req_exception.TcpReqError: raise except: raise tcp_req_exception.OtherError(conn)
async def _verify_tcp_req(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> Receiver: conn = TcpReceiverConn(writer=writer, reader=reader) addr, _ = writer.get_extra_info('peername') if isinstance(addr, str) and self._blacklist.should_be_banned(addr): print(f'拒绝黑名单用户 IP {addr} 连接请求') self._blacklist.refresh(addr) raise tcp_req_exception.BanError(conn) json_data = await conn.recv_json() if json_data is not None and isinstance(json_data, dict) and 'data' in json_data: data = json_data['data'] if isinstance(data, dict) and 'key' in data: try: orig_key = str(data['key']) key_index = self._key_handler.verify_key(orig_key) print(f'来自 IP {addr}的用户 {key_index[:5]} 成功验证身份') return Receiver(user_conn=conn, user_key_index=key_index) except KeyCheckMaxError: print(f'IP {addr} 使用的 key 已连接用户过多') raise tcp_req_exception.MaxError(conn) except KeyCheckVerificationError: self._blacklist.refresh(addr) print(f'IP {addr} 错误尝试 key') raise tcp_req_exception.VerificationError(conn) except: raise tcp_req_exception.DataError(conn) raise tcp_req_exception.DataError(conn)
def drive(cfg, client_ip=None, to_control=False): #Initialize car V = vehicle.Vehicle() client_ip = client_ip or cfg.CLIENT_IP camA = CSICamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE, gstreamer_flip=cfg.CSIC_CAM_GSTREAMER_FLIP_PARM, client_ip=client_ip) camB = RS_D435i(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE, client_ip=client_ip) V.add(camA, outputs=['cam/image_array_a'], threaded=True) V.add(camB, outputs=['cam/image_array_b', 'cam/image_array_c'], threaded=True) if to_control: V.add(NaiveController(), outputs=['throttle', 'steering'], threaded=True) V.add(Sender(), inputs=['throttle', 'steering'], threaded=True) else: V.add(Receiver(client_ip), threaded=True) #run the vehicle for 20 seconds V.start(rate_hz=cfg.DRIVE_LOOP_HZ, max_loop_count=cfg.MAX_LOOPS)
def main(): user_data = input().split() user = User(user_data[0], user_data[1], int(user_data[2])) book_data = Receiver(user).collect_books() chosen_book = Selector(book_data).select_book() print(chosen_book)
def setup(self, pw = None): info('controller', 'setup') self.receiver = Receiver() self.sender = Sender() self.signer = Signer(pw) info('controller', 'sender process') self.sendPipe, sendPipe = mp.Pipe() self.senderProcess = mp.Process(target=self.sender.start, name='sender', args=(sendPipe,)) info('controller', 'signer process') self.signPipe, signPipe = mp.Pipe() self.signerProcess = mp.Process(target=self.signer.start, name='signer', args=(signPipe,)) info('controller', 'receiver process') self.receivePipe, receivePipe = mp.Pipe() self.receiverProcess = mp.Process(target=self.receiver.start, name='receiver', args=(receivePipe,))
def main(): global indexer, uploader, sender, receiver, downloader setup_signals() logging.info("Asink client started at %s" % (time.strftime("%a, %d %b %Y %X GMT", time.gmtime()))) #create all threads which will be used to process events indexer = Indexer() uploader = Uploader() sender = Sender() receiver = Receiver() downloader = Downloader() #create and set up queues which are used to pass events between threads uploader_queue = Queue() indexer.uploader_queue = uploader_queue uploader.queue = uploader_queue #set on watcher when initialized sender_queue = Queue() uploader.sender_queue = sender_queue sender.queue = sender_queue downloader_queue = Queue() receiver.downloader_queue = downloader_queue downloader.queue = downloader_queue #setup storage provider storage = setup_storage() uploader.storage = storage.clone() downloader.storage = storage #start all threads watcher.start_watching(uploader_queue) indexer.start() uploader.start() sender.start() receiver.start() downloader.start() #sleep until signaled, which will call sig_handler while True: time.sleep(86400) #= 24 hours just for fun
def welcome_s(self, data_): sch_req_id = data_['sch_req_id'] stpdst = data_['tp_dst'] qtorecver = Queue.Queue(0) qfromrecver = Queue.Queue(0) laddr = (self.cl_ip, int(stpdst)) recver = Receiver(in_queue = qtorecver, out_queue = qfromrecver, laddr = laddr, proto = self.proto, rx_type = 'kstardata', file_url = 'kstardata_%s.dat' % stpdst, logto = self.logto ) recver.start() # self.sinfo_dict[sch_req_id] = {'tp_dst': stpdst, 'qtorecver': qtorecver, 'qfromrecver': qfromrecver } logging.info('welcome_s:: welcome sinfo=\n%s', pprint.pformat(self.sinfo_dict[sch_req_id])) threading.Thread(target = self.waitfor_couplingtoend, kwargs = {'sch_req_id': sch_req_id} ).start()
def handle_block(new_block_size, E, K): # Simulator.simulate returns the number of bit errors in each block bit_errors = Simulator.simulate(new_block_size, E) Statistics.update(Statistics.total_transmitions) if (bit_errors != 0): Statistics.update(Statistics.block_errors) try: Receiver.receive(bit_errors) Statistics.update(Statistics.no_error) Statistics.update(Statistics.correctly_received_blocks) return 0 except OneBitError: Statistics.update(Statistics.one_bit_error) if (K != 0): Statistics.update(Statistics.correctly_received_blocks) # Assume: Fixing the error requires 0 trials_time units return 0 return bit_errors except MultipleBitErrors: Statistics.update(Statistics.multiple_bit_errors) return bit_errors
class Connection: def __init__(self, packet_sender): print 'Init Connection' self.ee = EventEmitter() self._sender = Sender(packet_sender) self._receiver = Receiver(packet_sender) @self._receiver.ee.on('data') def on_data(data): self.ee.emit('data', data) def send(self, data): self._sender.send(data) def receive(self, packet): if packet.getIsAcknowledgement(): self._sender.verifyAcknowledgement(packet.getSequenceNumber()) else: self._receiver.receive(packet)
def main(): sender = Sender('localhost') sender.connect() sender.create_queue('inbox') sender.send_message('inbox', 'hello') sender.disconnect() receiver = Receiver('localhost') receiver.connect() receiver.receive('inbox') receiver.disconnect()
def main(): if len(sys.argv) == 6: filename = sys.argv[1] card_type = sys.argv[2] energy_constraint = sys.argv[3] chan_pred = eval(sys.argv[4]) threshold = eval(sys.argv[5]) print "filename: "+str(filename) else: print "Correct usage: python simulate_engtput.py trace_file card_type tx/rx pred(True/False)" sys.exit(1) nrx=3 # Create a tx ntx=3 ta = None transmitter = Transmitter(ntx,ta) # Create a channel chan = TraceChan(filename) num_chans=1 length = chan.create_chan(transmitter.Ntx,nrx) extname=filename.split('/')[-1].split('.')[0]+"_"+card_type+"_"+energy_constraint+"_pred"+str(chan_pred)+"th"+str(threshold) receiver = Receiver(EffSnrRAEngTput(card_type,energy_constraint,chan_pred,threshold),nrx,extname) for num in range(0,length): pkt = transmitter.transmit_pkt() chan.apply_channel(pkt) #print chan.curr_chan #print pkt # Create receiver receiver.receive_pkt(pkt) ack_pkt = receiver.get_feedback_pkt() transmitter.process_ack(ack_pkt)
def __init__(self, UPLOAD=True, USE_GUI=True, USE_FILESTREAM=False): self._socket_address = 'src/client/data_stream.sock' self._receiver = Receiver(self._socket_address) self._geo_listen = Geometry() self._frequency = 15 if USE_FILESTREAM: self._stream = FileStream( "gen_data/downtown-east2_only_turn_sigs_speed_lims.json", self._socket_address) self._send_frequency = 1 self._speed_limit = None self._speed_time = None self._gui = None self._forgot_signals_event = threading.Event() self._speeding_event = threading.Event() self._aggressive_event = threading.Event() self._green_event = threading.Event() self._green_event.direction = None self._speeding_event.speed_limit = None self._last_turn_forget = None self._turn_analyzer = TurnSignalAnalyzer(self._forgot_signals_event) self._speeding_analyzer = SpeedingAnalyzer(self._speeding_event) self._green = Green(1, self._green_event) self._aggressive_analyze = AggressiveAnalyzer(self._aggressive_event) self._evaluatebox_last_time = None if USE_GUI: self._gui = GUI(self._receiver.is_alive) t = threading.Thread(target=self._mainloop, daemon=True) t.daemon = True t.start() if UPLOAD: self._distributor = Distributor( '/src/client/upload_stream.sock', self._send_frequency) s = threading.Thread(target=self._sender, daemon=True) s.start() if USE_GUI: self._gui.mainloop() else: self._receiver.join() # keep main from exiting
import random from receiver import Receiver # tests the receiver a = [] e = [] rec = Receiver() for i in range(25): for j in range(10): a.append(random.randint(1, 100)) e.append(random.randint(1, 100)) print "sending: %r" % i rec.receiveIdeal(e, a) e = [] a = [] rec.hangUp()
channel = bch.BypassChannel(opt.noise, opt.lag, h) else: channel = ach.AudioChannel(opt.samplerate, opt.chunksize, opt.prefill) # transmit the samples, and retrieve samples back from the channel try: samples_rx = channel.xmit_and_recv(mod_samples) except ZeroDivisionError: # should only happen for audio channel print "I didn't get any samples; is your microphone or speaker OFF?" sys.exit(1) ################################# # process the received samples # make receiver r = Receiver(fc, opt.samplerate, opt.spb) demod_samples = r.demodulate(samples_rx) one, zero, thresh = r.detect_threshold(demod_samples) barker_start = r.detect_preamble(demod_samples, thresh, one) rcdbits = r.demap_and_check(demod_samples, barker_start) decoded_bits = r.decode(rcdbits) # push into sink sink = Sink() rcd_payload = sink.process(decoded_bits) if len(rcd_payload) > 0: hd, err = common_srcsink.hamming(decoded_bits, databits) print 'Hamming distance for payload at frequency', fc,'Hz:', hd, 'BER:', err else: print 'Could not recover transmission.'
def run(self): sleep_time = 0 while True: if (os.getppid() != self.ppid): logger.info('parent exited. aborting.') break try: self.rep_ip = self._replication_interface() break except: time.sleep(1) sleep_time = sleep_time + 1 if (sleep_time % 30 == 0): msg = ('Failed to get replication interface for last %d' ' seconds' % sleep_time) logger.info('failed to get replication interface') ctx = zmq.Context() #fs diffs are sent via this publisher. rep_pub = ctx.socket(zmq.PUB) rep_pub.bind('tcp://%s:%d' % (self.rep_ip, self.data_port)) #synchronization messages are received in this pull socket meta_pull = ctx.socket(zmq.PULL) meta_pull.RCVTIMEO = 100 meta_pull.bind('tcp://%s:%d' % (self.rep_ip, self.meta_port)) total_sleep = 0 while True: if (os.getppid() != self.ppid): logger.info('parent exited. aborting.') break while(not self.pubq.empty()): msg = self.pubq.get() rep_pub.send(msg) #check for any recv's coming try: self.recv_meta = meta_pull.recv_json() snap_id = self.recv_meta['id'] if (self.recv_meta['msg'] == 'begin'): logger.info('begin received. meta: %s' % self.recv_meta) rw = Receiver(self.recv_meta, Queue()) self.receivers[snap_id] = rw rw.start() elif (self.recv_meta['msg'] == 'begin_ok'): self.senders[snap_id].q.put('send') elif (self.recv_meta['msg'] == 'receive_ok' or self.recv_meta['msg'] == 'receive_error'): self.senders[snap_id].q.put(self.recv_meta['msg']) except zmq.error.Again: pass self._prune_workers((self.receivers, self.senders)) if (total_sleep >= 60 and len(self.senders) < 50): logger.info('scanning for replicas') for r in Replica.objects.filter(enabled=True): rt = ReplicaTrail.objects.filter(replica=r).order_by('-snapshot_created') now = datetime.utcnow().replace(second=0, microsecond=0, tzinfo=utc) sw = None snap_name = ('%s_replica_snap' % r.share) if (len(rt) == 0): snap_name = ('%s_1' % snap_name) sw = Sender(r, self.rep_ip, self.pubq, Queue(), snap_name) elif (rt[0].status == 'succeeded' and (now - rt[0].end_ts).total_seconds() > r.frequency): snap_name = ('%s_%d' % (snap_name, rt[0].id + 1)) sw = Sender(r, self.rep_ip, self.pubq, Queue(), snap_name, rt[0]) else: continue snap_id = ('%s_%s_%s_%s' % (self.rep_ip, r.pool, r.share, snap_name)) self.senders[snap_id] = sw sw.daemon = True sw.start() total_sleep = 0 time.sleep(1) total_sleep = total_sleep + 1
shutil.rmtree(filename, True) logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S", filename=filename, filemode="w") console = logging.StreamHandler() console.setLevel(logging.NOTSET) formatter = logging.Formatter("%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s") console.setFormatter(formatter) logging.getLogger('').addHandler(console) if __name__ == '__main__': InitLogging() handler = Handler() receiver = Receiver() transmitter = Transmitter() receiver.connect() td1 = threading.Thread(target=handler.run) td2 = threading.Thread(target=receiver.run) td3 = threading.Thread(target=transmitter.run) td1.start() td2.start() td3.start() # main loop while True: if handler.is_runing() and receiver.is_runing() and transmitter.is_runing(): msg = receiver.fetch() while msg != None:
def run(config): '''Primary Audiocom functionality.''' # Create the preamble to pre-pend to the transmission preamble = Preamble(config) # Create the sources sources = {} for i in range(len(config.channels)): frequency = config.channels[i] source = Source(config, i) print "Channel: %d Hz" % frequency print "\n".join(["\t%s" % source]) sources[frequency] = source # Create a sender for each source, so we can process the bits to # get the modulated samples. We combine all of the modulated # samples into a single array by adding them. modulated_samples = [] for frequency in sources: src = sources[frequency] sender = Sender(frequency, preamble, config) sender.set_source(src) modulated_samples = util.add_arrays(sender.modulated_samples(), modulated_samples) # Create the channel if config.bypass: channel = AbstractChannel(config.bypass_noise, config.bypass_h, config.bypass_lag) else: channel = AudioChannel(config) # Transmit and receive data on the channel. The received samples # (samples_rx) have not been processed in any way. samples_rx = channel.xmit_and_recv(modulated_samples) print 'Received', len(samples_rx), 'samples' for frequency in config.channels: r = Receiver(frequency, preamble, config) try: # Call the main receiver function. The returned array of bits # EXCLUDES the preamble. bits = r.process(samples_rx) # Push into a Sink so we can convert back to a useful payload # (this step will become more useful when we're transmitting # files or images instead of just bit arrays) src = sources[frequency] sink = Sink(src) received_payload = sink.process(bits) print "Received %d data bits" % len(received_payload) if src.type == Source.TEXT: print "Received text was:", sink.received_text if len(received_payload) > 0: # Output BER hd = util.hamming(received_payload, src.payload) ber = float(hd)/len(received_payload) print 'BER:', ber else: print 'Could not recover transmission.' except Exception as e: # In general, this is a fatal exception. But we'd still like # to look at the graphs, so we'll continue with that output print '*** ERROR: Could not detect preamble. ***' print repr(e) # Plot graphs if necessary if config.graphs: try: len_demod = config.spb * (len(received_payload) + preamble.preamble_data_len()) except: # If we didn't receive the payload, make a reasonable guess for the number of bits # (won't work for filetype, where n_bits changes) len_demod = config.spb * (config.n_bits + preamble.preamble_data_len()) if config.demod_type == Receiver.QUADRATURE: filtered = r.graph_info.demod_samples graphs.plot_sig_spectrum(samples_rx, filtered, "received samples", "filtered samples") elif config.src_type == Source.U: demod_samples = r.graph_info.demod_samples plotrange = preamble.preamble_data_len()*config.spb graphs.plot_samples(demod_samples[plotrange:len_demod], 'unit-step response', show=True) else: graphs.plot_graphs(r.graph_info.demod_samples[:len_demod], r.graph_info.hist_samples[:len_demod], config.spb, preamble)
exit(1) def printHelp(): print(""" -w - ожидание сеанса измерения скорости -с [ip] [packet size] [packets count] - измерение скорости с ip, отправка packet count пакетов по packet size байт каждый """) if __name__ == "__main__": if len(sys.argv) == 1: printHelp() else: argsInfo = parseArgs(sys.argv) if argsInfo == Mode.help: printHelp() try: if argsInfo[0] == Mode.wait: receiver = Receiver() receiver.start() else: sender = Sender(destIP=argsInfo[1]["ip"], packetSize=argsInfo[1]["packet_size"], packetsToSend=argsInfo[1]["packets_count"]) sender.measure() except Exception as e: fatalError(e)
def run(self): self.law = APIWrapper() try: so = Service.objects.get(name='replication') config_d = json.loads(so.config) self.listener_port = int(config_d['listener_port']) nco = NetworkConnection.objects.get( name=config_d['network_interface']) self.listener_interface = nco.ipaddr except NetworkConnection.DoesNotExist: self.listener_interface = '0.0.0.0' except Exception as e: msg = ('Failed to fetch network interface for Listner/Broker. ' 'Exception: %s' % e.__str__()) return logger.error(msg) try: self.uuid = Appliance.objects.get(current_appliance=True).uuid except Exception as e: msg = ('Failed to get uuid of current appliance. Aborting. ' 'Exception: %s' % e.__str__()) return logger.error(msg) ctx = zmq.Context() frontend = ctx.socket(zmq.ROUTER) frontend.set_hwm(10) frontend.bind('tcp://%s:%d' % (self.listener_interface, self.listener_port)) backend = ctx.socket(zmq.ROUTER) backend.bind('ipc://%s' % settings.REPLICATION.get('ipc_socket')) poller = zmq.Poller() poller.register(frontend, zmq.POLLIN) poller.register(backend, zmq.POLLIN) self.local_receivers = {} iterations = 10 poll_interval = 6000 # 6 seconds msg_count = 0 while True: # This loop may still continue even if replication service # is terminated, as long as data is coming in. socks = dict(poller.poll(timeout=poll_interval)) if (frontend in socks and socks[frontend] == zmq.POLLIN): address, command, msg = frontend.recv_multipart() if (address not in self.remote_senders): self.remote_senders[address] = 1 else: self.remote_senders[address] += 1 msg_count += 1 if (msg_count == 1000): msg_count = 0 for rs, count in self.remote_senders.items(): logger.debug('Active Receiver: %s. Messages processed:' '%d' % (rs, count)) if (command == 'sender-ready'): logger.debug('initial greeting from %s' % address) # Start a new receiver and send the appropriate response try: start_nr = True if (address in self.local_receivers): start_nr = False ecode = self.local_receivers[address].exitcode if (ecode is not None): del self.local_receivers[address] logger.debug('Receiver(%s) exited. exitcode: ' '%s. Forcing removal from broker ' 'list.' % (address, ecode)) start_nr = True else: msg = ('Receiver(%s) already exists. ' 'Will not start a new one.' % address) logger.error(msg) # @todo: There may be a different way to handle # this. For example, we can pass the message to # the active receiver and factor into it's # retry/robust logic. But that is for later. frontend.send_multipart( [address, 'receiver-init-error', msg]) if (start_nr): nr = Receiver(address, msg) nr.daemon = True nr.start() logger.debug('New Receiver(%s) started.' % address) self.local_receivers[address] = nr continue except Exception as e: msg = ('Exception while starting the ' 'new receiver for %s: %s' % (address, e.__str__())) logger.error(msg) frontend.send_multipart( [address, 'receiver-init-error', msg]) else: # do we hit hwm? is the dealer still connected? backend.send_multipart([address, command, msg]) elif (backend in socks and socks[backend] == zmq.POLLIN): address, command, msg = backend.recv_multipart() if (command == 'new-send'): rid = int(msg) logger.debug('new-send request received for %d' % rid) rcommand = 'ERROR' try: replica = Replica.objects.get(id=rid) if (replica.enabled): self._process_send(replica) msg = ('A new Sender started successfully for ' 'Replication Task(%d).' % rid) rcommand = 'SUCCESS' else: msg = ('Failed to start a new Sender for ' 'Replication ' 'Task(%d) because it is disabled.' % rid) except Exception as e: msg = ('Failed to start a new Sender for Replication ' 'Task(%d). Exception: %s' % (rid, e.__str__())) logger.error(msg) finally: backend.send_multipart([address, rcommand, str(msg)]) elif (address in self.remote_senders): if (command in ('receiver-ready', 'receiver-error', 'btrfs-recv-finished')): # noqa E501 logger.debug('Identitiy: %s command: %s' % (address, command)) backend.send_multipart([address, b'ACK', '']) # a new receiver has started. reply to the sender that # must be waiting frontend.send_multipart([address, command, msg]) else: iterations -= 1 if (iterations == 0): iterations = 10 self._prune_senders() self._delete_receivers() cur_time = time.time() if (self.trail_prune_time is None or (cur_time - self.trail_prune_time) > 3600): # prune send/receive trails every hour or so. self.trail_prune_time = cur_time map(self.prune_replica_trail, Replica.objects.filter()) map(self.prune_receive_trail, ReplicaShare.objects.filter()) logger.debug('Replica trails are truncated ' 'successfully.') if (os.getppid() != self.ppid): logger.error('Parent exited. Aborting.') ctx.destroy() # do some cleanup of senders before quitting? break
class GCS: def __init__(self): # No communications or arming yet self.comms = None self.armed = False # Do basic Tk initialization self.root = Tk() self.root.configure(bg=BACKGROUND_COLOR) self.root.resizable(False, False) self.root.title('Hackflight Ground Control Station') left = (self.root.winfo_screenwidth() - DISPLAY_WIDTH) / 2 top = (self.root.winfo_screenheight() - DISPLAY_HEIGHT) / 2 self.root.geometry('%dx%d+%d+%d' % (DISPLAY_WIDTH, DISPLAY_HEIGHT, left, top)) self.frame = Frame(self.root) self.root.wm_iconbitmap(bitmap = "@media/icon.xbm") self.root.tk.call('wm', 'iconphoto', self.root._w, PhotoImage('icon.png')) self.root.protocol('WM_DELETE_WINDOW', self.quit) # Create panes for two rows of widgets self.pane1 = self._add_pane() self.pane2 = self._add_pane() # Add a buttons self.button_connect = self._add_button('Connect', self.pane1, self._connect_callback) self.button_setup = self._add_button('Setup', self.pane2, self._setup_callback) self.button_motors = self._add_button('Motors', self.pane2, self._motors_button_callback) self.button_receiver = self._add_button('Receiver', self.pane2, self._receiver_button_callback) self.button_messages = self._add_button('Messages', self.pane2, self._messages_button_callback) #self.button_maps = self._add_button('Maps', self.pane2, self._maps_button_callback, disabled=False) # Prepare for adding ports as they are detected by our timer task self.portsvar = StringVar(self.root) self.portsmenu = None self.connected = False self.ports = [] # Finalize Tk stuff self.frame.pack() self.canvas = Canvas(self.root, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, background='black') self.canvas.pack() # Add widgets for motor-testing dialog; hide them immediately self.motors = Motors(self) self.motors.stop() # Create receiver dialog self.receiver = Receiver(self) # Create messages dialog self.messages = Messages(self) # Create setup dialog self.setup = Setup(self) self._schedule_connection_task() # Create a maps dialog #self.maps = Maps(self, yoffset=-30) # Create a splash image self.splashimage = PhotoImage(file='media/splash.png') self._show_splash() # Create a message parser self.parser = MSP_Parser() # Set up parser's request strings self.attitude_request = self.parser.serialize_ATTITUDE_Request() self.rc_request = self.parser.serialize_RC_Request() # No messages yet self.yaw_pitch_roll = 0,0,0 self.rxchannels = 0,0,0,0,0 # A hack to support display in Setup dialog self.active_axis = 0 def quit(self): self.motors.stop() self.root.destroy() def hide(self, widget): widget.place(x=-9999) def getChannels(self): return self.rxchannels def getYawPitchRoll(self): # configure button to show connected self._enable_buttons() self.button_connect['text'] = 'Disconnect' self._enable_button(self.button_connect) return self.yaw_pitch_roll def checkArmed(self): if self.armed: self._show_armed(self.root) self._show_armed(self.pane1) self._show_armed(self.pane2) self._disable_button(self.button_motors) else: self._show_disarmed(self.root) self._show_disarmed(self.pane1) self._show_disarmed(self.pane2) def scheduleTask(self, delay_msec, task): self.root.after(delay_msec, task) def _add_pane(self): pane = PanedWindow(self.frame, bg=BACKGROUND_COLOR) pane.pack(fill=BOTH, expand=1) return pane def _add_button(self, label, parent, callback, disabled=True): button = Button(parent, text=label, command=callback) button.pack(side=LEFT) button.config(state = 'disabled' if disabled else 'normal') return button # Callback for Setup button def _setup_callback(self): self._clear() self.motors.stop() self.receiver.stop() self.messages.stop() #self.maps.stop() self.parser.set_ATTITUDE_Handler(self._handle_attitude) self.setup.start() def _start(self): self.parser.set_ATTITUDE_Handler(self._handle_attitude) self._send_attitude_request() self.setup.start() self.parser.set_RC_Handler(self._handle_rc) self._send_rc_request() # Sends Attitude request to FC def _send_attitude_request(self): self.comms.send_request(self.attitude_request) # Sends RC request to FC def _send_rc_request(self): self.comms.send_request(self.rc_request) # Callback for Motors button def _motors_button_callback(self): self._clear() self.setup.stop() self.parser.set_ATTITUDE_Handler(self._handle_attitude) self.receiver.stop() self.messages.stop() #self.maps.stop() self.motors.start() def _clear(self): self.canvas.delete(ALL) # Callback for Receiver button def _receiver_button_callback(self): self._clear() self.setup.stop() self.motors.stop() self.messages.stop() #self.maps.stop() self.receiver.start() # Callback for Messages button def _messages_button_callback(self): self._clear() self.setup.stop() self.motors.stop() #self.maps.stop() self.receiver.stop() self.messages.start() def _getting_messages(self): return self.button_connect['text'] == 'Disconnect' # Callback for Maps button def _maps_button_callback(self): self._clear() if self._getting_messages(): self.receiver.stop() self.messages.stop() self.setup.stop() self.motors.stop() #self.maps.start() # Callback for Connect / Disconnect button def _connect_callback(self): if self.connected: self.setup.stop() #self.maps.stop() self.motors.stop() self.messages.stop() self.receiver.stop() if not self.comms is None: self.comms.stop() self._clear() self._disable_buttons() self.button_connect['text'] = 'Connect' self._show_splash() else: #self.maps.stop() self.comms = Comms(self) self.comms.start() self.button_connect['text'] = 'Connecting ...' self._disable_button(self.button_connect) self._hide_splash() self.scheduleTask(CONNECTION_DELAY_MSEC, self._start) self.connected = not self.connected # Gets available ports def _getports(self): allports = comports() ports = [] for port in allports: portname = port[0] if 'ttyACM' in portname or 'ttyUSB' in portname or 'COM' in portname: ports.append(portname) return ports # Checks for changes in port status (hot-plugging USB cables) def _connection_task(self): ports = self._getports() if ports != self.ports: if self.portsmenu is None: self.portsmenu = OptionMenu(self.pane1, self.portsvar, *ports) else: for port in ports: self.portsmenu['menu'].add_command(label=port) self.portsmenu.pack(side=LEFT) if ports == []: self._disable_button(self.button_connect) self._disable_buttons() else: self.portsvar.set(ports[0]) # default value self._enable_button(self.button_connect) self.ports = ports self._schedule_connection_task() # Mutually recursive with above def _schedule_connection_task(self): self.root.after(USB_UPDATE_MSEC, self._connection_task) def _disable_buttons(self): self._disable_button(self.button_setup) self._disable_button(self.button_motors) self._disable_button(self.button_receiver) self._disable_button(self.button_messages) def _enable_buttons(self): self._enable_button(self.button_setup) self._enable_button(self.button_motors) self._enable_button(self.button_receiver) self._enable_button(self.button_messages) def _enable_button(self, button): button['state'] = 'normal' def _disable_button(self, button): button['state'] = 'disabled' def sendMotorMessage(self, index, value): values = [1000]*4 values[index-1] = value self.comms.send_message(self.parser.serialize_SET_MOTOR, values) def _show_splash(self): self.splash = self.canvas.create_image((400,250), image=self.splashimage) def _hide_splash(self): self.canvas.delete(self.splash) def _show_armed(self, widget): widget.configure(bg='red') def _show_disarmed(self, widget): widget.configure(bg=BACKGROUND_COLOR) if self._getting_messages(): self._enable_button(self.button_motors) def _handle_calibrate_response(self): self.setup.showCalibrated() def _handle_params_response(self, pitchroll_kp_percent, yaw_kp_percent): # Only handle parms from firmware on a fresh connection if self.newconnect: self.setup.setParams(pitchroll_kp_percent, yaw_kp_percent) self.newconnect = False def _handle_attitude(self, x, y, z): self.yaw_pitch_roll = z, -y/10., x/10. self.messages.setCurrentMessage('Yaw/Pitch/Roll: %+3.3f %+3.3f %+3.3f' % self.yaw_pitch_roll) # As soon as we handle the callback from one request, send another request self._send_attitude_request() def _handle_rc(self, c1, c2, c3, c4, c5, c6, c7, c8): self.rxchannels = c1, c2, c3, c4, c5 # As soon as we handle the callback from one request, send another request self._send_rc_request() self.messages.setCurrentMessage('Receiver: %04d %04d %04d %04d %04d' % (c1, c2, c3, c4, c5)) def _handle_arm_status(self, armed): self.armed = armed self.messages.setCurrentMessage('ArmStatus: %s' % ('ARMED' if armed else 'Disarmed')) def _handle_battery_status(self, volts, amps): self.messages.setCurrentMessage('BatteryStatus: %3.3f volts, %3.3f amps' % (volts, amps))
def __init__(self): # No communications or arming yet self.comms = None self.armed = False # Do basic Tk initialization self.root = Tk() self.root.configure(bg=BACKGROUND_COLOR) self.root.resizable(False, False) self.root.title('Hackflight Ground Control Station') left = (self.root.winfo_screenwidth() - DISPLAY_WIDTH) / 2 top = (self.root.winfo_screenheight() - DISPLAY_HEIGHT) / 2 self.root.geometry('%dx%d+%d+%d' % (DISPLAY_WIDTH, DISPLAY_HEIGHT, left, top)) self.frame = Frame(self.root) self.root.wm_iconbitmap(bitmap = "@media/icon.xbm") self.root.tk.call('wm', 'iconphoto', self.root._w, PhotoImage('icon.png')) self.root.protocol('WM_DELETE_WINDOW', self.quit) # Create panes for two rows of widgets self.pane1 = self._add_pane() self.pane2 = self._add_pane() # Add a buttons self.button_connect = self._add_button('Connect', self.pane1, self._connect_callback) self.button_setup = self._add_button('Setup', self.pane2, self._setup_callback) self.button_motors = self._add_button('Motors', self.pane2, self._motors_button_callback) self.button_receiver = self._add_button('Receiver', self.pane2, self._receiver_button_callback) self.button_messages = self._add_button('Messages', self.pane2, self._messages_button_callback) #self.button_maps = self._add_button('Maps', self.pane2, self._maps_button_callback, disabled=False) # Prepare for adding ports as they are detected by our timer task self.portsvar = StringVar(self.root) self.portsmenu = None self.connected = False self.ports = [] # Finalize Tk stuff self.frame.pack() self.canvas = Canvas(self.root, width=DISPLAY_WIDTH, height=DISPLAY_HEIGHT, background='black') self.canvas.pack() # Add widgets for motor-testing dialog; hide them immediately self.motors = Motors(self) self.motors.stop() # Create receiver dialog self.receiver = Receiver(self) # Create messages dialog self.messages = Messages(self) # Create setup dialog self.setup = Setup(self) self._schedule_connection_task() # Create a maps dialog #self.maps = Maps(self, yoffset=-30) # Create a splash image self.splashimage = PhotoImage(file='media/splash.png') self._show_splash() # Create a message parser self.parser = MSP_Parser() # Set up parser's request strings self.attitude_request = self.parser.serialize_ATTITUDE_Request() self.rc_request = self.parser.serialize_RC_Request() # No messages yet self.yaw_pitch_roll = 0,0,0 self.rxchannels = 0,0,0,0,0 # A hack to support display in Setup dialog self.active_axis = 0
def run(self): while True: try: self.rep_ip = self._replication_interface() self.uuid = self._my_uuid() break except: msg = ('Failed to get replication interface or uuid. ' 'Aborting.') return logger.error(msg) ctx = zmq.Context() # fs diffs are sent via this publisher. rep_pub = ctx.socket(zmq.PUB) rep_pub.bind('tcp://%s:%d' % (self.rep_ip, self.data_port)) # synchronization messages are received in this pull socket meta_pull = ctx.socket(zmq.PULL) meta_pull.RCVTIMEO = 100 meta_pull.bind('tcp://%s:%d' % (self.rep_ip, self.meta_port)) total_sleep = 0 while True: if (os.getppid() != self.ppid): logger.error('Parent exited. Aborting.') break while(not self.pubq.empty()): msg = self.pubq.get() rep_pub.send(msg) # check for any recv's coming num_msgs = 0 while (num_msgs < 1000): try: self.recv_meta = meta_pull.recv_json() num_msgs = num_msgs + 1 snap_id = self.recv_meta['id'] if (self.recv_meta['msg'] == 'begin'): rw = Receiver(self.recv_meta) self.receivers[snap_id] = rw rw.start() elif (snap_id not in self.senders): logger.error('Unknown snap_id(%s) received. Ignoring' % snap_id) else: self.senders[snap_id].q.put(self.recv_meta) except zmq.error.Again: break self._prune_workers((self.receivers, self.senders)) if (int(time.time()) - self.prune_time > 3600): self.prune_time = int(time.time()) for rs in ReplicaShare.objects.all(): prune_receive_trail(rs.id, logger) for r in Replica.objects.all(): prune_replica_trail(r.id, logger) if (total_sleep >= 60 and len(self.senders) < 50): try: for r in get_replicas(logger): rt = get_replica_trail(r.id, logger) now = datetime.utcnow().replace(second=0, microsecond=0, tzinfo=utc) sw = None snap_name = 'replication' rt2 = ReplicaTrail.objects.filter().order_by('-id') if (len(rt2) != 0): snap_name = ('%s_%d' % (snap_name, rt2[0].id + 1)) else: snap_name = ('%s_1' % snap_name) snap_id = ('%s_%s_%s_%s' % (self.uuid, r.pool, r.share, snap_name)) if (len(rt) == 0): logger.debug('new sender for snap: %s' % snap_id) sw = Sender(r, self.rep_ip, self.pubq, Queue(), snap_name, self.meta_port, self.data_port, r.meta_port, self.uuid, snap_id) elif (rt[0].status == 'succeeded'): if (((now - rt[0].end_ts).total_seconds() > (r.frequency * 60))): logger.debug('incremental sender for snap: %s' % snap_id) sw = Sender(r, self.rep_ip, self.pubq, Queue(), snap_name, self.meta_port, self.data_port, r.meta_port, self.uuid, snap_id, rt[0]) else: continue elif (rt[0].status == 'pending'): prev_snap_id = ('%s_%s_%s_%s' % (self.uuid, r.pool, r.share, rt[0].snap_name)) if (prev_snap_id in self.senders): logger.debug('send process ongoing for snap: ' '%s' % snap_id) continue logger.debug('%s not found in senders. Previous ' 'sender must have Aborted. Marking ' 'it as failed' % prev_snap_id) msg = ('Sender process Aborted. See logs for ' 'more information') data = {'status': 'failed', 'end_ts': now.strftime(settings.SNAP_TS_FORMAT), 'error': msg, 'send_failed': now, } update_replica_status(rt[0].id, data, logger) continue elif (rt[0].status == 'failed'): snap_name = rt[0].snap_name # if num_failed attempts > 10, disable the replica num_tries = 0 for rto in rt: if (rto.status != 'failed' or num_tries >= self.MAX_ATTEMPTS or rto.end_ts < r.ts): break num_tries = num_tries + 1 if (num_tries >= self.MAX_ATTEMPTS): logger.info('Maximum attempts(%d) reached ' 'for snap: %s. Disabling the ' 'replica.' % (self.MAX_ATTEMPTS, snap_id)) disable_replica(r.id, logger) continue logger.info('previous backup failed for snap: ' '%s. Starting a new one. Attempt ' '%d/%d.' % (snap_id, num_tries, self.MAX_ATTEMPTS)) prev_rt = None for rto in rt: if (rto.status == 'succeeded'): prev_rt = rto break sw = Sender(r, self.rep_ip, self.pubq, Queue(), snap_name, self.meta_port, self.data_port, r.meta_port, self.uuid, snap_id, prev_rt) else: logger.error('unknown replica trail status: %s. ' 'ignoring snap: %s' % (rt[0].status, snap_id)) continue self.senders[snap_id] = sw sw.daemon = True sw.start() total_sleep = 0 except DatabaseError, e: e_msg = ('Error getting the list of enabled replica ' 'tasks. Moving on') logger.error(e_msg) logger.exception(e) time.sleep(1) total_sleep = total_sleep + 1
def bind(self, client_socket): self.debug_continue.disabled = self.debug self.sender = Sender(client_socket, self.send_queue, self) self.receiver = Receiver(client_socket, self.receive_queue, self) self.sender.start() self.receiver.start()
def main(): create_queue() sender = Sender() receiver = Receiver() sender.start() receiver.start()
def emulate(args): ''' Starts the Sender/Receiver process threads, sleeps for args.RUNTIME, and terminates both threads. Returns a tuple of lists: (s_log, r_log), where s_log is sender's log and r_log is receiver's log. ''' args.SENDER_TIMEOUT = float(args.SENDER_TIMEOUT) args.RUNTIME = float(args.RUNTIME) assert args.SENDER_TIMEOUT > 0 assert args.RUNTIME > 0 s = Sender(args.SENDER_TIMEOUT) r = Receiver() s.set_remote_endpoint(r) r.set_remote_endpoint(s) r.daemon = True s.daemon = True # Start the sender process. s.start() r.start() try: time.sleep(args.RUNTIME) except KeyboardInterrupt: print "Interrupted, terminating." # We have to be careful with terminating the two threads, as they # can only exit in specific states, and we can cause a deadlock. # First, we terminate the sender, and wait for it to finish. Once # this happens, we know that the receiver is in an ok terminal # state, so we terminate it right after. s.terminate() s.join() r.terminate() r.join() #s.log.append((([0,0], "S-TERM"))) #r.log.append((([0,0], "R-TERM"))) # At this point, the sender is not generating any more # messages. But, we might have some oustanding messages in # receiver's queue. So, process these, if any: while not r.rx_queue.empty(): # Receive msg and generate any outstanding acks. r.transition() r.transition() r.transition() # Consume any outstanding acks on the sender's side. s.consume_acks() return (s.log, r.log)