├── .gitignore ├── LICENSE ├── README.md ├── platformio.ini ├── screenshots ├── screenshot_01.png ├── screenshot_02.png ├── screenshot_03.png ├── screenshot_04.png └── screenshot_05.png └── src └── main.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | .pio 2 | .platformio 3 | .vscode/.browse.c_cpp.db* 4 | .vscode/c_cpp_properties.json 5 | .vscode/launch.json 6 | .vscode/ipch 7 | .vscode/extensions.json 8 | .DS_Store 9 | .vscode/settings.json 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Energy2Shelly_ESP 2 | 3 | ### Getting started 4 | This is a Shelly Pro 3EM Emulator running on ESP8266 or ESP32 using various input sources for power data.
5 | This can be used for zero feed-in with Hoymiles MS-A2 and Marstek Venus (testers needed!). 6 | 7 | Kudos to @sdeigms excellent work at https://github.com/sdeigm/uni-meter which made this port easily possible.
8 | SMA Multicast code is based on https://www.mikrocontroller.net/topic/559607 9 | 10 | 11 | # Installation 12 | 1) compile for your microcontrollers 13 | 2) flashing and power up (it opens a hotspot named "Energy2Shelly") 14 | 3) running WifiManager for intial WiFi setup and further configuration 15 | 16 | ### On the captive portal you can currently enter: 17 | - MQTT 18 | - Server IP, port and topic; power values on the MQTT topic are expected in JSON format. The are multiple fields to define the available values using a JSON Path-style syntax. 19 | You can also select between monophase and triphase power data.
20 | 21 | examples (monophase profile): 22 | - Total power JSON path -> ENERGY.Power for {"ENERGY":{"Power":9.99}}
23 | - Phase 1 power JSON path -> "no definition"
24 | - Phase 2 power JSON path -> "no definition"
25 | - Phase 3 power JSON path -> "no definition"
26 | - Energy from grid JSON path -> ENERGY.Consumption for {"ENERGY":{"Consumption"77}}
27 | - Energy to grid JSON path -> ENERGY.Production for {"ENERGY":{"Production"33}}
28 | -> Energy2Shelly_ESP responds to
{"ENERGY":{"Power": 9.99,"Consumption":77,"Production":33}}
29 | 30 | examples (triphase profile): 31 | - Total power JSON path -> ENERGY.Power for {"ENERGY":{"Power":7.3}}
32 | - Phase 1 power JSON path -> ENERGY.Pow1 for {"ENERGY":{"Pow1":98}}
33 | - Phase 2 power JSON path -> ENERGY.Pow2 for {"ENERGY":{"Pow2":196}}
34 | - Phase 3 power JSON path -> ENERGY.Pow3 for {"ENERGY":{"Pow3":294}}
35 | - Energy from grid JSON path -> ENERGY.Consumption for {"ENERGY":{"Consumption"98}} 36 | - Energy to grid JSON path -> ENERGY.Production for {"ENERGY":{"Production"131}}
37 | -> Energy2Shelly_ESP responds to
{"ENERGY":{"Power":7.3,"Pow1":98,"Pow2":196,"Pow3":294,"Consumption":98,"Production":131}}
38 | 39 | - SMA 40 | - SMA Energy Meter or Home Manager UDP multicast data; if you have multiple SMA energy meters you can optionally provide the serial number of the source you want to use in the configuration options 41 | - SHRDZM 42 | - SHRDZM smart meter interface (common in Austria) with UDP unicast data; please enable UDP broadcasts to the IP of the ESP and port 9522 within SHRDZM 43 | - HTTP 44 | - a generic HTTP input; enter a query URL in the second parameter field which delivers JSON data and define at least the JSON Path for total power. For full details on JSONPath configuration, check the section on MQTT above.
45 | - SUNSPEC 46 | - generic SUNSPEC register data polling via Modbus TCP; use server for address of Modbus device (e.g. Kostal Smart energy meter), port for Modbus TCP port (usually 502) and Modbus device ID for the unit ID (71 for KSEM) 47 | 48 | ### Here are some sample generic HTTP query paths for common devices: 49 | - Fronius: http://IP-address/solar_api/v1/GetMeterRealtimeData.cgi?Scope=System 50 | - Tasmota devices: http://IP-address/cm?cmnd=status%2010 51 | - ioBroker datapoints: http://IP-address:8082/getBulk/smartmeter.0.1-0:1_8_0__255.value,smartmeter.0.1-0:2_8_0__255.value,smartmeter.0.1-0:16_7_0__255.value/?json 52 | 53 | The Shelly ID defaults to the ESP's MAC address, you may change this if you want to substitute an existing uni-meter configuration without reconnecting the battery to a new shelly device. 54 | 55 | 4) Check if your device is visible in the WLAN. http://IP-address
56 | 5) Check the current power data at http://IP-address/status
57 | - [ ] \(Optional) If you want to reset you Wifi-Configuration and/or reconfigure other settings go to http://IP-address/reset and reconnect to the Energy2Shelly hotspot. 58 | 59 | # Tested microcontrollers 60 | * ESP32 (ESP32-WROOM-32) 61 | * ESP8266 62 | 63 | # You found a bug 64 | First, sorry. This software is not perfect. 65 | 1. Open a issue 66 | -With helpful title - use descriptive keywords in the title and body so others can find your bug (avoiding duplicates). 67 | - Which branch, what microcontroller, what setup 68 | - Steps to reproduce the problem, with actual vs. expected results 69 | - If you find a bug in our code, post the files and the lines. 70 |
71 |
72 | 73 | # some screenshots from project 74 | ![wifi](./screenshots/screenshot_01.png) 75 | 76 | ### Settings 77 | ![settings](./screenshots/screenshot_02.png) 78 | ![settings](./screenshots/screenshot_03.png) 79 | 80 | ### main page http://IP-address 81 | ![main](./screenshots/screenshot_04.png) 82 | 83 | ### status page http://IP-address/status 84 | ![status](./screenshots/screenshot_05.png) 85 | 86 | > [!NOTE] 87 | > Images may vary depending on the version. We always try to be up to date. 88 | -------------------------------------------------------------------------------- /platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [platformio] 12 | core_dir = .platformio 13 | description = Firmware for ESP82xx/ESP32 for Shelly Emulator 14 | 15 | [env] 16 | monitor_speed = 115200 17 | 18 | [lib_ESP32] 19 | lib_deps = 20 | knolleary/PubSubClient@^2.8 21 | bblanchon/ArduinoJson@^7.3.0 22 | tzapu/WiFiManager@^2.0.17 23 | esp32async/ESPAsyncWebServer@^3.7.1 24 | emelianov/modbus-esp8266@^4.1.0 25 | 26 | [lib_ESP8266] 27 | lib_deps = 28 | knolleary/PubSubClient@^2.8 29 | bblanchon/ArduinoJson@^7.3.0 30 | tzapu/WiFiManager@^2.0.17 31 | vshymanskyy/Preferences@^2.1.0 32 | esp32async/ESPAsyncWebServer@^3.7.1 33 | emelianov/modbus-esp8266@^4.1.0 34 | 35 | [env:esp32-devkit-v1] 36 | platform = espressif32 37 | board = esp32doit-devkit-v1 38 | board_build.partitions = min_spiffs.csv 39 | framework = arduino 40 | lib_deps = ${lib_ESP32.lib_deps} 41 | monitor_speed = ${env.monitor_speed} 42 | 43 | [env:esp32-devkit-v4] 44 | platform = espressif32 45 | board = az-delivery-devkit-v4 46 | board_build.partitions = min_spiffs.csv 47 | framework = arduino 48 | lib_deps = ${lib_ESP32.lib_deps} 49 | monitor_speed = ${env.monitor_speed} 50 | 51 | [env:esp32-d1-mini] 52 | platform = espressif32 53 | board = wemos_d1_mini32 54 | board_build.partitions = min_spiffs.csv 55 | framework = arduino 56 | lib_deps = ${lib_ESP32.lib_deps} 57 | monitor_speed = ${env.monitor_speed} 58 | 59 | [env:esp8266] 60 | platform = espressif8266 61 | board = nodemcuv2 62 | framework = arduino 63 | lib_deps = ${lib_ESP8266.lib_deps} 64 | monitor_speed = ${env.monitor_speed} 65 | 66 | [env:esp8266-d1-mini] 67 | platform = espressif8266 68 | board = d1_mini 69 | framework = arduino 70 | lib_deps = ${lib_ESP8266.lib_deps} 71 | monitor_speed = ${env.monitor_speed} 72 | -------------------------------------------------------------------------------- /screenshots/screenshot_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheRealMoeder/Energy2Shelly_ESP/c60859d13a099a421d3b28aaa3919052ac8fcdac/screenshots/screenshot_01.png -------------------------------------------------------------------------------- /screenshots/screenshot_02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheRealMoeder/Energy2Shelly_ESP/c60859d13a099a421d3b28aaa3919052ac8fcdac/screenshots/screenshot_02.png -------------------------------------------------------------------------------- /screenshots/screenshot_03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheRealMoeder/Energy2Shelly_ESP/c60859d13a099a421d3b28aaa3919052ac8fcdac/screenshots/screenshot_03.png -------------------------------------------------------------------------------- /screenshots/screenshot_04.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheRealMoeder/Energy2Shelly_ESP/c60859d13a099a421d3b28aaa3919052ac8fcdac/screenshots/screenshot_04.png -------------------------------------------------------------------------------- /screenshots/screenshot_05.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheRealMoeder/Energy2Shelly_ESP/c60859d13a099a421d3b28aaa3919052ac8fcdac/screenshots/screenshot_05.png -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | // Energy2Shelly_ESP v0.5.2 2 | #include 3 | #include 4 | #ifndef ESP32 5 | #define WEBSERVER_H "fix WifiManager conflict" 6 | #endif 7 | #ifdef ESP32 8 | #include 9 | #include 10 | #include 11 | #include 12 | #else 13 | #include 14 | #include 15 | #include 16 | #endif 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #define DEBUG true // set to false for no DEBUG output 26 | #define DEBUG_SERIAL if(DEBUG)Serial 27 | 28 | unsigned long startMillis = 0; 29 | unsigned long startMillis_sunspec = 0; 30 | unsigned long currentMillis; 31 | 32 | // define your default values here, if there are different values in config.json, they are overwritten. 33 | char input_type[40]; 34 | char mqtt_server[80]; 35 | char mqtt_port[6] = "1883"; 36 | char mqtt_topic[60] = "tele/meter/SENSOR"; 37 | char mqtt_user[40] = ""; 38 | char mqtt_passwd[40] = ""; 39 | char power_path[60] = ""; 40 | char pwr_export_path[60] = ""; 41 | char power_l1_path[60] = ""; 42 | char power_l2_path[60] = ""; 43 | char power_l3_path[60] = ""; 44 | char energy_in_path[60] = ""; 45 | char energy_out_path[60] = ""; 46 | char shelly_gen[2] = "2"; 47 | char shelly_fw_id[32] = "20241011-114455/1.4.4-g6d2a586"; 48 | char shelly_mac[13]; 49 | char shelly_name[26] = "shellypro3em-"; 50 | char query_period[10] = "1000"; 51 | char modbus_dev[10] = "71"; // default for KSEM 52 | char shelly_port[6] = "2220"; // old: 1010; new (FW>=226): 2220 53 | char force_pwr_decimals[6] = "true"; // to fix Marstek bug 54 | bool forcePwrDecimals = true; // to fix Marstek bug 55 | char sma_id[17] = ""; 56 | 57 | IPAddress modbus_ip; 58 | ModbusIP modbus1; 59 | int16_t modbus_result[256]; 60 | 61 | const uint8_t defaultVoltage = 230; 62 | const uint8_t defaultFrequency = 50; 63 | const uint8_t defaultPowerFactor = 1; 64 | 65 | // LED blink default values 66 | unsigned long ledOffTime = 0; 67 | uint8_t led = 0; 68 | bool led_i = false; 69 | const uint8_t ledblinkduration = 50; 70 | char led_gpio[3] = ""; 71 | char led_gpio_i[6]; 72 | 73 | unsigned long period = 1000; 74 | int rpcId = 1; 75 | char rpcUser[20] = "user_1"; 76 | 77 | // SMA Multicast IP and Port 78 | unsigned int multicastPort = 9522; // local port to listen on 79 | IPAddress multicastIP(239, 12, 255, 254); 80 | 81 | // flags for saving/resetting WifiManager data 82 | bool shouldSaveConfig = false; 83 | bool shouldResetConfig = false; 84 | 85 | Preferences preferences; 86 | 87 | // flags for data sources 88 | bool dataMQTT = false; 89 | bool dataSMA = false; 90 | bool dataSHRDZM = false; 91 | bool dataHTTP = false; 92 | bool dataSUNSPEC = false; 93 | 94 | struct PowerData { 95 | double current; 96 | double voltage; 97 | double power; 98 | double apparentPower; 99 | double powerFactor; 100 | double frequency; 101 | }; 102 | 103 | struct EnergyData { 104 | double gridfeedin; 105 | double consumption; 106 | }; 107 | 108 | PowerData PhasePower[3]; 109 | EnergyData PhaseEnergy[3]; 110 | String serJsonResponse; 111 | 112 | #ifndef ESP32 113 | MDNSResponder::hMDNSService hMDNSService = 0; // handle of the http service in the MDNS responder 114 | MDNSResponder::hMDNSService hMDNSService2 = 0; // handle of the shelly service in the MDNS responder 115 | #endif 116 | 117 | WiFiClient wifi_client; 118 | PubSubClient mqtt_client(wifi_client); 119 | static AsyncWebServer server(80); 120 | static AsyncWebSocket webSocket("/rpc"); 121 | WiFiUDP Udp; 122 | HTTPClient http; 123 | WiFiUDP UdpRPC; 124 | #ifdef ESP32 125 | #define UDPPRINT print 126 | #else 127 | #define UDPPRINT write 128 | #endif 129 | 130 | double round2(double value) { 131 | int ivalue = (int)(value * 100.0 + (value > 0.0 ? 0.5 : -0.5)); 132 | 133 | // fix Marstek bug: make sure to have decimal numbers 134 | if(forcePwrDecimals && (ivalue % 100 == 0)) ivalue++; 135 | 136 | return ivalue / 100.0; 137 | } 138 | 139 | JsonVariant resolveJsonPath(JsonVariant variant, const char *path) { 140 | for (size_t n = 0; path[n]; n++) { 141 | // Not a full array support, but works for Shelly 3EM emeters array! 142 | if (path[n] == '[') { 143 | variant = variant[JsonString(path, n)][atoi(&path[n+1])]; 144 | path += n + 4; 145 | n = 0; 146 | } 147 | if (path[n] == '.') { 148 | variant = variant[JsonString(path, n)]; 149 | path += n + 1; 150 | n = 0; 151 | } 152 | } 153 | return variant[path]; 154 | } 155 | 156 | void setPowerData(double totalPower) { 157 | for (int i = 0; i <= 2; i++) { 158 | PhasePower[i].power = round2(totalPower * 0.3333); 159 | PhasePower[i].voltage = defaultVoltage; 160 | PhasePower[i].current = round2(PhasePower[i].power / PhasePower[i].voltage); 161 | PhasePower[i].apparentPower = round2(PhasePower[i].power); 162 | PhasePower[i].powerFactor = defaultPowerFactor; 163 | PhasePower[i].frequency = defaultFrequency; 164 | } 165 | DEBUG_SERIAL.print("Current total power: "); 166 | DEBUG_SERIAL.println(totalPower); 167 | } 168 | 169 | void setPowerData(double phase1Power, double phase2Power, double phase3Power) { 170 | PhasePower[0].power = round2(phase1Power); 171 | PhasePower[1].power = round2(phase2Power); 172 | PhasePower[2].power = round2(phase3Power); 173 | for (int i = 0; i <= 2; i++) { 174 | PhasePower[i].voltage = defaultVoltage; 175 | PhasePower[i].current = round2(PhasePower[i].power / PhasePower[i].voltage); 176 | PhasePower[i].apparentPower = round2(PhasePower[i].power); 177 | PhasePower[i].powerFactor = defaultPowerFactor; 178 | PhasePower[i].frequency = defaultFrequency; 179 | } 180 | DEBUG_SERIAL.print("Current power L1: "); 181 | DEBUG_SERIAL.print(phase1Power); 182 | DEBUG_SERIAL.print(" - L2: "); 183 | DEBUG_SERIAL.print(phase2Power); 184 | DEBUG_SERIAL.print(" - L3: "); 185 | DEBUG_SERIAL.println(phase3Power); 186 | } 187 | 188 | void setEnergyData(double totalEnergyGridSupply, double totalEnergyGridFeedIn) { 189 | for (int i = 0; i <= 2; i++) { 190 | PhaseEnergy[i].consumption = round2(totalEnergyGridSupply * 0.3333); 191 | PhaseEnergy[i].gridfeedin = round2(totalEnergyGridFeedIn * 0.3333); 192 | } 193 | DEBUG_SERIAL.print("Total consumption: "); 194 | DEBUG_SERIAL.print(totalEnergyGridSupply); 195 | DEBUG_SERIAL.print(" - Total Grid Feed-In: "); 196 | DEBUG_SERIAL.println(totalEnergyGridFeedIn); 197 | } 198 | 199 | //callback notifying us of the need to save WifiManager config 200 | void saveConfigCallback() { 201 | DEBUG_SERIAL.println("Should save config"); 202 | shouldSaveConfig = true; 203 | } 204 | 205 | void setJsonPathPower(JsonDocument json) { 206 | if (strcmp(power_path, "TRIPHASE") == 0) { 207 | DEBUG_SERIAL.println("resolving triphase"); 208 | double power1 = resolveJsonPath(json, power_l1_path); 209 | double power2 = resolveJsonPath(json, power_l2_path); 210 | double power3 = resolveJsonPath(json, power_l3_path); 211 | setPowerData(power1, power2, power3); 212 | } else { 213 | // Check if BOTH paths (Import = power_path, Export = pwr_export_path) are defined 214 | if ((strcmp(power_path, "") != 0) && (strcmp(pwr_export_path, "") != 0)) { 215 | DEBUG_SERIAL.println("Resolving net power (import - export)"); 216 | double importPower = resolveJsonPath(json, power_path).as(); 217 | double exportPower = resolveJsonPath(json, pwr_export_path).as(); 218 | double netPower = importPower - exportPower; 219 | setPowerData(netPower); 220 | } 221 | // (FALLBACK): Only the normal power_path (import path) is defined (old logic) 222 | else if (strcmp(power_path, "") != 0) { 223 | DEBUG_SERIAL.println("Resolving monophase (single path only)"); 224 | double power = resolveJsonPath(json, power_path).as(); 225 | setPowerData(power); 226 | } 227 | } 228 | if ((strcmp(energy_in_path, "") != 0) && (strcmp(energy_out_path, "") != 0)) { 229 | double energyIn = resolveJsonPath(json, energy_in_path); 230 | double energyOut = resolveJsonPath(json, energy_out_path); 231 | setEnergyData(energyIn, energyOut); 232 | } 233 | } 234 | 235 | void rpcWrapper() { 236 | JsonDocument jsonResponse; 237 | JsonDocument doc; 238 | deserializeJson(doc, serJsonResponse); 239 | jsonResponse["id"] = rpcId; 240 | jsonResponse["src"] = shelly_name; 241 | if (strcmp(rpcUser, "EMPTY") != 0) { 242 | jsonResponse["dst"] = rpcUser; 243 | } 244 | jsonResponse["result"] = doc; 245 | serializeJson(jsonResponse, serJsonResponse); 246 | } 247 | 248 | void blinkled(int duration) { 249 | if (led > 0) { 250 | if (led_i) { 251 | digitalWrite(led, HIGH); 252 | } else { 253 | digitalWrite(led, LOW); 254 | } 255 | ledOffTime = millis() + duration; 256 | } 257 | } 258 | 259 | void handleblinkled() { 260 | if (led > 0) { 261 | if (ledOffTime > 0 && millis() > ledOffTime) { 262 | if (led_i) { 263 | digitalWrite(led, LOW); 264 | } else { 265 | digitalWrite(led, HIGH); 266 | } 267 | ledOffTime = 0; 268 | } 269 | } 270 | } 271 | 272 | void GetDeviceInfo() { 273 | JsonDocument jsonResponse; 274 | jsonResponse["name"] = shelly_name; 275 | jsonResponse["id"] = shelly_name; 276 | jsonResponse["mac"] = shelly_mac; 277 | jsonResponse["slot"] = 1; 278 | jsonResponse["model"] = "SPEM-003CEBEU"; 279 | jsonResponse["gen"] = shelly_gen; 280 | jsonResponse["fw_id"] = shelly_fw_id; 281 | jsonResponse["ver"] = "1.4.4"; 282 | jsonResponse["app"] = "Pro3EM"; 283 | jsonResponse["auth_en"] = false; 284 | jsonResponse["profile"] = "triphase"; 285 | serializeJson(jsonResponse, serJsonResponse); 286 | DEBUG_SERIAL.println(serJsonResponse); 287 | blinkled(ledblinkduration); 288 | } 289 | 290 | void EMGetStatus() { 291 | JsonDocument jsonResponse; 292 | jsonResponse["id"] = 0; 293 | jsonResponse["a_current"] = PhasePower[0].current; 294 | jsonResponse["a_voltage"] = PhasePower[0].voltage; 295 | jsonResponse["a_act_power"] = PhasePower[0].power; 296 | jsonResponse["a_aprt_power"] = PhasePower[0].apparentPower; 297 | jsonResponse["a_pf"] = PhasePower[0].powerFactor; 298 | jsonResponse["a_freq"] = PhasePower[0].frequency; 299 | jsonResponse["b_current"] = PhasePower[1].current; 300 | jsonResponse["b_voltage"] = PhasePower[1].voltage; 301 | jsonResponse["b_act_power"] = PhasePower[1].power; 302 | jsonResponse["b_aprt_power"] = PhasePower[1].apparentPower; 303 | jsonResponse["b_pf"] = PhasePower[1].powerFactor; 304 | jsonResponse["b_freq"] = PhasePower[1].frequency; 305 | jsonResponse["c_current"] = PhasePower[2].current; 306 | jsonResponse["c_voltage"] = PhasePower[2].voltage; 307 | jsonResponse["c_act_power"] = PhasePower[2].power; 308 | jsonResponse["c_aprt_power"] = PhasePower[2].apparentPower; 309 | jsonResponse["c_pf"] = PhasePower[2].powerFactor; 310 | jsonResponse["c_freq"] = PhasePower[2].frequency; 311 | jsonResponse["total_current"] = round2((PhasePower[0].power + PhasePower[1].power + PhasePower[2].power) / ((float)defaultVoltage)); 312 | jsonResponse["total_act_power"] = PhasePower[0].power + PhasePower[1].power + PhasePower[2].power; 313 | jsonResponse["total_aprt_power"] = PhasePower[0].apparentPower + PhasePower[1].apparentPower + PhasePower[2].apparentPower; 314 | serializeJson(jsonResponse, serJsonResponse); 315 | DEBUG_SERIAL.println(serJsonResponse); 316 | blinkled(ledblinkduration); 317 | } 318 | 319 | void EMDataGetStatus() { 320 | JsonDocument jsonResponse; 321 | jsonResponse["id"] = 0; 322 | jsonResponse["a_total_act_energy"] = PhaseEnergy[0].consumption; 323 | jsonResponse["a_total_act_ret_energy"] = PhaseEnergy[0].gridfeedin; 324 | jsonResponse["b_total_act_energy"] = PhaseEnergy[1].consumption; 325 | jsonResponse["b_total_act_ret_energy"] = PhaseEnergy[1].gridfeedin; 326 | jsonResponse["c_total_act_energy"] = PhaseEnergy[2].consumption; 327 | jsonResponse["c_total_act_ret_energy"] = PhaseEnergy[2].gridfeedin; 328 | jsonResponse["total_act"] = PhaseEnergy[0].consumption + PhaseEnergy[1].consumption + PhaseEnergy[2].consumption; 329 | jsonResponse["total_act_ret"] = PhaseEnergy[0].gridfeedin + PhaseEnergy[1].gridfeedin + PhaseEnergy[2].gridfeedin; 330 | serializeJson(jsonResponse, serJsonResponse); 331 | DEBUG_SERIAL.println(serJsonResponse); 332 | blinkled(ledblinkduration); 333 | } 334 | 335 | void EMGetConfig() { 336 | JsonDocument jsonResponse; 337 | jsonResponse["id"] = 0; 338 | jsonResponse["name"] = nullptr; 339 | jsonResponse["blink_mode_selector"] = "active_energy"; 340 | jsonResponse["phase_selector"] = "a"; 341 | jsonResponse["monitor_phase_sequence"] = true; 342 | jsonResponse["ct_type"] = "120A"; 343 | serializeJson(jsonResponse, serJsonResponse); 344 | DEBUG_SERIAL.println(serJsonResponse); 345 | blinkled(ledblinkduration); 346 | } 347 | 348 | void webSocketEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { 349 | JsonDocument json; 350 | switch (type) { 351 | case WS_EVT_DISCONNECT: 352 | DEBUG_SERIAL.printf("[%u] Websocket: disconnected!\n", client->id()); 353 | break; 354 | case WS_EVT_CONNECT: 355 | DEBUG_SERIAL.printf("[%u] Websocket: connected from %s\n", client->id(), client->remoteIP().toString().c_str()); 356 | break; 357 | case WS_EVT_DATA: 358 | { 359 | AwsFrameInfo *info = (AwsFrameInfo *)arg; 360 | if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) { 361 | data[len] = 0; 362 | deserializeJson(json, data); 363 | rpcId = json["id"]; 364 | if (json["method"] == "Shelly.GetDeviceInfo") { 365 | strcpy(rpcUser, "EMPTY"); 366 | GetDeviceInfo(); 367 | rpcWrapper(); 368 | webSocket.textAll(serJsonResponse); 369 | } else if (json["method"] == "EM.GetStatus") { 370 | strcpy(rpcUser, json["src"]); 371 | EMGetStatus(); 372 | rpcWrapper(); 373 | webSocket.textAll(serJsonResponse); 374 | } else if (json["method"] == "EMData.GetStatus") { 375 | strcpy(rpcUser, json["src"]); 376 | EMDataGetStatus(); 377 | rpcWrapper(); 378 | webSocket.textAll(serJsonResponse); 379 | } else if (json["method"] == "EM.GetConfig") { 380 | EMGetConfig(); 381 | rpcWrapper(); 382 | webSocket.textAll(serJsonResponse); 383 | } else { 384 | DEBUG_SERIAL.printf("Websocket: unknown request: %s\n", data); 385 | } 386 | } 387 | break; 388 | } 389 | case WS_EVT_PING: 390 | case WS_EVT_PONG: 391 | case WS_EVT_ERROR: 392 | break; 393 | } 394 | } 395 | 396 | void mqtt_callback(char *topic, byte *payload, unsigned int length) { 397 | JsonDocument json; 398 | deserializeJson(json, payload, length); 399 | setJsonPathPower(json); 400 | } 401 | 402 | void mqtt_reconnect() { 403 | DEBUG_SERIAL.print("Attempting MQTT connection..."); 404 | if (mqtt_client.connect(shelly_name, String(mqtt_user).c_str(), String(mqtt_passwd).c_str())) { 405 | DEBUG_SERIAL.println("connected"); 406 | mqtt_client.subscribe(mqtt_topic); 407 | } else { 408 | DEBUG_SERIAL.print("failed, rc="); 409 | DEBUG_SERIAL.print(mqtt_client.state()); 410 | DEBUG_SERIAL.println(" try again in 5 seconds"); 411 | delay(5000); 412 | } 413 | } 414 | 415 | void parseUdpRPC() { 416 | uint8_t buffer[1024]; 417 | int packetSize = UdpRPC.parsePacket(); 418 | if (packetSize) { 419 | JsonDocument json; 420 | int rSize = UdpRPC.read(buffer, 1024); 421 | buffer[rSize] = 0; 422 | DEBUG_SERIAL.print("Received UDP packet on port 1010: "); 423 | DEBUG_SERIAL.println((char *)buffer); 424 | deserializeJson(json, buffer); 425 | if (json["method"].is()) { 426 | rpcId = json["id"]; 427 | strcpy(rpcUser, "EMPTY"); 428 | UdpRPC.beginPacket(UdpRPC.remoteIP(), UdpRPC.remotePort()); 429 | if (json["method"] == "Shelly.GetDeviceInfo") { 430 | GetDeviceInfo(); 431 | rpcWrapper(); 432 | UdpRPC.UDPPRINT(serJsonResponse.c_str()); 433 | } else if (json["method"] == "EM.GetStatus") { 434 | EMGetStatus(); 435 | rpcWrapper(); 436 | UdpRPC.UDPPRINT(serJsonResponse.c_str()); 437 | } else if (json["method"] == "EMData.GetStatus") { 438 | EMDataGetStatus(); 439 | rpcWrapper(); 440 | UdpRPC.UDPPRINT(serJsonResponse.c_str()); 441 | } else if (json["method"] == "EM.GetConfig") { 442 | EMGetConfig(); 443 | rpcWrapper(); 444 | UdpRPC.UDPPRINT(serJsonResponse.c_str()); 445 | } else { 446 | DEBUG_SERIAL.printf("RPC over UDP: unknown request: %s\n", buffer); 447 | } 448 | UdpRPC.endPacket(); 449 | } 450 | } 451 | } 452 | 453 | void parseSMA() { 454 | uint8_t buffer[1024]; 455 | int packetSize = Udp.parsePacket(); 456 | if (packetSize) { 457 | int rSize = Udp.read(buffer, 1024); 458 | if (buffer[0] != 'S' || buffer[1] != 'M' || buffer[2] != 'A') { 459 | DEBUG_SERIAL.println("Not an SMA packet?"); 460 | return; 461 | } 462 | uint16_t grouplen; 463 | uint16_t grouptag; 464 | uint8_t *offset = buffer + 4; 465 | do { 466 | grouplen = (offset[0] << 8) + offset[1]; 467 | grouptag = (offset[2] << 8) + offset[3]; 468 | offset += 4; 469 | if (grouplen == 0xffff) return; 470 | if (grouptag == 0x02A0 && grouplen == 4) { 471 | offset += 4; 472 | } else if (grouptag == 0x0010) { 473 | uint8_t *endOfGroup = offset + grouplen; 474 | // uint16_t protocolID = (offset[0] << 8) + offset[1]; 475 | offset += 2; 476 | // uint16_t susyID = (offset[0] << 8) + offset[1]; 477 | offset += 2; 478 | uint32_t serial = (offset[0] << 24) + (offset[1] << 16) + (offset[2] << 8) + offset[3]; 479 | DEBUG_SERIAL.print("Received SMA multicast from "); 480 | DEBUG_SERIAL.println(serial); 481 | if ((strcmp(sma_id, "") != 0) && (String(sma_id).toInt() != serial)) { 482 | DEBUG_SERIAL.println("SMA serial not matching - ignoring packet"); 483 | break; 484 | } 485 | offset += 4; 486 | // uint32_t timestamp = (offset[0] << 24) + (offset[1] << 16) + (offset[2] << 8) + offset[3]; 487 | offset += 4; 488 | while (offset < endOfGroup) { 489 | uint8_t channel = offset[0]; 490 | uint8_t index = offset[1]; 491 | uint8_t type = offset[2]; 492 | // uint8_t tarif = offset[3]; 493 | offset += 4; 494 | if (type == 8) { 495 | uint64_t data = ((uint64_t)offset[0] << 56) + ((uint64_t)offset[1] << 48) + ((uint64_t)offset[2] << 40) + ((uint64_t)offset[3] << 32) + ((uint64_t)offset[4] << 24) + ((uint64_t)offset[5] << 16) + ((uint64_t)offset[6] << 8) + offset[7]; 496 | offset += 8; 497 | switch (index) { 498 | case 21: 499 | PhaseEnergy[0].consumption = data / 3600000; 500 | break; 501 | case 22: 502 | PhaseEnergy[0].gridfeedin = data / 3600000; 503 | break; 504 | case 41: 505 | PhaseEnergy[1].consumption = data / 3600000; 506 | break; 507 | case 42: 508 | PhaseEnergy[1].gridfeedin = data / 3600000; 509 | break; 510 | case 61: 511 | PhaseEnergy[2].consumption = data / 3600000; 512 | break; 513 | case 62: 514 | PhaseEnergy[2].gridfeedin = data / 3600000; 515 | break; 516 | } 517 | } else if (type == 4) { 518 | uint32_t data = (offset[0] << 24) + (offset[1] << 16) + (offset[2] << 8) + offset[3]; 519 | offset += 4; 520 | switch (index) { 521 | case 1: 522 | // 1.4.0 Total grid power in dW - unused 523 | break; 524 | case 2: 525 | // 2.4.0 Total feed-in power in dW - unused 526 | break; 527 | case 21: 528 | PhasePower[0].power = round2(data * 0.1); 529 | PhasePower[0].frequency = defaultFrequency; 530 | break; 531 | case 22: 532 | PhasePower[0].power -= round2(data * 0.1); 533 | break; 534 | case 29: 535 | PhasePower[0].apparentPower = round2(data * 0.1); 536 | break; 537 | case 30: 538 | PhasePower[0].apparentPower -= round2(data * 0.1); 539 | break; 540 | case 31: 541 | PhasePower[0].current = round2(data * 0.001); 542 | break; 543 | case 32: 544 | PhasePower[0].voltage = round2(data * 0.001); 545 | break; 546 | case 33: 547 | PhasePower[0].powerFactor = round2(data * 0.001); 548 | break; 549 | case 41: 550 | PhasePower[1].power = round2(data * 0.1); 551 | PhasePower[1].frequency = defaultFrequency; 552 | break; 553 | case 42: 554 | PhasePower[1].power -= round2(data * 0.1); 555 | break; 556 | case 49: 557 | PhasePower[1].apparentPower = round2(data * 0.1); 558 | break; 559 | case 50: 560 | PhasePower[1].apparentPower -= round2(data * 0.1); 561 | break; 562 | case 51: 563 | PhasePower[1].current = round2(data * 0.001); 564 | break; 565 | case 52: 566 | PhasePower[1].voltage = round2(data * 0.001); 567 | break; 568 | case 53: 569 | PhasePower[1].powerFactor = round2(data * 0.001); 570 | break; 571 | case 61: 572 | PhasePower[2].power = round2(data * 0.1); 573 | PhasePower[2].frequency = defaultFrequency; 574 | break; 575 | case 62: 576 | PhasePower[2].power -= round2(data * 0.1); 577 | break; 578 | case 69: 579 | PhasePower[2].apparentPower = round2(data * 0.1); 580 | break; 581 | case 70: 582 | PhasePower[2].apparentPower -= round2(data * 0.1); 583 | break; 584 | case 71: 585 | PhasePower[2].current = round2(data * 0.001); 586 | break; 587 | case 72: 588 | PhasePower[2].voltage = round2(data * 0.001); 589 | break; 590 | case 73: 591 | PhasePower[2].powerFactor = round2(data * 0.001); 592 | break; 593 | default: 594 | break; 595 | } 596 | } else if (channel == 144) { 597 | // optional handling of version number 598 | offset += 4; 599 | } else { 600 | offset += type; 601 | DEBUG_SERIAL.println("Unknown measurement"); 602 | } 603 | } 604 | } else if (grouptag == 0) { 605 | // end marker 606 | offset += grouplen; 607 | } else { 608 | DEBUG_SERIAL.print("unhandled group "); 609 | DEBUG_SERIAL.print(grouptag); 610 | DEBUG_SERIAL.print(" with len="); 611 | DEBUG_SERIAL.println(grouplen); 612 | offset += grouplen; 613 | } 614 | } while (grouplen > 0 && offset + 4 < buffer + rSize); 615 | } 616 | } 617 | 618 | void parseSHRDZM() { 619 | JsonDocument json; 620 | uint8_t buffer[1024]; 621 | int packetSize = Udp.parsePacket(); 622 | if (packetSize) { 623 | int rSize = Udp.read(buffer, 1024); 624 | buffer[rSize] = 0; 625 | deserializeJson(json, buffer); 626 | if (json["data"]["16.7.0"].is()) { 627 | double power = json["data"]["16.7.0"]; 628 | setPowerData(power); 629 | } 630 | if (json["data"]["1.8.0"].is() && json["data"]["2.8.0"].is()) { 631 | double energyIn = 0.001 * json["data"]["1.8.0"].as(); 632 | double energyOut = 0.001 * json["data"]["2.8.0"].as(); 633 | setEnergyData(energyIn, energyOut); 634 | } 635 | } 636 | } 637 | 638 | double SUNSPEC_scale(int n) 639 | { 640 | double val=1.0; 641 | switch (n) { 642 | case -3: val=0.001; break; 643 | case -2: val=0.01; break; 644 | case -1: val=0.1; break; 645 | case 0: val=1.0; break; 646 | case 1: val=10.0; break; 647 | case 2: val=100.0; break; 648 | default: 649 | val=1.0; 650 | } 651 | return val; 652 | } 653 | 654 | void parseSUNSPEC() { 655 | #define SUNSPEC_BASE 40072 656 | #define SUNSPEC_VOLTAGE 40077 657 | #define SUNSPEC_VOLTAGE_SCALE 40084 658 | #define SUNSPEC_REAL_POWER 40088 659 | #define SUNSPEC_REAL_POWER_SCALE 40091 660 | #define SUNSPEC_APPARANT_POWER 40093 661 | #define SUNSPEC_APPARANT_POWER_SCALE 40096 662 | #define SUNSPEC_CURRENT 40072 663 | #define SUNSPEC_CURRENT_SCALE 40075 664 | #define SUNSPEC_POWER_FACTOR 40103 665 | #define SUNSPEC_POWER_FACTOR_SCALE 40106 666 | #define SUNSPEC_FREQUENCY 40085 667 | #define SUNSPEC_FREQUENCY_SCALE 40086 668 | 669 | modbus_ip.fromString(mqtt_server); 670 | if (!modbus1.isConnected(modbus_ip)) { 671 | modbus1.connect(modbus_ip, String(mqtt_port).toInt()); 672 | } else { 673 | uint16_t transaction = modbus1.readHreg(modbus_ip, SUNSPEC_BASE, (uint16_t*) &modbus_result[0], 64, nullptr, String(modbus_dev).toInt()); 674 | delay(10); 675 | modbus1.task(); 676 | int t = 0; 677 | while (modbus1.isTransaction(transaction)) { 678 | modbus1.task(); 679 | delay(10); 680 | t++; 681 | if (t > 50) { 682 | DEBUG_SERIAL.println("Timeout SUNSPEC"); 683 | //prolong=10; 684 | modbus1.disconnect(modbus_ip); 685 | break; 686 | } 687 | } 688 | int32_t power = 0; 689 | if (t<=50) { 690 | double scale_V=SUNSPEC_scale(modbus_result[SUNSPEC_VOLTAGE_SCALE-SUNSPEC_BASE]); 691 | double scale_real_power=SUNSPEC_scale(modbus_result[SUNSPEC_REAL_POWER_SCALE-SUNSPEC_BASE]); 692 | double scale_apparant_power=SUNSPEC_scale(modbus_result[SUNSPEC_APPARANT_POWER_SCALE-SUNSPEC_BASE]); 693 | double scale_current=SUNSPEC_scale(modbus_result[SUNSPEC_CURRENT_SCALE-SUNSPEC_BASE]); 694 | double scale_powerfactor=SUNSPEC_scale(modbus_result[SUNSPEC_POWER_FACTOR_SCALE-SUNSPEC_BASE]); 695 | double scale_frequency=SUNSPEC_scale(modbus_result[SUNSPEC_FREQUENCY_SCALE-SUNSPEC_BASE]); 696 | 697 | for (int n=0;n<3;n++) { 698 | PhasePower[n].power=modbus_result[SUNSPEC_REAL_POWER-SUNSPEC_BASE+n]*scale_real_power; 699 | PhasePower[n].apparentPower=modbus_result[SUNSPEC_APPARANT_POWER-SUNSPEC_BASE+n]*scale_apparant_power; 700 | PhasePower[n].current= modbus_result[SUNSPEC_CURRENT-SUNSPEC_BASE+n]*scale_current; 701 | PhasePower[n].powerFactor=modbus_result[SUNSPEC_POWER_FACTOR-SUNSPEC_BASE+n]*scale_powerfactor; 702 | PhasePower[n].voltage=modbus_result[SUNSPEC_VOLTAGE-SUNSPEC_BASE+n]*scale_V; 703 | PhasePower[n].frequency=modbus_result[SUNSPEC_FREQUENCY-SUNSPEC_BASE]*scale_frequency; 704 | power+= PhasePower[n].power; 705 | } 706 | 707 | #define SUNSPEC_REAL_ENERGY_EXPORTED 40109 708 | #define SUNSPEC_REAL_IMPORTED_EXPORTED 40117 709 | #define SUNSPEC_REAL_ENERGY_SCALE 40123 710 | double scale_real_energy=SUNSPEC_scale(modbus_result[SUNSPEC_REAL_ENERGY_SCALE-SUNSPEC_BASE]); 711 | for (int n=0;n<3;n++) { 712 | uint32_t p=0; 713 | uint8_t *p_u8=(uint8_t *)&modbus_result[SUNSPEC_REAL_IMPORTED_EXPORTED-SUNSPEC_BASE+2*n]; 714 | p|=((uint32_t)p_u8[2])<<0; 715 | p|=((uint32_t)p_u8[3])<<8; 716 | p|=((uint32_t)p_u8[0])<<16; 717 | p|=((uint32_t)p_u8[1])<<24; 718 | PhaseEnergy[n].consumption=p/1000.0*scale_real_energy; 719 | p=0; 720 | p_u8=(uint8_t *)&modbus_result[SUNSPEC_REAL_ENERGY_EXPORTED-SUNSPEC_BASE+2*n]; 721 | p|=((uint32_t)p_u8[2])<<0; 722 | p|=((uint32_t)p_u8[3])<<8; 723 | p|=((uint32_t)p_u8[0])<<16; 724 | p|=((uint32_t)p_u8[1])<<24; 725 | PhaseEnergy[n].gridfeedin = -p/1000.0*scale_real_energy; 726 | } 727 | } 728 | DEBUG_SERIAL.printf("SUNSPEC power: %d,%d\n\r", t, power); 729 | } 730 | } 731 | 732 | void queryHTTP() { 733 | JsonDocument json; 734 | DEBUG_SERIAL.println("Querying HTTP source"); 735 | http.begin(wifi_client, mqtt_server); 736 | http.GET(); 737 | deserializeJson(json, http.getStream()); 738 | if (strcmp(power_path, "") == 0) { 739 | DEBUG_SERIAL.println("HTTP query: no JSONPath for power data provided"); 740 | } else { 741 | setJsonPathPower(json); 742 | } 743 | http.end(); 744 | } 745 | 746 | void WifiManagerSetup() { 747 | // Set Shelly ID to ESP's MAC address by default 748 | uint8_t mac[6]; 749 | WiFi.macAddress(mac); 750 | sprintf(shelly_mac, "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); 751 | 752 | preferences.begin("e2s_config", false); 753 | strcpy(input_type, preferences.getString("input_type", input_type).c_str()); 754 | strcpy(mqtt_server, preferences.getString("mqtt_server", mqtt_server).c_str()); 755 | strcpy(query_period, preferences.getString("query_period", query_period).c_str()); 756 | strcpy(led_gpio, preferences.getString("led_gpio", led_gpio).c_str()); 757 | strcpy(led_gpio_i, preferences.getString("led_gpio_i", led_gpio_i).c_str()); 758 | strcpy(shelly_mac, preferences.getString("shelly_mac", shelly_mac).c_str()); 759 | strcpy(mqtt_port, preferences.getString("mqtt_port", mqtt_port).c_str()); 760 | strcpy(mqtt_topic, preferences.getString("mqtt_topic", mqtt_topic).c_str()); 761 | strcpy(mqtt_user, preferences.getString("mqtt_user", mqtt_user).c_str()); 762 | strcpy(mqtt_passwd, preferences.getString("mqtt_passwd", mqtt_passwd).c_str()); 763 | strcpy(modbus_dev, preferences.getString("modbus_dev", modbus_dev).c_str()); 764 | strcpy(power_path, preferences.getString("power_path", power_path).c_str()); 765 | strcpy(pwr_export_path, preferences.getString("pwr_export_path", pwr_export_path).c_str()); 766 | strcpy(power_l1_path, preferences.getString("power_l1_path", power_l1_path).c_str()); 767 | strcpy(power_l2_path, preferences.getString("power_l2_path", power_l2_path).c_str()); 768 | strcpy(power_l3_path, preferences.getString("power_l3_path", power_l3_path).c_str()); 769 | strcpy(energy_in_path, preferences.getString("energy_in_path", energy_in_path).c_str()); 770 | strcpy(energy_out_path, preferences.getString("energy_out_path", energy_out_path).c_str()); 771 | strcpy(shelly_port, preferences.getString("shelly_port", shelly_port).c_str()); 772 | strcpy(force_pwr_decimals, preferences.getString("force_pwr_decimals", force_pwr_decimals).c_str()); 773 | strcpy(sma_id, preferences.getString("sma_id", sma_id).c_str()); 774 | 775 | WiFiManagerParameter custom_section1("

General settings

"); 776 | WiFiManagerParameter custom_input_type("type", "Data source
MQTT for MQTT
HTTP for generic HTTP
SMA for SMA EM/HM multicast
SHRDZM for SHRDZM UDP data
SUNSPEC for Modbus TCP SUNSPEC data", input_type, 40); 777 | WiFiManagerParameter custom_mqtt_server("server", "Server
MQTT Server IP, query url for generic HTTP or Modbus TCP server IP for SUNSPEC", mqtt_server, 80); 778 | WiFiManagerParameter custom_mqtt_port("port", "Port
for MQTT or Modbus TCP (SUNSPEC)", mqtt_port, 6); 779 | WiFiManagerParameter custom_query_period("query_period", "Query period
for generic HTTP and SUNSPEC, in milliseconds", query_period, 10); 780 | WiFiManagerParameter custom_led_gpio("led_gpio", "GPIO
of internal LED", led_gpio, 3); 781 | WiFiManagerParameter custom_led_gpio_i("led_gpio_i", "GPIO is inverted
true or false", led_gpio_i, 6); 782 | WiFiManagerParameter custom_shelly_mac("mac", "Shelly ID
12 char hexadecimal, defaults to MAC address of ESP", shelly_mac, 13); 783 | WiFiManagerParameter custom_shelly_port("shelly_port", "Shelly UDP port
1010 for old Marstek FW, 2220 for new Marstek FW v226+/v108+", shelly_port, 6); 784 | WiFiManagerParameter custom_force_pwr_decimals("force_pwr_decimals", "Force decimals numbers for Power values
true to fix Marstek bug", force_pwr_decimals, 6); 785 | WiFiManagerParameter custom_sma_id("sma_id", "SMA serial number
optional serial number if you have more than one SMA EM/HM in your network", sma_id, 16); 786 | WiFiManagerParameter custom_section2("

MQTT options

"); 787 | WiFiManagerParameter custom_mqtt_topic("topic", "MQTT Topic", mqtt_topic, 60); 788 | WiFiManagerParameter custom_mqtt_user("user", "MQTT user
optional", mqtt_user, 40); 789 | WiFiManagerParameter custom_mqtt_passwd("passwd", "MQTT password
optional", mqtt_passwd, 40); 790 | WiFiManagerParameter custom_section3("

Modbus TCP options

"); 791 | WiFiManagerParameter custom_modbus_dev("modbus_dev", "Modbus device ID
71 for Kostal SEM", modbus_dev, 60); 792 | WiFiManagerParameter custom_section4("

JSON paths for MQTT and generic HTTP

"); 793 | WiFiManagerParameter custom_power_path("power_path", "Total power JSON path
e.g. ENERGY.Power or TRIPHASE for tri-phase data", power_path, 60); 794 | WiFiManagerParameter custom_pwr_export_path("pwr_export_path", "Export power JSON path
Optional, for net calc (e.g. \"i-e\"", pwr_export_path, 60); 795 | WiFiManagerParameter custom_power_l1_path("power_l1_path", "Phase 1 power JSON path
optional", power_l1_path, 60); 796 | WiFiManagerParameter custom_power_l2_path("power_l2_path", "Phase 2 power JSON path
Phase 2 power JSON path
optional", power_l2_path, 60); 797 | WiFiManagerParameter custom_power_l3_path("power_l3_path", "Phase 3 power JSON path
Phase 3 power JSON path
optional", power_l3_path, 60); 798 | WiFiManagerParameter custom_energy_in_path("energy_in_path", "Energy from grid JSON path
e.g. ENERGY.Grid", energy_in_path, 60); 799 | WiFiManagerParameter custom_energy_out_path("energy_out_path", "Energy to grid JSON path
e.g. ENERGY.FeedIn", energy_out_path, 60); 800 | 801 | WiFiManager wifiManager; 802 | if (!DEBUG) { 803 | wifiManager.setDebugOutput(false); 804 | } 805 | wifiManager.setTitle("Energy2Shelly for ESP"); 806 | wifiManager.setSaveConfigCallback(saveConfigCallback); 807 | 808 | //add all your parameters here 809 | wifiManager.addParameter(&custom_section1); 810 | wifiManager.addParameter(&custom_input_type); 811 | wifiManager.addParameter(&custom_mqtt_server); 812 | wifiManager.addParameter(&custom_query_period); 813 | wifiManager.addParameter(&custom_led_gpio); 814 | wifiManager.addParameter(&custom_led_gpio_i); 815 | wifiManager.addParameter(&custom_shelly_mac); 816 | wifiManager.addParameter(&custom_shelly_port); 817 | wifiManager.addParameter(&custom_force_pwr_decimals); 818 | wifiManager.addParameter(&custom_sma_id); 819 | wifiManager.addParameter(&custom_section2); 820 | wifiManager.addParameter(&custom_mqtt_port); 821 | wifiManager.addParameter(&custom_mqtt_topic); 822 | wifiManager.addParameter(&custom_mqtt_user); 823 | wifiManager.addParameter(&custom_mqtt_passwd); 824 | wifiManager.addParameter(&custom_section3); 825 | wifiManager.addParameter(&custom_modbus_dev); 826 | wifiManager.addParameter(&custom_section4); 827 | wifiManager.addParameter(&custom_power_path); 828 | wifiManager.addParameter(&custom_pwr_export_path); 829 | wifiManager.addParameter(&custom_power_l1_path); 830 | wifiManager.addParameter(&custom_power_l2_path); 831 | wifiManager.addParameter(&custom_power_l3_path); 832 | wifiManager.addParameter(&custom_energy_in_path); 833 | wifiManager.addParameter(&custom_energy_out_path); 834 | 835 | 836 | if (!wifiManager.autoConnect("Energy2Shelly")) { 837 | DEBUG_SERIAL.println("failed to connect and hit timeout"); 838 | delay(3000); 839 | ESP.restart(); 840 | delay(5000); 841 | } 842 | DEBUG_SERIAL.println("connected"); 843 | 844 | //read updated parameters 845 | strcpy(input_type, custom_input_type.getValue()); 846 | strcpy(mqtt_server, custom_mqtt_server.getValue()); 847 | strcpy(mqtt_port, custom_mqtt_port.getValue()); 848 | strcpy(query_period, custom_query_period.getValue()); 849 | strcpy(led_gpio, custom_led_gpio.getValue()); 850 | strcpy(led_gpio_i, custom_led_gpio_i.getValue()); 851 | strcpy(shelly_mac, custom_shelly_mac.getValue()); 852 | strcpy(mqtt_topic, custom_mqtt_topic.getValue()); 853 | strcpy(mqtt_user, custom_mqtt_user.getValue()); 854 | strcpy(mqtt_passwd, custom_mqtt_passwd.getValue()); 855 | strcpy(modbus_dev, custom_modbus_dev.getValue()); 856 | strcpy(power_path, custom_power_path.getValue()); 857 | strcpy(pwr_export_path, custom_pwr_export_path.getValue()); 858 | strcpy(power_l1_path, custom_power_l1_path.getValue()); 859 | strcpy(power_l2_path, custom_power_l2_path.getValue()); 860 | strcpy(power_l3_path, custom_power_l3_path.getValue()); 861 | strcpy(energy_in_path, custom_energy_in_path.getValue()); 862 | strcpy(energy_out_path, custom_energy_out_path.getValue()); 863 | strcpy(shelly_port, custom_shelly_port.getValue()); 864 | strcpy(force_pwr_decimals, custom_force_pwr_decimals.getValue()); 865 | strcpy(sma_id, custom_sma_id.getValue()); 866 | 867 | DEBUG_SERIAL.println("The values in the preferences are: "); 868 | DEBUG_SERIAL.println("\tinput_type : " + String(input_type)); 869 | DEBUG_SERIAL.println("\tmqtt_server : " + String(mqtt_server)); 870 | DEBUG_SERIAL.println("\tmqtt_port : " + String(mqtt_port)); 871 | DEBUG_SERIAL.println("\tquery_period : " + String(query_period)); 872 | DEBUG_SERIAL.println("\tled_gpio : " + String(led_gpio)); 873 | DEBUG_SERIAL.println("\tled_gpio_i : " + String(led_gpio_i)); 874 | DEBUG_SERIAL.println("\tshelly_mac : " + String(shelly_mac)); 875 | DEBUG_SERIAL.println("\tmqtt_topic : " + String(mqtt_topic)); 876 | DEBUG_SERIAL.println("\tmqtt_user : " + String(mqtt_user)); 877 | DEBUG_SERIAL.println("\tmqtt_passwd : " + String(mqtt_passwd)); 878 | DEBUG_SERIAL.println("\tmodbus_dev : " + String(modbus_dev)); 879 | DEBUG_SERIAL.println("\tpower_path : " + String(power_path)); 880 | DEBUG_SERIAL.println("\tpwr_export_path : " + String(pwr_export_path)); 881 | DEBUG_SERIAL.println("\tpower_l1_path : " + String(power_l1_path)); 882 | DEBUG_SERIAL.println("\tpower_l2_path : " + String(power_l2_path)); 883 | DEBUG_SERIAL.println("\tpower_l3_path : " + String(power_l3_path)); 884 | DEBUG_SERIAL.println("\tenergy_in_path : " + String(energy_in_path)); 885 | DEBUG_SERIAL.println("\tenergy_out_path : " + String(energy_out_path)); 886 | DEBUG_SERIAL.println("\tshelly_port : " + String(shelly_port)); 887 | DEBUG_SERIAL.println("\tforce_pwr_decimals : " + String(force_pwr_decimals)); 888 | DEBUG_SERIAL.println("\tsma_id : " + String(sma_id)); 889 | 890 | if (strcmp(input_type, "SMA") == 0) { 891 | dataSMA = true; 892 | DEBUG_SERIAL.println("Enabling SMA Multicast data input"); 893 | } else if (strcmp(input_type, "SHRDZM") == 0) { 894 | dataSHRDZM = true; 895 | DEBUG_SERIAL.println("Enabling SHRDZM UDP data input"); 896 | } else if (strcmp(input_type, "HTTP") == 0) { 897 | dataHTTP = true; 898 | DEBUG_SERIAL.println("Enabling generic HTTP data input"); 899 | } else if (strcmp(input_type, "SUNSPEC") == 0) { 900 | dataSUNSPEC = true; 901 | DEBUG_SERIAL.println("Enabling SUNSPEC data input"); 902 | } 903 | else { 904 | dataMQTT = true; 905 | DEBUG_SERIAL.println("Enabling MQTT data input"); 906 | } 907 | 908 | if (strcmp(led_gpio_i, "true") == 0) { 909 | led_i = true; 910 | } else { 911 | led_i = false; 912 | } 913 | 914 | if (strcmp(force_pwr_decimals, "true") == 0) { 915 | forcePwrDecimals = true; 916 | } else { 917 | forcePwrDecimals = false; 918 | } 919 | 920 | if (shouldSaveConfig) { 921 | DEBUG_SERIAL.println("saving config"); 922 | preferences.putString("input_type", input_type); 923 | preferences.putString("mqtt_server", mqtt_server); 924 | preferences.putString("mqtt_port", mqtt_port); 925 | preferences.putString("query_period", query_period); 926 | preferences.putString("led_gpio", led_gpio); 927 | preferences.putString("led_gpio_i", led_gpio_i); 928 | preferences.putString("shelly_mac", shelly_mac); 929 | preferences.putString("mqtt_topic", mqtt_topic); 930 | preferences.putString("mqtt_user", mqtt_user); 931 | preferences.putString("mqtt_passwd", mqtt_passwd); 932 | preferences.putString("modbus_dev", modbus_dev); 933 | preferences.putString("power_path", power_path); 934 | preferences.putString("pwr_export_path", pwr_export_path); 935 | preferences.putString("power_l1_path", power_l1_path); 936 | preferences.putString("power_l2_path", power_l2_path); 937 | preferences.putString("power_l3_path", power_l3_path); 938 | preferences.putString("energy_in_path", energy_in_path); 939 | preferences.putString("energy_out_path", energy_out_path); 940 | preferences.putString("shelly_port", shelly_port); 941 | preferences.putString("force_pwr_decimals", force_pwr_decimals); 942 | preferences.putString("sma_id", sma_id); 943 | wifiManager.reboot(); 944 | } 945 | DEBUG_SERIAL.println("local ip"); 946 | DEBUG_SERIAL.println(WiFi.localIP()); 947 | } 948 | 949 | void setup(void) { 950 | DEBUG_SERIAL.begin(115200); 951 | WifiManagerSetup(); 952 | 953 | if (String(led_gpio).toInt() > 0) { 954 | led = String(led_gpio).toInt(); 955 | } 956 | 957 | if (led > 0) { 958 | pinMode(led, OUTPUT); 959 | if (led_i) { 960 | digitalWrite(led, LOW); 961 | } else { 962 | digitalWrite(led, HIGH); 963 | } 964 | } 965 | 966 | server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { 967 | request->send(200, "text/plain", "This is the Energy2Shelly for ESP converter!\r\nDevice and Energy status is available under /status\r\nTo reset configuration, goto /reset\r\n"); 968 | }); 969 | 970 | server.on("/status", HTTP_GET, [](AsyncWebServerRequest *request) { 971 | EMGetStatus(); 972 | request->send(200, "application/json", serJsonResponse); 973 | }); 974 | 975 | server.on("/reset", HTTP_GET, [](AsyncWebServerRequest *request) { 976 | shouldResetConfig = true; 977 | request->send(200, "text/plain", "Resetting WiFi configuration, please log back into the hotspot to reconfigure...\r\n"); 978 | }); 979 | 980 | server.on("/rpc/EM.GetStatus", HTTP_GET, [](AsyncWebServerRequest *request) { 981 | EMGetStatus(); 982 | request->send(200, "application/json", serJsonResponse); 983 | }); 984 | 985 | server.on("/rpc/EMData.GetStatus", HTTP_GET, [](AsyncWebServerRequest *request) { 986 | EMDataGetStatus(); 987 | request->send(200, "application/json", serJsonResponse); 988 | }); 989 | 990 | server.on("/rpc/EM.GetConfig", HTTP_GET, [](AsyncWebServerRequest *request) { 991 | EMGetConfig(); 992 | request->send(200, "application/json", serJsonResponse); 993 | }); 994 | 995 | server.on("/rpc/Shelly.GetDeviceInfo", HTTP_GET, [](AsyncWebServerRequest *request) { 996 | GetDeviceInfo(); 997 | request->send(200, "application/json", serJsonResponse); 998 | }); 999 | 1000 | server.on("/rpc", HTTP_POST, [](AsyncWebServerRequest *request) { 1001 | GetDeviceInfo(); 1002 | rpcWrapper(); 1003 | request->send(200, "application/json", serJsonResponse); 1004 | }); 1005 | 1006 | webSocket.onEvent(webSocketEvent); 1007 | server.addHandler(&webSocket); 1008 | server.begin(); 1009 | 1010 | // Set up RPC over UDP for Marstek users 1011 | UdpRPC.begin(String(shelly_port).toInt()); 1012 | 1013 | // Set up MQTT 1014 | if (dataMQTT) { 1015 | mqtt_client.setBufferSize(2048); 1016 | mqtt_client.setServer(mqtt_server, String(mqtt_port).toInt()); 1017 | mqtt_client.setCallback(mqtt_callback); 1018 | } 1019 | 1020 | // Set Up Multicast for SMA Energy Meter 1021 | if (dataSMA) { 1022 | Udp.begin(multicastPort); 1023 | #ifdef ESP8266 1024 | Udp.beginMulticast(WiFi.localIP(), multicastIP, multicastPort); 1025 | #else 1026 | Udp.beginMulticast(multicastIP, multicastPort); 1027 | #endif 1028 | } 1029 | 1030 | // Set Up UDP for SHRDZM smart meter interface 1031 | if (dataSHRDZM) { 1032 | Udp.begin(multicastPort); 1033 | } 1034 | 1035 | // Set Up Modbus TCP for SUNSPEC register query 1036 | if (dataSUNSPEC) { 1037 | modbus1.client(); 1038 | modbus_ip.fromString(mqtt_server); 1039 | if (!modbus1.isConnected(modbus_ip)) { // reuse mqtt server adresss for modbus adress 1040 | modbus1.connect(modbus_ip, String(mqtt_port).toInt()); 1041 | Serial.println("Trying to connect SUNSPEC powermeter data"); 1042 | } 1043 | } 1044 | 1045 | // Set Up HTTP query 1046 | if (dataHTTP) { 1047 | period = atol(query_period); 1048 | startMillis = millis(); 1049 | http.useHTTP10(true); 1050 | } 1051 | 1052 | // Set up mDNS responder 1053 | strcat(shelly_name, shelly_mac); 1054 | if (!MDNS.begin(shelly_name)) { 1055 | DEBUG_SERIAL.println("Error setting up MDNS responder!"); 1056 | } 1057 | 1058 | #ifdef ESP32 1059 | MDNS.addService("http", "tcp", 80); 1060 | MDNS.addService("shelly", "tcp", 80); 1061 | mdns_txt_item_t serviceTxtData[4] = { 1062 | { "fw_id", shelly_fw_id }, 1063 | { "arch", "esp8266" }, 1064 | { "id", shelly_name }, 1065 | { "gen", shelly_gen } 1066 | }; 1067 | mdns_service_instance_name_set("_http", "_tcp", shelly_name); 1068 | mdns_service_txt_set("_http", "_tcp", serviceTxtData, 4); 1069 | mdns_service_instance_name_set("_shelly", "_tcp", shelly_name); 1070 | mdns_service_txt_set("_shelly", "_tcp", serviceTxtData, 4); 1071 | #else 1072 | hMDNSService = MDNS.addService(0, "http", "tcp", 80); 1073 | hMDNSService2 = MDNS.addService(0, "shelly", "tcp", 80); 1074 | if (hMDNSService) { 1075 | MDNS.setServiceName(hMDNSService, shelly_name); 1076 | MDNS.addServiceTxt(hMDNSService, "fw_id", shelly_fw_id); 1077 | MDNS.addServiceTxt(hMDNSService, "arch", "esp8266"); 1078 | MDNS.addServiceTxt(hMDNSService, "id", shelly_name); 1079 | MDNS.addServiceTxt(hMDNSService, "gen", shelly_gen); 1080 | } 1081 | if (hMDNSService2) { 1082 | MDNS.setServiceName(hMDNSService2, shelly_name); 1083 | MDNS.addServiceTxt(hMDNSService2, "fw_id", shelly_fw_id); 1084 | MDNS.addServiceTxt(hMDNSService2, "arch", "esp8266"); 1085 | MDNS.addServiceTxt(hMDNSService2, "id", shelly_name); 1086 | MDNS.addServiceTxt(hMDNSService2, "gen", shelly_gen); 1087 | } 1088 | #endif 1089 | DEBUG_SERIAL.println("mDNS responder started"); 1090 | } 1091 | 1092 | void loop() { 1093 | #ifndef ESP32 1094 | MDNS.update(); 1095 | #endif 1096 | parseUdpRPC(); 1097 | if (shouldResetConfig) { 1098 | #ifdef ESP32 1099 | WiFi.disconnect(true, true); 1100 | #else 1101 | WiFi.disconnect(true); 1102 | #endif 1103 | delay(1000); 1104 | ESP.restart(); 1105 | } 1106 | if (dataMQTT) { 1107 | if (!mqtt_client.connected()) { 1108 | mqtt_reconnect(); 1109 | } 1110 | mqtt_client.loop(); 1111 | } 1112 | if (dataSMA) { 1113 | parseSMA(); 1114 | } 1115 | if (dataSHRDZM) { 1116 | parseSHRDZM(); 1117 | } 1118 | if (dataSUNSPEC) { 1119 | currentMillis = millis(); 1120 | if (currentMillis - startMillis_sunspec >= period) { 1121 | parseSUNSPEC(); 1122 | startMillis_sunspec = currentMillis; 1123 | } 1124 | 1125 | } 1126 | if (dataHTTP) { 1127 | currentMillis = millis(); 1128 | if (currentMillis - startMillis >= period) { 1129 | queryHTTP(); 1130 | startMillis = currentMillis; 1131 | } 1132 | } 1133 | handleblinkled(); 1134 | } 1135 | --------------------------------------------------------------------------------