def test3(): sys.path.append('../') from hexdump import dump data, params = load('test.wav') print dump(data) enc = speex.Encoder() spx_data = enc.encode(data) print dump(spx_data)
def rx(self, xbeedev, srcaddr, data): self.last_activity = datetime.datetime.now() logging.debug("RX [{:x}<-{:x}]: {} -- {}".format(self.xbee.address, srcaddr, data, hexdump.dump(data))) if data[0:1] in self.have_response: self.have_response[data[0:1]]['rsp'] = (srcaddr, data) self.have_response[data[0:1]]['e'].set() elif data[0:1] == xTP.HELLO: self.remote = srcaddr self.have_remote.set() elif data[0:1] == xTP.SEND32_BEGIN: self.begin_transfer.set() elif data[0:1] == xTP.SEND32_ACKS: l = struct.unpack(">L", data[1:5])[0] self.acks = bitarray() self.acks.setall(0) self.acks.frombytes(data[5:]) # mark extra bits as received so all() works for z in range(l, len(self.acks)): self.acks[z] = True logging.debug("mask is [{}]: {}".format( l, self.acks )) self.have_acks.set() else: logging.warn("RX -- unknown message format ({:x})".format(data[0]))
def advance_dump(data, base): PY3K = sys.version_info >= (3, 0) generator = hexdump.genchunks(data, 16) retstr = '' for addr, d in enumerate(generator): # 00000000: line = '%08X: ' % (base + addr * 16) # 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 dumpstr = hexdump.dump(d) line += dumpstr[:8 * 3] if len(d) > 8: # insert separator if needed line += ' ' + dumpstr[8 * 3:] # ................ # calculate indentation, which may be different for the last line pad = 2 if len(d) < 16: pad += 3 * (16 - len(d)) if len(d) <= 8: pad += 1 line += ' ' * pad for byte in d: # printable ASCII range 0x20 to 0x7E if not PY3K: byte = ord(byte) if 0x20 <= byte <= 0x7E: line += chr(byte) else: line += '.' retstr += line + '\n' return retstr
def _send_packet(self, data, recipient=1): """ according to the documentation: |------packet (3-16 bytes)---------| header message terminator (1 byte) (1-14 bytes) (1 byte) | X | X . . . . . . . . . . X | X | header: terminator: 1 s2 s1 s0 0 r2 r1 r0 0xff with r,s = recipient, sender msb first for broadcast the header is 0x88! we use -1 as recipient to send a broadcast! """ # we are the controller with id=0 sender = 0 if recipient == -1: #broadcast: rbits = 0x8 else: # the recipient (address = 3 bits) rbits = recipient & 0b111 sbits = (sender & 0b111) << 4 header = 0b10000000 | sbits | rbits terminator = 0xff packet = chr(header) + data + chr(terminator) logging.debug("Send: %s", hexdump.dump(packet)) self.serial.mutex.acquire() self.serial._write_packet(packet) reply = self.serial.recv_packet() logging.debug("Received: %s", hexdump.dump(reply)) if reply: if reply[-1:] != '\xff': logging.debug("received packet not terminated correctly: %s", reply.encode('hex')) reply = None self.serial.mutex.release() return reply else: return None
def read_idn(stream) -> hex: """Read an identifier of a chunk. An identifier is an unsigned short integer. """ b = stream.read(SHORT_S) print(pad(), hexdump.dump(b)) return hex(unpack('H', b)[0])
def main(): while True: print('## Iniciando ciclo de testes... ##') for k, v in tests.items(): cmd = (*v, calcSum(v), int(0x16)) ser.write(cmd) ser.flushInput() print('Enviei[t_{0}]: {1}'.format(k, dump(bytearray(cmd)))) if v[-1] == 0x54: rcv = ser.read(9) else: rcv = ser.read(7) print('Recebi: ' + dump(rcv)) sleep(3) print('---') print()
def get_samples( ): #collect abt 1000 samples for each channel for rate at 200k samples and #axis distance of 15 cm samples_count = 0 samples_x_tx_sensor = [] samples_x_rx_sensor = [] temp1 = 0 temp2 = 0 while (samples_count < 800): temp1 = zmq_sample_subscriber_ch1.recv() temp1 = hx.dump(temp1[::-1], size=4, sep=' ') samples_x_tx_sensor.append(int(temp1, 16)) temp2 = zmq_sample_subscriber_ch2.recv() temp2 = hx.dump(temp2[::-1], size=4, sep=' ') samples_x_rx_sensor.append(int(temp2, 16)) samples_count = samples_count + 1 return samples_x_rx_sensor, samples_x_tx_sensor
def dump(byts,hdr="",indent="",string=False): if hdr: s="%s%s\n" % (indent,hdr) else: s="" s="%s%s\n" % (s,hexdump.dump(byts,indent=indent)) if string: return s print(s)
def outout_data(data, output, show_addresses=False): if output: output.write(data) print('Saved {} bytes to {}'.format(output.tell(), output.name)) output.close() else: if show_addresses: hexdump.hexdump(data) else: print(hexdump.dump(data))
def handleAttr(attr_name, attr_val): if ("com.apple.lastuseddate#PS" in attr_name): # Convert hexdump to timestamp ret = hexdump.dump(attr_val) ret = ret.replace(" ", "") ret = ret[:8] ret = "".join(reversed([ret[i:i + 2] for i in range(0, len(ret), 2)])) ret = float.fromhex(ret) ret = time.localtime(ret) ret = time.strftime('%Y-%m-%d %H:%M:%S', ret) return ret elif ("com.apple.quarantine" in attr_name): t = attr_val[5:13] t = float.fromhex(t) t = time.localtime(t) ret = attr_val[:5] + time.strftime("%Y-%m-%d %H:%M:%S", t) + attr_val[13:] return ret elif ("com.apple.diskimages.fsck" in attr_name): ret = hexdump.dump(attr_val) elif ("com.apple.metadata:com_apple_mail_dateReceived" in attr_name): ret = hexdump.dump(attr_val) elif ("com.apple.metadata:com_apple_mail_dateSent" in attr_name): ret = hexdump.dump(attr_val) elif ("com.apple.metadata:com_apple_mail_isRemoteAttachment" in attr_name): ret = hexdump.dump(attr_val) elif ("metadata" in attr_name): ret = sanitize(attr_val) else: ret = sanitize(attr_val) return ret
def get_hexdump_output(exe_file_path): exe_file = open(exe_file_path, "rb") exe_file_bytes = hexdump.dump(exe_file.read()) ans = "" splitted = exe_file_bytes.split() i = 0 while i < len(splitted) - 16: ans += ' '.join(splitted[i:i + 16]) + "\n" i += 16 exe_file.close() with open(exe_file_path + "exe_hexdump.bytes", "w") as exe_hexdump: exe_hexdump.write(ans)
def getAppLayerClassification(data): if (data[0] != '\x20'): return "Unknown protocol version!" service = ord(data[1]) if (SERVICE_CLASSIFIER.has_key(service)): command = bytesToCommandNumber(data[2:4]) if SERVICE_CLASSIFIER[service].has_key(command): return SERVICE_CLASSIFIER[service][command] else: return "Unknown command: " + hexdump.dump(data[2:4]) else: return "Unknown service id"
def onMessage(self, payload, isBinary): # received = None; if isBinary: print("Binary message received from client: {0} bytes: ".format(len(payload)) + hexdump.dump(payload, sep=" ")) try: if payload[0] == 0x10: received = updateMotors(payload[1], payload[2], payload[3], payload[4]) elif payload[0] == 0x30: received = readBatteryVoltage() elif payload[0] == 0x40: #f = os.popen('iw wlan1 station dump | grep "signal avg" | grep -ohP "signal avg:\t-[0-9]*" | grep -ohP "[0-9]*" | tail -1') #signal = f.read() #signal = signal[:len(signal)-1] signal = link_quality.link_quality_var received = [0x41, int(signal)] elif payload[0] == 0x50: f = os.popen('v4l2-ctl --set-ctrl brightness=' + str(np.int8(payload[1])) + ' --set-ctrl contrast=' + str(np.int8(payload[2])) + ' --set-ctrl saturation=' + str(np.uint8(payload[3])) + \ ' --set-ctrl hue=' + str(np.int8(payload[4])) + ' --set-ctrl gamma=' + str( np.uint16((np.uint8(payload[5]) << 8) + np.uint(payload[6])) ) + ' --set-ctrl gain=' + str(np.uint8(payload[7])) + \ ' --set-ctrl sharpness=' + str(np.uint8(payload[8])) ) received = [0x51] elif payload[0] == 0x60: f = os.popen('vcgencmd measure_temp | grep -ohP "=[0-9]*" | cut -c 2-') temperature = f.read() temperature = temperature[:len(temperature)-1] received = [0x61, int(temperature)] elif payload[0] == 0x84: setNewManiPosition(payload[1], payload[2], payload[3], payload[4]) # add CRC received = [0x85, 0x00] elif payload[0] == 0x94: setNewGripperPosition(payload[1], payload[2]) # add CRC received = [0x95, 0x00] elif payload[0] == 0xA4: setNewCameraPosition(payload[1], payload[2]) received = [0xA5, 0x00] print("Received from Motor Module: " + hexdump.dump(bytes(received), sep=" ")) except OSError: received = None print("Communication error has occured") else: print("Text message received: {0}".format(payload.decode('utf8'))) # echo back message verbatim if received != None: self.sendMessage(bytes(received), True) else: self.sendMessage(bytes(0x00), False)
def get_hexdump_output(exe_file_path): time.sleep(1) exe_file = open(exe_file_path, "rb") exe_file_bytes = hexdump.dump(exe_file.read()) ans = "" splitted = exe_file_bytes.split() i = 0 while i < len(splitted) - 16: ans += ' '.join(splitted[i:i + 16]) + "\n" i += 16 exe_file.close() with open('bytes_from_exe.bytes', "w") as exe_hexdump: exe_hexdump.write(ans) return 'bytes_from_exe.bytes'
def test(loops=10, key_len=32): """ local tests """ print("ARC4 test") plaintext_org = str(23.5) for index in range(0, loops): encround = MQTTARC4("TTKS0600", key_len) start = time() ciphertext = encround.encrypt(plaintext_org) print("Encrypted " + " " + str(len(ciphertext)) + " in " + str(round((time() - start), 5)) + "\t" + hexdump.dump(ciphertext, size=2, sep=' ')) start = time() plaintext = encround.decrypt(ciphertext) print("Decrypted " + " " + str(len(plaintext)) + " in " + str(round((time() - start), 5)) + "\t" + hexdump.dump(plaintext.encode(), size=2, sep=' ')) if plaintext != plaintext_org: print("FAILED") print("\t" + str(plaintext_org)) print("\t" + str(plaintext)) index = index
def send(self, data, dest=0xffff): "send (no fragmentation)" self.last_activity = datetime.datetime.now() e = self.xbee.send(data, dest) logging.debug("TX [{:x}->{:x}][{}]: {}".format(self.xbee.address, dest, e.fid, hexdump.dump(data))) if e.wait(self.xbee._timeout.total_seconds()): logging.debug("TX [{}] complete: {}".format(e.fid, e.pkt)) else: logging.debug("TX [{}] timeout".format(e.fid))
def run_makefile_string(in_string, expected_string): # parse a Makefile from a string. # Compare resulting makefile to expected string. makefile = pymake.parse_makefile_string(in_string) m = makefile.makefile() print("# start makefile") print(m) print("# end makefile") print(hexdump.dump(in_string, 16), end="") print(hexdump.dump(expected_string, 16), end="") print(hexdump.dump(m, 16), end="") print("m=\"{0}\"".format(printable_string(m))) print("e=\"{0}\"".format(printable_string(expected_string))) assert m == expected_string # round trip expr = str(makefile) print(expr) m2 = eval(expr).makefile() print(m2) assert m2 == expected_string, m2
def test(loops=10): """ local tests """ print("SALSA20 test") plaintext_org = str(23.5) for index in range(0, loops): cipher = MQTTSALSA20(secret="TTKS0600") start = time() ciphertext = cipher.encrypt(plaintext_org) print("Encrypted " + " " + str(len(ciphertext)) + " in " + str(round((time() - start), 5)).ljust(4) + "\t" + hexdump.dump(ciphertext, size=2, sep=' ')) start = time() plaintext = cipher.decrypt(ciphertext) print("Decrypted " + " " + str(len(plaintext)) + " in " + str(round((time() - start), 5)).ljust(6) + "\t" + hexdump.dump(plaintext.encode(), size=2, sep=' ')) if plaintext != plaintext_org: print("FAILED") print("\t" + str(plaintext_org)) print("\t" + str(plaintext)) index = index
def value_in_same_location(self, value_length, weight_same_row, weight_in_row): test = [] ret = 0 for val in self.container: tst = hexdump.dump(bytes(val), value_length * 2, " ") test.append(tst.split(" ")) # Create chunks of desired length for rows in range(0, len(test)): ret += self.test_values(test[rows:], weight_same_row, True) for rows in range(0, len(test)): ret += self.test_values(test[rows:], weight_in_row, False) return ret
def sniff_random_value(host=None, counts=10): s = sniff(count=counts, filter=host) out_type_protocol = [] out_source_port = [] out_header_checksum = [] out_sequence_number = [] out_total_length = [] out_payload_length = [] for i in range(counts): packet = bytes(s[i]) mm = hexdump.dump(packet).split(' ') if mm[12] + mm[13] == '0800': if mm[23] == '11': out_type_protocol.append('IPv4, UDP') out_payload_length.append(None) out_sequence_number.append(None) out_header_checksum.append(mm[24] + ' ' + mm[25]) out_source_port.append(mm[34] + ' ' + mm[35]) out_total_length.append(mm[16] + ' ' + mm[17]) elif mm[23] == '06': out_type_protocol.append('IPv4, TCP') out_payload_length.append(None) out_sequence_number.append(mm[38] + ' ' + mm[39] + ' ' + mm[40] + ' ' + mm[41]) out_header_checksum.append(mm[24] + ' ' + mm[25]) out_source_port.append(mm[34] + ' ' + mm[35]) out_total_length.append(mm[16] + ' ' + mm[17]) else: out_type_protocol.append('IPv6') out_payload_length.append(mm[18] + ' ' + mm[19]) out_sequence_number.append(None) out_header_checksum.append(None) out_source_port.append(None) out_total_length.append(None) for j in range(len(out_type_protocol)): print( f'\nNumer pakietu: {j}. Zarejestrowano nastepujace losowe wartosci:' ) print(f'1. Typ protokolu: {out_type_protocol[j]}') print(f'2. Payload length (only IPv6): {out_payload_length[j]}') print(f'3. Sequence number (only TCP): {out_sequence_number[j]}') print(f'4. Header checksum: {out_header_checksum[j]}') print(f'5. Source port: {out_source_port[j]}') print(f'6. Total length: {out_total_length[j]}')
def send_pkt_retry(self, msg, waitfor_msg): self.have_response[waitfor_msg] = {'e': threading.Event(), 'rsp': None} for i in range(self.retries): logging.debug("TX -{:02x}- {}/{} [{:x}->{:x}]: {}".format( msg[0], i, self.retries, self.xbee.address, self.remote, hexdump.dump(msg))) try: self.xbee.sendwait(data=msg, dest=self.remote) except TimeoutError: continue if self.have_response[waitfor_msg]['e'].wait( self.xbee._timeout.total_seconds()): return self.have_response[waitfor_msg]['rsp'] return None, None
def _dump(self, command): """Dumps the layer bytes in different formats.""" if len(command) == 1: Interface.color_dump(self._l.raw, self._l.slice.start) return # Parsing the arguments cp = CommandParser(LayerInterface._dump_opts()) args = cp.parse(command) if not args: Interface._argument_error() return if args["-hex"]: Interface.color_dump(self._l.raw, self._l.slice.start) elif args["-b"]: print(str(self._l.raw[self._l.slice.start:]), '\n') elif args["-hexstr"]: d = hexdump.dump(self._l.raw).split(" ") print(" ".join(d[self._l.slice.start:]), '\n') elif args["-h"]: Interface.print_help(LayerInterface._dump_help())
def _dump(self, command): """Dumps the packet/template bytes in different formats.""" if len(command) == 1: hexdump.hexdump(self._t.raw) print("") return # Parsing the arguments cp = CommandParser(TemplateInterface._dump_opts()) args = cp.parse(command) if not args: Interface._argument_error() return if args["-hex"]: hexdump.hexdump(self._t.raw) print("") elif args["-b"]: print(str(self._t.raw), "\n") elif args["-hexstr"]: print(hexdump.dump(self._t.raw), "\n") elif args["-h"]: Interface.print_help(TemplateInterface._dump_help())
def scan_network(q, r, port): sleep(random() * 5) # Spread them out. while True: try: group = q.get(timeout=10) # print "======> " + str(group) except gevent.queue.Empty: break logging.info("Joining %s" % group) sock = join(str(group), port) try: data = sock.recv(16) logging.info("[%s]. Data: %s", group, dump(data, 2)) r.put(group) except socket.timeout: logging.info("[%s] Timeout", group) sleep(PER_GROUP_LISTEN_TIME) sock.close() q.task_done()
def on_message(client, userdata, message): """ MQTT - receive messages """ client = client userdata = userdata global DUMP try: DUMP.delete('1.0', tk.END) cont = mcont.MCONT(None, mfile.pw) package = cont.destruct(message.payload, message.topic) print(package) if isinstance(package["Ciphertext"], str): hx_value = package["Ciphertext"].encode() else: hx_value = package["Ciphertext"] hx_value = hexdump.dump(hx_value, size=4, sep=' ') DUMP.insert(tk.INSERT, "MQTT msg received\n") DUMP.insert(tk.INSERT, "Ciphertext\n") DUMP.insert(tk.INSERT, hx_value) DUMP.insert(tk.INSERT, "\n\nPlaintext\n") DUMP.insert(tk.INSERT, package["Plaintext"]) DUMP.insert(tk.INSERT, "\n\nPath\n") DUMP.insert(tk.INSERT, package["Path"]) DUMP.insert(tk.INSERT, "\n\nDecrypt duration\n") DUMP.insert(tk.END, str(round(package["Duration"], 8)) + "\n") except ValueError: DUMP.delete('1.0', tk.END) DUMP.insert(tk.INSERT, "Hash failure\n") #DUMP.insert(tk.INSERT, "\nBacktrace\n") #DUMP.insert(tk.INSERT, str(traceback.format_exc())) except Exception as failure: DUMP.delete('1.0', tk.END) DUMP.insert(tk.INSERT, str(failure)) DUMP.insert(tk.INSERT, "\nBacktrace\n") DUMP.insert(tk.INSERT, str(traceback.format_exc()))
def dump_file(self, file_name): with open(file_name, "rb") as f: chunk = f.read(self.chunks_size) chunk_counter = 0 actual_line = str_to_bytes("") while chunk: actual_line += chunk self.bytes_dump += hexdump.dump(chunk, self.chunks_size, self.chunks_separator) chunk_counter += 1 chunk = f.read(self.chunks_size) if chunk_counter == self.bytes_per_line: self.bytes_dump += "\n" print(self.dump_string(actual_line)) actual_line = str_to_bytes("") chunk_counter = 0 return self.bytes_dump
import hexdump from pytun import TunTapDevice, IFF_TAP tun = TunTapDevice(name='rfc6214') with open("captured_in.hex", "r") as the_file: hex = the_file.readline() buf = hexdump.dehex(hex) tun.write(buf) buf = tun.read(tun.mtu) hex = hexdump.dump(buf, 2, '') print(hex) with open('captured_out.hex', 'w') as the_file: the_file.write(hex)
def test_vline(): test_list = ( # single line ("foo : bar ; baz\n", "foo : bar ; baz\n"), ("backslash=\ \n", "backslash=\ \n"), # backslash then blank line then end-of-string (r"""space=\ """, "space= \n"), # backslash joining rule + recipe (r"""foo\ :\ bar\ ;\ baz """, "foo : bar ; baz\n"), # another way to write the previous test ("foo2\\\n:\\\nbar\\\n;\\\nbaz\n", "foo2 : bar ; baz\n"), # from ffmpeg (r"""SUBDIR_VARS := CLEANFILES EXAMPLES FFLIBS HOSTPROGS TESTPROGS TOOLS \ HEADERS ARCH_HEADERS BUILT_HEADERS SKIPHEADERS \ ARMV5TE-OBJS ARMV6-OBJS VFP-OBJS NEON-OBJS \ ALTIVEC-OBJS VIS-OBJS \ MMX-OBJS YASM-OBJS \ MIPSFPU-OBJS MIPSDSPR2-OBJS MIPSDSPR1-OBJS MIPS32R2-OBJS \ OBJS HOSTOBJS TESTOBJS """, "SUBDIR_VARS := CLEANFILES EXAMPLES FFLIBS HOSTPROGS TESTPROGS TOOLS HEADERS ARCH_HEADERS BUILT_HEADERS SKIPHEADERS ARMV5TE-OBJS ARMV6-OBJS VFP-OBJS NEON-OBJS ALTIVEC-OBJS VIS-OBJS MMX-OBJS YASM-OBJS MIPSFPU-OBJS MIPSDSPR2-OBJS MIPSDSPR1-OBJS MIPS32R2-OBJS OBJS HOSTOBJS TESTOBJS\n" ), # stupid DOS \r\n 0x0d0a <cr><lf> # ( """supid-dos:\\\r\nis\\\r\nstupid\r\n""", () ), (r"""more-fun-in-assign\ = \ the \ leading \ and \ trailing\ white \ space \ should \ be \ eliminated\ \ \ \ including \ \ \ blank\ \ \ lines """, "more-fun-in-assign = the leading and trailing white space should be eliminated including blank lines\n" ), # This is a weird one. Why doesn't GNU Make give me two \\ here? I only get # one. Disable the test for now. Need to dig into make # ( r"""literal-backslash-2 = \\\ # q #""", "literal-backslash-2 = \\ q\n" ), # ("foo : # this comment\\\ncontinues on this line\n", "foo : # this comment continues on this line\n"), # end of the tests list ) for test in test_list: # string, validation s, v = test # print(s,end="") # print("s={0}".format(hexdump.dump(s,16)),end="") # VirtualLine needs an array of lines from a file. The EOLs must be # preserved. But I want a nice easy way to make test strings (one # single string). # # The incoming string will be one single string with embedded \n's # (rather than trying to create an array of strings by hand). # Split the test string by \n into an array. Then restore \n on each line. # The [:-1] skips the empty string after the final \n file_lines = s.split("\n")[:-1] lines = [line + "\n" for line in file_lines] # print( "split={0}".format(s.split("\n"))) # print( "lines={0} len={1}".format(lines,len(lines)),end="") vline = VirtualLine(lines, 0) for line in vline.virt_lines: print(line) print(vline) s = str(vline) print("s={0}".format(hexdump.dump(s, 16))) print("v={0}".format(hexdump.dump(v, 16))) assert s == v
def send(self, data, remote_filename, filesize, offset=0, dest=0xffff): "send with fragmentation, returns true on success" start = datetime.datetime.now() self.last_activity = datetime.datetime.now() # mtu seems imprecise. (does not include headers) frags = list( frag.make_frags(data, threshold=self.xbee.mtu - 8, encode=False)) self.begin_transfer.clear() self.have_acks.clear() ok_begin = False for i in range(self.retries): msg = xTP.SEND32_REQ + struct.pack(">LLLL", offset, filesize, frags[0].total, frags[0].crc) + \ remote_filename.encode("utf-8") logging.debug("TX SEND32_REQ {}/{} [{:x}->{:x}]: {}".format( i, self.retries, self.xbee.address, dest, hexdump.dump(msg))) try: self.xbee.sendwait(data=msg, dest=dest) except TimeoutError: continue if (self.begin_transfer.wait(self.xbee._timeout.total_seconds())): logging.info("Begin transfer at {} of {} for file {}.".format( offset, filesize, remote_filename)) ok_begin = True break else: logging.info("Failed to begin transfer.") return False if ok_begin == False: return False #initial set of acks self.acks = bitarray(len(frags)) self.acks.setall(0) for j in range(self.retries): txcnt = 0 for i, f in enumerate(frags): if self.acks[i] == False: txcnt += 1 d = xTP.SEND32_DATA + struct.pack(">L", i) + f.data e = self.xbee.send(data=d, dest=dest) logging.debug( "TX SEND32_DATA {}/{} [{:x}->{:x}][{}]: {}".format( i, len(frags), self.xbee.address, dest, e.fid, hexdump.dump(d))) if txcnt == 0: logging.warn("TX complete due to no packets to send") return True # must have worked. # block until all packets go out... self.xbee.flush() got_acks = False for k in range(self.retries): msg = xTP.SEND32_GETACKS self.have_acks.clear() logging.debug( "TX SEND32_GETACKS {}/{} [{:x}->{:x}][{}]: {}".format( k, self.retries, self.xbee.address, dest, e.fid, hexdump.dump(msg))) try: self.xbee.sendwait(data=msg, dest=dest) except TimeoutError: continue if self.have_acks.wait(self.xbee._timeout.total_seconds()): logging.debug("Got acks. [all=={}]".format( self.acks.all())) got_acks = True tm = datetime.datetime.now() - start if self.acks.all(): logging.info( "Finish transfer at {} of {} for file {} in {} = {:.2f} kbps." .format(offset, filesize, remote_filename, tm, (8 * len(data) / 1024) / tm.total_seconds())) return True break if got_acks == False: loggin.warn("Failed because remote didn't send acks.") return False return False
def true_sendall(self, data, *args, **kwargs): req = decode_from_bytes(data) # make request unique again req_signature = hashlib.md5(encode_to_bytes(''.join(sorted(req.split('\r\n'))))).hexdigest() # port should be always a string port = text_type(self._port) # prepare responses dictionary responses = dict() if Mocket.get_truesocket_recording_dir(): path = os.path.join( Mocket.get_truesocket_recording_dir(), Mocket.get_namespace() + '.json', ) # check if there's already a recorded session dumped to a JSON file try: with io.open(path) as f: responses = json.load(f) # if not, create a new dictionary except (FileNotFoundError, JSONDecodeError): pass try: response_dict = responses[self._host][port][req_signature] except KeyError: # preventing next KeyError exceptions responses.setdefault(self._host, dict()) responses[self._host].setdefault(port, dict()) responses[self._host][port].setdefault(req_signature, dict()) response_dict = responses[self._host][port][req_signature] # try to get the response from the dictionary try: try: encoded_response = hexdump.dehex(response_dict['response']) except TypeError: # pragma: no cover # Python 2 encoded_response = hexdump.restore(encode_to_bytes(response_dict['response'])) # if not available, call the real sendall except KeyError: self._connect() self.true_socket.sendall(data, *args, **kwargs) encoded_response = b'' # https://github.com/kennethreitz/requests/blob/master/tests/testserver/server.py#L13 while select.select([self.true_socket], [], [], 0.5)[0]: recv = self.true_socket.recv(self._buflen) if recv: encoded_response += recv else: break # dump the resulting dictionary to a JSON file if Mocket.get_truesocket_recording_dir(): # update the dictionary with request and response lines response_dict['request'] = req response_dict['response'] = hexdump.dump(encoded_response) with io.open(path, mode='w') as f: f.write(decode_from_bytes(json.dumps(responses, indent=4, sort_keys=True))) # response back to .sendall() which writes it to the mocket socket and flush the BytesIO return encoded_response
async def hvacConnected(deviceSession, firstState): global devConnected print("Device connected! " + hexdump.dump(deviceSession.device.deviceData) + " state: ") print(firstState.toString()) devConnected = True
def _transmit(_from, _to): content = _from.recv_all() if content: print(dump(bytes(content, ENCODE))) _to.send(content) return content