Enable Travis Linting (#3)

* Flake8 Travis Job

* Fix flake8 warnings

* Fix pylint errors

* Fix travis file
This commit is contained in:
Otto Winter 2018-04-10 17:17:46 +02:00 committed by GitHub
parent 51c856e65e
commit 0ab63dc4d4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 238 additions and 180 deletions

10
.travis.yml Normal file
View file

@ -0,0 +1,10 @@
sudo: false
language: python
python:
- "2.7"
install:
- pip install -r requirements.txt
- pip install flake8==3.5.0 pylint==1.8.4
script:
- flake8 esphomeyaml
- pylint esphomeyaml

View file

@ -37,20 +37,20 @@ def discover_serial_ports():
return None return None
result = None result = None
for p, d, h in comports(): for port, _, info in comports():
if not p: if not port:
continue continue
if "VID:PID" in h: if "VID:PID" in info:
if result is not None: if result is not None:
return None return None
result = p result = port
return result return result
def run_platformio(*cmd): def run_platformio(*cmd):
def mock_exit(rc): def mock_exit(return_code):
raise SystemExit(rc) raise SystemExit(return_code)
orig_argv = sys.argv orig_argv = sys.argv
orig_exit = sys.exit # mock sys.exit orig_exit = sys.exit # mock sys.exit
@ -63,10 +63,10 @@ def run_platformio(*cmd):
return platformio.__main__.main() return platformio.__main__.main()
except KeyboardInterrupt: except KeyboardInterrupt:
return 1 return 1
except SystemExit as e: except SystemExit as err:
return e.args[0] return err.args[0]
except Exception as e: except Exception as err: # pylint: disable=broad-except
_LOGGER.error(u"Running platformio failed: %s", e) _LOGGER.error(u"Running platformio failed: %s", err)
_LOGGER.error(u"Please try running %s locally.", full_cmd) _LOGGER.error(u"Please try running %s locally.", full_cmd)
finally: finally:
sys.argv = orig_argv sys.argv = orig_argv
@ -129,9 +129,8 @@ def upload_program(config, args, port):
if args.upload_port == 'HELLO': if args.upload_port == 'HELLO':
return run_platformio('platformio', 'run', '-d', get_base_path(config), return run_platformio('platformio', 'run', '-d', get_base_path(config),
'-t', 'upload') '-t', 'upload')
else: return run_platformio('platformio', 'run', '-d', get_base_path(config),
return run_platformio('platformio', 'run', '-d', get_base_path(config), '-t', 'upload', '--upload-port', args.upload_port)
'-t', 'upload', '--upload-port', args.upload_port)
if port is not None: if port is not None:
_LOGGER.info("Serial device discovered, using it for upload") _LOGGER.info("Serial device discovered, using it for upload")
@ -258,6 +257,7 @@ def main():
if args.command == 'config': if args.command == 'config':
print(yaml_util.dump(config)) print(yaml_util.dump(config))
return 0
elif args.command == 'compile': elif args.command == 'compile':
exit_code = write_cpp(config) exit_code = write_cpp(config)
if exit_code != 0: if exit_code != 0:
@ -288,16 +288,15 @@ def main():
return exit_code return exit_code
_LOGGER.info(u"Successfully compiled program.") _LOGGER.info(u"Successfully compiled program.")
if args.no_logs: if args.no_logs:
return return 0
port = discover_serial_ports() port = discover_serial_ports()
exit_code = upload_program(config, args, port) exit_code = upload_program(config, args, port)
if exit_code != 0: if exit_code != 0:
return exit_code return exit_code
_LOGGER.info(u"Successfully uploaded program.") _LOGGER.info(u"Successfully uploaded program.")
return show_logs(config, args, port) return show_logs(config, args, port)
else: print(u"Unknown command {}".format(args.command))
print(u"Unknown command {}".format(args.command)) return 1
return 1
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -8,6 +8,8 @@ from esphomeyaml.helpers import App, Pvariable, RawExpression, add, exp_empty_op
LOG_LEVELS = ['NONE', 'ERROR', 'WARN', 'INFO', 'DEBUG', 'VERBOSE'] LOG_LEVELS = ['NONE', 'ERROR', 'WARN', 'INFO', 'DEBUG', 'VERBOSE']
# pylint: disable=invalid-name
is_log_level = vol.All(vol.Upper, vol.Any(*LOG_LEVELS)) is_log_level = vol.All(vol.Upper, vol.Any(*LOG_LEVELS))
CONFIG_SCHEMA = cv.ID_SCHEMA.extend({ CONFIG_SCHEMA = cv.ID_SCHEMA.extend({

View file

@ -24,8 +24,8 @@ def to_code(config):
rhs = App.init_ota() rhs = App.init_ota()
ota = Pvariable('OTAComponent', config[CONF_ID], rhs) ota = Pvariable('OTAComponent', config[CONF_ID], rhs)
if CONF_PASSWORD in config: if CONF_PASSWORD in config:
h = hashlib.md5(config[CONF_PASSWORD].encode()).hexdigest() hash_ = hashlib.md5(config[CONF_PASSWORD].encode()).hexdigest()
add(ota.set_auth_password_hash(h)) add(ota.set_auth_password_hash(hash_))
if config[CONF_SAFE_MODE]: if config[CONF_SAFE_MODE]:
add(ota.start_safe_mode()) add(ota.start_safe_mode())

View file

@ -46,6 +46,7 @@ MQTT_SENSOR_ID_SCHEMA = MQTT_SENSOR_SCHEMA.extend({
cv.GenerateID('mqtt_sensor'): cv.register_variable_id, cv.GenerateID('mqtt_sensor'): cv.register_variable_id,
}) })
# pylint: disable=invalid-name
OffsetFilter = MockObj('new sensor::OffsetFilter') OffsetFilter = MockObj('new sensor::OffsetFilter')
MultiplyFilter = MockObj('new sensor::MultiplyFilter') MultiplyFilter = MockObj('new sensor::MultiplyFilter')
FilterOutValueFilter = MockObj('new sensor::FilterOutValueFilter') FilterOutValueFilter = MockObj('new sensor::FilterOutValueFilter')

View file

@ -38,6 +38,8 @@ PLATFORM_SCHEMA = switch.PLATFORM_SCHEMA.extend({
vol.Optional(CONF_IR_TRANSMITTER_ID): cv.variable_id, vol.Optional(CONF_IR_TRANSMITTER_ID): cv.variable_id,
}).extend(switch.MQTT_SWITCH_SCHEMA.schema) }).extend(switch.MQTT_SWITCH_SCHEMA.schema)
# pylint: disable=invalid-name
SendData = MockObj('switch_::ir::SendData', '::') SendData = MockObj('switch_::ir::SendData', '::')

View file

@ -19,6 +19,8 @@ CONFIG_SCHEMA = cv.ID_SCHEMA.extend({
vol.Optional(CONF_HOSTNAME): cv.hostname, vol.Optional(CONF_HOSTNAME): cv.hostname,
}) })
# pylint: disable=invalid-name
IPAddress = MockObj('IPAddress') IPAddress = MockObj('IPAddress')

View file

@ -50,7 +50,6 @@ def get_component(domain):
module = importlib.import_module(path) module = importlib.import_module(path)
except ImportError as err: except ImportError as err:
_LOGGER.debug(err) _LOGGER.debug(err)
pass
else: else:
_COMPONENT_CACHE[domain] = module _COMPONENT_CACHE[domain] = module
return module return module
@ -87,7 +86,7 @@ def validate_config(config):
for req in REQUIRED_COMPONENTS: for req in REQUIRED_COMPONENTS:
if req not in config: if req not in config:
raise ESPHomeYAMLError("Component %s is required for esphomeyaml.", req) raise ESPHomeYAMLError("Component {} is required for esphomeyaml.".format(req))
_ALL_COMPONENTS = list(config.keys()) _ALL_COMPONENTS = list(config.keys())
@ -137,7 +136,7 @@ def validate_config(config):
continue continue
platforms = [] platforms = []
for i, p_config in enumerate(conf): for p_config in conf:
if not isinstance(p_config, dict): if not isinstance(p_config, dict):
result.add_error(u"Platform schemas mus have 'platform:' key") result.add_error(u"Platform schemas mus have 'platform:' key")
continue continue

View file

@ -16,9 +16,11 @@ from esphomeyaml.helpers import ensure_unique_string
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
# pylint: disable=invalid-name
port = vol.All(vol.Coerce(int), vol.Range(min=1, max=65535)) port = vol.All(vol.Coerce(int), vol.Range(min=1, max=65535))
positive_float = vol.All(vol.Coerce(float), vol.Range(min=0)) positive_float = vol.All(vol.Coerce(float), vol.Range(min=0))
zero_to_one_float = vol.All(vol.Coerce(float), vol.Range(min=0, max=1)), zero_to_one_float = vol.All(vol.Coerce(float), vol.Range(min=0, max=1))
positive_int = vol.All(vol.Coerce(int), vol.Range(min=0)) positive_int = vol.All(vol.Coerce(int), vol.Range(min=0))
positive_not_null_int = vol.All(vol.Coerce(int), vol.Range(min=0, min_included=False)) positive_not_null_int = vol.All(vol.Coerce(int), vol.Range(min=0, min_included=False))
@ -57,7 +59,7 @@ def alphanumeric(value):
def valid_name(value): def valid_name(value):
value = string_strict(value) value = string_strict(value)
if not all(c in ALLOWED_NAME_CHARS for c in value): if not all(c in ALLOWED_NAME_CHARS for c in value):
raise vol.Invalid(u"Valid characters for name are %s", ALLOWED_NAME_CHARS) raise vol.Invalid(u"Valid characters for name are {}".format(ALLOWED_NAME_CHARS))
return value return value
@ -71,7 +73,7 @@ def string(value):
def string_strict(value): def string_strict(value):
"""Strictly only allow strings.""" """Strictly only allow strings."""
if isinstance(value, str) or isinstance(value, unicode): if isinstance(value, (str, unicode)):
return value return value
raise vol.Invalid("Must be string, did you forget putting quotes " raise vol.Invalid("Must be string, did you forget putting quotes "
"around the value?") "around the value?")

View file

@ -43,6 +43,8 @@ import random
import socket import socket
import sys import sys
# pylint: disable=no-member
# Commands # Commands
FLASH = 0 FLASH = 0
SPIFFS = 100 SPIFFS = 100
@ -62,7 +64,7 @@ def update_progress(progress):
:return: :return:
""" """
if PROGRESS: if PROGRESS:
barLength = 60 # Modify this to change the length of the progress bar bar_length = 60 # Modify this to change the length of the progress bar
status = "" status = ""
if isinstance(progress, int): if isinstance(progress, int):
progress = float(progress) progress = float(progress)
@ -75,8 +77,8 @@ def update_progress(progress):
if progress >= 1: if progress >= 1:
progress = 1 progress = 1
status = "Done...\r\n" status = "Done...\r\n"
block = int(round(barLength * progress)) block = int(round(bar_length * progress))
text = "\rUploading: [{0}] {1}% {2}".format("=" * block + " " * (barLength - block), text = "\rUploading: [{0}] {1}% {2}".format("=" * block + " " * (bar_length - block),
int(progress * 100), status) int(progress * 100), status)
sys.stderr.write(text) sys.stderr.write(text)
sys.stderr.flush() sys.stderr.flush()
@ -93,14 +95,14 @@ def serve(remote_host, local_addr, remote_port, local_port, password, filename,
try: try:
sock.bind(server_address) sock.bind(server_address)
sock.listen(1) sock.listen(1)
except Exception: except Exception: # pylint: disable=broad-except
_LOGGER.error("Listen Failed") _LOGGER.error("Listen Failed")
return 1 return 1
content_size = os.path.getsize(filename) content_size = os.path.getsize(filename)
f = open(filename, 'rb') f_handle = open(filename, 'rb')
file_md5 = hashlib.md5(f.read()).hexdigest() file_md5 = hashlib.md5(f_handle.read()).hexdigest()
f.close() f_handle.close()
_LOGGER.info('Upload size: %d', content_size) _LOGGER.info('Upload size: %d', content_size)
message = '%d %d %d %s\n' % (command, local_port, content_size, file_md5) message = '%d %d %d %s\n' % (command, local_port, content_size, file_md5)
@ -116,7 +118,7 @@ def serve(remote_host, local_addr, remote_port, local_port, password, filename,
sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try: try:
sock2.sendto(message.encode(), remote_address) sock2.sendto(message.encode(), remote_address)
except Exception: except Exception: # pylint: disable=broad-except
_LOGGER.error('Failed') _LOGGER.error('Failed')
sock2.close() sock2.close()
_LOGGER.error('Host %s Not Found', remote_host) _LOGGER.error('Host %s Not Found', remote_host)
@ -125,7 +127,7 @@ def serve(remote_host, local_addr, remote_port, local_port, password, filename,
try: try:
data = sock2.recv(37).decode() data = sock2.recv(37).decode()
break break
except Exception: except Exception: # pylint: disable=broad-except
sys.stderr.write('.') sys.stderr.write('.')
sys.stderr.flush() sys.stderr.flush()
sock2.close() sock2.close()
@ -148,7 +150,7 @@ def serve(remote_host, local_addr, remote_port, local_port, password, filename,
sock2.settimeout(10) sock2.settimeout(10)
try: try:
data = sock2.recv(32).decode() data = sock2.recv(32).decode()
except Exception: except Exception: # pylint: disable=broad-except
_LOGGER.error('FAIL: No Answer to our Authentication') _LOGGER.error('FAIL: No Answer to our Authentication')
sock2.close() sock2.close()
return 1 return 1
@ -166,23 +168,23 @@ def serve(remote_host, local_addr, remote_port, local_port, password, filename,
_LOGGER.info('Waiting for device...') _LOGGER.info('Waiting for device...')
try: try:
sock.settimeout(10) sock.settimeout(10)
connection, client_address = sock.accept() connection, _ = sock.accept()
sock.settimeout(None) sock.settimeout(None)
connection.settimeout(None) connection.settimeout(None)
except Exception: except Exception: # pylint: disable=broad-except
_LOGGER.error('No response from device') _LOGGER.error('No response from device')
sock.close() sock.close()
return 1 return 1
try: try:
f = open(filename, "rb") f_handle = open(filename, "rb")
if PROGRESS: if PROGRESS:
update_progress(0) update_progress(0)
else: else:
_LOGGER.info('Uploading...') _LOGGER.info('Uploading...')
offset = 0 offset = 0
while True: while True:
chunk = f.read(1024) chunk = f_handle.read(1024)
if not chunk: if not chunk:
break break
offset += len(chunk) offset += len(chunk)
@ -191,11 +193,11 @@ def serve(remote_host, local_addr, remote_port, local_port, password, filename,
try: try:
connection.sendall(chunk) connection.sendall(chunk)
connection.recv(10) connection.recv(10)
except Exception: except Exception: # pylint: disable=broad-except
sys.stderr.write('\n') sys.stderr.write('\n')
_LOGGER.error('Error Uploading') _LOGGER.error('Error Uploading')
connection.close() connection.close()
f.close() f_handle.close()
sock.close() sock.close()
return 1 return 1
@ -208,26 +210,26 @@ def serve(remote_host, local_addr, remote_port, local_port, password, filename,
break break
_LOGGER.info('Result: OK') _LOGGER.info('Result: OK')
connection.close() connection.close()
f.close() f_handle.close()
sock.close() sock.close()
if data != "OK": if data != "OK":
_LOGGER.error('%s', data) _LOGGER.error('%s', data)
return 1 return 1
except Exception: except Exception: # pylint: disable=broad-except
_LOGGER.error('No Result!') _LOGGER.error('No Result!')
connection.close() connection.close()
f.close() f_handle.close()
sock.close() sock.close()
return 1 return 1
finally: finally:
connection.close() connection.close()
f.close() f_handle.close()
return 0 return 0
def parser(unparsed_args): def parse_args(unparsed_args):
parser = optparse.OptionParser( parser = optparse.OptionParser(
usage="%prog [options]", usage="%prog [options]",
description="Transmit image over the air to the esp8266 module with OTA support." description="Transmit image over the air to the esp8266 module with OTA support."
@ -235,82 +237,91 @@ def parser(unparsed_args):
# destination ip and port # destination ip and port
group = optparse.OptionGroup(parser, "Destination") group = optparse.OptionGroup(parser, "Destination")
group.add_option("-i", "--ip", group.add_option(
dest="esp_ip", "-i", "--ip",
action="store", dest="esp_ip",
help="ESP8266 IP Address.", action="store",
default=False help="ESP8266 IP Address.",
) default=False
group.add_option("-I", "--host_ip", )
dest="host_ip", group.add_option(
action="store", "-I", "--host_ip",
help="Host IP Address.", dest="host_ip",
default="0.0.0.0" action="store",
) help="Host IP Address.",
group.add_option("-p", "--port", default="0.0.0.0"
dest="esp_port", )
type="int", group.add_option(
help="ESP8266 ota Port. Default 8266", "-p", "--port",
default=8266 dest="esp_port",
) type="int",
group.add_option("-P", "--host_port", help="ESP8266 ota Port. Default 8266",
dest="host_port", default=8266
type="int", )
help="Host server ota Port. Default random 10000-60000", group.add_option(
default=random.randint(10000, 60000) "-P", "--host_port",
) dest="host_port",
type="int",
help="Host server ota Port. Default random 10000-60000",
default=random.randint(10000, 60000)
)
parser.add_option_group(group) parser.add_option_group(group)
# auth # auth
group = optparse.OptionGroup(parser, "Authentication") group = optparse.OptionGroup(parser, "Authentication")
group.add_option("-a", "--auth", group.add_option(
dest="auth", "-a", "--auth",
help="Set authentication password.", dest="auth",
action="store", help="Set authentication password.",
default="" action="store",
) default=""
)
parser.add_option_group(group) parser.add_option_group(group)
# image # image
group = optparse.OptionGroup(parser, "Image") group = optparse.OptionGroup(parser, "Image")
group.add_option("-f", "--file", group.add_option(
dest="image", "-f", "--file",
help="Image file.", dest="image",
metavar="FILE", help="Image file.",
default=None metavar="FILE",
) default=None
group.add_option("-s", "--spiffs", )
dest="spiffs", group.add_option(
action="store_true", "-s", "--spiffs",
help="Use this option to transmit a SPIFFS image and do not flash the " dest="spiffs",
"module.", action="store_true",
default=False help="Use this option to transmit a SPIFFS image and do not flash the "
) "module.",
default=False
)
parser.add_option_group(group) parser.add_option_group(group)
# output group # output group
group = optparse.OptionGroup(parser, "Output") group = optparse.OptionGroup(parser, "Output")
group.add_option("-d", "--debug", group.add_option(
dest="debug", "-d", "--debug",
help="Show debug output. And override loglevel with debug.", dest="debug",
action="store_true", help="Show debug output. And override loglevel with debug.",
default=False action="store_true",
) default=False
group.add_option("-r", "--progress", )
dest="progress", group.add_option(
help="Show progress output. Does not work for ArduinoIDE", "-r", "--progress",
action="store_true", dest="progress",
default=False help="Show progress output. Does not work for ArduinoIDE",
) action="store_true",
default=False
)
parser.add_option_group(group) parser.add_option_group(group)
(options, args) = parser.parse_args(unparsed_args) options, _ = parser.parse_args(unparsed_args)
return options return options
def main(args): def main(args):
options = parser(args) options = parse_args(args)
_LOGGER.debug("Options: %s", str(options)) _LOGGER.debug("Options: %s", str(options))
# check options # check options

View file

@ -48,7 +48,7 @@ class Expression(object):
pass pass
def __str__(self): def __str__(self):
raise NotImplemented raise NotImplementedError
class RawExpression(Expression): class RawExpression(Expression):
@ -107,11 +107,11 @@ class StructInitializer(Expression):
self.args[key] = safe_exp(value) self.args[key] = safe_exp(value)
def __str__(self): def __str__(self):
s = u'{}{{\n'.format(self.base) cpp = u'{}{{\n'.format(self.base)
for key, value in self.args.iteritems(): for key, value in self.args.iteritems():
s += u' .{} = {},\n'.format(key, value) cpp += u' .{} = {},\n'.format(key, value)
s += u'}' cpp += u'}'
return s return cpp
class ArrayInitializer(Expression): class ArrayInitializer(Expression):
@ -122,25 +122,25 @@ class ArrayInitializer(Expression):
def __str__(self): def __str__(self):
if not self.args: if not self.args:
return u'{}' return u'{}'
s = u'{\n' cpp = u'{\n'
for arg in self.args: for arg in self.args:
s += u' {},\n'.format(arg) cpp += u' {},\n'.format(arg)
s += u'}' cpp += u'}'
return s return cpp
class Literal(Expression): class Literal(Expression):
def __init__(self): def __str__(self):
super(Literal, self).__init__() raise NotImplementedError
class StringLiteral(Literal): class StringLiteral(Literal):
def __init__(self, s): def __init__(self, string):
super(StringLiteral, self).__init__() super(StringLiteral, self).__init__()
self.s = s self.string = string
def __str__(self): def __str__(self):
return u'"{}"'.format(self.s) return u'"{}"'.format(self.string)
class IntLiteral(Literal): class IntLiteral(Literal):
@ -153,12 +153,12 @@ class IntLiteral(Literal):
class BoolLiteral(Literal): class BoolLiteral(Literal):
def __init__(self, b): def __init__(self, binary):
super(BoolLiteral, self).__init__() super(BoolLiteral, self).__init__()
self.b = b self.binary = binary
def __str__(self): def __str__(self):
return u"true" if self.b else u"false" return u"true" if self.binary else u"false"
class HexIntLiteral(Literal): class HexIntLiteral(Literal):
@ -171,12 +171,12 @@ class HexIntLiteral(Literal):
class FloatLiteral(Literal): class FloatLiteral(Literal):
def __init__(self, f): def __init__(self, float_):
super(FloatLiteral, self).__init__() super(FloatLiteral, self).__init__()
self.f = f self.float_ = float_
def __str__(self): def __str__(self):
return u"{:f}f".format(self.f) return u"{:f}f".format(self.float_)
def safe_exp(obj): def safe_exp(obj):
@ -184,7 +184,7 @@ def safe_exp(obj):
return obj return obj
elif isinstance(obj, bool): elif isinstance(obj, bool):
return BoolLiteral(obj) return BoolLiteral(obj)
elif isinstance(obj, str) or isinstance(obj, unicode): elif isinstance(obj, (str, unicode)):
return StringLiteral(obj) return StringLiteral(obj)
elif isinstance(obj, (int, long)): elif isinstance(obj, (int, long)):
return IntLiteral(obj) return IntLiteral(obj)
@ -198,7 +198,7 @@ class Statement(object):
pass pass
def __str__(self): def __str__(self):
raise NotImplemented raise NotImplementedError
class RawStatement(Statement): class RawStatement(Statement):
@ -225,6 +225,7 @@ def statement(expression):
return ExpressionStatement(expression) return ExpressionStatement(expression)
# pylint: disable=redefined-builtin, invalid-name
def variable(type, id, rhs): def variable(type, id, rhs):
lhs = RawExpression(u'{} {}'.format(type if not SIMPLIFY else u'auto', id)) lhs = RawExpression(u'{} {}'.format(type if not SIMPLIFY else u'auto', id))
rhs = safe_exp(rhs) rhs = safe_exp(rhs)

View file

@ -13,7 +13,7 @@ _LOGGER = logging.getLogger(__name__)
def initialize(config, subscriptions, on_message, username, password, client_id): def initialize(config, subscriptions, on_message, username, password, client_id):
def on_connect(client, userdata, flags, rc): def on_connect(client, userdata, flags, return_code):
for topic in subscriptions: for topic in subscriptions:
client.subscribe(topic) client.subscribe(topic)
@ -47,8 +47,8 @@ def show_logs(config, topic=None, username=None, password=None, client_id=None):
_LOGGER.info(u"Starting log output from %s", topic) _LOGGER.info(u"Starting log output from %s", topic)
def on_message(client, userdata, msg): def on_message(client, userdata, msg):
t = datetime.now().time().strftime(u'[%H:%M:%S] ') time = datetime.now().time().strftime(u'[%H:%M:%S] ')
print(t + msg.payload) print(time + msg.payload)
return initialize(config, [topic], on_message, username, password, client_id) return initialize(config, [topic], on_message, username, password, client_id)
@ -58,7 +58,7 @@ def clear_topic(config, topic, username=None, password=None, client_id=None):
discovery_prefix = config[CONF_MQTT].get(CONF_DISCOVERY_PREFIX, u'homeassistant') discovery_prefix = config[CONF_MQTT].get(CONF_DISCOVERY_PREFIX, u'homeassistant')
name = config[CONF_ESPHOMEYAML][CONF_NAME] name = config[CONF_ESPHOMEYAML][CONF_NAME]
topic = u'{}/+/{}/#'.format(discovery_prefix, name) topic = u'{}/+/{}/#'.format(discovery_prefix, name)
_LOGGER.info(u"Clearing messages from {}".format(topic)) _LOGGER.info(u"Clearing messages from %s", topic)
def on_message(client, userdata, msg): def on_message(client, userdata, msg):
if not msg.payload: if not msg.payload:

View file

@ -101,16 +101,16 @@ def _validate_gpio_pin(value):
if value < 0 or value > 39: if value < 0 or value > 39:
raise vol.Invalid(u"ESP32: Invalid pin number: {}".format(value)) raise vol.Invalid(u"ESP32: Invalid pin number: {}".format(value))
if 6 <= value <= 11: if 6 <= value <= 11:
_LOGGER.warning(u"ESP32: Pin {} (6-11) might already be used by the " _LOGGER.warning(u"ESP32: Pin %s (6-11) might already be used by the "
u"flash interface. Be warned.".format(value)) u"flash interface. Be warned.", value)
if value in (20, 24, 28, 29, 30, 31): if value in (20, 24, 28, 29, 30, 31):
_LOGGER.warning(u"ESP32: Pin {} (20, 24, 28-31) can usually not be used. " _LOGGER.warning(u"ESP32: Pin %s (20, 24, 28-31) can usually not be used. "
u"Be warned.".format(value)) u"Be warned.", value)
return value return value
elif cv.ESP_PLATFORM == ESP_PLATFORM_ESP8266: elif cv.ESP_PLATFORM == ESP_PLATFORM_ESP8266:
if 6 <= value <= 11: if 6 <= value <= 11:
_LOGGER.warning(u"ESP8266: Pin {} (6-11) might already be used by the " _LOGGER.warning(u"ESP8266: Pin %s (6-11) might already be used by the "
u"flash interface. Be warned.".format(value)) u"flash interface. Be warned.", value)
if value < 0 or value > 17: if value < 0 or value > 17:
raise vol.Invalid(u"ESP8266: Invalid pin number: {}".format(value)) raise vol.Invalid(u"ESP8266: Invalid pin number: {}".format(value))
return value return value
@ -153,6 +153,7 @@ def analog_pin(value):
raise vol.Invalid(u"Invalid ESP platform.") raise vol.Invalid(u"Invalid ESP platform.")
# pylint: disable=invalid-name
input_output_pin = vol.All(input_pin, output_pin) input_output_pin = vol.All(input_pin, output_pin)
gpio_pin = vol.Any(input_pin, output_pin) gpio_pin = vol.Any(input_pin, output_pin)
PIN_MODES_ESP8266 = [ PIN_MODES_ESP8266 = [

View file

@ -2,49 +2,51 @@ from __future__ import print_function
import codecs import codecs
import os import os
from time import sleep
import unicodedata import unicodedata
from time import sleep
import voluptuous as vol import voluptuous as vol
import esphomeyaml.config_validation as cv import esphomeyaml.config_validation as cv
from esphomeyaml.components import mqtt from esphomeyaml.components import mqtt
from esphomeyaml.const import ESP_PLATFORMS, ESP_PLATFORM_ESP32, ESP_BOARDS_FOR_PLATFORM from esphomeyaml.const import ESP_BOARDS_FOR_PLATFORM, ESP_PLATFORMS, ESP_PLATFORM_ESP32
from esphomeyaml.helpers import color from esphomeyaml.helpers import color
CORE_BIG = """ _____ ____ _____ ______
# pylint: disable=anomalous-backslash-in-string
CORE_BIG = """ _____ ____ _____ ______
/ ____/ __ \| __ \| ____| / ____/ __ \| __ \| ____|
| | | | | | |__) | |__ | | | | | | |__) | |__
| | | | | | _ /| __| | | | | | | _ /| __|
| |___| |__| | | \ \| |____ | |___| |__| | | \ \| |____
\_____\____/|_| \_\______| \_____\____/|_| \_\______|
""" """
ESP_BIG = """ ______ _____ _____ ESP_BIG = """ ______ _____ _____
| ____|/ ____| __ \ | ____|/ ____| __ \\
| |__ | (___ | |__) | | |__ | (___ | |__) |
| __| \___ \| ___/ | __| \___ \| ___/
| |____ ____) | | | |____ ____) | |
|______|_____/|_| |______|_____/|_|
""" """
WIFI_BIG = """ __ ___ ______ _ WIFI_BIG = """ __ ___ ______ _
\ \ / (_) ____(_) \ \ / (_) ____(_)
\ \ /\ / / _| |__ _ \ \ /\ / / _| |__ _
\ \/ \/ / | | __| | | \ \/ \/ / | | __| | |
\ /\ / | | | | | \ /\ / | | | | |
\/ \/ |_|_| |_| \/ \/ |_|_| |_|
""" """
MQTT_BIG = """ __ __ ____ _______ _______ MQTT_BIG = """ __ __ ____ _______ _______
| \/ |/ __ \__ __|__ __| | \/ |/ __ \__ __|__ __|
| \ / | | | | | | | | | \ / | | | | | | | |
| |\/| | | | | | | | | | |\/| | | | | | | | |
| | | | |__| | | | | | | | | | |__| | | | | |
|_| |_|\___\_\ |_| |_| |_| |_|\___\_\ |_| |_|
""" """
OTA_BIG = """ ____ _______ OTA_BIG = """ ____ _______
/ __ \__ __|/\ / __ \__ __|/\\
| | | | | | / \ | | | | | | / \\
| | | | | | / /\ \ | | | | | | / /\ \\
| |__| | | |/ ____ \ | |__| | | |/ ____ \\
\____/ |_/_/ \_\\ \____/ |_/_/ \_\\
""" """
@ -85,8 +87,8 @@ def default_input(text, default):
# From https://stackoverflow.com/a/518232/8924614 # From https://stackoverflow.com/a/518232/8924614
def strip_accents(s): def strip_accents(string):
return u''.join(c for c in unicodedata.normalize('NFD', unicode(s)) return u''.join(c for c in unicodedata.normalize('NFD', unicode(string))
if unicodedata.category(c) != 'Mn') if unicodedata.category(c) != 'Mn')
@ -190,7 +192,7 @@ def wizard(path):
print() print()
sleep(1) sleep(1)
print("First, what's the " + color('green', 'SSID') + " (the name) of the WiFi network {} " print("First, what's the " + color('green', 'SSID') + " (the name) of the WiFi network {} "
"I should connect to?".format(name)) "I should connect to?".format(name))
sleep(1.5) sleep(1.5)
print("For example \"{}\".".format(color('bold_white', "Abraham Linksys"))) print("For example \"{}\".".format(color('bold_white', "Abraham Linksys")))
while True: while True:
@ -200,7 +202,7 @@ def wizard(path):
break break
except vol.Invalid: except vol.Invalid:
print(color('red', "Unfortunately, \"{}\" doesn't seem to be a valid SSID. " print(color('red', "Unfortunately, \"{}\" doesn't seem to be a valid SSID. "
"Please try again.".format(ssid))) "Please try again.".format(ssid)))
print() print()
sleep(1) sleep(1)
@ -230,9 +232,9 @@ def wizard(path):
try: try:
broker = mqtt.validate_broker(broker) broker = mqtt.validate_broker(broker)
break break
except vol.Invalid as e: except vol.Invalid as err:
print(color('red', "The broker address \"{}\" seems to be invalid: {} :(".format( print(color('red', "The broker address \"{}\" seems to be invalid: {} :(".format(
broker, e))) broker, err)))
print("Please try again.") print("Please try again.")
print() print()
sleep(1) sleep(1)
@ -271,8 +273,8 @@ def wizard(path):
else: else:
config += "ota:\n" config += "ota:\n"
with codecs.open(path, 'w') as f: with codecs.open(path, 'w') as f_handle:
f.write(config) f_handle.write(config)
print() print()
print(color('cyan', "DONE! I've now written a new configuration file to ") + print(color('cyan', "DONE! I've now written a new configuration file to ") +

View file

@ -35,9 +35,9 @@ void loop() {
INI_BASE_FORMAT = (u"""; Auto generated code by esphomeyaml INI_BASE_FORMAT = (u"""; Auto generated code by esphomeyaml
[common] [common]
lib_deps = lib_deps =
build_flags = build_flags =
upload_flags = upload_flags =
; ===== DO NOT EDIT ANYTHING BELOW THIS LINE ===== ; ===== DO NOT EDIT ANYTHING BELOW THIS LINE =====
""", u""" """, u"""
@ -63,7 +63,7 @@ PLATFORM_TO_PLATFORMIO = {
def get_ini_content(config): def get_ini_content(config):
d = { options = {
u'env': config[CONF_ESPHOMEYAML][CONF_NAME], u'env': config[CONF_ESPHOMEYAML][CONF_NAME],
u'platform': PLATFORM_TO_PLATFORMIO[config[CONF_ESPHOMEYAML][CONF_PLATFORM]], u'platform': PLATFORM_TO_PLATFORMIO[config[CONF_ESPHOMEYAML][CONF_PLATFORM]],
u'board': config[CONF_ESPHOMEYAML][CONF_BOARD], u'board': config[CONF_ESPHOMEYAML][CONF_BOARD],
@ -73,8 +73,8 @@ def get_ini_content(config):
if CONF_LOGGER in config: if CONF_LOGGER in config:
build_flags = get_component(CONF_LOGGER).get_build_flags(config[CONF_LOGGER]) build_flags = get_component(CONF_LOGGER).get_build_flags(config[CONF_LOGGER])
if build_flags: if build_flags:
d[u'build_flags'] = u'\n ' + build_flags options[u'build_flags'] = u'\n ' + build_flags
return INI_CONTENT_FORMAT.format(**d) return INI_CONTENT_FORMAT.format(**options)
def mkdir_p(path): def mkdir_p(path):
@ -109,8 +109,8 @@ def find_begin_end(text, begin_s, end_s):
def write_platformio_ini(content, path): def write_platformio_ini(content, path):
if os.path.isfile(path): if os.path.isfile(path):
try: try:
with codecs.open(path, 'r', encoding='utf-8') as f: with codecs.open(path, 'r', encoding='utf-8') as f_handle:
text = f.read() text = f_handle.read()
except OSError: except OSError:
raise ESPHomeYAMLError(u"Could not read ini file at {}".format(path)) raise ESPHomeYAMLError(u"Could not read ini file at {}".format(path))
prev_file = text prev_file = text
@ -123,15 +123,15 @@ def write_platformio_ini(content, path):
content + INI_AUTO_GENERATE_END + content_format[1] content + INI_AUTO_GENERATE_END + content_format[1]
if prev_file == full_file: if prev_file == full_file:
return return
with codecs.open(path, mode='w+', encoding='utf-8') as f: with codecs.open(path, mode='w+', encoding='utf-8') as f_handle:
f.write(full_file) f_handle.write(full_file)
def write_cpp(code_s, path): def write_cpp(code_s, path):
if os.path.isfile(path): if os.path.isfile(path):
try: try:
with codecs.open(path, 'r', encoding='utf-8') as f: with codecs.open(path, 'r', encoding='utf-8') as f_handle:
text = f.read() text = f_handle.read()
except OSError: except OSError:
raise ESPHomeYAMLError(u"Could not read C++ file at {}".format(path)) raise ESPHomeYAMLError(u"Could not read C++ file at {}".format(path))
prev_file = text prev_file = text
@ -145,5 +145,5 @@ def write_cpp(code_s, path):
code_s + CPP_AUTO_GENERATE_END + code_format[1] code_s + CPP_AUTO_GENERATE_END + code_format[1]
if prev_file == full_file: if prev_file == full_file:
return return
with codecs.open(path, 'w+', encoding='utf-8') as f: with codecs.open(path, 'w+', encoding='utf-8') as f_handle:
f.write(full_file) f_handle.write(full_file)

22
pylintrc Normal file
View file

@ -0,0 +1,22 @@
[MASTER]
reports=no
disable=
missing-docstring,
fixme,
unused-argument,
global-statement,
too-few-public-methods,
too-many-locals,
too-many-ancestors,
too-many-branches,
too-many-statements,
too-many-arguments,
too-many-return-statements,
duplicate-code,
additional-builtins=
unicode,
long,
raw_input

View file

@ -1,2 +1,6 @@
[metadata] [metadata]
description-file = README.md description-file = README.md
[flake8]
max-line-length = 120
builtins = unicode, long, raw_input