esphome/esphomeyaml/writer.py

266 lines
9.3 KiB
Python
Raw Permalink Normal View History

2018-04-07 01:23:03 +02:00
from __future__ import print_function
import codecs
import errno
2018-09-23 18:58:41 +02:00
import json
2018-04-07 01:23:03 +02:00
import os
2018-05-06 15:56:12 +02:00
from esphomeyaml import core
from esphomeyaml.config import iter_components
from esphomeyaml.const import ARDUINO_VERSION_ESP32_DEV, CONF_ARDUINO_VERSION, CONF_BOARD, \
CONF_BOARD_FLASH_MODE, CONF_ESPHOMELIB_VERSION, CONF_ESPHOMEYAML, CONF_LOCAL, CONF_NAME, \
CONF_USE_CUSTOM_CODE, ESP_PLATFORM_ESP32
2018-04-07 01:23:03 +02:00
from esphomeyaml.core import ESPHomeYAMLError
2018-09-23 18:58:41 +02:00
from esphomeyaml.core_config import VERSION_REGEX
from esphomeyaml.helpers import relative_path
2018-04-07 01:23:03 +02:00
CPP_AUTO_GENERATE_BEGIN = u'// ========== AUTO GENERATED CODE BEGIN ==========='
CPP_AUTO_GENERATE_END = u'// =========== AUTO GENERATED CODE END ============'
INI_AUTO_GENERATE_BEGIN = u'; ========== AUTO GENERATED CODE BEGIN ==========='
INI_AUTO_GENERATE_END = u'; =========== AUTO GENERATED CODE END ============'
CPP_BASE_FORMAT = (u"""// Auto generated code by esphomeyaml
#include "esphomelib/application.h"
using namespace esphomelib;
void setup() {
// ===== DO NOT EDIT ANYTHING BELOW THIS LINE =====
""", u"""
// ========= YOU CAN EDIT AFTER THIS LINE =========
App.setup();
}
void loop() {
App.loop();
delay(16);
2018-04-07 01:23:03 +02:00
}
""")
INI_BASE_FORMAT = (u"""; Auto generated code by esphomeyaml
[common]
lib_deps =
build_flags =
upload_flags =
2018-04-07 01:23:03 +02:00
; ===== DO NOT EDIT ANYTHING BELOW THIS LINE =====
""", u"""
; ========= YOU CAN EDIT AFTER THIS LINE =========
""")
INI_CONTENT_FORMAT = u"""[env:{env}]
platform = {platform}
board = {board}
framework = arduino
lib_deps =
2018-05-06 15:56:12 +02:00
{lib_deps}
2018-04-07 01:23:03 +02:00
${{common.lib_deps}}
build_flags =
{build_flags}
2018-04-07 01:23:03 +02:00
${{common.build_flags}}
upload_speed = {upload_speed}
2018-04-07 01:23:03 +02:00
"""
UPLOAD_SPEED_OVERRIDE = {
'esp210': 57600,
}
2018-04-07 01:23:03 +02:00
def get_build_flags(config, key):
build_flags = set()
for _, component, conf in iter_components(config):
if not hasattr(component, key):
continue
2018-05-06 15:56:12 +02:00
flags = getattr(component, key)
if callable(flags):
flags = flags(conf)
if flags is None:
continue
if isinstance(flags, (str, unicode)):
flags = [flags]
build_flags |= set(flags)
return build_flags
2018-09-23 18:58:41 +02:00
def get_ini_content(config, path):
version_specific_settings = determine_platformio_version_settings()
options = {
2018-04-07 01:23:03 +02:00
u'env': config[CONF_ESPHOMEYAML][CONF_NAME],
2018-09-23 18:58:41 +02:00
u'platform': config[CONF_ESPHOMEYAML][CONF_ARDUINO_VERSION],
2018-04-07 01:23:03 +02:00
u'board': config[CONF_ESPHOMEYAML][CONF_BOARD],
u'build_flags': u'',
u'upload_speed': UPLOAD_SPEED_OVERRIDE.get(core.BOARD, 115200),
2018-04-07 01:23:03 +02:00
}
build_flags = set()
2018-09-23 18:58:41 +02:00
if not config[CONF_ESPHOMEYAML][CONF_USE_CUSTOM_CODE]:
build_flags |= get_build_flags(config, 'build_flags')
2018-05-06 15:56:12 +02:00
build_flags |= get_build_flags(config, 'BUILD_FLAGS')
build_flags.add(u"-DESPHOMEYAML_USE")
build_flags |= get_build_flags(config, 'required_build_flags')
2018-05-14 11:50:56 +02:00
build_flags |= get_build_flags(config, 'REQUIRED_BUILD_FLAGS')
# avoid changing build flags order
build_flags = sorted(list(build_flags))
if build_flags:
options[u'build_flags'] = u'\n '.join(build_flags)
2018-05-06 15:56:12 +02:00
lib_deps = set()
2018-09-23 18:58:41 +02:00
lib_version = config[CONF_ESPHOMEYAML][CONF_ESPHOMELIB_VERSION]
lib_path = os.path.join(path, 'lib')
dst_path = os.path.join(lib_path, 'esphomelib')
if isinstance(lib_version, (str, unicode)):
lib_deps.add(lib_version)
if os.path.islink(dst_path):
os.unlink(dst_path)
else:
src_path = relative_path(lib_version[CONF_LOCAL])
do_write = True
if os.path.islink(dst_path):
old_path = os.path.join(os.readlink(dst_path), lib_path)
if old_path != lib_path:
os.unlink(dst_path)
else:
do_write = False
if do_write:
mkdir_p(lib_path)
os.symlink(src_path, dst_path)
# Manually add lib_deps because platformio seems to ignore them inside libs/
library_json_path = os.path.join(src_path, 'library.json')
with codecs.open(library_json_path, 'r', encoding='utf-8') as f_handle:
library_json_text = f_handle.read()
library_json = json.loads(library_json_text)
for dep in library_json.get('dependencies', []):
if 'version' in dep and VERSION_REGEX.match(dep['version']) is not None:
lib_deps.add(dep['name'] + '@' + dep['version'])
else:
lib_deps.add(dep['version'])
2018-05-14 11:50:56 +02:00
lib_deps |= get_build_flags(config, 'LIB_DEPS')
lib_deps |= get_build_flags(config, 'lib_deps')
2018-05-06 15:56:12 +02:00
if core.ESP_PLATFORM == ESP_PLATFORM_ESP32:
lib_deps |= {
2018-05-14 11:50:56 +02:00
'Preferences', # Preferences helper
2018-05-06 15:56:12 +02:00
}
2018-09-23 18:58:41 +02:00
# Manual fix for AsyncTCP
if config[CONF_ESPHOMEYAML].get(CONF_ARDUINO_VERSION) == ARDUINO_VERSION_ESP32_DEV:
lib_deps.add('https://github.com/me-no-dev/AsyncTCP.git#idf-update')
2018-05-14 11:50:56 +02:00
# avoid changing build flags order
lib_deps = sorted(x for x in lib_deps if x)
if lib_deps:
options[u'lib_deps'] = u'\n '.join(lib_deps)
2018-05-06 15:56:12 +02:00
2018-05-16 19:45:33 +02:00
content = INI_CONTENT_FORMAT.format(**options)
if CONF_BOARD_FLASH_MODE in config[CONF_ESPHOMEYAML]:
flash_mode_key = version_specific_settings['flash_mode_key']
2018-05-16 19:45:33 +02:00
flash_mode = config[CONF_ESPHOMEYAML][CONF_BOARD_FLASH_MODE]
content += "{} = {}\n".format(flash_mode_key, flash_mode)
2018-05-16 19:45:33 +02:00
return content
2018-04-07 01:23:03 +02:00
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def find_begin_end(text, begin_s, end_s):
begin_index = text.find(begin_s)
if begin_index == -1:
raise ESPHomeYAMLError(u"Could not find auto generated code begin in file, either"
u"delete the main sketch file or insert the comment again.")
if text.find(begin_s, begin_index + 1) != -1:
raise ESPHomeYAMLError(u"Found multiple auto generate code begins, don't know"
u"which to chose, please remove one of them.")
end_index = text.find(end_s)
if end_index == -1:
raise ESPHomeYAMLError(u"Could not find auto generated code end in file, either"
u"delete the main sketch file or insert the comment again.")
if text.find(end_s, end_index + 1) != -1:
raise ESPHomeYAMLError(u"Found multiple auto generate code endings, don't know"
u"which to chose, please remove one of them.")
return text[:begin_index], text[(end_index + len(end_s)):]
def write_platformio_ini(content, path):
if os.path.isfile(path):
try:
with codecs.open(path, 'r', encoding='utf-8') as f_handle:
text = f_handle.read()
2018-04-07 01:23:03 +02:00
except OSError:
raise ESPHomeYAMLError(u"Could not read ini file at {}".format(path))
prev_file = text
content_format = find_begin_end(text, INI_AUTO_GENERATE_BEGIN, INI_AUTO_GENERATE_END)
else:
prev_file = None
mkdir_p(os.path.dirname(path))
content_format = INI_BASE_FORMAT
full_file = content_format[0] + INI_AUTO_GENERATE_BEGIN + '\n' + \
2018-05-21 15:07:17 +02:00
content + INI_AUTO_GENERATE_END + content_format[1]
2018-04-07 01:23:03 +02:00
if prev_file == full_file:
return
with codecs.open(path, mode='w+', encoding='utf-8') as f_handle:
f_handle.write(full_file)
2018-04-07 01:23:03 +02:00
2018-06-12 21:18:04 +02:00
def write_platformio_project(config, path):
platformio_ini = os.path.join(path, 'platformio.ini')
2018-09-23 18:58:41 +02:00
content = get_ini_content(config, path)
2018-08-13 19:11:33 +02:00
if 'esp32_ble_beacon' in config or 'esp32_ble_tracker' in config:
2018-06-12 21:18:04 +02:00
content += 'board_build.partitions = partitions.csv\n'
partitions_csv = os.path.join(path, 'partitions.csv')
if not os.path.isfile(partitions_csv):
2018-08-13 19:11:33 +02:00
mkdir_p(path)
2018-06-12 21:18:04 +02:00
with open(partitions_csv, "w") as f:
f.write("nvs, data, nvs, 0x009000, 0x005000,\n")
f.write("otadata, data, ota, 0x00e000, 0x002000,\n")
f.write("app0, app, ota_0, 0x010000, 0x190000,\n")
f.write("app1, app, ota_1, 0x200000, 0x190000,\n")
f.write("eeprom, data, 0x99, 0x390000, 0x001000,\n")
f.write("spiffs, data, spiffs, 0x391000, 0x00F000\n")
write_platformio_ini(content, platformio_ini)
2018-04-07 01:23:03 +02:00
def write_cpp(code_s, path):
if os.path.isfile(path):
try:
with codecs.open(path, 'r', encoding='utf-8') as f_handle:
text = f_handle.read()
2018-04-07 01:23:03 +02:00
except OSError:
raise ESPHomeYAMLError(u"Could not read C++ file at {}".format(path))
prev_file = text
code_format = find_begin_end(text, CPP_AUTO_GENERATE_BEGIN, CPP_AUTO_GENERATE_END)
else:
prev_file = None
mkdir_p(os.path.dirname(path))
code_format = CPP_BASE_FORMAT
full_file = code_format[0] + CPP_AUTO_GENERATE_BEGIN + '\n' + \
2018-05-21 15:07:17 +02:00
code_s + CPP_AUTO_GENERATE_END + code_format[1]
2018-04-07 01:23:03 +02:00
if prev_file == full_file:
return
with codecs.open(path, 'w+', encoding='utf-8') as f_handle:
f_handle.write(full_file)
def determine_platformio_version_settings():
import platformio
settings = {}
if platformio.VERSION < (3, 5, 3):
settings['flash_mode_key'] = 'board_flash_mode'
else:
settings['flash_mode_key'] = 'board_build.flash_mode'
return settings