def test_packet(packet): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2) s.connect((target_host, target_port)) s.send(packet.encode()) for response in s.makefile('r'): response = response.encode() if protocol.decode(response).status == protocol.Status.OK: print(protocol.decode(response).status) elif protocol.decode(response).status == protocol.Status.ERR: print(protocol.decode(response).err) s.close() sleep(1) # sleep 1 sec before testing next packet.
def listenClient(conn, addr): conn.settimeout(2) while True: try: encoded_data = conn.recv(1024) logging.debug("received " + str(encoded_data)) if not encoded_data: logging.debug("data is None?!") raise Exception("data is None?!") logging.debug("decoding") decoded_data = protocol.decode(encoded_data) logging.debug("decoded data: " + str(decoded_data)) response_msg = Command.try_to_execute(" ".join(decoded_data)) logging.debug("stdout: " + response_msg) except AssertionError: response_msg = "failed checksum while decoding request" logging.debug(response_msg) except: e = sys.exc_info()[0] response_msg = str(e) finally: response = protocol.encode_response("", response_msg, conn.getsockname()[0], addr[0]) logging.debug("sending " + str(response)) conn.send(response) conn.close() logging.debug("sent and closed connection to " + str(addr)) break
def send_list(packet): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((target_host, target_port)) s.send(packet.encode()) for res in s.makefile('r'): res = res.encode() s.close() return protocol.decode(res)
def on_message(client,userdata,msg): newmsg=str(msg.payload) val=protocol.decode(username,newmsg) val=str(val) newList=val.split(":") if len(newList)>2: if newList[0]==username: client.publish("chat/"+reciepent,val, 1) else: print "\n\n\n"+newList[0]+">>>"+" "+newList[1] print "at "+newList[3]+"\n\n\n"
def send(packet): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((target_host, target_port)) s.send(packet.encode()) for res in s.makefile('r'): res = res.encode() res = protocol.decode(res) if res.status == protocol.Status.OK: s.close() return res elif res.status == protocol.Status.ERR: print(res.err) s.close() return res
def trusted_read(txid): """Reads transaction via blockchain.info API. This is nice because it doesn't require that callers have run Bitcoin nodes on their machines. But it is dangerous, too, as it relies on a centralized server. Use wallet_read() or local_read() whenever possible. """ transaction = info.transaction(txid) addresses = [] for o in transaction['out']: if o['value'] == 5430: addresses.append(o['addr']) return protocol.decode(addresses)
def put(self, socket): wsprotocol = socket.protocol while not self.session.is_expired(): try: messages = socket.receive() # blocking # geventwebsocket doesn't wrap these failure modes # into nice exceptions so we have to catch base Python # Exceptions. :( # Ignore invalid frames except ValueError: continue except TypeError: continue # Ignore empty frames except WebSocketError: continue # If the peer closes early then a fobj.read attribute # won't exist so ignore. except AttributeError: break #except socketerror: #break # Hybi = Closed # Hixie = None if messages is None: break try: messages = protocol.decode(messages) except InvalidJSON: # When user sends broken data - broken JSON for example, the # server must terminate the ws connection. break for msg in messages: self.conn.on_message(msg) self.session.incr_hits() # Session expires, so unlock socket.close() self.session.unlock() self.session.expire()
def put(self, socket): wsprotocol = socket.protocol while not self.session.is_expired(): try: messages = socket.receive() # blocking # geventwebsocket doesn't wrap these failure modes # into nice exceptions so we have to catch base Python # Exceptions. :( # Ignore invalid frames except ValueError: continue except TypeError: continue # Ignore empty frames except WebSocketError: continue # If the peer closes early then a fobj.read attribute # won't exist so ignore. except AttributeError: break #except socketerror: #break # Hybi = Closed # Hixie = None if isinstance(messages, Closed) or messages is None: break try: messages = protocol.decode(messages) except InvalidJSON: # When user sends broken data - broken JSON for example, the # server must terminate the ws connection. break for msg in messages: self.conn.on_message(msg) self.session.incr_hits() # Session expires, so unlock socket.close() self.session.unlock() self.session.expire()
def __recvResponse(self, header, data): self.lastReadTime = time.time() obj = protocol.decode(header, data) if isinstance(obj, protocol.DubboRequest): request = obj if request.isHeartbeat: response = protocol.DubboResponse(request.rid) response.isEvent = True response.isHeartbeat = True self.send(response) else: raise Exception('unimplement recv data request') else: response = obj if response.isHeartbeat: return Future.received(response)
def __recvResponse(self, header, data) : self.lastReadTime = time.time() obj = protocol.decode(header, data) if isinstance(obj, protocol.DubboRequest) : request = obj if request.isHeartbeat : response = protocol.DubboResponse(request.rid) response.isEvent = True response.isHeartbeat = True self.send(response) else : raise Exception('unimplement recv data request') else : response = obj if response.isHeartbeat : return Future.received(response)
def receive(sub, data): try: fn, args = protocol.decode(sub, data) except: print 'Wrong data "%s"' % data return try: if fn._sender['recvmeth'] != True: raise AttributeError except (AttributeError, KeyError): print 'Wrong function "%s"' % fn.__name__ return try: fn(sub, *args) except TypeError: print 'Wrong args %s' % args
def handle(self): try: # read data from socket self.data = self.rfile.readline().strip() logger.debug(self.data) # decode packet packet = protocol.decode(self.data) logger.debug("{} sent packet {}".format(self.client_address[0], packet.encode())) # stick packet on msg_q if packet.opcode == Opcode.PRIVATE_MSG: msg_q.put("*" + packet.username + ": " + packet.message) elif packet.opcode == Opcode.BROADCAST_MSG: msg_q.put("BROADCAST|" + packet.username + ": " + packet.message) elif packet.opcode == Opcode.MSG: msg_q.put(packet.username + "(" + packet.room + ")" + ": " + packet.message) elif packet.opcode == Opcode.DISCONNECT: logger.info("{}".format(packet.err)) os._exit(1) # Handle Server Disconnect except SystemError: os._exit(1)
def send_command(maq, cmd): with socket.socket() as skt: skt.settimeout(3) try: skt.connect(get_machine(maq)) msg = cmd.cmd + " " + cmd.params logging.debug("sending " + msg + " to " + str(get_machine(maq))) logging.debug("calling encode") local_ip = socket.gethostbyname(socket.gethostname()) encoded_request = protocol.encode_request(cmd.cmd, cmd.params, local_ip, skt.getsockname()[0]) logging.debug("sending encoded msg: " + str(encoded_request) + str(type(encoded_request))) skt.send(encoded_request) logging.debug("sent") encoded_response = skt.recv(1024) logging.debug("received encoded: %s" % encoded_response) decoded_response = protocol.decode(encoded_response) logging.debug("received decoded: %s" % str(decoded_response)) return decoded_response except socket.timeout as exp: logging.debug("connection timed out") return ("", "timeout") except AssertionError as err: logging.debug("failed checksum while decoding response") # TODO improve ETRYAGAIN return return ("ETRYAGAIN", "failed checksum while decoding response") except: e = sys.exc_info()[0] logging.debug("could not connect to %s %s" % (str(get_machine(maq)), e)) return ("", "could not connect: %s" % str(e))
def handle(self): """ handling request main logic """ try: # read data from socket self.data = self.rfile.readline().strip() logger.debug(self.request.getpeername()) # decode packet packet = protocol.decode(self.data) logger.debug("{} sent packet {}".format(self.client_address[0], packet.encode())) # handle packet response = self._handle_packet(packet) logger.debug("connected USERS - {}".format(USERS.__str__())) logger.debug("rooms available - {}".format(ROOMS.__str__())) # write response self.wfile.write(response.encode()) except Disconnection: return
def process_IO(self, port, baudrate, status, outgoing, read_lock, write_lock, heartbeat_callback, channels_callback): #connection state last_heartbeat_send = 0 last_heartbeat_recv = 0 running = True # setup process to handle termination signal gracefully def handler(signum, frame): global running running = False print('process terminating....') signal.signal(signal.SIGTERM, handler) # connect over serial ser = None try: ser = serial.Serial(port=port, baudrate=baudrate, timeout=0.5) except OSError: print("Unable to connect to {}".format(port)) return # clear I/O buffers ser.reset_input_buffer() ser.reset_output_buffer() time.sleep(0.3) # Main loop while running: time.sleep(0.001) # send heartbeat if (time.time() - last_heartbeat_send > 1.0 / proto.HEARTBEAT_RATE): msg = proto.pack_heartbeat() ser.write(msg) last_heartbeat_send = time.time() # check for timeout if (time.time() - last_heartbeat_recv > proto.HEARTBEAT_TIMEOUT): with read_lock: status['connected'] = False # check for outgoing messages with write_lock: if not outgoing.empty(): while not outgoing.empty(): msg = outgoing.get(block=False) #print("sent",msg,len(msg)) ser.write(msg) ser.flush() # check for incoming messages if ser.in_waiting > 0 and ser.read(1)[0] == proto.START: # read msg_id msg_id = ser.read(1)[0] # read payload payload = ser.read(proto.msg_len[msg_id]) #print("recv",msg_id,payload) #decode the msg msg = proto.decode(msg_id, payload) #handle the msg if msg['id'] == 'heartbeat': last_heartbeat_recv = time.time() msg.pop('id') #update car status with read_lock: status['connected'] = True status.update(msg) #call heartbeat_callback if heartbeat_callback is not None: pass elif msg['id'] == 'channels_in': msg.pop('id') # update car status with read_lock: status.update(msg) # call channels_callback if channels_callback is not None: pass elif msg['id'] == 'debug': print("DEBUG: {}, {}, {}".format(msg['val0'], msg['val1'], msg['val2'])) # Exitting # Flush outgoing messages with write_lock: if not outgoing.empty(): while not outgoing.empty(): msg = outgoing.get(block=False) ser.write(msg) ser.flush() #Close serial ser.close()
if __name__ == '__main__': try: # setup initial connection # select username USERNAME = input("enter username> ") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2) s.connect((target_host, target_port)) # get address to be used for later address = s.getsockname() s.send(protocol.Connect(USERNAME, {}).encode()) # if response is ok, start client's server, else print error for response in s.makefile('r'): response = response.encode() if protocol.decode(response).status == protocol.Status.OK: s.close() start_client(address) elif protocol.decode(response).status == protocol.Status.ERR: print(protocol.decode(response).err) s.close() except socket.error as serr: if serr.errno != 111: raise serr else: logger.error("could not contact server - server is probably down")
def decode(self, data): """ Wrapper around the protocol's frame decoding. """ return protocol.decode(data)
import zmq import protocol context = zmq.Context() sink = context.socket(zmq.PULL) sink.bind('tcp://*:6010') while True: message = sink.recv() print(protocol.decode(message))
def state(): request = protocol.msg_request_state() response = client_send_recv(request) return protocol.decode(response)
controller_address = 'tcp://192.168.1.106:6000' last_poll = datetime.datetime.fromtimestamp(0) period_seconds = 1 if output_file: mode = f'-> {output_file}' else: mode = '(discarding results)' while True: waiting = sink.poll(timeout=period_seconds) if waiting: message = sink.recv() result = protocol.decode(message) output_buffer.append(json.dumps(result)) recv_count += 1 now = datetime.datetime.now() if (now - last_poll) >= datetime.timedelta(seconds=period_seconds): last_poll = now if output_file: with open(output_file, 'a') as outfile: outfile.writelines(output_buffer) lines_written += len(output_buffer) assert lines_written == recv_count output_buffer = [] socket = context.socket(zmq.REQ)
listener = Listener(args.chunk, args.format, args.channels, args.rate, args.starting_freq, args.jump, args.bits, args.pulse_duration, args.silence_duration) filename = 'sound_files/' + args.filename encoded_signal = '' if args.extract: encoded_signal = listener.extract_info(filename, args.magnitude_percentage, args.time_threshold, args.center_error) else: encoded_signal = listener.listen_and_extract(args.seconds, filename, args.magnitude_percentage, args.time_threshold, args.center_error) protocol = protocol.IdentityProtocol() info = protocol.decode(encoded_signal) print('listen:', info.hex()) if args.plot: rate, audio = wavfile.read(filename) M = 1024 freqs, times, Sx = signal.spectrogram(audio, fs=args.rate, window='hanning', nperseg=1024, noverlap=M - 100, detrend=False, scaling='spectrum') plot_spectrogram(freqs, times, Sx)
def on_message(client, userdata, msg): a = protocol.decode(name, msg.payload) print a