Пример #1
0
    def __init__(self, dev_addr, nwk_swkey, app_swkey):
        #Initialise pyscan
        py = Pysense()
        self.axis_sensor = LIS2HH12(py)
        self.light_sensor = LTR329ALS01(py)
        self.air_sensor = SI7006A20(py)
        self.pressure_sensor = MPL3115A2(py)
        self.altitude_sensor = MPL3115A2(py, mode=ALTITUDE)

        # Initialise LoRa in LORAWAN mode.
        self.lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)

        # create an ABP authentication params
        dev_addr = struct.unpack(">l", binascii.unhexlify(dev_addr))[0]
        nwk_swkey = ubinascii.unhexlify(nwk_swkey)
        app_swkey = ubinascii.unhexlify(app_swkey)

        # join a network using ABP (Activation By Personalization)
        self.lora.join(activation=LoRa.ABP,
                       auth=(dev_addr, nwk_swkey, app_swkey))

        # create a LoRa socket
        self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

        # set the LoRaWAN data rate
        self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)

        # make the socket blocking
        # (waits for data to be sent and for the 2 receive windows to expire)
        self.s.setblocking(True)
Пример #2
0
def init(rdr, answerjs, raw_uid):
    log("INIT!")
    log(answerjs)
    if (answerjs["setantiblk"] != ""):
        log("initializing sector 0...")
        if rdr.auth(rdr.AUTHENT1A, 2, defaultkey, raw_uid) == rdr.OK:
            rdr.write(2, nfc_writemessage)

        for i in range(1, 16):
            log("writing sector %s" % i)
            if rdr.auth(rdr.AUTHENT1A, i * 4, defaultkey, raw_uid) == rdr.OK:
                #log("auth ok")
                for x in range(0, 3):
                    #write filler data or real hash
                    numblk = (i * 4) + x
                    numfiller = (
                        (i - 4) *
                        4) + x  #Array begins at 0 but blocks begin at 4
                    if numblk == int(answerjs["setantiblk"]):
                        log("writing hash to block: %s" % numblk)
                        rdr.write(int(answerjs["setantiblk"]),
                                  answerjs["txt"].encode())
                    else:
                        #log("writing filler to block: %s" % numblk)
                        rdr.write(numblk,
                                  answerjs["filler"][numfiller].encode())

                rdr.setKey(i, ubinascii.unhexlify(answerjs["keya"][i]),
                           ubinascii.unhexlify(answerjs["keyb"][i]))
                log("key set complete")
            else:
                log("auth error")
    else:
        log("server response error...")
Пример #3
0
    def test_get_address_from_contract(self):
        contracts = [
            TezosContractID(
                tag=TezosContractType.Implicit,
                hash=unhexlify("0090ec585b4d5fa39b20213e46b232cc57a4cfab4b"),
            ),
            TezosContractID(
                tag=TezosContractType.Implicit,
                hash=unhexlify("017dfb3fef44082eca8cd3eccebd77db44633ffc9e"),
            ),
            TezosContractID(
                tag=TezosContractType.Implicit,
                hash=unhexlify("02c1fc1b7e503825068ff4fe2f8916f98af981eab1"),
            ),
            TezosContractID(
                tag=TezosContractType.Originated,
                hash=unhexlify("65671dedc69669f066f45d586a2ecdeddacc95af00"),
            ),
        ]

        outputs = [
            "tz1YrK8Hqt6GAPYRHAaeJmhETYyPSQCHTrkj",
            "tz2KoN7TFjhp96V2XikqYSGyDmVVUHXvkzko",
            "tz3e1k3QzCwEbRZrfHCwT3Npvw1rezmMQArY",
            "KT1HpwLq2AjZgEQspiSnYmdtaHy4NgXw6BDC",
        ]

        for i, contract in enumerate(contracts):
            self.assertEqual(_get_address_from_contract(contract), outputs[i])
Пример #4
0
    def decrypt(self, payload):
        """Decrypts the each encrypted item of the payload.
        Initialize decryption cipher for each item and and use cipher to decrypt payload items.
        :param payload  : received MQTT message from Spinner #1. This includes all encrypted data, nodeid, iv, and HMAC
        :return         : MQTT message to publish to Spinner #1 on Topic "Acknowledge", can be "Successful Decryption"
        """
        decrypted_payload = ujson.loads(payload)
        decrypted_iv = ubinascii.unhexlify(decrypted_payload['encrypted_iv'])
        decrypted_nodeid = ubinascii.unhexlify(decrypted_payload['encrypted_nodeid'])
        decrypted_data = ubinascii.unhexlify(decrypted_payload['encrypted_data'])
        decrypted_hmac = decrypted_payload['hmac']
        
        decryption_cipher = aes(self.ivkey,2,self.staticiv)
        decrypt_iv= decryption_cipher.decrypt(decrypted_iv)

        decryption_data = aes(self.datakey,2,decrypt_iv)
        decrypt_data = decryption_data.decrypt(decrypted_data)

        sensor_data={}
        sensor_data['a_x']=float(decrypt_data[0:8])
        sensor_data['a_y']=float(decrypt_data[8:16])
        sensor_data['a_z']=float(decrypt_data[16:24])
        sensor_data['temp']=float(decrypt_data[24:32])

        return (0,sensor_data)
Пример #5
0
    def start(self, boot=True):
        if not self.sta_if.isconnected():
            print('Tentando conectar...', end="")
            self.sta_if.active(True)
            i = 0
            while i < len(self.config) and not self.sta_if.isconnected():
                self.connection(
                    ubinascii.a2b_base64(ubinascii.unhexlify(
                        self.config[i][0])),
                    ubinascii.a2b_base64(ubinascii.unhexlify(
                        self.config[i][1])))
                print(".", end="")
                time.sleep_ms(200)
                i += 1

        if not self.sta_if.isconnected() and boot:
            self.sta_if.active(False)
            print('Rede não conectada')
            d = dnsquery.start()
            self.connection(d[b's'].decode(), d[b'p'].decode())
            if self.sta_if.isconnected():
                self.config[self.lconf] = [
                    ubinascii.hexlify(ubinascii.b2a_base64(d[b's'])[:-1]),
                    ubinascii.hexlify(ubinascii.b2a_base64(d[b'p'])[:-1])
                ]
                f = open('config.json', 'w')
                f.write(ujson.dumps(self.config))
                f.close()
                machine.reset()
            else:
                time.sleep(1)
                machine.reset()

        return self.sta_if
Пример #6
0
    def decrypt(self, payload):
        """Decrypts the each encrypted item of the payload.
        Initialize decryption cipher for each item and and use cipher to decrypt payload items.
        :param payload  : received MQTT message from Spinner #1. This includes all encrypted data, nodeid, iv, and HMAC
        :return         : MQTT message to publish to Spinner #1 on Topic "Acknowledge", can be "Successful Decryption"
        """
        text = json.loads(payload)
        rece_HMAC = ubinascii.unhexlify(text["HMAC"])
        rece_iv = ubinascii.unhexlify(text["e_iv"])
        rece_nodeid = ubinascii.unhexlify(text["e_nodeid"])
        rece_sensord = ubinascii.unhexlify(text["e_sd"])

        #encrypt iv
        myaes = aes(self.ivkey, 2, self.staticiv)
        iv = myaes.decrypt(rece_iv)
        striv = iv.decode("utf-8")
        print(striv)
        #encrypt data
        myes = aes(self.datakey, 2, striv)
        node_id = myes.decrypt(rece_nodeid).decode("utf-8")
        byte_sensord = myes.decrypt(rece_sensord)
        sensord = byte_sensord.decode("utf-8")
        data = sensord.strip(chr(0)).split(' ')
        data_x = float(data[0])
        data_y = float(data[1])
        data_z = float(data[2])
        data_temp = float(data[3])
        print(data_x, data_y, data_z, data_temp)
        return True, node_id, data_x, data_y, data_z, data_temp
Пример #7
0
 def __init__(self, app_eui, app_key, frequency=868100000, dr=5):
     '''setup LoRaWAN for the European 868 MHz region with OTAA'''
     self.dr = dr
     self.frequency = frequency
     self.app_eui = ubinascii.unhexlify(app_eui)
     self.app_key = ubinascii.unhexlify(app_key)
     self.lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)
     self.socket = None
     self.setup()
Пример #8
0
    def test_tezos_encode_data_with_bool_prefix(self):
        w = bytearray()
        _encode_data_with_bool_prefix(w, None)
        self.assertEqual(bytes(w), bytes([0]))

        data = "afffeb1dc3c0"
        w = bytearray()
        _encode_data_with_bool_prefix(w, unhexlify(data))
        self.assertEqual(bytes(w), unhexlify("ff" + data))
Пример #9
0
    def __init__(self, app_eui, app_key):
        """setup LoRaWAN for the European 868 MHz region with OTAA"""
        self.app_eui = ubinascii.unhexlify(app_eui)
        self.app_key = ubinascii.unhexlify(app_key)

        self.lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)
        self.socket = None

        self.setup()
Пример #10
0
    def joinOTAA(self):
        app_eui = ubinascii.unhexlify(self.options['lora_app_eui'])
        app_key = ubinascii.unhexlify(self.options['lora_app_key'])

        self.lora.join(activation=LoRa.OTAA,
                       auth=(app_eui, app_key),
                       timeout=0)
        self.log("Joining via OTAA")
        self.lastJoin = time.time()
Пример #11
0
 def load_secret():
     try:
         with open(secret_fname, "r") as f:
             d = json.loads(f.read())
     except:
         return False
     Secret.secret = unhexlify(d["secret"])
     Secret.hmac = unhexlify(d["hmac"])
     return True
Пример #12
0
 async def _readline(self) -> (bytearray, bytearray, any):
     led = self._led
     line = b''
     start = utime.ticks_ms()
     while True:
         if line.endswith(b'\n'):
             self._ok = True  # Got at least 1 packet after an outage.
             if len(line) > 1:
                 d = uio.StringIO(line)
                 try:
                     preheader = bytearray(ubinascii.unhexlify(d.read(6)))
                     if preheader[1] != 0:
                         header = bytearray(
                             ubinascii.unhexlify(d.read(preheader[1] * 2)))
                     else:
                         header = None
                     if len(line
                            ) > 7 + preheader[1] * 2:  # preheader+header+\n
                         line = ujson.load(d)
                     else:
                         line = b""
                 except ValueError as e:
                     print("Error converting message:", d.read(), "error:",
                           e)
                     line = b''
                     continue
                 except Exception as e:
                     print("Error converting sth", e)
                     continue
                 finally:
                     d.close()
                     gc.collect()
                 return preheader, header, line
             # Got a keepalive: discard, reset timers, toggle LED.
             self._feed(0)
             line = b''
             if led is not None:
                 if isinstance(led, machine.Pin):
                     led(not led())
                 else:  # On Pyboard D
                     led.toggle()
         try:
             d = self._sock.readline()
         except Exception as e:
             self._verbose and print('_readline exception')
             raise
         if d == b'':
             self._verbose and print('_readline peer disconnect')
             raise OSError
         if d is None:  # Nothing received: wait on server
             if utime.ticks_diff(utime.ticks_ms(), start) > self._to:
                 self._verbose and print('_readline timeout')
                 raise OSError
             await asyncio.sleep_ms(0)
         else:  # Something received: reset timer
             start = utime.ticks_ms()
             line = b''.join((line, d)) if line else d
Пример #13
0
	def handle_incoming_telegram(self,telegram,ticks):
		"""Called whenever a new MBus master request has been received.\nParses the request and ensures the correct responses from the tracked devices are collected and sent back.\n"""
		if telegram[0] == 0x10:
			# SND_NKE
			if telegram[1] == 0x40:
				# If broadcast to 0xfd, deselect the currently selected device
				if telegram[2] == 0xfd:
					list(map(lambda device: device.deselect(),self.devices.values()))
				# If broadcast to all devices on bus, have them reply or indicate collision
				elif telegram[2] == 0xfe:
					#map(lambda device: device.select(),self.devices.values())
					no_of_devices = len(list(self.devices.values()))
					if no_of_devices >= 2:
						self.mbus_uart.send_collision()
					elif no_of_devices == 1:
						self.mbus_uart.send_ack()
				# If wanting to select a specific device via primary address
				elif telegram[2] in self.devices.keys():
					self.mbus_uart.send_ack()
			# REQ_UD2
			elif ((telegram[1] == 0x5b) or (telegram[1] == 0x7b)):
				# If broadcast to 0xFD (selected devices)..
				if telegram[2] == 0xfd:
					devices_found = [device for device in self.devices.values() if device.is_selected()]
					no_of_devices = len(devices_found)
					if no_of_devices >=2:
						self.mbus_uart.send_collision()
					elif no_of_devices == 1:
						device = devices_found[0]
						resp_bytes = ubinascii.unhexlify(device.get_latest_values())
						self.mbus_uart.send_telegram(resp_bytes,ticks)
				# If targetting a specific device via primary address					
				elif (telegram[2] in self.devices.keys()):
					device = self.devices[telegram[2]]
					resp_bytes = ubinascii.unhexlify(device.get_latest_values())
					self.mbus_uart.send_telegram(resp_bytes,ticks)						
		elif telegram[0] == 0x68:
			# SND_UD
			if ((telegram[4] == 0x53) or (telegram[4] == 0x73)):
				if ((telegram[5] == 0xfd) and (telegram[6] == 0x52)):
					search_bytes = list(telegram[7:11])
					search_bytes.reverse()
					search_string = "".join(['{0:0{1}x}'.format(b,2) for b in search_bytes])
					self.log("searching with string {}".format(search_string))
					devices_found = [device for device in self.devices.values() if device.matches_secondary_address(search_string)]
					devices_not_found = [device for device in self.devices.values() if device not in devices_found]
					list(map(lambda device: device.select(),devices_found))
					list(map(lambda device: device.deselect(),devices_not_found))
					if(len(devices_found) >= 2):
						self.log("multiple devices found for search string {}".format(search_string))
						for device in devices_found:
							self.mbus_uart.send_ack()
					elif(len(devices_found) == 1):
						device = devices_found[0]
						self.log("one device found for search string {}".format(search_string))
						self.mbus_uart.send_ack()
Пример #14
0
def main():
    # all from the same private key
    prv = ec.PrivateKey.from_wif(
        "L2e5y14ZD3U1J7Yr62t331RtYe2hRW2TBBP8qNQHB8nSPBNgt6dM")
    pub = prv.get_public_key()
    print("Public key:")
    print(hexlify(pub.serialize()))

    # we will generate regtest addresses
    network = NETWORKS['regtest']

    print("Legacy (pay to pubkey hash):")
    sc = script.p2pkh(pub)
    # default network is main
    print(sc.address(network))

    print("Segwit (pay to witness pubkey hash):")
    sc = script.p2wpkh(pub)
    print(sc.address(network))

    print("Nested segwit (p2sh-p2wpkh):")
    sc = script.p2sh(script.p2wpkh(pub))
    print(sc.address(network))

    print("\nMiltisig address (2 of 3):")
    # unsorted
    pubs = [
        ec.PublicKey.parse(
            unhexlify(
                "02edd7a58d2ff1e483d35f92a32e53607423f936b29bf95613cab24b0b7f92e0f1"
            )),
        ec.PublicKey.parse(
            unhexlify(
                "03a4a6d360acc45cb281e0022b03218fad6ee93881643488ae39d22b854d9fa261"
            )),
        ec.PublicKey.parse(
            unhexlify(
                "02e1fdc3b011effbba4b0771eb0f7193dee24cfe101ab7e8b64516d83f7116a615"
            )),
    ]
    # 2 of 3 multisig script
    sc = script.multisig(2, pubs)
    print("Legacy, unsorted (p2sh):")
    redeem_sc = script.p2sh(sc)
    print(redeem_sc.address(network))

    print("Native segwit, sorted (p2wsh):")
    sc = script.multisig(2, sorted(pubs))
    witness_sc = script.p2wsh(sc)
    print(witness_sc.address(network))

    print("Nested segwit, sorted (p2sh-p2wsh):")
    sc = script.multisig(2, sorted(pubs))
    witness_sc = script.p2wsh(sc)
    redeem_sc = script.p2sh(witness_sc)
    print(redeem_sc.address(network))
    def test_addresses(self):
        pubkey = unhexlify(
            'c5f54ba980fcbb657dbaaa42700539b207873e134d2375efeab5f1ab52f87844')
        address = nem.compute_address(pubkey, NEM_NETWORK_MAINNET)
        self.assertEqual(address, 'NDD2CT6LQLIYQ56KIXI3ENTM6EK3D44P5JFXJ4R4')

        pubkey = unhexlify(
            '114171230ad6f8522a000cdc73fbc5c733b30bb71f2b146ccbdf34499f79a810')
        address = nem.compute_address(pubkey, NEM_NETWORK_MAINNET)
        self.assertEqual(address, 'NCUKWDY3J3THKQHAKOK5ALF6ANJQABZHCH7VN6DP')
Пример #16
0
    def joinABP(self):
        net_key = ubinascii.unhexlify(self.options['lora_net_key'])
        app_key = ubinascii.unhexlify(self.options['lora_app_key'])
        # note: TTN seems to want the reverse bytes of this address
        device_address = ubinascii.unhexlify(self.options['lora_dev_adr'])

        self.lora.join(activation=LoRa.ABP,
                       auth=(device_address, net_key, app_key))
        self.log("Joining via ABP with device address", device_address)
        self.lastJoin = time.time()
Пример #17
0
    def initialize_lorawan_link(self):
        #print(ubinascii.hexlify(network.LoRa().mac()))

        # Initialise LoRa in LORAWAN mode.
        # Please pick the region that matches where you are using the device:
        # Asia = LoRa.AS923
        # Australia = LoRa.AU915
        # Europe = LoRa.EU868
        # United States = LoRa.US915
        lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.AU915, adr=False)
        self.myLora = lora

        # create an ABP authentication params
        dev_addr = struct.unpack(">l", ubinascii.unhexlify('260211EE'))[0]
        nwk_swkey = ubinascii.unhexlify('AB189EFE29DCF9F9830F3A564DC1844E')
        app_swkey = ubinascii.unhexlify('A55931ACC412DE51171CEDA45BE6B319')

        #for channel in range(0, 72):
        #    lora.add_channel(channel, frequency=916800000, dr_min=0, dr_max=5)
        #lora.add_channel(0, frequency=923300000, dr_min=0, dr_max=5)

        for i in range(8, 72):
            lora.remove_channel(i)

        start = 916800000
        f_inc = 200000
        curr  = start

        for i in range(8):
            #print(curr)
            lora.add_channel(index=i, frequency=curr, dr_min=0, dr_max=5)
            curr += f_inc

        #lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=self.lora_cb)

        # join a network using ABP (Activation By Personalization)
        lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))

        #print(lora.has_joined())

        # wait until the module has joined the network
        while not lora.has_joined():
            time.sleep(2.5)
            print('Not yet joined...')

        #print("Has joined!!!!!")

        # create a LoRa socket
        s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

        # set the LoRaWAN data rate
        s.setsockopt(socket.SOL_LORA, socket.SO_DR, self.data_rate)
        s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, False)

        return s
Пример #18
0
def connect():
    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)
    app_eui = ubinascii.unhexlify('70B3D57ED003E9AD')
    app_key = ubinascii.unhexlify('F212905C83160EE25DF713181E160274')
    dev_eui = ubinascii.unhexlify('70B3D549911BCF55')
    lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0)

    while not lora.has_joined():
        time.sleep(2.5)
        print('Not yet joined...')
    print('Joined')
Пример #19
0
def loraConnect():
    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)
    app_eui = ubinascii.unhexlify('70B3D57ED003E4C4')
    app_key = ubinascii.unhexlify('2F77C58DD6AB59F1A603976A6792A598')
    dev_eui = ubinascii.unhexlify('70B3D549943157B4')
    lora.join(activation=LoRa.OTAA,
              auth=(dev_eui, app_eui, app_key),
              timeout=0)
    while not lora.has_joined():
        time.sleep(2.5)
        print('Not yet joined...')
    print('Joined')
Пример #20
0
def connect(appeui, appkey, force=False, max_retry=20, grace_period=2.5):
    """
    Create and connect Socket for LoRa application using OTAA mechanism
    """

    # Initialise LoRa in LORAWAN mode.
    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)
    #lora.nvram_erase()
    lora.nvram_restore()

    if not lora.has_joined() or force:

        # create an OTAA authentication parameters
        app_eui = ubinascii.unhexlify(appeui)
        app_key = ubinascii.unhexlify(appkey)

        # join a network using OTAA (Over the Air Activation)
        lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
        
    # wait until the module has joined the network
    i = 0
    while not lora.has_joined():
        time.sleep(grace_period)
        i += 1
        print('LORA/OTAA [EUI={}]: Application Join request pending ({}/{})...'.format(appeui, i, max_retry))
        if i >= max_retry:
            break
    else:
        print('LORA/OTAA [EUI={}]: Application Join request accepted'.format(appeui))

    # create a LoRa socket
    sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

    # set the LoRaWAN data rate
    sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)

    # make the socket blocking
    # (waits for the data to be sent and for the 2 receive windows to expire)
    sock.setblocking(True)
    #sock.send(b'')
    
    # make the socket non-blocking
    # (because if there's no data received it will block forever...)
    sock.setblocking(False)
    #sock.recv(64)

    # Save LoRa State:
    # https://forum.pycom.io/topic/1668/has-anyone-successfully-used-lora-nvram_save-and-restore/16
    lora.nvram_save()
    print('LORA/OTAA [EUI={}]: LoRa state saved'.format(appeui))

    return sock, lora
Пример #21
0
def init_lora_wan(lora, timeout):
    app_eui = ubinascii.unhexlify('XXX')
    app_key = ubinascii.unhexlify('YYY')
    # #join a network using OTAA (Over the Air Activation)
    lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
    while not lora.has_joined():
        time.sleep(2.5)
        print('Not joined LoRa.OTAA yet ...')
    # #create a LoRa socket
    lorasocket = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
    # set the LoRaWAN data rate
    lorasocket.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
    return lorasocket
Пример #22
0
def bytes_from_address(address: str) -> bytes:
    if len(address) == 40:
        return unhexlify(address)

    elif len(address) == 42:
        if address[0:2] not in ("0x", "0X"):
            raise wire.ProcessError("Klaytn: invalid beginning of an address")
        return unhexlify(address[2:])

    elif len(address) == 0:
        return bytes()

    raise wire.ProcessError("Klaytn: Invalid address length")
Пример #23
0
def init():
    teller = 0
    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)
    app_eui = ubinascii.unhexlify('70B3D57ED003E4D4')
    app_key = ubinascii.unhexlify('511FCEA75A175980B26A145EAC4C56E9')
    lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
    while not lora.has_joined():
        time.sleep(1)
        print('Not yet joined...')
        teller = teller+1
        if teller==10:
            break
    return(lora)
Пример #24
0
def abp(address='00124f11',
        networkSessionKey='844a432a89b1b23598e4d24d631a9248',
        applicationSessionKey='3f1807cd4c7817144147a48b4ec93648',
        value=True):

    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)

    # This is to make sure it work with nano gw
    LORA_FREQUENCY = 868100000  # sigle channel used on nano gw
    lora.add_channel(0, frequency=LORA_FREQUENCY, dr_min=0, dr_max=5)
    lora.add_channel(1, frequency=LORA_FREQUENCY, dr_min=0, dr_max=5)
    lora.add_channel(2, frequency=LORA_FREQUENCY, dr_min=0, dr_max=5)

    # create an ABP authentication params
    dev_addr = struct.unpack(">l", ubinascii.unhexlify(address))[0]
    nwk_swkey = ubinascii.unhexlify(networkSessionKey)
    app_swkey = ubinascii.unhexlify(applicationSessionKey)

    # join a network using ABP (Activation By Personalization)
    lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))

    # create a LoRa socket
    s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

    # set the LoRaWAN data rate
    s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)

    # make the socket blocking
    # (waits for the data to be sent and for the 2 receive windows to expire)
    s.setblocking(True)

    # send some data
    lpp = CayenneLPP(size=100, sock=s)
    lpp.add_digital_input(value, channel=66)

    # sending the packet via the socket
    lpp.send()

    # s.send(bytes([0x01, 0x02, 0x03]))

    # make the socket non-blocking
    # (because if there's no data received it will block forever...)
    s.setblocking(False)

    # get any data received (if any...)
    data = s.recv(64)
    print(data)
    print("done")
    pycom.rgbled(0x007f00)  # green
    time.sleep(5)
    pycom.heartbeat(False)
Пример #25
0
def connect_to_app(app_eui, app_key):
    print("start connecting")
    # Initialise LoRa in LORAWAN mode.
    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)
    # create an OTAA authentication parameters
    app_eui = ubinascii.unhexlify(app_eui)
    app_key = ubinascii.unhexlify(app_key)
    # join a network using OTAA (Over the Air Activation)
    lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
    # wait until the module has joined the network
    while not lora.has_joined():
        time.sleep(2.5)
        print('Not yet joined...')
    print("has joined network. Ready to send data...")
Пример #26
0
    def __init__(self):
        super(LoRa, self).__init__()

        # check if safety variable is true
        if not self.config().get("antenna_connected"):
            raise Exception(
                "configuration variable 'antenna_connected' is not true")

        # get the reset cause
        import machine
        reset_cause = machine.reset_cause()

        # initialize lora network
        from network import LoRa as LoRa_drv
        self.lora = LoRa_drv(mode=LoRa_drv.LORAWAN,
                             region=LoRa_drv.EU868,
                             adr=self.config().get("adr"))

        # try to load previous lora connection if waking up from deep sleep
        if reset_cause == machine.DEEPSLEEP_RESET:
            self.lora.nvram_restore()

        if reset_cause == machine.DEEPSLEEP_RESET and self.lora.has_joined():
            log_info("Restored previous LoRaWAN join.")

        else:
            # get authentication parameters
            import ubinascii
            app_eui = ubinascii.unhexlify(self.config().get("app_eui"))
            app_key = ubinascii.unhexlify(self.config().get("app_key"))

            # join a network using OTAA (Over the Air Activation)
            self.lora.join(activation=LoRa_drv.OTAA,
                           auth=(app_eui, app_key),
                           timeout=0,
                           dr=self.config().get("data_rate"))

            # wait until the module has joined the network
            log_debug("Waiting until LoRa has joined.")
            while not self.lora.has_joined():
                pass
            log_info("Joined LoRa network.")

        # create a lora socket to send data
        import socket
        self.socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

        # set the LoRaWAN data rate
        self.socket.setsockopt(socket.SOL_LORA, socket.SO_DR,
                               self.config().get("data_rate"))
Пример #27
0
def join_lora(force_join=False):
    '''Joining The Things Network '''
    print('Joining TTN')

    # restore previous state
    if not force_join:
        lora.nvram_restore()

    if not lora.has_joined() or force_join == True:

        # create an OTA authentication params
        dev_eui = ubinascii.unhexlify(config['lora']['otaa']['app_device_eui'])
        app_eui = ubinascii.unhexlify(
            config['lora']['otaa']
            ['app_eui'])  # these settings can be found from TTN
        app_key = ubinascii.unhexlify(
            config['lora']['otaa']
            ['app_key'])  # these settings can be found from TTN
        # print('key:{}, eui:{}'.format(app_key, app_eui))
        # join a network using OTAA (Over the Air Activation) if not previously done
        # lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0, dr=0)
        lora.join(activation=LoRa.OTAA,
                  auth=(dev_eui, app_eui, app_key),
                  timeout=0)
        # lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))

        # wait until the module has joined the network
        while not lora.has_joined():
            print('Not yet joined...')
            pycom.rgbled(0xcc00ff)
            time.sleep(3)
            pycom.rgbled(0x000000)
            time.sleep(0.5)

        # saving the state
        lora.nvram_save()

        # returning whether the join was successful
        if lora.has_joined():
            flash_led_to(BLUE)
            print('LoRa Joined')
            return True
        else:
            flash_led_to(RED)
            print('LoRa Not Joined')
            return False

    else:
        return True
    def __init__(self, interval, app_eui, app_key, dp_callback):
        self.interval = interval  # num secs to sleep
        self.callback = dp_callback
        self.app_eui = ubinascii.unhexlify(
            app_eui)  # determines app to connect to
        self.app_key = ubinascii.unhexlify(app_key)  # grants access
        self.lora = LoRa(mode=LoRa.LORAWAN,
                         region=LoRa.EU868)  # used to join a network
        self.s = socket.socket(
            socket.AF_LORA,
            socket.SOCK_RAW)  # used to send data to joined network

        self.connect()  # joins application specified through app_eui

        self.__alarm = Timer.Alarm(self._uploader, interval, periodic=True)
Пример #29
0
def load_key():
    global entropy
    try:
        with open(reckless_fname, "r") as f:
            d = json.loads(f.read())
            entropy = unhexlify(d["entropy"])
        if "hmac" in d:
            hmac_calc = hmac_sha512(Key.key, entropy)
            if unhexlify(d["hmac"]) != hmac_calc:
                raise ValueError('Hmac does not match!')
            Key.iv = unhexlify(d["iv"])
            entropy = entropy_decrypt(entropy)
        ask_for_password()
    except:
        gui.error("Something went wrong, sorry")
Пример #30
0
def load_key():
    global entropy
    with open(reckless_fname, "r") as f:
        d = json.loads(f.read())
        entropy = unhexlify(d["entropy"])
    if "hmac" in d:
        hmac_calc = hmac_sha512(Key.key, entropy)
        if unhexlify(d["hmac"]) != hmac_calc:
            raise ValueError('Hmac does not match!')
        Key.iv = unhexlify(d["iv"])
        entropy = entropy_decrypt(entropy)
    if entropy is not None:
        ask_for_password()
    else:
        gui.error("Failed to load your recovery phrase.")
Пример #31
0
 def _push_data(self, data):
     token = uos.urandom(2)
     packet = bytes([PROTOCOL_VERSION]) + token + bytes([PUSH_DATA]) + ubinascii.unhexlify(self.id) + data
     with self.udp_lock:
         try:
             self.sock.sendto(packet, self.server_ip)
         except Exception as ex:
             self._log('Failed to push uplink packet to server: {}', ex)
Пример #32
0
 def _pull_data(self):
     token = uos.urandom(2)
     packet = bytes([PROTOCOL_VERSION]) + token + bytes([PULL_DATA]) + ubinascii.unhexlify(self.id)
     with self.udp_lock:
         try:
             self.sock.sendto(packet, self.server_ip)
         except Exception as ex:
             self._log('Failed to pull downlink packets from server: {}', ex)
Пример #33
0
 def _ack_pull_rsp(self, token, error):
     TX_ACK_PK["txpk_ack"]["error"] = error
     resp = ujson.dumps(TX_ACK_PK)
     packet = bytes([PROTOCOL_VERSION]) + token + bytes([PULL_ACK]) + ubinascii.unhexlify(self.id) + resp
     with self.udp_lock:
         try:
             self.sock.sendto(packet, self.server_ip)
         except Exception as ex:
             self._log('PULL RSP ACK exception: {}', ex)
Пример #34
0
def b16decode(s, casefold=False):
    """Decode a Base16 encoded byte string.

    s is the byte string to decode.  Optional casefold is a flag
    specifying whether a lowercase alphabet is acceptable as input.
    For security purposes, the default is False.

    The decoded byte string is returned.  binascii.Error is raised if
    s were incorrectly padded or if there are non-alphabet characters
    present in the string.
    """
    s = _bytes_from_decode_data(s)
    if casefold:
        s = s.upper()
    if re.search(b'[^0-9A-F]', s):
        raise binascii.Error('Non-base16 digit found')
    return binascii.unhexlify(s)
Пример #35
0
def recv_file_from_host(src_file, dst_filename, filesize, dst_mode='wb'):
    """Function which runs on the pyboard. Matches up with send_file_to_remote."""
    import sys
    import ubinascii
    import pyb
    usb = pyb.USB_VCP()
    if HAS_BUFFER and usb.isconnected():
        # We don't want 0x03 bytes in the data to be interpreted as a Control-C
        # This gets reset each time the REPL runs a line, so we don't need to
        # worry about resetting it ourselves
        usb.setinterrupt(-1)
    try:
        with open(dst_filename, dst_mode) as dst_file:
            bytes_remaining = filesize
            if not HAS_BUFFER:
                bytes_remaining *= 2 # hexlify makes each byte into 2
            buf_size = BUFFER_SIZE
            write_buf = bytearray(buf_size)
            read_buf = bytearray(buf_size)
            while bytes_remaining > 0:
                read_size = min(bytes_remaining, buf_size)
                buf_remaining = read_size
                buf_index = 0;
                while buf_remaining > 0:
                    if HAS_BUFFER:
                        bytes_read = sys.stdin.buffer.readinto(read_buf, bytes_remaining)
                    else:
                        bytes_read = sys.stdin.readinto(read_buf, bytes_remaining)
                    if bytes_read > 0:
                        write_buf[buf_index:bytes_read] = read_buf[0:bytes_read]
                        buf_index += bytes_read
                        buf_remaining -= bytes_read
                if HAS_BUFFER:
                    dst_file.write(write_buf[0:read_size])
                else:
                    dst_file.write(ubinascii.unhexlify(write_buf[0:read_size]))
                # Send back an ack as a form of flow control
                sys.stdout.write('\x06')
                bytes_remaining -= read_size
        return True
    except:
        return False
Пример #36
0
try:
    import ubinascii as binascii
except ImportError:
    import binascii

print(binascii.unhexlify(b'0001020304050607'))
print(binascii.unhexlify(b'08090a0b0c0d0e0f'))
print(binascii.unhexlify(b'7f80ff'))
print(binascii.unhexlify(b'313233344142434461626364'))
Пример #37
0
import ubinascii, gc, usnmp

#getresponse
s="3081d20201000403414643a281c702043821eea10201000201003081b8300f060a2b0601020102020101010201013013060a2b0601020102020102010405566c616e31300f060a2b0601020102020103010201353010060a2b060102010202010401020205dc3012060a2b06010201020201050142043b9aca003014060a2b0601020102020106010406001b8ff4d1c0300f060a2b060102010202010701020102300f060a2b0601020102020108010201023010060a2b06010201020201090143022c06300f060a2b060102010202010a01410100"

b=bytes(ubinascii.unhexlify(s))

usnmp.frombytes_tvat(b,0)
usnmp.frombytes_tvat(b,3)
usnmp.frombytes_tvat(b,6)
usnmp.frombytes_tvat(b,11)
usnmp.frombytes_tvat(b,14)
usnmp.frombytes_tvat(b,20)
usnmp.frombytes_tvat(b,23)
usnmp.frombytes_tvat(b,26)

usnmp.tobytes_tv(4, "hello world")
usnmp.frombytes_tvat(usnmp.tobytes_tv(4, b"hello world"),0)

usnmp.frombytes_tvat(usnmp.tobytes_tv(usnmp.ASN1_INT,12311),0)[1] == 12311
usnmp.frombytes_tvat(usnmp.tobytes_tv(usnmp.SNMP_GUAGE,23),0)[1] == 23
usnmp.frombytes_tvat(usnmp.tobytes_tv(usnmp.SNMP_TIMETICKS,65783634),0)[1] == 65783634
usnmp.frombytes_tvat(usnmp.tobytes_tv(usnmp.ASN1_NULL,None),0)[1] == None
usnmp.frombytes_tvat(usnmp.tobytes_tv(usnmp.ASN1_OID,"1.3.1.2.2.4324.2"),0)[1] == "1.3.1.2.2.4324.2"
usnmp.frombytes_tvat(usnmp.tobytes_tv(usnmp.SNMP_IPADDR,"172.26.235.23"),0)[1] == "172.26.235.23"

p = usnmp.SnmpPacket(b)
p.ver
p.community
p.type
p.id
Пример #38
0
try:
    try:
        import ubinascii as binascii
    except ImportError:
        import binascii
except ImportError:
    import sys
    print("SKIP")
    sys.exit()

print(binascii.unhexlify(b'0001020304050607'))
print(binascii.unhexlify(b'08090a0b0c0d0e0f'))
print(binascii.unhexlify(b'7f80ff'))
print(binascii.unhexlify(b'313233344142434461626364'))

try:
    a = binascii.unhexlify(b'0') # odd buffer length
except ValueError:
    print('ValueError')

try:
    a = binascii.unhexlify(b'gg') # digit not hex
except ValueError:
    print('ValueError')
Пример #39
0
def b32decode(s, casefold=False, map01=None):
    """Decode a Base32 encoded byte string.

    s is the byte string to decode.  Optional casefold is a flag
    specifying whether a lowercase alphabet is acceptable as input.
    For security purposes, the default is False.

    RFC 3548 allows for optional mapping of the digit 0 (zero) to the
    letter O (oh), and for optional mapping of the digit 1 (one) to
    either the letter I (eye) or letter L (el).  The optional argument
    map01 when not None, specifies which letter the digit 1 should be
    mapped to (when map01 is not None, the digit 0 is always mapped to
    the letter O).  For security purposes the default is None, so that
    0 and 1 are not allowed in the input.

    The decoded byte string is returned.  binascii.Error is raised if
    the input is incorrectly padded or if there are non-alphabet
    characters present in the input.
    """
    s = _bytes_from_decode_data(s)
    quanta, leftover = divmod(len(s), 8)
    if leftover:
        raise binascii.Error('Incorrect padding')
    # Handle section 2.4 zero and one mapping.  The flag map01 will be either
    # False, or the character to map the digit 1 (one) to.  It should be
    # either L (el) or I (eye).
    if map01 is not None:
        map01 = _bytes_from_decode_data(map01)
        assert len(map01) == 1, repr(map01)
        s = s.translate(bytes.maketrans(b'01', b'O' + map01))
    if casefold:
        s = s.upper()
    # Strip off pad characters from the right.  We need to count the pad
    # characters because this will tell us how many null bytes to remove from
    # the end of the decoded string.
    padchars = s.find(b'=')
    if padchars > 0:
        padchars = len(s) - padchars
        s = s[:-padchars]
    else:
        padchars = 0

    # Now decode the full quanta
    parts = []
    acc = 0
    shift = 35
    for c in s:
        val = _b32rev.get(c)
        if val is None:
            raise binascii.Error('Non-base32 digit found')
        acc += _b32rev[c] << shift
        shift -= 5
        if shift < 0:
            parts.append(binascii.unhexlify(bytes('%010x' % acc, "ascii")))
            acc = 0
            shift = 35
    # Process the last, partial quanta
    last = binascii.unhexlify(bytes('%010x' % acc, "ascii"))
    if padchars == 0:
        last = b''                      # No characters
    elif padchars == 1:
        last = last[:-1]
    elif padchars == 3:
        last = last[:-2]
    elif padchars == 4:
        last = last[:-3]
    elif padchars == 6:
        last = last[:-4]
    else:
        raise binascii.Error('Incorrect padding')
    parts.append(last)
    return b''.join(parts)