Example #1
0
class SectionHeader(namedtuple('SectionHeader', ['offset', 'size', 'crc' ])):
    @classmethod
    def read(cls, f):
        # read only next one; ftell has to be on first byte already
        fmt = '<QQL'

        sz = calcsize(fmt)
        bits = f.read(sz)
        if not bits:
            return

        rv = cls(*unpack(fmt, bits))
        rv.bits = bits

        return rv

    @classmethod
    def read_iter(cls, f, expect_crc=None):
        # read only next one; ftell has to be on first byte already
        rv = cls.read(f)

        if expect_crc != None:
            assert rv           # read past end
            assert masked_crc(rv.bits) == expect_crc

        section = f.read(rv.offset)
        hdr = f.read(rv.size)

        yield rv, hdr, section

    def write(self):
        return pack('<QQL', self.offset, self.size, self.crc)

    def actual_crc(self):
        return masked_crc(self.bits)
Example #2
0
 def test_mapper_multi_interrupts(self):
     TiTuple = namedtuple('TiTuple', ('tim', 'id'))
     for info in [TiTuple(pyb.Timer(tim_id, freq=tim_id + 1), tim_id) for tim_id in (1, 2, 4)]:
         @cmemgr.map_to_thread(info.tim.callback, info.id)
         def led_blink(led_id):
             with Indicator(led_id):
                 pyb.delay(30)
Example #3
0
 def consume(xfd, tname, fmt, names):
     # Parses the struct defined by `fmt` from `data`, stores the parsed fields
     # into a named tuple using `names`. Returns the named tuple.
     size = struct.calcsize(fmt)
     here = xfd.read(size)
     ty = namedtuple(tname, names.split())
     values = struct.unpack(fmt, here)
     return ty(*values)
Example #4
0
 def parse_control_packet(bytes):
     ControlPacket = collections.namedtuple(
         'ControlPacket', 'sequence payloadLength payload')
     sequence, payloadLength = struct.unpack('HB', bytes)
     payload = bytes[3:3 + payloadLength]
     return ControlPacket(sequence=sequence,
                          payloadLength=payloadLength,
                          payload=payload)
Example #5
0
 def init(cls, fail_silently=False):
     cls.__fields__ = list(cls.__schema__.keys())
     cls.Row = namedtuple(cls.__table__, cls.__fields__)
     for d in (cls.__db__.name, "%s/%s" % (cls.__db__.name, cls.__table__)):
         try:
             uos.mkdir(d)
         except OSError as e:
             if fail_silently:
                 print(e)
Example #6
0
class TokenInfo(
        namedtuple("TokenInfo", ("type", "string", "start", "end", "line"))):
    def __str__(self):
        return "TokenInfo(type=%d (%s), string=%r, line=%r)" % (
            self.type,
            tok_name[self.type],
            self.string,
            self.line,
        )
Example #7
0
    def parse_heartbeat_packet(bytes):
        HeartbeatPacket = collections.namedtuple(
            'HeartbeatPacket', 'coordLat coordLon neighbours')
        Neighbour = collections.namedtuple('Neighbour', 'nodeId snr received')
        coordLat, coordLon, noNeighbours = struct.unpack('ffB', bytes)

        # Parse list of neighbours
        neighbours = []
        for i in range(noNeighbours):
            # 4 + 4 + 1
            pos = 9 + i * 2
            neighbourId, infoByte = struct.unpack_from('BB', bytes, pos)
            snr, received = LoRaSwarmProtocol.extract_neighbour_info(infoByte)
            neighbours.append(
                Neighbour(nodeId=neighbourId, snr=snr, received=received))
        return HeartbeatPacket(coordLat=coordLat,
                               coordLon=coordLon,
                               neighbours=neighbours)
Example #8
0
 def __init__(self):
     # Initialize wlan
     self.wlan = WLAN(mode=WLAN.STA)
     # Internal (WLAN.INT_ANT) or external (WLAN.EXT_ANT) antenna
     self.wlan.antenna(WLAN.INT_ANT)
     self.nets = []
     # Define the named tuple that contains the WiFi access point information
     self.net = namedtuple('net',
                           ('ssid', 'bssid', 'sec', 'channel', 'rssi'))
class Publisher:
    """
    SSE-handler.
    Micropython version of server-sent-events library:

        https://github.com/boppreh/server-sent-events

    """

    Subscriber = namedtuple('Subscriber', ['ID', 'queue'])

    def __init__(self):
        """
        Creates a new publisher with an empty list of subscribers.
        """
        self.subscribers_by_channel = dict()

    def get_subscribers(self, channel='default channel'):
        subscribers_list = self.subscribers_by_channel.setdefault(channel, [])
        return subscribers_list

    def subscribe(self, channel='default channel'):

        q = Queue(15)
        subscriber = self.Subscriber(id(q), q)  # namedtuple

        subscribers_list = self.get_subscribers(channel)
        if len(subscribers_list) < max_clients:
            subscribers_list.append(subscriber)
            return self._make_generator(subscriber)
        else:
            return (None, None)

    def unsubscribe(self, subscriber_id, channel='default channel'):
        """ Finds subscriber by his ID end removes him from subscribers
        lists """
        subscribers_list = self.get_subscribers(channel)
        subscriber_to_remove = \
        list(filter(lambda x: x.ID == subscriber_id, subscribers_list))[0]
        subscribers_list.remove(subscriber_to_remove)

    def _make_generator(self, subscriber):
        """:returns subscriber.ID to identification and
        AsyncIterable(subscriber.queue) to write into response"""
        return (subscriber.ID, AsyncIterable(subscriber.queue))

    async def _publish_single(self, data, subscriber):
        str_data = str(data)
        # for line in str_data.split('\n'):
        #     subscriber.queue.put_nowait('{}\n'.format(line))
        for line in str_data.split('\n'):
            await subscriber.queue.put('{}\n'.format(line))

    async def publish(self, data, channel='default channel'):
        for subscriber in self.get_subscribers(channel):
            await self._publish_single(data, subscriber)
Example #10
0
    def parse_ext_application_packet(p):
        ExtApplicationPacket = collections.namedtuple(
            'ExtApplicationPacket', 'neighbours applicationPacket')
        Neighbour = collections.namedtuple('Neighbour', 'nodeId snr received')

        noNeighbours = p[0]
        # Parse list of neighbours
        neighbours = []
        for i in range(noNeighbours):
            pos = 1 + i * 2
            neighbourId, infoByte = struct.unpack_from('BB', p, pos)
            snr, received = LoRaSwarmProtocol.extract_neighbour_info(infoByte)
            neighbours.append(
                Neighbour(nodeId=neighbourId, snr=snr, received=received))

        appPacket = LoRaSwarmProtocol.parse_application_packet(
            p[1 + 2 * noNeighbours:])
        return ExtApplicationPacket(neighbours=neighbours,
                                    applicationPacket=appPacket)
Example #11
0
def namedtuple(name, fields):
    _T = ucollections.namedtuple(name, fields)

    @classmethod
    def _make(cls, seq):
        return cls(*seq)

    t = type(name, (_T,), {"_make": _make})

    return t
Example #12
0
class ExtType(namedtuple('ExtType', 'code data')):
    """ExtType represents ext type in msgpack."""
    def __new__(cls, code, data):
        if not isinstance(code, int):
            raise TypeError("code must be int")
        if not isinstance(data, bytes):
            raise TypeError("data must be bytes")
        if not 0 <= code <= 127:
            raise ValueError("code must be 0~127")
        return super(ExtType, cls).__new__(cls, code, data)
Example #13
0
    def _parse_args(self, args, return_unknown):
        # add optional args with defaults
        arg_dest = []
        arg_vals = []
        for opt in self.opt:
            arg_dest.append(opt.dest)
            arg_vals.append(opt.default)

        # deal with unknown arguments, if needed
        unknown = []

        def consume_unknown():
            while args and not args[0].startswith("-"):
                unknown.append(args.pop(0))

        # parse all args
        parsed_pos = False
        while args or not parsed_pos:
            if args and args[0].startswith(
                    "-") and args[0] != "-" and args[0] != "--":
                # optional arg
                a = args.pop(0)
                if a in ("-h", "--help"):
                    self.usage(True)
                    sys.exit(0)
                found = False
                for i, opt in enumerate(self.opt):
                    if a in opt.names:
                        arg_vals[i] = opt.parse(a, args)
                        found = True
                        break
                if not found:
                    if return_unknown:
                        unknown.append(a)
                        consume_unknown()
                    else:
                        raise _ArgError("unknown option %s" % a)
            else:
                # positional arg
                if parsed_pos:
                    if return_unknown:
                        unknown = unknown + args
                        break
                    else:
                        raise _ArgError("extra args: %s" % " ".join(args))
                for pos in self.pos:
                    arg_dest.append(pos.dest)
                    arg_vals.append(pos.parse(pos.names[0], args))
                parsed_pos = True
                if return_unknown:
                    consume_unknown()

        # build and return named tuple with arg values
        values = namedtuple("args", arg_dest)(*arg_vals)
        return (values, unknown) if return_unknown else values
Example #14
0
 def rows(cls):
     cls.Row = namedtuple(cls.__table__, cls.__fields__)
     try:
         for dirent in uos.ilistdir("%s/%s" % (cls.__db__.name, cls.__table__)):
             fname = dirent[0]
             if fname[0] == ".":
                 continue
             with open(cls.fname(fname)) as f:
                 yield cls.json2row(ujson.loads(f.read()))
     except OSError:
         return None
Example #15
0
    def _parse_args(self, args, return_unknown):
        # add optional args with defaults
        arg_dest = []
        arg_vals = []
        for opt in self.opt:
            arg_dest.append(opt.dest)
            arg_vals.append(opt.default)

        # deal with unknown arguments, if needed
        unknown = []
        def consume_unknown():
            while args and not args[0].startswith("-"):
                unknown.append(args.pop(0))

        # parse all args
        parsed_pos = False
        while args or not parsed_pos:
            if args and args[0].startswith("-") and args[0] != "-" and args[0] != "--":
                # optional arg
                a = args.pop(0)
                if a in ("-h", "--help"):
                    self.usage(True)
                    sys.exit(0)
                found = False
                for i, opt in enumerate(self.opt):
                    if a in opt.names:
                        arg_vals[i] = opt.parse(a, args)
                        found = True
                        break
                if not found:
                    if return_unknown:
                        unknown.append(a)
                        consume_unknown()
                    else:
                        raise _ArgError("unknown option %s" % a)
            else:
                # positional arg
                if parsed_pos:
                    if return_unknown:
                        unknown = unknown + args
                        break
                    else:
                        raise _ArgError("extra args: %s" % " ".join(args))
                for pos in self.pos:
                    arg_dest.append(pos.dest)
                    arg_vals.append(pos.parse(pos.names[0], args))
                parsed_pos = True
                if return_unknown:
                    consume_unknown()

        # build and return named tuple with arg values
        values = namedtuple("args", arg_dest)(*arg_vals)
        return (values, unknown) if return_unknown else values
Example #16
0
 def netDiff(self, nets1=[], nets2=[]):
     matchCnt = 0
     # Define the named tuple that contains the result of the matching
     diffRes = namedtuple('diffRes', ('net1', 'net2', 'match', 'noMatch'))
     for net1 in nets1:
         for net2 in nets2:
             if net1.bssid == net2.bssid:
                 matchCnt = matchCnt + 1
     noMatchCnt = len(nets1) + len(nets2) - (2 * matchCnt)
     return diffRes(net1=len(nets1),
                    net2=len(nets2),
                    match=matchCnt,
                    noMatch=noMatchCnt)
Example #17
0
    def parse_packet_header(p):
        PacketHeader = collections.namedtuple(
            'PacketHeader', 'nodeId status1 status2 packetType')
        protocolId, nodeId, status1, status2, packetType = struct.unpack(
            'BBBBB', p)
        if protocolId != LoRaSwarmProtocol.PROTOCOL_ID:
            raise ValueError('Packet malformed')

        packetContent = p[5:]
        return (PacketHeader(nodeId=nodeId,
                             status1=status1,
                             status2=status2,
                             packetType=packetType), packetContent)
Example #18
0
    def make_bitmask(name, defs):
        '''
            Take a list of bit widths and field names, and convert into a useful class.
        '''
        custom_t = namedtuple(name, [n for w, n in defs])

        assert sum(w for w, n in defs) == 16

        class wrapper:
            def __init__(self, *a, **kws):
                if not a:
                    a = [0] * len(defs)
                for idx, (_, nm) in enumerate(defs):
                    if nm in kws:
                        a[idx] = kws[nm]
                self.x = custom_t(*a)

            @classmethod
            def unpack(cls, ss):
                v = ustruct.unpack('<H', ss)[0]
                pos = 0
                rv = []
                for w, n in defs:
                    rv.append((v >> pos) & ((1 << w) - 1))
                    pos += w
                assert pos == 16
                return cls(*rv)

            def pack(self):
                ss = 0
                pos = 0
                for w, n in defs:
                    v = getattr(self.x, n)
                    assert v < (1 << w), n + " is too big"
                    ss |= (v << pos)
                    pos += w
                assert pos == 16
                return ustruct.pack("<H", ss)

            def as_int(self):
                return ustruct.unpack("<H", self.pack())[0]

            def as_hex(self):
                return hex(self.as_int())

            def __repr__(self):
                return repr(self.x) + ('=0x%04x' % self.as_int())

        return wrapper
Example #19
0
 def parse_application_packet(bytes):
     # We assume the protocol header has already been stripped
     ApplicationPacket = collections.namedtuple(
         'ApplicationPacket',
         'sender sequence forwardHorizon forwardCount payloadLength payload'
     )
     senderId, seq, forwardingByte, payloadLength = struct.unpack(
         'BBBB', bytes)
     forwardHorizon, forwardCount = LoRaSwarmProtocol.decompose_forwarding_byte(
         forwardingByte)
     payload = bytes[4:4 + payloadLength]
     return ApplicationPacket(sender=senderId,
                              sequence=seq,
                              forwardHorizon=forwardHorizon,
                              forwardCount=forwardCount,
                              payloadLength=payloadLength,
                              payload=payload)
Example #20
0
    def __init__(self,
                 name,
                 address,
                 fields=None,
                 bit_width=8,
                 read_only=False,
                 volatile=True):
        self.name = name
        self.address = address
        self.bit_width = bit_width
        self.read_only = read_only
        self.volatile = volatile
        self.is_read = False
        self.fields = {}

        for field in fields:
            self.fields[field.name] = field

        self.namedtuple = namedtuple(self.name, sorted(self.fields))
Example #21
0
    def test_heartbeat():
        header_bytes = LoRaSwarmProtocol.get_header_byte(255, 0x00, 0x00)

        # test neighbour list
        Neighbour = collections.namedtuple('Neighbour',
                                           'ID snr received neighbours')

        neighbour_list = []
        neighbour_list.append(
            Neighbour(ID=0xFA, snr=-14, received=9, neighbours=[]))
        neighbour_list.append(
            Neighbour(ID=0xFB, snr=4, received=0, neighbours=[]))

        heartbeat_packet_bytes = LoRaSwarmProtocol.get_heartbeat_packet(
            header_bytes, 3.2222, 3.4033, neighbour_list)
        # Try and parse the bytes
        header, content = LoRaSwarmProtocol.parse_packet_header(
            heartbeat_packet_bytes)
        heartbeatPacket = LoRaSwarmProtocol.parse_heartbeat_packet(content)
Example #22
0
    def test_multi_spin_mutex(self):
        TProp = namedtuple('TProp', ('mutex', 'led', 'id'))
        props = [
            TProp(syncpri.SpinMutex(), pyb.LED(led_id), led_id)
            for led_id in (1, 2, 4)
        ]

        @infinite_loop_thread
        def led_select():
            for prop in props:
                others = [p for p in props if p is not prop]
                [other.mutex.acquire() or other.led.off() for other in others]
                pyb.delay(500)
                [other.mutex.release() for other in others]

        @infinite_loop_thread_for(*props)
        def led_blink(prop):
            with prop.mutex:
                prop.led.toggle()
            pyb.delay(prop.id * 25)
Example #23
0
    def extract_value(self):
        reading = namedtuple('reading', 'temperature humidity')
        try:
            x = ubinascii.hexlify(
                sht21.conn.services()[3].characteristics()[0].read()).decode(
                )  # read value and convert to hexadecimals and strings

            #extraction temperature values
            tem = str(
                ustruct.unpack("i", ubinascii.unhexlify(x[:4] + '0000'))[0])
            tem = tem[:2] + '.' + tem[2:]
            print("The ambient temperature is: " + tem)

            # extract humidity values
            hum = str(
                ustruct.unpack("i", ubinascii.unhexlify(x[4:] + '0000'))[0])
            hum = hum[:2] + '.' + hum[2:]
            print("The ambient humidity is: " + hum)
            return reading(tem, hum)

        except:
            print("No connection established ...")
Example #24
0
    def __init__(self, config_file, player_name=None):
        """
        Initialize the IR events handler from the command line arguments.
        """
        self.sock_queries = None
        self.sock_events = None
        self.player_id = None
        self.power_regex = None
        self.volume_regex = None

        # Volume handling. Will be updated by querying the server.
        self.previous_volume = 100

        # Some primitive configuration file parsing.
        try:
            config = ujson.load(uio.open(config_file))
        except OSError:
            print('Error loading configuration file "{}".'.format(config_file))
            raise

        # Set player name.
        self.player_name = config.get('player_name')
        if player_name is not None:
            self.player_name = player_name
        if self.player_name is None:
            raise ValueError('No player name.')

        # Server settings.
        Server = namedtuple('Server', ('host', 'port', 'restart_delay'))
        self.server = Server(config['server']['host'],
                             config['server']['port'],
                             config['server']['restart_delay'])

        # Default settings.
        self.default_script = config['default_script']

        # Event commands.
        self.events = config['events']
Example #25
0
    def _parse_args(self, args):
        # add optional args with defaults
        arg_dest = []
        arg_vals = []
        for opt in self.opt:
            arg_dest.append(opt.dest)
            arg_vals.append(opt.default)

        # parse all args
        parsed_pos = False
        while args or not parsed_pos:
            if args and args[0].startswith(
                    "-") and args[0] != "-" and args[0] != "--":
                # optional arg
                a = args.pop(0)
                if a in ("-h", "--help"):
                    self.usage(True)
                    sys.exit(0)
                found = False
                for i, opt in enumerate(self.opt):
                    if a in opt.names:
                        arg_vals[i] = opt.parse(a, args)
                        found = True
                        break
                if not found:
                    raise _ArgError("unknown option %s" % a)
            else:
                # positional arg
                if parsed_pos:
                    raise _ArgError("extra args: %s" % " ".join(args))
                for pos in self.pos:
                    arg_dest.append(pos.dest)
                    arg_vals.append(pos.parse(pos.names[0], args))
                parsed_pos = True

        # build and return named tuple with arg values
        return namedtuple("args", arg_dest)(*arg_vals)
Example #26
0
    def _parse_args(self, args):
        # add optional args with defaults
        arg_dest = []
        arg_vals = []
        for opt in self.opt:
            arg_dest.append(opt.dest)
            arg_vals.append(opt.default)

        # parse all args
        parsed_pos = False
        while args or not parsed_pos:
            if args and args[0].startswith("-") and args[0] != "-" and args[0] != "--":
                # optional arg
                a = args.pop(0)
                if a in ("-h", "--help"):
                    self.usage(True)
                    sys.exit(0)
                found = False
                for i, opt in enumerate(self.opt):
                    if a in opt.names:
                        arg_vals[i] = opt.parse(a, args)
                        found = True
                        break
                if not found:
                    raise _ArgError("unknown option %s" % a)
            else:
                # positional arg
                if parsed_pos:
                    raise _ArgError("extra args: %s" % " ".join(args))
                for pos in self.pos:
                    arg_dest.append(pos.dest)
                    arg_vals.append(pos.parse(pos.names[0], args))
                parsed_pos = True

        # build and return named tuple with arg values
        return namedtuple("args", arg_dest)(*arg_vals)
import bench
from ucollections import namedtuple

T = namedtuple("Tup", ["foo1", "foo2", "foo3", "foo4", "num"])


def test(num):
    t = T(0, 0, 0, 0, 20000000)
    i = 0
    while i < t.num:
        i += 1


bench.run(test)
Example #28
0
import ucollections
import utime

DateTimeTuple = ucollections.namedtuple("DateTimeTuple", [
    "year", "month", "day", "weekday", "hour", "minute", "second",
    "millisecond"
])


def datetime_tuple(year=None,
                   month=None,
                   day=None,
                   weekday=None,
                   hour=None,
                   minute=None,
                   second=None,
                   millisecond=None):
    return DateTimeTuple(year, month, day, weekday, hour, minute, second,
                         millisecond)


def _bcd2bin(value):
    return (value or 0) - 6 * ((value or 0) >> 4)


def _bin2bcd(value):
    return (value or 0) + 6 * ((value or 0) // 10)


def tuple2seconds(datetime):
    return utime.mktime(
Example #29
0
    if "Sec-WebSocket-Key" in opts \
            and "Upgrade" in opts \
                and opts["Upgrade"].lower() == "websocket" \
            and "Connection" in opts \
                and opts["Connection"].lower() == "upgrade" \
            and "Sec-WebSocket-Version" in opts \
                and opts["Sec-WebSocket-Version"] == "13" \
            and "Origin" in opts \
            and "Host" in opts \
            and request.ver.major >= 1 \
                and request.ver.minor >= 1:
        return True
    return False


Request = namedtuple("Request", ("method", "uri", "ver", "options", "data"))
HttpVer = namedtuple("HttpVer", ("major", "minor"))

def request(req, options, data=None):
    # method,path,ver = str(req.strip(), "utf-8").split(" ")
    method,path,ver = req.strip().split(b" ")
    return Request(
        method,
        uri(path),
        HttpVer(*map(int, ver.split(b"/")[1].split(b"."))),
        options,
        data
    )


# browser does not send uri fragments to server
Example #30
0
try:
    try:
        from ucollections import namedtuple
    except ImportError:
        from collections import namedtuple
except ImportError:
    print("SKIP")
    raise SystemExit

T = namedtuple("Tup", ["foo", "bar"])
# CPython prints fully qualified name, what we don't bother to do so far
#print(T)
for t in T(1, 2), T(bar=1, foo=2):
    print(t)
    print(t[0], t[1])
    print(t.foo, t.bar)

    print(len(t))
    print(bool(t))
    print(t + t)
    print(t * 3)

    print([f for f in t])

    print(isinstance(t, tuple))

# Create using positional and keyword args
print(T(3, bar=4))

try:
    t[0] = 200
Example #31
0
# Micropython doesn't support abc as described here https://realpython.com/python-interface/
# My primitive ABC.
from ucollections import namedtuple
RelayStatusTuple = namedtuple("RelayStatus",
                              ("off_to_on", "on_to_off", "current_status"))


class ControlStrategyInterface:
    def apply_strategy(self, value: float) -> RelayStatusTuple:
        """
        Turn on/off relay based on input value.
        :param value:
        :return:
        """
        pass
Example #32
0
# microbit-module: [email protected]
from ucollections import namedtuple

NesController = namedtuple(
    "NesController",
    ("a", "b", "select", "start", "up", "down", "left", "right"))


def read_nes_controller(latch, clock, data):
    tempData = 0x00

    if data.read_digital() == 0:
        return NesController(*([False] * 8))

    latch.write_digital(1)
    latch.write_digital(0)
    for button in range(0, 8):
        if (data.read_digital() == 0):
            tempData = tempData | (1 << button)
        clock.write_digital(1)
        clock.write_digital(0)

    return NesController(bool(tempData & (1 << 0)), bool(tempData & (1 << 1)),
                         bool(tempData & (1 << 2)), bool(tempData & (1 << 3)),
                         bool(tempData & (1 << 4)), bool(tempData & (1 << 5)),
                         bool(tempData & (1 << 6)), bool(tempData & (1 << 7)))
Example #33
0
import ffilib
import uctypes
import ustruct

from ucollections import namedtuple


libc = ffilib.libc()

getpwnam_ = libc.func("P", "getpwnam", "s")


struct_passwd = namedtuple("struct_passwd",
    ["pw_name", "pw_passwd", "pw_uid", "pw_gid", "pw_gecos", "pw_dir", "pw_shell"])


def getpwnam(user):
    passwd = getpwnam_(user)
    if not passwd:
        raise KeyError("getpwnam(): name not found: {}".format(user))
    passwd_fmt = "SSIISSS"
    passwd = uctypes.bytes_at(passwd, ustruct.calcsize(passwd_fmt))
    passwd = ustruct.unpack(passwd_fmt, passwd)
    return struct_passwd(*passwd)
Example #34
0
except:
    from binascii import b2a_base64

try:
    from ucollections import namedtuple
except:
    from collections import namedtuple 

def bytes_to_int(b): #big-endian
    i = 0
    for b8 in b:
        i <<= 8
        i += b8
    return i

Frame = namedtuple("Frame", ("final", "opcode", "msg"))

OP_CONT = 0x0 # continuation frame
OP_TEXT = 0x1 # text frame
OP_BIN = 0x2 # binary frame
OP_CLOSE = 0x8 # close connection
OP_PING = 0x9 # ping frame
OP_PONG = 0xa # pong frame


class WebSocketError(Exception):
    pass


class WebSocket:
Example #35
0
try: # micropython
    from ucollections import namedtuple
except: # cpython
    from collections import namedtuple

Url = namedtuple("Url", ("scheme", "host", "port", "path", "file", "query"))

# urlparse derived from
# https://github.com/lucien2k/wipy-urllib/blob/master/urllib.py
# (c) Alex Cowan <*****@*****.**>

# scheme:[//host[:port]][/]path[/filename][?query]
def urlparse(url):
    scheme,url = url.split("://") if url.count("://") else ("",url)
    host = url.split("/")[0]
    host,port = host.split(":") if host.count(":") else (host,"")
    path,query = "/",""
    if host != url:
        path = path.join(url.split("/")[1:])
        if path.count("?"):
            if path.count("?") > 1:
                raise Exception("malformed url, too many ?")
            path, query = path.split("?")
    if not path.count("/"):
        path,file = "", path
    elif path.rfind(".") > path.rfind("/"):
        path,file = path[:path.rfind("/")], path[path.rfind("/")+1:]
    else:
        file = ""
        if path[-1] == "/":
            path = path[:-1]
Example #36
0
class vl53l0x():

        ADDRESS_DEFAULT                             = 0x29
        SYSRANGE_START                              = 0x00

        SYSTEM_THRESH_HIGH                          = 0x0C
        SYSTEM_THRESH_LOW                           = 0x0E

        SYSTEM_SEQUENCE_CONFIG                      = 0x01
        SYSTEM_RANGE_CONFIG                         = 0x09
        SYSTEM_INTERMEASUREMENT_PERIOD              = 0x04

        SYSTEM_INTERRUPT_CONFIG_GPIO                = 0x0A

        GPIO_HV_MUX_ACTIVE_HIGH                     = 0x84

        SYSTEM_INTERRUPT_CLEAR                      = 0x0B

        RESULT_INTERRUPT_STATUS                     = 0x13
        RESULT_RANGE_STATUS                         = 0x14

        RESULT_CORE_AMBIENT_WINDOW_EVENTS_RTN       = 0xBC
        RESULT_CORE_RANGING_TOTAL_EVENTS_RTN        = 0xC0
        RESULT_CORE_AMBIENT_WINDOW_EVENTS_REF       = 0xD0
        RESULT_CORE_RANGING_TOTAL_EVENTS_REF        = 0xD4
        RESULT_PEAK_SIGNAL_RATE_REF                 = 0xB6

        ALGO_PART_TO_PART_RANGE_OFFSET_MM           = 0x28

        I2C_SLAVE_DEVICE_ADDRESS                    = 0x8A

        MSRC_CONFIG_CONTROL                         = 0x60

        PRE_RANGE_CONFIG_MIN_SNR                    = 0x27
        PRE_RANGE_CONFIG_VALID_PHASE_LOW            = 0x56
        PRE_RANGE_CONFIG_VALID_PHASE_HIGH           = 0x57
        PRE_RANGE_MIN_COUNT_RATE_RTN_LIMIT          = 0x64

        FINAL_RANGE_CONFIG_MIN_SNR                  = 0x67
        FINAL_RANGE_CONFIG_VALID_PHASE_LOW          = 0x47
        FINAL_RANGE_CONFIG_VALID_PHASE_HIGH         = 0x48
        FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT = 0x44

        PRE_RANGE_CONFIG_SIGMA_THRESH_HI            = 0x61
        PRE_RANGE_CONFIG_SIGMA_THRESH_LO            = 0x62

        PRE_RANGE_CONFIG_VCSEL_PERIOD               = 0x50
        PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI          = 0x51
        PRE_RANGE_CONFIG_TIMEOUT_MACROP_LO          = 0x52

        SYSTEM_HISTOGRAM_BIN                        = 0x81
        HISTOGRAM_CONFIG_INITIAL_PHASE_SELECT       = 0x33
        HISTOGRAM_CONFIG_READOUT_CTRL               = 0x55

        FINAL_RANGE_CONFIG_VCSEL_PERIOD             = 0x70
        FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI        = 0x71
        FINAL_RANGE_CONFIG_TIMEOUT_MACROP_LO        = 0x72
        CROSSTALK_COMPENSATION_PEAK_RATE_MCPS       = 0x20

        MSRC_CONFIG_TIMEOUT_MACROP                  = 0x46

        SOFT_RESET_GO2_SOFT_RESET_N                 = 0xBF
        IDENTIFICATION_MODEL_ID                     = 0xC0
        IDENTIFICATION_REVISION_ID                  = 0xC2

        OSC_CALIBRATE_VAL                           = 0xF8

        GLOBAL_CONFIG_VCSEL_WIDTH                   = 0x32
        GLOBAL_CONFIG_SPAD_ENABLES_REF_0            = 0xB0
        GLOBAL_CONFIG_SPAD_ENABLES_REF_1            = 0xB1
        GLOBAL_CONFIG_SPAD_ENABLES_REF_2            = 0xB2
        GLOBAL_CONFIG_SPAD_ENABLES_REF_3            = 0xB3
        GLOBAL_CONFIG_SPAD_ENABLES_REF_4            = 0xB4
        GLOBAL_CONFIG_SPAD_ENABLES_REF_5            = 0xB5

        GLOBAL_CONFIG_REF_EN_START_SELECT           = 0xB6
        DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD         = 0x4E
        DYNAMIC_SPAD_REF_EN_START_OFFSET            = 0x4F
        POWER_MANAGEMENT_GO1_POWER_FORCE            = 0x80

        VHV_CONFIG_PAD_SCL_SDA__EXTSUP_HV           = 0x89

        ALGO_PHASECAL_LIM                           = 0x30
        ALGO_PHASECAL_CONFIG_TIMEOUT                = 0x30

        # TCC: Target CentreCheck
        # MSRC: Minimum Signal Rate Check
        # DSS: Dynamic Spad Selection
        #struct SequenceStepEnables
        #{
        #  boolean tcc, msrc, dss, pre_range, final_range
        #}

        #struct SequenceStepTimeouts
        #{
        #  uint16_t pre_range_vcsel_period_pclks, final_range_vcsel_period_pclks

        #  uint16_t msrc_dss_tcc_mclks, pre_range_mclks, final_range_mclks
        #  uint32_t msrc_dss_tcc_us,    pre_range_us,    final_range_us
        #}
        enables = namedtuple('enables', 'tcc msrc dss pre_range final_range')
        timeouts = namedtuple('timeouts', 'pre_range_vcsel_period_pclks final_range_vcsel_period_pclks \
                                msrc_dss_tcc_mclks pre_range_mclks final_range_mclks \
                                msrc_dss_tcc_us pre_range_usfinal_range_us')

        #enum vcselPeriodType { VcselPeriodPreRange, VcselPeriodFinalRange };
        vcselPeriodType = ['VcselPeriodPreRange', 'VcselPeriodFinalRange']

        # Record the current time to check an upcoming timeout against
        def startTimeout(self, timeout_start_ms):
                timeout_start_ms = int(round(time.time() * 1000))

        # Check if timeout is enabled (set to nonzero value) and has expired
        def checkTimeoutExpired(self, io_timeout, timeout_start_ms):
                if(io_timeout > 0 and (int(round(time.time() * 1000)) - timeout_start_ms) > io_timeout):
                        return True
                else:
                        return False

        # Decode VCSEL (vertical cavity surface emitting laser) pulse period in PCLKs
        # from register value
        # based on VL53L0X_decode_vcsel_period()
        def decodeVcselPeriod(self, reg_val):
                return (((reg_val) + 1) << 1)

        # Encode VCSEL pulse period register value from period in PCLKs
        # based on VL53L0X_encode_vcsel_period()
        def encodeVcselPeriod(self, period_pclks):
                return (((period_pclks) >> 1) - 1)

        # Calculate macro period in *nanoseconds* from VCSEL period in PCLKs
        # based on VL53L0X_calc_macro_period_ps()
        # PLL_period_ps = 1655 macro_period_vclks = 2304
        def calcMacroPeriod(self, vcsel_period_pclks):
                return (((2304 * (vcsel_period_pclks) * 1655) + 500) / 1000)

        # Constructors ################################

        def __init__(self, i2c, address):
                self.i2c = i2c
                if address == NULL:
                        self._address = ADDRESS_DEFAULT
                else:
                        self._address = address
                                print(self._address)
                self.init(True)
Example #37
0
try:
    try:
        from ucollections import namedtuple
    except ImportError:
        from collections import namedtuple
except ImportError:
    print("SKIP")
    raise SystemExit

t = namedtuple("Tup", ["baz", "foo", "bar"])(3, 2, 5)

try:
    t._asdict
except AttributeError:
    print("SKIP")
    raise SystemExit

d = t._asdict()
print(list(d.keys()))
print(list(d.values()))
Example #38
0
OP_PING = const(0x9)
OP_PONG = const(0xa)

# Close codes
CLOSE_OK = const(1000)
CLOSE_GOING_AWAY = const(1001)
CLOSE_PROTOCOL_ERROR = const(1002)
CLOSE_DATA_NOT_SUPPORTED = const(1003)
CLOSE_BAD_DATA = const(1007)
CLOSE_POLICY_VIOLATION = const(1008)
CLOSE_TOO_BIG = const(1009)
CLOSE_MISSING_EXTN = const(1010)
CLOSE_BAD_CONDITION = const(1011)

URL_RE = re.compile(r'(wss|ws)://([A-Za-z0-9-\.]+)(?:\:([0-9]+))?(/.+)?')
URI = namedtuple('URI', ('protocol', 'hostname', 'port', 'path'))


class NoDataException(Exception):
    pass


class ConnectionClosed(Exception):
    pass


def urlparse(uri):
    """Parse ws:// URLs"""
    match = URL_RE.match(uri)
    if match:
        protocol = match.group(1)
import bench
from ucollections import namedtuple

T = namedtuple("Tup", ["num", "bar"])

def test(num):
    t = T(20000000, 0)
    i = 0
    while i < t.num:
        i += 1

bench.run(test)