utils.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # -*- coding: utf-8 -*-
  2. # Copyright (C) 2015-2016 Peter Magnusson <peter@birchroad.net>
  3. """Various utility functions"""
  4. from platform import system
  5. from os import environ
  6. from wrapt import ObjectProxy
  7. __all__ = ['default_port', 'system']
  8. ENCODING = 'latin1'
  9. def default_port(sysname=system()):
  10. """This returns the default port used for different systems if SERIALPORT env variable is not set"""
  11. system_default = {
  12. 'Windows': 'COM1',
  13. 'Darwin': '/dev/tty.SLAB_USBtoUART'
  14. }.get(sysname, '/dev/ttyUSB0')
  15. return environ.get('SERIALPORT', system_default)
  16. def bytefy(x):
  17. return x if type(x) == bytes else x.encode(ENCODING)
  18. def to_hex(x):
  19. return hex(x) if type(x) == bytes else hex(ord(x))
  20. def hexify(byte_arr):
  21. return ':'.join((to_hex(x)[2:] for x in byte_arr))
  22. def from_file(path):
  23. with open(path, 'rb') as f:
  24. content = f.read().decode(ENCODING)
  25. return content
  26. class DecoderWrapper(ObjectProxy):
  27. def read(self, *args, **kwargs):
  28. return self.__wrapped__.read(*args, **kwargs).decode(ENCODING)
  29. def write(self, data):
  30. return self.__wrapped__.write(data.encode(ENCODING))
  31. def wrap(x):
  32. return DecoderWrapper(x)