Fix Python 3 conversion errors

Fixes #299
This commit is contained in:
Otto Winter 2019-01-05 14:24:15 +01:00
parent 907be3025c
commit 3cd1c2d723
No known key found for this signature in database
GPG key ID: DB66C0BE6013F97E
5 changed files with 43 additions and 18 deletions

View file

@ -14,7 +14,7 @@ import esphomeyaml.api.api_pb2 as pb
from esphomeyaml.const import CONF_PASSWORD, CONF_PORT from esphomeyaml.const import CONF_PASSWORD, CONF_PORT
from esphomeyaml.core import EsphomeyamlError from esphomeyaml.core import EsphomeyamlError
from esphomeyaml.helpers import resolve_ip_address, indent, color from esphomeyaml.helpers import resolve_ip_address, indent, color
from esphomeyaml.py_compat import text_type, IS_PY2, byte, char, format_bytes from esphomeyaml.py_compat import text_type, IS_PY2, byte_to_bytes, char_to_byte, format_bytes
from esphomeyaml.util import safe_print from esphomeyaml.util import safe_print
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -67,16 +67,16 @@ MESSAGE_TYPE_TO_PROTO = {
def _varuint_to_bytes(value): def _varuint_to_bytes(value):
if value <= 0x7F: if value <= 0x7F:
return byte(value) return byte_to_bytes(value)
ret = bytes() ret = bytes()
while value: while value:
temp = value & 0x7F temp = value & 0x7F
value >>= 7 value >>= 7
if value: if value:
ret += byte(temp | 0x80) ret += byte_to_bytes(temp | 0x80)
else: else:
ret += byte(temp) ret += byte_to_bytes(temp)
return ret return ret
@ -85,7 +85,7 @@ def _bytes_to_varuint(value):
result = 0 result = 0
bitpos = 0 bitpos = 0
for c in value: for c in value:
val = char(c) val = char_to_byte(c)
result |= (val & 0x7F) << bitpos result |= (val & 0x7F) << bitpos
bitpos += 7 bitpos += 7
if (val & 0x80) == 0: if (val & 0x80) == 0:
@ -361,7 +361,7 @@ class APIClient(threading.Thread):
def _recv_varint(self): def _recv_varint(self):
raw = bytes() raw = bytes()
while not raw or char(raw[-1]) & 0x80: while not raw or char_to_byte(raw[-1]) & 0x80:
raw += self._recv(1) raw += self._recv(1)
return _bytes_to_varuint(raw) return _bytes_to_varuint(raw)
@ -370,7 +370,7 @@ class APIClient(threading.Thread):
return return
# Preamble # Preamble
if char(self._recv(1)[0]) != 0x00: if char_to_byte(self._recv(1)[0]) != 0x00:
raise APIConnectionError("Invalid preamble") raise APIConnectionError("Invalid preamble")
length = self._recv_varint() length = self._recv_varint()

View file

@ -8,6 +8,7 @@ from esphomeyaml.const import CONF_FILE, CONF_GLYPHS, CONF_ID, CONF_SIZE
from esphomeyaml.core import CORE, HexInt from esphomeyaml.core import CORE, HexInt
from esphomeyaml.cpp_generator import ArrayInitializer, MockObj, Pvariable, RawExpression, add from esphomeyaml.cpp_generator import ArrayInitializer, MockObj, Pvariable, RawExpression, add
from esphomeyaml.cpp_types import App from esphomeyaml.cpp_types import App
from esphomeyaml.py_compat import sort_by_cmp
DEPENDENCIES = ['display'] DEPENDENCIES = ['display']
MULTI_CONF = True MULTI_CONF = True
@ -37,7 +38,7 @@ def validate_glyphs(value):
return 1 return 1
raise vol.Invalid(u"Found duplicate glyph {}".format(x)) raise vol.Invalid(u"Found duplicate glyph {}".format(x))
value.sort(cmp=comparator) sort_by_cmp(value, comparator)
return value return value

View file

@ -7,7 +7,7 @@ import time
from esphomeyaml.core import EsphomeyamlError from esphomeyaml.core import EsphomeyamlError
from esphomeyaml.helpers import resolve_ip_address, is_ip_address from esphomeyaml.helpers import resolve_ip_address, is_ip_address
from esphomeyaml.py_compat import IS_PY2, char from esphomeyaml.py_compat import IS_PY2, char_to_byte
RESPONSE_OK = 0 RESPONSE_OK = 0
RESPONSE_REQUEST_AUTH = 1 RESPONSE_REQUEST_AUTH = 1
@ -68,7 +68,7 @@ def recv_decode(sock, amount, decode=True):
data = sock.recv(amount) data = sock.recv(amount)
if not decode: if not decode:
return data return data
return [char(x) for x in data] return [char_to_byte(x) for x in data]
def receive_exactly(sock, amount, msg, expect, decode=True): def receive_exactly(sock, amount, msg, expect, decode=True):

View file

@ -6,7 +6,7 @@ import os
import socket import socket
import subprocess import subprocess
from esphomeyaml.py_compat import text_type, IS_PY2 from esphomeyaml.py_compat import text_type, char_to_byte
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -41,13 +41,19 @@ def indent(text, padding=u' '):
# From https://stackoverflow.com/a/14945195/8924614 # From https://stackoverflow.com/a/14945195/8924614
def cpp_string_escape(string, encoding='utf-8'): def cpp_string_escape(string, encoding='utf-8'):
def _should_escape(byte): # type: (int) -> bool
if not 32 <= byte < 127:
return True
if byte in (char_to_byte('\\'), char_to_byte('"')):
return True
return False
if isinstance(string, text_type): if isinstance(string, text_type):
string = string.encode(encoding) string = string.encode(encoding)
result = '' result = ''
for character in string: for character in string:
if IS_PY2: character = char_to_byte(character)
character = ord(character) if _should_escape(character):
if not (32 <= character < 127) or character in ('\\', '"'):
result += '\\%03o' % character result += '\\%03o' % character
else: else:
result += chr(character) result += chr(character)

View file

@ -1,3 +1,4 @@
import functools
import sys import sys
PYTHON_MAJOR = sys.version_info[0] PYTHON_MAJOR = sys.version_info[0]
@ -25,18 +26,28 @@ else:
binary_type = bytes binary_type = bytes
def byte(val): def byte_to_bytes(val): # type: (int) -> bytes
if IS_PY2: if IS_PY2:
return chr(val) return chr(val)
else: else:
return bytes([val]) return bytes([val])
def char(val): def char_to_byte(val): # type: (str) -> int
if IS_PY2: if IS_PY2:
return ord(val) if isinstance(val, string_types):
return ord(val)
elif isinstance(val, int):
return val
else:
raise ValueError
else: else:
return val if isinstance(val, str):
return ord(val)
elif isinstance(val, int):
return val
else:
raise ValueError
def format_bytes(val): def format_bytes(val):
@ -44,3 +55,10 @@ def format_bytes(val):
return ' '.join('{:02X}'.format(ord(x)) for x in val) return ' '.join('{:02X}'.format(ord(x)) for x in val)
else: else:
return ' '.join('{:02X}'.format(x) for x in val) return ' '.join('{:02X}'.format(x) for x in val)
def sort_by_cmp(list_, cmp):
if IS_PY2:
list_.sort(cmp=cmp)
else:
list_.sort(key=functools.cmp_to_key(cmp))