Initial internationalization

This commit is contained in:
fvanroie 2021-02-07 06:17:09 +01:00
parent 3618305d42
commit 8e0b379ba9
25 changed files with 651 additions and 401 deletions

View File

@ -188,7 +188,7 @@ bool IRAM_ATTR drv_touch_read(lv_indev_drv_t * indev_driver, lv_indev_data_t * d
return false; return false;
} }
void IRAM_ATTR drv_touch_loop() void drv_touch_loop()
{ {
#if TOUCH_DRIVER == 911 #if TOUCH_DRIVER == 911
GT911_loop(); GT911_loop();

View File

@ -103,7 +103,7 @@ lv_font_t * hasp_get_font(uint8_t fontid)
/** /**
* Check if sleep state needs to be updated * Check if sleep state needs to be updated
*/ */
bool IRAM_ATTR hasp_update_sleep_state() bool hasp_update_sleep_state()
{ {
uint32_t idle = lv_disp_get_inactive_time(NULL); uint32_t idle = lv_disp_get_inactive_time(NULL);
@ -522,11 +522,11 @@ void haspClearPage(uint16_t pageid)
{ {
lv_obj_t * page = get_page_obj(pageid); lv_obj_t * page = get_page_obj(pageid);
if(!page || (pageid > HASP_NUM_PAGES)) { if(!page || (pageid > HASP_NUM_PAGES)) {
Log.warning(TAG_HASP, F("Invalid page %u"), pageid); Log.warning(TAG_HASP, F(D_HASP_INVALID_PAGE), pageid);
} else if(page == lv_layer_sys() /*|| page == lv_layer_top()*/) { } else if(page == lv_layer_sys() /*|| page == lv_layer_top()*/) {
Log.warning(TAG_HASP, F("Cannot clear system layer")); Log.warning(TAG_HASP, F(D_HASP_INVALID_LAYER));
} else { } else {
Log.notice(TAG_HASP, F("Clearing page %u"), pageid); Log.notice(TAG_HASP, F(D_HASP_CLEAR_PAGE), pageid);
lv_obj_clean(page); lv_obj_clean(page);
} }
} }
@ -540,9 +540,9 @@ void haspSetPage(uint8_t pageid)
{ {
lv_obj_t * page = get_page_obj(pageid); lv_obj_t * page = get_page_obj(pageid);
if(!page || pageid == 0 || pageid > HASP_NUM_PAGES) { if(!page || pageid == 0 || pageid > HASP_NUM_PAGES) {
Log.warning(TAG_HASP, F("Invalid page %u"), pageid); Log.warning(TAG_HASP, F(D_HASP_INVALID_PAGE), pageid);
} else { } else {
Log.notice(TAG_HASP, F("Changing page to %u"), pageid); Log.notice(TAG_HASP, F(D_HASP_CHANGE_PAGE), pageid);
current_page = pageid; current_page = pageid;
lv_scr_load(page); lv_scr_load(page);
hasp_object_tree(page, pageid, 0); hasp_object_tree(page, pageid, 0);

View File

@ -70,7 +70,7 @@ bool haspSetConfig(const JsonObject & settings);
lv_font_t * hasp_get_font(uint8_t fontid); lv_font_t * hasp_get_font(uint8_t fontid);
bool IRAM_ATTR hasp_update_sleep_state(); bool hasp_update_sleep_state();
void hasp_get_sleep_time(uint16_t & short_time, uint16_t & long_time); void hasp_get_sleep_time(uint16_t & short_time, uint16_t & long_time);
void hasp_set_sleep_time(uint16_t short_time, uint16_t long_time); void hasp_set_sleep_time(uint16_t short_time, uint16_t long_time);

View File

@ -371,7 +371,7 @@ static void my_btnmatrix_map_create(lv_obj_t * obj, const char * payload)
Log.verbose(TAG_ATTR, F("%s %d lbl addr: %x"), __FILE__, __LINE__, buffer_addr); Log.verbose(TAG_ATTR, F("%s %d lbl addr: %x"), __FILE__, __LINE__, buffer_addr);
for(JsonVariant btn : arr) { for(JsonVariant btn : arr) {
size_t len = btn.as<String>().length() + 1; size_t len = btn.as<String>().length() + 1;
Log.verbose(TAG_ATTR, F(" * Adding button: %s (%d bytes) %x"), btn.as<String>().c_str(), len, Log.verbose(TAG_ATTR, F(D_BULLET"Adding button: %s (%d bytes) %x"), btn.as<String>().c_str(), len,
buffer_addr + pos); buffer_addr + pos);
memccpy(buffer_addr + pos, btn.as<String>().c_str(), 0, len); // Copy the label text into the buffer memccpy(buffer_addr + pos, btn.as<String>().c_str(), 0, len); // Copy the label text into the buffer
map_data_str[index++] = buffer_addr + pos; // save pointer to the label in the array map_data_str[index++] = buffer_addr + pos; // save pointer to the label in the array
@ -423,7 +423,7 @@ static void line_set_points(lv_obj_t * obj, const char * payload)
JsonArray point = v.as<JsonArray>(); // Parse point JsonArray point = v.as<JsonArray>(); // Parse point
point_arr[index].x = point[0].as<int16_t>(); point_arr[index].x = point[0].as<int16_t>();
point_arr[index].y = point[1].as<int16_t>(); point_arr[index].y = point[1].as<int16_t>();
Log.verbose(TAG_ATTR, F(" * Adding point %d: %d,%d"), index, point_arr[index].x, point_arr[index].y); Log.verbose(TAG_ATTR, F(D_BULLET"Adding point %d: %d,%d"), index, point_arr[index].x, point_arr[index].y);
index++; index++;
} }
@ -1188,7 +1188,7 @@ static void hasp_local_style_attr(lv_obj_t * obj, const char * attr_p, uint16_t
/* Transition attributes */ /* Transition attributes */
// Todo // Todo
} }
Log.warning(TAG_ATTR, F("Unknown property %s"), attr_p); Log.warning(TAG_ATTR, F(D_ATTRIBUTE_UNKNOWN), attr_p);
} }
static void hasp_process_arc_attribute(lv_obj_t * obj, const char * attr_p, uint16_t attr_hash, const char * payload, static void hasp_process_arc_attribute(lv_obj_t * obj, const char * attr_p, uint16_t attr_hash, const char * payload,
@ -1232,7 +1232,7 @@ static void hasp_process_arc_attribute(lv_obj_t * obj, const char * attr_p, uint
return (update) ? lv_arc_set_end_angle(obj, val) : hasp_out_int(obj, attr, lv_arc_get_angle_end(obj)); return (update) ? lv_arc_set_end_angle(obj, val) : hasp_out_int(obj, attr, lv_arc_get_angle_end(obj));
} }
Log.warning(TAG_ATTR, F("Unknown property %s"), attr_p); Log.warning(TAG_ATTR, F(D_ATTRIBUTE_UNKNOWN), attr_p);
} }
static void hasp_process_lmeter_attribute(lv_obj_t * obj, const char * attr_p, uint16_t attr_hash, const char * payload, static void hasp_process_lmeter_attribute(lv_obj_t * obj, const char * attr_p, uint16_t attr_hash, const char * payload,
@ -1264,7 +1264,7 @@ static void hasp_process_lmeter_attribute(lv_obj_t * obj, const char * attr_p, u
return (update) ? lv_linemeter_set_scale(obj, val, line_count) : hasp_out_int(obj, attr, angle); return (update) ? lv_linemeter_set_scale(obj, val, line_count) : hasp_out_int(obj, attr, angle);
} }
Log.warning(TAG_ATTR, F("Unknown property %s"), attr_p); Log.warning(TAG_ATTR, F(D_ATTRIBUTE_UNKNOWN), attr_p);
} }
static void hasp_process_gauge_attribute(lv_obj_t * obj, const char * attr_p, uint16_t attr_hash, const char * payload, static void hasp_process_gauge_attribute(lv_obj_t * obj, const char * attr_p, uint16_t attr_hash, const char * payload,
@ -1321,7 +1321,7 @@ static void hasp_process_gauge_attribute(lv_obj_t * obj, const char * attr_p, ui
return; return;
} }
Log.warning(TAG_ATTR, F("Unknown property %s"), attr_p); Log.warning(TAG_ATTR, F(D_ATTRIBUTE_UNKNOWN), attr_p);
} }
// ##################### Common Attributes ######################################################## // ##################### Common Attributes ########################################################
@ -1365,7 +1365,7 @@ static void hasp_process_obj_attribute_txt(lv_obj_t * obj, const char * attr, co
} }
#endif #endif
Log.warning(TAG_ATTR, F("Unknown property %s"), attr); Log.warning(TAG_ATTR, F(D_ATTRIBUTE_UNKNOWN), attr);
} }
bool hasp_process_obj_attribute_val(lv_obj_t * obj, const char * attr, const char * payload, bool update) bool hasp_process_obj_attribute_val(lv_obj_t * obj, const char * attr, const char * payload, bool update)
@ -1475,7 +1475,7 @@ static void hasp_process_obj_attribute_range(lv_obj_t * obj, const char * attr,
: hasp_out_int(obj, attr, set_min ? min : max); : hasp_out_int(obj, attr, set_min ? min : max);
} }
Log.warning(TAG_ATTR, F("Unknown property %s"), attr); Log.warning(TAG_ATTR, F(D_ATTRIBUTE_UNKNOWN), attr);
} }
// ##################### Default Attributes ######################################################## // ##################### Default Attributes ########################################################
@ -1491,7 +1491,7 @@ static void hasp_process_obj_attribute_range(lv_obj_t * obj, const char * attr,
void hasp_process_obj_attribute(lv_obj_t * obj, const char * attr_p, const char * payload, bool update) void hasp_process_obj_attribute(lv_obj_t * obj, const char * attr_p, const char * payload, bool update)
{ {
// unsigned long start = millis(); // unsigned long start = millis();
if(!obj) return Log.warning(TAG_ATTR, F("Unknown object")); if(!obj) return Log.warning(TAG_ATTR, F(D_OBJECT_UNKNOWN));
int16_t val = atoi(payload); int16_t val = atoi(payload);
char * attr = (char *)attr_p; char * attr = (char *)attr_p;
@ -1760,21 +1760,21 @@ void hasp_process_obj_attribute(lv_obj_t * obj, const char * attr_p, const char
case ATTR_DELETE: case ATTR_DELETE:
if(!lv_obj_get_parent(obj)) { if(!lv_obj_get_parent(obj)) {
return Log.error(TAG_ATTR, F("Unable to call %s on a page"), attr_p); return Log.error(TAG_ATTR, F(D_ATTRIBUTE_PAGE_METHOD_INVALID), attr_p);
} }
lv_obj_del_async(obj); lv_obj_del_async(obj);
break; // attribute_found break; // attribute_found
case ATTR_TO_FRONT: case ATTR_TO_FRONT:
if(!lv_obj_get_parent(obj)) { if(!lv_obj_get_parent(obj)) {
return Log.error(TAG_ATTR, F("Unable to call %s on a page"), attr_p); return Log.error(TAG_ATTR, F(D_ATTRIBUTE_PAGE_METHOD_INVALID), attr_p);
} }
lv_obj_move_foreground(obj); lv_obj_move_foreground(obj);
break; // attribute_found break; // attribute_found
case ATTR_TO_BACK: case ATTR_TO_BACK:
if(!lv_obj_get_parent(obj)) { if(!lv_obj_get_parent(obj)) {
return Log.error(TAG_ATTR, F("Unable to call %s on a page"), attr_p); return Log.error(TAG_ATTR, F(D_ATTRIBUTE_PAGE_METHOD_INVALID), attr_p);
} }
lv_obj_move_background(obj); lv_obj_move_background(obj);
break; // attribute_found break; // attribute_found
@ -1789,5 +1789,5 @@ attribute_found:
return; return;
attribute_not_found: attribute_not_found:
Log.warning(TAG_ATTR, F("Unknown property %s (%d)"), attr_p, attr_hash); Log.warning(TAG_ATTR, F(D_ATTRIBUTE_UNKNOWN " (%d)"), attr_p, attr_hash);
} }

View File

@ -87,7 +87,7 @@ bool dispatch_factory_reset()
void dispatch_json_error(uint8_t tag, DeserializationError & jsonError) void dispatch_json_error(uint8_t tag, DeserializationError & jsonError)
{ {
Log.error(tag, F("JSON parsing failed: %s"), jsonError.c_str()); Log.error(tag, F(D_JSON_FAILED " %s"), jsonError.c_str());
} }
// p[x].b[y].attr=value // p[x].b[y].attr=value
@ -175,7 +175,7 @@ void dispatch_command(const char * topic, const char * payload)
#if HASP_USE_WIFI > 0 #if HASP_USE_WIFI > 0
} else if(!strcmp_P(topic, F_CONFIG_SSID) || !strcmp_P(topic, F_CONFIG_PASS)) { } else if(!strcmp_P(topic, F_CONFIG_SSID) || !strcmp_P(topic, F_CONFIG_PASS)) {
DynamicJsonDocument settings(45); StaticJsonDocument<64> settings;
settings[topic] = payload; settings[topic] = payload;
wifiSetConfig(settings.as<JsonObject>()); wifiSetConfig(settings.as<JsonObject>());
#endif // HASP_USE_WIFI #endif // HASP_USE_WIFI
@ -188,7 +188,7 @@ void dispatch_command(const char * topic, const char * payload)
// memset(item, 0, sizeof(item)); // memset(item, 0, sizeof(item));
// strncpy(item, topic + 4, 4); // strncpy(item, topic + 4, 4);
DynamicJsonDocument settings(45); StaticJsonDocument<64> settings;
settings[topic + 4] = payload; settings[topic + 4] = payload;
mqttSetConfig(settings.as<JsonObject>()); mqttSetConfig(settings.as<JsonObject>());
#endif // HASP_USE_MQTT #endif // HASP_USE_MQTT
@ -199,7 +199,7 @@ void dispatch_command(const char * topic, const char * payload)
if(strlen(payload) == 0) { if(strlen(payload) == 0) {
// dispatch_text_line(topic); // Could cause an infinite loop! // dispatch_text_line(topic); // Could cause an infinite loop!
} }
Log.warning(TAG_MSGR, F("Command '%s' not found => %s"), topic, payload); Log.warning(TAG_MSGR, F(D_DISPATCH_COMMAND_NOT_FOUND " => %s"), topic, payload);
} }
} }
@ -258,11 +258,11 @@ void dispatch_text_line(const char * cmnd)
memcpy(topic, cmnd, sizeof(topic) - 1); memcpy(topic, cmnd, sizeof(topic) - 1);
// topic is before '=', payload is after '=' position // topic is before '=', payload is after '=' position
Log.notice(TAG_MSGR, F("%s = %s"), topic, cmnd + pos + 1); Log.notice(TAG_MSGR, F("%s=%s"), topic, cmnd + pos + 1);
dispatch_topic_payload(topic, cmnd + pos + 1); dispatch_topic_payload(topic, cmnd + pos + 1);
} else { } else {
char empty_payload[1] = {0}; char empty_payload[1] = {0};
Log.notice(TAG_MSGR, F("%s = %s"), cmnd, empty_payload); Log.notice(TAG_MSGR, F("%s=%s"), cmnd, empty_payload);
dispatch_topic_payload(cmnd, empty_payload); dispatch_topic_payload(cmnd, empty_payload);
} }
} }
@ -604,7 +604,7 @@ void dispatch_parse_json(const char *, const char * payload)
dispatch_text_line(json.as<String>().c_str()); dispatch_text_line(json.as<String>().c_str());
} else { } else {
Log.warning(TAG_MSGR, F("Failed to parse incoming JSON command")); Log.warning(TAG_MSGR, F(D_DISPATCH_COMMAND_NOT_FOUND), payload);
} }
} }
@ -617,32 +617,23 @@ void dispatch_parse_jsonl(std::istringstream & stream)
uint8_t savedPage = haspGetPage(); uint8_t savedPage = haspGetPage();
size_t line = 1; size_t line = 1;
DynamicJsonDocument jsonl(MQTT_MAX_PACKET_SIZE / 2 + 128); // max ~256 characters per line DynamicJsonDocument jsonl(MQTT_MAX_PACKET_SIZE / 2 + 128); // max ~256 characters per line
DeserializationError err = deserializeJson(jsonl, stream); DeserializationError jsonError = deserializeJson(jsonl, stream);
stream.setTimeout(25); stream.setTimeout(25);
// guiStop(); // guiStop();
while(err == DeserializationError::Ok) { while(jsonError == DeserializationError::Ok) {
hasp_new_object(jsonl.as<JsonObject>(), savedPage); hasp_new_object(jsonl.as<JsonObject>(), savedPage);
err = deserializeJson(jsonl, stream); jsonError = deserializeJson(jsonl, stream);
line++; line++;
} }
// guiStart(); // guiStart();
/* For debugging pourposes */ /* For debugging pourposes */
if(err == DeserializationError::EmptyInput) { if(jsonError == DeserializationError::EmptyInput) {
Log.trace(TAG_MSGR, F("Jsonl parsed successfully")); Log.trace(TAG_MSGR, F(D_JSONL_SUCCEEDED));
} else if(err == DeserializationError::InvalidInput || err == DeserializationError::IncompleteInput) { } else {
Log.error(TAG_MSGR, F("Jsonl: Invalid Input at object %d"), line); Log.error(TAG_MSGR, F(D_JSONL_FAILED ": %s"), line, jsonError.c_str());
} else if(err == DeserializationError::NoMemory) {
Log.error(TAG_MSGR, F("Jsonl: Object line %d is too long"), line);
} else if(err == DeserializationError::NotSupported) {
Log.error(TAG_MSGR, F("Jsonl: Not Supported at object %d"), line);
} else if(err == DeserializationError::TooDeep) {
Log.error(TAG_MSGR, F("Jsonl: Too Deep at object %d"), line);
} }
} }
@ -680,7 +671,7 @@ void dispatch_page(const char *, const char * page)
} else if(!strcasecmp_P(page, PSTR("next"))) { } else if(!strcasecmp_P(page, PSTR("next"))) {
dispatch_page_next(); dispatch_page_next();
} else { } else {
Log.warning(TAG_MSGR, PSTR("Invalid page %s"), page); Log.warning(TAG_MSGR, PSTR(D_DISPATCH_INVALID_PAGE), page);
} }
return; return;
} }
@ -794,7 +785,7 @@ void dispatch_backlight(const char *, const char * payload)
void dispatch_web_update(const char *, const char * espOtaUrl) void dispatch_web_update(const char *, const char * espOtaUrl)
{ {
#if HASP_USE_OTA > 0 #if HASP_USE_OTA > 0
Log.notice(TAG_MSGR, F("Checking for updates at URL: %s"), espOtaUrl); Log.notice(TAG_MSGR, F(D_OTA_CHECK_UPDATE), espOtaUrl);
otaHttpUpdate(espOtaUrl); otaHttpUpdate(espOtaUrl);
#endif #endif
} }
@ -815,7 +806,7 @@ void dispatch_reboot(bool saveConfig)
wifiStop(); wifiStop();
#endif #endif
Log.verbose(TAG_MSGR, F("-------------------------------------")); Log.verbose(TAG_MSGR, F("-------------------------------------"));
Log.notice(TAG_MSGR, F("HALT: Properly Rebooting the MCU now!")); Log.notice(TAG_MSGR, F(D_DISPATCH_REBOOT));
Serial.flush(); Serial.flush();
halRestartMcu(); halRestartMcu();
} }
@ -904,7 +895,7 @@ void dispatch_factory_reset(const char *, const char *)
static void dispatch_add_command(const char * p_cmdstr, void (*func)(const char *, const char *)) static void dispatch_add_command(const char * p_cmdstr, void (*func)(const char *, const char *))
{ {
if(nCommands >= sizeof(commands) / sizeof(haspCommand_t)) { if(nCommands >= sizeof(commands) / sizeof(haspCommand_t)) {
Log.fatal(TAG_MSGR, F("CMD overflow %d"), nCommands); Log.fatal(TAG_MSGR, F("CMD_OVERFLOW %d"), nCommands);
while(1) { while(1) {
} }
} else { } else {

View File

@ -324,13 +324,13 @@ void generic_event_handler(lv_obj_t * obj, lv_event_t event)
return; return;
case LV_EVENT_DELETE: case LV_EVENT_DELETE:
Log.verbose(TAG_HASP, F("Object deleted Event %d occured"), event); Log.verbose(TAG_HASP, F(D_OBJECT_DELETED));
hasp_object_delete(obj); // free and destroy persistent memory allocated for certain objects hasp_object_delete(obj); // free and destroy persistent memory allocated for certain objects
last_press_was_short = false; last_press_was_short = false;
return; return;
default: default:
Log.warning(TAG_HASP, F("Unknown Event %d occured"), event); Log.warning(TAG_HASP, F(D_OBJECT_EVENT_UNKNOWN), event);
last_press_was_short = false; last_press_was_short = false;
return; return;
} }
@ -388,7 +388,7 @@ void toggle_event_handler(lv_obj_t * obj, lv_event_t event)
dispatch_normalized_group_value(obj->user_data.groupid, NORMALIZE(val, 0, 1), obj); dispatch_normalized_group_value(obj->user_data.groupid, NORMALIZE(val, 0, 1), obj);
} else if(event == LV_EVENT_DELETE) { } else if(event == LV_EVENT_DELETE) {
Log.verbose(TAG_HASP, F("Object deleted Event %d occured"), event); Log.verbose(TAG_HASP, F(D_OBJECT_DELETED));
hasp_object_delete(obj); hasp_object_delete(obj);
} }
} }
@ -450,7 +450,7 @@ static void selector_event_handler(lv_obj_t * obj, lv_event_t event)
if(max > 0) dispatch_normalized_group_value(obj->user_data.groupid, NORMALIZE(val, 0, max), obj); if(max > 0) dispatch_normalized_group_value(obj->user_data.groupid, NORMALIZE(val, 0, max), obj);
} else if(event == LV_EVENT_DELETE) { } else if(event == LV_EVENT_DELETE) {
Log.verbose(TAG_HASP, F("Object deleted Event %d occured"), event); Log.verbose(TAG_HASP, F(D_OBJECT_DELETED));
hasp_object_delete(obj); hasp_object_delete(obj);
} }
} }
@ -495,7 +495,7 @@ void slider_event_handler(lv_obj_t * obj, lv_event_t event)
dispatch_normalized_group_value(obj->user_data.groupid, NORMALIZE(val, min, max), obj); dispatch_normalized_group_value(obj->user_data.groupid, NORMALIZE(val, min, max), obj);
} else if(event == LV_EVENT_DELETE) { } else if(event == LV_EVENT_DELETE) {
Log.verbose(TAG_HASP, F("Object deleted Event %d occured"), event); Log.verbose(TAG_HASP, F(D_OBJECT_DELETED));
hasp_object_delete(obj); hasp_object_delete(obj);
} }
} }
@ -514,7 +514,7 @@ static void cpicker_event_handler(lv_obj_t * obj, lv_event_t event)
hasp_update_sleep_state(); // wakeup? hasp_update_sleep_state(); // wakeup?
hasp_send_obj_attribute_color(obj, color, lv_cpicker_get_color(obj)); hasp_send_obj_attribute_color(obj, color, lv_cpicker_get_color(obj));
} else if(event == LV_EVENT_DELETE) { } else if(event == LV_EVENT_DELETE) {
Log.verbose(TAG_HASP, F("Object deleted Event %d occured"), event); Log.verbose(TAG_HASP, F(D_OBJECT_DELETED));
hasp_object_delete(obj); hasp_object_delete(obj);
} }
} }
@ -586,7 +586,7 @@ void hasp_process_attribute(uint8_t pageid, uint8_t objid, const char * attr, co
if(lv_obj_t * obj = hasp_find_obj_from_parent_id(get_page_obj(pageid), objid)) { if(lv_obj_t * obj = hasp_find_obj_from_parent_id(get_page_obj(pageid), objid)) {
hasp_process_obj_attribute(obj, attr, payload, strlen(payload) > 0); hasp_process_obj_attribute(obj, attr, payload, strlen(payload) > 0);
} else { } else {
Log.warning(TAG_HASP, F("Unknown object " HASP_OBJECT_NOTATION ""), pageid, objid); Log.warning(TAG_HASP, F(D_OBJECT_UNKNOWN " " HASP_OBJECT_NOTATION), pageid, objid);
} }
} }
@ -604,7 +604,7 @@ void hasp_new_object(const JsonObject & config, uint8_t & saved_page_id)
uint8_t pageid = config[F("page")].isNull() ? saved_page_id : config[F("page")].as<uint8_t>(); uint8_t pageid = config[F("page")].isNull() ? saved_page_id : config[F("page")].as<uint8_t>();
lv_obj_t * parent_obj = get_page_obj(pageid); lv_obj_t * parent_obj = get_page_obj(pageid);
if(!parent_obj) { if(!parent_obj) {
return Log.warning(TAG_HASP, F("Page ID %u not defined"), pageid); return Log.warning(TAG_HASP, F(D_OBJECT_PAGE_UNKNOWN), pageid);
} else { } else {
saved_page_id = pageid; /* save the current pageid */ saved_page_id = pageid; /* save the current pageid */
} }
@ -627,10 +627,9 @@ void hasp_new_object(const JsonObject & config, uint8_t & saved_page_id)
/* Define Objects*/ /* Define Objects*/
lv_obj_t * obj = hasp_find_obj_from_parent_id(parent_obj, id); lv_obj_t * obj = hasp_find_obj_from_parent_id(parent_obj, id);
if(obj) { if(!obj) {
// return Log.warning(TAG_HASP, F("Object ID %u already exists!"), id);
} else { /* Create the object first */
/* Validate type */ /* Validate type */
if(config[F("objid")].isNull()) { // TODO: obsolete objid if(config[F("objid")].isNull()) { // TODO: obsolete objid
@ -950,7 +949,7 @@ void hasp_new_object(const JsonObject & config, uint8_t & saved_page_id)
/* No object was actually created */ /* No object was actually created */
if(!obj) { if(!obj) {
return Log.error(TAG_HASP, F("Object ID %u is NULL, skipping..."), id); return Log.error(TAG_HASP, F(D_OBJECT_CREATE_FAILED), id);
} }
// Prevent losing press when the press is slid out of the objects. // Prevent losing press when the press is slid out of the objects.
@ -965,18 +964,18 @@ void hasp_new_object(const JsonObject & config, uint8_t & saved_page_id)
/** testing start **/ /** testing start **/
uint8_t temp; uint8_t temp;
if(!hasp_find_id_from_obj(obj, &pageid, &temp)) { if(!hasp_find_id_from_obj(obj, &pageid, &temp)) {
return Log.error(TAG_HASP, F("Lost track of the created object, not found!")); return Log.error(TAG_HASP, F(D_OBJECT_LOST));
} }
/** verbose reporting **/ /** verbose reporting **/
lv_obj_type_t list; lv_obj_type_t list;
lv_obj_get_type(obj, &list); lv_obj_get_type(obj, &list);
Log.verbose(TAG_HASP, F(" * " HASP_OBJECT_NOTATION " = %s"), pageid, temp, list.type[0]); Log.verbose(TAG_HASP, F(D_BULLET HASP_OBJECT_NOTATION " = %s"), pageid, temp, list.type[0]);
/* test double-check */ /* test double-check */
lv_obj_t * test = hasp_find_obj_from_parent_id(get_page_obj(pageid), (uint8_t)temp); lv_obj_t * test = hasp_find_obj_from_parent_id(get_page_obj(pageid), (uint8_t)temp);
if(test != obj) { if(test != obj) {
return Log.error(TAG_HASP, F("Objects DO NOT match!")); return Log.error(TAG_HASP, F(D_OBJECT_MISMATCH));
} }
} }

View File

@ -3,26 +3,26 @@
#if HASP_USE_CONFIG > 0 #if HASP_USE_CONFIG > 0
#include "ArduinoJson.h" #include "ArduinoJson.h"
#include "StreamUtils.h" // For EEPromStream #include "StreamUtils.h" // For EEPromStream
#include "hasp_conf.h" #include "hasp_conf.h"
#include "hasp_config.h" #include "hasp_config.h"
#include "hasp_debug.h" #include "hasp_debug.h"
#include "hasp_gui.h" #include "hasp_gui.h"
//#include "hasp_ota.h" included in conf //#include "hasp_ota.h" included in conf
//#include "hasp_filesystem.h" included in conf //#include "hasp_filesystem.h" included in conf
//#include "hasp_telnet.h" included in conf //#include "hasp_telnet.h" included in conf
//#include "hasp_gpio.h" included in conf //#include "hasp_gpio.h" included in conf
//#include "hasp_eeprom.h" //#include "hasp_eeprom.h"
#include "hasp/hasp.h" #include "hasp/hasp.h"
#if HASP_USE_EEPROM > 0 #if HASP_USE_EEPROM > 0
#include "EEPROM.h" #include "EEPROM.h"
#endif #endif
void confDebugSet(const __FlashStringHelper * fstr_name) void confDebugSet(const __FlashStringHelper * fstr_name)
{ {
@ -73,17 +73,17 @@ void configStartDebug(bool setupdebug, String & configFile)
{ {
if(setupdebug) { if(setupdebug) {
debugStart(); // Debug started, now we can use it; HASP header sent debugStart(); // Debug started, now we can use it; HASP header sent
#if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0 #if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0
Log.trace(TAG_CONF, F("[SUCCESS] SPI flash FS mounted")); Log.trace(TAG_CONF, F("[SUCCESS] SPI flash FS mounted"));
filesystemInfo(); filesystemInfo();
filesystemList(); filesystemList();
#endif #endif
} }
#if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0 #if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0
Log.notice(TAG_CONF, F("Loading %s"), configFile.c_str()); Log.notice(TAG_CONF, F("Loading %s"), configFile.c_str());
#else #else
Log.notice(TAG_CONF, F("reading EEPROM")); Log.notice(TAG_CONF, F("reading EEPROM"));
#endif #endif
} }
void configGetConfig(JsonDocument & settings, bool setupdebug = false) void configGetConfig(JsonDocument & settings, bool setupdebug = false)
@ -93,7 +93,7 @@ void configGetConfig(JsonDocument & settings, bool setupdebug = false)
configFile = String(FPSTR(HASP_CONFIG_FILE)); configFile = String(FPSTR(HASP_CONFIG_FILE));
DeserializationError error; DeserializationError error;
#if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0 #if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0
File file = HASP_FS.open(configFile, "r"); File file = HASP_FS.open(configFile, "r");
if(file) { if(file) {
@ -116,7 +116,7 @@ void configGetConfig(JsonDocument & settings, bool setupdebug = false)
// show settings in log // show settings in log
String output; String output;
serializeJson(settings, output); serializeJson(settings, output);
String passmask = F("********"); String passmask = F(D_PASSWORD_MASK);
output.replace(settings[F("http")][F("pass")].as<String>(), passmask); output.replace(settings[F("http")][F("pass")].as<String>(), passmask);
output.replace(settings[F("mqtt")][F("pass")].as<String>(), passmask); output.replace(settings[F("mqtt")][F("pass")].as<String>(), passmask);
output.replace(settings[F("wifi")][F("pass")].as<String>(), passmask); output.replace(settings[F("wifi")][F("pass")].as<String>(), passmask);
@ -127,14 +127,14 @@ void configGetConfig(JsonDocument & settings, bool setupdebug = false)
return; return;
} }
} }
#else #else
#if HASP_USE_EEPROM > 0 #if HASP_USE_EEPROM > 0
EepromStream eepromStream(0, 1024); EepromStream eepromStream(0, 1024);
error = deserializeJson(settings, eepromStream); error = deserializeJson(settings, eepromStream);
#endif #endif
#endif #endif
// File does not exist or error reading file // File does not exist or error reading file
if(setupdebug) { if(setupdebug) {
@ -142,9 +142,9 @@ void configGetConfig(JsonDocument & settings, bool setupdebug = false)
} }
configStartDebug(setupdebug, configFile); configStartDebug(setupdebug, configFile);
#if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0 #if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0
Log.error(TAG_CONF, F("Failed to load %s"), configFile.c_str()); Log.error(TAG_CONF, F("Failed to load %s"), configFile.c_str());
#endif #endif
} }
/* /*
void configBackupToEeprom() void configBackupToEeprom()
@ -204,7 +204,7 @@ void configWriteConfig()
bool changed = false; bool changed = false;
const __FlashStringHelper * module; const __FlashStringHelper * module;
#if HASP_USE_WIFI > 0 #if HASP_USE_WIFI > 0
module = F("wifi"); module = F("wifi");
if(settings[module].as<JsonObject>().isNull()) settings.createNestedObject(module); if(settings[module].as<JsonObject>().isNull()) settings.createNestedObject(module);
changed = wifiGetConfig(settings[module]); changed = wifiGetConfig(settings[module]);
@ -213,9 +213,9 @@ void configWriteConfig()
configOutput(settings[module], TAG_WIFI); configOutput(settings[module], TAG_WIFI);
writefile = true; writefile = true;
} }
#endif #endif
#if HASP_USE_MQTT > 0 #if HASP_USE_MQTT > 0
module = F("mqtt"); module = F("mqtt");
if(settings[module].as<JsonObject>().isNull()) settings.createNestedObject(module); if(settings[module].as<JsonObject>().isNull()) settings.createNestedObject(module);
changed = mqttGetConfig(settings[module]); changed = mqttGetConfig(settings[module]);
@ -224,9 +224,9 @@ void configWriteConfig()
configOutput(settings[module], TAG_MQTT); configOutput(settings[module], TAG_MQTT);
writefile = true; writefile = true;
} }
#endif #endif
#if HASP_USE_TELNET > 0 #if HASP_USE_TELNET > 0
module = F("telnet"); module = F("telnet");
if(settings[module].as<JsonObject>().isNull()) settings.createNestedObject(module); if(settings[module].as<JsonObject>().isNull()) settings.createNestedObject(module);
changed = telnetGetConfig(settings[module]); changed = telnetGetConfig(settings[module]);
@ -235,9 +235,9 @@ void configWriteConfig()
configOutput(settings[module], TAG_TELN); configOutput(settings[module], TAG_TELN);
writefile = true; writefile = true;
} }
#endif #endif
#if HASP_USE_MDNS > 0 #if HASP_USE_MDNS > 0
module = F("mdns"); module = F("mdns");
if(settings[module].as<JsonObject>().isNull()) settings.createNestedObject(module); if(settings[module].as<JsonObject>().isNull()) settings.createNestedObject(module);
changed = mdnsGetConfig(settings[module]); changed = mdnsGetConfig(settings[module]);
@ -246,9 +246,9 @@ void configWriteConfig()
configOutput(settings[module], TAG_MDNS); configOutput(settings[module], TAG_MDNS);
writefile = true; writefile = true;
} }
#endif #endif
#if HASP_USE_HTTP > 0 #if HASP_USE_HTTP > 0
if(settings[F("http")].as<JsonObject>().isNull()) settings.createNestedObject(F("http")); if(settings[F("http")].as<JsonObject>().isNull()) settings.createNestedObject(F("http"));
changed = httpGetConfig(settings[F("http")]); changed = httpGetConfig(settings[F("http")]);
if(changed) { if(changed) {
@ -256,9 +256,9 @@ void configWriteConfig()
configOutput(settings[F("http")], TAG_HTTP); configOutput(settings[F("http")], TAG_HTTP);
writefile = true; writefile = true;
} }
#endif #endif
#if HASP_USE_GPIO > 0 #if HASP_USE_GPIO > 0
module = F("gpio"); module = F("gpio");
if(settings[module].as<JsonObject>().isNull()) settings.createNestedObject(module); if(settings[module].as<JsonObject>().isNull()) settings.createNestedObject(module);
changed = gpioGetConfig(settings[module]); changed = gpioGetConfig(settings[module]);
@ -267,7 +267,7 @@ void configWriteConfig()
configOutput(settings[module], TAG_GPIO); configOutput(settings[module], TAG_GPIO);
writefile = true; writefile = true;
} }
#endif #endif
module = F("debug"); module = F("debug");
if(settings[module].as<JsonObject>().isNull()) settings.createNestedObject(module); if(settings[module].as<JsonObject>().isNull()) settings.createNestedObject(module);
@ -297,7 +297,7 @@ void configWriteConfig()
// changed |= otaGetConfig(settings[F("ota")].as<JsonObject>()); // changed |= otaGetConfig(settings[F("ota")].as<JsonObject>());
if(writefile) { if(writefile) {
#if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0 #if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0
File file = HASP_FS.open(configFile, "w"); File file = HASP_FS.open(configFile, "w");
if(file) { if(file) {
Log.notice(TAG_CONF, F("Writing %s"), configFile.c_str()); Log.notice(TAG_CONF, F("Writing %s"), configFile.c_str());
@ -312,7 +312,7 @@ void configWriteConfig()
} else { } else {
Log.error(TAG_CONF, F("Failed to write %s"), configFile.c_str()); Log.error(TAG_CONF, F("Failed to write %s"), configFile.c_str());
} }
#endif #endif
// Method 1 // Method 1
// Log.trace(TAG_CONF,F("Writing to EEPROM")); // Log.trace(TAG_CONF,F("Writing to EEPROM"));
@ -322,7 +322,7 @@ void configWriteConfig()
// bufferedWifiClient.flush(); // <- OPTIONAL // bufferedWifiClient.flush(); // <- OPTIONAL
// eepromStream.flush(); // (for ESP) // eepromStream.flush(); // (for ESP)
#if defined(STM32F4xx) #if defined(STM32F4xx)
// Method 2 // Method 2
Log.trace(TAG_CONF, F("Writing to EEPROM")); Log.trace(TAG_CONF, F("Writing to EEPROM"));
char buffer[1024 + 128]; char buffer[1024 + 128];
@ -336,7 +336,7 @@ void configWriteConfig()
} else { } else {
Log.error(TAG_CONF, F("Failed to save config to EEPROM")); Log.error(TAG_CONF, F("Failed to save config to EEPROM"));
} }
#endif #endif
} else { } else {
Log.trace(TAG_CONF, F("Configuration did not change")); Log.trace(TAG_CONF, F("Configuration did not change"));
@ -353,19 +353,19 @@ void configSetup()
Serial.println(__LINE__); Serial.println(__LINE__);
if(i == 0) { if(i == 0) {
#if HASP_USE_SPIFFS > 0 #if HASP_USE_SPIFFS > 0
EepromStream eepromStream(0, 2048); EepromStream eepromStream(0, 2048);
DeserializationError err = deserializeJson(settings, eepromStream); DeserializationError err = deserializeJson(settings, eepromStream);
#else #else
continue; continue;
#endif #endif
} else { } else {
#if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0 #if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0
if(!filesystemSetup()) { if(!filesystemSetup()) {
Log.error(TAG_CONF, F("FILE: SPI flash init failed. Unable to mount FS: Using default settings...")); Log.error(TAG_CONF, F("FILE: SPI flash init failed. Unable to mount FS: Using default settings..."));
return; return;
} }
#endif #endif
configGetConfig(settings, true); configGetConfig(settings, true);
} }
@ -378,35 +378,35 @@ void configSetup()
haspSetConfig(settings[F("hasp")]); haspSetConfig(settings[F("hasp")]);
// otaGetConfig(settings[F("ota")]); // otaGetConfig(settings[F("ota")]);
#if HASP_USE_WIFI > 0 #if HASP_USE_WIFI > 0
Log.trace(TAG_WIFI, F("Loading WiFi settings")); Log.trace(TAG_WIFI, F("Loading WiFi settings"));
wifiSetConfig(settings[F("wifi")]); wifiSetConfig(settings[F("wifi")]);
#endif #endif
#if HASP_USE_MQTT > 0 #if HASP_USE_MQTT > 0
Log.trace(TAG_MQTT, F("Loading MQTT settings")); Log.trace(TAG_MQTT, F("Loading MQTT settings"));
mqttSetConfig(settings[F("mqtt")]); mqttSetConfig(settings[F("mqtt")]);
#endif #endif
#if HASP_USE_TELNET > 0 #if HASP_USE_TELNET > 0
Log.trace(TAG_TELN, F("Loading Telnet settings")); Log.trace(TAG_TELN, F("Loading Telnet settings"));
telnetSetConfig(settings[F("telnet")]); telnetSetConfig(settings[F("telnet")]);
#endif #endif
#if HASP_USE_MDNS > 0 #if HASP_USE_MDNS > 0
Log.trace(TAG_MDNS, F("Loading MDNS settings")); Log.trace(TAG_MDNS, F("Loading MDNS settings"));
mdnsSetConfig(settings[F("mdns")]); mdnsSetConfig(settings[F("mdns")]);
#endif #endif
#if HASP_USE_HTTP > 0 #if HASP_USE_HTTP > 0
Log.trace(TAG_HTTP, F("Loading HTTP settings")); Log.trace(TAG_HTTP, F("Loading HTTP settings"));
httpSetConfig(settings[F("http")]); httpSetConfig(settings[F("http")]);
#endif #endif
#if HASP_USE_GPIO > 0 #if HASP_USE_GPIO > 0
Log.trace(TAG_GPIO, F("Loading GPIO settings")); Log.trace(TAG_GPIO, F("Loading GPIO settings"));
gpioSetConfig(settings[F("gpio")]); gpioSetConfig(settings[F("gpio")]);
#endif #endif
Log.trace(TAG_CONF, F("User configuration loaded")); Log.trace(TAG_CONF, F("User configuration loaded"));
} }
@ -421,7 +421,7 @@ void configOutput(const JsonObject & settings, uint8_t tag)
String passmask((char *)0); String passmask((char *)0);
passmask.reserve(128); passmask.reserve(128);
passmask = F("\"pass\":\"********\""); passmask = F("\"pass\":\"" D_PASSWORD_MASK "\"");
String password((char *)0); String password((char *)0);
password.reserve(128); password.reserve(128);
@ -460,7 +460,7 @@ void configOutput(const JsonObject & settings, uint8_t tag)
bool configClearEeprom() bool configClearEeprom()
{ {
#if defined(STM32F4xx) #if defined(STM32F4xx)
Log.notice(TAG_CONF, F("Clearing EEPROM")); Log.notice(TAG_CONF, F("Clearing EEPROM"));
char buffer[1024 + 128]; char buffer[1024 + 128];
memset(buffer, 1, sizeof(buffer)); memset(buffer, 1, sizeof(buffer));
@ -475,11 +475,11 @@ bool configClearEeprom()
Log.error(TAG_CONF, F("Failed to clear to EEPROM")); Log.error(TAG_CONF, F("Failed to clear to EEPROM"));
return false; return false;
} }
#elif HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0 #elif HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0
return HASP_FS.format(); return HASP_FS.format();
#else #else
return false; return false;
#endif #endif
} }
#endif // HAS_USE_CONFIG #endif // HAS_USE_CONFIG

View File

@ -151,7 +151,7 @@ void debugSetup()
{ {
// memset(serialInputBuffer, 0, sizeof(serialInputBuffer)); // memset(serialInputBuffer, 0, sizeof(serialInputBuffer));
// serialInputIndex = 0; // serialInputIndex = 0;
Log.notice(TAG_DEBG, F("Setting the console parser")); Log.notice(TAG_DEBG, F(D_SERVICE_STARTING)); // Starting console
debugConsole.setLineCallback(dispatch_text_line); debugConsole.setLineCallback(dispatch_text_line);
} }
@ -172,10 +172,10 @@ void debugStartSyslog()
if(syslogClient) { if(syslogClient) {
if(syslogClient->beginPacket(debugSyslogHost, debugSyslogPort)) { if(syslogClient->beginPacket(debugSyslogHost, debugSyslogPort)) {
Log.registerOutput(2, syslogClient, LOG_LEVEL_VERBOSE, true); Log.registerOutput(2, syslogClient, LOG_LEVEL_VERBOSE, true);
Log.trace(TAG_DEBG, F("Syslog client started")); Log.trace(TAG_SYSL, F(D_SERVICE_STARTED));
} }
} else { } else {
Log.error(TAG_DEBG, F("Failed to start syslog client")); Log.error(TAG_SYSL, F(D_SERVICE_START_FAILED));
} }
} }
#endif #endif
@ -185,6 +185,7 @@ void debugStopSyslog()
{ {
#if HASP_USE_SYSLOG > 0 #if HASP_USE_SYSLOG > 0
if(strlen(debugSyslogHost) > 0) { if(strlen(debugSyslogHost) > 0) {
Log.warning(TAG_SYSL, F(D_SERVICE_STOPPED));
Log.unregisterOutput(2); Log.unregisterOutput(2);
} }
#endif #endif

View File

@ -8,6 +8,8 @@
#include "ArduinoLog.h" #include "ArduinoLog.h"
#include "lvgl.h" #include "lvgl.h"
#include "lang/lang.h"
/* ===== Default Event Processors ===== */ /* ===== Default Event Processors ===== */
void debugPreSetup(JsonObject settings); void debugPreSetup(JsonObject settings);
void debugSetup(); void debugSetup();

View File

@ -318,7 +318,7 @@ void gpio_set_normalized_value(hasp_gpio_config_t gpio, uint16_t state)
default: default:
return; return;
} }
Log.verbose(TAG_GPIO, F(" * Group %d - Pin %d = %d"), gpio.group, gpio.pin, gpio.val); Log.verbose(TAG_GPIO, F(D_BULLET "Group %d - Pin %d = %d"), gpio.group, gpio.pin, gpio.val);
} }
// void gpio_set_group_onoff(uint8_t groupid, bool ison) // void gpio_set_group_onoff(uint8_t groupid, bool ison)

View File

@ -57,7 +57,7 @@ static void peek_password_cb(lv_obj_t * obj, lv_event_t event)
static void kb_event_cb(lv_obj_t * event_kb, lv_event_t event) static void kb_event_cb(lv_obj_t * event_kb, lv_event_t event)
{ {
if(event == LV_EVENT_APPLY) { if(event == LV_EVENT_APPLY) {
DynamicJsonDocument settings(256); StaticJsonDocument<256> settings;
char ssid[32] = ""; char ssid[32] = "";
char pass[32] = ""; char pass[32] = "";
lv_obj_t * obj; lv_obj_t * obj;
@ -77,7 +77,7 @@ static void kb_event_cb(lv_obj_t * event_kb, lv_event_t event)
if(strlen(ssid) > 0 && wifiValidateSsid(ssid, pass)) { if(strlen(ssid) > 0 && wifiValidateSsid(ssid, pass)) {
wifiSetConfig(settings.as<JsonObject>()); wifiSetConfig(settings.as<JsonObject>());
Log.notice(TAG_OOBE, F("SSID %s validated"), ssid); Log.notice(TAG_OOBE, F(D_OOBE_SSID_VALIDATED), ssid);
dispatch_reboot(true); dispatch_reboot(true);
} }
@ -324,10 +324,10 @@ bool oobeSetup()
lv_obj_set_click(lv_disp_get_layer_sys(NULL), true); lv_obj_set_click(lv_disp_get_layer_sys(NULL), true);
if(oobeAutoCalibrate) { if(oobeAutoCalibrate) {
lv_obj_set_event_cb(lv_disp_get_layer_sys(NULL), oobe_calibrate_cb); lv_obj_set_event_cb(lv_disp_get_layer_sys(NULL), oobe_calibrate_cb);
Log.trace(TAG_OOBE, F("Enabled Auto Calibrate on touch")); Log.trace(TAG_OOBE, F(D_OOBE_AUTO_CALIBRATE));
} else { } else {
lv_obj_set_event_cb(lv_disp_get_layer_sys(NULL), gotoPage1_cb); lv_obj_set_event_cb(lv_disp_get_layer_sys(NULL), gotoPage1_cb);
Log.trace(TAG_OOBE, F("Already calibrated")); Log.trace(TAG_OOBE, F(D_OOBE_CALIBRATED));
} }
oobeSetPage(0); oobeSetPage(0);
return true; return true;
@ -355,9 +355,9 @@ void oobeFakeSetup(const char *, const char *)
if(oobeAutoCalibrate) { if(oobeAutoCalibrate) {
lv_obj_set_click(lv_disp_get_layer_sys(NULL), true); lv_obj_set_click(lv_disp_get_layer_sys(NULL), true);
lv_obj_set_event_cb(lv_disp_get_layer_sys(NULL), oobe_calibrate_cb); lv_obj_set_event_cb(lv_disp_get_layer_sys(NULL), oobe_calibrate_cb);
Log.trace(TAG_OOBE, F("Enabled Auto Calibrate on touch")); Log.trace(TAG_OOBE, F(D_OOBE_AUTO_CALIBRATE));
} else { } else {
Log.trace(TAG_OOBE, F("Already calibrated")); Log.trace(TAG_OOBE, F(D_OOBE_CALIBRATED));
} }
#endif #endif
} }

110
src/lang/en_US.h Normal file
View File

@ -0,0 +1,110 @@
#ifndef HASP_LANG_EN_US_H
#define HASP_LANG_EN_US_H
#define D_SERVICE_STARTING "Starting..."
#define D_SERVICE_STARTED "Started"
#define D_SERVICE_START_FAILED "Failed to start"
#define D_SERVICE_STOPPED "Stopped"
#define D_SERVICE_DISABLED "Disabled"
#define D_SERVICE_CONNECTED "Connected"
#define D_SERVICE_DISCONNECTED "Disconnected"
#define D_NETWORK_IP_ADDRESS_RECEIVED "Received IP address %s"
#define D_NETWORK_ONLINE "online"
#define D_NETWORK_OFFLINE "offline"
#define D_NETWORK_CONNECTION_FAILED "Connection failed"
#define D_MQTT_DEFAULT_NAME "plate_%s"
#define D_MQTT_CONNECTING "Connecting..."
#define D_MQTT_CONNECTED "Connected to broker %s as clientID %s"
#define D_MQTT_NOT_CONNECTED "Not connected ???"
#define D_MQTT_DISCONNECTING "Disconnecting..."
#define D_MQTT_DISCONNECTED "Disconnected"
#define D_MQTT_RECONNECTING "Disconnected from broker, reconnection..."
#define D_MQTT_NOT_CONFIGURED "Broker not configured"
#define D_MQTT_STARTED "Started: %d bytes"
#define D_MQTT_FAILED "Failed:"
#define D_MQTT_INVALID_TOPIC "Message has invalid topic"
#define D_MQTT_SUBSCRIBED "Subscribed to %s"
#define D_MQTT_NOT_SUBSCRIBED "Failed to subscribe to %s"
#define D_MQTT_HA_AUTO_DISCOVERY "Register HA auto-discovery"
#define D_TELNET_CLOSING_CONNECTION "Closing session from %s"
#define D_TELNET_CLIENT_LOGIN_FROM "Client login from %s"
#define D_TELNET_CLIENT_CONNECT_FROM "Client connected from %s"
#define D_TELNET_CLIENT_NOT_CONNECTED "Client NOT connected"
#define D_TELNET_USERNAME "Username:"
#define D_TELNET_PASSWORD "Password:"
#define D_TELNET_AUTHENTICATION_FAILED "Authorization failed!"
#define D_TELNET_INCORRECT_LOGIN_ATTEMPT "Incorrect login attempt from %s"
#define D_TELNET_STARTED "Telnet console started"
#define D_TELNET_FAILED "Failed to start telnet console"
#define D_TELNET_CLIENT_CONNECTED "Client connected"
#define D_TELNET_CLIENT_NOT_CONNECTED "Client NOT connected"
#define D_TELNET_CLIENT_REJECTED "Client rejected"
#define D_HASP_INVALID_PAGE "Invalid page %u"
#define D_HASP_INVALID_LAYER "Cannot clear system layer"
#define D_HASP_CHANGE_PAGE "Changing page to %u"
#define D_HASP_CLEAR_PAGE "Clearing page %u"
#define D_OBJECT_DELETED "Object deleted"
#define D_OBJECT_UNKNOWN "Unknown object"
#define D_OBJECT_MISMATCH "Objects DO NOT match!"
#define D_OBJECT_LOST "Lost object!"
#define D_OBJECT_CREATE_FAILED "Object %u failed"
#define D_OBJECT_PAGE_UNKNOWN "Page ID %u not defined"
#define D_OBJECT_EVENT_UNKNOWN "Unknown Event %d"
#define D_ATTRIBUTE_UNKNOWN "Unknown property %s"
#define D_ATTRIBUTE_PAGE_METHOD_INVALID "Unable to call %s on a page"
#define D_OOBE_SSID_VALIDATED "SSID %s validated"
#define D_OOBE_AUTO_CALIBRATE "Auto calibrate enabled"
#define D_OOBE_CALIBRATED "Already calibrated"
#define D_DISPATCH_COMMAND_NOT_FOUND "Command '%s' not found"
#define D_DISPATCH_INVALID_PAGE "Invalid page %s"
#define D_DISPATCH_REBOOT "Rebooting the MCU now!"
#define D_JSON_FAILED "JSON parsing failed:"
#define D_JSONL_FAILED "JSONL parsing failed at line %d"
#define D_JSONL_SUCCEEDED "Jsonl fully parsed"
#define D_OTA_CHECK_UPDATE "Checking updates URL: %s"
#define D_OTA_CHECK_COMPLETE "Update check complete"
#define D_OTA_CHECK_FAILED "Update check failed: %s"
#define D_OTA_UPDATE_FIRMWARE "OTA Update firmware"
#define D_OTA_UPDATE_COMPLETE "OTA Update complete"
#define D_OTA_UPDATE_APPLY "Applying Firmware & Reboot"
#define D_OTA_UPDATE_FAILED "OTA Update failed"
#define D_HTTP_HASP_DESIGN "HASP Design"
#define D_HTTP_INFORMATION "Information"
#define D_HTTP_HTTP_SETTINGS "HTTP Settings"
#define D_HTTP_WIFI_SETTINGS "Wifi Settings"
#define D_HTTP_MQTT_SETTINGS "MQTT Settings"
#define D_HTTP_GPIO_SETTINGS "GPIO Settings"
#define D_HTTP_MDNS_SETTINGS "mDNS Settings"
#define D_HTTP_TELNET_SETTINGS "Telnet Settings"
#define D_HTTP_DEBUG_SETTINGS "Debug Settings"
#define D_HTTP_GUI_SETTINGS "Display Settings"
#define D_HTTP_SAVE_SETTINGS "Save Settings"
#define D_HTTP_UPLOAD_FILE "Upload File"
#define D_HTTP_ERASE_DEVICE "Reset All Settings"
#define D_HTTP_ADD_GPIO "Add New Pin"
#define D_HTTP_BACK "Back"
#define D_HTTP_REFRESH "Refresh"
#define D_HTTP_PREV_PAGE "Prev Page"
#define D_HTTP_NEXT_PAGE "Next Page"
#define D_HTTP_CALIBRATE "Calibrate"
#define D_HTTP_SCREENSHOT "Screenshot"
#define D_HTTP_FILE_BROWSER "File Browser"
#define D_HTTP_FIRMWARE_UPGRADE "Firmware Upgrade"
#define D_HTTP_UPDATE_FIRMWARE "Update Firmware"
#define D_HTTP_FACTORY_RESET "Factory Reset"
#define D_HTTP_MAIN_MENU "Main Menu"
#define D_HTTP_REBOOT "Restart"
#define D_HTTP_CONFIGURATION "Configuration"
#endif

9
src/lang/lang.h Normal file
View File

@ -0,0 +1,9 @@
#ifndef HASP_LANG_H
#define HASP_LANG_H
#include "nl_NL.h"
#define D_PASSWORD_MASK "********"
#define D_BULLET " * "
#endif

110
src/lang/nl_NL.h Normal file
View File

@ -0,0 +1,110 @@
#ifndef HASP_LANG_EN_US_H
#define HASP_LANG_EN_US_H
#define D_SERVICE_STARTING "Starten..."
#define D_SERVICE_STARTED "Gestart"
#define D_SERVICE_START_FAILED "Starten mislukt"
#define D_SERVICE_STOPPED "Gestopt"
#define D_SERVICE_DISABLED "Uitgeschakeld"
#define D_SERVICE_CONNECTED "Verbonden"
#define D_SERVICE_DISCONNECTED "Verbroken"
#define D_NETWORK_IP_ADDRESS_RECEIVED "IP adres %s ontvangen"
#define D_NETWORK_ONLINE "online"
#define D_NETWORK_OFFLINE "offline"
#define D_NETWORK_CONNECTION_FAILED "Verbinding mislukt"
#define D_MQTT_DEFAULT_NAME "plaat_%s"
#define D_MQTT_CONNECTING "Verbinden..."
#define D_MQTT_CONNECTED "Verbonden met broker %s als clientID %s"
#define D_MQTT_NOT_CONNECTED "Niet verbonden ???"
#define D_MQTT_DISCONNECTING "Verbinding verbreken..."
#define D_MQTT_DISCONNECTED "Verbinding verbroken"
#define D_MQTT_RECONNECTING "Verbinding verbroken, opnieuw verbinden..."
#define D_MQTT_NOT_CONFIGURED "Broker niet ingesteld"
#define D_MQTT_STARTED "Gestart: %d bytes"
#define D_MQTT_FAILED "Mislukt:"
#define D_MQTT_INVALID_TOPIC "Boodschap met ongeldig onderwerp"
#define D_MQTT_SUBSCRIBED "Ingeschreven op %s"
#define D_MQTT_NOT_SUBSCRIBED "Inschrijving op %s mislukt"
#define D_MQTT_HA_AUTO_DISCOVERY "Registeren HA auto-configuratie"
#define D_TELNET_CLOSING_CONNECTION "Sessie sluiten van %s"
#define D_TELNET_CLIENT_LOGIN_FROM "Client aangemeld van %s"
#define D_TELNET_CLIENT_CONNECT_FROM "Client verbonden van %s"
#define D_TELNET_CLIENT_NOT_CONNECTED "Client NIET vzebonden"
#define D_TELNET_USERNAME "Gebruikersnaam:"
#define D_TELNET_PASSWORD "Wachtwoord:"
#define D_TELNET_AUTHENTICATION_FAILED "Autorisatie mislukt!"
#define D_TELNET_INCORRECT_LOGIN_ATTEMPT "Aanmelding van %s mislukt"
#define D_TELNET_STARTED "Telnet console gestart"
#define D_TELNET_FAILED "Telnet console starten is mislukt"
#define D_TELNET_CLIENT_CONNECTED "Client verbonden"
#define D_TELNET_CLIENT_NOT_CONNECTED "Client NIET verbonden"
#define D_TELNET_CLIENT_REJECTED "Client geweigerd"
#define D_HASP_INVALID_PAGE "Ongeldige pagina %u"
#define D_HASP_INVALID_LAYER "Kan systeemlaag niet wissen"
#define D_HASP_CHANGE_PAGE "Pagina %u laden"
#define D_HASP_CLEAR_PAGE "Pagina %u wissen"
#define D_OBJECT_DELETED "Object verwijderd"
#define D_OBJECT_UNKNOWN "Onbekend object"
#define D_OBJECT_MISMATCH "Objecten komen niet overeen!"
#define D_OBJECT_LOST "Object kwijt!"
#define D_OBJECT_CREATE_FAILED "Object %u mislukt"
#define D_OBJECT_PAGE_UNKNOWN "Paginga %u niet gedefinieerd"
#define D_OBJECT_EVENT_UNKNOWN "Onbekend Event %d"
#define D_ATTRIBUTE_UNKNOWN "Onbekend attribuut %s"
#define D_ATTRIBUTE_PAGE_METHOD_INVALID "%s is ongeldig voor een pagina"
#define D_OOBE_SSID_VALIDATED "SSID %s gevalideerd"
#define D_OOBE_AUTO_CALIBRATE "Auto calibratie actief"
#define D_OOBE_CALIBRATED "Reeds gecalibreerd"
#define D_DISPATCH_COMMAND_NOT_FOUND "Opdracht '%s' niet gevonden"
#define D_DISPATCH_INVALID_PAGE "Ongeldige pagina %s"
#define D_DISPATCH_REBOOT "De MCU wordt herstart!"
#define D_JSON_FAILED "JSON verwerking mislukt:"
#define D_JSONL_FAILED "JSONL verwerking mislukt op lijn %d"
#define D_JSONL_SUCCEEDED "Jsonl volledig verwerkt"
#define D_OTA_CHECK_UPDATE "Checking updates URL: %s"
#define D_OTA_CHECK_COMPLETE "Update check complete"
#define D_OTA_CHECK_FAILED "Update check failed: %s"
#define D_OTA_UPDATE_FIRMWARE "OTA Update firmware"
#define D_OTA_UPDATE_COMPLETE "OTA Update complete"
#define D_OTA_UPDATE_APPLY "Applying Firmware & Reboot"
#define D_OTA_UPDATE_FAILED "OTA Update failed"
#define D_HTTP_HASP_DESIGN "HASP Ontwerp"
#define D_HTTP_INFORMATION "Informatie"
#define D_HTTP_HTTP_SETTINGS "HTTP Instellingen"
#define D_HTTP_WIFI_SETTINGS "Wifi Instellingen"
#define D_HTTP_MQTT_SETTINGS "MQTT Instellingen"
#define D_HTTP_GPIO_SETTINGS "GPIO Instellingen"
#define D_HTTP_MDNS_SETTINGS "mDNS Instellingen"
#define D_HTTP_TELNET_SETTINGS "Telnet Instellingen"
#define D_HTTP_DEBUG_SETTINGS "Debug Instellingen"
#define D_HTTP_GUI_SETTINGS "Scherm Instellingen"
#define D_HTTP_SAVE_SETTINGS "Bewaar Instellingen"
#define D_HTTP_UPLOAD_FILE "Bestand Opladen"
#define D_HTTP_ERASE_DEVICE "Alle Instellingen Wissen"
#define D_HTTP_ADD_GPIO "Pin Toevoegen"
#define D_HTTP_BACK "Terug"
#define D_HTTP_REFRESH "Vernieuwen"
#define D_HTTP_PREV_PAGE "Vorige Pagina"
#define D_HTTP_NEXT_PAGE "Volgende Pagina"
#define D_HTTP_CALIBRATE "Calibratie"
#define D_HTTP_SCREENSHOT "Schermafbeelding"
#define D_HTTP_FILE_BROWSER "Bestandsverkenner"
#define D_HTTP_FIRMWARE_UPGRADE "Firmware Upgrade"
#define D_HTTP_UPDATE_FIRMWARE "Firmware Bijwerken"
#define D_HTTP_FACTORY_RESET "Fabrieksinstellingen"
#define D_HTTP_MAIN_MENU "Hoofdmenu"
#define D_HTTP_REBOOT "Herstarten"
#define D_HTTP_CONFIGURATION "Configuratie"
#endif

View File

@ -15,12 +15,12 @@ void EthernetEvent(WiFiEvent_t event)
{ {
switch(event) { switch(event) {
case SYSTEM_EVENT_ETH_START: case SYSTEM_EVENT_ETH_START:
Log.notice(TAG_ETH, F("Started")); Log.notice(TAG_ETH, F(D_SERVICE_STARTED));
// set eth hostname here // set eth hostname here
ETH.setHostname(mqttGetNodename().c_str()); ETH.setHostname(mqttGetNodename().c_str());
break; break;
case SYSTEM_EVENT_ETH_CONNECTED: case SYSTEM_EVENT_ETH_CONNECTED:
Log.notice(TAG_ETH, F("Connected")); Log.notice(TAG_ETH, F(D_SERVICE_CONNECTED));
eth_connected = true; eth_connected = true;
break; break;
case SYSTEM_EVENT_ETH_GOT_IP: case SYSTEM_EVENT_ETH_GOT_IP:
@ -35,12 +35,12 @@ void EthernetEvent(WiFiEvent_t event)
networkStart(); // Start network services networkStart(); // Start network services
break; break;
case SYSTEM_EVENT_ETH_DISCONNECTED: case SYSTEM_EVENT_ETH_DISCONNECTED:
Log.notice(TAG_ETH, F("Disconnected")); Log.notice(TAG_ETH, F(D_SERVICE_DISCONNECTED));
eth_connected = false; eth_connected = false;
networkStop(); // Stop network services networkStop(); // Stop network services
break; break;
case SYSTEM_EVENT_ETH_STOP: case SYSTEM_EVENT_ETH_STOP:
Log.notice(TAG_ETH, F("Stopped")); Log.warning(TAG_ETH, F(D_SERVICE_STOPPED));
eth_connected = false; eth_connected = false;
break; break;
default: default:
@ -59,7 +59,7 @@ void IRAM_ATTR ethernetLoop(void)
bool ethernetEvery5Seconds() bool ethernetEvery5Seconds()
{ {
// Log.warning(TAG_ETH, eth_connected ? F("ONLINE") : F("OFFLINE")); // Log.warning(TAG_ETH, eth_connected ? F(D_NETWORK_ONLINE) : F(D_NETWORK_OFFLINE));
return eth_connected; return eth_connected;
} }

View File

@ -15,7 +15,7 @@ void ethernetSetup()
{ {
#if USE_BUILTIN_ETHERNET > 0 #if USE_BUILTIN_ETHERNET > 0
// start Ethernet and UDP // start Ethernet and UDP
Log.notice(TAG_ETH, F("Begin Ethernet LAN8720")); Log.notice(TAG_ETH, F("LAN8720 "D_SERVICE_STARTING));
if(Ethernet.begin() == 0) { if(Ethernet.begin() == 0) {
Log.notice(TAG_ETH, F("Failed to configure Ethernet using DHCP")); Log.notice(TAG_ETH, F("Failed to configure Ethernet using DHCP"));
eth_connected = false; eth_connected = false;
@ -44,7 +44,7 @@ void ethernetSetup()
Ethernet.setCsPin(W5500_CS); Ethernet.setCsPin(W5500_CS);
Ethernet.setRstPin(W5500_RST); Ethernet.setRstPin(W5500_RST);
Ethernet.setHostname(ethHostname); Ethernet.setHostname(ethHostname);
Log.notice(TAG_ETH, F("Begin Ethernet W5500")); Log.notice(TAG_ETH, F("W5500 "D_SERVICE_STARTING));
if(Ethernet.begin(mac) == 0) { if(Ethernet.begin(mac) == 0) {
Log.notice(TAG_ETH, F("Failed to configure Ethernet using DHCP")); Log.notice(TAG_ETH, F("Failed to configure Ethernet using DHCP"));
} else { } else {
@ -59,7 +59,7 @@ void ethernetLoop(void)
switch(Ethernet.maintain()) { switch(Ethernet.maintain()) {
case 1: case 1:
// renewed fail // renewed fail
Log.notice(TAG_ETH, F("Error: renewed fail")); Log.error(TAG_ETH, F("Error: renewed fail"));
break; break;
case 2: case 2:
@ -70,7 +70,7 @@ void ethernetLoop(void)
case 3: case 3:
// rebind fail // rebind fail
Log.notice(TAG_ETH, F("Error: rebind fail")); Log.error(TAG_ETH, F("Error: rebind fail"));
break; break;
case 4: case 4:
@ -93,7 +93,7 @@ bool ethernetEvery5Seconds()
#else #else
state = Ethernet.link() == 1; state = Ethernet.link() == 1;
#endif #endif
Log.warning(TAG_ETH, state ? F("ONLINE") : F("OFFLINE")); Log.warning(TAG_ETH, state ? F(D_NETWORK_ONLINE) : F(D_NETWORK_OFFLINE));
return state; return state;
} }

View File

@ -62,10 +62,10 @@ static void wifiConnected(IPAddress ipaddress)
ip = WiFi.localIP(); ip = WiFi.localIP();
Log.notice(TAG_WIFI, F("Received IP address %d.%d.%d.%d"), ip[0], ip[1], ip[2], ip[3]); Log.notice(TAG_WIFI, F("Received IP address %d.%d.%d.%d"), ip[0], ip[1], ip[2], ip[3]);
#else #else
Log.notice(TAG_WIFI, F("Received IP address %s"), ipaddress.toString().c_str()); Log.notice(TAG_WIFI, F(D_NETWORK_IP_ADDRESS_RECEIVED), ipaddress.toString().c_str());
#endif #endif
Log.verbose(TAG_WIFI, F("Connected = %s"), WiFi.status() == WL_CONNECTED ? PSTR("yes") : PSTR("no")); Log.verbose(TAG_WIFI, F("Connected = %s"), WiFi.status() == WL_CONNECTED ? PSTR(D_NETWORK_ONLINE) : PSTR(D_NETWORK_OFFLINE));
networkStart(); networkStart();
} }
@ -259,7 +259,7 @@ static void wifiDisconnected(const char * ssid, uint8_t reason)
snprintf_P(buffer, sizeof(buffer), PSTR("handshake failed")); snprintf_P(buffer, sizeof(buffer), PSTR("handshake failed"));
break; break;
case WIFI_REASON_CONNECTION_FAIL: case WIFI_REASON_CONNECTION_FAIL:
snprintf_P(buffer, sizeof(buffer), PSTR("connection failed")); snprintf_P(buffer, sizeof(buffer), PSTR(D_NETWORK_CONNECTION_FAILED));
break; break;
#endif #endif
@ -471,14 +471,14 @@ bool wifiValidateSsid(const char * ssid, const char * pass)
delay(500); delay(500);
} }
#if defined(STM32F4xx) #if defined(STM32F4xx)
Log.trace(TAG_WIFI, F("Received IP addres %s"), espIp); Log.trace(TAG_WIFI, F(D_NETWORK_IP_ADDRESS_RECEIVED), espIp);
if((WiFi.status() == WL_CONNECTED && String(espIp) != F("0.0.0.0"))) return true; if((WiFi.status() == WL_CONNECTED && String(espIp) != F("0.0.0.0"))) return true;
#else #else
Log.trace(TAG_WIFI, F("Received IP addres %s"), WiFi.localIP().toString().c_str()); Log.trace(TAG_WIFI, F(D_NETWORK_IP_ADDRESS_RECEIVED), WiFi.localIP().toString().c_str());
if((WiFi.status() == WL_CONNECTED && WiFi.localIP().toString() != F("0.0.0.0"))) return true; if((WiFi.status() == WL_CONNECTED && WiFi.localIP().toString() != F("0.0.0.0"))) return true;
#endif #endif
Log.warning(TAG_WIFI, F("Received IP addres %s"), WiFi.localIP().toString().c_str()); Log.warning(TAG_WIFI, F(D_NETWORK_IP_ADDRESS_RECEIVED), WiFi.localIP().toString().c_str());
WiFi.disconnect(); WiFi.disconnect();
return false; return false;
} }
@ -490,7 +490,7 @@ void wifiStop()
#if !defined(STM32F4xx) #if !defined(STM32F4xx)
WiFi.mode(WIFI_OFF); WiFi.mode(WIFI_OFF);
#endif #endif
Log.warning(TAG_WIFI, F("Stopped")); Log.warning(TAG_WIFI, F(D_SERVICE_STOPPED));
} }
void wifi_get_statusupdate(char * buffer, size_t len) void wifi_get_statusupdate(char * buffer, size_t len)
@ -543,7 +543,7 @@ bool wifiSetConfig(const JsonObject & settings)
} }
if(!settings[FPSTR(F_CONFIG_PASS)].isNull() && if(!settings[FPSTR(F_CONFIG_PASS)].isNull() &&
settings[FPSTR(F_CONFIG_PASS)].as<String>() != String(FPSTR("********"))) { settings[FPSTR(F_CONFIG_PASS)].as<String>() != String(FPSTR(D_PASSWORD_MASK))) {
changed |= strcmp(wifiPassword, settings[FPSTR(F_CONFIG_PASS)]) != 0; changed |= strcmp(wifiPassword, settings[FPSTR(F_CONFIG_PASS)]) != 0;
strncpy(wifiPassword, settings[FPSTR(F_CONFIG_PASS)], sizeof(wifiPassword)); strncpy(wifiPassword, settings[FPSTR(F_CONFIG_PASS)], sizeof(wifiPassword));
} }

View File

@ -23,16 +23,18 @@
#if HASP_USE_HTTP > 0 #if HASP_USE_HTTP > 0
bool httpEnable = true;
bool webServerStarted = false;
uint16_t httpPort = 80;
#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) #if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32)
File fsUploadFile; File fsUploadFile;
#endif #endif
char httpUser[32] = ""; bool webServerStarted = false;
char httpPassword[32] = "";
// bool httpEnable = true;
// uint16_t httpPort = 80;
// char httpUser[32] = "";
// char httpPassword[32] = "";
hasp_http_config_t http_config;
#define HTTP_PAGE_SIZE (6 * 256) #define HTTP_PAGE_SIZE (6 * 256)
#if defined(STM32F4xx) && HASP_USE_ETHERNET > 0 #if defined(STM32F4xx) && HASP_USE_ETHERNET > 0
@ -59,7 +61,7 @@ WebServer webServer(80);
HTTPUpload * upload; HTTPUpload * upload;
const char MAIN_MENU_BUTTON[] PROGMEM = const char MAIN_MENU_BUTTON[] PROGMEM =
"</p><p><form method='get' action='/'><button type='submit'>Main Menu</button></form>"; "</p><p><form method='get' action='/'><button type='submit'>" D_HTTP_MAIN_MENU "</button></form>";
const char MIT_LICENSE[] PROGMEM = "</br>MIT License</p>"; const char MIT_LICENSE[] PROGMEM = "</br>MIT License</p>";
const char HTTP_DOCTYPE[] PROGMEM = const char HTTP_DOCTYPE[] PROGMEM =
@ -68,19 +70,23 @@ const char HTTP_DOCTYPE[] PROGMEM =
const char HTTP_META_GO_BACK[] PROGMEM = "<meta http-equiv='refresh' content='15;url=/'/>"; const char HTTP_META_GO_BACK[] PROGMEM = "<meta http-equiv='refresh' content='15;url=/'/>";
const char HTTP_HEADER[] PROGMEM = "<title>%s</title>"; const char HTTP_HEADER[] PROGMEM = "<title>%s</title>";
const char HTTP_STYLE[] PROGMEM = const char HTTP_STYLE[] PROGMEM =
"<style>.c{text-align:center;}" "<style>"
"body,.c{text-align:center;}"
"div,input{padding:5px;font-size:1em;}" "div,input{padding:5px;font-size:1em;}"
"input{width:90%;}" "input{width:90%;}"
"#hue{width:100%;}" "input[type=checkbox],input[type=radio]{width:1em;}"
"body{text-align:center;font-family:verdana;}" "input:invalid{border:1px solid red;}"
"button{border:0;border-radius:0.6rem;background-color:#1fb3ec;color:#eee;line-height:2.4rem;font-size:1.2rem;" //"#hue{width:100%;}"
"body{font-family:verdana;width:60%;margin:auto;}"
"button{border:0;border-radius:0.6rem;background-color:#0af;color:#eee;line-height:2.4rem;font-size:1.2rem;"
"width:100%;}" "width:100%;}"
".q{float:right;width:64px;text-align:right;}" //".q{float:right;width:64px;text-align:right;}"
".red{background-color:#f33;}" ".red{background-color:#f33;}"
".button3{background-color:#f44336;}" // ".button3{background-color:#f44336;}"
".button4{background-color:#e7e7e7;color:black;}" // ".button4{background-color:#e7e7e7;color:black;}"
".button5{background-color:#555555;}" // ".button5{background-color:#555555;}"
".button6{background-color:#4CAF50;}</style>"; // ".button6{background-color:#4CAF50;}"
"</style>";
const char HTTP_SCRIPT[] PROGMEM = "<script>function " const char HTTP_SCRIPT[] PROGMEM = "<script>function "
"c(l){document.getElementById('s').value=l.innerText||l.textContent;document." "c(l){document.getElementById('s').value=l.innerText||l.textContent;document."
"getElementById('p').focus();}</script>"; "getElementById('p').focus();}</script>";
@ -90,11 +96,6 @@ const char HTTP_END[] PROGMEM = "<div style='text-align:right;font-size:11px;'><
"style='color:#aaa;'>HASP "; "style='color:#aaa;'>HASP ";
const char HTTP_FOOTER[] PROGMEM = " by Francis Van Roie</div></body></html>"; const char HTTP_FOOTER[] PROGMEM = " by Francis Van Roie</div></body></html>";
// Additional CSS style to match Hass theme
const char HASP_STYLE[] PROGMEM =
"<style>button{background-color:#03A9F4;}body{width:60%;margin:auto;}input:invalid{border:"
"1px solid red;}input[type=checkbox]{width:20px;}input[type=radio]{width:20px;}</style>";
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
// URL for auto-update "version.json" // URL for auto-update "version.json"
@ -121,8 +122,8 @@ static inline char * httpGetNodename()
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
bool httpIsAuthenticated(const __FlashStringHelper * fstr_page) bool httpIsAuthenticated(const __FlashStringHelper * fstr_page)
{ {
if(httpPassword[0] != '\0') { // Request HTTP auth if httpPassword is set if(http_config.password[0] != '\0') { // Request HTTP auth if httpPassword is set
if(!webServer.authenticate(httpUser, httpPassword)) { if(!webServer.authenticate(http_config.user, http_config.password)) {
webServer.requestAuthentication(); webServer.requestAuthentication();
return false; return false;
} }
@ -183,7 +184,7 @@ void webSendPage(char * nodename, uint32_t httpdatalength, bool gohome = false)
contentLength += sizeof(HTTP_HEADER) - 1 - 2 + strlen(nodename); // -2 for %s contentLength += sizeof(HTTP_HEADER) - 1 - 2 + strlen(nodename); // -2 for %s
contentLength += sizeof(HTTP_SCRIPT) - 1; contentLength += sizeof(HTTP_SCRIPT) - 1;
contentLength += sizeof(HTTP_STYLE) - 1; contentLength += sizeof(HTTP_STYLE) - 1;
contentLength += sizeof(HASP_STYLE) - 1; // contentLength += sizeof(HASP_STYLE) - 1;
if(gohome) contentLength += sizeof(HTTP_META_GO_BACK) - 1; if(gohome) contentLength += sizeof(HTTP_META_GO_BACK) - 1;
contentLength += sizeof(HTTP_HEADER_END) - 1; contentLength += sizeof(HTTP_HEADER_END) - 1;
contentLength += sizeof(HTTP_END) - 1; contentLength += sizeof(HTTP_END) - 1;
@ -197,7 +198,7 @@ void webSendPage(char * nodename, uint32_t httpdatalength, bool gohome = false)
#if defined(ARDUINO_ARCH_ESP32) || defined(ARDUINO_ARCH_ESP8266) #if defined(ARDUINO_ARCH_ESP32) || defined(ARDUINO_ARCH_ESP8266)
webServer.send_P(200, PSTR("text/html"), HTTP_DOCTYPE); // 122 webServer.send_P(200, PSTR("text/html"), HTTP_DOCTYPE); // 122
#else #else
webServer.send(200, ("text/html"), HTTP_DOCTYPE); // 122 webServer.send(200, ("text/html"), HTTP_DOCTYPE); // 122
#endif #endif
snprintf_P(buffer, sizeof(buffer), HTTP_HEADER, nodename); snprintf_P(buffer, sizeof(buffer), HTTP_HEADER, nodename);
@ -205,15 +206,15 @@ void webSendPage(char * nodename, uint32_t httpdatalength, bool gohome = false)
} }
#if defined(STM32F4xx) #if defined(STM32F4xx)
webServer.sendContent(HTTP_SCRIPT); // 131 webServer.sendContent(HTTP_SCRIPT); // 131
webServer.sendContent(HTTP_STYLE); // 487 webServer.sendContent(HTTP_STYLE); // 487
webServer.sendContent(HASP_STYLE); // 145 // webServer.sendContent(HASP_STYLE); // 145
if(gohome) webServer.sendContent(HTTP_META_GO_BACK); // 47 if(gohome) webServer.sendContent(HTTP_META_GO_BACK); // 47
webServer.sendContent(HTTP_HEADER_END); // 80 webServer.sendContent(HTTP_HEADER_END); // 80
#else #else
webServer.sendContent_P(HTTP_SCRIPT); // 131 webServer.sendContent_P(HTTP_SCRIPT); // 131
webServer.sendContent_P(HTTP_STYLE); // 487 webServer.sendContent_P(HTTP_STYLE); // 487
webServer.sendContent_P(HASP_STYLE); // 145 // webServer.sendContent_P(HASP_STYLE); // 145
if(gohome) webServer.sendContent_P(HTTP_META_GO_BACK); // 47 if(gohome) webServer.sendContent_P(HTTP_META_GO_BACK); // 47
webServer.sendContent_P(HTTP_HEADER_END); // 80 webServer.sendContent_P(HTTP_HEADER_END); // 80
#endif #endif
@ -225,7 +226,7 @@ void saveConfig()
if(webServer.hasArg(PSTR("save"))) { if(webServer.hasArg(PSTR("save"))) {
String save = webServer.arg(PSTR("save")); String save = webServer.arg(PSTR("save"));
DynamicJsonDocument settings(256); StaticJsonDocument<256> settings;
for(int i = 0; i < webServer.args(); i++) settings[webServer.argName(i)] = webServer.arg(i); for(int i = 0; i < webServer.args(); i++) settings[webServer.argName(i)] = webServer.arg(i);
if(save == String(PSTR("hasp"))) { if(save == String(PSTR("hasp"))) {
@ -271,27 +272,29 @@ void webHandleRoot()
httpMessage += httpGetNodename(); httpMessage += httpGetNodename();
httpMessage += F("</h1><hr>"); httpMessage += F("</h1><hr>");
httpMessage += httpMessage += F("<p><form method='get' action='/config/hasp'><button type='submit'>" D_HTTP_HASP_DESIGN
F("<p><form method='get' action='/config/hasp'><button type='submit'>HASP Design</button></form></p>"); "</button></form></p>");
httpMessage += F("<p><form method='get' action='screenshot'><button type='submit'>" D_HTTP_SCREENSHOT
"</button></form></p>");
httpMessage += httpMessage +=
F("<p><form method='get' action='screenshot'><button type='submit'>Screenshot</button></form></p>"); F("<p><form method='get' action='info'><button type='submit'>" D_HTTP_INFORMATION "</button></form></p>");
httpMessage += F("<p><form method='get' action='info'><button type='submit'>Information</button></form></p>"); httpMessage += F("<p><form method='get' action='config'><button type='submit'>" D_HTTP_CONFIGURATION
httpMessage += "</button></form></p>");
F("<p><form method='get' action='config'><button type='submit'>Configuration</button></form></p>");
httpMessage += httpMessage += F("<p><form method='get' action='firmware'><button type='submit'>" D_HTTP_FIRMWARE_UPGRADE
F("<p><form method='get' action='firmware'><button type='submit'>Firmware Upgrade</button></form></p>"); "</button></form></p>");
#if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0 #if HASP_USE_SPIFFS > 0 || HASP_USE_LITTLEFS > 0
if(HASP_FS.exists(F("/edit.htm.gz"))) { if(HASP_FS.exists(F("/edit.htm.gz"))) {
httpMessage += F("<p><form method='get' action='edit.htm.gz?path=/'><button type='submit'>File " httpMessage +=
"Browser</button></form></p>"); F("<p><form method='get' action='edit.htm.gz?path=/'><button type='submit'>" D_HTTP_FILE_BROWSER
"</button></form></p>");
} }
#endif #endif
httpMessage += httpMessage += F("<p><form method='get' action='reboot'><button class='red' type='submit'>" D_HTTP_REBOOT
F("<p><form method='get' action='reboot'><button class='red' type='submit'>Restart</button></form></p>"); "</button></form></p>");
webSendPage(httpGetNodename(), httpMessage.length(), false); webSendPage(httpGetNodename(), httpMessage.length(), false);
webServer.sendContent(httpMessage); webServer.sendContent(httpMessage);
@ -311,7 +314,7 @@ void httpHandleReboot()
httpMessage += F("<h1>"); httpMessage += F("<h1>");
httpMessage += httpGetNodename(); httpMessage += httpGetNodename();
httpMessage += F("</h1><hr>"); httpMessage += F("</h1><hr>");
httpMessage = F("Rebooting Device"); httpMessage = F(D_DISPATCH_REBOOT);
webSendPage(httpGetNodename(), httpMessage.length(), true); webSendPage(httpGetNodename(), httpMessage.length(), true);
webServer.sendContent(httpMessage); webServer.sendContent(httpMessage);
@ -359,13 +362,14 @@ void webHandleScreenshot()
// Automatic refresh // Automatic refresh
httpMessage += F(" onload=\"aref(5)\" onerror=\"aref(5)\"/></p>"); httpMessage += F(" onload=\"aref(5)\" onerror=\"aref(5)\"/></p>");
httpMessage += F("<p><form method='get' onsubmit=\"return ref('')\"><button " httpMessage += F("<p><form method='get' onsubmit=\"return ref('')\"><button type='submit'>" D_HTTP_REFRESH
"type='submit'>Refresh</button></form></p>"); "</button></form></p>");
httpMessage += F("<p><form method='get' onsubmit=\"return ref('prev');\"><button " httpMessage +=
"type='submit'>Previous " F("<p><form method='get' onsubmit=\"return ref('prev');\"><button type='submit'>" D_HTTP_PREV_PAGE
"Page</button></form></p>"); "</button></form></p>");
httpMessage += F("<p><form method='get' onsubmit=\"return ref('next');\"><button type='submit'>Next " httpMessage +=
"Page</button></form></p>"); F("<p><form method='get' onsubmit=\"return ref('next');\"><button type='submit'>" D_HTTP_NEXT_PAGE
"</button></form></p>");
httpMessage += FPSTR(MAIN_MENU_BUTTON); httpMessage += FPSTR(MAIN_MENU_BUTTON);
webSendPage(httpGetNodename(), httpMessage.length(), false); webSendPage(httpGetNodename(), httpMessage.length(), false);
@ -688,7 +692,7 @@ void webUploadProgress()
{ {
long t = webServer.header("Content-Length").toInt(); long t = webServer.header("Content-Length").toInt();
if(millis() - htppLastLoopTime >= 1250) { if(millis() - htppLastLoopTime >= 1250) {
Log.verbose(TAG_HTTP, F(" * Uploaded %u bytes / %d"), upload->totalSize + upload->currentSize, t); Log.verbose(TAG_HTTP, F(D_BULLET "Uploaded %u / %d bytes"), upload->totalSize + upload->currentSize, t);
htppLastLoopTime = millis(); htppLastLoopTime = millis();
} }
if(t > 0) t = (upload->totalSize + upload->currentSize) * 100 / t; if(t > 0) t = (upload->totalSize + upload->currentSize) * 100 / t;
@ -751,7 +755,7 @@ void webHandleFirmwareUpdate()
} else if(upload->status == UPLOAD_FILE_END) { } else if(upload->status == UPLOAD_FILE_END) {
haspProgressVal(100); haspProgressVal(100);
if(Update.end(true)) { // true to set the size to the current progress if(Update.end(true)) { // true to set the size to the current progress
haspProgressMsg(F("Applying Firmware & Reboot")); haspProgressMsg(F(D_OTA_UPDATE_APPLY));
webUpdateReboot(); webUpdateReboot();
} else { } else {
webUpdatePrintError(); webUpdatePrintError();
@ -966,35 +970,36 @@ void webHandleConfig()
httpMessage += F("</h1><hr>"); httpMessage += F("</h1><hr>");
#if HASP_USE_WIFI > 0 #if HASP_USE_WIFI > 0
httpMessage += httpMessage += F("<p><form method='get' action='/config/wifi'><button type='submit'>" D_HTTP_WIFI_SETTINGS
F("<p><form method='get' action='/config/wifi'><button type='submit'>Wifi Settings</button></form></p>"); "</button></form></p>");
#endif #endif
#if HASP_USE_MQTT > 0 #if HASP_USE_MQTT > 0
httpMessage += httpMessage += F("<p><form method='get' action='/config/mqtt'><button type='submit'>" D_HTTP_MQTT_SETTINGS
F("<p><form method='get' action='/config/mqtt'><button type='submit'>MQTT Settings</button></form></p>"); "</button></form></p>");
#endif #endif
httpMessage += httpMessage += F("<p><form method='get' action='/config/http'><button type='submit'>" D_HTTP_HTTP_SETTINGS
F("<p><form method='get' action='/config/http'><button type='submit'>HTTP Settings</button></form></p>"); "</button></form></p>");
httpMessage += httpMessage += F("<p><form method='get' action='/config/gui'><button type='submit'>" D_HTTP_GUI_SETTINGS
F("<p><form method='get' action='/config/gui'><button type='submit'>Display Settings</button></form></p>"); "</button></form></p>");
// httpMessage += // httpMessage +=
// F("<p><form method='get' action='/config/hasp'><button type='submit'>HASP // F("<p><form method='get' action='/config/hasp'><button type='submit'>HASP
// Settings</button></form></p>"); // Settings</button></form></p>");
#if HASP_USE_GPIO > 0 #if HASP_USE_GPIO > 0
httpMessage += httpMessage += F("<p><form method='get' action='/config/gpio'><button type='submit'>" D_HTTP_GPIO_SETTINGS
F("<p><form method='get' action='/config/gpio'><button type='submit'>GPIO Settings</button></form></p>"); "</button></form></p>");
#endif #endif
httpMessage += httpMessage += F("<p><form method='get' action='/config/debug'><button type='submit'>" D_HTTP_DEBUG_SETTINGS
F("<p><form method='get' action='/config/debug'><button type='submit'>Debug Settings</button></form></p>"); "</button></form></p>");
httpMessage += F("<p><form method='get' action='resetConfig'><button class='red' type='submit'>Factory Reset" httpMessage +=
"</button></form>"); F("<p><form method='get' action='resetConfig'><button class='red' type='submit'>" D_HTTP_FACTORY_RESET
"</button></form>");
httpMessage += FPSTR(MAIN_MENU_BUTTON); httpMessage += FPSTR(MAIN_MENU_BUTTON);
@ -1011,7 +1016,7 @@ void webHandleMqttConfig()
{ // http://plate01/config/mqtt { // http://plate01/config/mqtt
if(!httpIsAuthenticated(F("config/mqtt"))) return; if(!httpIsAuthenticated(F("config/mqtt"))) return;
DynamicJsonDocument settings(256); StaticJsonDocument<256> settings;
mqttGetConfig(settings.to<JsonObject>()); mqttGetConfig(settings.to<JsonObject>());
{ {
@ -1041,11 +1046,12 @@ void webHandleMqttConfig()
httpMessage += settings[FPSTR(F_CONFIG_USER)].as<String>(); httpMessage += settings[FPSTR(F_CONFIG_USER)].as<String>();
httpMessage += F("'><br/><b>MQTT Password</b> <i><small>(optional)</small></i><input id='pass' " httpMessage += F("'><br/><b>MQTT Password</b> <i><small>(optional)</small></i><input id='pass' "
"name='pass' type='password' maxlength=31 placeholder='mqttPassword' value='"); "name='pass' type='password' maxlength=31 placeholder='mqttPassword' value='");
if(settings[FPSTR(F_CONFIG_PASS)].as<String>() != "") httpMessage += F("********"); if(settings[FPSTR(F_CONFIG_PASS)].as<String>() != "") httpMessage += F(D_PASSWORD_MASK);
httpMessage += F("'><p><button type='submit' name='save' value='mqtt'>Save Settings</button></form></p>");
httpMessage += httpMessage +=
PSTR("<p><form method='get' action='/config'><button type='submit'>Configuration</button></form></p>"); F("'><p><button type='submit' name='save' value='mqtt'>" D_HTTP_SAVE_SETTINGS "</button></form></p>");
httpMessage += PSTR("<p><form method='get' action='/config'><button type='submit'>&#8617; " D_HTTP_CONFIGURATION
"</button></form></p>");
webSendPage(httpGetNodename(), httpMessage.length(), false); webSendPage(httpGetNodename(), httpMessage.length(), false);
webServer.sendContent(httpMessage); webServer.sendContent(httpMessage);
@ -1061,7 +1067,7 @@ void webHandleGuiConfig()
if(!httpIsAuthenticated(F("config/gui"))) return; if(!httpIsAuthenticated(F("config/gui"))) return;
{ {
DynamicJsonDocument settings(256); StaticJsonDocument<256> settings;
guiGetConfig(settings.to<JsonObject>()); guiGetConfig(settings.to<JsonObject>());
String httpMessage((char *)0); String httpMessage((char *)0);
@ -1107,6 +1113,7 @@ void webHandleGuiConfig()
httpMessage += getOption(-1, F("None"), bcklpin == -1); httpMessage += getOption(-1, F("None"), bcklpin == -1);
#if defined(ARDUINO_ARCH_ESP32) #if defined(ARDUINO_ARCH_ESP32)
httpMessage += getOption(5, F("GPIO 5"), bcklpin == 5); // D8 on ESP32 for D1 mini 32 httpMessage += getOption(5, F("GPIO 5"), bcklpin == 5); // D8 on ESP32 for D1 mini 32
httpMessage += getOption(12, F("GPIO 12"), bcklpin == 12); // TFT_LED on the Liligo Pi
httpMessage += getOption(16, F("GPIO 16"), bcklpin == 16); // D4 on ESP32 for D1 mini 32 httpMessage += getOption(16, F("GPIO 16"), bcklpin == 16); // D4 on ESP32 for D1 mini 32
httpMessage += getOption(17, F("GPIO 17"), bcklpin == 17); // D3 on ESP32 for D1 mini 32 httpMessage += getOption(17, F("GPIO 17"), bcklpin == 17); // D3 on ESP32 for D1 mini 32
httpMessage += getOption(18, F("GPIO 18"), bcklpin == 18); // D5 on ESP32 for D1 mini 32 httpMessage += getOption(18, F("GPIO 18"), bcklpin == 18); // D5 on ESP32 for D1 mini 32
@ -1123,15 +1130,16 @@ void webHandleGuiConfig()
#endif #endif
httpMessage += F("</select></p>"); httpMessage += F("</select></p>");
httpMessage += F("<p><button type='submit' name='save' value='gui'>Save Settings</button></p></form>"); httpMessage +=
F("<p><button type='submit' name='save' value='gui'>" D_HTTP_SAVE_SETTINGS "</button></p></form>");
#if TOUCH_DRIVER == 2046 && defined(TOUCH_CS) #if TOUCH_DRIVER == 2046 && defined(TOUCH_CS)
httpMessage += PSTR("<p><form method='get' action='/config/gui'><button type='submit' name='action' " httpMessage += PSTR("<p><form method='get' action='/config/gui'><button type='submit' name='action' "
"value='calibrate'>Calibrate</button></form></p>"); "value='calibrate'>" D_HTTP_CALIBRATE "</button></form></p>");
#endif #endif
httpMessage += httpMessage += PSTR("<p><form method='get' action='/config'><button type='submit'>&#8617; " D_HTTP_CONFIGURATION
PSTR("<p><form method='get' action='/config'><button type='submit'>Configuration</button></form></p>"); "</button></form></p>");
webSendPage(httpGetNodename(), httpMessage.length(), false); webSendPage(httpGetNodename(), httpMessage.length(), false);
webServer.sendContent(httpMessage); webServer.sendContent(httpMessage);
@ -1147,7 +1155,7 @@ void webHandleWifiConfig()
{ // http://plate01/config/wifi { // http://plate01/config/wifi
if(!httpIsAuthenticated(F("config/wifi"))) return; if(!httpIsAuthenticated(F("config/wifi"))) return;
DynamicJsonDocument settings(256); StaticJsonDocument<256> settings;
wifiGetConfig(settings.to<JsonObject>()); wifiGetConfig(settings.to<JsonObject>());
String httpMessage((char *)0); String httpMessage((char *)0);
@ -1163,14 +1171,15 @@ void webHandleWifiConfig()
httpMessage += F("'><br/><b>WiFi Password</b> <i><small>(required)</small></i><input id='pass' required " httpMessage += F("'><br/><b>WiFi Password</b> <i><small>(required)</small></i><input id='pass' required "
"name='pass' type='password' maxlength=63 placeholder='WiFi Password' value='"); "name='pass' type='password' maxlength=63 placeholder='WiFi Password' value='");
if(settings[FPSTR(F_CONFIG_PASS)].as<String>() != "") { if(settings[FPSTR(F_CONFIG_PASS)].as<String>() != "") {
httpMessage += F("********"); httpMessage += F(D_PASSWORD_MASK);
} }
httpMessage += F("'><p><button type='submit' name='save' value='wifi'>Save Settings</button></p></form>"); httpMessage +=
F("'><p><button type='submit' name='save' value='wifi'>" D_HTTP_SAVE_SETTINGS "</button></p></form>");
#if HASP_USE_WIFI > 0 && !defined(STM32F4xx) #if HASP_USE_WIFI > 0 && !defined(STM32F4xx)
if(WiFi.getMode() == WIFI_STA) { if(WiFi.getMode() == WIFI_STA) {
httpMessage += httpMessage += PSTR("<p><form method='get' action='/config'><button type='submit'>&#8617; " D_HTTP_CONFIGURATION
PSTR("<p><form method='get' action='/config'><button type='submit'>Configuration</button></form></p>"); "</button></form></p>");
} }
#endif #endif
@ -1192,7 +1201,7 @@ void webHandleHttpConfig()
if(!httpIsAuthenticated(F("config/http"))) return; if(!httpIsAuthenticated(F("config/http"))) return;
{ {
DynamicJsonDocument settings(256); StaticJsonDocument<256> settings;
httpGetConfig(settings.to<JsonObject>()); httpGetConfig(settings.to<JsonObject>());
String httpMessage((char *)0); String httpMessage((char *)0);
@ -1208,12 +1217,13 @@ void webHandleHttpConfig()
httpMessage += F("'><br/><b>Web Password</b> <i><small>(optional)</small></i><input id='pass' " httpMessage += F("'><br/><b>Web Password</b> <i><small>(optional)</small></i><input id='pass' "
"name='pass' type='password' maxlength=63 placeholder='Password' value='"); "name='pass' type='password' maxlength=63 placeholder='Password' value='");
if(settings[FPSTR(F_CONFIG_PASS)].as<String>() != "") { if(settings[FPSTR(F_CONFIG_PASS)].as<String>() != "") {
httpMessage += F("********"); httpMessage += F(D_PASSWORD_MASK);
} }
httpMessage += F("'><p><button type='submit' name='save' value='http'>Save Settings</button></p></form>");
httpMessage += httpMessage +=
PSTR("<p><form method='get' action='/config'><button type='submit'>Configuration</button></form></p>"); F("'><p><button type='submit' name='save' value='http'>" D_HTTP_SAVE_SETTINGS "</button></p></form>");
httpMessage += PSTR("<p><form method='get' action='/config'><button type='submit'>&#8617; " D_HTTP_CONFIGURATION
"</button></form></p>");
webSendPage(httpGetNodename(), httpMessage.length(), false); webSendPage(httpGetNodename(), httpMessage.length(), false);
webServer.sendContent(httpMessage); webServer.sendContent(httpMessage);
@ -1230,7 +1240,7 @@ void webHandleGpioConfig()
if(!httpIsAuthenticated(F("config/gpio"))) return; if(!httpIsAuthenticated(F("config/gpio"))) return;
uint8_t configCount = 0; uint8_t configCount = 0;
// DynamicJsonDocument settings(256); // StaticJsonDocument<256> settings;
// gpioGetConfig(settings.to<JsonObject>()); // gpioGetConfig(settings.to<JsonObject>());
if(webServer.hasArg(PSTR("save"))) { if(webServer.hasArg(PSTR("save"))) {
@ -1335,14 +1345,14 @@ void webHandleGpioConfig()
httpMessage += F("</table></form>"); httpMessage += F("</table></form>");
if(configCount < HASP_NUM_GPIO_CONFIG) { if(configCount < HASP_NUM_GPIO_CONFIG) {
httpMessage += PSTR("<p><form method='GET' action='gpio/options'>"); httpMessage += F("<p><form method='GET' action='gpio/options'>");
httpMessage += F("<input type='hidden' name='id' value='"); httpMessage += F("<input type='hidden' name='id' value='");
httpMessage += gpioGetFreeConfigId(); httpMessage += gpioGetFreeConfigId();
httpMessage += PSTR("'><button type='submit'>Add New Pin</button></form></p>"); httpMessage += F("'><button type='submit'>" D_HTTP_ADD_GPIO "</button></form></p>");
} }
httpMessage += PSTR( httpMessage += F("<p><form method='get' action='/config'><button type='submit'>&#8617; " D_HTTP_CONFIGURATION
"<p><form method='get' action='/config'><button type='submit'>&#8617; Configuration</button></form></p>"); "</button></form></p>");
webSendPage(httpGetNodename(), httpMessage.length(), false); webSendPage(httpGetNodename(), httpMessage.length(), false);
webServer.sendContent(httpMessage); webServer.sendContent(httpMessage);
@ -1357,7 +1367,7 @@ void webHandleGpioOptions()
if(!httpIsAuthenticated(F("config/gpio/options"))) return; if(!httpIsAuthenticated(F("config/gpio/options"))) return;
{ {
DynamicJsonDocument settings(256); StaticJsonDocument<256> settings;
guiGetConfig(settings.to<JsonObject>()); guiGetConfig(settings.to<JsonObject>());
uint8_t config_id = webServer.arg(F("id")).toInt(); uint8_t config_id = webServer.arg(F("id")).toInt();
@ -1437,10 +1447,11 @@ void webHandleGpioOptions()
httpMessage += getOption(0, F("Low"), !inverted); httpMessage += getOption(0, F("Low"), !inverted);
httpMessage += F("</select></p>"); httpMessage += F("</select></p>");
httpMessage += F("<p><button type='submit' name='save' value='gpio'>Save Settings</button></p></form>");
httpMessage += httpMessage +=
PSTR("<p><form method='get' action='/config/gpio'><button type='submit'>&#8617; Back</button></form></p>"); F("<p><button type='submit' name='save' value='gpio'>" D_HTTP_SAVE_SETTINGS "</button></p></form>");
httpMessage += PSTR("<p><form method='get' action='/config/gpio'><button type='submit'>&#8617; " D_HTTP_BACK
"</button></form></p>");
webSendPage(httpGetNodename(), httpMessage.length(), false); webSendPage(httpGetNodename(), httpMessage.length(), false);
webServer.sendContent(httpMessage); webServer.sendContent(httpMessage);
@ -1456,7 +1467,7 @@ void webHandleDebugConfig()
{ // http://plate01/config/debug { // http://plate01/config/debug
if(!httpIsAuthenticated(F("config/debug"))) return; if(!httpIsAuthenticated(F("config/debug"))) return;
DynamicJsonDocument settings(256); StaticJsonDocument<256> settings;
debugGetConfig(settings.to<JsonObject>()); debugGetConfig(settings.to<JsonObject>());
{ {
@ -1503,10 +1514,11 @@ void webHandleDebugConfig()
httpMessage += F(">BSD (RFC 3164)"); httpMessage += F(">BSD (RFC 3164)");
#endif #endif
httpMessage += F("</p><p><button type='submit' name='save' value='debug'>Save Settings</button></p></form>");
httpMessage += httpMessage +=
PSTR("<p><form method='get' action='/config'><button type='submit'>Configuration</button></form></p>"); F("</p><p><button type='submit' name='save' value='debug'>" D_HTTP_SAVE_SETTINGS "</button></p></form>");
httpMessage += PSTR("<p><form method='get' action='/config'><button type='submit'>&#8617; " D_HTTP_CONFIGURATION
"</button></form></p>");
webSendPage(httpGetNodename(), httpMessage.length(), false); webSendPage(httpGetNodename(), httpMessage.length(), false);
webServer.sendContent(httpMessage); webServer.sendContent(httpMessage);
@ -1520,7 +1532,7 @@ void webHandleHaspConfig()
{ // http://plate01/config/http { // http://plate01/config/http
if(!httpIsAuthenticated(F("config/hasp"))) return; if(!httpIsAuthenticated(F("config/hasp"))) return;
DynamicJsonDocument settings(256); StaticJsonDocument<256> settings;
haspGetConfig(settings.to<JsonObject>()); haspGetConfig(settings.to<JsonObject>());
{ {
@ -1532,7 +1544,7 @@ void webHandleHaspConfig()
httpMessage += F("<p><form action='/edit' method='post' enctype='multipart/form-data'><input type='file' " httpMessage += F("<p><form action='/edit' method='post' enctype='multipart/form-data'><input type='file' "
"name='filename' accept='.jsonl,.zi'>"); "name='filename' accept='.jsonl,.zi'>");
httpMessage += F("<button type='submit'>Upload File</button></form></p><hr>"); httpMessage += F("<button type='submit'>" D_HTTP_UPLOAD_FILE "</button></form></p><hr>");
// httpMessage += F("<form method='POST' action='/config'>"); // httpMessage += F("<form method='POST' action='/config'>");
httpMessage += F("<form method='POST' action='/'>"); httpMessage += F("<form method='POST' action='/'>");
@ -1560,7 +1572,7 @@ void webHandleHaspConfig()
httpMessage += F("</select></br>"); httpMessage += F("</select></br>");
httpMessage += httpMessage +=
F("<b>Hue</b><div style='width:100%;background-image:linear-gradient(to " F("<b>Hue</b><div style='width:100%;background-image:linear-gradient(to "
"right,red,orange,yellow,green,blue,indigo,violet);'><input style='align:center;padding:0px' id='hue' " "right,red,orange,yellow,green,blue,indigo,violet);'><input style='align:center;padding:0px;width:100%;' "
"name='hue' type='range' min='0' max='360' value='"); "name='hue' type='range' min='0' max='360' value='");
httpMessage += settings[FPSTR(F_CONFIG_HUE)].as<String>(); httpMessage += settings[FPSTR(F_CONFIG_HUE)].as<String>();
httpMessage += F("'></div></p>"); httpMessage += F("'></div></p>");
@ -1603,10 +1615,12 @@ void webHandleHaspConfig()
httpMessage += settings[FPSTR(F_CONFIG_STARTDIM)].as<String>(); httpMessage += settings[FPSTR(F_CONFIG_STARTDIM)].as<String>();
httpMessage += F("'></p>"); httpMessage += F("'></p>");
httpMessage += F("<p><button type='submit' name='save' value='hasp'>Save Settings</button></form></p>"); httpMessage +=
F("<p><button type='submit' name='save' value='hasp'>" D_HTTP_SAVE_SETTINGS "</button></form></p>");
// httpMessage += // httpMessage +=
// F("<p><form method='get' action='/config'><button type='submit'>Configuration</button></form></p>"); // F("<p><form method='get' action='/config'><button
// type='submit'>"D_HTTP_CONFIGURATION"</button></form></p>");
httpMessage += FPSTR(MAIN_MENU_BUTTON); httpMessage += FPSTR(MAIN_MENU_BUTTON);
webSendPage(httpGetNodename(), httpMessage.length(), false); webSendPage(httpGetNodename(), httpMessage.length(), false);
@ -1661,7 +1675,7 @@ void webHandleFirmware()
httpMessage += F("<p><form action='/update' method='post' enctype='multipart/form-data'><input type='file' " httpMessage += F("<p><form action='/update' method='post' enctype='multipart/form-data'><input type='file' "
"name='filename' accept='.bin'>"); "name='filename' accept='.bin'>");
httpMessage += F("<button type='submit'>Update Firmware</button></form></p>"); httpMessage += F("<button type='submit'>" D_HTTP_UPDATE_FIRMWARE "</button></form></p>");
// httpMessage += F("<p><form action='/update' method='post' enctype='multipart/form-data'><input type='file' " // httpMessage += F("<p><form action='/update' method='post' enctype='multipart/form-data'><input type='file' "
// "name='filename' accept='.spiffs'>"); // "name='filename' accept='.spiffs'>");
@ -1740,11 +1754,12 @@ void httpHandleResetConfig()
"panel to " "panel to "
"re-configure the device before accessing it again. ALL FILES WILL BE LOST!" "re-configure the device before accessing it again. ALL FILES WILL BE LOST!"
"<br/><hr><br/><form method='get' action='resetConfig'>" "<br/><hr><br/><form method='get' action='resetConfig'>"
"<br/><br/><button type='submit' name='confirm' value='yes'>Reset All Settings</button></form>" "<br/><br/><button type='submit' name='confirm' value='yes'>" D_HTTP_ERASE_DEVICE "</button></form>"
"<br/><hr><br/>"); "<br/><hr><br/>");
httpMessage += httpMessage +=
PSTR("<p><form method='get' action='/config'><button type='submit'>Configuration</button></form></p>"); PSTR("<p><form method='get' action='/config'><button type='submit'>&#8617; " D_HTTP_CONFIGURATION
"</button></form></p>");
} }
webSendPage(httpGetNodename(), httpMessage.length(), resetConfirmed); webSendPage(httpGetNodename(), httpMessage.length(), resetConfirmed);
@ -1769,9 +1784,9 @@ void httpStart()
#if defined(STM32F4xx) #if defined(STM32F4xx)
IPAddress ip; IPAddress ip;
ip = WiFi.localIP(); ip = WiFi.localIP();
Log.trace(TAG_HTTP, F("Server started @ http://%d.%d.%d.%d"), ip[0], ip[1], ip[2], ip[3]); Log.trace(TAG_HTTP, F(D_SERVICE_STARTED " @ http://%d.%d.%d.%d"), ip[0], ip[1], ip[2], ip[3]);
#else #else
Log.trace(TAG_HTTP, F("Server started @ http://%s"), Log.trace(TAG_HTTP, F(D_SERVICE_STARTED " @ http://%s"),
(WiFi.getMode() != WIFI_STA ? WiFi.softAPIP().toString().c_str() : WiFi.localIP().toString().c_str())); (WiFi.getMode() != WIFI_STA ? WiFi.softAPIP().toString().c_str() : WiFi.localIP().toString().c_str()));
#endif #endif
#else #else
@ -1781,7 +1796,7 @@ void httpStart()
#else #else
ip = Ethernet.localIP(); ip = Ethernet.localIP();
#endif #endif
Log.trace(TAG_HTTP, F("Server started @ http://%d.%d.%d.%d"), ip[0], ip[1], ip[2], ip[3]); Log.trace(TAG_HTTP, F(D_SERVICE_STARTED " @ http://%d.%d.%d.%d"), ip[0], ip[1], ip[2], ip[3]);
#endif #endif
} }
@ -1789,7 +1804,7 @@ void httpStop()
{ {
webServer.stop(); webServer.stop();
webServerStarted = false; webServerStarted = false;
Log.warning(TAG_HTTP, F("Server stoped")); Log.warning(TAG_HTTP, F(D_SERVICE_STOPPED));
} }
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
@ -1887,14 +1902,14 @@ void httpSetup()
webServer.on(F("/espfirmware"), httpHandleEspFirmware); webServer.on(F("/espfirmware"), httpHandleEspFirmware);
#endif #endif
Log.trace(TAG_HTTP, F("Setup Complete")); Log.trace(TAG_HTTP, F(D_SERVICE_STARTED));
// webStart(); Wait for network connection // webStart(); Wait for network connection
} }
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
void httpReconnect() void httpReconnect()
{ {
if(!httpEnable) return; if(!http_config.enable) return;
if(webServerStarted) { if(webServerStarted) {
httpStop(); httpStop();
@ -1910,7 +1925,7 @@ void httpReconnect()
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
void IRAM_ATTR httpLoop(void) void IRAM_ATTR httpLoop(void)
{ {
if(httpEnable) webServer.handleClient(); if(http_config.enable) webServer.handleClient();
} }
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
@ -1925,16 +1940,16 @@ bool httpGetConfig(const JsonObject & settings)
{ {
bool changed = false; bool changed = false;
settings[FPSTR(F_CONFIG_ENABLE)] = httpEnable; settings[FPSTR(F_CONFIG_ENABLE)] = http_config.enable;
if(httpPort != settings[FPSTR(F_CONFIG_PORT)].as<uint16_t>()) changed = true; if(http_config.port != settings[FPSTR(F_CONFIG_PORT)].as<uint16_t>()) changed = true;
settings[FPSTR(F_CONFIG_PORT)] = httpPort; settings[FPSTR(F_CONFIG_PORT)] = http_config.port;
if(strcmp(httpUser, settings[FPSTR(F_CONFIG_USER)].as<String>().c_str()) != 0) changed = true; if(strcmp(http_config.user, settings[FPSTR(F_CONFIG_USER)].as<String>().c_str()) != 0) changed = true;
settings[FPSTR(F_CONFIG_USER)] = httpUser; settings[FPSTR(F_CONFIG_USER)] = http_config.user;
if(strcmp(httpPassword, settings[FPSTR(F_CONFIG_PASS)].as<String>().c_str()) != 0) changed = true; if(strcmp(http_config.password, settings[FPSTR(F_CONFIG_PASS)].as<String>().c_str()) != 0) changed = true;
settings[FPSTR(F_CONFIG_PASS)] = httpPassword; settings[FPSTR(F_CONFIG_PASS)] = http_config.password;
if(changed) configOutput(settings, TAG_HTTP); if(changed) configOutput(settings, TAG_HTTP);
return changed; return changed;
@ -1953,16 +1968,16 @@ bool httpSetConfig(const JsonObject & settings)
configOutput(settings, TAG_HTTP); configOutput(settings, TAG_HTTP);
bool changed = false; bool changed = false;
changed |= configSet(httpPort, settings[FPSTR(F_CONFIG_PORT)], F("httpPort")); changed |= configSet(http_config.port, settings[FPSTR(F_CONFIG_PORT)], F("httpPort"));
if(!settings[FPSTR(F_CONFIG_USER)].isNull()) { if(!settings[FPSTR(F_CONFIG_USER)].isNull()) {
changed |= strcmp(httpUser, settings[FPSTR(F_CONFIG_USER)]) != 0; changed |= strcmp(http_config.user, settings[FPSTR(F_CONFIG_USER)]) != 0;
strncpy(httpUser, settings[FPSTR(F_CONFIG_USER)], sizeof(httpUser)); strncpy(http_config.user, settings[FPSTR(F_CONFIG_USER)], sizeof(http_config.user));
} }
if(!settings[FPSTR(F_CONFIG_PASS)].isNull()) { if(!settings[FPSTR(F_CONFIG_PASS)].isNull()) {
changed |= strcmp(httpPassword, settings[FPSTR(F_CONFIG_PASS)]) != 0; changed |= strcmp(http_config.password, settings[FPSTR(F_CONFIG_PASS)]) != 0;
strncpy(httpPassword, settings[FPSTR(F_CONFIG_PASS)], sizeof(httpPassword)); strncpy(http_config.password, settings[FPSTR(F_CONFIG_PASS)], sizeof(http_config.password));
} }
return changed; return changed;

View File

@ -6,6 +6,15 @@
#include "hasp_conf.h" #include "hasp_conf.h"
struct hasp_http_config_t
{
bool enable = true;
uint16_t port = 80;
char user[32] = "";
char password[32] = "";
};
void httpSetup(); void httpSetup();
void IRAM_ATTR httpLoop(void); void IRAM_ATTR httpLoop(void);
void httpEvery5Seconds(void); void httpEvery5Seconds(void);

View File

@ -15,7 +15,8 @@
#include "hasp_config.h" #include "hasp_config.h"
#include "hasp_debug.h" #include "hasp_debug.h"
uint8_t mdnsEnabled = true; // uint8_t mdnsEnabled = true;
hasp_mdns_config_t mdns_config;
void mdnsSetup() void mdnsSetup()
{ {
@ -25,12 +26,12 @@ void mdnsSetup()
void mdnsStart() void mdnsStart()
{ {
if(!mdnsEnabled) { if(!mdns_config.enable) {
Log.notice(TAG_MDNS, F("MDNS Responder is disabled")); Log.notice(TAG_MDNS, F(D_SERVICE_DISABLED));
return; return;
} }
Log.notice(TAG_MDNS, F("Starting MDNS Responder...")); Log.notice(TAG_MDNS, F(D_SERVICE_STARTING));
#if HASP_USE_MQTT > 0 #if HASP_USE_MQTT > 0
String hasp2Node = mqttGetNodename(); String hasp2Node = mqttGetNodename();
@ -45,7 +46,7 @@ void mdnsStart()
uint8_t attempt = 0; uint8_t attempt = 0;
while(!MDNS.begin(hasp2Node.c_str())) { while(!MDNS.begin(hasp2Node.c_str())) {
if(attempt++ >= 3) { if(attempt++ >= 3) {
Log.error(TAG_MDNS, F("Responder failed to start %s"), hasp2Node.c_str()); Log.error(TAG_MDNS, F(D_SERVICE_START_FAILED ": %s"), hasp2Node.c_str());
return; return;
} }
@ -64,13 +65,13 @@ void mdnsStart()
MDNS.addService(F("telnet"), F("tcp"), 23); MDNS.addService(F("telnet"), F("tcp"), 23);
// } // }
Log.trace(TAG_MDNS, F("Responder started")); Log.trace(TAG_MDNS, F(D_SERVICE_STARTED));
} }
void IRAM_ATTR mdnsLoop(void) void IRAM_ATTR mdnsLoop(void)
{ {
#if defined(ARDUINO_ARCH_ESP8266) #if defined(ARDUINO_ARCH_ESP8266)
if(mdnsEnabled) { if(mdns_config.enable) {
MDNS.update(); MDNS.update();
} }
#endif #endif
@ -89,8 +90,8 @@ bool mdnsGetConfig(const JsonObject & settings)
{ {
bool changed = false; bool changed = false;
if(mdnsEnabled != settings[FPSTR(F_CONFIG_ENABLE)].as<bool>()) changed = true; if(mdns_config.enable != settings[FPSTR(F_CONFIG_ENABLE)].as<bool>()) changed = true;
settings[FPSTR(F_CONFIG_ENABLE)] = mdnsEnabled; settings[FPSTR(F_CONFIG_ENABLE)] = mdns_config.enable;
if(changed) configOutput(settings, TAG_MDNS); if(changed) configOutput(settings, TAG_MDNS);
return changed; return changed;
@ -106,7 +107,7 @@ bool mdnsSetConfig(const JsonObject & settings)
configOutput(settings, TAG_MDNS); configOutput(settings, TAG_MDNS);
bool changed = false; bool changed = false;
changed |= configSet(mdnsEnabled, settings[FPSTR(F_CONFIG_ENABLE)], F("mdnsEnabled")); changed |= configSet(mdns_config.enable, settings[FPSTR(F_CONFIG_ENABLE)], F("mdnsEnabled"));
return changed; return changed;
} }

View File

@ -6,6 +6,11 @@
#include "ArduinoJson.h" #include "ArduinoJson.h"
struct hasp_mdns_config_t
{
uint8_t enable = true;
};
/* ===== Default Event Processors ===== */ /* ===== Default Event Processors ===== */
void mdnsSetup(); void mdnsSetup();
void IRAM_ATTR mdnsLoop(void); void IRAM_ATTR mdnsLoop(void);

View File

@ -44,9 +44,6 @@ EthernetClient mqttNetworkClient;
#include "user_config_override.h" #include "user_config_override.h"
#endif #endif
// String mqttClientId((char *)0); // Auto-generated MQTT ClientID
// String mqttNodeTopic((char *)0);
// String mqttGroupTopic((char *)0);
char mqttNodeTopic[24]; char mqttNodeTopic[24];
char mqttGroupTopic[24]; char mqttGroupTopic[24];
bool mqttEnabled = false; bool mqttEnabled = false;
@ -98,10 +95,10 @@ static bool mqttPublish(const char * topic, const char * payload, size_t len, bo
Log.notice(TAG_MQTT_PUB, F("%s => %s"), topic, payload); Log.notice(TAG_MQTT_PUB, F("%s => %s"), topic, payload);
return true; return true;
} else { } else {
Log.error(TAG_MQTT_PUB, F("Failed : %s => %s"), topic, payload); Log.error(TAG_MQTT_PUB, F(D_MQTT_FAILED " %s => %s"), topic, payload);
} }
} else { } else {
Log.error(TAG_MQTT, F("Not connected")); Log.error(TAG_MQTT, F(D_MQTT_NOT_CONNECTED));
} }
return false; return false;
} }
@ -178,7 +175,7 @@ static void mqtt_message_cb(char * topic, byte * payload, unsigned int length)
} else { } else {
// Other topic // Other topic
Log.error(TAG_MQTT, F("Message received with invalid topic")); Log.error(TAG_MQTT, F(D_MQTT_INVALID_TOPIC));
return; return;
} }
@ -207,9 +204,9 @@ static void mqttSubscribeTo(const char * format, const char * data)
char tmp_topic[strlen(format) + 2 + strlen(data)]; char tmp_topic[strlen(format) + 2 + strlen(data)];
snprintf_P(tmp_topic, sizeof(tmp_topic), format, data); snprintf_P(tmp_topic, sizeof(tmp_topic), format, data);
if(mqttClient.subscribe(tmp_topic)) { if(mqttClient.subscribe(tmp_topic)) {
Log.verbose(TAG_MQTT, F(" * Subscribed to %s"), tmp_topic); Log.verbose(TAG_MQTT, F(D_BULLET D_MQTT_SUBSCRIBED), tmp_topic);
} else { } else {
Log.error(TAG_MQTT, F("Failed to subscribe to %s"), tmp_topic); Log.error(TAG_MQTT, F(D_MQTT_NOT_SUBSCRIBED), tmp_topic);
} }
} }
@ -229,7 +226,7 @@ void mqttStart()
String mac = halGetMacAddress(3, ""); String mac = halGetMacAddress(3, "");
mac.toLowerCase(); mac.toLowerCase();
memset(mqttClientId, 0, sizeof(mqttClientId)); memset(mqttClientId, 0, sizeof(mqttClientId));
snprintf_P(mqttClientId, sizeof(mqttClientId), PSTR("plate_%s"), mac.c_str()); snprintf_P(mqttClientId, sizeof(mqttClientId), PSTR(D_MQTT_DEFAULT_NAME), mac.c_str());
Log.trace(TAG_MQTT, mqttClientId); Log.trace(TAG_MQTT, mqttClientId);
} }
@ -237,7 +234,7 @@ void mqttStart()
snprintf_P(buffer, sizeof(buffer), PSTR("%sLWT"), mqttNodeTopic); // lastWillTopic snprintf_P(buffer, sizeof(buffer), PSTR("%sLWT"), mqttNodeTopic); // lastWillTopic
snprintf_P(lastWillPayload, sizeof(lastWillPayload), PSTR("offline")); // lastWillPayload snprintf_P(lastWillPayload, sizeof(lastWillPayload), PSTR("offline")); // lastWillPayload
haspProgressMsg(F("Connecting MQTT...")); haspProgressMsg(F(D_MQTT_CONNECTING));
haspProgressVal(mqttReconnectCount * 5); haspProgressVal(mqttReconnectCount * 5);
if(!mqttClient.connect(mqttClientId, mqttUser, mqttPassword, buffer, 0, true, lastWillPayload, true)) { if(!mqttClient.connect(mqttClientId, mqttUser, mqttPassword, buffer, 0, true, lastWillPayload, true)) {
// Retry until we give up and restart after connectTimeout seconds // Retry until we give up and restart after connectTimeout seconds
@ -254,7 +251,7 @@ void mqttStart()
snprintf_P(buffer, sizeof(buffer), PSTR("Connection failed")); snprintf_P(buffer, sizeof(buffer), PSTR("Connection failed"));
break; break;
case MQTT_DISCONNECTED: case MQTT_DISCONNECTED:
snprintf_P(buffer, sizeof(buffer), PSTR("Disconnected")); snprintf_P(buffer, sizeof(buffer), PSTR(D_MQTT_DISCONNECTED));
break; break;
case MQTT_CONNECTED: case MQTT_CONNECTED:
break; break;
@ -285,7 +282,7 @@ void mqttStart()
return; return;
} }
Log.trace(TAG_MQTT, F("Connected to broker %s as clientID %s"), mqttServer, mqttClientId); Log.trace(TAG_MQTT, F(D_MQTT_CONNECTED), mqttServer, mqttClientId);
// Subscribe to our incoming topics // Subscribe to our incoming topics
mqttSubscribeTo(PSTR("%scommand/#"), mqttGroupTopic); mqttSubscribeTo(PSTR("%scommand/#"), mqttGroupTopic);
@ -318,15 +315,15 @@ void mqttSetup()
{ {
mqttEnabled = strlen(mqttServer) > 0 && mqttPort > 0; mqttEnabled = strlen(mqttServer) > 0 && mqttPort > 0;
if(mqttEnabled) { if(mqttEnabled) {
mqttClient.setServer(mqttServer, 1883); mqttClient.setServer(mqttServer, mqttPort);
mqttClient.setCallback(mqtt_message_cb); mqttClient.setCallback(mqtt_message_cb);
// if(!mqttClient.setBufferSize(1024)) { // if(!mqttClient.setBufferSize(1024)) {
// Log.error(TAG_MQTT, F("Buffer allocation failed")); // Log.error(TAG_MQTT, F("Buffer allocation failed"));
// } else { // } else {
Log.trace(TAG_MQTT, F("Setup Complete: %d bytes"), mqttClient.getBufferSize()); Log.trace(TAG_MQTT, F(D_MQTT_STARTED), mqttClient.getBufferSize());
// } // }
} else { } else {
Log.warning(TAG_MQTT, F("Broker not configured")); Log.warning(TAG_MQTT, F(D_MQTT_NOT_CONFIGURED));
} }
} }
@ -338,7 +335,7 @@ void IRAM_ATTR mqttLoop(void)
void mqttEvery5Seconds(bool networkIsConnected) void mqttEvery5Seconds(bool networkIsConnected)
{ {
if(mqttEnabled && networkIsConnected && !mqttClient.connected()) { if(mqttEnabled && networkIsConnected && !mqttClient.connected()) {
Log.notice(TAG_MQTT, F("Disconnected from broker, reconnection...")); Log.notice(TAG_MQTT, F(D_MQTT_RECONNECTING));
mqttStart(); mqttStart();
} }
} }
@ -351,10 +348,10 @@ String mqttGetNodename()
void mqttStop() void mqttStop()
{ {
if(mqttEnabled && mqttClient.connected()) { if(mqttEnabled && mqttClient.connected()) {
Log.notice(TAG_MQTT, F("Disconnecting...")); Log.notice(TAG_MQTT, F(D_MQTT_DISCONNECTING));
mqtt_send_lwt(false); mqtt_send_lwt(false);
mqttClient.disconnect(); mqttClient.disconnect();
Log.trace(TAG_MQTT, F("Disconnected")); Log.trace(TAG_MQTT, F(D_MQTT_DISCONNECTED));
} }
} }
@ -408,7 +405,7 @@ bool mqttSetConfig(const JsonObject & settings)
if(strlen(mqttNodeName) == 0) { if(strlen(mqttNodeName) == 0) {
String mac = halGetMacAddress(3, ""); String mac = halGetMacAddress(3, "");
mac.toLowerCase(); mac.toLowerCase();
snprintf_P(mqttNodeName, sizeof(mqttNodeName), PSTR("plate_%s"), mac.c_str()); snprintf_P(mqttNodeName, sizeof(mqttNodeName), PSTR(D_MQTT_DEFAULT_NAME), mac.c_str());
changed = true; changed = true;
} }
@ -433,7 +430,7 @@ bool mqttSetConfig(const JsonObject & settings)
} }
if(!settings[FPSTR(F_CONFIG_PASS)].isNull() && if(!settings[FPSTR(F_CONFIG_PASS)].isNull() &&
settings[FPSTR(F_CONFIG_PASS)].as<String>() != String(FPSTR("********"))) { settings[FPSTR(F_CONFIG_PASS)].as<String>() != String(FPSTR(D_PASSWORD_MASK))) {
changed |= strcmp(mqttPassword, settings[FPSTR(F_CONFIG_PASS)]) != 0; changed |= strcmp(mqttPassword, settings[FPSTR(F_CONFIG_PASS)]) != 0;
strncpy(mqttPassword, settings[FPSTR(F_CONFIG_PASS)], sizeof(mqttPassword)); strncpy(mqttPassword, settings[FPSTR(F_CONFIG_PASS)], sizeof(mqttPassword));
} }

View File

@ -26,7 +26,7 @@ extern bool mqttHAautodiscover;
char discovery_prefix[] = "homeassistant"; char discovery_prefix[] = "homeassistant";
void mqtt_ha_send_json(char * topic, DynamicJsonDocument & doc) void mqtt_ha_send_json(char * topic, JsonDocument & doc)
{ {
Log.verbose(TAG_MQTT_PUB, topic); Log.verbose(TAG_MQTT_PUB, topic);
mqttClient.beginPublish(topic, measureJson(doc), RETAINED); mqttClient.beginPublish(topic, measureJson(doc), RETAINED);
@ -34,7 +34,7 @@ void mqtt_ha_send_json(char * topic, DynamicJsonDocument & doc)
mqttClient.endPublish(); mqttClient.endPublish();
} }
void mqtt_ha_add_device(DynamicJsonDocument & doc) void mqtt_ha_add_device(JsonDocument & doc)
{ {
JsonObject device = doc.createNestedObject(F("device")); JsonObject device = doc.createNestedObject(F("device"));
JsonArray ids = device.createNestedArray(F("ids")); JsonArray ids = device.createNestedArray(F("ids"));
@ -54,10 +54,10 @@ void mqtt_ha_add_device(DynamicJsonDocument & doc)
void mqtt_ha_register_button(uint8_t page, uint8_t id) void mqtt_ha_register_button(uint8_t page, uint8_t id)
{ {
char buffer[128]; StaticJsonDocument<640> doc;
DynamicJsonDocument doc(640);
mqtt_ha_add_device(doc); mqtt_ha_add_device(doc);
char buffer[128];
snprintf_P(buffer, sizeof(buffer), PSTR(HASP_OBJECT_NOTATION), page, id); snprintf_P(buffer, sizeof(buffer), PSTR(HASP_OBJECT_NOTATION), page, id);
doc[F("stype")] = buffer; // subtype = "p0b0" doc[F("stype")] = buffer; // subtype = "p0b0"
snprintf_P(buffer, sizeof(buffer), PSTR("~state/" HASP_OBJECT_NOTATION), page, id); snprintf_P(buffer, sizeof(buffer), PSTR("~state/" HASP_OBJECT_NOTATION), page, id);
@ -96,10 +96,10 @@ void mqtt_ha_register_button(uint8_t page, uint8_t id)
void mqtt_ha_register_switch(uint8_t page, uint8_t id) void mqtt_ha_register_switch(uint8_t page, uint8_t id)
{ {
char buffer[128]; StaticJsonDocument<640> doc;
DynamicJsonDocument doc(640);
mqtt_ha_add_device(doc); mqtt_ha_add_device(doc);
char buffer[128];
snprintf_P(buffer, sizeof(buffer), PSTR(HASP_OBJECT_NOTATION), page, id); snprintf_P(buffer, sizeof(buffer), PSTR(HASP_OBJECT_NOTATION), page, id);
doc[F("stype")] = buffer; // subtype = "p0b0" doc[F("stype")] = buffer; // subtype = "p0b0"
snprintf_P(buffer, sizeof(buffer), PSTR("~state/" HASP_OBJECT_NOTATION), page, id); snprintf_P(buffer, sizeof(buffer), PSTR("~state/" HASP_OBJECT_NOTATION), page, id);
@ -109,18 +109,18 @@ void mqtt_ha_register_switch(uint8_t page, uint8_t id)
doc[F("pl")] = "SHORT"; // payload doc[F("pl")] = "SHORT"; // payload
doc[F("type")] = "button_short_release"; doc[F("type")] = "button_short_release";
snprintf_P(buffer, sizeof(buffer), PSTR("%s/device_automation/%s/" HASP_OBJECT_NOTATION "_%s/config"), discovery_prefix, mqttNodeName, snprintf_P(buffer, sizeof(buffer), PSTR("%s/device_automation/%s/" HASP_OBJECT_NOTATION "_%s/config"),
page, id, "short"); discovery_prefix, mqttNodeName, page, id, "short");
mqtt_ha_send_json(buffer, doc); mqtt_ha_send_json(buffer, doc);
} }
void mqtt_ha_register_connectivity() void mqtt_ha_register_connectivity()
{ {
DynamicJsonDocument doc(640); StaticJsonDocument<640> doc;
mqtt_ha_add_device(doc); mqtt_ha_add_device(doc);
char buffer[128];
char buffer[128];
char item[16]; char item[16];
snprintf_P(item, sizeof(item), PSTR("connectivity")); snprintf_P(item, sizeof(item), PSTR("connectivity"));
@ -144,10 +144,10 @@ void mqtt_ha_register_connectivity()
void mqtt_ha_register_backlight() void mqtt_ha_register_backlight()
{ {
DynamicJsonDocument doc(640); StaticJsonDocument<640> doc;
mqtt_ha_add_device(doc); mqtt_ha_add_device(doc);
char buffer[128];
char buffer[128];
char item[16]; char item[16];
snprintf_P(item, sizeof(item), PSTR("backlight")); snprintf_P(item, sizeof(item), PSTR("backlight"));
@ -175,8 +175,8 @@ void mqtt_ha_register_moodlight()
{ {
DynamicJsonDocument doc(1024); DynamicJsonDocument doc(1024);
mqtt_ha_add_device(doc); mqtt_ha_add_device(doc);
char buffer[128];
char buffer[128];
char item[16]; char item[16];
snprintf_P(item, sizeof(item), PSTR("moodlight")); snprintf_P(item, sizeof(item), PSTR("moodlight"));
@ -208,10 +208,10 @@ void mqtt_ha_register_moodlight()
void mqtt_ha_register_idle() void mqtt_ha_register_idle()
{ {
DynamicJsonDocument doc(640); StaticJsonDocument<640> doc;
mqtt_ha_add_device(doc); mqtt_ha_add_device(doc);
char buffer[128];
char buffer[128];
char item[16]; char item[16];
snprintf_P(item, sizeof(item), PSTR("idle")); snprintf_P(item, sizeof(item), PSTR("idle"));
@ -235,10 +235,10 @@ void mqtt_ha_register_idle()
void mqtt_ha_register_activepage() void mqtt_ha_register_activepage()
{ {
DynamicJsonDocument doc(640); StaticJsonDocument<640> doc;
mqtt_ha_add_device(doc); mqtt_ha_add_device(doc);
char buffer[128];
char buffer[128];
char item[16]; char item[16];
snprintf_P(item, sizeof(item), PSTR("page")); snprintf_P(item, sizeof(item), PSTR("page"));
@ -259,10 +259,10 @@ void mqtt_ha_register_activepage()
void mqtt_ha_register_auto_discovery() void mqtt_ha_register_auto_discovery()
{ {
Log.notice(TAG_MQTT_PUB, F("Register HA auto-discovery")); Log.notice(TAG_MQTT_PUB, F(D_MQTT_HA_AUTO_DISCOVERY));
mqtt_ha_register_activepage(); mqtt_ha_register_activepage();
mqtt_ha_register_button(0, 1); // mqtt_ha_register_button(0, 1);
mqtt_ha_register_button(0, 2); // mqtt_ha_register_button(0, 2);
mqtt_ha_register_backlight(); mqtt_ha_register_backlight();
mqtt_ha_register_moodlight(); mqtt_ha_register_moodlight();
mqtt_ha_register_idle(); mqtt_ha_register_idle();

View File

@ -32,7 +32,7 @@ bool otaUpdateCheck()
{ // firmware update check { // firmware update check
WiFiClientSecure wifiUpdateClientSecure; WiFiClientSecure wifiUpdateClientSecure;
HTTPClient updateClient; HTTPClient updateClient;
Log.notice(TAG_OTA, F("UPDATE: Checking update URL: %s"), otaUrl.c_str()); Log.notice(TAG_OTA, F(D_OTA_CHECK_UPDATE), otaUrl.c_str());
// wifiUpdateClientSecure.setInsecure(); // wifiUpdateClientSecure.setInsecure();
// wifiUpdateClientSecure.setBufferSizes(512, 512); // wifiUpdateClientSecure.setBufferSizes(512, 512);
@ -40,7 +40,7 @@ bool otaUpdateCheck()
int httpCode = updateClient.GET(); // start connection and send HTTP header int httpCode = updateClient.GET(); // start connection and send HTTP header
if(httpCode != HTTP_CODE_OK) { if(httpCode != HTTP_CODE_OK) {
Log.error(TAG_OTA, F("Update check failed: %s"), updateClient.errorToString(httpCode).c_str()); Log.error(TAG_OTA, F(D_OTA_CHECK_FAILED), updateClient.errorToString(httpCode).c_str());
return false; return false;
} }
@ -65,7 +65,7 @@ bool otaUpdateCheck()
// debugPrintln(String(F("UPDATE: New ESP version available: ")) + String(updateEspAvailableVersion)); // debugPrintln(String(F("UPDATE: New ESP version available: ")) + String(updateEspAvailableVersion));
// } // }
} }
Log.verbose(TAG_OTA, F("UPDATE: Update check completed")); Log.verbose(TAG_OTA, F(D_OTA_CHECK_COMPLETE));
} }
return true; return true;
} }
@ -97,16 +97,16 @@ void otaSetup(void)
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
} }
Log.notice(TAG_OTA, F("Starting OTA update")); Log.notice(TAG_OTA, F(D_SERVICE_STARTING));
haspProgressMsg(F(D_OTA_UPDATE_FIRMWARE));
haspProgressVal(0); haspProgressVal(0);
haspProgressMsg(F("Firmware Update"));
otaPrecentageComplete = 0; otaPrecentageComplete = 0;
}); });
ArduinoOTA.onEnd([]() { ArduinoOTA.onEnd([]() {
otaPrecentageComplete = 100; otaPrecentageComplete = 100;
Log.notice(TAG_OTA, F("OTA update complete")); Log.notice(TAG_OTA, F(D_OTA_UPDATE_COMPLETE));
haspProgressVal(100); haspProgressVal(100);
haspProgressMsg(F("Applying Firmware & Reboot")); haspProgressMsg(F(D_OTA_UPDATE_APPLY));
otaProgress(); otaProgress();
otaPrecentageComplete = -1; otaPrecentageComplete = -1;
// setup(); // setup();
@ -137,7 +137,7 @@ void otaSetup(void)
otaPrecentageComplete = -1; otaPrecentageComplete = -1;
Log.error(TAG_OTA, F("%s failed (%s)"), buffer, error); Log.error(TAG_OTA, F("%s failed (%s)"), buffer, error);
haspProgressMsg(F("ESP OTA FAILED")); haspProgressMsg(F(D_OTA_UPDATE_FAILED));
// delay(5000); // delay(5000);
}); });
@ -164,9 +164,9 @@ void otaSetup(void)
#endif #endif
ArduinoOTA.begin(); ArduinoOTA.begin();
Log.trace(TAG_OTA, F("Over the Air firmware update ready")); Log.trace(TAG_OTA, F(D_SERVICE_STARTED));
} else { } else {
Log.warning(TAG_OTA, F("Disabled")); Log.warning(TAG_OTA, F(D_SERVICE_DISABLED));
} }
} }

View File

@ -4,33 +4,33 @@
#include "hasp_conf.h" #include "hasp_conf.h"
#if HASP_USE_TELNET > 0 #if HASP_USE_TELNET > 0
#include "ArduinoJson.h" #include "ArduinoJson.h"
#include "ConsoleInput.h" #include "ConsoleInput.h"
#include "hasp_debug.h" #include "hasp_debug.h"
#include "hasp_config.h" #include "hasp_config.h"
#include "hasp_telnet.h" #include "hasp_telnet.h"
#include "../hasp/hasp_dispatch.h" #include "../hasp/hasp_dispatch.h"
#if defined(ARDUINO_ARCH_ESP32) #if defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h> #include <WiFi.h>
WiFiClient telnetClient; WiFiClient telnetClient;
static WiFiServer * telnetServer; static WiFiServer * telnetServer;
#elif defined(ARDUINO_ARCH_ESP8266) #elif defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h> #include <ESP8266WiFi.h>
WiFiClient telnetClient; WiFiClient telnetClient;
static WiFiServer * telnetServer; static WiFiServer * telnetServer;
#else #else
//#include <STM32Ethernet.h> //#include <STM32Ethernet.h>
EthernetClient telnetClient; EthernetClient telnetClient;
static EthernetServer telnetServer(23); static EthernetServer telnetServer(23);
#endif #endif
#if HASP_USE_HTTP > 0 #if HASP_USE_HTTP > 0
extern char httpUser[32]; extern char httpUser[32];
extern char httpPassword[32]; extern char httpPassword[32];
#endif #endif
uint8_t telnetLoginState = TELNET_UNAUTHENTICATED; uint8_t telnetLoginState = TELNET_UNAUTHENTICATED;
uint16_t telnetPort = 23; uint16_t telnetPort = 23;
@ -41,7 +41,7 @@ ConsoleInput * telnetConsole;
void telnetClientDisconnect() void telnetClientDisconnect()
{ {
Log.unregisterOutput(1); // telnetClient Log.unregisterOutput(1); // telnetClient
Log.notice(TAG_TELN, F("Closing session from %s"), telnetClient.remoteIP().toString().c_str()); Log.notice(TAG_TELN, F(D_TELNET_CLOSING_CONNECTION), telnetClient.remoteIP().toString().c_str());
telnetLoginState = TELNET_UNAUTHENTICATED; telnetLoginState = TELNET_UNAUTHENTICATED;
telnetLoginAttempt = 0; // Initial attempt telnetLoginAttempt = 0; // Initial attempt
// delete telnetConsole; // delete telnetConsole;
@ -59,9 +59,9 @@ void telnetClientLogon()
/* Now register logger for telnet */ /* Now register logger for telnet */
Log.registerOutput(1, &telnetClient, LOG_LEVEL_VERBOSE, true); Log.registerOutput(1, &telnetClient, LOG_LEVEL_VERBOSE, true);
telnetClient.flush(); telnetClient.flush();
// telnetClient.setTimeout(10); // telnetClient.setTimeout(10);
Log.notice(TAG_TELN, F("Client login from %s"), telnetClient.remoteIP().toString().c_str()); Log.notice(TAG_TELN, F(D_TELNET_CLIENT_LOGIN_FROM), telnetClient.remoteIP().toString().c_str());
} }
void telnetAcceptClient() void telnetAcceptClient()
@ -72,10 +72,10 @@ void telnetAcceptClient()
} }
telnetClient = telnetServer->available(); // ready for new client telnetClient = telnetServer->available(); // ready for new client
if(!telnetClient) { if(!telnetClient) {
Log.verbose(TAG_TELN, F("Client NOT connected")); Log.verbose(TAG_TELN, F(D_TELNET_CLIENT_NOT_CONNECTED));
return; return;
} }
Log.trace(TAG_TELN, F("Client connected from %s"), telnetClient.remoteIP().toString().c_str()); Log.trace(TAG_TELN, F(D_TELNET_CLIENT_CONNECT_FROM), telnetClient.remoteIP().toString().c_str());
telnetClient.setNoDelay(true); telnetClient.setNoDelay(true);
/* Avoid a buffer here */ /* Avoid a buffer here */
@ -83,27 +83,27 @@ void telnetAcceptClient()
// telnetClient.print((char)0xFD); // telnetClient.print((char)0xFD);
// telnetClient.print((char)0x1B); // telnetClient.print((char)0x1B);
#if HASP_USE_HTTP > 0 #if HASP_USE_HTTP > 0
if(strlen(httpUser) != 0 || strlen(httpPassword) != 0) { if(strlen(httpUser) != 0 || strlen(httpPassword) != 0) {
telnetClient.println(F("\r\nUsername: ")); telnetClient.println(F("\r\n" D_TELNET_USERNAME " "));
telnetLoginState = TELNET_UNAUTHENTICATED; telnetLoginState = TELNET_UNAUTHENTICATED;
} else } else
#endif #endif
{ {
telnetClientLogon(); telnetClientLogon();
} }
telnetLoginAttempt = 0; // Initial attempt telnetLoginAttempt = 0; // Initial attempt
} }
#if 0 #if 0
static inline void telnetProcessLine() static inline void telnetProcessLine()
{ {
telnetInputBuffer[telnetInputIndex] = 0; // null terminate our char array telnetInputBuffer[telnetInputIndex] = 0; // null terminate our char array
switch(telnetLoginState) { switch(telnetLoginState) {
case TELNET_UNAUTHENTICATED: { case TELNET_UNAUTHENTICATED: {
telnetClient.printf(PSTR("Password: %c%c%c"), 0xFF, 0xFB, 0x01); // Hide characters telnetClient.printf(PSTR(D_TELNET_PASSWORD" %c%c%c"), 0xFF, 0xFB, 0x01); // Hide characters
#if HASP_USE_HTTP > 0 #if HASP_USE_HTTP > 0
telnetLoginState = strcmp(telnetInputBuffer, httpUser) == 0 ? TELNET_USERNAME_OK : TELNET_USERNAME_NOK; telnetLoginState = strcmp(telnetInputBuffer, httpUser) == 0 ? TELNET_USERNAME_OK : TELNET_USERNAME_NOK;
break; break;
} }
@ -115,17 +115,17 @@ static inline void telnetProcessLine()
} else { } else {
telnetLoginState = TELNET_UNAUTHENTICATED; telnetLoginState = TELNET_UNAUTHENTICATED;
telnetLoginAttempt++; // Subsequent attempt telnetLoginAttempt++; // Subsequent attempt
telnetClient.println(F("Authorization failed!\r\n")); telnetClient.println(F(D_TELNET_AUTHENTICATION_FAILED"\r\n"));
Log.warning(TAG_TELN, F("Incorrect login attempt from %s"), telnetClient.remoteIP().toString().c_str()); Log.warning(TAG_TELN, F(D_TELNET_INCORRECT_LOGIN_ATTEMPT), telnetClient.remoteIP().toString().c_str());
if(telnetLoginAttempt >= 3) { if(telnetLoginAttempt >= 3) {
telnetClientDisconnect(); telnetClientDisconnect();
} else { } else {
telnetClient.print(F("Username: ")); telnetClient.print(F(D_TELNET_USERNAME" "));
} }
} }
#else #else
telnetClientLogon(); telnetClientLogon();
#endif #endif
break; break;
} }
default: default:
@ -179,16 +179,17 @@ static inline void telnetProcessCharacter(char ch)
//} //}
} }
#endif #endif
static inline void telnetProcessLine(const char * input) static inline void telnetProcessLine(const char * input)
{ {
switch(telnetLoginState) { switch(telnetLoginState) {
case TELNET_UNAUTHENTICATED: { case TELNET_UNAUTHENTICATED: {
char buffer[20]; char buffer[20];
snprintf_P(buffer, sizeof(buffer), PSTR("Password: %c%c%c\n"), 0xFF, 0xFB, 0x01); // Hide characters snprintf_P(buffer, sizeof(buffer), PSTR(D_TELNET_PASSWORD " %c%c%c\n"), 0xFF, 0xFB,
0x01); // Hide characters
telnetClient.print(buffer); telnetClient.print(buffer);
#if HASP_USE_HTTP > 0 #if HASP_USE_HTTP > 0
telnetLoginState = strcmp(input, httpUser) == 0 ? TELNET_USERNAME_OK : TELNET_USERNAME_NOK; telnetLoginState = strcmp(input, httpUser) == 0 ? TELNET_USERNAME_OK : TELNET_USERNAME_NOK;
break; break;
} }
@ -200,24 +201,24 @@ static inline void telnetProcessLine(const char * input)
} else { } else {
telnetLoginState = TELNET_UNAUTHENTICATED; telnetLoginState = TELNET_UNAUTHENTICATED;
telnetLoginAttempt++; // Subsequent attempt telnetLoginAttempt++; // Subsequent attempt
telnetClient.println(F("Authorization failed!\r\n")); telnetClient.println(F(D_TELNET_AUTHENTICATION_FAILED "\r\n"));
Log.warning(TAG_TELN, F("Incorrect login attempt from %s"), telnetClient.remoteIP().toString().c_str()); Log.warning(TAG_TELN, F(D_TELNET_INCORRECT_LOGIN_ATTEMPT), telnetClient.remoteIP().toString().c_str());
if(telnetLoginAttempt >= 3) { if(telnetLoginAttempt >= 3) {
telnetClientDisconnect(); telnetClientDisconnect();
} else { } else {
telnetClient.print(F("Username: ")); telnetClient.print(F(D_TELNET_USERNAME " "));
} }
} }
#else #else
telnetClientLogon(); telnetClientLogon();
#endif #endif
break; break;
} }
default: default:
if(strcasecmp_P(input, PSTR("exit")) == 0) { if(strcasecmp_P(input, PSTR("exit")) == 0) {
telnetClientDisconnect(); telnetClientDisconnect();
} else if(strcasecmp_P(input, PSTR("logoff")) == 0) { } else if(strcasecmp_P(input, PSTR("logoff")) == 0) {
telnetClient.println(F("\r\nUsername: ")); telnetClient.println(F("\r\n" D_TELNET_USERNAME " "));
telnetLoginState = TELNET_UNAUTHENTICATED; telnetLoginState = TELNET_UNAUTHENTICATED;
} else { } else {
dispatch_text_line(input); dispatch_text_line(input);
@ -230,15 +231,15 @@ void telnetSetup()
// telnetSetConfig(settings); // telnetSetConfig(settings);
if(telnetEnabled) { // Setup telnet server for remote debug output if(telnetEnabled) { // Setup telnet server for remote debug output
#if defined(STM32F4xx) #if defined(STM32F4xx)
// if(!telnetServer) telnetServer = new EthernetServer(telnetPort); // if(!telnetServer) telnetServer = new EthernetServer(telnetPort);
// if(telnetServer) { // if(telnetServer) {
telnetServer->begin(); telnetServer->begin();
Log.trace(TAG_TELN, F("Remote console started")); Log.trace(TAG_TELN, F(D_TELNET_STARTED));
// } else { // } else {
// Log.error(TAG_TELN,F("Failed to start telnet server")); // Log.error(TAG_TELN,F("Failed to start telnet server"));
//} //}
#else #else
if(!telnetServer) telnetServer = new WiFiServer(telnetPort); if(!telnetServer) telnetServer = new WiFiServer(telnetPort);
if(telnetServer) { if(telnetServer) {
telnetServer->setNoDelay(true); telnetServer->setNoDelay(true);
@ -247,13 +248,13 @@ void telnetSetup()
telnetConsole = new ConsoleInput(&telnetClient, HASP_CONSOLE_BUFFER); telnetConsole = new ConsoleInput(&telnetClient, HASP_CONSOLE_BUFFER);
if(telnetConsole != NULL) { if(telnetConsole != NULL) {
telnetConsole->setLineCallback(telnetProcessLine); telnetConsole->setLineCallback(telnetProcessLine);
Log.trace(TAG_TELN, F("Remote console started")); Log.trace(TAG_TELN, F(D_TELNET_STARTED));
return; return;
} }
} }
Log.error(TAG_TELN, F("Failed to start telnet console")); Log.error(TAG_TELN, F(D_TELNET_FAILED));
#endif #endif
} }
} }
@ -261,7 +262,7 @@ void IRAM_ATTR telnetLoop()
{ {
// Basic telnet client handling code from: https://gist.github.com/tablatronix/4793677ca748f5f584c95ec4a2b10303 // Basic telnet client handling code from: https://gist.github.com/tablatronix/4793677ca748f5f584c95ec4a2b10303
#if defined(STM32F4xx) #if defined(STM32F4xx)
Ethernet.schedule(); Ethernet.schedule();
// if(telnetServer) // if(telnetServer)
{ // client is connected { // client is connected
@ -273,10 +274,10 @@ void IRAM_ATTR telnetLoop()
telnetClient = client; // ready for new client telnetClient = client; // ready for new client
// Log.notice(TAG_TELN,F("Client connected from %s"), telnetClient.remoteIP().toString().c_str()); // Log.notice(TAG_TELN,F("Client connected from %s"), telnetClient.remoteIP().toString().c_str());
if(!telnetClient) { if(!telnetClient) {
Log.warning(TAG_TELN, F("Client NOT connected")); Log.warning(TAG_TELN, F(D_TELNET_CLIENT_NOT_CONNECTED));
return; return;
} }
Log.notice(TAG_TELN, F("Client connected")); Log.notice(TAG_TELN, F(D_TELNET_CLIENT_CONNECTED));
/* Avoid a buffer here */ /* Avoid a buffer here */
// telnetClient.print(0xFF); // DO TERMINAL-TYPE // telnetClient.print(0xFF); // DO TERMINAL-TYPE
@ -288,12 +289,12 @@ void IRAM_ATTR telnetLoop()
} }
} }
} }
#else #else
if(telnetServer && telnetServer->hasClient()) { // a new client has connected if(telnetServer && telnetServer->hasClient()) { // a new client has connected
if(!telnetClient.connected()) { // nobody is already connected if(!telnetClient.connected()) { // nobody is already connected
telnetAcceptClient(); // allow the new client telnetAcceptClient(); // allow the new client
} else { } else {
Log.warning(TAG_TELN, F("Rejecting client, another connection is already active")); Log.warning(TAG_TELN, F(D_TELNET_CLIENT_REJECTED));
telnetServer->available().stop(); // already have a client, block new connections telnetServer->available().stop(); // already have a client, block new connections
} }
} else { } else {
@ -311,10 +312,10 @@ void IRAM_ATTR telnetLoop()
} }
} }
} }
#endif #endif
} }
#if HASP_USE_CONFIG > 0 #if HASP_USE_CONFIG > 0
bool telnetGetConfig(const JsonObject & settings) bool telnetGetConfig(const JsonObject & settings)
{ {
bool changed = false; bool changed = false;
@ -347,6 +348,6 @@ bool telnetSetConfig(const JsonObject & settings)
return changed; return changed;
} }
#endif // HASP_USE_CONFIG #endif // HASP_USE_CONFIG
#endif #endif