Python ubinascii.hexlify() Examples

The following are 30 code examples of ubinascii.hexlify(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ubinascii , or try the search function .
Example #1
Source File: simple.py    From xbee-micropython with MIT License 6 votes vote down vote up
def subscribe(self, topic, qos=0):
        assert self.cb is not None, "Subscribe callback is not set"
        pkt = bytearray(b"\x82\0\0\0")
        self.pid += 1
        struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid)
        #print(hex(len(pkt)), hexlify(pkt, ":"))
        self.sock.write(pkt)
        self._send_str(topic)
        self.sock.write(qos.to_bytes(1, "little"))
        while 1:
            op = self.wait_msg()
            if op == 0x90:
                resp = self.sock.read(4)
                #print(resp)
                assert resp[1] == pkt[2] and resp[2] == pkt[3]
                if resp[3] == 0x80:
                    raise MQTTException(resp[3])
                return

    # Wait for a single incoming MQTT message and process it.
    # Subscribed messages are delivered to a callback previously
    # set by .set_callback() method. Other (internal) MQTT
    # messages processed internally. 
Example #2
Source File: umqtt.py    From pyaiot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def subscribe(self, topic, qos=0):
        assert self.cb is not None, "Subscribe callback is not set"
        pkt = bytearray(b"\x82\0\0\0")
        self.pid += 1
        struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid)
        #print(hex(len(pkt)), hexlify(pkt, ":"))
        self.sock.write(pkt)
        self._send_str(topic)
        self.sock.write(qos.to_bytes(1))
        while 1:
            op = self.wait_msg()
            if op == 0x90:
                resp = self.sock.read(4)
                #print(resp)
                assert resp[1] == pkt[2] and resp[2] == pkt[3]
                if resp[3] == 0x80:
                    raise MQTTException(resp[3])
                return

    # Wait for a single incoming MQTT message and process it.
    # Subscribed messages are delivered to a callback previously
    # set by .set_callback() method. Other (internal) MQTT
    # messages processed internally. 
Example #3
Source File: sys_vars.py    From pysmartnode with MIT License 6 votes vote down vote up
def getDeviceDiscovery():
    from pysmartnode import config
    mf = "espressif" if platform in ("esp8266", "esp32", "esp32_LoBo") else "None"
    if platform != "linux":
        import network
        s = network.WLAN(network.STA_IF)
        mac = ',"connections": [["mac", "{!s}"]]'.format(
            ubinascii.hexlify(s.config("mac"), ":").decode())
    else:
        mac = ""
    return DISCOVERY_DEVICE_BASE.format(getDeviceID(),
                                        config.VERSION,
                                        mf,
                                        os.uname().sysname if platform != "linux" else "linux",
                                        config.DEVICE_NAME if config.DEVICE_NAME is not None else getDeviceID(),
                                        mac) 
Example #4
Source File: mqtt.py    From upython-aq-monitor with MIT License 6 votes vote down vote up
def subscribe(self, topic, qos=0):
        assert self.cb is not None, "Subscribe callback is not set"
        pkt = bytearray(b"\x82\0\0\0")
        self.pid += 1
        struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid)
        #print(hex(len(pkt)), hexlify(pkt, ":"))
        self.sock.write(pkt)
        self._send_str(topic)
        self.sock.write(qos.to_bytes(1))
        while 1:
            op = self.wait_msg()
            if op == 0x90:
                resp = self.sock.read(4)
                #print(resp)
                assert resp[1] == pkt[2] and resp[2] == pkt[3]
                if resp[3] == 0x80:
                    raise MQTTException(resp[3])
                return

    # Wait for a single incoming MQTT message and process it.
    # Subscribed messages are delivered to a callback previously
    # set by .set_callback() method. Other (internal) MQTT
    # messages processed internally. 
Example #5
Source File: hashlist.py    From ulnoiot-upy with MIT License 6 votes vote down vote up
def _hashlist(root):
    if root.endswith("/"):
        root = root[0:-1]  # strip slash
    try:
        st = os.stat(root)
    except:
        # print("noaccess",root) - does not exist, so don't print
        return
    if st[0] & 0x4000:  # stat.S_IFDIR
        print("<dir>", root)
        l = os.listdir(root)
        for f in l:
            gc.collect()
            p = root + "/" + f
            _hashlist(p)
    else:
        h = sha256()
        hf = open(root, "rb")
        while True:
            b = hf.read(40)
            if len(b) == 0: break
            h.update(b)
        print(ubinascii.hexlify(h.digest()).decode(), root)
        hf.close() 
Example #6
Source File: extract_byte_code.py    From upy-examples with MIT License 6 votes vote down vote up
def inspect(f, nbytes=16):
    import stm
    import array
    import ubinascii
    @micropython.asm_thumb
    def dummy():
        pass
    if type(f) != type(dummy):
        raise ValueError('expecting an inline-assembler function')
    baddr = bytes(array.array('O', [f]))
    addr = baddr[0] | baddr[1] << 8 | baddr[2] << 16 | baddr[3] << 24
    print('function object at: 0x%08x' % addr)
    print('number of args: %u' % stm.mem32[addr + 4])
    code_addr = stm.mem32[addr + 8]
    print('machine code at: 0x%08x' % code_addr)
    print('----------')
    print('import binascii')
    print("with open('code.bin', 'wb') as f:")
    import ubinascii
    hex_str = ubinascii.hexlify(bytearray([stm.mem8[code_addr + i] for i in range(nbytes)]))
    print("    f.write(binascii.unhexlify(%s))" % hex_str)
    print('----------') 
Example #7
Source File: simple.py    From UIFlow-Code with GNU General Public License v3.0 6 votes vote down vote up
def subscribe(self, topic, qos=0):
        assert self.cb is not None, "Subscribe callback is not set"
        self.sock.setblocking(True)
        pkt = bytearray(b"\x82\0\0\0")
        self.pid += 1
        struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid)
        #print(hex(len(pkt)), hexlify(pkt, ":"))
        self.sock.write(pkt)
        self._send_str(topic)
        self.sock.write(qos.to_bytes(1, "little"))
        # print("simple --> wait socket msg")
        while 1:
            op = self.wait_msg()
            if op == 0x90:
                resp = self.sock.read(4)
                #print(resp)
                assert resp[1] == pkt[2] and resp[2] == pkt[3]
                if resp[3] == 0x80:
                    raise MQTTException(resp[3])
                # print("simple --> wait socket finish")                
                return 
Example #8
Source File: util.py    From terkin-datalogger with GNU Affero General Public License v3.0 6 votes vote down vote up
def encode_ieee11073(value, precision=2):
    """Binary representation of float value as IEEE-11073:20601 32-bit FLOAT for
    implementing the BLE GATT "Temperature Measurement 2A1C" characteristic.

    -- https://community.hiveeyes.org/t/convenient-ble-gatts-ess-with-micropython/2413/3

    print('Adding Temperature Measurement')
    payload = bytearray([0b00000000]) + float_ieee11073(42.42)
    service.characteristic(uuid=0x2A1C, value=payload)

    :param value:
    :param precision:  (Default value = 2)

    >>> ubinascii.hexlify(encode_ieee11073(42.42))
    b'921000fe'
    """

    # FIXME: Sanity checks dearly required.
    return int(value * (10 ** precision)).to_bytes(3, 'little', True) + pack('<b', -precision) 
Example #9
Source File: wifi.py    From terkin-datalogger with GNU Affero General Public License v3.0 6 votes vote down vote up
def auth_mode_nvs_key(self, ssid):
        """Hack to get a short representation of a WiFi SSID in order to
        squeeze it into a NVRAM key with a maximum length of 15 characters.
        
        Fixme: Review this.

        :param ssid: 

        """
        import hashlib
        import ubinascii
        try:
            hashfun = hashlib.sha512
        except AttributeError:
            hashfun = hashlib.sha256
        digest = ubinascii.hexlify(hashfun(ssid).digest()).decode()
        identifier = 'wa.{}'.format(digest[15:27])
        return identifier 
Example #10
Source File: wifi.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def humanize_mac_addresses(self, mac):
        """

        :param mac: 

        """
        info = {}
        if hasattr(mac, 'sta_mac'):
            info['sta_mac'] = format_mac_address(binascii.hexlify(mac.sta_mac).decode())
        if hasattr(mac, 'ap_mac'):
            info['ap_mac'] = format_mac_address(binascii.hexlify(mac.ap_mac).decode())
        return info 
Example #11
Source File: pycom.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_device_id():
    """ """
    import machine
    from ubinascii import hexlify
    return hexlify(machine.unique_id()).decode() 
Example #12
Source File: sys_vars.py    From pysmartnode with MIT License 5 votes vote down vote up
def getDeviceID():
    if platform == "linux":
        from pysmartnode import config
        return config.DEVICE_NAME
    import machine
    return ubinascii.hexlify(machine.unique_id()).decode() 
Example #13
Source File: mfrc522.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        now = time.ticks_ms()
        if time.ticks_diff(now, self.last_access) > self.access_interval:
            retval = b'0'  # Let's assume nothing is there
            try:
                (stat, tag_type) = self.request(_REQIDL)
                if stat == _OK:  # Something is there, so ignore this if not successfully read
                    retval = None

                    (stat, raw_uid) = self.anticoll()

                    if stat == _OK:
                        retval = str(tag_type).encode() + b' ' + ubinascii.hexlify(bytes(raw_uid))

                        if self.select_tag(raw_uid) == _OK:

                            data_read = False
                            for sector in range(0, self.datasize//12): # /16/3*4
                                if (sector+1) % 4 != 0:  # every 4th sector has only management info
                                    if self.auth(_AUTHENT1A, sector+4, self.key, raw_uid) == _OK:
                                        if not data_read:
                                            retval += b' '
                                        self._read(sector + 4, into=self.card_data_buf)
                                        retval += ubinascii.hexlify(self.card_data_buf)  # TODO: remove hexlify and do binary
                                        data_read = True
                                    else:
                                        print("MFRC522: authentication error")
                                        return None  # Not successfull read
                            self.stop_crypto1()
                            # TODO: think how to avoid this busy-waiting
                            print("MFRC522: read time " + str(time.ticks_diff(time.ticks_ms(), now)))
                        else:
                            print("MFRC522: Select failed")
                        _ = self.anticoll()  # prevent reading of empty
                        self.last_access = time.ticks_ms()  # TODO: check why this is necessary
            except Exception as e:
                print('Trouble in MFRC522. Got exception:', e)
                print('Retval so far:', retval)
            return retval
        return None  # didn't read 
Example #14
Source File: mfrc522.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        now = time.ticks_ms()
        if time.ticks_diff(now, self.last_access) > self.access_interval:
            retval = b'0'  # Let's assume nothing is there
            try:
                (stat, tag_type) = self.request(_REQIDL)
                if stat == _OK:  # Something is there, so ignore this if not successfully read
                    retval = None

                    (stat, raw_uid) = self.anticoll()

                    if stat == _OK:
                        retval = str(tag_type).encode() + b' ' + ubinascii.hexlify(bytes(raw_uid))

                        if self.select_tag(raw_uid) == _OK:

                            data_read = False
                            for sector in range(0, self.datasize//12): # /16/3*4
                                if (sector+1) % 4 != 0:  # every 4th sector has only management info
                                    if self.auth(_AUTHENT1A, sector+4, self.key, raw_uid) == _OK:
                                        if not data_read:
                                            retval += b' '
                                        self._read(sector + 4, into=self.card_data_buf)
                                        retval += ubinascii.hexlify(self.card_data_buf)  # TODO: remove hexlify and do binary
                                        data_read = True
                                    else:
                                        print("MFRC522: authentication error")
                                        return None  # Not successfull read
                            self.stop_crypto1()
                            # TODO: think how to avoid this busy-waiting
                            print("MFRC522: read time " + str(time.ticks_diff(time.ticks_ms(), now)))
                        else:
                            print("MFRC522: Select failed")
                        _ = self.anticoll()  # prevent reading of empty
                        self.last_access = time.ticks_ms()  # TODO: check why this is necessary
            except Exception as e:
                print('Trouble in MFRC522. Got exception:', e)
                print('Retval so far:', retval)
            return retval
        return None  # didn't read 
Example #15
Source File: mfrc522.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        now = time.ticks_ms()
        if time.ticks_diff(now, self.last_access) > self.access_interval:
            retval = b'0'  # Let's assume nothing is there
            try:
                (stat, tag_type) = self.request(_REQIDL)
                if stat == _OK:  # Something is there, so ignore this if not successfully read
                    retval = None

                    (stat, raw_uid) = self.anticoll()

                    if stat == _OK:
                        retval = str(tag_type).encode() + b' ' + ubinascii.hexlify(bytes(raw_uid))

                        if self.select_tag(raw_uid) == _OK:

                            data_read = False
                            for sector in range(0, self.datasize//12): # /16/3*4
                                if (sector+1) % 4 != 0:  # every 4th sector has only management info
                                    if self.auth(_AUTHENT1A, sector+4, self.key, raw_uid) == _OK:
                                        if not data_read:
                                            retval += b' '
                                        self._read(sector + 4, into=self.card_data_buf)
                                        retval += ubinascii.hexlify(self.card_data_buf)  # TODO: remove hexlify and do binary
                                        data_read = True
                                    else:
                                        print("MFRC522: authentication error")
                                        return None  # Not successfull read
                            self.stop_crypto1()
                            # TODO: think how to avoid this busy-waiting
                            print("MFRC522: read time " + str(time.ticks_diff(time.ticks_ms(), now)))
                        else:
                            print("MFRC522: Select failed")
                        _ = self.anticoll()  # prevent reading of empty
                        self.last_access = time.ticks_ms()  # TODO: check why this is necessary
            except Exception as e:
                print('Trouble in MFRC522. Got exception:', e)
                print('Retval so far:', retval)
            return retval
        return None  # didn't read 
Example #16
Source File: mfrc522.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        now = time.ticks_ms()
        if time.ticks_diff(now, self.last_access) > self.access_interval:
            retval = b'0'  # Let's assume nothing is there
            try:
                (stat, tag_type) = self.request(_REQIDL)
                if stat == _OK:  # Something is there, so ignore this if not successfully read
                    retval = None

                    (stat, raw_uid) = self.anticoll()

                    if stat == _OK:
                        retval = str(tag_type).encode() + b' ' + ubinascii.hexlify(bytes(raw_uid))

                        if self.select_tag(raw_uid) == _OK:

                            data_read = False
                            for sector in range(0, self.datasize//12): # /16/3*4
                                if (sector+1) % 4 != 0:  # every 4th sector has only management info
                                    if self.auth(_AUTHENT1A, sector+4, self.key, raw_uid) == _OK:
                                        if not data_read:
                                            retval += b' '
                                        self._read(sector + 4, into=self.card_data_buf)
                                        retval += ubinascii.hexlify(self.card_data_buf)  # TODO: remove hexlify and do binary
                                        data_read = True
                                    else:
                                        print("MFRC522: authentication error")
                                        return None  # Not successfull read
                            self.stop_crypto1()
                            # TODO: think how to avoid this busy-waiting
                            print("MFRC522: read time " + str(time.ticks_diff(time.ticks_ms(), now)))
                        else:
                            print("MFRC522: Select failed")
                        _ = self.anticoll()  # prevent reading of empty
                        self.last_access = time.ticks_ms()  # TODO: check why this is necessary
            except Exception as e:
                print('Trouble in MFRC522. Got exception:', e)
                print('Retval so far:', retval)
            return retval
        return None  # didn't read 
Example #17
Source File: mfrc522.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        now = time.ticks_ms()
        if time.ticks_diff(now, self.last_access) > self.access_interval:
            retval = b'0'  # Let's assume nothing is there
            try:
                (stat, tag_type) = self.request(_REQIDL)
                if stat == _OK:  # Something is there, so ignore this if not successfully read
                    retval = None

                    (stat, raw_uid) = self.anticoll()

                    if stat == _OK:
                        retval = str(tag_type).encode() + b' ' + ubinascii.hexlify(bytes(raw_uid))

                        if self.select_tag(raw_uid) == _OK:

                            data_read = False
                            for sector in range(0, self.datasize//12): # /16/3*4
                                if (sector+1) % 4 != 0:  # every 4th sector has only management info
                                    if self.auth(_AUTHENT1A, sector+4, self.key, raw_uid) == _OK:
                                        if not data_read:
                                            retval += b' '
                                        self._read(sector + 4, into=self.card_data_buf)
                                        retval += ubinascii.hexlify(self.card_data_buf)  # TODO: remove hexlify and do binary
                                        data_read = True
                                    else:
                                        print("MFRC522: authentication error")
                                        return None  # Not successfull read
                            self.stop_crypto1()
                            # TODO: think how to avoid this busy-waiting
                            print("MFRC522: read time " + str(time.ticks_diff(time.ticks_ms(), now)))
                        else:
                            print("MFRC522: Select failed")
                        _ = self.anticoll()  # prevent reading of empty
                        self.last_access = time.ticks_ms()  # TODO: check why this is necessary
            except Exception as e:
                print('Trouble in MFRC522. Got exception:', e)
                print('Retval so far:', retval)
            return retval
        return None  # didn't read 
Example #18
Source File: util.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def from_bytes_le(thing):
        """
        Taken from Pycopy's UUID class. By Paul Sokolovsky.

        https://github.com/pfalcon/pycopy-lib/blob/master/uuid/uuid.py#L5-L20
        """
        if len(thing) != 16:
            raise ValueError('bytes arg must be 16 bytes long')
        hex = ubinascii.hexlify(bytes(reversed(thing))).decode()
        uuid = '-'.join((hex[0:8], hex[8:12], hex[12:16], hex[16:20], hex[20:32]))
        return uuid 
Example #19
Source File: inisetup.py    From microhomie with MIT License 5 votes vote down vote up
def wifi():
    import ubinascii
    ap_if = network.WLAN(network.AP_IF)
    essid = b"Microhomie-%s" % ubinascii.hexlify(ap_if.config("mac")[-3:])
    ap_if.config(essid=essid, authmode=network.AUTH_WPA_WPA2_PSK, password=b"microhomiE") 
Example #20
Source File: config_lora.py    From uPyLoRaWAN with Apache License 2.0 5 votes vote down vote up
def get_nodename():
    uuid = ubinascii.hexlify(machine.unique_id()).decode()
    node_name = "ESP_" + uuid
    return node_name 
Example #21
Source File: simple.py    From xbee-micropython with MIT License 5 votes vote down vote up
def publish(self, topic, msg, retain=False, qos=0):
        pkt = bytearray(b"\x30\0\0\0")
        pkt[0] |= qos << 1 | retain
        sz = 2 + len(topic) + len(msg)
        if qos > 0:
            sz += 2
        assert sz < 2097152
        i = 1
        while sz > 0x7f:
            pkt[i] = (sz & 0x7f) | 0x80
            sz >>= 7
            i += 1
        pkt[i] = sz
        #print(hex(len(pkt)), hexlify(pkt, ":"))
        self.sock.write(pkt, i + 1)
        self._send_str(topic)
        if qos > 0:
            self.pid += 1
            pid = self.pid
            struct.pack_into("!H", pkt, 0, pid)
            self.sock.write(pkt, 2)
        self.sock.write(msg)
        if qos == 1:
            while 1:
                op = self.wait_msg()
                if op == 0x40:
                    sz = self.sock.read(1)
                    assert sz == b"\x02"
                    rcv_pid = self.sock.read(2)
                    rcv_pid = rcv_pid[0] << 8 | rcv_pid[1]
                    if pid == rcv_pid:
                        return
        elif qos == 2:
            assert 0 
Example #22
Source File: umqtt.py    From pyaiot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def publish(self, topic, msg, retain=False, qos=0):
        pkt = bytearray(b"\x30\0\0\0")
        pkt[0] |= qos << 1 | retain
        sz = 2 + len(topic) + len(msg)
        if qos > 0:
            sz += 2
        assert sz < 2097152
        i = 1
        while sz > 0x7f:
            pkt[i] = (sz & 0x7f) | 0x80
            sz >>= 7
            i += 1
        pkt[i] = sz
        #print(hex(len(pkt)), hexlify(pkt, ":"))
        self.sock.write(pkt, i + 1)
        self._send_str(topic)
        if qos > 0:
            self.pid += 1
            pid = self.pid
            struct.pack_into("!H", pkt, 0, pid)
            self.sock.write(pkt, 2)
        self.sock.write(msg)
        if qos == 1:
            while 1:
                op = self.wait_msg()
                if op == 0x40:
                    sz = self.sock.read(1)
                    assert sz == b"\x02"
                    rcv_pid = self.sock.read(2)
                    rcv_pid = rcv_pid[0] << 8 | rcv_pid[1]
                    if pid == rcv_pid:
                        return
        elif qos == 2:
            assert 0 
Example #23
Source File: utils.py    From microhomie with MIT License 5 votes vote down vote up
def get_unique_id():
    if LINUX is False:
        return hexlify(unique_id()).decode()
    else:
        raise NotImplementedError(
            "Linux doesn't have a unique id. Provide the DEVICE_ID option in your settings.py."
        ) 
Example #24
Source File: utils.py    From microhomie with MIT License 5 votes vote down vote up
def get_local_mac():
    try:
        return hexlify(WLAN(0).config("mac"), ":")
    except NameError:
        return b"00:00:00:00:00:00" 
Example #25
Source File: util.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_device_id():
    """ 
    MAC address of device if supported.
    """
    import machine
    from ubinascii import hexlify
    return hexlify(machine.unique_id()).decode() 
Example #26
Source File: mqtt_as.py    From microhomie with MIT License 5 votes vote down vote up
def __init__(self, client_id=None,
                 server=None,
                 port=0,
                 user='',
                 password='',
                 keepalive=60,
                 ping_interval=0,
                 ssl=False,
                 ssl_params={},
                 response_time=10,
                 clean_init=True,
                 clean=True,
                 max_repubs=4,
                 will=None,
                 subs_cb=lambda *_: None,
                 wifi_coro=None,
                 connect_coro=None,
                 ssid=None,
                 wifi_pw=None):
        client_id = client_id or hexlify(unique_id())
        wifi_coro = wifi_coro or eliza
        connect_coro = connect_coro or eliza
        super().__init__(client_id, server, port, user, password, keepalive, ping_interval,
                         ssl, ssl_params, response_time, clean_init, clean, max_repubs, will,
                         subs_cb, wifi_coro, connect_coro, ssid, wifi_pw)
        self._isconnected = False  # Current connection state
        keepalive = 1000 * self._keepalive  # ms
        self._ping_interval = keepalive // 4 if keepalive else 20000
        p_i = self.ping_interval * 1000  # Can specify shorter e.g. for subscribe-only
        if p_i and p_i < self._ping_interval:
            self._ping_interval = p_i
        self._in_connect = False
        self._has_connected = False  # Define 'Clean Session' value to use.
        if ESP8266:
            import esp
            esp.sleep_type(0)  # Improve connection integrity at cost of power consumption. 
Example #27
Source File: umqtt.py    From pyaiot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect(self, clean_session=True):
        self.sock = socket.socket()
        self.sock.connect(self.addr)
        if self.ssl:
            import ussl
            self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
        msg = bytearray(b"\x10\0\0\x04MQTT\x04\x02\0\0")
        msg[1] = 10 + 2 + len(self.client_id)
        msg[9] = clean_session << 1
        if self.user is not None:
            msg[1] += 2 + len(self.user) + 2 + len(self.pswd)
            msg[9] |= 0xC0
        if self.keepalive:
            assert self.keepalive < 65536
            msg[10] |= self.keepalive >> 8
            msg[11] |= self.keepalive & 0x00FF
        if self.lw_topic:
            msg[1] += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
            msg[9] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
            msg[9] |= self.lw_retain << 5
        self.sock.write(msg)
        #print(hex(len(msg)), hexlify(msg, ":"))
        self._send_str(self.client_id)
        if self.lw_topic:
            self._send_str(self.lw_topic)
            self._send_str(self.lw_msg)
        if self.user is not None:
            self._send_str(self.user)
            self._send_str(self.pswd)
        resp = self.sock.read(4)
        assert resp[0] == 0x20 and resp[1] == 0x02
        if resp[3] != 0:
            raise MQTTException(resp[3])
        return resp[2] & 1 
Example #28
Source File: files.py    From ampy with MIT License 5 votes vote down vote up
def get(self, filename):
        """Retrieve the contents of the specified file and return its contents
        as a byte string.
        """
        # Open the file and read it a few bytes at a time and print out the
        # raw bytes.  Be careful not to overload the UART buffer so only write
        # a few bytes at a time, and don't use print since it adds newlines and
        # expects string data.
        command = """
            import sys
            import ubinascii
            with open('{0}', 'rb') as infile:
                while True:
                    result = infile.read({1})
                    if result == b'':
                        break
                    len = sys.stdout.write(ubinascii.hexlify(result))
        """.format(
            filename, BUFFER_SIZE
        )
        self._pyboard.enter_raw_repl()
        try:
            out = self._pyboard.exec_(textwrap.dedent(command))
        except PyboardError as ex:
            # Check if this is an OSError #2, i.e. file doesn't exist and
            # rethrow it as something more descriptive.
            try:
                if ex.args[2].decode("utf-8").find("OSError: [Errno 2] ENOENT") != -1:
                    raise RuntimeError("No such file: {0}".format(filename))
                else:
                    raise ex
            except UnicodeDecodeError:
                raise ex
        self._pyboard.exit_raw_repl()
        return binascii.unhexlify(out) 
Example #29
Source File: oled_test.py    From SX127x_driver_for_MicroPython_on_ESP8266 with GNU General Public License v3.0 5 votes vote down vote up
def get_eui():
    id = ubinascii.hexlify(unique_id()).decode()
    return mac2eui(id) 
Example #30
Source File: mqtt.py    From micropython-mqtt with MIT License 5 votes vote down vote up
def __init__(self, channel, config):
        self.channel = channel
        self.subscriptions = {}
        # Config defaults:
        # 4 repubs, delay of 10 secs between (response_time).
        # Initially clean session.
        config['subs_cb'] = self.subs_cb
        config['wifi_coro'] = self.wifi_han
        config['connect_coro'] = self.conn_han
        config['client_id'] = ubinascii.hexlify(unique_id())
        super().__init__(config)

    # Get NTP time or 0 on any error.