1
0
mirror of https://github.com/undera/pylgbst.git synced 2020-11-18 19:37:26 -08:00
Mike C. Fletcher c955820521 Bunch of Tiny Fixes and Enhancements (#41)
* Use setuptools to allow the extras_require to work in python3.6

This also declares some hidden dependencies for the underlying
connection protocols, but note that they are normally reliant
on system-packaged versions, which is a bit less than optimal.

* In message, on assert of incoming type, note failing type

* In utilities, guard against truncated input.

* In demo allow for specifying different connections and demos on command line

Also addresses a crash in led demo where parameters x and y were not provided
to an empty lamba that was passed in.

* Remove commentted line, apply black formatting

* Raise TypeError when an incorrectly-typed message is received

* Apply black automatic formatting to the utilities module
2019-12-27 10:27:59 +03:00

51 lines
1.2 KiB
Python

"""
This module offers some utilities, in a way they are work in both Python 2 and 3
"""
import binascii
import logging
import sys
from struct import unpack
log = logging.getLogger(__name__)
if sys.version_info[0] == 2:
import Queue as queue
else:
import queue as queue
queue = queue # just to use it
def check_unpack(seq, index, pattern, size):
"""Check that we got size bytes, if so, unpack using pattern"""
data = seq[index : index + size]
if len(data) == size:
return unpack(pattern, data)[0]
else:
log.warning(
"Unpacking of %s bytes failed, insufficient data: %r", size, seq[index:]
)
raise ValueError(data, "Expected %s bytes" % (size,))
def usbyte(seq, index):
return check_unpack(seq, index, "<B", 1)
def ushort(seq, index):
return check_unpack(seq, index, "<H", 2)
def usint(seq, index):
return check_unpack(seq, index, "<I", 4)
def str2hex(data): # we need it for python 2+3 compatibility
# if sys.version_info[0] == 3:
# data = bytes(data, 'ascii')
if not isinstance(data, (bytes, bytearray)):
data = bytes(data, "ascii")
hexed = binascii.hexlify(data)
return hexed