def test_attribute_assignment(self): u = Unpacker({'a': 2, 'b': 3}) u.a = 45 u.b = 67 self.assertEqual(u.a, 45) self.assertEqual(u.b, 67) self.assertEqual(u['a'], 45) self.assertEqual(u['b'], 67)
def test_multiple_assignment(self): u = Unpacker(OrderedDict([('a', 12), ('c', 13)])) a, c = u self.assertEqual(a, u.a) self.assertEqual(c, u.c) u.b = 14 self.assertEqual(u['b'], 14) a, c, b = u self.assertEqual(a, u.a) self.assertEqual(c, u.c) self.assertEqual(b, u.b)
def test_indpendence_from_dict(self): d = {'a': 2, 'b': 3} u = Unpacker(d) d['a'] = 4 u['a'] = 5 self.assertEqual(d['a'], 4) self.assertEqual(u['a'], 5)
def main(): try: parser = optparse.OptionParser( usage= '%prog -a <Device_address> -z <Zip_file>\n\nExample:\n\tupdate.py -a cd:e3:4a:47:1c:e4 -z application.zip' ) parser.add_option('-a', '--address', action='store', dest="deviceAddr", type="string", default=None) parser.add_option('-z', '--zip', action='store', dest="zipfile", type="string", default=None) options, args = parser.parse_args() except Exception as e: print(e) print("For help use --help") try: if (not options.deviceAddr): print("Error: Device address not passed in") print("For help use --help") elif (not options.zipfile): print("Error: Zip file not passed in") print("For help use --help") elif not os.path.isfile(options.zipfile): print("Error: Zip file not found") print("For help use --help") unpacker = Unpacker() binfile, datfile = unpacker.unpack(options.zipfile) bleClient = BleClient(options.deviceAddr.upper()) bleClient.updateDevice(binfile, datfile) except Exception as e: print(e) print("For help use --help")
def test_multiple_key_return(self): u = Unpacker({'a': 2, 'c': 3}) self.assertEqual(u['a', 'c'], (2, 3)) u.b = 4 self.assertEqual(u['b', 'c'], (4, 3)) u['b', 'a', 'c'] = (5, 6, 7) self.assertEqual(u['a'], 6) self.assertEqual(u['c'], 7) self.assertEqual(u['b'], 5) u['a', 'e'] = 100, 300 u['b', 'c'] = (n**2 for n in [2, 3]) self.assertEqual(u['a'], 100) self.assertEqual(u['e'], 300) self.assertEqual(u['b'], 4) self.assertEqual(u['c'], 9) with self.assertRaises(Exception): # ValueError preferably u['b', 'a', 'c'] = (5, 6) with self.assertRaises(Exception): # ValueError preferably u['b', 'a'] = (5, 6, 7)
def unpack_data(self, modules: list): logging.debug('UNPACKING:') for module in modules: project_path = self.WORKING_DIR / ( "%s%s" % (module['filename'], self.PROJECT_SUFFIX)) sample_path = project_path / 'samples' try: project_path.mkdir(exist_ok=True) sample_path.mkdir(exist_ok=True) except (IOError, OSError): msg = "Cannot create folders %s, %s at the working dir %s" % ( project_path.resolve(), sample_path.resolve(), self.WORKING_DIR.resolve()) logging.error(msg) return try: Unpacker.unpack(module, project_path, sample_path) except Unpacker.ModuleUnpackerError: msg = "Cannot unpack module: %s" % module.name logging.error(msg)
def test_multiple_key_assignment(self): u = Unpacker({'a': 2, 'c': 3}) self.assertEqual(repr(u), 'Unpacker(a=2, c=3)') self.assertEqual(str(u), 'Unpacker(a=2, c=3)') u['b'] = 4 self.assertEqual(str(u), 'Unpacker(a=2, c=3, b=4)') u['c'] = "hi" self.assertEqual(str(u), "Unpacker(a=2, c='hi', b=4)") u['a'] = date(2020, 1, 1) self.assertEqual( str(u), "Unpacker(a=datetime.date(2020, 1, 1), c='hi', b=4)", )
def main(): # Inicializa enlace ... variavel com possui todos os metodos e propriedades do enlace, que funciona em threading com = Enlace(serialName) # Ativa comunicacao com.enable() com.rx.clearBuffer() packer = Packer() unpacker = Unpacker() # Log run = True call = True response = False serverReady_message_get = False count = 1 while (run): if not response: if call: selected = select_file() print("-------------------------") print("Gerando dados para transmissao :") print("-------------------------") data = open(selected, "rb").read() delivery, total = packer.pack(data, get_kind(selected), Protocol.type_package_delivery, get_total=True) print("-------------------------") print("Chamando o server para tranferência de dados") print("-------------------------") message_timeot = time.time() call = False else: if (time.time() - message_timeot) < Protocol.great_timeout: message = packer.pack_message(Protocol.type_client_call, total, total, Protocol.sever_number) com.sendData(message) while (com.tx.getIsBussy()): pass dataRx = com.getData(Protocol.max_size, time.time()) data, code, atual = unpacker.unpack(dataRx) if code == Protocol.type_server_ready: serverReady_message_get = True response = True print("-------------------------") print("Server pronto, começando o envio") print("-------------------------") start = time.time() time_out_time = time.time() count = 1 else: response = True elif not call and serverReady_message_get: if count <= total and (time.time() - time_out_time) < Protocol.great_timeout: print("-------------------------") print("Envindo pacote {} de {}".format(count, total)) print("-------------------------") com.sendData(delivery[count - 1]) while (com.tx.getIsBussy()): pass dataRx = com.getData(Protocol.max_size, time.time()) data, code, atual = unpacker.unpack(dataRx) if code == Protocol.type_package_ok and atual == count: print("-------------------------") print("Pacote {} de {} enviado com sucesso".format( count, total)) print("-------------------------") count += 1 time_out_time = time.time() else: print("-------------------------") print("Erro") print("-------------------------") if 1 <= atual <= total: count = atual elif count > total: end = time.time() - start print("-------------------------") print("Pacotes enviados com sucesso") print("Taxa de recepção: {:02}".format( total * Protocol.max_size / end)) print("-------------------------") print("-------------------------") go_on = input( "Se desejar um novo envio digite sim, caso contrário outro caractere: " ) print("-------------------------") call = True serverReady_message_get = False response = False count = 1 if go_on != "sim": print("-------------------------") print("Até mais!") print("-------------------------") run = False else: print("-------------------------") print("O server não respondeu e um timeout ocorreu") print("-------------------------") print("-------------------------") go_on = input( "Se desejar um novo envio digite sim, caso contrário outro caractere: " ) print("-------------------------") call = True serverReady_message_get = False response = False count = 1 if go_on != "sim": print("-------------------------") print("Até mais!") print("-------------------------") run = False else: print("-------------------------") print("O server não respondeu e um timeout ocorreu") print("-------------------------") print("-------------------------") go_on = input( "Se desejar um novo envio digite sim, caso contrário outro caractere: " ) print("-------------------------") call = True serverReady_message_get = False response = False count = 1 if go_on != "sim": print("-------------------------") print("Até mais!") print("-------------------------") run = False
def test_constructor(self): Unpacker() Unpacker({'a': 2, 'b': 3})
34-35 dstport TCP/UDP destination port number or equivalent 36 pad1 Unused (zero) bytes 37 tcp_flags Cumulative OR of TCP flags 38 prot IP protocol type (for example, TCP = 6; UDP = 17) 39 tos IP type of service (ToS) 40-41 src_as Autonomous system number of the source, either origin or peer 42-43 dst_as Autonomous system number of the destination, either origin or peer 44 src_mask Source address prefix mask bits 45 dst_mask Destination address prefix mask bits 46-47 pad2 Unused (zero) bytes """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # UDP sock.bind(('127.0.0.1', 2055)) unpck = Unpacker.Unpacker() while True: try: print('listening..') (packet, addr) = sock.recvfrom(65535) version, count = unpack('!HH', packet[0:4]) print("Kuda") print("We have " + str(count) + " packets and Version is: " + str(version)) print(str(addr)) # version = unpck.unpackbufferint(packetbuf, 0, 2) # print(str(addr)) # print(str(version)) # totalrecord = unpck.unpackbufferint(packetbuf, 2, 2) # # as per the Netflow version 5 Standard.. # if totalrecord < 1 or totalrecord > 30:
def test_original_dictionary_unchanged(self): bundle = {'a': 2, 'b': 3} u = Unpacker(bundle) u.c = 4 self.assertEqual(bundle, {'a': 2, 'b': 3})
def test_only_as_key_access(self): u = Unpacker({'shape type': 1, 'identifier': 'Square'}) self.assertEqual(u.identifier, 'Square') self.assertEqual(u['shape type'], 1)
from packer import Packer from unpacker import Unpacker unp = Unpacker('/mnt/d/mobile/firm/T91_4_TF/T91_4.bin') unp.export('/mnt/d/mobile/unpack', unpack_files=True, crc_check=True) print(unp) p = Packer('/mnt/d/mobile/test_firm') p.export('/mnt/d/mobile/T91_4.bin.new')
def test_key_assignment(self): u = Unpacker({'a': 2, 'b': 3}) u['a'] = 45 u['b'] = 67 self.assertEqual(u['a'], 45) self.assertEqual(u['b'], 67)
def test_attribute_access(self): u = Unpacker({'a': 2, 'b': 3}) self.assertEqual(u.a, 2) self.assertEqual(u.b, 3)
def test_key_access(self): u = Unpacker({'a': 2, 'b': 3}) self.assertEqual(u['a'], 2) self.assertEqual(u['b'], 3)
if not options.address: parser.print_help() exit(2) unpacker = None hexfile = None datfile = None if options.zipfile != None: if (options.hexfile != None) or (options.datfile != None): print "Conflicting input directives" exit(2) unpacker = Unpacker() #print options.zipfile try: hexfile, datfile = unpacker.unpack_zipfile(options.zipfile) except Exception, e: print "ERR" print e pass else: if (not options.hexfile) or (not options.datfile): parser.print_help() exit(2) if not os.path.isfile(options.hexfile): print "Error: Hex file doesn't exist"
if not options.address: parser.print_help() exit(2) unpacker = None hexfile = None datfile = None if options.zipfile != None: if (options.hexfile != None) or (options.datfile != None): print "Conflicting input directives" exit(2) unpacker = Unpacker() hexfile, datfile = unpacker.unpack_zipfile(options.zipfile) else: if (not options.hexfile) or (not options.datfile): parser.print_help() exit(2) if not os.path.isfile(options.hexfile): print "Error: Hex file doesn't exist" exit(2) if not os.path.isfile(options.datfile): print "Error: DAT file doesn't exist" exit(2)
def main(): # Inicializa enlace ... variavel com possui todos os metodos e propriedades do enlace, que funciona em threading com = Enlace(serialName) # repare que o metodo construtor recebe um string (nome) # Ativa comunicacao com.enable() com.rx.clearBuffer() my_server = Protocol.sever_number packer = Packer() unpacker = Unpacker() file_num = 1 try_num = 1 # Log print("-------------------------") print("Comunicação inicializada") print(" porta : {}".format(com.fisica.name)) print("-------------------------") ocioso = True serverReady_message_sent = False count = 1 while(True): # Server está ocioso if ocioso: dataRx = com.getData(Protocol.max_size, time.time()) data, code, kind, total, server, client = unpacker.unpack(dataRx, first=True) # Server checa se o código e número de server da mensagem estão certos if code == Protocol.type_client_call and server == my_server: # Log do server é inicializado log = open("log/fille{:02}log_try{:02}.txt".format(file_num, try_num),"w+") # Server deixa de estar ocioso ocioso = False client_number = client print("-------------------------") print("Server chamado pelo client") print("-------------------------") log.write("Msg: {} – recebida: {} – remetente: {}\n".format(code, time.ctime(time.time()), client)) # Server não está mais ociono mas ainda não mandou uma mensagem com Código 2 elif serverReady_message_sent == False: message = packer.pack_message(Protocol.type_server_ready, total, total, my_server, client_number) com.sendData(message) while(com.tx.getIsBussy()): pass serverReady_message_sent = True log.write("Msg: {} – enviada: {} – destinatário: {}\n".format(Protocol.type_server_ready, time.ctime(time.time()), client_number)) print("-------------------------") print("Total de pacotes a receber : {}".format(total)) print("Tipo de arquivo : {}".format(Protocol.from_kind[kind])) print("-------------------------") # Variáveis são iniciadas aqui para que não sejam mudadas indevidamente no loop de envio recieved = bytes() start = time.time() time_out_time = time.time() # Server recebe os pacotes e checa seus conteúdos else: # Enquanto todos os pacotes ainda não foram recebido, é checado se ainda não ocorreu um timeout if count <= total and (time.time() - time_out_time) < Protocol.great_timeout: dataRx = com.getData(Protocol.max_size, time.time()) data, code, atual, client = unpacker.unpack(dataRx) print("-------------------------") print("Pacote aberto") print("Contador {} e atual {} e código {}".format(count, atual, code)) print("-------------------------") log.write("Msg: {} – recebida: {} – remetente: {}\n".format(code, time.ctime(time.time()), client)) # Se o pacote recebido conter o código certo e seu número bater com o esperado, # seu conteúdo é adicionado e uma mensagem de confirmação é enviada if code == Protocol.type_package_delivery and atual == count and client == client_number: print("-------------------------") print("Pacote {} de {} recebido".format(atual, total)) print("-------------------------") recieved += data message = packer.pack_message(Protocol.type_package_ok, count, total, Protocol.sever_number, client_number) com.sendData(message) while(com.tx.getIsBussy()): pass count += 1 time_out_time = time.time() log.write("Msg: {} – enviada: {} – destinatário: {}\n".format(Protocol.type_package_ok, time.ctime(time.time()), client_number)) # Se o pacote recebido não conter o código certo eou seu número não bater com o esperado, # seu conteúdo é ignorado e uma mensage de erro com o pacote esperado é enviada else: print("-------------------------") print("Erro") print("Aguardando reenvio") print("-------------------------") message = packer.pack_message(Protocol.type_error, count, total, Protocol.sever_number, client_number) com.sendData(message) while(com.tx.getIsBussy()): pass log.write("Msg: {} – enviada: {} – destinatário: {}\n".format(Protocol.type_error, time.ctime(time.time()), client_number)) # Quando todos os pacotes forem recebidos o stuffing, se houver, é removido e o arquivo salvo # O server volta para seu estado ocioso elif count > total: end = time.time() - start print("-------------------------") print("Pacotes recebidos com sucesso") print("Taxa de recepção: {:02}".format(total*Protocol.max_size/end)) print("Salvando") print("-------------------------") to_save = unpacker.destuff(recieved) open("recieved/recieved{:02}".format(file_num) + Protocol.from_kind[kind],"wb").write(to_save) log.write("Salvo em: {}\n".format(time.ctime(time.time()))) log.close() file_num += 1 print("-------------------------") print("Aguardando novo envio") print("-------------------------") ocioso = True serverReady_message_sent = False com.rx.clearBuffer() count = 1 try_num = 1 # Se mais tempo que o estipulado para um timeout passou, o server volta para seu estado ocioso else: print("-------------------------") print("Timeout") print("Aguardando novo envio") print("-------------------------") message = packer.pack_message(Protocol.type_time_out, count, total, my_server, client_number) com.sendData(message) while(com.tx.getIsBussy()): pass ocioso = True serverReady_message_sent = False count = 1 log.write("Msg: {} – enviada: {} – destinatário: {}\n".format(Protocol.type_time_out, time.ctime(time.time()), client_number)) log.write("Encerrado\n") log.close()
def main(): try: parser = optparse.OptionParser( usage= '%prog -f <hex_file> -a <dfu_target_address>\n\nExample:\n\tdfu.py -f application.hex -d application.dat -a cd:e3:4a:47:1c:e4', version='0.5') parser.add_option('-a', '--address', action='store', dest="address", type="string", default=None, help='DFU target address.') parser.add_option('-f', '--file', action='store', dest="hexfile", type="string", default=None, help='hex file to be uploaded.') parser.add_option('-d', '--dat', action='store', dest="datfile", type="string", default=None, help='dat file to be uploaded.') parser.add_option('-z', '--zip', action='store', dest="zipfile", type="string", default=None, help='zip file to be used.') parser.add_option('--secure', action='store_true', dest='secure_dfu', default=True, help='Use secure bootloader (Nordic SDK > 12)') parser.add_option('--legacy', action='store_false', dest='secure_dfu', help='Use secure bootloader (Nordic SDK < 12)') parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='Enable verbose mode') options, args = parser.parse_args() except Exception as e: print(e) print("For help use --help") sys.exit(2) try: ''' Validate input parameters ''' if not options.address: parser.print_help() exit(2) unpacker = None hexfile = None datfile = None if options.zipfile != None: if (options.hexfile != None) or (options.datfile != None): print("Conflicting input directives") exit(2) unpacker = Unpacker() #print options.zipfile try: hexfile, datfile = unpacker.unpack_zipfile(options.zipfile) except Exception as e: print("ERR") print(e) pass else: if (not options.hexfile) or (not options.datfile): parser.print_help() exit(2) if not os.path.isfile(options.hexfile): print("Error: Hex file doesn't exist") exit(2) if not os.path.isfile(options.datfile): print("Error: DAT file doesn't exist") exit(2) hexfile = options.hexfile datfile = options.datfile ''' Start of Device Firmware Update processing ''' if options.verbose: init_msg = \ """ ================================ == == == DFU Server == == == ================================ """ # print "DFU Server start" print(init_msg) if options.secure_dfu: ble_dfu = BleDfuControllerSecure(options.address.upper(), hexfile, datfile) else: ble_dfu = BleDfuControllerLegacy(options.address.upper(), hexfile, datfile) # Initialize inputs ble_dfu.input_setup() # Connect to peer device. Assume application mode. if ble_dfu.scan_and_connect(): if not ble_dfu.check_DFU_mode(): print("Need to switch to DFU mode") success = ble_dfu.switch_to_dfu_mode() if not success: print("Couldn't reconnect") else: # The device might already be in DFU mode (MAC + 1) ble_dfu.target_mac_increase(1) # Try connection with new address print("Couldn't connect, will try DFU MAC") if not ble_dfu.scan_and_connect(): raise Exception("Can't connect to device") ble_dfu.start() # Disconnect from peer device if not done already and clean up. ble_dfu.disconnect() except Exception as e: # print traceback.format_exc() print("Exception at line {}: {}".format(sys.exc_info()[2].tb_lineno, e)) pass except: pass # If Unpacker for zipfile used then delete Unpacker if unpacker != None: unpacker.delete() if options.verbose: print("DFU Server done")