diff --git a/README.md b/README.md index 4e4d333e7..b7ae6c322 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,21 @@ ## Sonoff-Tasmota Provide ESP8266 based Sonoff by [iTead Studio](https://www.itead.cc/) and ElectroDragon IoT Relay with Serial, Web and MQTT control allowing 'Over the Air' or OTA firmware updates using Arduino IDE. -Current version is **4.2.0** - See [sonoff/_releasenotes.ino](https://github.com/arendst/Sonoff-Tasmota/blob/master/sonoff/_releasenotes.ino) for change information. +Current version is **5.0.0** - See [sonoff/_releasenotes.ino](https://github.com/arendst/Sonoff-Tasmota/blob/master/sonoff/_releasenotes.ino) for change information. + +### **** ATTENTION Version 5.0.0 specific information ******* + +This version uses a new linker script to free flash memory for future code additions. It moves the settings from Spiffs to Eeprom. If you compile your own download the new linker to your IDE or Platformio base folder. + +Best practice to implement is: +- Open the webpage to your device +- Perform option ``Backup Configuration`` +- Upgrade new firmware using ``Firmware upgrade`` +- If configuration conversion failed keep the webpage open and perform ``Restore Configuration`` + +You should now have a device with 32k more code memory to play with. + +### ********************************************************* - This version provides all (Sonoff) modules in one file and starts up with Sonoff Basic. - Once uploaded select module using the configuration webpage or the commands ```Modules``` and ```Module```. diff --git a/api/arduino/sonoff-minimal.ino.bin b/api/arduino/sonoff-minimal.ino.bin index 120748e40..92e33feb9 100644 Binary files a/api/arduino/sonoff-minimal.ino.bin and b/api/arduino/sonoff-minimal.ino.bin differ diff --git a/api/arduino/sonoff.ino.bin b/api/arduino/sonoff.ino.bin index ae6873b93..9b072715c 100644 Binary files a/api/arduino/sonoff.ino.bin and b/api/arduino/sonoff.ino.bin differ diff --git a/sonoff/_releasenotes.ino b/sonoff/_releasenotes.ino index c2f899236..b76613230 100644 --- a/sonoff/_releasenotes.ino +++ b/sonoff/_releasenotes.ino @@ -1,4 +1,11 @@ -/* 4.2.0 20170424 +/* 5.0.0 20170425 + * Memory status message update + * Fix setting migration to better preserve settings during move (#382) + * Best practice is first doing a Backup Configuration before installing version 5.0.0 + * Reset save count after setting move + * Start using new linker script without SPIFFS + * + * 4.2.0 20170424 * Prepare for SPIFFS removal by moving settings to EEPROM area * Fix compilation error when webserver is disabled (#378) * diff --git a/sonoff/settings.ino b/sonoff/settings.ino index 4739d0cc9..ca8cbd49d 100644 --- a/sonoff/settings.ino +++ b/sonoff/settings.ino @@ -36,7 +36,9 @@ uint32_t getRtcHash() uint32_t hash = 0; uint8_t *bytes = (uint8_t*)&rtcMem; - for (uint16_t i = 0; i < sizeof(RTCMEM); i++) hash += bytes[i]*(i+1); + for (uint16_t i = 0; i < sizeof(RTCMEM); i++) { + hash += bytes[i]*(i+1); + } return hash; } @@ -70,7 +72,7 @@ void RTC_Load() boolean RTC_Valid() { - return (rtcMem.valid == RTC_MEM_VALID); + return (RTC_MEM_VALID == rtcMem.valid); } #ifdef DEBUG_THEO @@ -79,7 +81,10 @@ void RTC_Dump() #define CFG_COLS 16 char log[LOGSZ]; - uint16_t idx, maxrow, row, col; + uint16_t idx; + uint16_t maxrow; + uint16_t row; + uint16_t col; uint8_t *buffer = (uint8_t *) &rtcMem; maxrow = ((sizeof(RTCMEM)+CFG_COLS)/CFG_COLS); @@ -88,12 +93,16 @@ void RTC_Dump() idx = row * CFG_COLS; snprintf_P(log, sizeof(log), PSTR("%04X:"), idx); for (col = 0; col < CFG_COLS; col++) { - if (!(col%4)) snprintf_P(log, sizeof(log), PSTR("%s "), log); + if (!(col%4)) { + snprintf_P(log, sizeof(log), PSTR("%s "), log); + } snprintf_P(log, sizeof(log), PSTR("%s %02X"), log, buffer[idx + col]); } snprintf_P(log, sizeof(log), PSTR("%s |"), log); for (col = 0; col < CFG_COLS; col++) { -// if (!(col%4)) snprintf_P(log, sizeof(log), PSTR("%s "), log); +// if (!(col%4)) { +// snprintf_P(log, sizeof(log), PSTR("%s "), log); +// } snprintf_P(log, sizeof(log), PSTR("%s%c"), log, ((buffer[idx + col] > 0x20) && (buffer[idx + col] < 0x7F)) ? (char)buffer[idx + col] : ' '); } snprintf_P(log, sizeof(log), PSTR("%s|"), log); @@ -111,7 +120,6 @@ extern "C" { } #include "eboot_command.h" -//extern "C" uint32_t _SPIFFS_start; extern "C" uint32_t _SPIFFS_end; #define SPIFFS_END ((uint32_t)&_SPIFFS_end - 0x40200000) / SPI_FLASH_SEC_SIZE @@ -145,11 +153,11 @@ void setFlashMode(byte option, byte mode) address = 0; } _buffer = new uint8_t[FLASH_SECTOR_SIZE]; - if (spi_flash_read(address, (uint32_t*)_buffer, FLASH_SECTOR_SIZE) == SPI_FLASH_RESULT_OK) { + if (SPI_FLASH_RESULT_OK == spi_flash_read(address, (uint32_t*)_buffer, FLASH_SECTOR_SIZE)) { if (_buffer[2] != mode) { _buffer[2] = mode &3; noInterrupts(); - if (spi_flash_erase_sector(address / FLASH_SECTOR_SIZE) == SPI_FLASH_RESULT_OK) { + if (SPI_FLASH_RESULT_OK == spi_flash_erase_sector(address / FLASH_SECTOR_SIZE)) { spi_flash_write(address, (uint32_t*)_buffer, FLASH_SECTOR_SIZE); } interrupts(); @@ -163,7 +171,9 @@ void setFlashMode(byte option, byte mode) void setModuleFlashMode(byte option) { uint8_t mode = 0; // QIO - ESP8266 - if ((sysCfg.module == SONOFF_TOUCH) || (sysCfg.module == SONOFF_4CH)) mode = 3; // DOUT - ESP8285 + if ((SONOFF_TOUCH == sysCfg.module) || (SONOFF_4CH == sysCfg.module)) { + mode = 3; // DOUT - ESP8285 + } setFlashMode(option, mode); } @@ -172,7 +182,9 @@ uint32_t getHash() uint32_t hash = 0; uint8_t *bytes = (uint8_t*)&sysCfg; - for (uint16_t i = 0; i < sizeof(SYSCFG); i++) hash += bytes[i]*(i+1); + for (uint16_t i = 0; i < sizeof(SYSCFG); i++) { + hash += bytes[i]*(i+1); + } return hash; } @@ -215,7 +227,7 @@ void CFG_Load() addLog(LOG_LEVEL_DEBUG, log); if (sysCfg.cfg_holder != CFG_HOLDER) { - if ((sysCfg.version < 0x04020000) || (sysCfg.version > 0x73000000)) { + if ((sysCfg.version < 0x04020000) || (sysCfg.version > 0x06000000)) { noInterrupts(); spi_flash_read((CFG_LOCATION_3) * SPI_FLASH_SEC_SIZE, (uint32*)&sysCfg, sizeof(SYSCFG)); spi_flash_read((CFG_LOCATION_3 + 1) * SPI_FLASH_SEC_SIZE, (uint32*)&_sysCfgH, sizeof(SYSCFGH)); @@ -224,6 +236,8 @@ void CFG_Load() interrupts(); if (sysCfg.cfg_holder != CFG_HOLDER) { CFG_Default(); + } else { + sysCfg.saveFlag = 0; } } else { CFG_Default(); @@ -253,7 +267,7 @@ void CFG_Erase() if (_serialoutput) { Serial.print(F("Flash: Erased sector ")); Serial.print(_sector); - if (result == SPI_FLASH_RESULT_OK) { + if (SPI_FLASH_RESULT_OK == result) { Serial.println(F(" OK")); } else { Serial.println(F(" Error")); @@ -268,7 +282,10 @@ void CFG_Dump() #define CFG_COLS 16 char log[LOGSZ]; - uint16_t idx, maxrow, row, col; + uint16_t idx; + uint16_t maxrow; + uint16_t row; + uint16_t col; uint8_t *buffer = (uint8_t *) &sysCfg; maxrow = ((sizeof(SYSCFG)+CFG_COLS)/CFG_COLS); @@ -277,12 +294,16 @@ void CFG_Dump() idx = row * CFG_COLS; snprintf_P(log, sizeof(log), PSTR("%04X:"), idx); for (col = 0; col < CFG_COLS; col++) { - if (!(col%4)) snprintf_P(log, sizeof(log), PSTR("%s "), log); + if (!(col%4)) { + snprintf_P(log, sizeof(log), PSTR("%s "), log); + } snprintf_P(log, sizeof(log), PSTR("%s %02X"), log, buffer[idx + col]); } snprintf_P(log, sizeof(log), PSTR("%s |"), log); for (col = 0; col < CFG_COLS; col++) { -// if (!(col%4)) snprintf_P(log, sizeof(log), PSTR("%s "), log); +// if (!(col%4)) { +// snprintf_P(log, sizeof(log), PSTR("%s "), log); +// } snprintf_P(log, sizeof(log), PSTR("%s%c"), log, ((buffer[idx + col] > 0x20) && (buffer[idx + col] < 0x7F)) ? (char)buffer[idx + col] : ' '); } snprintf_P(log, sizeof(log), PSTR("%s|"), log); @@ -424,16 +445,26 @@ void CFG_DefaultSet_3_2_4() void CFG_DefaultSet_3_9_3() { - for (byte i = 0; i < 4; i++) sysCfg.domoticz_switch_idx[i] = 0; - for (byte i = 0; i < 12; i++) sysCfg.domoticz_sensor_idx[i] = 0; + for (byte i = 0; i < 4; i++) { + sysCfg.domoticz_switch_idx[i] = 0; + } + for (byte i = 0; i < 12; i++) { + sysCfg.domoticz_sensor_idx[i] = 0; + } sysCfg.module = MODULE; - for (byte i = 0; i < MAX_GPIO_PIN; i++) sysCfg.my_module.gp.io[i] = 0; + for (byte i = 0; i < MAX_GPIO_PIN; i++){ + sysCfg.my_module.gp.io[i] = 0; + } sysCfg.led_pixels = 0; - for (byte i = 0; i < 5; i++) sysCfg.led_color[i] = 255; + for (byte i = 0; i < 5; i++) { + sysCfg.led_color[i] = 255; + } sysCfg.led_table = 0; - for (byte i = 0; i < 3; i++) sysCfg.led_dimmer[i] = 10; + for (byte i = 0; i < 3; i++){ + sysCfg.led_dimmer[i] = 10; + } sysCfg.led_fade = 0; sysCfg.led_speed = 0; sysCfg.led_scheme = 0; @@ -446,11 +477,17 @@ void CFG_DefaultSet_4_0_4() strlcpy(sysCfg.ntp_server[0], NTP_SERVER1, sizeof(sysCfg.ntp_server[0])); strlcpy(sysCfg.ntp_server[1], NTP_SERVER2, sizeof(sysCfg.ntp_server[1])); strlcpy(sysCfg.ntp_server[2], NTP_SERVER3, sizeof(sysCfg.ntp_server[2])); - for (byte j =0; j < 3; j++) - for (byte i = 0; i < strlen(sysCfg.ntp_server[j]); i++) - if (sysCfg.ntp_server[j][i] == ',') sysCfg.ntp_server[j][i] = '.'; + for (byte j =0; j < 3; j++) { + for (byte i = 0; i < strlen(sysCfg.ntp_server[j]); i++) { + if (sysCfg.ntp_server[j][i] == ',') { + sysCfg.ntp_server[j][i] = '.'; + } + } + } sysCfg.pulsetime[0] = sysCfg.ex_pulsetime; - for (byte i = 1; i < MAX_PULSETIMERS; i++) sysCfg.pulsetime[i] = 0; + for (byte i = 1; i < MAX_PULSETIMERS; i++) { + sysCfg.pulsetime[i] = 0; + } } void CFG_DefaultSet_4_0_9() @@ -535,7 +572,9 @@ void CFG_Delta() sysCfg.my_module.gp.io[MAX_GPIO_PIN -1] = 0; // Clear ADC0 } if (sysCfg.version < 0x04000700) { - for (byte i = 0; i < 5; i++) sysCfg.pwmvalue[i] = 0; + for (byte i = 0; i < 5; i++) { + sysCfg.pwmvalue[i] = 0; + } } if (sysCfg.version < 0x04000804) { CFG_DefaultSet_4_0_9(); diff --git a/sonoff/sonoff.ino b/sonoff/sonoff.ino index b2af00202..cb4c6ceeb 100644 --- a/sonoff/sonoff.ino +++ b/sonoff/sonoff.ino @@ -6,11 +6,11 @@ * - Change libraries/PubSubClient/src/PubSubClient.h * #define MQTT_MAX_PACKET_SIZE 512 * - * - Select IDE Tools - Flash size: "1M (64k SPIFFS)" + * - Select IDE Tools - Flash size: "1M (no SPIFFS)" * ==================================================== */ -#define VERSION 0x04020000 // 4.2.0 +#define VERSION 0x05000000 // 5.0.0 enum log_t {LOG_LEVEL_NONE, LOG_LEVEL_ERROR, LOG_LEVEL_INFO, LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG_MORE, LOG_LEVEL_ALL}; enum week_t {Last, First, Second, Third, Fourth}; @@ -292,13 +292,15 @@ void getClient(char* output, const char* input, byte size) } } } - if (!digits) strlcpy(output, input, size); + if (!digits) { + strlcpy(output, input, size); + } } void setLatchingRelay(uint8_t power, uint8_t state) { power &= 1; - if (state == 2) { // Reset relay + if (2 == state) { // Reset relay state = 0; latching_power = power; latching_relay_pulse = 0; @@ -307,14 +309,16 @@ void setLatchingRelay(uint8_t power, uint8_t state) latching_power = power; latching_relay_pulse = 2; // max 200mS (initiated by stateloop()) } - if (pin[GPIO_REL1 +latching_power] < 99) digitalWrite(pin[GPIO_REL1 +latching_power], rel_inverted[latching_power] ? !state : state); + if (pin[GPIO_REL1 +latching_power] < 99) { + digitalWrite(pin[GPIO_REL1 +latching_power], rel_inverted[latching_power] ? !state : state); + } } void setRelay(uint8_t power) { uint8_t state; - if ((sysCfg.module == SONOFF_DUAL) || (sysCfg.module == CH4)) { + if ((SONOFF_DUAL == sysCfg.module) || (CH4 == sysCfg.module)) { Serial.write(0xA0); Serial.write(0x04); Serial.write(power); @@ -322,16 +326,18 @@ void setRelay(uint8_t power) Serial.write('\n'); Serial.flush(); } - else if (sysCfg.module == SONOFF_LED) { + else if (SONOFF_LED == sysCfg.module) { sl_setPower(power &1); } - else if (sysCfg.module == EXS_RELAY) { + else if (EXS_RELAY == sysCfg.module) { setLatchingRelay(power, 1); } else { for (byte i = 0; i < Maxdevice; i++) { state = power &1; - if (pin[GPIO_REL1 +i] < 99) digitalWrite(pin[GPIO_REL1 +i], rel_inverted[i] ? !state : state); + if (pin[GPIO_REL1 +i] < 99) { + digitalWrite(pin[GPIO_REL1 +i], rel_inverted[i] ? !state : state); + } power >>= 1; } } @@ -340,7 +346,9 @@ void setRelay(uint8_t power) void setLed(uint8_t state) { - if (state) state = 1; + if (state) { + state = 1; + } digitalWrite(pin[GPIO_LED1], (led_inverted[0]) ? !state : state); } @@ -348,10 +356,14 @@ void setLed(uint8_t state) void json2legacy(char* stopic, char* svalue) { - char *p, *token; - uint16_t i, j; + char *p; + char *token; + uint16_t i; + uint16_t j; - if (!strstr(svalue, "{\"")) return; // No JSON + if (!strstr(svalue, "{\"")) { + return; // No JSON + } // stopic = stat/sonoff/RESULT // svalue = {"POWER2":"ON"} @@ -366,7 +378,9 @@ void json2legacy(char* stopic, char* svalue) token = strtok(svalue, "{\""); // Topic p = strrchr(stopic, '/') +1; i = p - stopic; - for (j = 0; j < strlen(token)+1; j++) stopic[i+j] = toupper(token[j]); + for (j = 0; j < strlen(token)+1; j++) { + stopic[i+j] = toupper(token[j]); + } token = strtok(NULL, "\""); // : or :3} or :3, or :{ if (strstr(token, ":{")) { token = strtok(NULL, "\""); // Subtopic @@ -375,7 +389,9 @@ void json2legacy(char* stopic, char* svalue) if (strlen(token) > 1) { token++; p = strchr(token, ','); - if (!p) p = strchr(token, '}'); + if (!p) { + p = strchr(token, '}'); + } i = p - token; token[i] = '\0'; // Value } else { @@ -393,7 +409,9 @@ void json2legacy(char* stopic, char* svalue) char* getStateText(byte state) { - if (state > 2) state = 1; + if (state > 2) { + state = 1; + } return sysCfg.state_text[state]; } @@ -415,7 +433,9 @@ void mqtt_publish_sec(const char* topic, const char* data, boolean retained) } addLog(LOG_LEVEL_INFO, log); - if (sysCfg.ledstate &0x04) blinks++; + if (sysCfg.ledstate &0x04) { + blinks++; + } } void mqtt_publish(const char* topic, const char* data, boolean retained) @@ -424,7 +444,9 @@ void mqtt_publish(const char* topic, const char* data, boolean retained) if (!strcmp(sysCfg.mqtt_prefix[0],sysCfg.mqtt_prefix[1])) { me = strstr(topic,sysCfg.mqtt_prefix[0]); - if (me == topic) mqtt_cmnd_publish += 8; + if (me == topic) { + mqtt_cmnd_publish += 8; + } } mqtt_publish_sec(topic, data, retained); } @@ -436,7 +458,8 @@ void mqtt_publish(const char* topic, const char* data) void mqtt_publish_topic_P(uint8_t prefix, const char* subtopic, const char* data) { - char romram[16], stopic[TOPSZ]; + char romram[16]; + char stopic[TOPSZ]; snprintf_P(romram, sizeof(romram), ((prefix > 3) && !sysCfg.mqtt_response) ? PSTR("RESULT") : subtopic); prefix &= 1; @@ -446,9 +469,13 @@ void mqtt_publish_topic_P(uint8_t prefix, const char* subtopic, const char* data void mqtt_publishPowerState(byte device) { - char stopic[TOPSZ], sdevice[10], svalue[64]; // was MESSZ + char stopic[TOPSZ]; + char sdevice[10]; + char svalue[64]; // was MESSZ - if ((device < 1) || (device > Maxdevice)) device = 1; + if ((device < 1) || (device > Maxdevice)) { + device = 1; + } snprintf_P(sdevice, sizeof(sdevice), PSTR("%d"), device); snprintf_P(stopic, sizeof(stopic), PSTR("%s/%s/%s"), sysCfg.mqtt_prefix[1], sysCfg.mqtt_topic, (sysCfg.mqtt_response)?"POWER":"RESULT"); @@ -461,9 +488,12 @@ void mqtt_publishPowerState(byte device) void mqtt_publishPowerBlinkState(byte device) { - char sdevice[10], svalue[64]; // was MESSZ + char sdevice[10]; + char svalue[64]; // was MESSZ - if ((device < 1) || (device > Maxdevice)) device = 1; + if ((device < 1) || (device > Maxdevice)) { + device = 1; + } snprintf_P(sdevice, sizeof(sdevice), PSTR("%d"), device); snprintf_P(svalue, sizeof(svalue), PSTR("{\"POWER%s\":\"BLINK %s\"}"), (Maxdevice > 1) ? sdevice : "", getStateText(bitRead(blink_mask, device -1))); @@ -472,7 +502,8 @@ void mqtt_publishPowerBlinkState(byte device) void mqtt_connected() { - char stopic[TOPSZ], svalue[128]; // was MESSZ + char stopic[TOPSZ]; + char svalue[128]; // was MESSZ if (sysCfg.mqtt_enabled) { @@ -502,14 +533,16 @@ void mqtt_connected() #ifdef USE_WEBSERVER if (sysCfg.webserver) { snprintf_P(svalue, sizeof(svalue), PSTR("{\"WebserverMode\":\"%s\", \"Hostname\":\"%s\", \"IPaddress\":\"%s\"}"), - (sysCfg.webserver == 2) ? "Admin" : "User", Hostname, WiFi.localIP().toString().c_str()); + (2 == sysCfg.webserver) ? "Admin" : "User", Hostname, WiFi.localIP().toString().c_str()); mqtt_publish_topic_P(1, PSTR("INFO2"), svalue); } #endif // USE_WEBSERVER snprintf_P(svalue, sizeof(svalue), PSTR("{\"Started\":\"%s\"}"), (getResetReason() == "Exception") ? ESP.getResetInfo().c_str() : getResetReason().c_str()); mqtt_publish_topic_P(1, PSTR("INFO3"), svalue); - if (sysCfg.tele_period) tele_period = sysCfg.tele_period -9; + if (sysCfg.tele_period) { + tele_period = sysCfg.tele_period -9; + } status_update_timer = 2; #ifdef USE_DOMOTICZ domoticz_setUpdateTimer(2); @@ -520,7 +553,9 @@ void mqtt_connected() void mqtt_reconnect() { - char stopic[TOPSZ], svalue[TOPSZ], log[LOGSZ]; + char stopic[TOPSZ]; + char svalue[TOPSZ]; + char log[LOGSZ]; mqttcounter = MQTT_RETRY_SECS; @@ -581,19 +616,20 @@ void mqtt_reconnect() boolean mqtt_command(boolean grpflg, char *type, uint16_t index, char *dataBuf, uint16_t data_len, int16_t payload, char *svalue, uint16_t ssvalue) { boolean serviced = true; - char stemp1[TOPSZ], stemp2[10]; + char stemp1[TOPSZ]; + char stemp2[10]; uint16_t i; if (!strcmp(type,"MQTTHOST")) { if ((data_len > 0) && (data_len < sizeof(sysCfg.mqtt_host))) { - strlcpy(sysCfg.mqtt_host, (payload == 1) ? MQTT_HOST : dataBuf, sizeof(sysCfg.mqtt_host)); + strlcpy(sysCfg.mqtt_host, (1 == payload) ? MQTT_HOST : dataBuf, sizeof(sysCfg.mqtt_host)); restartflag = 2; } snprintf_P(svalue, ssvalue, PSTR("{\"MqttHost\",\"%s\"}"), sysCfg.mqtt_host); } else if (!strcmp(type,"MQTTPORT")) { if ((data_len > 0) && (payload > 0) && (payload < 32766)) { - sysCfg.mqtt_port = (payload == 1) ? MQTT_PORT : payload; + sysCfg.mqtt_port = (1 == payload) ? MQTT_PORT : payload; restartflag = 2; } snprintf_P(svalue, ssvalue, PSTR("{\"MqttPort\":%d}"), sysCfg.mqtt_port); @@ -606,8 +642,11 @@ boolean mqtt_command(boolean grpflg, char *type, uint16_t index, char *dataBuf, } else if (!strcmp(type,"STATETEXT") && (index > 0) && (index <= 3)) { if ((data_len > 0) && (data_len < sizeof(sysCfg.state_text[0]))) { - for(i = 0; i <= data_len; i++) if (dataBuf[i] == ' ') dataBuf[i] = '_'; -// strlcpy(sysCfg.state_text[index -1], (payload == 1) ? (index==1)?MQTT_STATUS_OFF:(index==2)?MQTT_STATUS_ON:MQTT_CMND_TOGGLE : dataBuf, sizeof(sysCfg.state_text[0])); + for(i = 0; i <= data_len; i++) { + if (dataBuf[i] == ' ') { + dataBuf[i] = '_'; + } + } strlcpy(sysCfg.state_text[index -1], dataBuf, sizeof(sysCfg.state_text[0])); } snprintf_P(svalue, ssvalue, PSTR("{\"StateText%d\":\"%s\"}"), index, getStateText(index -1)); @@ -615,7 +654,7 @@ boolean mqtt_command(boolean grpflg, char *type, uint16_t index, char *dataBuf, #ifdef USE_MQTT_TLS else if (!strcmp(type,"MQTTFINGERPRINT")) { if ((data_len > 0) && (data_len < sizeof(sysCfg.mqtt_fingerprint))) { - strlcpy(sysCfg.mqtt_fingerprint, (!strcmp(dataBuf,"0")) ? "" : (payload == 1) ? MQTT_FINGERPRINT : dataBuf, sizeof(sysCfg.mqtt_fingerprint)); + strlcpy(sysCfg.mqtt_fingerprint, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_FINGERPRINT : dataBuf, sizeof(sysCfg.mqtt_fingerprint)); restartflag = 2; } snprintf_P(svalue, ssvalue, PSTR("{\"MqttFingerprint\":\"%s\"}"), sysCfg.mqtt_fingerprint); @@ -623,31 +662,33 @@ boolean mqtt_command(boolean grpflg, char *type, uint16_t index, char *dataBuf, #endif else if (!grpflg && !strcmp(type,"MQTTCLIENT")) { if ((data_len > 0) && (data_len < sizeof(sysCfg.mqtt_client))) { - strlcpy(sysCfg.mqtt_client, (payload == 1) ? MQTT_CLIENT_ID : dataBuf, sizeof(sysCfg.mqtt_client)); + strlcpy(sysCfg.mqtt_client, (1 == payload) ? MQTT_CLIENT_ID : dataBuf, sizeof(sysCfg.mqtt_client)); restartflag = 2; } snprintf_P(svalue, ssvalue, PSTR("{\"MqttClient\":\"%s\"}"), sysCfg.mqtt_client); } else if (!strcmp(type,"MQTTUSER")) { if ((data_len > 0) && (data_len < sizeof(sysCfg.mqtt_user))) { - strlcpy(sysCfg.mqtt_user, (!strcmp(dataBuf,"0")) ? "" : (payload == 1) ? MQTT_USER : dataBuf, sizeof(sysCfg.mqtt_user)); + strlcpy(sysCfg.mqtt_user, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_USER : dataBuf, sizeof(sysCfg.mqtt_user)); restartflag = 2; } snprintf_P(svalue, ssvalue, PSTR("[\"MqttUser\":\"%s\"}"), sysCfg.mqtt_user); } else if (!strcmp(type,"MQTTPASSWORD")) { if ((data_len > 0) && (data_len < sizeof(sysCfg.mqtt_pwd))) { - strlcpy(sysCfg.mqtt_pwd, (!strcmp(dataBuf,"0")) ? "" : (payload == 1) ? MQTT_PASS : dataBuf, sizeof(sysCfg.mqtt_pwd)); + strlcpy(sysCfg.mqtt_pwd, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? MQTT_PASS : dataBuf, sizeof(sysCfg.mqtt_pwd)); restartflag = 2; } snprintf_P(svalue, ssvalue, PSTR("{\"MqttPassword\":\"%s\"}"), sysCfg.mqtt_pwd); } else if (!strcmp(type,"PREFIX") && (index > 0) && (index <= 3)) { if ((data_len > 0) && (data_len < sizeof(sysCfg.mqtt_prefix[0]))) { - for(i = 0; i <= data_len; i++) -// if ((dataBuf[i] == '/') || (dataBuf[i] == '+') || (dataBuf[i] == '#') || (dataBuf[i] == ' ')) dataBuf[i] = '_'; - if ((dataBuf[i] == '+') || (dataBuf[i] == '#') || (dataBuf[i] == ' ')) dataBuf[i] = '_'; - strlcpy(sysCfg.mqtt_prefix[index -1], (payload == 1) ? (index==1)?SUB_PREFIX:(index==2)?PUB_PREFIX:PUB_PREFIX2 : dataBuf, sizeof(sysCfg.mqtt_prefix[0])); + for(i = 0; i <= data_len; i++) { + if ((dataBuf[i] == '+') || (dataBuf[i] == '#') || (dataBuf[i] == ' ')) { + dataBuf[i] = '_'; + } + } + strlcpy(sysCfg.mqtt_prefix[index -1], (1 == payload) ? (1==index)?SUB_PREFIX:(2==index)?PUB_PREFIX:PUB_PREFIX2 : dataBuf, sizeof(sysCfg.mqtt_prefix[0])); // if (sysCfg.mqtt_prefix[index -1][strlen(sysCfg.mqtt_prefix[index -1])] == '/') sysCfg.mqtt_prefix[index -1][strlen(sysCfg.mqtt_prefix[index -1])] = 0; restartflag = 2; } @@ -655,39 +696,59 @@ boolean mqtt_command(boolean grpflg, char *type, uint16_t index, char *dataBuf, } else if (!strcmp(type,"GROUPTOPIC")) { if ((data_len > 0) && (data_len < sizeof(sysCfg.mqtt_grptopic))) { - for(i = 0; i <= data_len; i++) - if ((dataBuf[i] == '/') || (dataBuf[i] == '+') || (dataBuf[i] == '#')) dataBuf[i] = '_'; - if (!strcmp(dataBuf, MQTTClient)) payload = 1; - strlcpy(sysCfg.mqtt_grptopic, (payload == 1) ? MQTT_GRPTOPIC : dataBuf, sizeof(sysCfg.mqtt_grptopic)); + for(i = 0; i <= data_len; i++) { + if ((dataBuf[i] == '/') || (dataBuf[i] == '+') || (dataBuf[i] == '#')) { + dataBuf[i] = '_'; + } + } + if (!strcmp(dataBuf, MQTTClient)) { + payload = 1; + } + strlcpy(sysCfg.mqtt_grptopic, (1 == payload) ? MQTT_GRPTOPIC : dataBuf, sizeof(sysCfg.mqtt_grptopic)); restartflag = 2; } snprintf_P(svalue, ssvalue, PSTR("{\"GroupTopic\":\"%s\"}"), sysCfg.mqtt_grptopic); } else if (!grpflg && !strcmp(type,"TOPIC")) { if ((data_len > 0) && (data_len < sizeof(sysCfg.mqtt_topic))) { - for(i = 0; i <= data_len; i++) - if ((dataBuf[i] == '/') || (dataBuf[i] == '+') || (dataBuf[i] == '#') || (dataBuf[i] == ' ')) dataBuf[i] = '_'; - if (!strcmp(dataBuf, MQTTClient)) payload = 1; - strlcpy(sysCfg.mqtt_topic, (payload == 1) ? MQTT_TOPIC : dataBuf, sizeof(sysCfg.mqtt_topic)); + for(i = 0; i <= data_len; i++) { + if ((dataBuf[i] == '/') || (dataBuf[i] == '+') || (dataBuf[i] == '#') || (dataBuf[i] == ' ')) { + dataBuf[i] = '_'; + } + } + if (!strcmp(dataBuf, MQTTClient)) { + payload = 1; + } + strlcpy(sysCfg.mqtt_topic, (1 == payload) ? MQTT_TOPIC : dataBuf, sizeof(sysCfg.mqtt_topic)); restartflag = 2; } snprintf_P(svalue, ssvalue, PSTR("{\"Topic\":\"%s\"}"), sysCfg.mqtt_topic); } else if (!grpflg && !strcmp(type,"BUTTONTOPIC")) { if ((data_len > 0) && (data_len < sizeof(sysCfg.button_topic))) { - for(i = 0; i <= data_len; i++) - if ((dataBuf[i] == '/') || (dataBuf[i] == '+') || (dataBuf[i] == '#') || (dataBuf[i] == ' ')) dataBuf[i] = '_'; - if (!strcmp(dataBuf, MQTTClient)) payload = 1; - strlcpy(sysCfg.button_topic, (!strcmp(dataBuf,"0")) ? "" : (payload == 1) ? sysCfg.mqtt_topic : dataBuf, sizeof(sysCfg.button_topic)); + for(i = 0; i <= data_len; i++) { + if ((dataBuf[i] == '/') || (dataBuf[i] == '+') || (dataBuf[i] == '#') || (dataBuf[i] == ' ')) { + dataBuf[i] = '_'; + } + } + if (!strcmp(dataBuf, MQTTClient)) { + payload = 1; + } + strlcpy(sysCfg.button_topic, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? sysCfg.mqtt_topic : dataBuf, sizeof(sysCfg.button_topic)); } snprintf_P(svalue, ssvalue, PSTR("{\"ButtonTopic\":\"%s\"}"), sysCfg.button_topic); } else if (!grpflg && !strcmp(type,"SWITCHTOPIC")) { if ((data_len > 0) && (data_len < sizeof(sysCfg.switch_topic))) { - for(i = 0; i <= data_len; i++) - if ((dataBuf[i] == '/') || (dataBuf[i] == '+') || (dataBuf[i] == '#') || (dataBuf[i] == ' ')) dataBuf[i] = '_'; - if (!strcmp(dataBuf, MQTTClient)) payload = 1; - strlcpy(sysCfg.switch_topic, (!strcmp(dataBuf,"0")) ? "" : (payload == 1) ? sysCfg.mqtt_topic : dataBuf, sizeof(sysCfg.switch_topic)); + for(i = 0; i <= data_len; i++) { + if ((dataBuf[i] == '/') || (dataBuf[i] == '+') || (dataBuf[i] == '#') || (dataBuf[i] == ' ')) { + dataBuf[i] = '_'; + } + } + if (!strcmp(dataBuf, MQTTClient)) { + payload = 1; + } + strlcpy(sysCfg.switch_topic, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? sysCfg.mqtt_topic : dataBuf, sizeof(sysCfg.switch_topic)); } snprintf_P(svalue, ssvalue, PSTR("{\"SwitchTopic\":\"%s\"}"), sysCfg.switch_topic); } @@ -705,7 +766,7 @@ boolean mqtt_command(boolean grpflg, char *type, uint16_t index, char *dataBuf, } else if (!strcmp(type,"SWITCHRETAIN")) { if ((data_len > 0) && (payload >= 0) && (payload <= 1)) { - strlcpy(sysCfg.button_topic, sysCfg.mqtt_topic, sizeof(sysCfg.button_topic)); + strlcpy(sysCfg.button_topic, sysCfg.mqtt_topic, sizeof(sysCfg.button_topic)); if (!payload) { for(i = 1; i <= 4; i++) { send_button_power(1, i, 3); // Clear MQTT retain in broker @@ -748,14 +809,26 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) if (!strcmp(sysCfg.mqtt_prefix[0],sysCfg.mqtt_prefix[1])) { str = strstr(topic,sysCfg.mqtt_prefix[0]); if ((str == topic) && mqtt_cmnd_publish) { - if (mqtt_cmnd_publish > 8) mqtt_cmnd_publish -= 8; else mqtt_cmnd_publish = 0; + if (mqtt_cmnd_publish > 8) { + mqtt_cmnd_publish -= 8; + } else { + mqtt_cmnd_publish = 0; + } return; } } - char topicBuf[TOPSZ], dataBuf[data_len+1], dataBufUc[128], svalue[MESSZ], stemp1[TOPSZ]; - char *p, *mtopic = NULL, *type = NULL; - uint16_t i = 0, grpflg = 0, index; + char topicBuf[TOPSZ]; + char dataBuf[data_len+1]; + char dataBufUc[128]; + char svalue[MESSZ]; + char stemp1[TOPSZ]; + char *p; + char *mtopic = NULL; + char *type = NULL; + uint16_t i = 0; + uint16_t grpflg = 0; + uint16_t index; uint32_t address; strncpy(topicBuf, topic, sizeof(topicBuf)); @@ -768,7 +841,9 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) #ifdef USE_DOMOTICZ if (sysCfg.mqtt_enabled) { - if (domoticz_mqttData(topicBuf, sizeof(topicBuf), dataBuf, sizeof(dataBuf))) return; + if (domoticz_mqttData(topicBuf, sizeof(topicBuf), dataBuf, sizeof(dataBuf))) { + return; + } } #endif // USE_DOMOTICZ @@ -784,17 +859,27 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) type = str; } } - if (!strcmp(mtopic, sysCfg.mqtt_grptopic)) grpflg = 1; + if (!strcmp(mtopic, sysCfg.mqtt_grptopic)) { + grpflg = 1; + } index = 1; if (type != NULL) { - for (i = 0; i < strlen(type); i++) type[i] = toupper(type[i]); - while (isdigit(type[i-1])) i--; - if (i < strlen(type)) index = atoi(type +i); + for (i = 0; i < strlen(type); i++) { + type[i] = toupper(type[i]); + } + while (isdigit(type[i-1])) { + i--; + } + if (i < strlen(type)) { + index = atoi(type +i); + } type[i] = '\0'; } - for (i = 0; i <= sizeof(dataBufUc); i++) dataBufUc[i] = toupper(dataBuf[i]); + for (i = 0; i <= sizeof(dataBufUc); i++) { + dataBufUc[i] = toupper(dataBuf[i]); + } snprintf_P(svalue, sizeof(svalue), PSTR("RSLT: DataCb Topic %s, Group %d, Index %d, Type %s, Data %s (%s)"), mtopic, grpflg, index, type, dataBuf, dataBufUc); @@ -803,24 +888,42 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) // snprintf_P(stopic, sizeof(stopic), PSTR("%s/%s/RESULT"), PUB_PREFIX, sysCfg.mqtt_topic); if (type != NULL) { snprintf_P(svalue, sizeof(svalue), PSTR("{\"Command\":\"Error\"}")); - if (sysCfg.ledstate &0x02) blinks++; + if (sysCfg.ledstate &0x02) { + blinks++; + } - if (!strcmp(dataBufUc,"?")) data_len = 0; + if (!strcmp(dataBufUc,"?")) { + data_len = 0; + } int16_t payload = atoi(dataBuf); // -32766 - 32767 uint16_t payload16 = atoi(dataBuf); // 0 - 65535 - if (!strcmp(dataBufUc,"OFF") || !strcmp(dataBufUc,"FALSE") || !strcmp(dataBufUc,"STOP")) payload = 0; - if (!strcmp(dataBufUc,"ON") || !strcmp(dataBufUc,"TRUE") || !strcmp(dataBufUc,"START") || !strcmp(dataBufUc,"USER")) payload = 1; - if (!strcmp(dataBufUc,"TOGGLE") || !strcmp(dataBufUc,"ADMIN")) payload = 2; - if (!strcmp(dataBufUc,"BLINK")) payload = 3; - if (!strcmp(dataBufUc,"BLINKOFF")) payload = 4; + if (!strcmp(dataBufUc,"OFF") || !strcmp(dataBufUc,"FALSE") || !strcmp(dataBufUc,"STOP")) { + payload = 0; + } + if (!strcmp(dataBufUc,"ON") || !strcmp(dataBufUc,"TRUE") || !strcmp(dataBufUc,"START") || !strcmp(dataBufUc,"USER")) { + payload = 1; + } + if (!strcmp(dataBufUc,"TOGGLE") || !strcmp(dataBufUc,"ADMIN")) { + payload = 2; + } + if (!strcmp(dataBufUc,"BLINK")) { + payload = 3; + } + if (!strcmp(dataBufUc,"BLINKOFF")) { + payload = 4; + } if (!strcmp(type,"POWER") && (index > 0) && (index <= Maxdevice)) { - if ((data_len == 0) || (payload > 4)) payload = 9; + if ((0 == data_len) || (payload > 4)) { + payload = 9; + } do_cmnd_power(index, payload); return; } else if (!strcmp(type,"STATUS")) { - if ((data_len == 0) || (payload < 0) || (payload > MAX_STATUS)) payload = 99; + if ((0 == data_len) || (payload < 0) || (payload > MAX_STATUS)) { + payload = 99; + } publish_status(payload); return; } @@ -840,18 +943,22 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) else if (!strcmp(type,"BLINKTIME")) { if ((data_len > 0) && (payload > 2) && (payload <= 3600)) { sysCfg.blinktime = payload; - if (blink_timer) blink_timer = sysCfg.blinktime; + if (blink_timer) { + blink_timer = sysCfg.blinktime; + } } snprintf_P(svalue, sizeof(svalue), PSTR("{\"BlinkTime\":%d}"), sysCfg.blinktime); } else if (!strcmp(type,"BLINKCOUNT")) { if (data_len > 0) { sysCfg.blinkcount = payload16; // 0 - 65535 - if (blink_counter) blink_counter = sysCfg.blinkcount *2; + if (blink_counter) { + blink_counter = sysCfg.blinkcount *2; + } } snprintf_P(svalue, sizeof(svalue), PSTR("{\"BlinkCount\":%d}"), sysCfg.blinkcount); } - else if ((sysCfg.module == SONOFF_LED) && sl_command(type, index, dataBufUc, data_len, payload, svalue, sizeof(svalue))) { + else if ((SONOFF_LED == sysCfg.module) && sl_command(type, index, dataBufUc, data_len, payload, svalue, sizeof(svalue))) { // Serviced } else if (!strcmp(type,"SAVEDATA")) { @@ -859,9 +966,13 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) sysCfg.savedata = payload; savedatacounter = sysCfg.savedata; } - if (sysCfg.savestate) sysCfg.power = power; + if (sysCfg.savestate) { + sysCfg.power = power; + } CFG_Save(); - if (sysCfg.savedata > 1) snprintf_P(stemp1, sizeof(stemp1), PSTR("Every %d seconds"), sysCfg.savedata); + if (sysCfg.savedata > 1) { + snprintf_P(stemp1, sizeof(stemp1), PSTR("Every %d seconds"), sysCfg.savedata); + } snprintf_P(svalue, sizeof(svalue), PSTR("{\"SaveData\":\"%s\"}"), (sysCfg.savedata > 1) ? stemp1 : getStateText(sysCfg.savedata)); } else if (!strcmp(type,"SAVESTATE")) { @@ -895,7 +1006,9 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) byte new_modflg = (sysCfg.module != payload); sysCfg.module = payload; if (new_modflg) { - for (byte i = 0; i < MAX_GPIO_PIN; i++) sysCfg.my_module.gp.io[i] = 0; + for (byte i = 0; i < MAX_GPIO_PIN; i++) { + sysCfg.my_module.gp.io[i] = 0; + } setModuleFlashMode(0); } restartflag = 2; @@ -907,7 +1020,9 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) snprintf_P(svalue, sizeof(svalue), PSTR("{\"Modules1\":\""), svalue); byte jsflg = 0; for (byte i = 0; i < MAXMODULE /2; i++) { - if (jsflg) snprintf_P(svalue, sizeof(svalue), PSTR("%s, "), svalue); + if (jsflg) { + snprintf_P(svalue, sizeof(svalue), PSTR("%s, "), svalue); + } jsflg = 1; snprintf_P(stemp1, sizeof(stemp1), modules[i].name); snprintf_P(svalue, sizeof(svalue), PSTR("%s%d (%s)"), svalue, i +1, stemp1); @@ -917,7 +1032,9 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) snprintf_P(svalue, sizeof(svalue), PSTR("{\"Modules2\":\""), svalue); jsflg = 0; for (byte i = MAXMODULE /2; i < MAXMODULE; i++) { - if (jsflg) snprintf_P(svalue, sizeof(svalue), PSTR("%s, "), svalue); + if (jsflg) { + snprintf_P(svalue, sizeof(svalue), PSTR("%s, "), svalue); + } jsflg = 1; snprintf_P(stemp1, sizeof(stemp1), modules[i].name); snprintf_P(svalue, sizeof(svalue), PSTR("%s%d (%s)"), svalue, i +1, stemp1); @@ -927,9 +1044,11 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) else if (!strcmp(type,"GPIO") && (index < MAX_GPIO_PIN)) { mytmplt cmodule; memcpy_P(&cmodule, &modules[sysCfg.module], sizeof(cmodule)); - if ((data_len > 0) && (cmodule.gp.io[index] == GPIO_USER) && (payload >= 0) && (payload < GPIO_SENSOR_END)) { + if ((data_len > 0) && (GPIO_USER == cmodule.gp.io[index]) && (payload >= 0) && (payload < GPIO_SENSOR_END)) { for (byte i = 0; i < MAX_GPIO_PIN; i++) { - if ((cmodule.gp.io[i] == GPIO_USER) && (sysCfg.my_module.gp.io[i] == payload)) sysCfg.my_module.gp.io[i] = 0; + if ((GPIO_USER == cmodule.gp.io[i]) && (sysCfg.my_module.gp.io[i] == payload)) { + sysCfg.my_module.gp.io[i] = 0; + } } sysCfg.my_module.gp.io[index] = payload; restartflag = 2; @@ -937,8 +1056,10 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) snprintf_P(svalue, sizeof(svalue), PSTR("{"), svalue); byte jsflg = 0; for (byte i = 0; i < MAX_GPIO_PIN; i++) { - if (cmodule.gp.io[i] == GPIO_USER) { - if (jsflg) snprintf_P(svalue, sizeof(svalue), PSTR("%s, "), svalue); + if (GPIO_USER == cmodule.gp.io[i]) { + if (jsflg) { + snprintf_P(svalue, sizeof(svalue), PSTR("%s, "), svalue); + } jsflg = 1; snprintf_P(stemp1, sizeof(stemp1), sensors[sysCfg.my_module.gp.io[i]]); snprintf_P(svalue, sizeof(svalue), PSTR("%s\"GPIO%d\":%d (%s)"), svalue, i, sysCfg.my_module.gp.io[i], stemp1); @@ -954,7 +1075,9 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) snprintf_P(svalue, sizeof(svalue), PSTR("{\"GPIOs1\":\""), svalue); byte jsflg = 0; for (byte i = 0; i < GPIO_SENSOR_END /2; i++) { - if (jsflg) snprintf_P(svalue, sizeof(svalue), PSTR("%s, "), svalue); + if (jsflg) { + snprintf_P(svalue, sizeof(svalue), PSTR("%s, "), svalue); + } jsflg = 1; snprintf_P(stemp1, sizeof(stemp1), sensors[i]); snprintf_P(svalue, sizeof(svalue), PSTR("%s%d (%s)"), svalue, i, stemp1); @@ -964,7 +1087,9 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) snprintf_P(svalue, sizeof(svalue), PSTR("{\"GPIOs2\":\""), svalue); jsflg = 0; for (byte i = GPIO_SENSOR_END /2; i < GPIO_SENSOR_END; i++) { - if (jsflg) snprintf_P(svalue, sizeof(svalue), PSTR("%s, "), svalue); + if (jsflg) { + snprintf_P(svalue, sizeof(svalue), PSTR("%s, "), svalue); + } jsflg = 1; snprintf_P(stemp1, sizeof(stemp1), sensors[i]); snprintf_P(svalue, sizeof(svalue), PSTR("%s%d (%s)"), svalue, i, stemp1); @@ -988,21 +1113,24 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) } else if (!strcmp(type,"SLEEP")) { if ((data_len > 0) && (payload >= 0) && (payload < 251)) { - if ((!sysCfg.sleep && payload) || (sysCfg.sleep && !payload)) restartflag = 2; + if ((!sysCfg.sleep && payload) || (sysCfg.sleep && !payload)) { + restartflag = 2; + } sysCfg.sleep = payload; sleep = payload; -// restartflag = 2; } snprintf_P(svalue, sizeof(svalue), PSTR("{\"Sleep\":\"%d%s (%d%s)\"}"), sleep, (sysCfg.value_units) ? " mS" : "", sysCfg.sleep, (sysCfg.value_units) ? " mS" : ""); } else if (!strcmp(type,"FLASHMODE")) { // 0 = QIO, 1 = QOUT, 2 = DIO, 3 = DOUT if ((data_len > 0) && (payload >= 0) && (payload <= 3)) { - if (ESP.getFlashChipMode() != payload) setFlashMode(0, payload &3); + if (ESP.getFlashChipMode() != payload) { + setFlashMode(0, payload &3); + } } snprintf_P(svalue, sizeof(svalue), PSTR("{\"FlashMode\":%d}"), ESP.getFlashChipMode()); } else if (!strcmp(type,"UPGRADE") || !strcmp(type,"UPLOAD")) { - if ((data_len > 0) && (payload == 1)) { + if ((data_len > 0) && (1 == payload)) { otaflag = 3; snprintf_P(svalue, sizeof(svalue), PSTR("{\"Upgrade\":\"Version %s from %s\"}"), Version, sysCfg.otaUrl); } else { @@ -1011,7 +1139,7 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) } else if (!strcmp(type,"OTAURL")) { if ((data_len > 0) && (data_len < sizeof(sysCfg.otaUrl))) - strlcpy(sysCfg.otaUrl, (payload == 1) ? OTA_URL : dataBuf, sizeof(sysCfg.otaUrl)); + strlcpy(sysCfg.otaUrl, (1 == payload) ? OTA_URL : dataBuf, sizeof(sysCfg.otaUrl)); snprintf_P(svalue, sizeof(svalue), PSTR("{\"OtaUrl\":\"%s\"}"), sysCfg.otaUrl); } else if (!strcmp(type,"SERIALLOG")) { @@ -1032,13 +1160,13 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) } else if (!strcmp(type,"LOGHOST")) { if ((data_len > 0) && (data_len < sizeof(sysCfg.syslog_host))) { - strlcpy(sysCfg.syslog_host, (payload == 1) ? SYS_LOG_HOST : dataBuf, sizeof(sysCfg.syslog_host)); + strlcpy(sysCfg.syslog_host, (1 == payload) ? SYS_LOG_HOST : dataBuf, sizeof(sysCfg.syslog_host)); } snprintf_P(svalue, sizeof(svalue), PSTR("{\"LogHost\":\"%s\"}"), sysCfg.syslog_host); } else if (!strcmp(type,"LOGPORT")) { if ((data_len > 0) && (payload > 0) && (payload < 32766)) { - sysCfg.syslog_port = (payload == 1) ? SYS_LOG_PORT : payload; + sysCfg.syslog_port = (1 == payload) ? SYS_LOG_PORT : payload; } snprintf_P(svalue, sizeof(svalue), PSTR("{\"LogPort\":%d}"), sysCfg.syslog_port); } @@ -1048,12 +1176,16 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) // restartflag = 2; } snprintf_P(stemp1, sizeof(stemp1), PSTR(" (%s)"), WiFi.localIP().toString().c_str()); - snprintf_P(svalue, sizeof(svalue), PSTR("{\"IPAddress%d\":\"%s%s\"}"), index, IPAddress(sysCfg.ip_address[index -1]).toString().c_str(), (index == 1) ? stemp1:""); + snprintf_P(svalue, sizeof(svalue), PSTR("{\"IPAddress%d\":\"%s%s\"}"), index, IPAddress(sysCfg.ip_address[index -1]).toString().c_str(), (1 == index) ? stemp1:""); } else if (!strcmp(type,"NTPSERVER") && (index > 0) && (index <= 3)) { if ((data_len > 0) && (data_len < sizeof(sysCfg.ntp_server[0]))) { - strlcpy(sysCfg.ntp_server[index -1], (!strcmp(dataBuf,"0")) ? "" : (payload == 1) ? (index==1)?NTP_SERVER1:(index==2)?NTP_SERVER2:NTP_SERVER3 : dataBuf, sizeof(sysCfg.ntp_server[0])); - for (i = 0; i < strlen(sysCfg.ntp_server[index -1]); i++) if (sysCfg.ntp_server[index -1][i] == ',') sysCfg.ntp_server[index -1][i] = '.'; + strlcpy(sysCfg.ntp_server[index -1], (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? (1==index)?NTP_SERVER1:(2==index)?NTP_SERVER2:NTP_SERVER3 : dataBuf, sizeof(sysCfg.ntp_server[0])); + for (i = 0; i < strlen(sysCfg.ntp_server[index -1]); i++) { + if (sysCfg.ntp_server[index -1][i] == ',') { + sysCfg.ntp_server[index -1][i] = '.'; + } + } restartflag = 2; } snprintf_P(svalue, sizeof(svalue), PSTR("{\"NtpServer%d\":\"%s\"}"), index, sysCfg.ntp_server[index -1]); @@ -1074,7 +1206,7 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) } else if (!strcmp(type,"SSID") && (index > 0) && (index <= 2)) { if ((data_len > 0) && (data_len < sizeof(sysCfg.sta_ssid[0]))) { - strlcpy(sysCfg.sta_ssid[index -1], (payload == 1) ? (index == 1) ? STA_SSID1 : STA_SSID2 : dataBuf, sizeof(sysCfg.sta_ssid[0])); + strlcpy(sysCfg.sta_ssid[index -1], (1 == payload) ? (1 == index) ? STA_SSID1 : STA_SSID2 : dataBuf, sizeof(sysCfg.sta_ssid[0])); sysCfg.sta_active = 0; restartflag = 2; } @@ -1082,7 +1214,7 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) } else if (!strcmp(type,"PASSWORD") && (index > 0) && (index <= 2)) { if ((data_len > 0) && (data_len < sizeof(sysCfg.sta_pwd[0]))) { - strlcpy(sysCfg.sta_pwd[index -1], (payload == 1) ? (index == 1) ? STA_PASS1 : STA_PASS2 : dataBuf, sizeof(sysCfg.sta_pwd[0])); + strlcpy(sysCfg.sta_pwd[index -1], (1 == payload) ? (1 == index) ? STA_PASS1 : STA_PASS2 : dataBuf, sizeof(sysCfg.sta_pwd[0])); sysCfg.sta_active = 0; restartflag = 2; } @@ -1090,8 +1222,10 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) } else if (!grpflg && !strcmp(type,"HOSTNAME")) { if ((data_len > 0) && (data_len < sizeof(sysCfg.hostname))) { - strlcpy(sysCfg.hostname, (payload == 1) ? WIFI_HOSTNAME : dataBuf, sizeof(sysCfg.hostname)); - if (strstr(sysCfg.hostname,"%")) strlcpy(sysCfg.hostname, WIFI_HOSTNAME, sizeof(sysCfg.hostname)); + strlcpy(sysCfg.hostname, (1 == payload) ? WIFI_HOSTNAME : dataBuf, sizeof(sysCfg.hostname)); + if (strstr(sysCfg.hostname,"%")) { + strlcpy(sysCfg.hostname, WIFI_HOSTNAME, sizeof(sysCfg.hostname)); + } restartflag = 2; } snprintf_P(svalue, sizeof(svalue), PSTR("{\"Hostname\":\"%s\"}"), sysCfg.hostname); @@ -1113,12 +1247,12 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) } else if (!strcmp(type,"FRIENDLYNAME") && (index > 0) && (index <= 4)) { if ((data_len > 0) && (data_len < sizeof(sysCfg.friendlyname[0]))) { - if (index == 1) { + if (1 == index) { snprintf_P(stemp1, sizeof(stemp1), PSTR(FRIENDLY_NAME)); } else { snprintf_P(stemp1, sizeof(stemp1), PSTR(FRIENDLY_NAME "%d"), index); } - strlcpy(sysCfg.friendlyname[index -1], (payload == 1) ? stemp1 : dataBuf, sizeof(sysCfg.friendlyname[index -1])); + strlcpy(sysCfg.friendlyname[index -1], (1 == payload) ? stemp1 : dataBuf, sizeof(sysCfg.friendlyname[index -1])); } snprintf_P(svalue, sizeof(svalue), PSTR("{\"FriendlyName%d\":\"%s\"}"), index, sysCfg.friendlyname[index -1]); } @@ -1135,14 +1269,14 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) } if (sysCfg.webserver) { snprintf_P(svalue, sizeof(svalue), PSTR("{\"Webserver\":\"Active for %s on %s with IP address %s\"}"), - (sysCfg.webserver == 2) ? "ADMIN" : "USER", Hostname, WiFi.localIP().toString().c_str()); + (2 == sysCfg.webserver) ? "ADMIN" : "USER", Hostname, WiFi.localIP().toString().c_str()); } else { snprintf_P(svalue, sizeof(svalue), PSTR("{\"Webserver\":\"%s\"}"), getStateText(0)); } } else if (!strcmp(type,"WEBPASSWORD")) { if ((data_len > 0) && (data_len < sizeof(sysCfg.web_password))) { - strlcpy(sysCfg.web_password, (!strcmp(dataBuf,"0")) ? "" : (payload == 1) ? WEB_PASSWORD : dataBuf, sizeof(sysCfg.web_password)); + strlcpy(sysCfg.web_password, (!strcmp(dataBuf,"0")) ? "" : (1 == payload) ? WEB_PASSWORD : dataBuf, sizeof(sysCfg.web_password)); } snprintf_P(svalue, sizeof(svalue), PSTR("{\"WebPassword\":\"%s\"}"), sysCfg.web_password); } @@ -1164,8 +1298,10 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) #endif // USE_WEBSERVER else if (!strcmp(type,"TELEPERIOD")) { if ((data_len > 0) && (payload >= 0) && (payload < 3601)) { - sysCfg.tele_period = (payload == 1) ? TELE_PERIOD : payload; - if ((sysCfg.tele_period > 0) && (sysCfg.tele_period < 10)) sysCfg.tele_period = 10; // Do not allow periods < 10 seconds + sysCfg.tele_period = (1 == payload) ? TELE_PERIOD : payload; + if ((sysCfg.tele_period > 0) && (sysCfg.tele_period < 10)) { + sysCfg.tele_period = 10; // Do not allow periods < 10 seconds + } tele_period = sysCfg.tele_period; } snprintf_P(svalue, sizeof(svalue), PSTR("{\"TelePeriod\":\"%d%s\"}"), sysCfg.tele_period, (sysCfg.value_units) ? " Sec" : ""); @@ -1199,7 +1335,7 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) } } else if (!strcmp(type,"TIMEZONE")) { - if ((data_len > 0) && (((payload >= -12) && (payload <= 12)) || (payload == 99))) { + if ((data_len > 0) && (((payload >= -12) && (payload <= 12)) || (99 == payload))) { sysCfg.timezone = payload; } snprintf_P(svalue, sizeof(svalue), PSTR("{\"Timezone\":%d}"), sysCfg.timezone); @@ -1224,7 +1360,9 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) else if (!strcmp(type,"LEDSTATE")) { if ((data_len > 0) && (payload >= 0) && (payload < MAX_LED_OPTION)) { sysCfg.ledstate = payload; - if (!sysCfg.ledstate) setLed(0); + if (!sysCfg.ledstate) { + setLed(0); + } } snprintf_P(svalue, sizeof(svalue), PSTR("{\"LedState\":%d}"), sysCfg.ledstate); } @@ -1255,7 +1393,9 @@ void mqttDataCb(char* topic, byte* data, unsigned int data_len) #endif // USE_IR_REMOTE #ifdef DEBUG_THEO else if (!strcmp(type,"EXCEPTION")) { - if (data_len > 0) exception_tst(payload); + if (data_len > 0) { + exception_tst(payload); + } snprintf_P(svalue, sizeof(svalue), PSTR("{\"Exception\":\"Triggered\"}")); } #endif // DEBUG_THEO @@ -1279,17 +1419,21 @@ void send_button_power(byte key, byte device, byte state) // key 0 = button_topic // key 1 = switch_topic - char stopic[TOPSZ], svalue[TOPSZ], stemp1[10]; + char stopic[TOPSZ]; + char svalue[TOPSZ]; + char stemp1[10]; - if (!key && (device > Maxdevice)) device = 1; + if (!key && (device > Maxdevice)) { + device = 1; + } snprintf_P(stemp1, sizeof(stemp1), PSTR("%d"), device); snprintf_P(stopic, sizeof(stopic), PSTR("%s/%s/POWER%s"), sysCfg.mqtt_prefix[0], (key) ? sysCfg.switch_topic : sysCfg.button_topic, (key || (Maxdevice > 1)) ? stemp1 : ""); - if (state == 3) { + if (3 == state) { svalue[0] = '\0'; } else { - if (!strcmp(sysCfg.mqtt_topic,(key) ? sysCfg.switch_topic : sysCfg.button_topic) && (state == 2)) { + if (!strcmp(sysCfg.mqtt_topic,(key) ? sysCfg.switch_topic : sysCfg.button_topic) && (2 == state)) { state = ~(power >> (device -1)) & 0x01; } snprintf_P(svalue, sizeof(svalue), PSTR("%s"), getStateText(state)); @@ -1313,7 +1457,9 @@ void do_cmnd_power(byte device, byte state) // state 4 = Stop blinking relay // state 9 = Show power state - if ((device < 1) || (device > Maxdevice)) device = 1; + if ((device < 1) || (device > Maxdevice)) { + device = 1; + } byte mask = 0x01 << (device -1); pulse_timer[(device -1)&3] = 0; if (state <= 2) { @@ -1337,7 +1483,7 @@ void do_cmnd_power(byte device, byte state) #endif // USE_DOMOTICZ pulse_timer[(device -1)&3] = (power & mask) ? sysCfg.pulsetime[(device -1)&3] : 0; } - else if (state == 3) { // Blink + else if (3 == state) { // Blink if (!(blink_mask & mask)) { blink_powersave = (blink_powersave & (0xFF ^ mask)) | (power & mask); // Save state blink_power = (power >> (device -1))&1; // Prep to Toggle @@ -1348,11 +1494,13 @@ void do_cmnd_power(byte device, byte state) mqtt_publishPowerBlinkState(device); return; } - else if (state == 4) { // No Blink + else if (4 == state) { // No Blink byte flag = (blink_mask & mask); blink_mask &= (0xFF ^ mask); // Clear device mask mqtt_publishPowerBlinkState(device); - if (flag) do_cmnd_power(device, (blink_powersave >> (device -1))&1); // Restore state + if (flag) { + do_cmnd_power(device, (blink_powersave >> (device -1))&1); // Restore state + } return; } mqtt_publishPowerState(device); @@ -1360,9 +1508,9 @@ void do_cmnd_power(byte device, byte state) void stop_all_power_blink() { - byte i, mask; + byte mask; - for (i = 1; i <= Maxdevice; i++) { + for (byte i = 1; i <= Maxdevice; i++) { mask = 0x01 << (i -1); if (blink_mask & mask) { blink_mask &= (0xFF ^ mask); // Clear device mask @@ -1374,14 +1522,17 @@ void stop_all_power_blink() void do_cmnd(char *cmnd) { - char stopic[TOPSZ], svalue[128]; + char stopic[TOPSZ]; + char svalue[128]; char *start; char *token; token = strtok(cmnd, " "); if (token != NULL) { start = strrchr(token, '/'); // Skip possible cmnd/sonoff/ preamble - if (start) token = start; + if (start) { + token = start; + } } snprintf_P(stopic, sizeof(stopic), PSTR("%s/%s/%s"), sysCfg.mqtt_prefix[0], sysCfg.mqtt_topic, token); token = strtok(NULL, ""); @@ -1397,74 +1548,76 @@ void publish_status(uint8_t payload) // Workaround MQTT - TCP/IP stack queueing when SUB_PREFIX = PUB_PREFIX option = (!strcmp(sysCfg.mqtt_prefix[0],sysCfg.mqtt_prefix[1]) && (!payload)); - if ((!sysCfg.mqtt_enabled) && (payload == 6)) payload = 99; - if ((!hlw_flg) && ((payload == 8) || (payload == 9))) payload = 99; + if ((!sysCfg.mqtt_enabled) && (6 == payload)) { + payload = 99; + } + if ((!hlw_flg) && ((8 == payload) || (9 == payload))) { + payload = 99; + } - if ((payload == 0) || (payload == 99)) { + if ((0 == payload) || (99 == payload)) { snprintf_P(svalue, sizeof(svalue), PSTR("{\"Status\":{\"Module\":%d, \"FriendlyName\":\"%s\", \"Topic\":\"%s\", \"ButtonTopic\":\"%s\", \"Power\":%d, \"PowerOnState\":%d, \"LedState\":%d, \"SaveData\":%d, \"SaveState\":%d, \"ButtonRetain\":%d, \"PowerRetain\":%d}}"), sysCfg.module +1, sysCfg.friendlyname[0], sysCfg.mqtt_topic, sysCfg.button_topic, power, sysCfg.poweronstate, sysCfg.ledstate, sysCfg.savedata, sysCfg.savestate, sysCfg.mqtt_button_retain, sysCfg.mqtt_power_retain); mqtt_publish_topic_P(option, PSTR("STATUS"), svalue); } - if ((payload == 0) || (payload == 1)) { + if ((0 == payload) || (1 == payload)) { snprintf_P(svalue, sizeof(svalue), PSTR("{\"StatusPRM\":{\"Baudrate\":%d, \"GroupTopic\":\"%s\", \"OtaUrl\":\"%s\", \"Uptime\":%d, \"Sleep\":%d, \"BootCount\":%d, \"SaveCount\":%d}}"), Baudrate, sysCfg.mqtt_grptopic, sysCfg.otaUrl, uptime, sysCfg.sleep, sysCfg.bootcount, sysCfg.saveFlag); mqtt_publish_topic_P(option, PSTR("STATUS1"), svalue); } - if ((payload == 0) || (payload == 2)) { -// snprintf_P(svalue, sizeof(svalue), PSTR("{\"StatusFWR\":{\"Program\":\"%s\", \"BuildDateTime\":\"%s/%s\", \"Boot\":%d, \"Core\":\"%s\", \"SDK\":\"%s\"}}"), -// Version, __DATE__, __TIME__, ESP.getBootVersion(), ESP.getCoreVersion().c_str(), ESP.getSdkVersion()); + if ((0 == payload) || (2 == payload)) { snprintf_P(svalue, sizeof(svalue), PSTR("{\"StatusFWR\":{\"Program\":\"%s\", \"BuildDateTime\":\"%s\", \"Boot\":%d, \"Core\":\"%s\", \"SDK\":\"%s\"}}"), Version, getBuildDateTime().c_str(), ESP.getBootVersion(), ESP.getCoreVersion().c_str(), ESP.getSdkVersion()); mqtt_publish_topic_P(option, PSTR("STATUS2"), svalue); } - if ((payload == 0) || (payload == 3)) { + if ((0 == payload) || (3 == payload)) { snprintf_P(svalue, sizeof(svalue), PSTR("{\"StatusLOG\":{\"Seriallog\":%d, \"Weblog\":%d, \"Syslog\":%d, \"LogHost\":\"%s\", \"SSId1\":\"%s\", \"SSId2\":\"%s\", \"TelePeriod\":%d}}"), sysCfg.seriallog_level, sysCfg.weblog_level, sysCfg.syslog_level, sysCfg.syslog_host, sysCfg.sta_ssid[0], sysCfg.sta_ssid[1], sysCfg.tele_period); mqtt_publish_topic_P(option, PSTR("STATUS3"), svalue); } - if ((payload == 0) || (payload == 4)) { - snprintf_P(svalue, sizeof(svalue), PSTR("{\"StatusMEM\":{\"ProgramSize\":%d, \"Free\":%d, \"Heap\":%d, \"FlashSize\":%d, \"ProgramFlashSize\":%d, \"FlashMode\":%d}}"), - ESP.getSketchSize()/1024, ESP.getFreeSketchSpace()/1024, ESP.getFreeHeap()/1024, ESP.getFlashChipRealSize()/1024, ESP.getFlashChipSize()/1024, ESP.getFlashChipMode()); + if ((0 == payload) || (4 == payload)) { + snprintf_P(svalue, sizeof(svalue), PSTR("{\"StatusMEM\":{\"ProgramSize\":%d, \"Free\":%d, \"Heap\":%d, \"ProgramFlashSize\":%d, \"FlashSize\":%d, \"FlashMode\":%d}}"), + ESP.getSketchSize()/1024, ESP.getFreeSketchSpace()/1024, ESP.getFreeHeap()/1024, ESP.getFlashChipSize()/1024, ESP.getFlashChipRealSize()/1024, ESP.getFlashChipMode()); mqtt_publish_topic_P(option, PSTR("STATUS4"), svalue); } - if ((payload == 0) || (payload == 5)) { + if ((0 == payload) || (5 == payload)) { snprintf_P(svalue, sizeof(svalue), PSTR("{\"StatusNET\":{\"Host\":\"%s\", \"IP\":\"%s\", \"Gateway\":\"%s\", \"Subnetmask\":\"%s\", \"DNSServer\":\"%s\", \"Mac\":\"%s\", \"Webserver\":%d, \"WifiConfig\":%d}}"), Hostname, WiFi.localIP().toString().c_str(), IPAddress(sysCfg.ip_address[1]).toString().c_str(), IPAddress(sysCfg.ip_address[2]).toString().c_str(), IPAddress(sysCfg.ip_address[3]).toString().c_str(), WiFi.macAddress().c_str(), sysCfg.webserver, sysCfg.sta_config); mqtt_publish_topic_P(option, PSTR("STATUS5"), svalue); } - if (((payload == 0) || (payload == 6)) && sysCfg.mqtt_enabled) { + if (((0 == payload) || (6 == payload)) && sysCfg.mqtt_enabled) { snprintf_P(svalue, sizeof(svalue), PSTR("{\"StatusMQT\":{\"Host\":\"%s\", \"Port\":%d, \"ClientMask\":\"%s\", \"Client\":\"%s\", \"User\":\"%s\", \"MAX_PACKET_SIZE\":%d, \"KEEPALIVE\":%d}}"), sysCfg.mqtt_host, sysCfg.mqtt_port, sysCfg.mqtt_client, MQTTClient, sysCfg.mqtt_user, MQTT_MAX_PACKET_SIZE, MQTT_KEEPALIVE); mqtt_publish_topic_P(option, PSTR("STATUS6"), svalue); } - if ((payload == 0) || (payload == 7)) { + if ((0 == payload) || (7 == payload)) { snprintf_P(svalue, sizeof(svalue), PSTR("{\"StatusTIM\":{\"UTC\":\"%s\", \"Local\":\"%s\", \"StartDST\":\"%s\", \"EndDST\":\"%s\", \"Timezone\":%d}}"), rtc_time(0).c_str(), rtc_time(1).c_str(), rtc_time(2).c_str(), rtc_time(3).c_str(), sysCfg.timezone); mqtt_publish_topic_P(option, PSTR("STATUS7"), svalue); } if (hlw_flg) { - if ((payload == 0) || (payload == 8)) { + if ((0 == payload) || (8 == payload)) { hlw_mqttStatus(svalue, sizeof(svalue)); mqtt_publish_topic_P(option, PSTR("STATUS8"), svalue); } - if ((payload == 0) || (payload == 9)) { + if ((0 == payload) || (9 == payload)) { snprintf_P(svalue, sizeof(svalue), PSTR("{\"StatusPTH\":{\"PowerLow\":%d, \"PowerHigh\":%d, \"VoltageLow\":%d, \"VoltageHigh\":%d, \"CurrentLow\":%d, \"CurrentHigh\":%d}}"), sysCfg.hlw_pmin, sysCfg.hlw_pmax, sysCfg.hlw_umin, sysCfg.hlw_umax, sysCfg.hlw_imin, sysCfg.hlw_imax); mqtt_publish_topic_P(option, PSTR("STATUS9"), svalue); } } - if ((payload == 0) || (payload == 10)) { + if ((0 == payload) || (10 == payload)) { uint8_t djson = 0; snprintf_P(svalue, sizeof(svalue), PSTR("{\"StatusSNS\":")); sensors_mqttPresent(svalue, sizeof(svalue), &djson); @@ -1472,7 +1625,7 @@ void publish_status(uint8_t payload) mqtt_publish_topic_P(option, PSTR("STATUS10"), svalue); } - if ((payload == 0) || (payload == 11)) { + if ((0 == payload) || (11 == payload)) { snprintf_P(svalue, sizeof(svalue), PSTR("{\"StatusSTS\":")); state_mqttPresent(svalue, sizeof(svalue)); snprintf_P(svalue, sizeof(svalue), PSTR("%s}"), svalue); @@ -1491,7 +1644,7 @@ void state_mqttPresent(char* svalue, uint16_t ssvalue) snprintf_P(svalue, ssvalue, PSTR("%s, \"Vcc\":%s"), svalue, stemp1); #endif for (byte i = 0; i < Maxdevice; i++) { - if (Maxdevice == 1) { // Legacy + if (1 == Maxdevice) { // Legacy snprintf_P(svalue, ssvalue, PSTR("%s, \"POWER\":"), svalue); } else { snprintf_P(svalue, ssvalue, PSTR("%s, \"POWER%d\":"), svalue, i +1); @@ -1507,7 +1660,7 @@ void sensors_mqttPresent(char* svalue, uint16_t ssvalue, uint8_t* djson) snprintf_P(svalue, ssvalue, PSTR("%s{\"Time\":\"%s\""), svalue, getDateTime().c_str()); for (byte i = 0; i < 4; i++) { if (pin[GPIO_SWT1 +i] < 99) { - boolean swm = ((sysCfg.switchmode[i] == FOLLOW_INV)||(sysCfg.switchmode[i] == PUSHBUTTON_INV)); + boolean swm = ((FOLLOW_INV == sysCfg.switchmode[i]) || (PUSHBUTTON_INV == sysCfg.switchmode[i])); snprintf_P(svalue, ssvalue, PSTR("%s, \"Switch%d\":\"%s\""), svalue, i +1, getStateText(swm ^ lastwallswitch[i])); *djson = 1; } @@ -1518,7 +1671,9 @@ void sensors_mqttPresent(char* svalue, uint16_t ssvalue, uint8_t* djson) *djson = 1; } #endif - if (sysCfg.module == SONOFF_SC) sc_mqttPresent(svalue, ssvalue, djson); + if (SONOFF_SC == sysCfg.module) { + sc_mqttPresent(svalue, ssvalue, djson); + } if (pin[GPIO_DSB] < 99) { #ifdef USE_DS18B20 dsb_mqttPresent(svalue, ssvalue, djson); @@ -1528,7 +1683,9 @@ void sensors_mqttPresent(char* svalue, uint16_t ssvalue, uint8_t* djson) #endif // USE_DS18x20 } #ifdef USE_DHT - if (dht_type) dht_mqttPresent(svalue, ssvalue, djson); + if (dht_type) { + dht_mqttPresent(svalue, ssvalue, djson); + } #endif // USE_DHT #ifdef USE_I2C if (i2c_flg) { @@ -1555,7 +1712,11 @@ void every_second() { char svalue[MESSZ]; - for (byte i = 0; i < MAX_PULSETIMERS; i++) if (pulse_timer[i] > 111) pulse_timer[i]--; + for (byte i = 0; i < MAX_PULSETIMERS; i++) { + if (pulse_timer[i] > 111) { + pulse_timer[i]--; + } + } if (seriallog_timer) { seriallog_timer--; @@ -1584,7 +1745,9 @@ void every_second() if (status_update_timer) { status_update_timer--; if (!status_update_timer) { - for (byte i = 1; i <= Maxdevice; i++) mqtt_publishPowerState(i); + for (byte i = 1; i <= Maxdevice; i++) { + mqtt_publishPowerState(i); + } } } @@ -1601,7 +1764,9 @@ void every_second() #endif // USE_DS18x20 } #ifdef USE_DHT - if (dht_type) dht_readPrep(); + if (dht_type) { + dht_readPrep(); + } #endif // USE_DHT #ifdef USE_I2C if (i2c_flg) { @@ -1630,46 +1795,65 @@ void every_second() uint8_t djson = 0; svalue[0] = '\0'; sensors_mqttPresent(svalue, sizeof(svalue), &djson); - if (djson) mqtt_publish_topic_P(1, PSTR("SENSOR"), svalue); + if (djson) { + mqtt_publish_topic_P(1, PSTR("SENSOR"), svalue); + } - if (hlw_flg) hlw_mqttPresent(); + if (hlw_flg) { + hlw_mqttPresent(); + } } } - if (hlw_flg) hlw_margin_chk(); + if (hlw_flg) { + hlw_margin_chk(); + } - if ((rtcTime.Minute == 2) && uptime_flg) { + if ((2 == rtcTime.Minute) && uptime_flg) { uptime_flg = false; uptime++; snprintf_P(svalue, sizeof(svalue), PSTR("{\"Time\":\"%s\", \"Uptime\":%d}"), getDateTime().c_str(), uptime); mqtt_publish_topic_P(1, PSTR("UPTIME"), svalue); } - if ((rtcTime.Minute == 3) && !uptime_flg) uptime_flg = true; + if ((3 == rtcTime.Minute) && !uptime_flg) { + uptime_flg = true; + } } void stateloop() { - uint8_t button = NOT_PRESSED, flag, switchflag, power_now; - char scmnd[20], log[LOGSZ], svalue[80]; // was MESSZ + uint8_t button = NOT_PRESSED; + uint8_t flag; + uint8_t switchflag; + uint8_t power_now; + char scmnd[20]; + char log[LOGSZ]; + char svalue[80]; // was MESSZ timerxs = millis() + (1000 / STATES); state++; - if (state == STATES) { // Every second + if (STATES == state) { // Every second state = 0; every_second(); } - if (mqtt_cmnd_publish) mqtt_cmnd_publish--; // Clean up + if (mqtt_cmnd_publish) { + mqtt_cmnd_publish--; // Clean up + } if (latching_relay_pulse) { latching_relay_pulse--; - if (!latching_relay_pulse) setLatchingRelay(0, 0); + if (!latching_relay_pulse) { + setLatchingRelay(0, 0); + } } for (byte i = 0; i < MAX_PULSETIMERS; i++) if ((pulse_timer[i] > 0) && (pulse_timer[i] < 112)) { pulse_timer[i]--; - if (!pulse_timer[i]) do_cmnd_power(i +1, 0); + if (!pulse_timer[i]) { + do_cmnd_power(i +1, 0); + } } if (blink_mask) { @@ -1687,26 +1871,34 @@ void stateloop() } } - if (sysCfg.module == SONOFF_LED) sl_animate(); + if (SONOFF_LED == sysCfg.module) { + sl_animate(); + } #ifdef USE_WS2812 - if (pin[GPIO_WS2812] < 99) ws2812_animate(); + if (pin[GPIO_WS2812] < 99) { + ws2812_animate(); + } #endif // USE_WS2812 - if ((sysCfg.module == SONOFF_DUAL) || (sysCfg.module == CH4)) { + if ((SONOFF_DUAL == sysCfg.module) || (CH4 == sysCfg.module)) { if (ButtonCode) { snprintf_P(log, sizeof(log), PSTR("APP: Button code %04X"), ButtonCode); addLog(LOG_LEVEL_DEBUG, log); button = PRESSED; - if (ButtonCode == 0xF500) holdcount = (STATES *4) -1; + if (0xF500 == ButtonCode) { + holdcount = (STATES *4) -1; + } ButtonCode = 0; } else { button = NOT_PRESSED; } } else { - if (pin[GPIO_KEY1] < 99) button = digitalRead(pin[GPIO_KEY1]); + if (pin[GPIO_KEY1] < 99) { + button = digitalRead(pin[GPIO_KEY1]); + } } - if ((button == PRESSED) && (lastbutton[0] == NOT_PRESSED)) { + if ((PRESSED == button) && (NOT_PRESSED == lastbutton[0])) { multipress = (multiwindow) ? multipress +1 : 1; snprintf_P(log, sizeof(log), PSTR("APP: Multipress %d"), multipress); addLog(LOG_LEVEL_DEBUG, log); @@ -1714,11 +1906,11 @@ void stateloop() multiwindow = STATES /2; // 1/2 second multi press window } lastbutton[0] = button; - if (button == NOT_PRESSED) { + if (NOT_PRESSED == button) { holdcount = 0; } else { holdcount++; - if (!sysCfg.button_restrict && (holdcount == (STATES *4))) { // 4 seconds button hold + if (!sysCfg.button_restrict && ((STATES *4) == holdcount)) { // 4 seconds button hold snprintf_P(scmnd, sizeof(scmnd), PSTR("reset 1")); multipress = 0; do_cmnd(scmnd); @@ -1728,15 +1920,15 @@ void stateloop() multiwindow--; } else { if ((!restartflag) && (!holdcount) && (multipress > 0) && (multipress < MAX_BUTTON_COMMANDS +3)) { - if ((sysCfg.module == SONOFF_DUAL) || (sysCfg.module == CH4)) { - flag = ((multipress == 1) || (multipress == 2)); + if ((SONOFF_DUAL == sysCfg.module) || (CH4 == sysCfg.module)) { + flag = ((1 == multipress) || (2 == multipress)); } else { - flag = (multipress == 1); + flag = (1 == multipress); } if (flag && sysCfg.mqtt_enabled && mqttClient.connected() && (strlen(sysCfg.button_topic) != 0) && strcmp(sysCfg.button_topic, "0")) { send_button_power(0, multipress, 2); // Execute command via MQTT using ButtonTopic to sync external clients } else { - if ((multipress == 1) || (multipress == 2)) { + if ((1 == multipress) || (2 == multipress)) { if (WIFI_State()) { // WPSconfig, Smartconfig or Wifimanager active restartflag = 1; } else { @@ -1753,46 +1945,54 @@ void stateloop() } } - for (byte i = 1; i < Maxdevice; i++) if (pin[GPIO_KEY1 +i] < 99) { - button = digitalRead(pin[GPIO_KEY1 +i]); - if ((button == PRESSED) && (lastbutton[i] == NOT_PRESSED)) { - if (sysCfg.mqtt_enabled && mqttClient.connected() && (strlen(sysCfg.button_topic) != 0) && strcmp(sysCfg.button_topic, "0")) { - send_button_power(0, i +1, 2); // Execute commend via MQTT - } else { - do_cmnd_power(i +1, 2); // Execute command internally - } - } - lastbutton[i] = button; - } - - for (byte i = 0; i < 4; i++) if (pin[GPIO_SWT1 +i] < 99) { - button = digitalRead(pin[GPIO_SWT1 +i]); - if (button != lastwallswitch[i]) { - switchflag = 3; - switch (sysCfg.switchmode[i]) { - case TOGGLE: - switchflag = 2; // Toggle - break; - case FOLLOW: - switchflag = button & 0x01; // Follow wall switch state - break; - case FOLLOW_INV: - switchflag = ~button & 0x01; // Follow inverted wall switch state - break; - case PUSHBUTTON: - if ((button == PRESSED) && (lastwallswitch[i] == NOT_PRESSED)) switchflag = 2; // Toggle with pushbutton to Gnd - break; - case PUSHBUTTON_INV: - if ((button == NOT_PRESSED) && (lastwallswitch[i] == PRESSED)) switchflag = 2; // Toggle with releasing pushbutton from Gnd - } - if (switchflag < 3) { - if (sysCfg.mqtt_enabled && mqttClient.connected() && (strlen(sysCfg.switch_topic) != 0) && strcmp(sysCfg.switch_topic, "0")) { - send_button_power(1, i +1, switchflag); // Execute commend via MQTT + for (byte i = 1; i < Maxdevice; i++) { + if (pin[GPIO_KEY1 +i] < 99) { + button = digitalRead(pin[GPIO_KEY1 +i]); + if ((PRESSED == button) && (NOT_PRESSED == lastbutton[i])) { + if (sysCfg.mqtt_enabled && mqttClient.connected() && (strlen(sysCfg.button_topic) != 0) && strcmp(sysCfg.button_topic, "0")) { + send_button_power(0, i +1, 2); // Execute commend via MQTT } else { - do_cmnd_power(i +1, switchflag); // Execute command internally (if i < Maxdevice) + do_cmnd_power(i +1, 2); // Execute command internally } } - lastwallswitch[i] = button; + lastbutton[i] = button; + } + } + + for (byte i = 0; i < 4; i++) { + if (pin[GPIO_SWT1 +i] < 99) { + button = digitalRead(pin[GPIO_SWT1 +i]); + if (button != lastwallswitch[i]) { + switchflag = 3; + switch (sysCfg.switchmode[i]) { + case TOGGLE: + switchflag = 2; // Toggle + break; + case FOLLOW: + switchflag = button & 0x01; // Follow wall switch state + break; + case FOLLOW_INV: + switchflag = ~button & 0x01; // Follow inverted wall switch state + break; + case PUSHBUTTON: + if ((PRESSED == button) && (NOT_PRESSED == lastwallswitch[i])) { + switchflag = 2; // Toggle with pushbutton to Gnd + } + break; + case PUSHBUTTON_INV: + if ((NOT_PRESSED == button) && (PRESSED == lastwallswitch[i])) { + switchflag = 2; // Toggle with releasing pushbutton from Gnd + } + } + if (switchflag < 3) { + if (sysCfg.mqtt_enabled && mqttClient.connected() && (strlen(sysCfg.switch_topic) != 0) && strcmp(sysCfg.switch_topic, "0")) { + send_button_power(1, i +1, switchflag); // Execute commend via MQTT + } else { + do_cmnd_power(i +1, switchflag); // Execute command internally (if i < Maxdevice) + } + } + lastwallswitch[i] = button; + } } } @@ -1808,10 +2008,14 @@ void stateloop() } if (!blinkstate) { blinks--; - if (blinks == 200) blinks = 0; + if (200 == blinks) { + blinks = 0; + } } } else { - if (sysCfg.ledstate &0x01) setLed(power); + if (sysCfg.ledstate &0x01) { + setLed(power); + } } } @@ -1819,14 +2023,15 @@ void stateloop() case (STATES/10)*2: if (otaflag) { otaflag--; - if (otaflag == 2){ + if (2 == otaflag) { otaretry = OTA_ATTEMPTS; ESPhttpUpdate.rebootOnUpdate(false); - sl_blank(1); } if (otaflag <= 0) { #ifdef USE_WEBSERVER - if (sysCfg.webserver) stopWebserver(); + if (sysCfg.webserver) { + stopWebserver(); + } #endif // USE_WEBSERVER otaflag = 92; otaok = 0; @@ -1834,11 +2039,13 @@ void stateloop() if (otaretry) { // snprintf_P(log, sizeof(log), PSTR("OTA: Attempt %d"), OTA_ATTEMPTS - otaretry); // addLog(LOG_LEVEL_INFO, log); - otaok = (ESPhttpUpdate.update(sysCfg.otaUrl) == HTTP_UPDATE_OK); - if (!otaok) otaflag = 2; + otaok = (HTTP_UPDATE_OK == ESPhttpUpdate.update(sysCfg.otaUrl)); + if (!otaok) { + otaflag = 2; + } } } - if (otaflag == 90) { // Allow MQTT to reconnect + if (90 == otaflag) { // Allow MQTT to reconnect otaflag = 0; if (otaok) { setModuleFlashMode(1); // QIO - ESP8266, DOUT - ESP8285 (Sonoff 4CH and Touch) @@ -1857,26 +2064,35 @@ void stateloop() if (savedatacounter <= 0) { if (sysCfg.savestate) { byte mask = 0xFF; - for (byte i = 0; i < MAX_PULSETIMERS; i++) - if ((sysCfg.pulsetime[i] > 0) && (sysCfg.pulsetime[i] < 30)) mask &= ~(1 << i); - if (!((sysCfg.power &mask) == (power &mask))) sysCfg.power = power; + for (byte i = 0; i < MAX_PULSETIMERS; i++) { + if ((sysCfg.pulsetime[i] > 0) && (sysCfg.pulsetime[i] < 30)) { + mask &= ~(1 << i); + } + } + if (!((sysCfg.power &mask) == (power &mask))) { + sysCfg.power = power; + } } CFG_Save(); savedatacounter = sysCfg.savedata; } } if (restartflag) { - if (restartflag == 211) { + if (211 == restartflag) { CFG_Default(); restartflag = 2; } - if (restartflag == 212) { + if (212 == restartflag) { CFG_Erase(); CFG_Default(); restartflag = 2; } - if (sysCfg.savestate) sysCfg.power = power; - if (hlw_flg) hlw_savestate(); + if (sysCfg.savestate) { + sysCfg.power = power; + } + if (hlw_flg) { + hlw_savestate(); + } CFG_Save(); restartflag--; if (restartflag <= 0) { @@ -1890,7 +2106,7 @@ void stateloop() wificheckflag = WIFI_RESTART; break; case (STATES/10)*8: - if (WiFi.status() == WL_CONNECTED) { + if (WL_CONNECTED == WiFi.status()) { if (sysCfg.mqtt_enabled) { if (!mqttClient.connected()) { if (!mqttcounter) { @@ -1926,10 +2142,12 @@ void serial() ButtonCode = (ButtonCode << 8) | SerialInByte; SerialInByte = 0; } else { - if (SerialInByte != 0xA1) ButtonCode = 0; // 0xA1 - End of Sonoff dual button code + if (SerialInByte != 0xA1) { + ButtonCode = 0; // 0xA1 - End of Sonoff dual button code + } } } - if (SerialInByte == 0xA0) { // 0xA0 - Start of Sonoff dual button code + if (0xA0 == SerialInByte) { // 0xA0 - Start of Sonoff dual button code SerialInByte = 0; ButtonCode = 0; Hexcode = 3; @@ -1976,16 +2194,24 @@ void GPIO_init() uint8_t mpin; mytmplt def_module; - if (!sysCfg.module || (sysCfg.module >= MAXMODULE)) sysCfg.module = MODULE; + if (!sysCfg.module || (sysCfg.module >= MAXMODULE)) { + sysCfg.module = MODULE; + } memcpy_P(&def_module, &modules[sysCfg.module], sizeof(def_module)); strlcpy(my_module.name, def_module.name, sizeof(my_module.name)); for (byte i = 0; i < MAX_GPIO_PIN; i++) { - if (sysCfg.my_module.gp.io[i] > GPIO_NONE) my_module.gp.io[i] = sysCfg.my_module.gp.io[i]; - if ((def_module.gp.io[i] > GPIO_NONE) && (def_module.gp.io[i] < GPIO_USER)) my_module.gp.io[i] = def_module.gp.io[i]; + if (sysCfg.my_module.gp.io[i] > GPIO_NONE) { + my_module.gp.io[i] = sysCfg.my_module.gp.io[i]; + } + if ((def_module.gp.io[i] > GPIO_NONE) && (def_module.gp.io[i] < GPIO_USER)) { + my_module.gp.io[i] = def_module.gp.io[i]; + } } - for (byte i = 0; i < GPIO_MAX; i++) pin[i] = 99; + for (byte i = 0; i < GPIO_MAX; i++) { + pin[i] = 99; + } for (byte i = 0; i < MAX_GPIO_PIN; i++) { mpin = my_module.gp.io[i]; @@ -2001,12 +2227,14 @@ void GPIO_init() led_inverted[mpin - GPIO_LED1_INV] = 1; mpin -= 4; } - else if (mpin == GPIO_DHT11) dht_type = mpin; - else if (mpin == GPIO_DHT21) { + else if (GPIO_DHT11 == mpin) { + dht_type = mpin; + } + else if (GPIO_DHT21 == mpin) { dht_type = mpin; mpin--; } - else if (mpin == GPIO_DHT22) { + else if (GPIO_DHT22 == mpin) { dht_type = mpin; mpin -= 2; } @@ -2014,25 +2242,27 @@ void GPIO_init() } } - if (pin[GPIO_TXD] == 2) Serial.set_tx(2); + if (2 == pin[GPIO_TXD]) { + Serial.set_tx(2); + } analogWriteRange(PWM_RANGE); // Default is 1023 (Arduino.h) analogWriteFreq(PWM_FREQ); // Default is 1000 (core_esp8266_wiring_pwm.c) Maxdevice = 1; - if (sysCfg.module == SONOFF_DUAL) { + if (SONOFF_DUAL == sysCfg.module) { Maxdevice = 2; Baudrate = 19200; } - else if (sysCfg.module == CH4) { + else if (CH4 == sysCfg.module) { Maxdevice = 4; Baudrate = 19200; } - else if (sysCfg.module == SONOFF_SC) { + else if (SONOFF_SC == sysCfg.module) { Maxdevice = 0; Baudrate = 19200; } - else if (sysCfg.module == SONOFF_LED) { + else if (SONOFF_LED == sysCfg.module) { pwm_idxoffset = 2; pin[GPIO_WS2812] = 99; // I do not allow both Sonoff Led AND WS2812 led if (!my_module.gp.io[4]) { @@ -2056,7 +2286,9 @@ void GPIO_init() pinMode(pin[GPIO_REL1 +i], OUTPUT); Maxdevice++; } - if (pin[GPIO_KEY1 +i] < 99) pinMode(pin[GPIO_KEY1 +i], INPUT_PULLUP); + if (pin[GPIO_KEY1 +i] < 99) { + pinMode(pin[GPIO_KEY1 +i], INPUT_PULLUP); + } } } for (byte i = 0; i < 4; i++) { @@ -2078,34 +2310,46 @@ void GPIO_init() } } - if (sysCfg.module == EXS_RELAY) { + if (EXS_RELAY == sysCfg.module) { setLatchingRelay(0,2); setLatchingRelay(1,2); } setLed(sysCfg.ledstate &8); hlw_flg = ((pin[GPIO_HLW_SEL] < 99) && (pin[GPIO_HLW_CF1] < 99) && (pin[GPIO_HLW_CF] < 99)); - if (hlw_flg) hlw_init(); + if (hlw_flg) { + hlw_init(); + } #ifdef USE_DHT - if (dht_type) dht_init(); + if (dht_type) { + dht_init(); + } #endif // USE_DHT #ifdef USE_DS18x20 - if (pin[GPIO_DSB] < 99) ds18x20_init(); + if (pin[GPIO_DSB] < 99) { + ds18x20_init(); + } #endif // USE_DS18x20 #ifdef USE_I2C i2c_flg = ((pin[GPIO_I2C_SCL] < 99) && (pin[GPIO_I2C_SDA] < 99)); - if (i2c_flg) Wire.begin(pin[GPIO_I2C_SDA], pin[GPIO_I2C_SCL]); + if (i2c_flg) { + Wire.begin(pin[GPIO_I2C_SDA], pin[GPIO_I2C_SCL]); + } #endif // USE_I2C #ifdef USE_WS2812 - if (pin[GPIO_WS2812] < 99) ws2812_init(); + if (pin[GPIO_WS2812] < 99) { + ws2812_init(); + } #endif // USE_WS2812 #ifdef USE_IR_REMOTE - if (pin[GPIO_IRSEND] < 99) ir_send_init(); + if (pin[GPIO_IRSEND] < 99) { + ir_send_init(); + } #endif // USE_IR_REMOTE } @@ -2166,31 +2410,41 @@ void setup() getClient(MQTTClient, sysCfg.mqtt_client, sizeof(MQTTClient)); - if (sysCfg.module == MOTOR) sysCfg.poweronstate = 1; // Needs always on else in limbo! + if (MOTOR == sysCfg.module) { + sysCfg.poweronstate = 1; // Needs always on else in limbo! + } if (ESP.getResetReason() == "Power on") { - if (sysCfg.poweronstate == 0) { // All off + if (0 == sysCfg.poweronstate) { // All off power = 0; setRelay(power); } - else if (sysCfg.poweronstate == 1) { // All on + else if (1 == sysCfg.poweronstate) { // All on power = ((0x00FF << Maxdevice) >> 8); setRelay(power); } - else if (sysCfg.poweronstate == 2) { // All saved state toggle + else if (2 == sysCfg.poweronstate) { // All saved state toggle power = (sysCfg.power & ((0x00FF << Maxdevice) >> 8)) ^ 0xFF; - if (sysCfg.savestate) setRelay(power); + if (sysCfg.savestate) { + setRelay(power); + } } - else if (sysCfg.poweronstate == 3) { // All saved state + else if (3 == sysCfg.poweronstate) { // All saved state power = sysCfg.power & ((0x00FF << Maxdevice) >> 8); - if (sysCfg.savestate) setRelay(power); + if (sysCfg.savestate) { + setRelay(power); + } } } else { power = sysCfg.power & ((0x00FF << Maxdevice) >> 8); - if (sysCfg.savestate) setRelay(power); + if (sysCfg.savestate) { + setRelay(power); + } } blink_powersave = power; - if (sysCfg.module == SONOFF_SC) sc_init(); + if (SONOFF_SC == sysCfg.module) { + sc_init(); + } rtc_init(); @@ -2208,12 +2462,20 @@ void loop() #endif // USE_WEBSERVER #ifdef USE_EMULATION - if (sysCfg.emulation) pollUDP(); + if (sysCfg.emulation) { + pollUDP(); + } #endif // USE_EMULATION - if (millis() >= timerxs) stateloop(); - if (sysCfg.mqtt_enabled) mqttClient.loop(); - if (Serial.available()) serial(); + if (millis() >= timerxs) { + stateloop(); + } + if (sysCfg.mqtt_enabled) { + mqttClient.loop(); + } + if (Serial.available()){ + serial(); + } // yield(); // yield == delay(0), delay contains yield, auto yield in loop delay(sleep); // https://github.com/esp8266/Arduino/issues/2021 diff --git a/sonoff/support.ino b/sonoff/support.ino index 5730146d9..37f7a0730 100644 --- a/sonoff/support.ino +++ b/sonoff/support.ino @@ -51,7 +51,7 @@ void osw_osWatch() snprintf_P(log, sizeof(log), PSTR("osWatch: FreeRam %d, rssi %d, last_run %d"), ESP.getFreeHeap(), WIFI_getRSSIasQuality(WiFi.RSSI()), last_run); addLog(LOG_LEVEL_DEBUG, log); #endif // DEBUG_THEO - if(last_run >= (OSWATCH_RESET_TIME * 1000)) { + if (last_run >= (OSWATCH_RESET_TIME * 1000)) { addLog_P(LOG_LEVEL_INFO, PSTR("osWatch: Warning, loop blocked. Restart now")); rtcMem.osw_flag = 1; RTC_Save(); @@ -131,7 +131,7 @@ Decoding 14 results 00:00:08 MQTT: tele/sonoff/INFO3 = {"Started":"Fatal exception:28 flag:2 (EXCEPTION) epc1:0x4000bf64 epc2:0x00000000 epc3:0x00000000 excvaddr:0x00000007 depc:0x00000000"} */ - if (type == 1) { + if (1 == type) { char svalue[10]; snprintf_P(svalue, sizeof(svalue), PSTR("%s"), 7); // Exception 28 as number in string (7 in excvaddr) } @@ -145,7 +145,7 @@ Decoding 14 results 14:51:42 osWatch: FreeRam 25360, rssi 62, last_run 38771 14:51:42 osWatch: Warning, loop blocked. Restart now */ - if (type == 2) { + if (2 == type) { while(1) delay(1000); // this will trigger the os watch } } @@ -155,23 +155,6 @@ Decoding 14 results * General \*********************************************************************************************/ -boolean parseIPx(char* str, uint16_t len, uint32_t* addr) -{ - uint8_t *part = (uint8_t *)addr; - byte i; - - if (!len) return false; - *addr = 0; - for (i = 0; i <= len; i++) if (*(str +i) == ',') *(str +i) = '.'; - for (i = 0; i < 4; i++) { - part[i] = strtoul(str, NULL, 10); // Convert byte - str = strchr(str, '.'); - if (str == NULL || *str == '\0') break; // No more separators, exit - str++; // Point to next character after separator - } - return (i == 3); -} - boolean parseIP(uint32_t* addr, const char* str) { uint8_t *part = (uint8_t*)addr; @@ -181,10 +164,12 @@ boolean parseIP(uint32_t* addr, const char* str) for (i = 0; i < 4; i++) { part[i] = strtoul(str, NULL, 10); // Convert byte str = strchr(str, '.'); - if (str == NULL || *str == '\0') break; // No more separators, exit + if (str == NULL || *str == '\0') { + break; // No more separators, exit + } str++; // Point to next character after separator } - return (i == 3); + return (3 == i); } /*********************************************************************************************\ @@ -196,7 +181,12 @@ boolean parseIP(uint32_t* addr, const char* str) #define WIFI_CHECK_SEC 20 // seconds #define WIFI_RETRY_SEC 30 // seconds -uint8_t _wificounter, _wifiretry, _wifistatus, _wpsresult, _wificonfigflag = 0, _wifiConfigCounter = 0; +uint8_t _wificounter; +uint8_t _wifiretry; +uint8_t _wifistatus; +uint8_t _wpsresult; +uint8_t _wificonfigflag = 0; +uint8_t _wifiConfigCounter = 0; int WIFI_getRSSIasQuality(int RSSI) { @@ -214,7 +204,9 @@ int WIFI_getRSSIasQuality(int RSSI) boolean WIFI_configCounter() { - if (_wifiConfigCounter) _wifiConfigCounter = WIFI_MANAGER_SEC; + if (_wifiConfigCounter) { + _wifiConfigCounter = WIFI_MANAGER_SEC; + } return (_wifiConfigCounter); } @@ -239,7 +231,7 @@ void WIFI_wps_status_cb(wps_cb_status status) */ _wpsresult = status; - if (_wpsresult == WPS_CB_ST_SUCCESS) { + if (WPS_CB_ST_SUCCESS == _wpsresult) { wifi_wps_disable(); } else { snprintf_P(log, sizeof(log), PSTR("WPSconfig: FAILED with status %d"), _wpsresult); @@ -256,17 +248,27 @@ boolean WIFI_WPSConfigDone(void) boolean WIFI_beginWPSConfig(void) { _wpsresult = 99; - if (!wifi_wps_disable()) return false; - if (!wifi_wps_enable(WPS_TYPE_PBC)) return false; // so far only WPS_TYPE_PBC is supported (SDK 2.0.0) - if (!wifi_set_wps_cb((wps_st_cb_t) &WIFI_wps_status_cb)) return false; - if (!wifi_wps_start()) return false; + if (!wifi_wps_disable()) { + return false; + } + if (!wifi_wps_enable(WPS_TYPE_PBC)) { + return false; // so far only WPS_TYPE_PBC is supported (SDK 2.0.0) + } + if (!wifi_set_wps_cb((wps_st_cb_t) &WIFI_wps_status_cb)) { + return false; + } + if (!wifi_wps_start()) { + return false; + } return true; } void WIFI_config(uint8_t type) { if (!_wificonfigflag) { - if (type == WIFI_RETRY) return; + if (WIFI_RETRY == type) { + return; + } #ifdef USE_EMULATION UDP_Disconnect(); #endif // USE_EMULATION @@ -275,14 +277,14 @@ void WIFI_config(uint8_t type) _wifiConfigCounter = WIFI_CONFIG_SEC; // Allow up to WIFI_CONFIG_SECS seconds for phone to provide ssid/pswd _wificounter = _wifiConfigCounter +5; blinks = 1999; - if (_wificonfigflag == WIFI_RESTART) { + if (WIFI_RESTART == _wificonfigflag) { restartflag = 2; } - else if (_wificonfigflag == WIFI_SMARTCONFIG) { + else if (WIFI_SMARTCONFIG == _wificonfigflag) { addLog_P(LOG_LEVEL_INFO, PSTR("Smartconfig: Active for 1 minute")); WiFi.beginSmartConfig(); } - else if (_wificonfigflag == WIFI_WPSCONFIG) { + else if (WIFI_WPSCONFIG == _wificonfigflag) { if (WIFI_beginWPSConfig()) { addLog_P(LOG_LEVEL_INFO, PSTR("WPSconfig: Active for 1 minute")); } else { @@ -291,7 +293,7 @@ void WIFI_config(uint8_t type) } } #ifdef USE_WEBSERVER - else if (_wificonfigflag == WIFI_MANAGER) { + else if (WIFI_MANAGER == _wificonfigflag) { addLog_P(LOG_LEVEL_INFO, PSTR("Wifimanager: Active for 1 minute")); beginWifiManager(); } @@ -313,11 +315,15 @@ void WIFI_begin(uint8_t flag) } WiFi.disconnect(); WiFi.mode(WIFI_STA); // Disable AP mode -// if (sysCfg.sleep) wifi_set_sleep_type(LIGHT_SLEEP_T); // Allow light sleep during idle times - if (sysCfg.sleep) WiFi.setSleepMode(WIFI_LIGHT_SLEEP); // Allow light sleep during idle times -// WiFi.setSleepMode(WIFI_LIGHT_SLEEP); // Allow light sleep during idle times -// if (WiFi.getPhyMode() != WIFI_PHY_MODE_11N) WiFi.setPhyMode(WIFI_PHY_MODE_11N); - if (!WiFi.getAutoConnect()) WiFi.setAutoConnect(true); + if (sysCfg.sleep) { + WiFi.setSleepMode(WIFI_LIGHT_SLEEP); // Allow light sleep during idle times + } +// if (WiFi.getPhyMode() != WIFI_PHY_MODE_11N) { +// WiFi.setPhyMode(WIFI_PHY_MODE_11N); +// } + if (!WiFi.getAutoConnect()) { + WiFi.setAutoConnect(true); + } // WiFi.setAutoReconnect(true); switch (flag) { case 0: // AP1 @@ -327,9 +333,12 @@ void WIFI_begin(uint8_t flag) case 2: // Toggle sysCfg.sta_active ^= 1; } // 3: Current AP - if (strlen(sysCfg.sta_ssid[1]) == 0) sysCfg.sta_active = 0; - if (sysCfg.ip_address[0]) + if (0 == strlen(sysCfg.sta_ssid[1])) { + sysCfg.sta_active = 0; + } + if (sysCfg.ip_address[0]) { WiFi.config(sysCfg.ip_address[0], sysCfg.ip_address[1], sysCfg.ip_address[2], sysCfg.ip_address[3]); // Set static IP + } WiFi.hostname(Hostname); WiFi.begin(sysCfg.sta_ssid[sysCfg.sta_active], sysCfg.sta_pwd[sysCfg.sta_active]); snprintf_P(log, sizeof(log), PSTR("Wifi: Connecting to AP%d %s in mode 11%c as %s..."), @@ -339,7 +348,7 @@ void WIFI_begin(uint8_t flag) void WIFI_check_ip() { - if ((WiFi.status() == WL_CONNECTED) && (static_cast(WiFi.localIP()) != 0)) { + if ((WL_CONNECTED == WiFi.status()) && (static_cast(WiFi.localIP()) != 0)) { _wificounter = WIFI_CHECK_SEC; _wifiretry = WIFI_RETRY_SEC; addLog_P((_wifistatus != WL_CONNECTED) ? LOG_LEVEL_INFO : LOG_LEVEL_DEBUG_MORE, PSTR("Wifi: Connected")); @@ -360,24 +369,36 @@ void WIFI_check_ip() break; case WL_NO_SSID_AVAIL: addLog_P(LOG_LEVEL_INFO, PSTR("Wifi: Connect failed as AP cannot be reached")); - if (_wifiretry > (WIFI_RETRY_SEC / 2)) _wifiretry = WIFI_RETRY_SEC / 2; - else if (_wifiretry) _wifiretry = 0; + if (_wifiretry > (WIFI_RETRY_SEC / 2)) { + _wifiretry = WIFI_RETRY_SEC / 2; + } + else if (_wifiretry) { + _wifiretry = 0; + } break; case WL_CONNECT_FAILED: addLog_P(LOG_LEVEL_INFO, PSTR("Wifi: Connect failed with AP incorrect password")); - if (_wifiretry > (WIFI_RETRY_SEC / 2)) _wifiretry = WIFI_RETRY_SEC / 2; - else if (_wifiretry) _wifiretry = 0; + if (_wifiretry > (WIFI_RETRY_SEC / 2)) { + _wifiretry = WIFI_RETRY_SEC / 2; + } + else if (_wifiretry) { + _wifiretry = 0; + } break; default: // WL_IDLE_STATUS and WL_DISCONNECTED - if (!_wifiretry || (_wifiretry == (WIFI_RETRY_SEC / 2))) { + if (!_wifiretry || ((WIFI_RETRY_SEC / 2) == _wifiretry)) { addLog_P(LOG_LEVEL_INFO, PSTR("Wifi: Connect failed with AP timeout")); } else { addLog_P(LOG_LEVEL_DEBUG, PSTR("Wifi: Attempting connection...")); } } if (_wifiretry) { - if (_wifiretry == WIFI_RETRY_SEC) WIFI_begin(3); // Select default SSID - if (_wifiretry == (WIFI_RETRY_SEC / 2)) WIFI_begin(2); // Select alternate SSID + if (WIFI_RETRY_SEC == _wifiretry) { + WIFI_begin(3); // Select default SSID + } + if ((WIFI_RETRY_SEC / 2) == _wifiretry) { + WIFI_begin(2); // Select alternate SSID + } _wificounter = 1; _wifiretry--; } else { @@ -404,18 +425,28 @@ void WIFI_Check(uint8_t param) _wifiConfigCounter--; _wificounter = _wifiConfigCounter +5; if (_wifiConfigCounter) { - if ((_wificonfigflag == WIFI_SMARTCONFIG) && WiFi.smartConfigDone()) _wifiConfigCounter = 0; - if ((_wificonfigflag == WIFI_WPSCONFIG) && WIFI_WPSConfigDone()) _wifiConfigCounter = 0; + if ((WIFI_SMARTCONFIG == _wificonfigflag) && WiFi.smartConfigDone()) { + _wifiConfigCounter = 0; + } + if ((WIFI_WPSCONFIG == _wificonfigflag) && WIFI_WPSConfigDone()) { + _wifiConfigCounter = 0; + } if (!_wifiConfigCounter) { - if (strlen(WiFi.SSID().c_str())) strlcpy(sysCfg.sta_ssid[0], WiFi.SSID().c_str(), sizeof(sysCfg.sta_ssid[0])); - if (strlen(WiFi.psk().c_str())) strlcpy(sysCfg.sta_pwd[0], WiFi.psk().c_str(), sizeof(sysCfg.sta_pwd[0])); + if (strlen(WiFi.SSID().c_str())) { + strlcpy(sysCfg.sta_ssid[0], WiFi.SSID().c_str(), sizeof(sysCfg.sta_ssid[0])); + } + if (strlen(WiFi.psk().c_str())) { + strlcpy(sysCfg.sta_pwd[0], WiFi.psk().c_str(), sizeof(sysCfg.sta_pwd[0])); + } sysCfg.sta_active = 0; snprintf_P(log, sizeof(log), PSTR("Wificonfig: SSID1 %s and Password1 %s"), sysCfg.sta_ssid[0], sysCfg.sta_pwd[0]); addLog(LOG_LEVEL_INFO, log); } } if (!_wifiConfigCounter) { - if (_wificonfigflag == WIFI_SMARTCONFIG) WiFi.stopSmartConfig(); + if (WIFI_SMARTCONFIG == _wificonfigflag) { + WiFi.stopSmartConfig(); + } restartflag = 2; } } else { @@ -424,7 +455,7 @@ void WIFI_Check(uint8_t param) _wificounter = WIFI_CHECK_SEC; WIFI_check_ip(); } - if ((WiFi.status() == WL_CONNECTED) && (static_cast(WiFi.localIP()) != 0) && !_wificonfigflag) { + if ((WL_CONNECTED == WiFi.status()) && (static_cast(WiFi.localIP()) != 0) && !_wificonfigflag) { #ifdef USE_DISCOVERY if (!mDNSbegun) { mDNSbegun = MDNS.begin(Hostname); @@ -444,7 +475,9 @@ void WIFI_Check(uint8_t param) stopWebserver(); } #ifdef USE_EMULATION - if (sysCfg.emulation) UDP_Connect(); + if (sysCfg.emulation) { + UDP_Connect(); + } #endif // USE_EMULATION #endif // USE_WEBSERVER } else { @@ -461,8 +494,12 @@ int WIFI_State() { int state; - if ((WiFi.status() == WL_CONNECTED) && (static_cast(WiFi.localIP()) != 0)) state = WIFI_RESTART; - if (_wificonfigflag) state = _wificonfigflag; + if ((WL_CONNECTED == WiFi.status()) && (static_cast(WiFi.localIP()) != 0)) { + state = WIFI_RESTART; + } + if (_wificonfigflag) { + state = _wificonfigflag; + } return state; } @@ -482,10 +519,13 @@ void WIFI_Connect() #ifdef MQTT_HOST_DISCOVERY boolean mdns_discoverMQTTServer() { - char log[LOGSZ], ip_str[20]; + char log[LOGSZ]; + char ip_str[20]; int n; - if (!mDNSbegun) return false; + if (!mDNSbegun) { + return false; + } n = MDNS.queryService("mqtt", "tcp"); // Search for mqtt service @@ -536,13 +576,14 @@ int32_t i2c_read(uint8_t addr, uint8_t reg, uint8_t size) do { Wire.beginTransmission(addr); // start transmission to device Wire.write(reg); // sends register address to read from - if (Wire.endTransmission(false) == 0) { // Try to become I2C Master, send data and collect bytes, keep master status for next request... + if (0 == Wire.endTransmission(false)) { // Try to become I2C Master, send data and collect bytes, keep master status for next request... Wire.requestFrom((int)addr, (int)size); // send data n-bytes read - if (Wire.available() == size) + if (Wire.available() == size) { for(byte i = 0; i < size; i++) { data <<= 8; data |= Wire.read(); // receive DATA } + } } x++; } while (Wire.endTransmission(true) != 0 && x <= I2C_RETRY_COUNTER); // end transmission @@ -594,19 +635,23 @@ void i2c_write8(uint8_t addr, uint8_t reg, uint8_t val) void i2c_scan(char *devs, unsigned int devs_len) { - byte error, address, any = 0; + byte error; + byte address; + byte any = 0; char tstr[10]; snprintf_P(devs, devs_len, PSTR("{\"I2Cscan\":\"Device(s) found at")); for (address = 1; address <= 127; address++) { Wire.beginTransmission(address); error = Wire.endTransmission(); - if (error == 0) { + if (0 == error) { snprintf_P(tstr, sizeof(tstr), PSTR(" 0x%2x"), address); strncat(devs, tstr, devs_len); any = 1; } - else if (error == 4) snprintf_P(devs, devs_len, PSTR("{\"I2Cscan\":\"Unknown error at 0x%2x\"}"), address); + else if (4 == error) { + snprintf_P(devs, devs_len, PSTR("{\"I2Cscan\":\"Unknown error at 0x%2x\"}"), address); + } } if (any) { strncat(devs, "\"}", devs_len); @@ -637,15 +682,24 @@ Ticker tickerRTC; static const uint8_t monthDays[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // API starts months from 1, this array starts from 0 static const char monthNames[] = "JanFebMarAprMayJunJulAugSepOctNovDec"; -uint32_t utctime = 0, loctime = 0, dsttime = 0, stdtime = 0, ntptime = 0, midnight = 1451602800; +uint32_t utctime = 0; +uint32_t loctime = 0; +uint32_t dsttime = 0; +uint32_t stdtime = 0; +uint32_t ntptime = 0; +uint32_t midnight = 1451602800; String getBuildDateTime() { // "2017-03-07T11:08:02" char bdt[21]; - char *str, *p, *smonth; + char *str; + char *p; + char *smonth; char mdate[] = __DATE__; // "Mar 7 2017" - int month, day, year; + int month; + int day; + int year; // sscanf(mdate, "%s %d %d", bdt, &day, &year); // Not implemented in 2.3.0 and probably too many code byte i = 0; @@ -682,7 +736,9 @@ void breakTime(uint32_t timeInput, TIME_T &tm) // this is a more compact version of the C library localtime function // note that year is offset from 1970 !!! - uint8_t year, month, monthLength; + uint8_t year; + uint8_t month; + uint8_t monthLength; uint32_t time; unsigned long days; @@ -710,7 +766,7 @@ void breakTime(uint32_t timeInput, TIME_T &tm) month = 0; monthLength = 0; for (month = 0; month < 12; month++) { - if (month == 1) { // february + if (1 == month) { // february if (LEAP_YEAR(year)) { monthLength = 29; } else { @@ -750,7 +806,7 @@ uint32_t makeTime(TIME_T &tm) // add days for this year, months start from 1 for (i = 1; i < tm.Month; i++) { - if ((i == 2) && LEAP_YEAR(tm.Year)) { + if ((2 == i) && LEAP_YEAR(tm.Year)) { seconds += SECS_PER_DAY * 29; } else { seconds += SECS_PER_DAY * monthDays[i-1]; // monthDay array starts from 0 @@ -767,16 +823,17 @@ uint32_t toTime_t(TimeChangeRule r, int yr) { TIME_T tm; uint32_t t; - uint8_t m, w; // temp copies of r.month and r.week + uint8_t m; + uint8_t w; // temp copies of r.month and r.week m = r.month; w = r.week; - if (w == 0) { // Last week = 0 - if (++m > 12) { // for "Last", go to the next month - m = 1; - yr++; - } - w = 1; // and treat as first week of next month, subtract 7 days later + if (0 == w) { // Last week = 0 + if (++m > 12) { // for "Last", go to the next month + m = 1; + yr++; + } + w = 1; // and treat as first week of next month, subtract 7 days later } tm.Hour = r.hour; @@ -788,7 +845,9 @@ uint32_t toTime_t(TimeChangeRule r, int yr) t = makeTime(tm); // First day of the month, or first day of next month for "Last" rules breakTime(t, tm); t += (7 * (w - 1) + (r.dow - tm.Wday + 7) % 7) * SECS_PER_DAY; - if (r.week == 0) t -= 7 * SECS_PER_DAY; //back up a week if this is a "Last" rule + if (0 == r.week) { + t -= 7 * SECS_PER_DAY; //back up a week if this is a "Last" rule + } return t; } @@ -797,9 +856,9 @@ String rtc_time(int type) char stime[25]; // Skip newline uint32_t time = utctime; - if (type == 1) time = loctime; - if (type == 2) time = dsttime; - if (type == 3) time = stdtime; + if (1 == type) time = loctime; + if (2 == type) time = dsttime; + if (3 == type) time = stdtime; snprintf_P(stime, sizeof(stime), PSTR("%s"), sntp_get_real_time(time)); return String(stime); } @@ -818,16 +877,17 @@ void rtc_second() { char log[LOGSZ]; byte ntpsync; - uint32_t stdoffset, dstoffset; + uint32_t stdoffset; + uint32_t dstoffset; TIME_T tmpTime; ntpsync = 0; if (rtcTime.Year < 2016) { - if (WiFi.status() == WL_CONNECTED) { + if (WL_CONNECTED == WiFi.status()) { ntpsync = 1; // Initial NTP sync } } else { - if ((rtcTime.Minute == 1) && (rtcTime.Second == 1)) { + if ((1 == rtcTime.Minute) && (1 == rtcTime.Second)) { ntpsync = 1; // Hourly NTP sync at xx:01:01 } } @@ -850,7 +910,7 @@ void rtc_second() utctime++; loctime = utctime; if (loctime > 1451602800) { // 2016-01-01 - if (sysCfg.timezone == 99) { + if (99 == sysCfg.timezone) { dstoffset = myDST.offset * SECS_PER_MIN; stdoffset = mySTD.offset * SECS_PER_MIN; if ((utctime >= (dsttime - stdoffset)) && (utctime < (stdtime - dstoffset))) { @@ -913,11 +973,14 @@ void addLog(byte loglevel, const char *line) if (sysCfg.webserver && (loglevel <= sysCfg.weblog_level)) { Log[logidx] = String(mxtime) + " " + String(line); logidx++; - if (logidx > MAX_LOG_LINES -1) logidx = 0; + if (logidx > MAX_LOG_LINES -1) { + logidx = 0; + } } #endif // USE_WEBSERVER -// if (sysCfg.emulation) return; // Disable syslog (UDP) when emulation using UDP is selected - if ((WiFi.status() == WL_CONNECTED) && (loglevel <= syslog_level)) syslog(line); + if ((WL_CONNECTED == WiFi.status()) && (loglevel <= syslog_level)) { + syslog(line); + } } void addLog_P(byte loglevel, const char *formatP) diff --git a/sonoff/webserver.ino b/sonoff/webserver.ino index aaf9f5dcc..f1011fa2d 100644 --- a/sonoff/webserver.ino +++ b/sonoff/webserver.ino @@ -286,7 +286,10 @@ ESP8266WebServer *webServer; boolean _removeDuplicateAPs = true; int _minimumQuality = -1; -uint8_t _httpflag = HTTP_OFF, _uploaderror = 0, _uploadfiletype, _colcount; +uint8_t _httpflag = HTTP_OFF; +uint8_t _uploaderror = 0; +uint8_t _uploadfiletype; +uint8_t _colcount; void startWebserver(int type, IPAddress ipweb) { @@ -294,7 +297,7 @@ void startWebserver(int type, IPAddress ipweb) if (!_httpflag) { if (!webServer) { - webServer = new ESP8266WebServer((type==HTTP_MANAGER)?80:WEB_PORT); + webServer = new ESP8266WebServer((HTTP_MANAGER==type)?80:WEB_PORT); webServer->on("/", handleRoot); webServer->on("/cn", handleConfig); webServer->on("/md", handleModule); @@ -323,12 +326,12 @@ void startWebserver(int type, IPAddress ipweb) webServer->on("/rb", handleRestart); webServer->on("/fwlink", handleRoot); // Microsoft captive portal. Maybe not needed. Might be handled by notFound handler. #ifdef USE_EMULATION - if (sysCfg.emulation == EMUL_WEMO) { + if (EMUL_WEMO == sysCfg.emulation) { webServer->on("/upnp/control/basicevent1", HTTP_POST, handleUPnPevent); webServer->on("/eventservice.xml", handleUPnPservice); webServer->on("/setup.xml", handleUPnPsetupWemo); } - if (sysCfg.emulation == EMUL_HUE) { + if (EMUL_HUE == sysCfg.emulation) { webServer->on("/description.xml", handleUPnPsetupHue); } #endif // USE_EMULATION @@ -357,7 +360,7 @@ void stopWebserver() void beginWifiManager() { // setup AP - if ((WiFi.status() == WL_CONNECTED) && (static_cast(WiFi.localIP()) != 0)) { + if ((WL_CONNECTED == WiFi.status()) && (static_cast(WiFi.localIP()) != 0)) { WiFi.mode(WIFI_AP_STA); addLog_P(LOG_LEVEL_DEBUG, PSTR("Wifimanager: Set AccessPoint and keep Station")); } else { @@ -379,18 +382,22 @@ void beginWifiManager() void pollDnsWeb() { - if (dnsServer) dnsServer->processNextRequest(); - if (webServer) webServer->handleClient(); + if (dnsServer) { + dnsServer->processNextRequest(); + } + if (webServer) { + webServer->handleClient(); + } } void showPage(String &page) { - if((_httpflag == HTTP_ADMIN) && (sysCfg.web_password[0] != 0) && !webServer->authenticate(WEB_USERNAME, sysCfg.web_password)) { + if((HTTP_ADMIN == _httpflag) && (sysCfg.web_password[0] != 0) && !webServer->authenticate(WEB_USERNAME, sysCfg.web_password)) { return webServer->requestAuthentication(); } page.replace("{ha}", my_module.name); page.replace("{h}", sysCfg.friendlyname[0]); - if (_httpflag == HTTP_MANAGER) { + if (HTTP_MANAGER == _httpflag) { if (WIFI_configCounter()) { page.replace("", ""); page += FPSTR(HTTP_COUNTER); @@ -412,7 +419,7 @@ void handleRoot() return; } - if (_httpflag == HTTP_MANAGER) { + if (HTTP_MANAGER == _httpflag) { handleWifi0(); } else { char stemp[10], line[100]; @@ -422,7 +429,7 @@ void handleRoot() page += F("
"); if (Maxdevice) { - if (sysCfg.module == SONOFF_LED) { + if (SONOFF_LED == sysCfg.module) { snprintf_P(line, sizeof(line), PSTR(""), sysCfg.led_dimmer[0]); page += line; @@ -438,7 +445,7 @@ void handleRoot() page += F(""); } - if (_httpflag == HTTP_ADMIN) { + if (HTTP_ADMIN == _httpflag) { page += FPSTR(HTTP_BTN_MENU1); page += FPSTR(HTTP_BTN_RSTRT); } @@ -450,23 +457,35 @@ void handleAjax2() { char svalue[16]; - if (strlen(webServer->arg("o").c_str())) do_cmnd_power(atoi(webServer->arg("o").c_str()), 2); + if (strlen(webServer->arg("o").c_str())) { + do_cmnd_power(atoi(webServer->arg("o").c_str()), 2); + } if (strlen(webServer->arg("d").c_str())) { snprintf_P(svalue, sizeof(svalue), PSTR("dimmer %s"), webServer->arg("d").c_str()); do_cmnd(svalue); } String tpage = ""; - if (hlw_flg) tpage += hlw_webPresent(); - if (sysCfg.module == SONOFF_SC) tpage += sc_webPresent(); + if (hlw_flg) { + tpage += hlw_webPresent(); + } + if (SONOFF_SC == sysCfg.module) { + tpage += sc_webPresent(); + } #ifdef USE_DS18B20 - if (pin[GPIO_DSB] < 99) tpage += dsb_webPresent(); + if (pin[GPIO_DSB] < 99) { + tpage += dsb_webPresent(); + } #endif // USE_DS18B20 #ifdef USE_DS18x20 - if (pin[GPIO_DSB] < 99) tpage += ds18x20_webPresent(); + if (pin[GPIO_DSB] < 99) { + tpage += ds18x20_webPresent(); + } #endif // USE_DS18x20 #ifdef USE_DHT - if (dht_type) tpage += dht_webPresent(); + if (dht_type) { + tpage += dht_webPresent(); + } #endif // USE_DHT #ifdef USE_I2C if (i2c_flg) { @@ -504,7 +523,7 @@ void handleAjax2() } /* * Will interrupt user action when selected - if (sysCfg.module == SONOFF_LED) { + if (SONOFF_LED == sysCfg.module) { snprintf_P(line, sizeof(line), PSTR(""), sysCfg.led_dimmer[0]); page += line; @@ -518,20 +537,26 @@ void handleAjax2() boolean httpUser() { - boolean status = (_httpflag == HTTP_USER); - if (status) handleRoot(); + boolean status = (HTTP_USER == _httpflag); + if (status) { + handleRoot(); + } return status; } void handleConfig() { - if (httpUser()) return; + if (httpUser()) { + return; + } addLog_P(LOG_LEVEL_DEBUG, PSTR("HTTP: Handle config")); String page = FPSTR(HTTP_HEAD); page.replace("{v}", "Configuration"); page += FPSTR(HTTP_BTN_MENU2); - if (sysCfg.mqtt_enabled) page += FPSTR(HTTP_BTN_MENU3); + if (sysCfg.mqtt_enabled) { + page += FPSTR(HTTP_BTN_MENU3); + } page += FPSTR(HTTP_BTN_MENU4); page += FPSTR(HTTP_BTN_MAIN); showPage(page); @@ -541,29 +566,49 @@ boolean inModule(byte val, uint8_t *arr) { int offset = 0; - if (!val) return false; // None + if (!val) { + return false; // None + } #ifndef USE_I2C - if (val == GPIO_I2C_SCL) return true; - if (val == GPIO_I2C_SDA) return true; + if (GPIO_I2C_SCL == val) { + return true; + } + if (GPIO_I2C_SDA == val) { + return true; + } #endif #ifndef USE_WS2812 - if (val == GPIO_WS2812) return true; + if (GPIO_WS2812 == val) { + return true; + } #endif #ifndef USE_IR_REMOTE - if (val == GPIO_IRSEND) return true; + if (GPIO_IRSEND == val) { + return true; + } #endif - if (((val >= GPIO_REL1) && (val <= GPIO_REL4)) || ((val >= GPIO_LED1) && (val <= GPIO_LED4))) offset = 4; - if (((val >= GPIO_REL1_INV) && (val <= GPIO_REL4_INV)) || ((val >= GPIO_LED1_INV) && (val <= GPIO_LED4_INV))) offset = -4; + if (((val >= GPIO_REL1) && (val <= GPIO_REL4)) || ((val >= GPIO_LED1) && (val <= GPIO_LED4))) { + offset = 4; + } + if (((val >= GPIO_REL1_INV) && (val <= GPIO_REL4_INV)) || ((val >= GPIO_LED1_INV) && (val <= GPIO_LED4_INV))) { + offset = -4; + } for (byte i = 0; i < MAX_GPIO_PIN; i++) { - if (arr[i] == val) return true; - if (arr[i] == val + offset) return true; + if (arr[i] == val) { + return true; + } + if (arr[i] == val + offset) { + return true; + } } return false; } void handleModule() { - if (httpUser()) return; + if (httpUser()) { + return; + } char stemp[20], line[128]; addLog_P(LOG_LEVEL_DEBUG, PSTR("HTTP: Handle Module config")); @@ -596,9 +641,9 @@ void handleModule() } func += F("\";os=o0.replace(/-1/g,\"