├── ESP_Power_Sensor.pdf ├── KiCad PCB Files ├── Power Monitor Version 1.kicad_pcb ├── Power Monitor Version 1.pro └── Power Monitor Version 1.sch ├── PCB Gerber Files ├── Power Monitor Version 1-B.Cu.gbr ├── Power Monitor Version 1-B.Mask.gbr ├── Power Monitor Version 1-B.Paste.gbr ├── Power Monitor Version 1-B.SilkS.gbr ├── Power Monitor Version 1-Edge.Cuts.gbr ├── Power Monitor Version 1-F.Cu.gbr ├── Power Monitor Version 1-F.Mask.gbr ├── Power Monitor Version 1-F.Paste.gbr ├── Power Monitor Version 1-F.SilkS.gbr ├── Power Monitor Version 1-NPTH.drl └── Power Monitor Version 1-PTH.drl ├── README.md ├── WemosEM-Mqtt-Power-Sensor ├── .gitignore ├── .travis.yml ├── .vscode │ ├── extensions.json │ └── settings.json ├── WemosEM │ ├── WemosEM.ino │ ├── WiFiClientPrint.h │ ├── data │ │ ├── bootstrap.min.css │ │ ├── index.html │ │ ├── index.html.gz │ │ ├── index.html.gz.h │ │ ├── jquery-3.3.1.min.js │ │ └── wemosem.js │ ├── iot_platforms_support.h │ ├── mqtt_wifi_serial_support.h │ ├── ntp_support.h │ ├── power_meter_support.h │ ├── settings.h │ ├── variables.h │ └── webserver_support.h ├── firmware.map ├── html │ ├── index.html │ ├── switch.css │ └── wemosem.js ├── ld │ ├── eagle.app.v6.common.ld │ └── eagle.flash.4m1m.ld ├── lib │ ├── PubSubClient-EspEasy-2.7.12 │ │ ├── .gitignore │ │ ├── .travis.yml │ │ ├── CHANGES.txt │ │ ├── LICENSE.txt │ │ ├── README.md │ │ ├── examples │ │ │ ├── mqtt_auth │ │ │ │ └── mqtt_auth.ino │ │ │ ├── mqtt_basic │ │ │ │ └── mqtt_basic.ino │ │ │ ├── mqtt_esp8266 │ │ │ │ └── mqtt_esp8266.ino │ │ │ ├── mqtt_large_message │ │ │ │ └── mqtt_large_message.ino │ │ │ ├── mqtt_publish_in_callback │ │ │ │ └── mqtt_publish_in_callback.ino │ │ │ ├── mqtt_reconnect_nonblocking │ │ │ │ └── mqtt_reconnect_nonblocking.ino │ │ │ └── mqtt_stream │ │ │ │ └── mqtt_stream.ino │ │ ├── keywords.txt │ │ ├── library.json │ │ ├── library.properties │ │ ├── src │ │ │ ├── PubSubClient.cpp │ │ │ └── PubSubClient.h │ │ └── tests │ │ │ ├── .gitignore │ │ │ ├── Makefile │ │ │ ├── README.md │ │ │ ├── src │ │ │ ├── connect_spec.cpp │ │ │ ├── keepalive_spec.cpp │ │ │ ├── lib │ │ │ │ ├── Arduino.h │ │ │ │ ├── BDDTest.cpp │ │ │ │ ├── BDDTest.h │ │ │ │ ├── Buffer.cpp │ │ │ │ ├── Buffer.h │ │ │ │ ├── Client.h │ │ │ │ ├── IPAddress.cpp │ │ │ │ ├── IPAddress.h │ │ │ │ ├── Print.h │ │ │ │ ├── ShimClient.cpp │ │ │ │ ├── ShimClient.h │ │ │ │ ├── Stream.cpp │ │ │ │ ├── Stream.h │ │ │ │ └── trace.h │ │ │ ├── publish_spec.cpp │ │ │ ├── receive_spec.cpp │ │ │ └── subscribe_spec.cpp │ │ │ ├── testcases │ │ │ ├── __init__.py │ │ │ ├── mqtt_basic.py │ │ │ ├── mqtt_publish_in_callback.py │ │ │ └── settings.py │ │ │ └── testsuite.py │ ├── README │ └── WiFiManager │ │ ├── LICENSE │ │ ├── README.md │ │ ├── WiFiManager.cpp │ │ ├── WiFiManager.h │ │ ├── examples │ │ ├── AutoConnect │ │ │ └── AutoConnect.ino │ │ ├── AutoConnectWithFSParameters │ │ │ └── AutoConnectWithFSParameters.ino │ │ ├── AutoConnectWithFSParametersAndCustomIP │ │ │ └── AutoConnectWithFSParametersAndCustomIP.ino │ │ ├── AutoConnectWithFeedback │ │ │ └── AutoConnectWithFeedback.ino │ │ ├── AutoConnectWithFeedbackLED │ │ │ └── AutoConnectWithFeedbackLED.ino │ │ ├── AutoConnectWithReset │ │ │ └── AutoConnectWithReset.ino │ │ ├── AutoConnectWithStaticIP │ │ │ └── AutoConnectWithStaticIP.ino │ │ ├── AutoConnectWithTimeout │ │ │ └── AutoConnectWithTimeout.ino │ │ └── OnDemandConfigPortal │ │ │ └── OnDemandConfigPortal.ino │ │ ├── extras │ │ ├── WiFiManager.template.html │ │ ├── parse.js │ │ └── template.h │ │ ├── keywords.txt │ │ ├── library.json │ │ ├── library.properties │ │ └── travis │ │ └── common.sh ├── platformio.ini ├── symbols.sh └── test.html └── images ├── energy-meter-icon.gif ├── energy-meter-icon.png ├── energy-meter-icon.psd ├── favicon.ico ├── installation01.jpg ├── installation02.jpg ├── installation03.jpg ├── installation04.jpg ├── installation05.jpg ├── screenshot01.jpg ├── screenshot02.jpg ├── screenshot03.jpg ├── screenshot04.jpg ├── screenshot05.jpg └── wemos-sensor-stc013.jpg /ESP_Power_Sensor.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alcar21/WemosEM/90f029c280fc198d436d2481c994b29a755ef94b/ESP_Power_Sensor.pdf -------------------------------------------------------------------------------- /KiCad PCB Files/Power Monitor Version 1.pro: -------------------------------------------------------------------------------- 1 | update=22/05/2015 07:44:53 2 | version=1 3 | last_client=kicad 4 | [general] 5 | version=1 6 | RootSch= 7 | BoardNm= 8 | [pcbnew] 9 | version=1 10 | LastNetListRead= 11 | UseCmpFile=1 12 | PadDrill=0.600000000000 13 | PadDrillOvalY=0.600000000000 14 | PadSizeH=1.500000000000 15 | PadSizeV=1.500000000000 16 | PcbTextSizeV=1.500000000000 17 | PcbTextSizeH=1.500000000000 18 | PcbTextThickness=0.300000000000 19 | ModuleTextSizeV=1.000000000000 20 | ModuleTextSizeH=1.000000000000 21 | ModuleTextSizeThickness=0.150000000000 22 | SolderMaskClearance=0.000000000000 23 | SolderMaskMinWidth=0.000000000000 24 | DrawSegmentWidth=0.200000000000 25 | BoardOutlineThickness=0.100000000000 26 | ModuleOutlineThickness=0.150000000000 27 | [cvpcb] 28 | version=1 29 | NetIExt=net 30 | [eeschema] 31 | version=1 32 | LibDir= 33 | [eeschema/libraries] 34 | -------------------------------------------------------------------------------- /KiCad PCB Files/Power Monitor Version 1.sch: -------------------------------------------------------------------------------- 1 | EESchema Schematic File Version 4 2 | LIBS:Power Monitor Version 1-cache 3 | EELAYER 26 0 4 | EELAYER END 5 | $Descr A4 11693 8268 6 | encoding utf-8 7 | Sheet 1 1 8 | Title "ESP Power Sensor" 9 | Date "4th October 2018" 10 | Rev "1" 11 | Comp "" 12 | Comment1 "" 13 | Comment2 "" 14 | Comment3 "" 15 | Comment4 "" 16 | $EndDescr 17 | $Comp 18 | L DRM_Device:R R1 19 | U 1 1 5BB7258A 20 | P 4300 3450 21 | F 0 "R1" H 4370 3496 50 0000 L CNN 22 | F 1 "22R" H 4370 3405 50 0000 L CNN 23 | F 2 "DRM_Parts_General:Resistor_THT" V 4230 3450 50 0001 C CNN 24 | F 3 "~" H 4300 3450 50 0001 C CNN 25 | 1 4300 3450 26 | 1 0 0 -1 27 | $EndComp 28 | Wire Wire Line 29 | 4300 3125 4300 3300 30 | Wire Wire Line 31 | 4300 3800 4300 3600 32 | $Comp 33 | L DRM_ESP8266_WiFi:Wemos_D1_Mini M1 34 | U 1 1 5BB72746 35 | P 5950 3025 36 | F 0 "M1" H 6500 3350 50 0000 C CNN 37 | F 1 "Wemos_D1_Mini" H 6450 2075 50 0001 C CNN 38 | F 2 "DRM_ESP8266:Wemos D1 Mini" H 6550 2625 50 0001 C CNN 39 | F 3 "" H 6550 2625 50 0001 C CNN 40 | 1 5950 3025 41 | 1 0 0 -1 42 | $EndComp 43 | Wire Wire Line 44 | 4300 3125 5950 3125 45 | Connection ~ 4300 3125 46 | $Comp 47 | L DRM_Device:R R3 48 | U 1 1 5BB72888 49 | P 5000 4175 50 | F 0 "R3" H 5070 4221 50 0000 L CNN 51 | F 1 "10K" H 5070 4130 50 0000 L CNN 52 | F 2 "DRM_Parts_General:Resistor_THT" V 4930 4175 50 0001 C CNN 53 | F 3 "~" H 5000 4175 50 0001 C CNN 54 | 1 5000 4175 55 | 1 0 0 -1 56 | $EndComp 57 | $Comp 58 | L DRM_Device:R R2 59 | U 1 1 5BB72928 60 | P 5000 3450 61 | F 0 "R2" H 5070 3496 50 0000 L CNN 62 | F 1 "10K" H 5070 3405 50 0000 L CNN 63 | F 2 "DRM_Parts_General:Resistor_THT" V 4930 3450 50 0001 C CNN 64 | F 3 "~" H 5000 3450 50 0001 C CNN 65 | 1 5000 3450 66 | 1 0 0 -1 67 | $EndComp 68 | Wire Wire Line 69 | 5000 3600 5000 3800 70 | Wire Wire Line 71 | 4300 3800 5000 3800 72 | Connection ~ 4300 3800 73 | Connection ~ 5000 3800 74 | Wire Wire Line 75 | 5000 3800 5000 4025 76 | $Comp 77 | L DRM_Power:+3V3 #PWR02 78 | U 1 1 5BB72A64 79 | P 5000 2800 80 | F 0 "#PWR02" H 5000 2650 50 0001 C CNN 81 | F 1 "+3V3" H 5015 2973 50 0000 C CNN 82 | F 2 "" H 5000 2800 50 0001 C CNN 83 | F 3 "" H 5000 2800 50 0001 C CNN 84 | 1 5000 2800 85 | 1 0 0 -1 86 | $EndComp 87 | Wire Wire Line 88 | 5000 2800 5000 3300 89 | $Comp 90 | L DRM_Power:GND #PWR03 91 | U 1 1 5BB72B4B 92 | P 5000 4525 93 | F 0 "#PWR03" H 5000 4275 50 0001 C CNN 94 | F 1 "GND" H 5005 4352 50 0000 C CNN 95 | F 2 "" H 5000 4525 50 0001 C CNN 96 | F 3 "" H 5000 4525 50 0001 C CNN 97 | 1 5000 4525 98 | 1 0 0 -1 99 | $EndComp 100 | Wire Wire Line 101 | 5000 4525 5000 4325 102 | $Comp 103 | L DRM_Device:CP C1 104 | U 1 1 5BB72C86 105 | P 4300 4200 106 | F 0 "C1" H 4418 4246 50 0000 L CNN 107 | F 1 "10uF 25V" H 3825 4100 50 0000 L CNN 108 | F 2 "DRM_Parts_General:Cap_5mm_THT" H 4338 4050 50 0001 C CNN 109 | F 3 "~" H 4300 4200 50 0001 C CNN 110 | 1 4300 4200 111 | 1 0 0 -1 112 | $EndComp 113 | $Comp 114 | L DRM_Power:GND #PWR01 115 | U 1 1 5BB72D06 116 | P 4300 4525 117 | F 0 "#PWR01" H 4300 4275 50 0001 C CNN 118 | F 1 "GND" H 4305 4352 50 0000 C CNN 119 | F 2 "" H 4300 4525 50 0001 C CNN 120 | F 3 "" H 4300 4525 50 0001 C CNN 121 | 1 4300 4525 122 | 1 0 0 -1 123 | $EndComp 124 | Wire Wire Line 125 | 4300 4525 4300 4350 126 | Wire Wire Line 127 | 4300 4050 4300 3800 128 | Wire Wire Line 129 | 5950 3725 5500 3725 130 | Wire Wire Line 131 | 5500 3725 5500 2800 132 | $Comp 133 | L DRM_Power:+3V3 #PWR04 134 | U 1 1 5BB730F7 135 | P 5500 2800 136 | F 0 "#PWR04" H 5500 2650 50 0001 C CNN 137 | F 1 "+3V3" H 5515 2973 50 0000 C CNN 138 | F 2 "" H 5500 2800 50 0001 C CNN 139 | F 3 "" H 5500 2800 50 0001 C CNN 140 | 1 5500 2800 141 | 1 0 0 -1 142 | $EndComp 143 | Wire Wire Line 144 | 7050 3625 7250 3625 145 | Wire Wire Line 146 | 7250 3625 7250 4525 147 | $Comp 148 | L DRM_Power:GND #PWR05 149 | U 1 1 5BB7324D 150 | P 7250 4525 151 | F 0 "#PWR05" H 7250 4275 50 0001 C CNN 152 | F 1 "GND" H 7255 4352 50 0000 C CNN 153 | F 2 "" H 7250 4525 50 0001 C CNN 154 | F 3 "" H 7250 4525 50 0001 C CNN 155 | 1 7250 4525 156 | 1 0 0 -1 157 | $EndComp 158 | Wire Wire Line 159 | 7050 3525 7875 3525 160 | $Comp 161 | L DRM_Device:R R4 162 | U 1 1 5BB734A4 163 | P 7875 3825 164 | F 0 "R4" H 7945 3871 50 0000 L CNN 165 | F 1 "1K" H 7945 3780 50 0000 L CNN 166 | F 2 "DRM_Parts_General:Resistor_THT" V 7805 3825 50 0001 C CNN 167 | F 3 "~" H 7875 3825 50 0001 C CNN 168 | 1 7875 3825 169 | 1 0 0 -1 170 | $EndComp 171 | Wire Wire Line 172 | 7875 3675 7875 3525 173 | $Comp 174 | L DRM_Device:LED D1 175 | U 1 1 5BB7372C 176 | P 7875 4250 177 | F 0 "D1" V 7829 4328 50 0000 L CNN 178 | F 1 "LED" V 7920 4328 50 0000 L CNN 179 | F 2 "DRM_LED_Display:LED 5mm" H 7880 4250 50 0001 C CNN 180 | F 3 "~" H 7880 4250 50 0001 C CNN 181 | 1 7875 4250 182 | 0 1 1 0 183 | $EndComp 184 | $Comp 185 | L DRM_Power:GND #PWR0101 186 | U 1 1 5BB7379F 187 | P 7875 4525 188 | F 0 "#PWR0101" H 7875 4275 50 0001 C CNN 189 | F 1 "GND" H 7880 4352 50 0000 C CNN 190 | F 2 "" H 7875 4525 50 0001 C CNN 191 | F 3 "" H 7875 4525 50 0001 C CNN 192 | 1 7875 4525 193 | 1 0 0 -1 194 | $EndComp 195 | Wire Wire Line 196 | 7875 4100 7875 3975 197 | Wire Wire Line 198 | 7875 4400 7875 4525 199 | $Comp 200 | L DRM_Conectors:Jack_3.5mm J1 201 | U 1 1 5BB74853 202 | P 3250 3600 203 | F 0 "J1" H 2548 3617 50 0000 R CNN 204 | F 1 "3.5mm Jack Socket - PJ-307" H 2815 3910 50 0001 C CNN 205 | F 2 "DRM_Connectors:Jack_3.5_PJ-307" H 3250 3600 50 0001 C CNN 206 | F 3 "" H 3250 3600 50 0001 C CNN 207 | 1 3250 3600 208 | 1 0 0 1 209 | $EndComp 210 | Wire Wire Line 211 | 3250 3800 4300 3800 212 | Wire Wire Line 213 | 3450 3125 3450 3400 214 | Wire Wire Line 215 | 3450 3400 3250 3400 216 | Wire Wire Line 217 | 3450 3125 4300 3125 218 | Wire Wire Line 219 | 3250 3700 3450 3700 220 | Wire Wire Line 221 | 3450 3700 3450 3600 222 | Connection ~ 3450 3400 223 | Wire Wire Line 224 | 3250 3600 3450 3600 225 | Connection ~ 3450 3600 226 | Wire Wire Line 227 | 3450 3600 3450 3500 228 | Wire Wire Line 229 | 3250 3500 3450 3500 230 | Connection ~ 3450 3500 231 | Wire Wire Line 232 | 3450 3500 3450 3400 233 | NoConn ~ 7050 3025 234 | NoConn ~ 7050 3125 235 | NoConn ~ 7050 3225 236 | NoConn ~ 7050 3325 237 | NoConn ~ 7050 3425 238 | NoConn ~ 7050 3725 239 | NoConn ~ 5950 3625 240 | NoConn ~ 5950 3525 241 | NoConn ~ 5950 3425 242 | NoConn ~ 5950 3325 243 | NoConn ~ 5950 3225 244 | NoConn ~ 5950 3025 245 | $EndSCHEMATC 246 | -------------------------------------------------------------------------------- /PCB Gerber Files/Power Monitor Version 1-B.Mask.gbr: -------------------------------------------------------------------------------- 1 | G04 #@! TF.GenerationSoftware,KiCad,Pcbnew,5.0.0-fee4fd1~65~ubuntu17.10.1* 2 | G04 #@! TF.CreationDate,2018-11-13T13:37:27+00:00* 3 | G04 #@! TF.ProjectId,Power Monitor Version 1,506F776572204D6F6E69746F72205665,rev?* 4 | G04 #@! TF.SameCoordinates,Original* 5 | G04 #@! TF.FileFunction,Soldermask,Bot* 6 | G04 #@! TF.FilePolarity,Negative* 7 | %FSLAX46Y46*% 8 | G04 Gerber Fmt 4.6, Leading zero omitted, Abs format (unit mm)* 9 | G04 Created by KiCad (PCBNEW 5.0.0-fee4fd1~65~ubuntu17.10.1) date Tue Nov 13 13:37:27 2018* 10 | %MOMM*% 11 | %LPD*% 12 | G01* 13 | G04 APERTURE LIST* 14 | %ADD10R,1.900000X1.900000*% 15 | %ADD11C,1.900000*% 16 | %ADD12R,1.924000X1.924000*% 17 | %ADD13C,1.924000*% 18 | %ADD14C,1.200000*% 19 | %ADD15C,2.400000*% 20 | %ADD16C,3.400000*% 21 | %ADD17R,2.200000X2.200000*% 22 | %ADD18C,2.200000*% 23 | G04 APERTURE END LIST* 24 | D10* 25 | G04 #@! TO.C,C1* 26 | X129540000Y-73025000D03* 27 | D11* 28 | X129540000Y-75057000D03* 29 | G04 #@! TD* 30 | D12* 31 | G04 #@! TO.C,D1* 32 | X134493000Y-74422000D03* 33 | D13* 34 | X137033000Y-74422000D03* 35 | G04 #@! TD* 36 | D14* 37 | G04 #@! TO.C,J1* 38 | X135763000Y-102743000D03* 39 | X130683000Y-107823000D03* 40 | X130683000Y-110363000D03* 41 | X140843000Y-107823000D03* 42 | X140843000Y-110363000D03* 43 | D15* 44 | X133223000Y-102743000D03* 45 | X130683000Y-102743000D03* 46 | X138303000Y-102743000D03* 47 | X140843000Y-102743000D03* 48 | D16* 49 | X135763000Y-107823000D03* 50 | G04 #@! TD* 51 | D17* 52 | G04 #@! TO.C,M1* 53 | X124027001Y-85292001D03* 54 | D18* 55 | X124027001Y-87832001D03* 56 | X124027001Y-90372001D03* 57 | X124027001Y-92912001D03* 58 | X124027001Y-95452001D03* 59 | X124027001Y-97992001D03* 60 | X124027001Y-100532001D03* 61 | X147522001Y-103072001D03* 62 | X147522001Y-100532001D03* 63 | X147522001Y-97992001D03* 64 | X147522001Y-95452001D03* 65 | X147522001Y-92912001D03* 66 | X147522001Y-90372001D03* 67 | X124027001Y-103072001D03* 68 | X147522001Y-87832001D03* 69 | X147522001Y-85292001D03* 70 | G04 #@! TD* 71 | D13* 72 | G04 #@! TO.C,R1* 73 | X131826000Y-96520000D03* 74 | X140081000Y-96520000D03* 75 | G04 #@! TD* 76 | G04 #@! TO.C,R2* 77 | X131826000Y-88900000D03* 78 | X140081000Y-88900000D03* 79 | G04 #@! TD* 80 | G04 #@! TO.C,R3* 81 | X131826000Y-92710000D03* 82 | X140081000Y-92710000D03* 83 | G04 #@! TD* 84 | G04 #@! TO.C,R4* 85 | X131826000Y-85090000D03* 86 | X140081000Y-85090000D03* 87 | G04 #@! TD* 88 | M02* 89 | -------------------------------------------------------------------------------- /PCB Gerber Files/Power Monitor Version 1-B.Paste.gbr: -------------------------------------------------------------------------------- 1 | G04 #@! TF.GenerationSoftware,KiCad,Pcbnew,5.0.0-fee4fd1~65~ubuntu17.10.1* 2 | G04 #@! TF.CreationDate,2018-11-13T13:37:27+00:00* 3 | G04 #@! TF.ProjectId,Power Monitor Version 1,506F776572204D6F6E69746F72205665,rev?* 4 | G04 #@! TF.SameCoordinates,Original* 5 | G04 #@! TF.FileFunction,Paste,Bot* 6 | G04 #@! TF.FilePolarity,Positive* 7 | %FSLAX46Y46*% 8 | G04 Gerber Fmt 4.6, Leading zero omitted, Abs format (unit mm)* 9 | G04 Created by KiCad (PCBNEW 5.0.0-fee4fd1~65~ubuntu17.10.1) date Tue Nov 13 13:37:27 2018* 10 | %MOMM*% 11 | %LPD*% 12 | G01* 13 | G04 APERTURE LIST* 14 | G04 APERTURE END LIST* 15 | M02* 16 | -------------------------------------------------------------------------------- /PCB Gerber Files/Power Monitor Version 1-B.SilkS.gbr: -------------------------------------------------------------------------------- 1 | G04 #@! TF.GenerationSoftware,KiCad,Pcbnew,5.0.0-fee4fd1~65~ubuntu17.10.1* 2 | G04 #@! TF.CreationDate,2018-11-13T13:37:27+00:00* 3 | G04 #@! TF.ProjectId,Power Monitor Version 1,506F776572204D6F6E69746F72205665,rev?* 4 | G04 #@! TF.SameCoordinates,Original* 5 | G04 #@! TF.FileFunction,Legend,Bot* 6 | G04 #@! TF.FilePolarity,Positive* 7 | %FSLAX46Y46*% 8 | G04 Gerber Fmt 4.6, Leading zero omitted, Abs format (unit mm)* 9 | G04 Created by KiCad (PCBNEW 5.0.0-fee4fd1~65~ubuntu17.10.1) date Tue Nov 13 13:37:27 2018* 10 | %MOMM*% 11 | %LPD*% 12 | G01* 13 | G04 APERTURE LIST* 14 | %ADD10C,0.300000*% 15 | G04 APERTURE END LIST* 16 | D10* 17 | X141104285Y-80458571D02* 18 | X140604285Y-81958571D01* 19 | X140104285Y-80458571D01* 20 | X139032857Y-81887142D02* 21 | X139175714Y-81958571D01* 22 | X139461428Y-81958571D01* 23 | X139604285Y-81887142D01* 24 | X139675714Y-81744285D01* 25 | X139675714Y-81172857D01* 26 | X139604285Y-81030000D01* 27 | X139461428Y-80958571D01* 28 | X139175714Y-80958571D01* 29 | X139032857Y-81030000D01* 30 | X138961428Y-81172857D01* 31 | X138961428Y-81315714D01* 32 | X139675714Y-81458571D01* 33 | X138318571Y-81958571D02* 34 | X138318571Y-80958571D01* 35 | X138318571Y-81244285D02* 36 | X138247142Y-81101428D01* 37 | X138175714Y-81030000D01* 38 | X138032857Y-80958571D01* 39 | X137890000Y-80958571D01* 40 | X137461428Y-81887142D02* 41 | X137318571Y-81958571D01* 42 | X137032857Y-81958571D01* 43 | X136890000Y-81887142D01* 44 | X136818571Y-81744285D01* 45 | X136818571Y-81672857D01* 46 | X136890000Y-81530000D01* 47 | X137032857Y-81458571D01* 48 | X137247142Y-81458571D01* 49 | X137390000Y-81387142D01* 50 | X137461428Y-81244285D01* 51 | X137461428Y-81172857D01* 52 | X137390000Y-81030000D01* 53 | X137247142Y-80958571D01* 54 | X137032857Y-80958571D01* 55 | X136890000Y-81030000D01* 56 | X136175714Y-81958571D02* 57 | X136175714Y-80958571D01* 58 | X136175714Y-80458571D02* 59 | X136247142Y-80530000D01* 60 | X136175714Y-80601428D01* 61 | X136104285Y-80530000D01* 62 | X136175714Y-80458571D01* 63 | X136175714Y-80601428D01* 64 | X135247142Y-81958571D02* 65 | X135390000Y-81887142D01* 66 | X135461428Y-81815714D01* 67 | X135532857Y-81672857D01* 68 | X135532857Y-81244285D01* 69 | X135461428Y-81101428D01* 70 | X135390000Y-81030000D01* 71 | X135247142Y-80958571D01* 72 | X135032857Y-80958571D01* 73 | X134890000Y-81030000D01* 74 | X134818571Y-81101428D01* 75 | X134747142Y-81244285D01* 76 | X134747142Y-81672857D01* 77 | X134818571Y-81815714D01* 78 | X134890000Y-81887142D01* 79 | X135032857Y-81958571D01* 80 | X135247142Y-81958571D01* 81 | X134104285Y-80958571D02* 82 | X134104285Y-81958571D01* 83 | X134104285Y-81101428D02* 84 | X134032857Y-81030000D01* 85 | X133890000Y-80958571D01* 86 | X133675714Y-80958571D01* 87 | X133532857Y-81030000D01* 88 | X133461428Y-81172857D01* 89 | X133461428Y-81958571D01* 90 | X130818571Y-81958571D02* 91 | X131675714Y-81958571D01* 92 | X131247142Y-81958571D02* 93 | X131247142Y-80458571D01* 94 | X131390000Y-80672857D01* 95 | X131532857Y-80815714D01* 96 | X131675714Y-80887142D01* 97 | X146282857Y-78632857D02* 98 | X145782857Y-78632857D01* 99 | X145568571Y-79418571D02* 100 | X146282857Y-79418571D01* 101 | X146282857Y-77918571D01* 102 | X145568571Y-77918571D01* 103 | X144997142Y-79347142D02* 104 | X144782857Y-79418571D01* 105 | X144425714Y-79418571D01* 106 | X144282857Y-79347142D01* 107 | X144211428Y-79275714D01* 108 | X144140000Y-79132857D01* 109 | X144140000Y-78990000D01* 110 | X144211428Y-78847142D01* 111 | X144282857Y-78775714D01* 112 | X144425714Y-78704285D01* 113 | X144711428Y-78632857D01* 114 | X144854285Y-78561428D01* 115 | X144925714Y-78490000D01* 116 | X144997142Y-78347142D01* 117 | X144997142Y-78204285D01* 118 | X144925714Y-78061428D01* 119 | X144854285Y-77990000D01* 120 | X144711428Y-77918571D01* 121 | X144354285Y-77918571D01* 122 | X144140000Y-77990000D01* 123 | X143497142Y-79418571D02* 124 | X143497142Y-77918571D01* 125 | X142925714Y-77918571D01* 126 | X142782857Y-77990000D01* 127 | X142711428Y-78061428D01* 128 | X142640000Y-78204285D01* 129 | X142640000Y-78418571D01* 130 | X142711428Y-78561428D01* 131 | X142782857Y-78632857D01* 132 | X142925714Y-78704285D01* 133 | X143497142Y-78704285D01* 134 | X141997142Y-78847142D02* 135 | X140854285Y-78847142D01* 136 | X140140000Y-79418571D02* 137 | X140140000Y-77918571D01* 138 | X139568571Y-77918571D01* 139 | X139425714Y-77990000D01* 140 | X139354285Y-78061428D01* 141 | X139282857Y-78204285D01* 142 | X139282857Y-78418571D01* 143 | X139354285Y-78561428D01* 144 | X139425714Y-78632857D01* 145 | X139568571Y-78704285D01* 146 | X140140000Y-78704285D01* 147 | X138425714Y-79418571D02* 148 | X138568571Y-79347142D01* 149 | X138640000Y-79275714D01* 150 | X138711428Y-79132857D01* 151 | X138711428Y-78704285D01* 152 | X138640000Y-78561428D01* 153 | X138568571Y-78490000D01* 154 | X138425714Y-78418571D01* 155 | X138211428Y-78418571D01* 156 | X138068571Y-78490000D01* 157 | X137997142Y-78561428D01* 158 | X137925714Y-78704285D01* 159 | X137925714Y-79132857D01* 160 | X137997142Y-79275714D01* 161 | X138068571Y-79347142D01* 162 | X138211428Y-79418571D01* 163 | X138425714Y-79418571D01* 164 | X137425714Y-78418571D02* 165 | X137140000Y-79418571D01* 166 | X136854285Y-78704285D01* 167 | X136568571Y-79418571D01* 168 | X136282857Y-78418571D01* 169 | X135140000Y-79347142D02* 170 | X135282857Y-79418571D01* 171 | X135568571Y-79418571D01* 172 | X135711428Y-79347142D01* 173 | X135782857Y-79204285D01* 174 | X135782857Y-78632857D01* 175 | X135711428Y-78490000D01* 176 | X135568571Y-78418571D01* 177 | X135282857Y-78418571D01* 178 | X135140000Y-78490000D01* 179 | X135068571Y-78632857D01* 180 | X135068571Y-78775714D01* 181 | X135782857Y-78918571D01* 182 | X134425714Y-79418571D02* 183 | X134425714Y-78418571D01* 184 | X134425714Y-78704285D02* 185 | X134354285Y-78561428D01* 186 | X134282857Y-78490000D01* 187 | X134140000Y-78418571D01* 188 | X133997142Y-78418571D01* 189 | X132425714Y-79347142D02* 190 | X132211428Y-79418571D01* 191 | X131854285Y-79418571D01* 192 | X131711428Y-79347142D01* 193 | X131640000Y-79275714D01* 194 | X131568571Y-79132857D01* 195 | X131568571Y-78990000D01* 196 | X131640000Y-78847142D01* 197 | X131711428Y-78775714D01* 198 | X131854285Y-78704285D01* 199 | X132140000Y-78632857D01* 200 | X132282857Y-78561428D01* 201 | X132354285Y-78490000D01* 202 | X132425714Y-78347142D01* 203 | X132425714Y-78204285D01* 204 | X132354285Y-78061428D01* 205 | X132282857Y-77990000D01* 206 | X132140000Y-77918571D01* 207 | X131782857Y-77918571D01* 208 | X131568571Y-77990000D01* 209 | X130354285Y-79347142D02* 210 | X130497142Y-79418571D01* 211 | X130782857Y-79418571D01* 212 | X130925714Y-79347142D01* 213 | X130997142Y-79204285D01* 214 | X130997142Y-78632857D01* 215 | X130925714Y-78490000D01* 216 | X130782857Y-78418571D01* 217 | X130497142Y-78418571D01* 218 | X130354285Y-78490000D01* 219 | X130282857Y-78632857D01* 220 | X130282857Y-78775714D01* 221 | X130997142Y-78918571D01* 222 | X129640000Y-78418571D02* 223 | X129640000Y-79418571D01* 224 | X129640000Y-78561428D02* 225 | X129568571Y-78490000D01* 226 | X129425714Y-78418571D01* 227 | X129211428Y-78418571D01* 228 | X129068571Y-78490000D01* 229 | X128997142Y-78632857D01* 230 | X128997142Y-79418571D01* 231 | X128354285Y-79347142D02* 232 | X128211428Y-79418571D01* 233 | X127925714Y-79418571D01* 234 | X127782857Y-79347142D01* 235 | X127711428Y-79204285D01* 236 | X127711428Y-79132857D01* 237 | X127782857Y-78990000D01* 238 | X127925714Y-78918571D01* 239 | X128140000Y-78918571D01* 240 | X128282857Y-78847142D01* 241 | X128354285Y-78704285D01* 242 | X128354285Y-78632857D01* 243 | X128282857Y-78490000D01* 244 | X128140000Y-78418571D01* 245 | X127925714Y-78418571D01* 246 | X127782857Y-78490000D01* 247 | X126854285Y-79418571D02* 248 | X126997142Y-79347142D01* 249 | X127068571Y-79275714D01* 250 | X127140000Y-79132857D01* 251 | X127140000Y-78704285D01* 252 | X127068571Y-78561428D01* 253 | X126997142Y-78490000D01* 254 | X126854285Y-78418571D01* 255 | X126640000Y-78418571D01* 256 | X126497142Y-78490000D01* 257 | X126425714Y-78561428D01* 258 | X126354285Y-78704285D01* 259 | X126354285Y-79132857D01* 260 | X126425714Y-79275714D01* 261 | X126497142Y-79347142D01* 262 | X126640000Y-79418571D01* 263 | X126854285Y-79418571D01* 264 | X125711428Y-79418571D02* 265 | X125711428Y-78418571D01* 266 | X125711428Y-78704285D02* 267 | X125640000Y-78561428D01* 268 | X125568571Y-78490000D01* 269 | X125425714Y-78418571D01* 270 | X125282857Y-78418571D01* 271 | M02* 272 | -------------------------------------------------------------------------------- /PCB Gerber Files/Power Monitor Version 1-Edge.Cuts.gbr: -------------------------------------------------------------------------------- 1 | G04 #@! TF.GenerationSoftware,KiCad,Pcbnew,5.0.0-fee4fd1~65~ubuntu17.10.1* 2 | G04 #@! TF.CreationDate,2018-11-13T13:37:27+00:00* 3 | G04 #@! TF.ProjectId,Power Monitor Version 1,506F776572204D6F6E69746F72205665,rev?* 4 | G04 #@! TF.SameCoordinates,Original* 5 | G04 #@! TF.FileFunction,Profile,NP* 6 | %FSLAX46Y46*% 7 | G04 Gerber Fmt 4.6, Leading zero omitted, Abs format (unit mm)* 8 | G04 Created by KiCad (PCBNEW 5.0.0-fee4fd1~65~ubuntu17.10.1) date Tue Nov 13 13:37:27 2018* 9 | %MOMM*% 10 | %LPD*% 11 | G01* 12 | G04 APERTURE LIST* 13 | %ADD10C,0.150000*% 14 | G04 APERTURE END LIST* 15 | D10* 16 | X138557000Y-110363000D02* 17 | X138557000Y-111887000D01* 18 | X132969000Y-110363000D02* 19 | X138557000Y-110363000D01* 20 | X132969000Y-111887000D02* 21 | X132969000Y-110363000D01* 22 | X132969000Y-111887000D02* 23 | X121729500Y-111887000D01* 24 | X149796500Y-111887000D02* 25 | X138557000Y-111887000D01* 26 | X151828500Y-73152000D02* 27 | X151828500Y-109855000D01* 28 | X121729500Y-71120000D02* 29 | X149796500Y-71120000D01* 30 | X119697500Y-109855000D02* 31 | X119697500Y-73152000D01* 32 | X121729500Y-111887000D02* 33 | G75* 34 | G02X119697500Y-109855000I0J2032000D01* 35 | G01* 36 | X119697500Y-73152000D02* 37 | G75* 38 | G02X121729500Y-71120000I2032000J0D01* 39 | G01* 40 | X149796500Y-71120000D02* 41 | G75* 42 | G02X151828500Y-73152000I0J-2032000D01* 43 | G01* 44 | X151828500Y-109855000D02* 45 | G75* 46 | G02X149796500Y-111887000I-2032000J0D01* 47 | G01* 48 | M02* 49 | -------------------------------------------------------------------------------- /PCB Gerber Files/Power Monitor Version 1-F.Mask.gbr: -------------------------------------------------------------------------------- 1 | G04 #@! TF.GenerationSoftware,KiCad,Pcbnew,5.0.0-fee4fd1~65~ubuntu17.10.1* 2 | G04 #@! TF.CreationDate,2018-11-13T13:37:27+00:00* 3 | G04 #@! TF.ProjectId,Power Monitor Version 1,506F776572204D6F6E69746F72205665,rev?* 4 | G04 #@! TF.SameCoordinates,Original* 5 | G04 #@! TF.FileFunction,Soldermask,Top* 6 | G04 #@! TF.FilePolarity,Negative* 7 | %FSLAX46Y46*% 8 | G04 Gerber Fmt 4.6, Leading zero omitted, Abs format (unit mm)* 9 | G04 Created by KiCad (PCBNEW 5.0.0-fee4fd1~65~ubuntu17.10.1) date Tue Nov 13 13:37:27 2018* 10 | %MOMM*% 11 | %LPD*% 12 | G01* 13 | G04 APERTURE LIST* 14 | %ADD10R,1.900000X1.900000*% 15 | %ADD11C,1.900000*% 16 | %ADD12R,1.924000X1.924000*% 17 | %ADD13C,1.924000*% 18 | %ADD14C,1.200000*% 19 | %ADD15C,2.400000*% 20 | %ADD16C,3.400000*% 21 | %ADD17R,2.200000X2.200000*% 22 | %ADD18C,2.200000*% 23 | G04 APERTURE END LIST* 24 | D10* 25 | G04 #@! TO.C,C1* 26 | X129540000Y-73025000D03* 27 | D11* 28 | X129540000Y-75057000D03* 29 | G04 #@! TD* 30 | D12* 31 | G04 #@! TO.C,D1* 32 | X134493000Y-74422000D03* 33 | D13* 34 | X137033000Y-74422000D03* 35 | G04 #@! TD* 36 | D14* 37 | G04 #@! TO.C,J1* 38 | X135763000Y-102743000D03* 39 | X130683000Y-107823000D03* 40 | X130683000Y-110363000D03* 41 | X140843000Y-107823000D03* 42 | X140843000Y-110363000D03* 43 | D15* 44 | X133223000Y-102743000D03* 45 | X130683000Y-102743000D03* 46 | X138303000Y-102743000D03* 47 | X140843000Y-102743000D03* 48 | D16* 49 | X135763000Y-107823000D03* 50 | G04 #@! TD* 51 | D17* 52 | G04 #@! TO.C,M1* 53 | X124027001Y-85292001D03* 54 | D18* 55 | X124027001Y-87832001D03* 56 | X124027001Y-90372001D03* 57 | X124027001Y-92912001D03* 58 | X124027001Y-95452001D03* 59 | X124027001Y-97992001D03* 60 | X124027001Y-100532001D03* 61 | X147522001Y-103072001D03* 62 | X147522001Y-100532001D03* 63 | X147522001Y-97992001D03* 64 | X147522001Y-95452001D03* 65 | X147522001Y-92912001D03* 66 | X147522001Y-90372001D03* 67 | X124027001Y-103072001D03* 68 | X147522001Y-87832001D03* 69 | X147522001Y-85292001D03* 70 | G04 #@! TD* 71 | D13* 72 | G04 #@! TO.C,R1* 73 | X131826000Y-96520000D03* 74 | X140081000Y-96520000D03* 75 | G04 #@! TD* 76 | G04 #@! TO.C,R2* 77 | X131826000Y-88900000D03* 78 | X140081000Y-88900000D03* 79 | G04 #@! TD* 80 | G04 #@! TO.C,R3* 81 | X131826000Y-92710000D03* 82 | X140081000Y-92710000D03* 83 | G04 #@! TD* 84 | G04 #@! TO.C,R4* 85 | X131826000Y-85090000D03* 86 | X140081000Y-85090000D03* 87 | G04 #@! TD* 88 | M02* 89 | -------------------------------------------------------------------------------- /PCB Gerber Files/Power Monitor Version 1-F.Paste.gbr: -------------------------------------------------------------------------------- 1 | G04 #@! TF.GenerationSoftware,KiCad,Pcbnew,5.0.0-fee4fd1~65~ubuntu17.10.1* 2 | G04 #@! TF.CreationDate,2018-11-13T13:37:27+00:00* 3 | G04 #@! TF.ProjectId,Power Monitor Version 1,506F776572204D6F6E69746F72205665,rev?* 4 | G04 #@! TF.SameCoordinates,Original* 5 | G04 #@! TF.FileFunction,Paste,Top* 6 | G04 #@! TF.FilePolarity,Positive* 7 | %FSLAX46Y46*% 8 | G04 Gerber Fmt 4.6, Leading zero omitted, Abs format (unit mm)* 9 | G04 Created by KiCad (PCBNEW 5.0.0-fee4fd1~65~ubuntu17.10.1) date Tue Nov 13 13:37:27 2018* 10 | %MOMM*% 11 | %LPD*% 12 | G01* 13 | G04 APERTURE LIST* 14 | G04 APERTURE END LIST* 15 | M02* 16 | -------------------------------------------------------------------------------- /PCB Gerber Files/Power Monitor Version 1-NPTH.drl: -------------------------------------------------------------------------------- 1 | M48 2 | ;DRILL file {KiCad 5.0.0-fee4fd1~65~ubuntu17.10.1} date Tue Nov 13 13:37:22 2018 3 | ;FORMAT={-:-/ absolute / inch / decimal} 4 | FMAT,2 5 | INCH,TZ 6 | T1C0.0315 7 | % 8 | G90 9 | G05 10 | M72 11 | T1 12 | X5.145Y-4.245 13 | X5.145Y-4.345 14 | X5.345Y-4.045 15 | X5.545Y-4.245 16 | X5.545Y-4.345 17 | T0 18 | M30 19 | -------------------------------------------------------------------------------- /PCB Gerber Files/Power Monitor Version 1-PTH.drl: -------------------------------------------------------------------------------- 1 | M48 2 | ;DRILL file {KiCad 5.0.0-fee4fd1~65~ubuntu17.10.1} date Tue Nov 13 13:37:22 2018 3 | ;FORMAT={-:-/ absolute / inch / decimal} 4 | FMAT,2 5 | INCH,TZ 6 | T1C0.0157 7 | T2C0.0236 8 | T3C0.0300 9 | T4C0.0315 10 | T5C0.0394 11 | T6C0.0433 12 | T7C0.0472 13 | % 14 | G90 15 | G05 16 | M72 17 | T1 18 | X4.8Y-3.05 19 | X4.8Y-3.15 20 | X4.8Y-3.6 21 | X4.8Y-3.8 22 | X4.85Y-4.2 23 | X4.9Y-3.05 24 | X4.9Y-3.15 25 | X4.95Y-3.6 26 | X4.95Y-3.8 27 | X4.95Y-4.2 28 | X4.95Y-4.3 29 | X5.Y-3.05 30 | X5.Y-3.15 31 | X5.04Y-3.545 32 | X5.05Y-3.4 33 | X5.085Y-3.725 34 | X5.24Y-3.2 35 | X5.285Y-3.09 36 | X5.35Y-3.5 37 | X5.35Y-3.6 38 | X5.35Y-3.7 39 | X5.35Y-3.8 40 | X5.5Y-3.05 41 | X5.5Y-3.15 42 | X5.6Y-3.05 43 | X5.6Y-3.15 44 | X5.6Y-3.5 45 | X5.65Y-3.8 46 | X5.7Y-3.05 47 | X5.7Y-3.15 48 | X5.7Y-4.2 49 | X5.7Y-4.3 50 | X5.75Y-3.6 51 | X5.8Y-3.05 52 | X5.8Y-3.15 53 | X5.8Y-4.2 54 | X5.9Y-3.6 55 | X5.9Y-3.8 56 | T2 57 | X5.1Y-2.955 58 | T3 59 | X5.295Y-2.93 60 | X5.395Y-2.93 61 | X5.19Y-3.8 62 | X5.515Y-3.8 63 | X5.19Y-3.65 64 | X5.515Y-3.65 65 | X5.19Y-3.35 66 | X5.515Y-3.35 67 | X5.19Y-3.5 68 | X5.515Y-3.5 69 | T4 70 | X5.1Y-2.875 71 | T5 72 | X4.883Y-3.358 73 | X4.883Y-3.458 74 | X4.883Y-3.558 75 | X4.883Y-3.658 76 | X4.883Y-3.758 77 | X4.883Y-3.858 78 | X4.883Y-3.958 79 | X4.883Y-4.058 80 | X5.808Y-3.358 81 | X5.808Y-3.458 82 | X5.808Y-3.558 83 | X5.808Y-3.658 84 | X5.808Y-3.758 85 | X5.808Y-3.858 86 | X5.808Y-3.958 87 | X5.808Y-4.058 88 | T6 89 | X5.145Y-4.045 90 | X5.245Y-4.045 91 | X5.445Y-4.045 92 | X5.545Y-4.045 93 | T7 94 | X5.345Y-4.245 95 | T0 96 | M30 97 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/.gitignore: -------------------------------------------------------------------------------- 1 | .pio 2 | .vscode/.browse.c_cpp.db* 3 | .vscode/c_cpp_properties.json 4 | .vscode/launch.json 5 | .vscode/ipch 6 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/.travis.yml: -------------------------------------------------------------------------------- 1 | # Continuous Integration (CI) is the practice, in software 2 | # engineering, of merging all developer working copies with a shared mainline 3 | # several times a day < https://docs.platformio.org/page/ci/index.html > 4 | # 5 | # Documentation: 6 | # 7 | # * Travis CI Embedded Builds with PlatformIO 8 | # < https://docs.travis-ci.com/user/integration/platformio/ > 9 | # 10 | # * PlatformIO integration with Travis CI 11 | # < https://docs.platformio.org/page/ci/travis.html > 12 | # 13 | # * User Guide for `platformio ci` command 14 | # < https://docs.platformio.org/page/userguide/cmd_ci.html > 15 | # 16 | # 17 | # Please choose one of the following templates (proposed below) and uncomment 18 | # it (remove "# " before each line) or use own configuration according to the 19 | # Travis CI documentation (see above). 20 | # 21 | 22 | 23 | # 24 | # Template #1: General project. Test it using existing `platformio.ini`. 25 | # 26 | 27 | # language: python 28 | # python: 29 | # - "2.7" 30 | # 31 | # sudo: false 32 | # cache: 33 | # directories: 34 | # - "~/.platformio" 35 | # 36 | # install: 37 | # - pip install -U platformio 38 | # - platformio update 39 | # 40 | # script: 41 | # - platformio run 42 | 43 | 44 | # 45 | # Template #2: The project is intended to be used as a library with examples. 46 | # 47 | 48 | # language: python 49 | # python: 50 | # - "2.7" 51 | # 52 | # sudo: false 53 | # cache: 54 | # directories: 55 | # - "~/.platformio" 56 | # 57 | # env: 58 | # - PLATFORMIO_CI_SRC=path/to/test/file.c 59 | # - PLATFORMIO_CI_SRC=examples/file.ino 60 | # - PLATFORMIO_CI_SRC=path/to/test/directory 61 | # 62 | # install: 63 | # - pip install -U platformio 64 | # - platformio update 65 | # 66 | # script: 67 | # - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N 68 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "platformio.platformio-ide" 6 | ] 7 | } -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "terminal.integrated.env.windows": { 3 | "PATH": "C:\\Users\\Alfonso\\.platformio\\penv\\Scripts;C:\\Users\\Alfonso\\.platformio\\penv;C:\\ProgramData\\Oracle\\Java\\javapath;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files\\TortoiseSVN\\bin;C:\\Herramientas\\maven\\apache-maven-3.6.0\\bin;C:\\Users\\Alfonso\\AppData\\Local\\Microsoft\\WindowsApps;C:\\adb;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files\\nodejs\\;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Program Files\\Microsoft VS Code\\bin;C:\\Program Files\\Git\\cmd;C:\\Program Files\\Git\\mingw64\\bin;C:\\Program Files\\Git\\usr\\bin;C:\\Users\\Alfonso\\AppData\\Local\\Programs\\Python\\Python36\\Scripts\\;C:\\Users\\Alfonso\\AppData\\Local\\Programs\\Python\\Python36\\;C:\\Users\\Alfonso\\AppData\\Roaming\\npm;C:\\Users\\Alfonso\\AppData\\Local\\Programs\\Microsoft VS Code\\bin;C:\\ProgramData\\Oracle\\Java\\javapath;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files\\TortoiseSVN\\bin;C:\\Herramientas\\maven\\apache-maven-3.6.0\\bin;C:\\Users\\Alfonso\\AppData\\Local\\Microsoft\\WindowsApps;C:\\adb;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files\\nodejs\\;C:\\WINDOWS\\System32\\OpenSSH\\;C:\\Program Files\\Microsoft VS Code\\bin;C:\\Program Files\\Git\\cmd;C:\\Program Files\\Git\\mingw64\\bin;C:\\Program Files\\Git\\usr\\bin;C:\\Users\\Alfonso\\AppData\\Local\\Programs\\Python\\Python36\\Scripts\\;C:\\Users\\Alfonso\\AppData\\Local\\Programs\\Python\\Python36\\;C:\\Users\\Alfonso\\AppData\\Roaming\\npm;C:\\Users\\Alfonso\\AppData\\Local\\Programs\\Microsoft VS Code\\bin", 4 | "PLATFORMIO_CALLER": "vscode" 5 | }, 6 | "C_Cpp.errorSquiggles": "Enabled", 7 | "files.associations": { 8 | "string": "cpp", 9 | "functional": "cpp" 10 | } 11 | } -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/WemosEM/WemosEM.ino: -------------------------------------------------------------------------------- 1 | /* 2 | MQTT with ESP8266 and Power Monitor 5th December 2017 3 | David Mottram 4 | Updated by Alfonso C. Alvarez (Alcar), 14nd September 2019 5 | 6 | @author Alfonso Carlos Alvarez Reyes 7 | 8 | Compile with Arduino 2.4.2 9 | */ 10 | 11 | #include 12 | #include //Local DNS Server used for redirecting all requests to the configuration portal 13 | #include //Local WebServer used to serve the configuration portal 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include "WiFiClientPrint.h" 27 | #include "variables.h" 28 | #include "settings.h" 29 | #include "ntp_support.h" 30 | #include "mqtt_wifi_serial_support.h" 31 | #include "iot_platforms_support.h" 32 | #include "power_meter_support.h" 33 | #include "webserver_support.h" 34 | 35 | // Initial setup 36 | void setup(void) { 37 | 38 | delay(10); 39 | 40 | prepareHostMacAndEvents(); 41 | 42 | pinMode(Status_LED, OUTPUT); // Initialize Status LED 43 | Status_LED_Off; 44 | 45 | initSerial(); 46 | 47 | loadConfig(); 48 | 49 | setupWifi(); 50 | 51 | emon.current(A0, Ical); // Current: input pin A6=D4, calibration factor 52 | 53 | initMqtt(); 54 | 55 | randomSeed(micros()); 56 | 57 | ms_since_last_message = millis(); // Reset time since sending last message 58 | 59 | setup_http_server(); 60 | 61 | setup_blynk(); 62 | 63 | setup_thingspeak(); 64 | 65 | setupOTA(); 66 | 67 | emon.current(A0, Ical); 68 | em_read(true); 69 | 70 | Serial.println("Setup finished"); 71 | } // End of setup 72 | 73 | 74 | // main loop 75 | void loop() { 76 | 77 | ArduinoOTA.handle(); 78 | 79 | ntp_loop(); 80 | 81 | em_loop(); 82 | 83 | if (WiFi.status() != WL_CONNECTED) { 84 | Serial.println("WiFi connection lost!"); 85 | ESP.restart(); 86 | delay(100); 87 | } 88 | 89 | mqtt_client.loop(); 90 | httpServer.handleClient(); //handles requests for the firmware update page 91 | 92 | if (resetESP) { 93 | WiFi.persistent(true); // use SDK storage of SSID/WPA parameters 94 | WiFi.disconnect(); // this will store empty ssid/wpa into sdk storage 95 | WiFi.persistent(false); // Do not use SDK storage of SSID/WPA parameters 96 | Serial.println("formatting..."); 97 | SPIFFS.format(); 98 | ESP.restart(); 99 | delay(100); 100 | } 101 | 102 | if (restartESP) { 103 | ESP.restart(); 104 | delay(100); 105 | } 106 | 107 | } // End of main loop 108 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/WemosEM/WiFiClientPrint.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | template 7 | 8 | class WiFiClientPrint : public Print 9 | { 10 | public: 11 | WiFiClientPrint(WiFiClient client) 12 | : _client(client), 13 | _length(0) 14 | { 15 | } 16 | 17 | ~WiFiClientPrint() 18 | { 19 | #ifdef DEBUG_ESP_PORT 20 | // Note: This is manual expansion of assertion macro 21 | if (_length != 0) { 22 | DEBUG_ESP_PORT.printf("\nassertion failed at " __FILE__ ":%d: " "_length == 0" "\n", __LINE__); 23 | // Note: abort() causes stack dump and restart of the ESP 24 | abort(); 25 | } 26 | #endif 27 | } 28 | 29 | virtual size_t write(uint8_t c) override 30 | { 31 | _buffer[_length++] = c; 32 | if (_length == BUFFER_SIZE) { 33 | flush(); 34 | } 35 | } 36 | 37 | void flush() 38 | { 39 | if (_length != 0) { 40 | _client.write((const uint8_t*)_buffer, _length); 41 | _length = 0; 42 | } 43 | } 44 | 45 | void stop() 46 | { 47 | flush(); 48 | _client.stop(); 49 | } 50 | 51 | private: 52 | WiFiClient _client; 53 | uint8_t _buffer[BUFFER_SIZE]; 54 | size_t _length; 55 | }; -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/WemosEM/data/index.html.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alcar21/WemosEM/90f029c280fc198d436d2481c994b29a755ef94b/WemosEM-Mqtt-Power-Sensor/WemosEM/data/index.html.gz -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/WemosEM/data/wemosem.js: -------------------------------------------------------------------------------- 1 | function showInfo(e) { console.log("INFO: " + e), $(".message-info").html(e), $(".message-info").show(), setTimeout(function () { $(".message-info").hide() }, 4e3) } function showError(e) { console.log("ERROR: " + e), $(".message-error").html(e), $(".message-error").show(), setTimeout(function () { $(".message-error").hide() }, 4e3) } function prepareWifiMode() { "dhcp" == $("#ipMode").val() ? $(".staticIP").css("display", "none") : $(".staticIP").css("display", "") } function loadWIFI() { $.post("/api/loadwifi").done(function (e) { $("#wifi-name").val(e.wifi_ssid), $("#wifi-pass").val(e.wifi_password), $("#wifi-ipmode").val(e.wifi_mode), $("#wifi-ip").val(e.wifi_ip), $("#wifi-mask").val(e.wifi_mask), $("#wifi-gateway").val(e.wifi_gateway) }).fail(function (e) { showError("Error in load WIFI parameteres of WemosEM") }) } function loadCalibration() { $.post("/api/loadcalibrate").done(function (e) { $("#voltage").val(e.votalje), $("#ical").val(e.ical), $("#messageinterval").val(e.messageinterval) }).fail(function (e) { showError("Error in load Calibrate parameteres of WemosEM") }) } function loadtime() { $.post("/api/loadtime").done(function (e) { $("#timezone").val(e.timezone), $("#minute-timezone").val(e.minutestimezone) }).fail(function (e) { showError("Error in load Calibrate parameteres of WemosEM") }) } function loadSystem() { } function loadMQTT() { $.post("/api/loadmqtt").done(function (e) { $("#enableMQTT").prop("checked", e.mqtt_enabled), $("#mqtt-ip").val(e.mqtt_server), $("#mqtt-port").val(e.mqtt_port), $("#mqtt-user").val(e.mqtt_username), $("#mqtt-pass").val(e.mqtt_password) }).fail(function (e) { showError("Error in load MQTT parameteres of WemosEM") }) } function saveWifi() { $.post("/api/savewifi", { "wifi-name": $("#wifi-name").val(), "wifi-pass": $("#wifi-pass").val(), "wifi-ipmode": $("#wifi-ipmode").val(), "wifi-ip": $("#wifi-ip").val(), "wifi-mask": $("#wifi-mask").val(), "wifi-gateway": $("#wifi-gateway").val() }).done(function (e) { loadMQTT(), e && 0 != e.length ? showError("Error in Wifi saved parameters: " + JSON.stringify(e)) : (showInfo("Wifi parameters saved"), 1 == $("#wifi-ipmode").val() && (window.location.href = "http://" + $("#wifi-ip").val())) }).fail(function (e) { showError("Error in save Wifi parameteres of WemosEM") }) } function saveMQTT() { $.post("/api/savemqtt", { mqtt_enabled: $("#enableMQTT").prop("checked") ? "1" : "0", mqtt_server: $("#mqtt-ip").val(), mqtt_port: $("#mqtt-port").val(), mqtt_username: $("#mqtt-user").val(), mqtt_password: $("#mqtt-pass").val() }).done(function (e) { loadMQTT(), e && 0 != e.length ? showError("Error in MQTT saved parameters: " + JSON.stringify(e)) : showInfo("MQTT parameters saved") }).fail(function (e) { showError("Error in save MQTT parameteres of WemosEM") }) } function saveCalibrate() { $.post("/api/savecalibrate", { voltage: $("#voltage").val(), ical: $("#ical").val(), messageinterval: $("#messageinterval").val() }).done(function (e) { loadCalibration(), e && 0 != e.length ? showError("Error saving calibrate settings: " + JSON.stringify(e)) : showInfo("Calibrate settings saved") }).fail(function (e) { showError("Error saving Calibrate parameteres of WemosEM") }) } function saveTime() { $.post("/api/savetime", { timezone: $("#timezone").val(), minutestimezone: $("#minute-timezone").val() }).done(function (e) { loadCalibration(), e && 0 != e.length ? showError("Error saving time settings: " + JSON.stringify(e)) : showInfo("Timezone settings saved") }).fail(function (e) { showError("Error saving time settings of WemosEM") }) } function saveSystem() { $.post("/api/savesystem", { systempassword: $("#systemPassword").val() }).done(function (e) { loadSystem(), e && 0 != e.length ? showError("Error saving system settings: " + JSON.stringify(e)) : showInfo("System settings saved") }).fail(function (e) { showError("Error saving system settings of WemosEM") }) } function loadStatus() { setInterval(function () { $.post("/api/status").done(function (e) { $(".current-value").html(e.current), $(".voltage-value").html(e.voltage), $(".watios-value").html(e.watios), $(".kwh-value").html(e.kwh), $(".ical-value").html(e.ical), $(".mqttreconnected-value").html(e.mqttreconnected), $(".wifidb-value").html(e.wifidb), $(".uptime-value").html(e.uptime), $(".time-value").html(e.time), $(".freemem-value").html(e.freemem) }).fail(function (e) { console.log("Error in load status of WemosEM") }) }, 2e3) } !function (o) { o.each(["show", "hide"], function (e, t) { var i = o.fn[t]; o.fn[t] = function () { return this.trigger(t), i.apply(this, arguments) } }) }(jQuery), $(document).ready(function () { $(".see-system-password").mousedown(function () { $("#systemPassword").prop("type", "text") }), $(".see-system-password").mouseup(function () { $("#systemPassword").prop("type", "password") }), $(".see-mqtt-password").mousedown(function () { $("#mqtt-pass").prop("type", "text") }), $(".see-mqtt-password").mouseup(function () { $("#mqtt-pass").prop("type", "password") }), $(".btn-update").click(function () { window.location.href = "/WebFirmwareUpgrade" }); $.post("/api/id").done(function (e) { $(".wemos-id").html(e) }); loadStatus(), loadWIFI(), loadMQTT(), loadCalibration(), loadtime(), loadSystem(), $(".btn-reboot").click(function () { $.post("/reboot").done(function () { showInfo("reboot success") }).fail(function () { showError("error in reboot") }) }), $(".btn-reset").click(function () { $.post("/reset").done(function () { showInfo("reset success") }).fail(function () { showError("error in reset") }) }), $(".btn-save-wifi").click(function () { saveWifi() }), $(".btn-save-mqtt").click(function () { saveMQTT() }), $(".btn-save-calibrate").click(function () { saveCalibrate() }), $(".btn-save-time").click(function () { saveTime() }), $(".btn-save-system").click(function () { saveSystem() }), $("#ipMode").change(function () { prepareWifiMode() }), $(".cardWifi").on("show", function () { prepareWifiMode() }), $(".btn-wifi").click(function () { $(".card").hide(), $(".cardWifi").show() }), $(".btn-mqtt").click(function () { $(".card").hide(), $(".cardMQTT").show() }), $(".btn-calibrate").click(function () { $(".card").hide(), $(".cardCalibrate").show() }), $(".btn-time").click(function () { $(".card").hide(), $(".cardTime").show() }), $(".btn-system").click(function () { $(".card").hide(), $(".cardSystem").show() }) }); -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/WemosEM/iot_platforms_support.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | /* 4 | IOT Plattform integration 5 | 6 | Alfonso C. Alvarez (Alcar), 14nd September 2019 7 | 8 | @author Alfonso Carlos Alvarez Reyes 9 | 10 | Compile with Arduino 2.4.2 11 | */ 12 | 13 | BLYNK_CONNECTED() { 14 | Blynk.syncAll(); 15 | } 16 | 17 | void setup_blynk() { 18 | 19 | if (blynk_enabled && blynkAuth.length() > 0 && blynkAuth != "null") { 20 | Serial.println("[BLYNK] Enabled"); 21 | if (blynkServer.length() > 0 && blynkPort != 0 ) { 22 | Serial.println("[BLYNK] Custom server connecting..."); 23 | Blynk.config(blynkAuth.c_str(), blynkServer.c_str(), blynkPort); 24 | } else { 25 | Blynk.config(blynkAuth.c_str()); 26 | } 27 | } 28 | } 29 | 30 | void blynk_loop() { 31 | 32 | if (!blynk_enabled) { 33 | Serial.println("[BLYNK] Disabled"); 34 | return; 35 | } 36 | 37 | unsigned long init = millis(); 38 | Serial.println("[BLYNK] Sending data"); 39 | 40 | if (Blynk.connected()) { 41 | Blynk.run(); 42 | } else { 43 | Blynk.connect(); 44 | } 45 | 46 | Blynk.virtualWrite(VPIN_VOLTAGE, mainsVoltage); 47 | Blynk.virtualWrite(VPIN_CURRENT, rmsCurrent); 48 | Blynk.virtualWrite(VPIN_WATIOS, rmsPower); 49 | Blynk.virtualWrite(VPIN_ENERGY, kiloWattHours); 50 | Blynk.virtualWrite(VPIN_ENERGY_LAST_RESET, beforeResetKiloWattHours); 51 | 52 | Serial.println("[BLYNK] End sending data. time: " + String(millis() - init) + "ms"); 53 | } 54 | 55 | void setup_thingspeak() { 56 | 57 | if (thingSpeak_enabled) { 58 | Serial.println("[THINGSPEAK] Enabled"); 59 | ThingSpeak.begin(espClient); 60 | } 61 | } 62 | 63 | 64 | void thinkgSpeak_loop() { 65 | 66 | if (!thingSpeak_enabled) { 67 | Serial.println("[THINGSPEAK] Disabled"); 68 | return; 69 | } 70 | 71 | if ((millis() - lastTimeMeasureTS) < TIME_BEETWEEN_REQUEST) { 72 | return; 73 | } 74 | 75 | lastTimeMeasureTS = millis(); 76 | 77 | unsigned long init = millis(); 78 | Serial.println("[THINGSPEAK] Sending data"); 79 | int statusTS; 80 | 81 | ThingSpeak.setField(1, mainsVoltage); 82 | ThingSpeak.setField(2, (float)rmsCurrent); 83 | ThingSpeak.setField(3, (float)rmsPower); 84 | ThingSpeak.setField(4, (float)kiloWattHours); 85 | ThingSpeak.setField(5, (float)beforeResetKiloWattHours); 86 | 87 | statusTS = ThingSpeak.writeFields(tsChannelNumber, tsWriteAPIKey.c_str()); 88 | 89 | Serial.println("[THINGSPEAK] Status: " + String(statusTS)); 90 | Serial.println("[THINGSPEAK] End sending data. time: " + String(millis() - init) + "ms"); 91 | 92 | } -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/WemosEM/ntp_support.h: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | NTP setup and operations 4 | 5 | Alfonso C. Alvarez (Alcar), 14nd September 2019 6 | 7 | @author Alfonso Carlos Alvarez Reyes 8 | 9 | Compile with Arduino 2.4.2 10 | */ 11 | 12 | void processSyncEvent (NTPSyncEvent_t ntpEvent) { 13 | 14 | if (ntpEvent < 0) { 15 | Serial.printf ("Time Sync error: %d\n", ntpEvent); 16 | if (ntpEvent == noResponse) 17 | Serial.println ("NTP server not reachable"); 18 | else if (ntpEvent == invalidAddress) 19 | Serial.println ("Invalid NTP server address"); 20 | else 21 | Serial.println ("Error sending request or NTP response error"); 22 | } else { 23 | if (ntpEvent == timeSyncd) { 24 | Serial.print ("Got NTP time: "); 25 | Serial.println (NTP.getTimeDateString (NTP.getLastNTPSync ())); 26 | } 27 | } 28 | } 29 | 30 | void setup_NTP() { 31 | 32 | NTP.onNTPSyncEvent ([](NTPSyncEvent_t event) { 33 | ntpEvent = event; 34 | syncEventTriggered = true; 35 | }); 36 | } 37 | 38 | void ntp_loop() { 39 | 40 | if (wifiFirstConnected) { 41 | wifiFirstConnected = false; 42 | // NTP.setInterval (63); 43 | NTP.begin (ntpServer, timeZone, true, minutesTimeZone); 44 | } 45 | 46 | if (syncEventTriggered) { 47 | processSyncEvent (ntpEvent); 48 | syncEventTriggered = false; 49 | } 50 | } 51 | 52 | void print_ntp_time() { 53 | Serial.print (NTP.getTimeDateString ()); Serial.print (" "); 54 | Serial.print (NTP.isSummerTime () ? "Summer Time. " : "Winter Time. "); 55 | Serial.print ("Uptime: "); 56 | Serial.print (NTP.getUptimeString ()); Serial.print (" since "); 57 | Serial.println (NTP.getTimeDateString (NTP.getFirstSync ()).c_str ()); 58 | } 59 | 60 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/WemosEM/power_meter_support.h: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Metering power functions 4 | 5 | Alfonso C. Alvarez (Alcar), 14nd September 2019 6 | 7 | @author Alfonso Carlos Alvarez Reyes 8 | 9 | Compile with Arduino 2.4.2 10 | */ 11 | 12 | long lastEMRead = 0; // Last EM Read 13 | long lastMsgMQTT = 0; // Last Message MQTT 14 | 15 | void resetKwh() { 16 | 17 | beforeResetKiloWattHours = kiloWattHours; 18 | watiosTotal = 0.0; 19 | kiloWattHours = 0.0; 20 | } 21 | 22 | 23 | 24 | void setIcal(float _Ical) { 25 | Ical = _Ical; 26 | } 27 | 28 | void em_calibrate() { 29 | 30 | for (int i = 0; i < 5; i++) { 31 | emon.calcIrms(NUM_SAMPLES); // Calculate Irms only 32 | } 33 | 34 | if (lastTimeMeasure == 0) { 35 | lastTimeMeasure = millis(); 36 | } 37 | } 38 | 39 | // Read information from Clamp 40 | void em_read(bool calibrate) { 41 | 42 | if (calibrate) { 43 | em_calibrate(); 44 | return; 45 | } 46 | 47 | unsigned long now = millis(); 48 | if (now - lastEMRead > MIN_READ_EM_INTERVAL) { 49 | 50 | lastEMRead = now; 51 | 52 | rmsCurrent = emon.calcIrms(NUM_SAMPLES); // Calculate Irms only 53 | 54 | rmsPower = rmsCurrent * mainsVoltage; // Calculates RMS Power 55 | watiosTotal += ((double)rmsPower * ((millis()-lastTimeMeasure) / 1000.0)/3600.0); // Calculates kilowatt hours used since last reboot. 3600 = 60min*60sec / 1000.0 watios = kwh 56 | 57 | kiloWattHours = watiosTotal / 1000.0; 58 | 59 | Serial.print(" [METER] - rmsCurrent: "); 60 | Serial.print(rmsCurrent); 61 | Serial.print(" mainsVoltage: "); 62 | Serial.print(mainsVoltage); 63 | Serial.print(" Watios: "); 64 | Serial.print(watiosTotal); 65 | 66 | Serial.print(" kwh: "); 67 | Serial.print(kiloWattHours); 68 | Serial.print(" Before reset kwh: "); 69 | Serial.print(beforeResetKiloWattHours); 70 | Serial.print(" lastTimeMeasure: "); 71 | Serial.println(lastTimeMeasure); 72 | 73 | // If not AP mode 74 | // if (isSTA()) { 75 | // saveConfig(); 76 | // } 77 | 78 | lastTimeMeasure = millis(); 79 | } 80 | 81 | } 82 | 83 | // Read information from Clamp 84 | void em_read() { 85 | em_read(false); // do not show calibrate by default 86 | } 87 | 88 | void em_loop() { 89 | 90 | if (isResetEnergyToday && day(now()) != dayReset) { 91 | 92 | isResetEnergyToday = false; 93 | } else if (!isResetEnergyToday && day(now()) == dayReset) { 94 | 95 | resetKwh(); 96 | isResetEnergyToday = true; 97 | } 98 | 99 | unsigned long now = millis(); 100 | // If enough time since sending last message, or if birth message must be published 101 | if (now - lastMsgMQTT < message_interval) { 102 | return; 103 | } 104 | 105 | lastMsgMQTT = now; 106 | 107 | Status_LED_On; 108 | em_read(); 109 | Status_LED_Off; 110 | 111 | blynk_loop(); 112 | thinkgSpeak_loop(); 113 | 114 | if (!mqtt_enabled) { 115 | return; 116 | } 117 | 118 | // Check if we're still connected to MQTT broker 119 | if (!mqtt_client.connected()) { 120 | // reconnect if not 121 | mqtt_reconnect(); 122 | } 123 | 124 | 125 | String payload = build_payload(); 126 | 127 | Serial.print(" [METER] - Payload: "); 128 | Serial.println(payload); 129 | 130 | Status_LED_On; 131 | // Publish a MQTT message with the payload 132 | if (mqtt_client.publish(mqtt_topic.c_str(), (char*) payload.c_str(), 0)) { 133 | Serial.print(" [MQTT] - Published: "); 134 | Serial.print(mqtt_topic); 135 | Serial.print(" > "); 136 | Serial.println(payload); 137 | mqtt_client.publish(mqtt_topic_status.c_str(), (char*) "online", 0); 138 | Serial.print(" [MQTT] - Published: "); 139 | Serial.print(mqtt_topic_status); 140 | Serial.println(" > online"); 141 | } else { 142 | Serial.print("ERROR MQTT Topic not Published: "); 143 | Serial.println(mqtt_topic); 144 | } 145 | 146 | Status_LED_Off; 147 | 148 | 149 | } 150 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/WemosEM/settings.h: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Default parameters, settings load and save functions 4 | 5 | Alfonso C. Alvarez (Alcar), 14nd September 2019 6 | 7 | @author Alfonso Carlos Alvarez Reyes 8 | 9 | Compile with Arduino 2.4.2 10 | */ 11 | 12 | #define DEFAULT_EMPTY "" 13 | 14 | // WIFI 15 | #define DEFAULT_WIFI_NAME "" 16 | #define DEFAULT_WIFI_PASSWORD "" 17 | #define DEFAULT_IP_MODE 0 // 0 = DHCP, 1 = Static 18 | #define DEFAULT_IP "" 19 | #define DEFAULT_MASK "" 20 | #define DEFAULT_GATEWAY "" 21 | // MQTT 22 | #define DEFAULT_MQTT_SERVER "192.168.1.2" 23 | #define DEFAULT_MQTT_PORT 1883 24 | #define DEFAULT_MQTT_USERNAME "" 25 | #define DEFAULT_MQTT_PASSWORD "" 26 | // CALIBRATE 27 | #define DEFAULT_MESSAGE_INTERVAL 10000 28 | #define DEFAULT_VOLTAGE 225.0 29 | #define DEFAULT_ICAL 30.50 30 | // TIMEZONE 31 | #define DEFAULT_TIMEZONE 1 32 | #define DEFAULT_MINUTES_TIMEZONE 0 33 | // SYSTEM 34 | #define DEFAULT_SYSTEM_USER "wemosem" 35 | #define DEFAULT_SYSTEM_PASSWORD "infinito&masalla" 36 | 37 | // VARIABLES 38 | String system_password = DEFAULT_SYSTEM_PASSWORD; 39 | int ipMode = DEFAULT_IP_MODE; // 0 = DHCP, 1 = Static 40 | 41 | // Add your Wifi details below. Set SSID to NULL if unused. 42 | // WiFi slot 1 43 | String wifi_name = DEFAULT_WIFI_NAME; 44 | String wifi_password = DEFAULT_WIFI_PASSWORD; 45 | String ip = DEFAULT_IP; 46 | String mask = DEFAULT_MASK; 47 | String gateway = DEFAULT_GATEWAY; 48 | 49 | // MQTT Broker address and port 50 | boolean mqtt_enabled = false; 51 | String mqtt_server = DEFAULT_MQTT_SERVER; 52 | int mqtt_port = 1883; 53 | String mqtt_username = DEFAULT_MQTT_USERNAME; 54 | String mqtt_password = DEFAULT_MQTT_PASSWORD; 55 | 56 | int message_interval = DEFAULT_MESSAGE_INTERVAL; // Time in ms between each message. 5000 ms = 5 seconds 57 | 58 | // Mains voltage and calibration 59 | float mainsVoltage = DEFAULT_VOLTAGE; // Mains voltage in Volts. Change this value according to your mains. 60 | float Ical = DEFAULT_ICAL; // Varia dentro del mismo fabricante, hay que calibrarlo (1800 vueltas del secundario STC013 / 69 Ohm resistencia carga (burden)) = 26.1 61 | 62 | // Iot Platforms 63 | // Blynk platform 64 | boolean blynk_enabled = false; 65 | String blynkAuth = DEFAULT_EMPTY; 66 | String blynkServer = DEFAULT_EMPTY; 67 | uint16_t blynkPort = 0; 68 | 69 | // ThingSpeak platform 70 | boolean thingSpeak_enabled = false; 71 | unsigned long tsChannelNumber = 0; 72 | String tsWriteAPIKey = DEFAULT_EMPTY; 73 | 74 | // TimeZone 75 | int8_t timeZone = DEFAULT_TIMEZONE; 76 | int8_t minutesTimeZone = DEFAULT_MINUTES_TIMEZONE; 77 | 78 | // Date RESET 79 | int dayReset = 0; 80 | 81 | boolean loadConfig() { 82 | 83 | String jsonString; 84 | 85 | if (!SPIFFS.begin()) { 86 | Serial.println("ERROR: Failed to mount file system"); 87 | return false; 88 | } 89 | 90 | File configFile = SPIFFS.open("/config.json", "r"); 91 | if (!configFile) { 92 | Serial.println("ERROR: Failed to open config file"); 93 | return false; 94 | } 95 | 96 | size_t size = configFile.size(); 97 | // if (size > 1024) { 98 | // Serial.println("ERROR: Config file size is too large"); 99 | // return false; 100 | // } 101 | 102 | // Allocate a buffer to store contents of the file. 103 | std::unique_ptr buf(new char[size]); 104 | 105 | // We don't use String here because ArduinoJson library requires the input 106 | // buffer to be mutable. If you don't use ArduinoJson, you may as well 107 | // use configFile.readString instead. 108 | configFile.readBytes(buf.get(), size); 109 | 110 | DynamicJsonDocument jsonConfig(1024); 111 | auto error = deserializeJson(jsonConfig, buf.get()); 112 | if (error) { 113 | Serial.println("Failed to parse config file"); 114 | return false; 115 | } 116 | 117 | serializeJson(jsonConfig, jsonString); 118 | Serial.println("LOADED CONFIG: " + jsonString); 119 | 120 | // WIFI 121 | wifi_name = (jsonConfig["wifi_name"] == "" ? DEFAULT_WIFI_NAME : jsonConfig["wifi_name"].as()); 122 | wifi_password = (jsonConfig["wifi_password"] == "" ? DEFAULT_WIFI_PASSWORD : jsonConfig["wifi_password"].as()); 123 | ipMode = (jsonConfig["ip_mode"] == "" ? DEFAULT_IP_MODE : jsonConfig["ip_mode"]); 124 | ip = (jsonConfig["ip"] == "" ? DEFAULT_IP : jsonConfig["ip"].as()); 125 | mask = (jsonConfig["mask"] == "" ? DEFAULT_MASK : jsonConfig["mask"].as()); 126 | gateway = (jsonConfig["gateway"] == "" ? DEFAULT_GATEWAY : jsonConfig["gateway"].as()); 127 | // MQTT 128 | mqtt_enabled = (jsonConfig["mqtt_enabled"]); 129 | mqtt_server = (jsonConfig["mqtt_server"] == "" ? DEFAULT_MQTT_SERVER : jsonConfig["mqtt_server"].as()); 130 | mqtt_port = (jsonConfig["mqtt_port"] == "" ? DEFAULT_MQTT_PORT : jsonConfig["mqtt_port"]); 131 | mqtt_username = (jsonConfig["mqtt_username"] == "" ? DEFAULT_MQTT_USERNAME : jsonConfig["mqtt_username"].as()); 132 | mqtt_password = (jsonConfig["mqtt_password"] == "" ? DEFAULT_MQTT_PASSWORD : jsonConfig["mqtt_password"].as()); 133 | // CALIBRATE 134 | message_interval = (jsonConfig["message_interval"] == "" ? DEFAULT_MESSAGE_INTERVAL : jsonConfig["message_interval"]); 135 | mainsVoltage = (jsonConfig["voltage"] == "" ? DEFAULT_VOLTAGE : jsonConfig["voltage"]); 136 | Ical = (jsonConfig["ical"] == "" ? DEFAULT_ICAL : jsonConfig["ical"]); 137 | // IOT PLATFORMS 138 | blynk_enabled = (jsonConfig["blynk_enabled"] == 1 ? true : false); 139 | blynkAuth = (jsonConfig["blynkAuth"] == "" || jsonConfig["blynkAuth"] == "null" ? DEFAULT_EMPTY : jsonConfig["blynkAuth"].as()); 140 | blynkServer = (jsonConfig["blynkServer"] == "" || jsonConfig["blynkServer"] == "null" ? DEFAULT_EMPTY : jsonConfig["blynkServer"].as()); 141 | blynkPort = (jsonConfig["blynkPort"] == "" ? DEFAULT_MQTT_PORT : jsonConfig["blynkPort"]); 142 | 143 | thingSpeak_enabled = (jsonConfig["ts_enabled"] == 1 ? true : false); 144 | tsChannelNumber = (jsonConfig["tsChannelNumber"] == "" ? 0 : jsonConfig["tsChannelNumber"]); 145 | tsWriteAPIKey = (jsonConfig["tsWriteAPIKey"] == "" || jsonConfig["tsWriteAPIKey"] == "null" ? DEFAULT_EMPTY : jsonConfig["tsWriteAPIKey"].as()); 146 | 147 | // SYSTEM - TIMEZONE 148 | timeZone = (jsonConfig["timezone"] == "" ? DEFAULT_TIMEZONE : jsonConfig["timezone"]); 149 | minutesTimeZone = (jsonConfig["minutes_timezone"] == "" ? DEFAULT_MINUTES_TIMEZONE : jsonConfig["minutes_timezone"]); 150 | // SYSTEM 151 | system_password = (jsonConfig["system_password"] == "" ? DEFAULT_SYSTEM_PASSWORD : jsonConfig["system_password"].as()); 152 | dayReset = (jsonConfig["dayReset"] == "" ? 0 : jsonConfig["dayReset"]); 153 | 154 | // KWH 155 | watiosTotal = (jsonConfig["watiosTotal"] == "" ? 0.0 : jsonConfig["watiosTotal"]); 156 | kiloWattHours = (jsonConfig["kiloWattHours"] == "" ? 0.0 : jsonConfig["kiloWattHours"]); 157 | beforeResetKiloWattHours = (jsonConfig["beforeResetKiloWattHours"] == "" ? 0.0 : jsonConfig["beforeResetKiloWattHours"]); 158 | 159 | return true; 160 | 161 | } 162 | 163 | bool saveConfig() { 164 | DynamicJsonDocument jsonConfig(1024); 165 | String jsonString; 166 | 167 | // WIFI 168 | jsonConfig["wifi_name"] = wifi_name; 169 | jsonConfig["wifi_password"] = wifi_password; 170 | jsonConfig["ip_mode"] = ipMode; 171 | jsonConfig["ip"] = ip; 172 | jsonConfig["mask"] = mask; 173 | jsonConfig["gateway"] = gateway; 174 | // MQTT 175 | jsonConfig["mqtt_enabled"] = mqtt_enabled; 176 | jsonConfig["mqtt_server"] = mqtt_server; 177 | jsonConfig["mqtt_port"] = mqtt_port; 178 | jsonConfig["mqtt_username"] = mqtt_username; 179 | jsonConfig["mqtt_password"] = mqtt_password; 180 | // CALIBRATE 181 | jsonConfig["message_interval"] = message_interval; 182 | jsonConfig["voltage"] = mainsVoltage; 183 | jsonConfig["ical"] = Ical; 184 | 185 | // IOT PLATFORMS 186 | jsonConfig["blynk_enabled"] = blynk_enabled; 187 | jsonConfig["blynkAuth"] = blynkAuth; 188 | jsonConfig["blynkServer"] = blynkServer; 189 | jsonConfig["blynkPort"] = blynkPort; 190 | 191 | jsonConfig["ts_enabled"] = thingSpeak_enabled; 192 | jsonConfig["tsChannelNumber"] = tsChannelNumber; 193 | jsonConfig["tsWriteAPIKey"] = tsWriteAPIKey; 194 | 195 | // SYSTEM - TIMEZONE 196 | jsonConfig["timezone"] = timeZone; 197 | jsonConfig["minutes_timezone"] = minutesTimeZone; 198 | // SYSTEM 199 | jsonConfig["system_password"] = system_password; 200 | jsonConfig["dayReset"] = dayReset; 201 | 202 | 203 | // KWH 204 | jsonConfig["watiosTotal"] = watiosTotal; 205 | jsonConfig["kiloWattHours"] = kiloWattHours; 206 | jsonConfig["beforeResetKiloWattHours"] = beforeResetKiloWattHours; 207 | 208 | File configFile = SPIFFS.open("/config.json", "w"); 209 | if (!configFile) { 210 | Serial.println("Failed to open config file for writing"); 211 | return false; 212 | } 213 | 214 | serializeJson(jsonConfig, configFile); 215 | serializeJson(jsonConfig, jsonString); 216 | Serial.println("SAVED CONFIG: " + jsonString); 217 | return true; 218 | } 219 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/WemosEM/variables.h: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Global variables and constants 4 | 5 | Alfonso C. Alvarez (Alcar), 14nd September 2019 6 | 7 | @author Alfonso Carlos Alvarez Reyes 8 | 9 | Compile with Arduino 2.4.2 10 | */ 11 | 12 | // I/O 13 | #define Status_LED 2 // D4 14 | #define Status_LED_On digitalWrite(Status_LED, HIGH) 15 | #define Status_LED_Off digitalWrite(Status_LED, LOW) 16 | 17 | #define MIN_READ_EM_INTERVAL 1000 // Minimum seconds read sensor Clamp of energy meter 18 | #define NUM_SAMPLES 1480 // measured by Tom in Mui Wo 19 | 20 | #define MAXLEN_MQTT_ENABLED 1 21 | #define MAXLEN_MQTT_SERVER 100 22 | #define MAXLEN_MQTT_PORT 5 23 | #define MAXLEN_MQTT_USERNAME 30 24 | #define MAXLEN_MQTT_PASSWORD 30 25 | #define MAXLEN_SYSTEM_PASSWORD 30 26 | 27 | #define MAXLEN_VOLTAGE 7 28 | #define MAXLEN_ICAL 6 29 | #define MAXLEN_TIMEZONE 2 30 | #define MIN_MESSAGE_INTERVAL 5000 31 | #define MAXLEN_MESSAGE_INTERVAL 7 32 | 33 | #define HOSTNAME_PREFIX "wemosEM-" 34 | 35 | #define TOPIC_VOLTAGE "voltage" 36 | #define TOPIC_STATUS "status" 37 | #define TOPIC_RESET_KWH "resetkwh" 38 | 39 | // BLYNK Virtual Pins 40 | #define VPIN_VOLTAGE V0 41 | #define VPIN_CURRENT V1 42 | #define VPIN_WATIOS V2 43 | #define VPIN_ENERGY V3 44 | #define VPIN_ENERGY_LAST_RESET V4 45 | 46 | // THINGSPEAK 47 | #define TIME_BEETWEEN_REQUEST 15000 //15 seconds 48 | 49 | const PROGMEM char TOPIC_HA_CURRENT[] = "homeassistant/sensor/%s/current/config"; 50 | const PROGMEM char TOPIC_HA_POWER[] = "homeassistant/sensor/%s/power/config"; 51 | const PROGMEM char TOPIC_HA_KWH[] = "homeassistant/sensor/%s/kwh/config"; 52 | // const PROGMEM char TOPIC_HA_KWTOTAL[] = "homeassistant/sensor/%s/kwTotal/config"; 53 | const PROGMEM char MESSAGE_HA_CURRENT[] = "{\"unit_of_measurement\":\"A\",\"state_topic\":\"wemos/%s/power\",\"value_template\":\"{{ value_json.current }}\",\"json_attributes_topic\":\"wemos/%s/power\",\"name\":\"%s-current\",\"unique_id\":\"%s-current-wemosem\",\"device\":{\"identifiers\":[\"%s\"],\"name\":\"%s\",\"sw_version\":\"WemosEM 1.1\",\"model\":\"Wemos D1 Mini + SCT013\",\"manufacturer\":\"Wemos\"},\"icon\":\"mdi:counter\",\"availability_topic\":\"wemos/%s/status\"}"; 54 | const PROGMEM char MESSAGE_HA_POWER[] = "{\"unit_of_measurement\":\"w\",\"state_topic\":\"wemos/%s/power\",\"device_class\":\"power\",\"value_template\":\"{{ value_json.watios }}\",\"json_attributes_topic\":\"wemos/%s/power\",\"name\":\"%s-watios\",\"unique_id\":\"%s-watios-wemosem\",\"device\":{\"identifiers\":[\"%s\"],\"name\":\"%s\",\"sw_version\":\"WemosEM 1.1\",\"model\":\"Wemos D1 Mini + SCT013\",\"manufacturer\":\"Wemos\"},\"icon\":\"mdi:counter\",\"availability_topic\":\"wemos/%s/status\"}"; 55 | const PROGMEM char MESSAGE_HA_KWH[] = "{\"unit_of_measurement\":\"kwh\",\"state_topic\":\"wemos/%s/power\",\"device_class\":\"power\",\"value_template\":\"{{ value_json.kwh }}\",\"json_attributes_topic\":\"wemos/%s/power\",\"name\":\"%s-kwh\",\"unique_id\":\"%s-kwh-wemosem\",\"device\":{\"identifiers\":[\"%s\"],\"name\":\"%s\",\"sw_version\":\"WemosEM 1.1\",\"model\":\"Wemos D1 Mini + SCT013\",\"manufacturer\":\"Wemos\"},\"icon\":\"mdi:counter\",\"availability_topic\":\"wemos/%s/status\"}"; 56 | // const PROGMEM char MESSAGE_HA_KWTOTAL[] = "{\"unit_of_measurement\":\"kwTotal\",\"state_topic\":\"wemos/%s/power\",\"device_class\":\"power\",\"value_template\":\"{{ value_json.kwTotal }}\",\"json_attributes_topic\":\"wemos/%s/power\",\"name\":\"%s-kwTotal\",\"unique_id\":\"%s-kwTotal-wemosem\",\"device\":{\"identifiers\":[\"%s\"],\"name\":\"%s\",\"sw_version\":\"WemosEM 1.1\",\"model\":\"Wemos D1 Mini + SCT013\",\"manufacturer\":\"Wemos\"},\"icon\":\"mdi:counter\",\"availability_topic\":\"wemos/%s/status\"}"; 57 | 58 | 59 | // WIFI AND MQTT 60 | WiFiClient espClient; // For ESP8266 boards 61 | PubSubClient mqtt_client(espClient); 62 | WiFiManager wifiManager; 63 | WiFiEventHandler gotIpEventHandler, disconnectedEventHandler; // Event IP Handler 64 | unsigned long uptimeAP = 0; 65 | 66 | // UPDATE FIRMWARE 67 | const char* update_path = "/WebFirmwareUpgrade"; 68 | 69 | // TIME ZONE 70 | //const PROGMEM char ntpServer[] = "pool.ntp.org"; 71 | const char *ntpServer = "pool.ntp.org"; 72 | 73 | // Message timing 74 | int reconnected_count = 0; // Counter of messages sent 75 | long ms_since_last_message = 0; // Time elapsed since last message was sent, in ms 76 | 77 | // Energy Monitor 78 | EnergyMonitor emon; 79 | 80 | // Data of Energy Monitor 81 | double watiosTotal = 0; // Measured energy in watios/h 82 | double kiloWattHours = 0; // Measured energy in KWh 83 | double beforeResetKiloWattHours = 0; // Measured energy in KWh 84 | double rmsCurrent = 0; // Measured current in A 85 | double rmsPower = 0; // Measured power in W 86 | unsigned long lastTimeMeasure = 0; // Last time measure in ms 87 | boolean isResetEnergyToday = false; // reset energy on setup day 88 | 89 | // ThingSpeak 90 | unsigned long lastTimeMeasureTS = 0; 91 | 92 | // NTP 93 | boolean syncEventTriggered = false; // True if a time even has been triggered 94 | NTPSyncEvent_t ntpEvent; // Last triggered event 95 | 96 | // Web Server 97 | ESP8266WebServer httpServer(80); 98 | ESP8266HTTPUpdateServer httpUpdater; 99 | 100 | String My_MAC = ""; // MAC address, to be read from ESP8266 101 | String wifi_hostname; 102 | String mqtt_topic = "None"; 103 | String mqtt_topic_status = "None"; 104 | String mqtt_topic_prefix_subscribe = ""; 105 | String mqtt_topic_subscribe = ""; 106 | bool wifiFirstConnected = false; 107 | 108 | bool resetESP = false; 109 | bool restartESP = false; 110 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/html/switch.css: -------------------------------------------------------------------------------- 1 | .switch { 2 | position: relative; 3 | display: inline-block; 4 | width: 40px; 5 | height: 24px; 6 | margin: 0px 10px 0 0; 7 | } 8 | 9 | .switch input[type='checkbox'] { 10 | opacity: 0; 11 | width: 0; 12 | height: 0; 13 | } 14 | 15 | .switch .slider { 16 | position: absolute; 17 | cursor: pointer; 18 | top: 0; 19 | left: 0; 20 | right: 0; 21 | bottom: 0; 22 | background-color: #ccc; 23 | -webkit-transition: .4s; 24 | transition: .4s; 25 | } 26 | 27 | .switch .slider:before { 28 | position: absolute; 29 | content: ""; 30 | height: 16px; 31 | width: 16px; 32 | left: 4px; 33 | bottom: 4px; 34 | background-color: white; 35 | -webkit-transition: .4s; 36 | transition: .4s; 37 | } 38 | 39 | .switch input[type='checkbox']:checked + .slider { 40 | background-color: #2196F3; 41 | } 42 | 43 | .switch .switch input[type='checkbox']:focus + .slider { 44 | box-shadow: 0 0 1px #2196F3; 45 | } 46 | 47 | .switch input[type='checkbox']:checked + .slider:before { 48 | -webkit-transform: translateX(16px); 49 | -ms-transform: translateX(16px); 50 | transform: translateX(16px); 51 | } 52 | 53 | /* Rounded sliders */ 54 | .switch .slider.round { 55 | border-radius: 34px; 56 | } 57 | 58 | .switch .slider.round:before { 59 | border-radius: 50%; 60 | } -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/ld/eagle.app.v6.common.ld: -------------------------------------------------------------------------------- 1 | /* This linker script generated from xt-genldscripts.tpp for LSP . */ 2 | /* Linker Script for ld -N */ 3 | 4 | PHDRS 5 | { 6 | dport0_0_phdr PT_LOAD; 7 | dram0_0_phdr PT_LOAD; 8 | dram0_0_bss_phdr PT_LOAD; 9 | iram1_0_phdr PT_LOAD; 10 | irom0_0_phdr PT_LOAD; 11 | } 12 | 13 | 14 | /* Default entry point: */ 15 | ENTRY(call_user_start) 16 | EXTERN(_DebugExceptionVector) 17 | EXTERN(_DoubleExceptionVector) 18 | EXTERN(_KernelExceptionVector) 19 | EXTERN(_NMIExceptionVector) 20 | EXTERN(_UserExceptionVector) 21 | PROVIDE(_memmap_vecbase_reset = 0x40000000); 22 | /* Various memory-map dependent cache attribute settings: */ 23 | _memmap_cacheattr_wb_base = 0x00000110; 24 | _memmap_cacheattr_wt_base = 0x00000110; 25 | _memmap_cacheattr_bp_base = 0x00000220; 26 | _memmap_cacheattr_unused_mask = 0xFFFFF00F; 27 | _memmap_cacheattr_wb_trapnull = 0x2222211F; 28 | _memmap_cacheattr_wba_trapnull = 0x2222211F; 29 | _memmap_cacheattr_wbna_trapnull = 0x2222211F; 30 | _memmap_cacheattr_wt_trapnull = 0x2222211F; 31 | _memmap_cacheattr_bp_trapnull = 0x2222222F; 32 | _memmap_cacheattr_wb_strict = 0xFFFFF11F; 33 | _memmap_cacheattr_wt_strict = 0xFFFFF11F; 34 | _memmap_cacheattr_bp_strict = 0xFFFFF22F; 35 | _memmap_cacheattr_wb_allvalid = 0x22222112; 36 | _memmap_cacheattr_wt_allvalid = 0x22222112; 37 | _memmap_cacheattr_bp_allvalid = 0x22222222; 38 | PROVIDE(_memmap_cacheattr_reset = _memmap_cacheattr_wb_trapnull); 39 | 40 | SECTIONS 41 | { 42 | 43 | .dport0.rodata : ALIGN(4) 44 | { 45 | _dport0_rodata_start = ABSOLUTE(.); 46 | *(.dport0.rodata) 47 | *(.dport.rodata) 48 | _dport0_rodata_end = ABSOLUTE(.); 49 | } >dport0_0_seg :dport0_0_phdr 50 | 51 | .dport0.literal : ALIGN(4) 52 | { 53 | _dport0_literal_start = ABSOLUTE(.); 54 | *(.dport0.literal) 55 | *(.dport.literal) 56 | _dport0_literal_end = ABSOLUTE(.); 57 | } >dport0_0_seg :dport0_0_phdr 58 | 59 | .dport0.data : ALIGN(4) 60 | { 61 | _dport0_data_start = ABSOLUTE(.); 62 | *(.dport0.data) 63 | *(.dport.data) 64 | _dport0_data_end = ABSOLUTE(.); 65 | } >dport0_0_seg :dport0_0_phdr 66 | 67 | .data : ALIGN(4) 68 | { 69 | _data_start = ABSOLUTE(.); 70 | *(.data) 71 | *(.data.*) 72 | *(.gnu.linkonce.d.*) 73 | *(.data1) 74 | *(.sdata) 75 | *(.sdata.*) 76 | *(.gnu.linkonce.s.*) 77 | *(.sdata2) 78 | *(.sdata2.*) 79 | *(.gnu.linkonce.s2.*) 80 | *(.jcr) 81 | . = ALIGN(4); 82 | _Pri_3_HandlerAddress = ABSOLUTE(.); 83 | _data_end = ABSOLUTE(.); 84 | } >dram0_0_seg :dram0_0_phdr 85 | 86 | .rodata : ALIGN(4) 87 | { 88 | _rodata_start = ABSOLUTE(.); 89 | *(.sdk.version) 90 | *(.rodata) 91 | *(.rodata.*) 92 | *(.gnu.linkonce.r.*) 93 | *(.rodata1) 94 | __XT_EXCEPTION_TABLE__ = ABSOLUTE(.); 95 | *(.xt_except_table) 96 | *(.gcc_except_table) 97 | *(.gnu.linkonce.e.*) 98 | *(.gnu.version_r) 99 | *(.eh_frame) 100 | . = (. + 3) & ~ 3; 101 | /* C++ constructor and destructor tables, properly ordered: */ 102 | __init_array_start = ABSOLUTE(.); 103 | KEEP (*crtbegin.o(.ctors)) 104 | KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors)) 105 | KEEP (*(SORT(.ctors.*))) 106 | KEEP (*(.ctors)) 107 | __init_array_end = ABSOLUTE(.); 108 | KEEP (*crtbegin.o(.dtors)) 109 | KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors)) 110 | KEEP (*(SORT(.dtors.*))) 111 | KEEP (*(.dtors)) 112 | /* C++ exception handlers table: */ 113 | __XT_EXCEPTION_DESCS__ = ABSOLUTE(.); 114 | *(.xt_except_desc) 115 | *(.gnu.linkonce.h.*) 116 | __XT_EXCEPTION_DESCS_END__ = ABSOLUTE(.); 117 | *(.xt_except_desc_end) 118 | *(.dynamic) 119 | *(.gnu.version_d) 120 | . = ALIGN(4); /* this table MUST be 4-byte aligned */ 121 | _bss_table_start = ABSOLUTE(.); 122 | LONG(_bss_start) 123 | LONG(_bss_end) 124 | _bss_table_end = ABSOLUTE(.); 125 | _rodata_end = ABSOLUTE(.); 126 | } >dram0_0_seg :dram0_0_phdr 127 | 128 | .bss ALIGN(8) (NOLOAD) : ALIGN(4) 129 | { 130 | . = ALIGN (8); 131 | _bss_start = ABSOLUTE(.); 132 | *(.dynsbss) 133 | *(.sbss) 134 | *(.sbss.*) 135 | *(.gnu.linkonce.sb.*) 136 | *(.scommon) 137 | *(.sbss2) 138 | *(.sbss2.*) 139 | *(.gnu.linkonce.sb2.*) 140 | *(.dynbss) 141 | *(.bss) 142 | *(.bss.*) 143 | *(.gnu.linkonce.b.*) 144 | *(COMMON) 145 | . = ALIGN (8); 146 | _bss_end = ABSOLUTE(.); 147 | _heap_start = ABSOLUTE(.); 148 | /* _stack_sentry = ALIGN(0x8); */ 149 | } >dram0_0_seg :dram0_0_bss_phdr 150 | /* __stack = 0x3ffc8000; */ 151 | 152 | .irom0.text : ALIGN(4) 153 | { 154 | _irom0_text_start = ABSOLUTE(.); 155 | *(.ver_number) 156 | *.c.o( EXCLUDE_FILE (umm_malloc.c.o) .literal*, \ 157 | EXCLUDE_FILE (umm_malloc.c.o) .text*) 158 | *.cpp.o(.literal*, .text*) 159 | *libm.a:(.literal .text .literal.* .text.*) 160 | *libgcc.a:_umoddi3.o(.literal .text) 161 | *libgcc.a:_udivdi3.o(.literal .text) 162 | *libsmartconfig.a:(.literal .text .literal.* .text.*) 163 | *(.irom0.literal .irom.literal .irom.text.literal .irom0.text .irom.text .irom.text.*) 164 | _irom0_text_end = ABSOLUTE(.); 165 | _flash_code_end = ABSOLUTE(.); 166 | } >irom0_0_seg :irom0_0_phdr 167 | 168 | .text : ALIGN(4) 169 | { 170 | _stext = .; 171 | _text_start = ABSOLUTE(.); 172 | *(.UserEnter.text) 173 | . = ALIGN(16); 174 | *(.DebugExceptionVector.text) 175 | . = ALIGN(16); 176 | *(.NMIExceptionVector.text) 177 | . = ALIGN(16); 178 | *(.KernelExceptionVector.text) 179 | LONG(0) 180 | LONG(0) 181 | LONG(0) 182 | LONG(0) 183 | . = ALIGN(16); 184 | *(.UserExceptionVector.text) 185 | LONG(0) 186 | LONG(0) 187 | LONG(0) 188 | LONG(0) 189 | . = ALIGN(16); 190 | *(.DoubleExceptionVector.text) 191 | LONG(0) 192 | LONG(0) 193 | LONG(0) 194 | LONG(0) 195 | . = ALIGN (16); 196 | *(.entry.text) 197 | *(.init.literal) 198 | *(.init) 199 | *(.literal .text .literal.* .text.* .stub .gnu.warning .gnu.linkonce.literal.* .gnu.linkonce.t.*.literal .gnu.linkonce.t.*) 200 | *.cpp.o(.iram.text) 201 | *.c.o(.iram.text) 202 | *(.fini.literal) 203 | *(.fini) 204 | *(.gnu.version) 205 | _text_end = ABSOLUTE(.); 206 | _etext = .; 207 | } >iram1_0_seg :iram1_0_phdr 208 | 209 | .lit4 : ALIGN(4) 210 | { 211 | _lit4_start = ABSOLUTE(.); 212 | *(*.lit4) 213 | *(.lit4.*) 214 | *(.gnu.linkonce.lit4.*) 215 | _lit4_end = ABSOLUTE(.); 216 | } >iram1_0_seg :iram1_0_phdr 217 | 218 | 219 | } 220 | 221 | /* get ROM code address */ 222 | INCLUDE "../ld/eagle.rom.addr.v6.ld" 223 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/ld/eagle.flash.4m1m.ld: -------------------------------------------------------------------------------- 1 | /* Flash Split for 4M chips */ 2 | /* sketch 1019KB */ 3 | /* empty 2048KB */ 4 | /* spiffs 1004KB */ 5 | /* eeprom 20KB */ 6 | 7 | MEMORY 8 | { 9 | dport0_0_seg : org = 0x3FF00000, len = 0x10 10 | dram0_0_seg : org = 0x3FFE8000, len = 0x14000 11 | iram1_0_seg : org = 0x40100000, len = 0x8000 12 | irom0_0_seg : org = 0x40201010, len = 0xfeff0 13 | } 14 | 15 | PROVIDE ( _SPIFFS_start = 0x40500000 ); 16 | PROVIDE ( _SPIFFS_end = 0x405FB000 ); 17 | PROVIDE ( _SPIFFS_page = 0x100 ); 18 | PROVIDE ( _SPIFFS_block = 0x2000 ); 19 | 20 | INCLUDE "ld/eagle.app.v6.common.ld" 21 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/.gitignore: -------------------------------------------------------------------------------- 1 | tests/bin 2 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: cpp 3 | compiler: 4 | - g++ 5 | script: cd tests && make && make test 6 | os: 7 | - linux 8 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/CHANGES.txt: -------------------------------------------------------------------------------- 1 | 2.7 2 | * Fix remaining-length handling to prevent buffer overrun 3 | * Add large-payload API - beginPublish/write/publish/endPublish 4 | * Add yield call to improve reliability on ESP 5 | * Add Clean Session flag to connect options 6 | * Add ESP32 support for functional callback signature 7 | * Various other fixes 8 | 9 | 2.4 10 | * Add MQTT_SOCKET_TIMEOUT to prevent it blocking indefinitely 11 | whilst waiting for inbound data 12 | * Fixed return code when publishing >256 bytes 13 | 14 | 2.3 15 | * Add publish(topic,payload,retained) function 16 | 17 | 2.2 18 | * Change code layout to match Arduino Library reqs 19 | 20 | 2.1 21 | * Add MAX_TRANSFER_SIZE def to chunk messages if needed 22 | * Reject topic/payloads that exceed MQTT_MAX_PACKET_SIZE 23 | 24 | 2.0 25 | * Add (and default to) MQTT 3.1.1 support 26 | * Fix PROGMEM handling for Intel Galileo/ESP8266 27 | * Add overloaded constructors for convenience 28 | * Add chainable setters for server/callback/client/stream 29 | * Add state function to return connack return code 30 | 31 | 1.9 32 | * Do not split MQTT packets over multiple calls to _client->write() 33 | * API change: All constructors now require an instance of Client 34 | to be passed in. 35 | * Fixed example to match 1.8 api changes - dpslwk 36 | * Added username/password support - WilHall 37 | * Added publish_P - publishes messages from PROGMEM - jobytaffey 38 | 39 | 1.8 40 | * KeepAlive interval is configurable in PubSubClient.h 41 | * Maximum packet size is configurable in PubSubClient.h 42 | * API change: Return boolean rather than int from various functions 43 | * API change: Length parameter in message callback changed 44 | from int to unsigned int 45 | * Various internal tidy-ups around types 46 | 1.7 47 | * Improved keepalive handling 48 | * Updated to the Arduino-1.0 API 49 | 1.6 50 | * Added the ability to publish a retained message 51 | 52 | 1.5 53 | * Added default constructor 54 | * Fixed compile error when used with arduino-0021 or later 55 | 56 | 1.4 57 | * Fixed connection lost handling 58 | 59 | 1.3 60 | * Fixed packet reading bug in PubSubClient.readPacket 61 | 62 | 1.2 63 | * Fixed compile error when used with arduino-0016 or later 64 | 65 | 66 | 1.1 67 | * Reduced size of library 68 | * Added support for Will messages 69 | * Clarified licensing - see LICENSE.txt 70 | 71 | 72 | 1.0 73 | * Only Quality of Service (QOS) 0 messaging is supported 74 | * The maximum message size, including header, is 128 bytes 75 | * The keepalive interval is set to 30 seconds 76 | * No support for Will messages 77 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2008-2015 Nicholas O'Leary 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/README.md: -------------------------------------------------------------------------------- 1 | # Arduino Client for MQTT 2 | 3 | This library provides a client for doing simple publish/subscribe messaging with 4 | a server that supports MQTT. 5 | 6 | ## Examples 7 | 8 | The library comes with a number of example sketches. See File > Examples > PubSubClient 9 | within the Arduino application. 10 | 11 | Full API documentation is available here: https://pubsubclient.knolleary.net 12 | 13 | ## Limitations 14 | 15 | - It can only publish QoS 0 messages. It can subscribe at QoS 0 or QoS 1. 16 | - The maximum message size, including header, is **128 bytes** by default. This 17 | is configurable via `MQTT_MAX_PACKET_SIZE` in `PubSubClient.h`. 18 | - The keepalive interval is set to 15 seconds by default. This is configurable 19 | via `MQTT_KEEPALIVE` in `PubSubClient.h`. 20 | - The client uses MQTT 3.1.1 by default. It can be changed to use MQTT 3.1 by 21 | changing value of `MQTT_VERSION` in `PubSubClient.h`. 22 | 23 | 24 | ## Compatible Hardware 25 | 26 | The library uses the Arduino Ethernet Client api for interacting with the 27 | underlying network hardware. This means it Just Works with a growing number of 28 | boards and shields, including: 29 | 30 | - Arduino Ethernet 31 | - Arduino Ethernet Shield 32 | - Arduino YUN – use the included `YunClient` in place of `EthernetClient`, and 33 | be sure to do a `Bridge.begin()` first 34 | - Arduino WiFi Shield - if you want to send packets > 90 bytes with this shield, 35 | enable the `MQTT_MAX_TRANSFER_SIZE` define in `PubSubClient.h`. 36 | - Sparkfun WiFly Shield – [library](https://github.com/dpslwk/WiFly) 37 | - TI CC3000 WiFi - [library](https://github.com/sparkfun/SFE_CC3000_Library) 38 | - Intel Galileo/Edison 39 | - ESP8266 40 | - ESP32 41 | 42 | The library cannot currently be used with hardware based on the ENC28J60 chip – 43 | such as the Nanode or the Nuelectronics Ethernet Shield. For those, there is an 44 | [alternative library](https://github.com/njh/NanodeMQTT) available. 45 | 46 | ## License 47 | 48 | This code is released under the MIT License. 49 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/examples/mqtt_auth/mqtt_auth.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Basic MQTT example with Authentication 3 | 4 | - connects to an MQTT server, providing username 5 | and password 6 | - publishes "hello world" to the topic "outTopic" 7 | - subscribes to the topic "inTopic" 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | // Update these with values suitable for your network. 15 | byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; 16 | IPAddress ip(172, 16, 0, 100); 17 | IPAddress server(172, 16, 0, 2); 18 | 19 | void callback(char* topic, byte* payload, unsigned int length) { 20 | // handle message arrived 21 | } 22 | 23 | EthernetClient ethClient; 24 | PubSubClient client(server, 1883, callback, ethClient); 25 | 26 | void setup() 27 | { 28 | Ethernet.begin(mac, ip); 29 | // Note - the default maximum packet size is 128 bytes. If the 30 | // combined length of clientId, username and password exceed this, 31 | // you will need to increase the value of MQTT_MAX_PACKET_SIZE in 32 | // PubSubClient.h 33 | 34 | if (client.connect("arduinoClient", "testuser", "testpass")) { 35 | client.publish("outTopic","hello world"); 36 | client.subscribe("inTopic"); 37 | } 38 | } 39 | 40 | void loop() 41 | { 42 | client.loop(); 43 | } 44 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/examples/mqtt_basic/mqtt_basic.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Basic MQTT example 3 | 4 | This sketch demonstrates the basic capabilities of the library. 5 | It connects to an MQTT server then: 6 | - publishes "hello world" to the topic "outTopic" 7 | - subscribes to the topic "inTopic", printing out any messages 8 | it receives. NB - it assumes the received payloads are strings not binary 9 | 10 | It will reconnect to the server if the connection is lost using a blocking 11 | reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to 12 | achieve the same result without blocking the main loop. 13 | 14 | */ 15 | 16 | #include 17 | #include 18 | #include 19 | 20 | // Update these with values suitable for your network. 21 | byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; 22 | IPAddress ip(172, 16, 0, 100); 23 | IPAddress server(172, 16, 0, 2); 24 | 25 | void callback(char* topic, byte* payload, unsigned int length) { 26 | Serial.print("Message arrived ["); 27 | Serial.print(topic); 28 | Serial.print("] "); 29 | for (int i=0;i Preferences -> Additional Boards Manager URLs": 20 | http://arduino.esp8266.com/stable/package_esp8266com_index.json 21 | - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266" 22 | - Select your ESP8266 in "Tools -> Board" 23 | 24 | */ 25 | 26 | #include 27 | #include 28 | 29 | // Update these with values suitable for your network. 30 | 31 | const char* ssid = "........"; 32 | const char* password = "........"; 33 | const char* mqtt_server = "broker.mqtt-dashboard.com"; 34 | 35 | WiFiClient espClient; 36 | PubSubClient client(espClient); 37 | long lastMsg = 0; 38 | char msg[50]; 39 | int value = 0; 40 | 41 | void setup_wifi() { 42 | 43 | delay(10); 44 | // We start by connecting to a WiFi network 45 | Serial.println(); 46 | Serial.print("Connecting to "); 47 | Serial.println(ssid); 48 | 49 | WiFi.begin(ssid, password); 50 | 51 | while (WiFi.status() != WL_CONNECTED) { 52 | delay(500); 53 | Serial.print("."); 54 | } 55 | 56 | randomSeed(micros()); 57 | 58 | Serial.println(""); 59 | Serial.println("WiFi connected"); 60 | Serial.println("IP address: "); 61 | Serial.println(WiFi.localIP()); 62 | } 63 | 64 | void callback(char* topic, byte* payload, unsigned int length) { 65 | Serial.print("Message arrived ["); 66 | Serial.print(topic); 67 | Serial.print("] "); 68 | for (int i = 0; i < length; i++) { 69 | Serial.print((char)payload[i]); 70 | } 71 | Serial.println(); 72 | 73 | // Switch on the LED if an 1 was received as first character 74 | if ((char)payload[0] == '1') { 75 | digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level 76 | // but actually the LED is on; this is because 77 | // it is active low on the ESP-01) 78 | } else { 79 | digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH 80 | } 81 | 82 | } 83 | 84 | void reconnect() { 85 | // Loop until we're reconnected 86 | while (!client.connected()) { 87 | Serial.print("Attempting MQTT connection..."); 88 | // Create a random client ID 89 | String clientId = "ESP8266Client-"; 90 | clientId += String(random(0xffff), HEX); 91 | // Attempt to connect 92 | if (client.connect(clientId.c_str())) { 93 | Serial.println("connected"); 94 | // Once connected, publish an announcement... 95 | client.publish("outTopic", "hello world"); 96 | // ... and resubscribe 97 | client.subscribe("inTopic"); 98 | } else { 99 | Serial.print("failed, rc="); 100 | Serial.print(client.state()); 101 | Serial.println(" try again in 5 seconds"); 102 | // Wait 5 seconds before retrying 103 | delay(5000); 104 | } 105 | } 106 | } 107 | 108 | void setup() { 109 | pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output 110 | Serial.begin(115200); 111 | setup_wifi(); 112 | client.setServer(mqtt_server, 1883); 113 | client.setCallback(callback); 114 | } 115 | 116 | void loop() { 117 | 118 | if (!client.connected()) { 119 | reconnect(); 120 | } 121 | client.loop(); 122 | 123 | long now = millis(); 124 | if (now - lastMsg > 2000) { 125 | lastMsg = now; 126 | ++value; 127 | snprintf (msg, 50, "hello world #%ld", value); 128 | Serial.print("Publish message: "); 129 | Serial.println(msg); 130 | client.publish("outTopic", msg); 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/examples/mqtt_large_message/mqtt_large_message.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Long message ESP8266 MQTT example 3 | 4 | This sketch demonstrates sending arbitrarily large messages in combination 5 | with the ESP8266 board/library. 6 | 7 | It connects to an MQTT server then: 8 | - publishes "hello world" to the topic "outTopic" 9 | - subscribes to the topic "greenBottles/#", printing out any messages 10 | it receives. NB - it assumes the received payloads are strings not binary 11 | - If the sub-topic is a number, it publishes a "greenBottles/lyrics" message 12 | with a payload consisting of the lyrics to "10 green bottles", replacing 13 | 10 with the number given in the sub-topic. 14 | 15 | It will reconnect to the server if the connection is lost using a blocking 16 | reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to 17 | achieve the same result without blocking the main loop. 18 | 19 | To install the ESP8266 board, (using Arduino 1.6.4+): 20 | - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs": 21 | http://arduino.esp8266.com/stable/package_esp8266com_index.json 22 | - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266" 23 | - Select your ESP8266 in "Tools -> Board" 24 | 25 | */ 26 | 27 | #include 28 | #include 29 | 30 | // Update these with values suitable for your network. 31 | 32 | const char* ssid = "........"; 33 | const char* password = "........"; 34 | const char* mqtt_server = "broker.mqtt-dashboard.com"; 35 | 36 | WiFiClient espClient; 37 | PubSubClient client(espClient); 38 | long lastMsg = 0; 39 | char msg[50]; 40 | int value = 0; 41 | 42 | void setup_wifi() { 43 | 44 | delay(10); 45 | // We start by connecting to a WiFi network 46 | Serial.println(); 47 | Serial.print("Connecting to "); 48 | Serial.println(ssid); 49 | 50 | WiFi.begin(ssid, password); 51 | 52 | while (WiFi.status() != WL_CONNECTED) { 53 | delay(500); 54 | Serial.print("."); 55 | } 56 | 57 | randomSeed(micros()); 58 | 59 | Serial.println(""); 60 | Serial.println("WiFi connected"); 61 | Serial.println("IP address: "); 62 | Serial.println(WiFi.localIP()); 63 | } 64 | 65 | void callback(char* topic, byte* payload, unsigned int length) { 66 | Serial.print("Message arrived ["); 67 | Serial.print(topic); 68 | Serial.print("] "); 69 | for (int i = 0; i < length; i++) { 70 | Serial.print((char)payload[i]); 71 | } 72 | Serial.println(); 73 | 74 | // Find out how many bottles we should generate lyrics for 75 | String topicStr(topic); 76 | int bottleCount = 0; // assume no bottles unless we correctly parse a value from the topic 77 | if (topicStr.indexOf('/') >= 0) { 78 | // The topic includes a '/', we'll try to read the number of bottles from just after that 79 | topicStr.remove(0, topicStr.indexOf('/')+1); 80 | // Now see if there's a number of bottles after the '/' 81 | bottleCount = topicStr.toInt(); 82 | } 83 | 84 | if (bottleCount > 0) { 85 | // Work out how big our resulting message will be 86 | int msgLen = 0; 87 | for (int i = bottleCount; i > 0; i--) { 88 | String numBottles(i); 89 | msgLen += 2*numBottles.length(); 90 | if (i == 1) { 91 | msgLen += 2*String(" green bottle, standing on the wall\n").length(); 92 | } else { 93 | msgLen += 2*String(" green bottles, standing on the wall\n").length(); 94 | } 95 | msgLen += String("And if one green bottle should accidentally fall\nThere'll be ").length(); 96 | switch (i) { 97 | case 1: 98 | msgLen += String("no green bottles, standing on the wall\n\n").length(); 99 | break; 100 | case 2: 101 | msgLen += String("1 green bottle, standing on the wall\n\n").length(); 102 | break; 103 | default: 104 | numBottles = i-1; 105 | msgLen += numBottles.length(); 106 | msgLen += String(" green bottles, standing on the wall\n\n").length(); 107 | break; 108 | }; 109 | } 110 | 111 | // Now we can start to publish the message 112 | client.beginPublish("greenBottles/lyrics", msgLen, false); 113 | for (int i = bottleCount; i > 0; i--) { 114 | for (int j = 0; j < 2; j++) { 115 | client.print(i); 116 | if (i == 1) { 117 | client.print(" green bottle, standing on the wall\n"); 118 | } else { 119 | client.print(" green bottles, standing on the wall\n"); 120 | } 121 | } 122 | client.print("And if one green bottle should accidentally fall\nThere'll be "); 123 | switch (i) { 124 | case 1: 125 | client.print("no green bottles, standing on the wall\n\n"); 126 | break; 127 | case 2: 128 | client.print("1 green bottle, standing on the wall\n\n"); 129 | break; 130 | default: 131 | client.print(i-1); 132 | client.print(" green bottles, standing on the wall\n\n"); 133 | break; 134 | }; 135 | } 136 | // Now we're done! 137 | client.endPublish(); 138 | } 139 | } 140 | 141 | void reconnect() { 142 | // Loop until we're reconnected 143 | while (!client.connected()) { 144 | Serial.print("Attempting MQTT connection..."); 145 | // Create a random client ID 146 | String clientId = "ESP8266Client-"; 147 | clientId += String(random(0xffff), HEX); 148 | // Attempt to connect 149 | if (client.connect(clientId.c_str())) { 150 | Serial.println("connected"); 151 | // Once connected, publish an announcement... 152 | client.publish("outTopic", "hello world"); 153 | // ... and resubscribe 154 | client.subscribe("greenBottles/#"); 155 | } else { 156 | Serial.print("failed, rc="); 157 | Serial.print(client.state()); 158 | Serial.println(" try again in 5 seconds"); 159 | // Wait 5 seconds before retrying 160 | delay(5000); 161 | } 162 | } 163 | } 164 | 165 | void setup() { 166 | pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output 167 | Serial.begin(115200); 168 | setup_wifi(); 169 | client.setServer(mqtt_server, 1883); 170 | client.setCallback(callback); 171 | } 172 | 173 | void loop() { 174 | 175 | if (!client.connected()) { 176 | reconnect(); 177 | } 178 | client.loop(); 179 | } 180 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/examples/mqtt_publish_in_callback/mqtt_publish_in_callback.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Publishing in the callback 3 | 4 | - connects to an MQTT server 5 | - subscribes to the topic "inTopic" 6 | - when a message is received, republishes it to "outTopic" 7 | 8 | This example shows how to publish messages within the 9 | callback function. The callback function header needs to 10 | be declared before the PubSubClient constructor and the 11 | actual callback defined afterwards. 12 | This ensures the client reference in the callback function 13 | is valid. 14 | 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | // Update these with values suitable for your network. 22 | byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; 23 | IPAddress ip(172, 16, 0, 100); 24 | IPAddress server(172, 16, 0, 2); 25 | 26 | // Callback function header 27 | void callback(char* topic, byte* payload, unsigned int length); 28 | 29 | EthernetClient ethClient; 30 | PubSubClient client(server, 1883, callback, ethClient); 31 | 32 | // Callback function 33 | void callback(char* topic, byte* payload, unsigned int length) { 34 | // In order to republish this payload, a copy must be made 35 | // as the orignal payload buffer will be overwritten whilst 36 | // constructing the PUBLISH packet. 37 | 38 | // Allocate the correct amount of memory for the payload copy 39 | byte* p = (byte*)malloc(length); 40 | // Copy the payload to the new buffer 41 | memcpy(p,payload,length); 42 | client.publish("outTopic", p, length); 43 | // Free the memory 44 | free(p); 45 | } 46 | 47 | void setup() 48 | { 49 | 50 | Ethernet.begin(mac, ip); 51 | if (client.connect("arduinoClient")) { 52 | client.publish("outTopic","hello world"); 53 | client.subscribe("inTopic"); 54 | } 55 | } 56 | 57 | void loop() 58 | { 59 | client.loop(); 60 | } 61 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/examples/mqtt_reconnect_nonblocking/mqtt_reconnect_nonblocking.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Reconnecting MQTT example - non-blocking 3 | 4 | This sketch demonstrates how to keep the client connected 5 | using a non-blocking reconnect function. If the client loses 6 | its connection, it attempts to reconnect every 5 seconds 7 | without blocking the main loop. 8 | 9 | */ 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | // Update these with values suitable for your hardware/network. 16 | byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; 17 | IPAddress ip(172, 16, 0, 100); 18 | IPAddress server(172, 16, 0, 2); 19 | 20 | void callback(char* topic, byte* payload, unsigned int length) { 21 | // handle message arrived 22 | } 23 | 24 | EthernetClient ethClient; 25 | PubSubClient client(ethClient); 26 | 27 | long lastReconnectAttempt = 0; 28 | 29 | boolean reconnect() { 30 | if (client.connect("arduinoClient")) { 31 | // Once connected, publish an announcement... 32 | client.publish("outTopic","hello world"); 33 | // ... and resubscribe 34 | client.subscribe("inTopic"); 35 | } 36 | return client.connected(); 37 | } 38 | 39 | void setup() 40 | { 41 | client.setServer(server, 1883); 42 | client.setCallback(callback); 43 | 44 | Ethernet.begin(mac, ip); 45 | delay(1500); 46 | lastReconnectAttempt = 0; 47 | } 48 | 49 | 50 | void loop() 51 | { 52 | if (!client.connected()) { 53 | long now = millis(); 54 | if (now - lastReconnectAttempt > 5000) { 55 | lastReconnectAttempt = now; 56 | // Attempt to reconnect 57 | if (reconnect()) { 58 | lastReconnectAttempt = 0; 59 | } 60 | } 61 | } else { 62 | // Client connected 63 | 64 | client.loop(); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/examples/mqtt_stream/mqtt_stream.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Example of using a Stream object to store the message payload 3 | 4 | Uses SRAM library: https://github.com/ennui2342/arduino-sram 5 | but could use any Stream based class such as SD 6 | 7 | - connects to an MQTT server 8 | - publishes "hello world" to the topic "outTopic" 9 | - subscribes to the topic "inTopic" 10 | */ 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | // Update these with values suitable for your network. 18 | byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; 19 | IPAddress ip(172, 16, 0, 100); 20 | IPAddress server(172, 16, 0, 2); 21 | 22 | SRAM sram(4, SRAM_1024); 23 | 24 | void callback(char* topic, byte* payload, unsigned int length) { 25 | sram.seek(1); 26 | 27 | // do something with the message 28 | for(uint8_t i=0; i 4 | maintainer=Nick O'Leary 5 | sentence=A client library for MQTT messaging. 6 | paragraph=MQTT is a lightweight messaging protocol ideal for small devices. This library allows you to send and receive MQTT messages. It supports the latest MQTT 3.1.1 protocol and can be configured to use the older MQTT 3.1 if needed. It supports all Arduino Ethernet Client compatible hardware, including the Intel Galileo/Edison, ESP8266 and TI CC3000. 7 | category=Communication 8 | url=http://pubsubclient.knolleary.net 9 | architectures=* 10 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/src/PubSubClient.h: -------------------------------------------------------------------------------- 1 | /* 2 | PubSubClient.h - A simple client for MQTT. 3 | Nick O'Leary 4 | http://knolleary.net 5 | */ 6 | 7 | #ifndef PubSubClient_h 8 | #define PubSubClient_h 9 | 10 | #include 11 | #include "IPAddress.h" 12 | #include "Client.h" 13 | #include "Stream.h" 14 | 15 | #define MQTT_VERSION_3_1 3 16 | #define MQTT_VERSION_3_1_1 4 17 | 18 | // MQTT_VERSION : Pick the version 19 | //#define MQTT_VERSION MQTT_VERSION_3_1 20 | #ifndef MQTT_VERSION 21 | #define MQTT_VERSION MQTT_VERSION_3_1_1 22 | #endif 23 | 24 | // MQTT_MAX_PACKET_SIZE : Maximum packet size 25 | #ifndef MQTT_MAX_PACKET_SIZE 26 | //#define MQTT_MAX_PACKET_SIZE 128 27 | #define MQTT_MAX_PACKET_SIZE 1000 // Tasmota v5.11.1c 28 | #endif 29 | 30 | // MQTT_KEEPALIVE : keepAlive interval in Seconds 31 | // Keepalive timeout for default MQTT Broker is 10s 32 | #ifndef MQTT_KEEPALIVE 33 | //#define MQTT_KEEPALIVE 10 34 | #define MQTT_KEEPALIVE 30 // Tasmota v6.5.0.14 enabling AWS-iot 35 | #endif 36 | 37 | // MQTT_SOCKET_TIMEOUT: socket timeout interval in Seconds 38 | #ifndef MQTT_SOCKET_TIMEOUT 39 | #define MQTT_SOCKET_TIMEOUT 15 40 | #endif 41 | 42 | // MQTT_MAX_TRANSFER_SIZE : limit how much data is passed to the network client 43 | // in each write call. Needed for the Arduino Wifi Shield. Leave undefined to 44 | // pass the entire MQTT packet in each write call. 45 | //#define MQTT_MAX_TRANSFER_SIZE 80 46 | 47 | // Possible values for client.state() 48 | #define MQTT_CONNECTION_TIMEOUT -4 49 | #define MQTT_CONNECTION_LOST -3 50 | #define MQTT_CONNECT_FAILED -2 51 | #define MQTT_DISCONNECTED -1 52 | #define MQTT_CONNECTED 0 53 | #define MQTT_CONNECT_BAD_PROTOCOL 1 54 | #define MQTT_CONNECT_BAD_CLIENT_ID 2 55 | #define MQTT_CONNECT_UNAVAILABLE 3 56 | #define MQTT_CONNECT_BAD_CREDENTIALS 4 57 | #define MQTT_CONNECT_UNAUTHORIZED 5 58 | 59 | #define MQTTCONNECT 1 << 4 // Client request to connect to Server 60 | #define MQTTCONNACK 2 << 4 // Connect Acknowledgment 61 | #define MQTTPUBLISH 3 << 4 // Publish message 62 | #define MQTTPUBACK 4 << 4 // Publish Acknowledgment 63 | #define MQTTPUBREC 5 << 4 // Publish Received (assured delivery part 1) 64 | #define MQTTPUBREL 6 << 4 // Publish Release (assured delivery part 2) 65 | #define MQTTPUBCOMP 7 << 4 // Publish Complete (assured delivery part 3) 66 | #define MQTTSUBSCRIBE 8 << 4 // Client Subscribe request 67 | #define MQTTSUBACK 9 << 4 // Subscribe Acknowledgment 68 | #define MQTTUNSUBSCRIBE 10 << 4 // Client Unsubscribe request 69 | #define MQTTUNSUBACK 11 << 4 // Unsubscribe Acknowledgment 70 | #define MQTTPINGREQ 12 << 4 // PING Request 71 | #define MQTTPINGRESP 13 << 4 // PING Response 72 | #define MQTTDISCONNECT 14 << 4 // Client is Disconnecting 73 | #define MQTTReserved 15 << 4 // Reserved 74 | 75 | #define MQTTQOS0 (0 << 1) 76 | #define MQTTQOS1 (1 << 1) 77 | #define MQTTQOS2 (2 << 1) 78 | 79 | // Maximum size of fixed header and variable length size header 80 | #define MQTT_MAX_HEADER_SIZE 5 81 | 82 | #if defined(ESP8266) || defined(ESP32) 83 | #include 84 | #define MQTT_CALLBACK_SIGNATURE std::function callback 85 | #else 86 | #define MQTT_CALLBACK_SIGNATURE void (*callback)(char*, uint8_t*, unsigned int) 87 | #endif 88 | 89 | #define CHECK_STRING_LENGTH(l,s) if (l+2+strlen(s) > MQTT_MAX_PACKET_SIZE) {_client->stop();return false;} 90 | 91 | class PubSubClient : public Print { 92 | private: 93 | Client* _client; 94 | uint8_t buffer[MQTT_MAX_PACKET_SIZE]; 95 | uint16_t nextMsgId; 96 | unsigned long lastOutActivity; 97 | unsigned long lastInActivity; 98 | bool pingOutstanding; 99 | MQTT_CALLBACK_SIGNATURE; 100 | uint16_t readPacket(uint8_t*); 101 | boolean readByte(uint8_t * result); 102 | boolean readByte(uint8_t * result, uint16_t * index); 103 | boolean write(uint8_t header, uint8_t* buf, uint16_t length); 104 | uint16_t writeString(const char* string, uint8_t* buf, uint16_t pos); 105 | // Build up the header ready to send 106 | // Returns the size of the header 107 | // Note: the header is built at the end of the first MQTT_MAX_HEADER_SIZE bytes, so will start 108 | // (MQTT_MAX_HEADER_SIZE - ) bytes into the buffer 109 | size_t buildHeader(uint8_t header, uint8_t* buf, uint16_t length); 110 | IPAddress ip; 111 | String domain; 112 | uint16_t port; 113 | Stream* stream; 114 | int _state; 115 | public: 116 | PubSubClient(); 117 | PubSubClient(Client& client); 118 | PubSubClient(IPAddress, uint16_t, Client& client); 119 | PubSubClient(IPAddress, uint16_t, Client& client, Stream&); 120 | PubSubClient(IPAddress, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client); 121 | PubSubClient(IPAddress, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client, Stream&); 122 | PubSubClient(uint8_t *, uint16_t, Client& client); 123 | PubSubClient(uint8_t *, uint16_t, Client& client, Stream&); 124 | PubSubClient(uint8_t *, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client); 125 | PubSubClient(uint8_t *, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client, Stream&); 126 | PubSubClient(const char*, uint16_t, Client& client); 127 | PubSubClient(const char*, uint16_t, Client& client, Stream&); 128 | PubSubClient(const char*, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client); 129 | PubSubClient(const char*, uint16_t, MQTT_CALLBACK_SIGNATURE,Client& client, Stream&); 130 | virtual ~PubSubClient() {} 131 | 132 | PubSubClient& setServer(IPAddress ip, uint16_t port); 133 | PubSubClient& setServer(uint8_t * ip, uint16_t port); 134 | PubSubClient& setServer(const char * domain, uint16_t port); 135 | PubSubClient& setCallback(MQTT_CALLBACK_SIGNATURE); 136 | PubSubClient& setClient(Client& client); 137 | PubSubClient& setStream(Stream& stream); 138 | 139 | boolean connect(const char* id); 140 | boolean connect(const char* id, const char* user, const char* pass); 141 | boolean connect(const char* id, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage); 142 | boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage); 143 | boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage, boolean cleanSession); 144 | void disconnect(); 145 | boolean publish(const char* topic, const char* payload); 146 | boolean publish(const char* topic, const char* payload, boolean retained); 147 | boolean publish(const char* topic, const uint8_t * payload, unsigned int plength); 148 | boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained); 149 | boolean publish_P(const char* topic, const char* payload, boolean retained); 150 | boolean publish_P(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained); 151 | // Start to publish a message. 152 | // This API: 153 | // beginPublish(...) 154 | // one or more calls to write(...) 155 | // endPublish() 156 | // Allows for arbitrarily large payloads to be sent without them having to be copied into 157 | // a new buffer and held in memory at one time 158 | // Returns 1 if the message was started successfully, 0 if there was an error 159 | boolean beginPublish(const char* topic, unsigned int plength, boolean retained); 160 | // Finish off this publish message (started with beginPublish) 161 | // Returns 1 if the packet was sent successfully, 0 if there was an error 162 | int endPublish(); 163 | // Write a single byte of payload (only to be used with beginPublish/endPublish) 164 | virtual size_t write(uint8_t); 165 | // Write size bytes from buffer into the payload (only to be used with beginPublish/endPublish) 166 | // Returns the number of bytes written 167 | virtual size_t write(const uint8_t *buffer, size_t size); 168 | boolean subscribe(const char* topic); 169 | boolean subscribe(const char* topic, uint8_t qos); 170 | boolean unsubscribe(const char* topic); 171 | boolean loop(); 172 | boolean connected(); 173 | int state(); 174 | }; 175 | 176 | 177 | #endif 178 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/.gitignore: -------------------------------------------------------------------------------- 1 | .build 2 | tmpbin 3 | logs 4 | *.pyc 5 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/Makefile: -------------------------------------------------------------------------------- 1 | SRC_PATH=./src 2 | OUT_PATH=./bin 3 | TEST_SRC=$(wildcard ${SRC_PATH}/*_spec.cpp) 4 | TEST_BIN= $(TEST_SRC:${SRC_PATH}/%.cpp=${OUT_PATH}/%) 5 | VPATH=${SRC_PATH} 6 | SHIM_FILES=${SRC_PATH}/lib/*.cpp 7 | PSC_FILE=../src/PubSubClient.cpp 8 | CC=g++ 9 | CFLAGS=-I${SRC_PATH}/lib -I../src 10 | 11 | all: $(TEST_BIN) 12 | 13 | ${OUT_PATH}/%: ${SRC_PATH}/%.cpp ${PSC_FILE} ${SHIM_FILES} 14 | mkdir -p ${OUT_PATH} 15 | ${CC} ${CFLAGS} $^ -o $@ 16 | 17 | clean: 18 | @rm -rf ${OUT_PATH} 19 | 20 | test: 21 | @bin/connect_spec 22 | @bin/publish_spec 23 | @bin/receive_spec 24 | @bin/subscribe_spec 25 | @bin/keepalive_spec 26 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/README.md: -------------------------------------------------------------------------------- 1 | # Arduino Client for MQTT Test Suite 2 | 3 | This is a regression test suite for the `PubSubClient` library. 4 | 5 | There are two parts: 6 | 7 | - Tests that can be compiled and run on any machine 8 | - Tests that build the example sketches using the Arduino IDE 9 | 10 | 11 | It is a work-in-progress and is subject to complete refactoring as the whim takes 12 | me. 13 | 14 | 15 | ## Local tests 16 | 17 | These are a set of executables that can be run to test specific areas of functionality. 18 | They do not require a real Arduino to be attached, nor the use of the Arduino IDE. 19 | 20 | The tests include a set of mock files to stub out the parts of the Arduino environment the library 21 | depends on. 22 | 23 | ### Dependencies 24 | 25 | - g++ 26 | 27 | ### Running 28 | 29 | Build the tests using the provided `Makefile`: 30 | 31 | $ make 32 | 33 | This will create a set of executables in `./bin/`. Run each of these executables to test the corresponding functionality. 34 | 35 | *Note:* the `connect_spec` and `keepalive_spec` tests involve testing keepalive timers so naturally take a few minutes to run through. 36 | 37 | ## Arduino tests 38 | 39 | *Note:* INO Tool doesn't currently play nicely with Arduino 1.5. This has broken this test suite. 40 | 41 | Without a suitable arduino plugged in, the test suite will only check the 42 | example sketches compile cleanly against the library. 43 | 44 | With an arduino plugged in, each sketch that has a corresponding python 45 | test case is built, uploaded and then the tests run. 46 | 47 | ### Dependencies 48 | 49 | - Python 2.7+ 50 | - [INO Tool](http://inotool.org/) - this provides command-line build/upload of Arduino sketches 51 | 52 | ### Running 53 | 54 | The test suite _does not_ run an MQTT server - it is assumed to be running already. 55 | 56 | $ python testsuite.py 57 | 58 | A summary of activity is printed to the console. More comprehensive logs are written 59 | to the `logs` directory. 60 | 61 | ### What it does 62 | 63 | For each sketch in the library's `examples` directory, e.g. `mqtt_basic.ino`, the suite looks for a matching test case 64 | `testcases/mqtt_basic.py`. 65 | 66 | The test case must follow these conventions: 67 | - sub-class `unittest.TestCase` 68 | - provide the class methods `setUpClass` and `tearDownClass` (TODO: make this optional) 69 | - all test method names begin with `test_` 70 | 71 | The suite will call the `setUpClass` method _before_ uploading the sketch. This 72 | allows any test setup to be performed before the sketch runs - such as connecting 73 | a client and subscribing to topics. 74 | 75 | 76 | ### Settings 77 | 78 | The file `testcases/settings.py` is used to config the test environment. 79 | 80 | - `server_ip` - the IP address of the broker the client should connect to (the broker port is assumed to be 1883). 81 | - `arduino_ip` - the IP address the arduino should use (when not testing DHCP). 82 | 83 | Before each sketch is compiled, these values are automatically substituted in. To 84 | do this, the suite looks for lines that _start_ with the following: 85 | 86 | byte server[] = { 87 | byte ip[] = { 88 | 89 | and replaces them with the appropriate values. 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/keepalive_spec.cpp: -------------------------------------------------------------------------------- 1 | #include "PubSubClient.h" 2 | #include "ShimClient.h" 3 | #include "Buffer.h" 4 | #include "BDDTest.h" 5 | #include "trace.h" 6 | #include 7 | 8 | byte server[] = { 172, 16, 0, 2 }; 9 | 10 | void callback(char* topic, byte* payload, unsigned int length) { 11 | // handle message arrived 12 | } 13 | 14 | 15 | int test_keepalive_pings_idle() { 16 | IT("keeps an idle connection alive (takes 1 minute)"); 17 | 18 | ShimClient shimClient; 19 | shimClient.setAllowConnect(true); 20 | 21 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 22 | shimClient.respond(connack,4); 23 | 24 | PubSubClient client(server, 1883, callback, shimClient); 25 | int rc = client.connect((char*)"client_test1"); 26 | IS_TRUE(rc); 27 | 28 | byte pingreq[] = { 0xC0,0x0 }; 29 | shimClient.expect(pingreq,2); 30 | byte pingresp[] = { 0xD0,0x0 }; 31 | shimClient.respond(pingresp,2); 32 | 33 | for (int i = 0; i < 50; i++) { 34 | sleep(1); 35 | if ( i == 15 || i == 31 || i == 47) { 36 | shimClient.expect(pingreq,2); 37 | shimClient.respond(pingresp,2); 38 | } 39 | rc = client.loop(); 40 | IS_TRUE(rc); 41 | } 42 | 43 | IS_FALSE(shimClient.error()); 44 | 45 | END_IT 46 | } 47 | 48 | int test_keepalive_pings_with_outbound_qos0() { 49 | IT("keeps a connection alive that only sends qos0 (takes 1 minute)"); 50 | 51 | ShimClient shimClient; 52 | shimClient.setAllowConnect(true); 53 | 54 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 55 | shimClient.respond(connack,4); 56 | 57 | PubSubClient client(server, 1883, callback, shimClient); 58 | int rc = client.connect((char*)"client_test1"); 59 | IS_TRUE(rc); 60 | 61 | byte publish[] = {0x30,0xe,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; 62 | 63 | for (int i = 0; i < 50; i++) { 64 | TRACE(i<<":"); 65 | shimClient.expect(publish,16); 66 | rc = client.publish((char*)"topic",(char*)"payload"); 67 | IS_TRUE(rc); 68 | IS_FALSE(shimClient.error()); 69 | sleep(1); 70 | if ( i == 15 || i == 31 || i == 47) { 71 | byte pingreq[] = { 0xC0,0x0 }; 72 | shimClient.expect(pingreq,2); 73 | byte pingresp[] = { 0xD0,0x0 }; 74 | shimClient.respond(pingresp,2); 75 | } 76 | rc = client.loop(); 77 | IS_TRUE(rc); 78 | IS_FALSE(shimClient.error()); 79 | } 80 | 81 | END_IT 82 | } 83 | 84 | int test_keepalive_pings_with_inbound_qos0() { 85 | IT("keeps a connection alive that only receives qos0 (takes 1 minute)"); 86 | 87 | ShimClient shimClient; 88 | shimClient.setAllowConnect(true); 89 | 90 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 91 | shimClient.respond(connack,4); 92 | 93 | PubSubClient client(server, 1883, callback, shimClient); 94 | int rc = client.connect((char*)"client_test1"); 95 | IS_TRUE(rc); 96 | 97 | byte publish[] = {0x30,0xe,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; 98 | 99 | for (int i = 0; i < 50; i++) { 100 | TRACE(i<<":"); 101 | sleep(1); 102 | if ( i == 15 || i == 31 || i == 47) { 103 | byte pingreq[] = { 0xC0,0x0 }; 104 | shimClient.expect(pingreq,2); 105 | byte pingresp[] = { 0xD0,0x0 }; 106 | shimClient.respond(pingresp,2); 107 | } 108 | shimClient.respond(publish,16); 109 | rc = client.loop(); 110 | IS_TRUE(rc); 111 | IS_FALSE(shimClient.error()); 112 | } 113 | 114 | END_IT 115 | } 116 | 117 | int test_keepalive_no_pings_inbound_qos1() { 118 | IT("does not send pings for connections with inbound qos1 (takes 1 minute)"); 119 | 120 | ShimClient shimClient; 121 | shimClient.setAllowConnect(true); 122 | 123 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 124 | shimClient.respond(connack,4); 125 | 126 | PubSubClient client(server, 1883, callback, shimClient); 127 | int rc = client.connect((char*)"client_test1"); 128 | IS_TRUE(rc); 129 | 130 | byte publish[] = {0x32,0x10,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x12,0x34,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; 131 | byte puback[] = {0x40,0x2,0x12,0x34}; 132 | 133 | for (int i = 0; i < 50; i++) { 134 | shimClient.respond(publish,18); 135 | shimClient.expect(puback,4); 136 | sleep(1); 137 | rc = client.loop(); 138 | IS_TRUE(rc); 139 | IS_FALSE(shimClient.error()); 140 | } 141 | 142 | END_IT 143 | } 144 | 145 | int test_keepalive_disconnects_hung() { 146 | IT("disconnects a hung connection (takes 30 seconds)"); 147 | 148 | ShimClient shimClient; 149 | shimClient.setAllowConnect(true); 150 | 151 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 152 | shimClient.respond(connack,4); 153 | 154 | PubSubClient client(server, 1883, callback, shimClient); 155 | int rc = client.connect((char*)"client_test1"); 156 | IS_TRUE(rc); 157 | 158 | byte pingreq[] = { 0xC0,0x0 }; 159 | shimClient.expect(pingreq,2); 160 | 161 | for (int i = 0; i < 32; i++) { 162 | sleep(1); 163 | rc = client.loop(); 164 | } 165 | IS_FALSE(rc); 166 | 167 | int state = client.state(); 168 | IS_TRUE(state == MQTT_CONNECTION_TIMEOUT); 169 | 170 | IS_FALSE(shimClient.error()); 171 | 172 | END_IT 173 | } 174 | 175 | int main() 176 | { 177 | SUITE("Keep-alive"); 178 | test_keepalive_pings_idle(); 179 | test_keepalive_pings_with_outbound_qos0(); 180 | test_keepalive_pings_with_inbound_qos0(); 181 | test_keepalive_no_pings_inbound_qos1(); 182 | test_keepalive_disconnects_hung(); 183 | 184 | FINISH 185 | } 186 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/Arduino.h: -------------------------------------------------------------------------------- 1 | #ifndef Arduino_h 2 | #define Arduino_h 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include "Print.h" 9 | 10 | 11 | extern "C"{ 12 | typedef uint8_t byte ; 13 | typedef uint8_t boolean ; 14 | 15 | /* sketch */ 16 | extern void setup( void ) ; 17 | extern void loop( void ) ; 18 | uint32_t millis( void ); 19 | } 20 | 21 | #define PROGMEM 22 | #define pgm_read_byte_near(x) *(x) 23 | 24 | #define yield(x) {} 25 | 26 | #endif // Arduino_h 27 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/BDDTest.cpp: -------------------------------------------------------------------------------- 1 | #include "BDDTest.h" 2 | #include "trace.h" 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | int testCount = 0; 9 | int testPasses = 0; 10 | const char* testDescription; 11 | 12 | std::list failureList; 13 | 14 | void bddtest_suite(const char* name) { 15 | LOG(name << "\n"); 16 | } 17 | 18 | int bddtest_test(const char* file, int line, const char* assertion, int result) { 19 | if (!result) { 20 | LOG("✗\n"); 21 | std::ostringstream os; 22 | os << " ! "<::iterator it = failureList.begin(); it != failureList.end(); it++) { 40 | LOG("\n"); 41 | LOG(*it); 42 | LOG("\n"); 43 | } 44 | 45 | LOG(std::dec << testPasses << "/" << testCount << " tests passed\n\n"); 46 | if (testPasses == testCount) { 47 | return 0; 48 | } 49 | return 1; 50 | } 51 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/BDDTest.h: -------------------------------------------------------------------------------- 1 | #ifndef bddtest_h 2 | #define bddtest_h 3 | 4 | void bddtest_suite(const char* name); 5 | int bddtest_test(const char*, int, const char*, int); 6 | void bddtest_start(const char*); 7 | void bddtest_end(); 8 | int bddtest_summary(); 9 | 10 | #define SUITE(x) { bddtest_suite(x); } 11 | #define TEST(x) { if (!bddtest_test(__FILE__, __LINE__, #x, (x))) return false; } 12 | 13 | #define IT(x) { bddtest_start(x); } 14 | #define END_IT { bddtest_end();return true;} 15 | 16 | #define FINISH { return bddtest_summary(); } 17 | 18 | #define IS_TRUE(x) TEST(x) 19 | #define IS_FALSE(x) TEST(!(x)) 20 | #define IS_EQUAL(x,y) TEST(x==y) 21 | #define IS_NOT_EQUAL(x,y) TEST(x!=y) 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/Buffer.cpp: -------------------------------------------------------------------------------- 1 | #include "Buffer.h" 2 | #include "Arduino.h" 3 | 4 | Buffer::Buffer() { 5 | this->pos = 0; 6 | this->length = 0; 7 | } 8 | 9 | Buffer::Buffer(uint8_t* buf, size_t size) { 10 | this->pos = 0; 11 | this->length = 0; 12 | this->add(buf,size); 13 | } 14 | bool Buffer::available() { 15 | return this->pos < this->length; 16 | } 17 | 18 | uint8_t Buffer::next() { 19 | if (this->available()) { 20 | return this->buffer[this->pos++]; 21 | } 22 | return 0; 23 | } 24 | 25 | void Buffer::reset() { 26 | this->pos = 0; 27 | } 28 | 29 | void Buffer::add(uint8_t* buf, size_t size) { 30 | uint16_t i = 0; 31 | for (;ibuffer[this->length++] = buf[i]; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/Buffer.h: -------------------------------------------------------------------------------- 1 | #ifndef buffer_h 2 | #define buffer_h 3 | 4 | #include "Arduino.h" 5 | 6 | class Buffer { 7 | private: 8 | uint8_t buffer[1024]; 9 | uint16_t pos; 10 | uint16_t length; 11 | 12 | public: 13 | Buffer(); 14 | Buffer(uint8_t* buf, size_t size); 15 | 16 | virtual bool available(); 17 | virtual uint8_t next(); 18 | virtual void reset(); 19 | 20 | virtual void add(uint8_t* buf, size_t size); 21 | }; 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/Client.h: -------------------------------------------------------------------------------- 1 | #ifndef client_h 2 | #define client_h 3 | #include "IPAddress.h" 4 | 5 | class Client { 6 | public: 7 | virtual int connect(IPAddress ip, uint16_t port) =0; 8 | virtual int connect(const char *host, uint16_t port) =0; 9 | virtual size_t write(uint8_t) =0; 10 | virtual size_t write(const uint8_t *buf, size_t size) =0; 11 | virtual int available() = 0; 12 | virtual int read() = 0; 13 | virtual int read(uint8_t *buf, size_t size) = 0; 14 | virtual int peek() = 0; 15 | virtual void flush() = 0; 16 | virtual void stop() = 0; 17 | virtual uint8_t connected() = 0; 18 | virtual operator bool() = 0; 19 | }; 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/IPAddress.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | IPAddress::IPAddress() 6 | { 7 | memset(_address, 0, sizeof(_address)); 8 | } 9 | 10 | IPAddress::IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet) 11 | { 12 | _address[0] = first_octet; 13 | _address[1] = second_octet; 14 | _address[2] = third_octet; 15 | _address[3] = fourth_octet; 16 | } 17 | 18 | IPAddress::IPAddress(uint32_t address) 19 | { 20 | memcpy(_address, &address, sizeof(_address)); 21 | } 22 | 23 | IPAddress::IPAddress(const uint8_t *address) 24 | { 25 | memcpy(_address, address, sizeof(_address)); 26 | } 27 | 28 | IPAddress& IPAddress::operator=(const uint8_t *address) 29 | { 30 | memcpy(_address, address, sizeof(_address)); 31 | return *this; 32 | } 33 | 34 | IPAddress& IPAddress::operator=(uint32_t address) 35 | { 36 | memcpy(_address, (const uint8_t *)&address, sizeof(_address)); 37 | return *this; 38 | } 39 | 40 | bool IPAddress::operator==(const uint8_t* addr) 41 | { 42 | return memcmp(addr, _address, sizeof(_address)) == 0; 43 | } 44 | 45 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/IPAddress.h: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * MIT License: 4 | * Copyright (c) 2011 Adrian McEwen 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy 6 | * of this software and associated documentation files (the "Software"), to deal 7 | * in the Software without restriction, including without limitation the rights 8 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | * copies of the Software, and to permit persons to whom the Software is 10 | * furnished to do so, subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in 13 | * all copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | * THE SOFTWARE. 22 | * 23 | * adrianm@mcqn.com 1/1/2011 24 | */ 25 | 26 | #ifndef IPAddress_h 27 | #define IPAddress_h 28 | 29 | 30 | // A class to make it easier to handle and pass around IP addresses 31 | 32 | class IPAddress { 33 | private: 34 | uint8_t _address[4]; // IPv4 address 35 | // Access the raw byte array containing the address. Because this returns a pointer 36 | // to the internal structure rather than a copy of the address this function should only 37 | // be used when you know that the usage of the returned uint8_t* will be transient and not 38 | // stored. 39 | uint8_t* raw_address() { return _address; }; 40 | 41 | public: 42 | // Constructors 43 | IPAddress(); 44 | IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet); 45 | IPAddress(uint32_t address); 46 | IPAddress(const uint8_t *address); 47 | 48 | // Overloaded cast operator to allow IPAddress objects to be used where a pointer 49 | // to a four-byte uint8_t array is expected 50 | operator uint32_t() { return *((uint32_t*)_address); }; 51 | bool operator==(const IPAddress& addr) { return (*((uint32_t*)_address)) == (*((uint32_t*)addr._address)); }; 52 | bool operator==(const uint8_t* addr); 53 | 54 | // Overloaded index operator to allow getting and setting individual octets of the address 55 | uint8_t operator[](int index) const { return _address[index]; }; 56 | uint8_t& operator[](int index) { return _address[index]; }; 57 | 58 | // Overloaded copy operators to allow initialisation of IPAddress objects from other types 59 | IPAddress& operator=(const uint8_t *address); 60 | IPAddress& operator=(uint32_t address); 61 | 62 | 63 | friend class EthernetClass; 64 | friend class UDP; 65 | friend class Client; 66 | friend class Server; 67 | friend class DhcpClass; 68 | friend class DNSClient; 69 | }; 70 | 71 | 72 | #endif 73 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/Print.h: -------------------------------------------------------------------------------- 1 | /* 2 | Print.h - Base class that provides print() and println() 3 | Copyright (c) 2008 David A. Mellis. All right reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #ifndef Print_h 21 | #define Print_h 22 | 23 | class Print { 24 | public: 25 | virtual size_t write(uint8_t) = 0; 26 | }; 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/ShimClient.cpp: -------------------------------------------------------------------------------- 1 | #include "ShimClient.h" 2 | #include "trace.h" 3 | #include 4 | #include 5 | #include 6 | 7 | extern "C" { 8 | uint32_t millis(void) { 9 | return time(0)*1000; 10 | } 11 | } 12 | 13 | ShimClient::ShimClient() { 14 | this->responseBuffer = new Buffer(); 15 | this->expectBuffer = new Buffer(); 16 | this->_allowConnect = true; 17 | this->_connected = false; 18 | this->_error = false; 19 | this->expectAnything = true; 20 | this->_received = 0; 21 | this->_expectedPort = 0; 22 | } 23 | 24 | int ShimClient::connect(IPAddress ip, uint16_t port) { 25 | if (this->_allowConnect) { 26 | this->_connected = true; 27 | } 28 | if (this->_expectedPort !=0) { 29 | // if (memcmp(ip,this->_expectedIP,4) != 0) { 30 | // TRACE( "ip mismatch\n"); 31 | // this->_error = true; 32 | // } 33 | if (port != this->_expectedPort) { 34 | TRACE( "port mismatch\n"); 35 | this->_error = true; 36 | } 37 | } 38 | return this->_connected; 39 | } 40 | int ShimClient::connect(const char *host, uint16_t port) { 41 | if (this->_allowConnect) { 42 | this->_connected = true; 43 | } 44 | if (this->_expectedPort !=0) { 45 | if (strcmp(host,this->_expectedHost) != 0) { 46 | TRACE( "host mismatch\n"); 47 | this->_error = true; 48 | } 49 | if (port != this->_expectedPort) { 50 | TRACE( "port mismatch\n"); 51 | this->_error = true; 52 | } 53 | 54 | } 55 | return this->_connected; 56 | } 57 | size_t ShimClient::write(uint8_t b) { 58 | this->_received += 1; 59 | TRACE(std::hex << (unsigned int)b); 60 | if (!this->expectAnything) { 61 | if (this->expectBuffer->available()) { 62 | uint8_t expected = this->expectBuffer->next(); 63 | if (expected != b) { 64 | this->_error = true; 65 | TRACE("!=" << (unsigned int)expected); 66 | } 67 | } else { 68 | this->_error = true; 69 | } 70 | } 71 | TRACE("\n"<< std::dec); 72 | return 1; 73 | } 74 | size_t ShimClient::write(const uint8_t *buf, size_t size) { 75 | this->_received += size; 76 | TRACE( "[" << std::dec << (unsigned int)(size) << "] "); 77 | uint16_t i=0; 78 | for (;i0) { 80 | TRACE(":"); 81 | } 82 | TRACE(std::hex << (unsigned int)(buf[i])); 83 | 84 | if (!this->expectAnything) { 85 | if (this->expectBuffer->available()) { 86 | uint8_t expected = this->expectBuffer->next(); 87 | if (expected != buf[i]) { 88 | this->_error = true; 89 | TRACE("!=" << (unsigned int)expected); 90 | } 91 | } else { 92 | this->_error = true; 93 | } 94 | } 95 | } 96 | TRACE("\n"<responseBuffer->available(); 101 | } 102 | int ShimClient::read() { return this->responseBuffer->next(); } 103 | int ShimClient::read(uint8_t *buf, size_t size) { 104 | uint16_t i = 0; 105 | for (;iread(); 107 | } 108 | return size; 109 | } 110 | int ShimClient::peek() { return 0; } 111 | void ShimClient::flush() {} 112 | void ShimClient::stop() { 113 | this->setConnected(false); 114 | } 115 | uint8_t ShimClient::connected() { return this->_connected; } 116 | ShimClient::operator bool() { return true; } 117 | 118 | 119 | ShimClient* ShimClient::respond(uint8_t *buf, size_t size) { 120 | this->responseBuffer->add(buf,size); 121 | return this; 122 | } 123 | 124 | ShimClient* ShimClient::expect(uint8_t *buf, size_t size) { 125 | this->expectAnything = false; 126 | this->expectBuffer->add(buf,size); 127 | return this; 128 | } 129 | 130 | void ShimClient::setConnected(bool b) { 131 | this->_connected = b; 132 | } 133 | void ShimClient::setAllowConnect(bool b) { 134 | this->_allowConnect = b; 135 | } 136 | 137 | bool ShimClient::error() { 138 | return this->_error; 139 | } 140 | 141 | uint16_t ShimClient::received() { 142 | return this->_received; 143 | } 144 | 145 | void ShimClient::expectConnect(IPAddress ip, uint16_t port) { 146 | this->_expectedIP = ip; 147 | this->_expectedPort = port; 148 | } 149 | 150 | void ShimClient::expectConnect(const char *host, uint16_t port) { 151 | this->_expectedHost = host; 152 | this->_expectedPort = port; 153 | } 154 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/ShimClient.h: -------------------------------------------------------------------------------- 1 | #ifndef shimclient_h 2 | #define shimclient_h 3 | 4 | #include "Arduino.h" 5 | #include "Client.h" 6 | #include "IPAddress.h" 7 | #include "Buffer.h" 8 | 9 | 10 | class ShimClient : public Client { 11 | private: 12 | Buffer* responseBuffer; 13 | Buffer* expectBuffer; 14 | bool _allowConnect; 15 | bool _connected; 16 | bool expectAnything; 17 | bool _error; 18 | uint16_t _received; 19 | IPAddress _expectedIP; 20 | uint16_t _expectedPort; 21 | const char* _expectedHost; 22 | 23 | public: 24 | ShimClient(); 25 | virtual int connect(IPAddress ip, uint16_t port); 26 | virtual int connect(const char *host, uint16_t port); 27 | virtual size_t write(uint8_t); 28 | virtual size_t write(const uint8_t *buf, size_t size); 29 | virtual int available(); 30 | virtual int read(); 31 | virtual int read(uint8_t *buf, size_t size); 32 | virtual int peek(); 33 | virtual void flush(); 34 | virtual void stop(); 35 | virtual uint8_t connected(); 36 | virtual operator bool(); 37 | 38 | virtual ShimClient* respond(uint8_t *buf, size_t size); 39 | virtual ShimClient* expect(uint8_t *buf, size_t size); 40 | 41 | virtual void expectConnect(IPAddress ip, uint16_t port); 42 | virtual void expectConnect(const char *host, uint16_t port); 43 | 44 | virtual uint16_t received(); 45 | virtual bool error(); 46 | 47 | virtual void setAllowConnect(bool b); 48 | virtual void setConnected(bool b); 49 | }; 50 | 51 | #endif 52 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/Stream.cpp: -------------------------------------------------------------------------------- 1 | #include "Stream.h" 2 | #include "trace.h" 3 | #include 4 | #include 5 | 6 | Stream::Stream() { 7 | this->expectBuffer = new Buffer(); 8 | this->_error = false; 9 | this->_written = 0; 10 | } 11 | 12 | size_t Stream::write(uint8_t b) { 13 | this->_written++; 14 | TRACE(std::hex << (unsigned int)b); 15 | if (this->expectBuffer->available()) { 16 | uint8_t expected = this->expectBuffer->next(); 17 | if (expected != b) { 18 | this->_error = true; 19 | TRACE("!=" << (unsigned int)expected); 20 | } 21 | } else { 22 | this->_error = true; 23 | } 24 | TRACE("\n"<< std::dec); 25 | return 1; 26 | } 27 | 28 | 29 | bool Stream::error() { 30 | return this->_error; 31 | } 32 | 33 | void Stream::expect(uint8_t *buf, size_t size) { 34 | this->expectBuffer->add(buf,size); 35 | } 36 | 37 | uint16_t Stream::length() { 38 | return this->_written; 39 | } 40 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/Stream.h: -------------------------------------------------------------------------------- 1 | #ifndef Stream_h 2 | #define Stream_h 3 | 4 | #include "Arduino.h" 5 | #include "Buffer.h" 6 | 7 | class Stream { 8 | private: 9 | Buffer* expectBuffer; 10 | bool _error; 11 | uint16_t _written; 12 | 13 | public: 14 | Stream(); 15 | virtual size_t write(uint8_t); 16 | 17 | virtual bool error(); 18 | virtual void expect(uint8_t *buf, size_t size); 19 | virtual uint16_t length(); 20 | }; 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/lib/trace.h: -------------------------------------------------------------------------------- 1 | #ifndef trace_h 2 | #define trace_h 3 | #include 4 | 5 | #include 6 | 7 | #define LOG(x) {std::cout << x << std::flush; } 8 | #define TRACE(x) {if (getenv("TRACE")) { std::cout << x << std::flush; }} 9 | 10 | #endif 11 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/publish_spec.cpp: -------------------------------------------------------------------------------- 1 | #include "PubSubClient.h" 2 | #include "ShimClient.h" 3 | #include "Buffer.h" 4 | #include "BDDTest.h" 5 | #include "trace.h" 6 | 7 | 8 | byte server[] = { 172, 16, 0, 2 }; 9 | 10 | void callback(char* topic, byte* payload, unsigned int length) { 11 | // handle message arrived 12 | } 13 | 14 | int test_publish() { 15 | IT("publishes a null-terminated string"); 16 | ShimClient shimClient; 17 | shimClient.setAllowConnect(true); 18 | 19 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 20 | shimClient.respond(connack,4); 21 | 22 | PubSubClient client(server, 1883, callback, shimClient); 23 | int rc = client.connect((char*)"client_test1"); 24 | IS_TRUE(rc); 25 | 26 | byte publish[] = {0x30,0xe,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; 27 | shimClient.expect(publish,16); 28 | 29 | rc = client.publish((char*)"topic",(char*)"payload"); 30 | IS_TRUE(rc); 31 | 32 | IS_FALSE(shimClient.error()); 33 | 34 | END_IT 35 | } 36 | 37 | 38 | int test_publish_bytes() { 39 | IT("publishes a byte array"); 40 | ShimClient shimClient; 41 | shimClient.setAllowConnect(true); 42 | 43 | byte payload[] = { 0x01,0x02,0x03,0x0,0x05 }; 44 | int length = 5; 45 | 46 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 47 | shimClient.respond(connack,4); 48 | 49 | PubSubClient client(server, 1883, callback, shimClient); 50 | int rc = client.connect((char*)"client_test1"); 51 | IS_TRUE(rc); 52 | 53 | byte publish[] = {0x30,0xc,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x1,0x2,0x3,0x0,0x5}; 54 | shimClient.expect(publish,14); 55 | 56 | rc = client.publish((char*)"topic",payload,length); 57 | IS_TRUE(rc); 58 | 59 | IS_FALSE(shimClient.error()); 60 | 61 | END_IT 62 | } 63 | 64 | 65 | int test_publish_retained() { 66 | IT("publishes retained - 1"); 67 | ShimClient shimClient; 68 | shimClient.setAllowConnect(true); 69 | 70 | byte payload[] = { 0x01,0x02,0x03,0x0,0x05 }; 71 | int length = 5; 72 | 73 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 74 | shimClient.respond(connack,4); 75 | 76 | PubSubClient client(server, 1883, callback, shimClient); 77 | int rc = client.connect((char*)"client_test1"); 78 | IS_TRUE(rc); 79 | 80 | byte publish[] = {0x31,0xc,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x1,0x2,0x3,0x0,0x5}; 81 | shimClient.expect(publish,14); 82 | 83 | rc = client.publish((char*)"topic",payload,length,true); 84 | IS_TRUE(rc); 85 | 86 | IS_FALSE(shimClient.error()); 87 | 88 | END_IT 89 | } 90 | 91 | int test_publish_retained_2() { 92 | IT("publishes retained - 2"); 93 | ShimClient shimClient; 94 | shimClient.setAllowConnect(true); 95 | 96 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 97 | shimClient.respond(connack,4); 98 | 99 | PubSubClient client(server, 1883, callback, shimClient); 100 | int rc = client.connect((char*)"client_test1"); 101 | IS_TRUE(rc); 102 | 103 | byte publish[] = {0x31,0xc,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,'A','B','C','D','E'}; 104 | shimClient.expect(publish,14); 105 | 106 | rc = client.publish((char*)"topic",(char*)"ABCDE",true); 107 | IS_TRUE(rc); 108 | 109 | IS_FALSE(shimClient.error()); 110 | 111 | END_IT 112 | } 113 | 114 | int test_publish_not_connected() { 115 | IT("publish fails when not connected"); 116 | ShimClient shimClient; 117 | 118 | PubSubClient client(server, 1883, callback, shimClient); 119 | 120 | int rc = client.publish((char*)"topic",(char*)"payload"); 121 | IS_FALSE(rc); 122 | 123 | IS_FALSE(shimClient.error()); 124 | 125 | END_IT 126 | } 127 | 128 | int test_publish_too_long() { 129 | IT("publish fails when topic/payload are too long"); 130 | ShimClient shimClient; 131 | shimClient.setAllowConnect(true); 132 | 133 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 134 | shimClient.respond(connack,4); 135 | 136 | PubSubClient client(server, 1883, callback, shimClient); 137 | int rc = client.connect((char*)"client_test1"); 138 | IS_TRUE(rc); 139 | 140 | // 0 1 2 3 4 5 6 7 8 9 0 1 2 141 | rc = client.publish((char*)"topic",(char*)"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"); 142 | IS_FALSE(rc); 143 | 144 | IS_FALSE(shimClient.error()); 145 | 146 | END_IT 147 | } 148 | 149 | int test_publish_P() { 150 | IT("publishes using PROGMEM"); 151 | ShimClient shimClient; 152 | shimClient.setAllowConnect(true); 153 | 154 | byte payload[] = { 0x01,0x02,0x03,0x0,0x05 }; 155 | int length = 5; 156 | 157 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 158 | shimClient.respond(connack,4); 159 | 160 | PubSubClient client(server, 1883, callback, shimClient); 161 | int rc = client.connect((char*)"client_test1"); 162 | IS_TRUE(rc); 163 | 164 | byte publish[] = {0x31,0xc,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x1,0x2,0x3,0x0,0x5}; 165 | shimClient.expect(publish,14); 166 | 167 | rc = client.publish_P((char*)"topic",payload,length,true); 168 | IS_TRUE(rc); 169 | 170 | IS_FALSE(shimClient.error()); 171 | 172 | END_IT 173 | } 174 | 175 | 176 | 177 | 178 | int main() 179 | { 180 | SUITE("Publish"); 181 | test_publish(); 182 | test_publish_bytes(); 183 | test_publish_retained(); 184 | test_publish_retained_2(); 185 | test_publish_not_connected(); 186 | test_publish_too_long(); 187 | test_publish_P(); 188 | 189 | FINISH 190 | } 191 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/receive_spec.cpp: -------------------------------------------------------------------------------- 1 | #include "PubSubClient.h" 2 | #include "ShimClient.h" 3 | #include "Buffer.h" 4 | #include "BDDTest.h" 5 | #include "trace.h" 6 | 7 | 8 | byte server[] = { 172, 16, 0, 2 }; 9 | 10 | bool callback_called = false; 11 | char lastTopic[1024]; 12 | char lastPayload[1024]; 13 | unsigned int lastLength; 14 | 15 | void reset_callback() { 16 | callback_called = false; 17 | lastTopic[0] = '\0'; 18 | lastPayload[0] = '\0'; 19 | lastLength = 0; 20 | } 21 | 22 | void callback(char* topic, byte* payload, unsigned int length) { 23 | callback_called = true; 24 | strcpy(lastTopic,topic); 25 | memcpy(lastPayload,payload,length); 26 | lastLength = length; 27 | } 28 | 29 | int test_receive_callback() { 30 | IT("receives a callback message"); 31 | reset_callback(); 32 | 33 | ShimClient shimClient; 34 | shimClient.setAllowConnect(true); 35 | 36 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 37 | shimClient.respond(connack,4); 38 | 39 | PubSubClient client(server, 1883, callback, shimClient); 40 | int rc = client.connect((char*)"client_test1"); 41 | IS_TRUE(rc); 42 | 43 | byte publish[] = {0x30,0xe,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; 44 | shimClient.respond(publish,16); 45 | 46 | rc = client.loop(); 47 | 48 | IS_TRUE(rc); 49 | 50 | IS_TRUE(callback_called); 51 | IS_TRUE(strcmp(lastTopic,"topic")==0); 52 | IS_TRUE(memcmp(lastPayload,"payload",7)==0); 53 | IS_TRUE(lastLength == 7); 54 | 55 | IS_FALSE(shimClient.error()); 56 | 57 | END_IT 58 | } 59 | 60 | int test_receive_stream() { 61 | IT("receives a streamed callback message"); 62 | reset_callback(); 63 | 64 | Stream stream; 65 | stream.expect((uint8_t*)"payload",7); 66 | 67 | ShimClient shimClient; 68 | shimClient.setAllowConnect(true); 69 | 70 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 71 | shimClient.respond(connack,4); 72 | 73 | PubSubClient client(server, 1883, callback, shimClient, stream); 74 | int rc = client.connect((char*)"client_test1"); 75 | IS_TRUE(rc); 76 | 77 | byte publish[] = {0x30,0xe,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; 78 | shimClient.respond(publish,16); 79 | 80 | rc = client.loop(); 81 | 82 | IS_TRUE(rc); 83 | 84 | IS_TRUE(callback_called); 85 | IS_TRUE(strcmp(lastTopic,"topic")==0); 86 | IS_TRUE(lastLength == 7); 87 | 88 | IS_FALSE(stream.error()); 89 | IS_FALSE(shimClient.error()); 90 | 91 | END_IT 92 | } 93 | 94 | int test_receive_max_sized_message() { 95 | IT("receives an max-sized message"); 96 | reset_callback(); 97 | 98 | ShimClient shimClient; 99 | shimClient.setAllowConnect(true); 100 | 101 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 102 | shimClient.respond(connack,4); 103 | 104 | PubSubClient client(server, 1883, callback, shimClient); 105 | int rc = client.connect((char*)"client_test1"); 106 | IS_TRUE(rc); 107 | 108 | int length = MQTT_MAX_PACKET_SIZE; 109 | byte publish[] = {0x30,length-2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; 110 | byte bigPublish[length]; 111 | memset(bigPublish,'A',length); 112 | bigPublish[length] = 'B'; 113 | memcpy(bigPublish,publish,16); 114 | shimClient.respond(bigPublish,length); 115 | 116 | rc = client.loop(); 117 | 118 | IS_TRUE(rc); 119 | 120 | IS_TRUE(callback_called); 121 | IS_TRUE(strcmp(lastTopic,"topic")==0); 122 | IS_TRUE(lastLength == length-9); 123 | IS_TRUE(memcmp(lastPayload,bigPublish+9,lastLength)==0); 124 | 125 | IS_FALSE(shimClient.error()); 126 | 127 | END_IT 128 | } 129 | 130 | int test_receive_oversized_message() { 131 | IT("drops an oversized message"); 132 | reset_callback(); 133 | 134 | ShimClient shimClient; 135 | shimClient.setAllowConnect(true); 136 | 137 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 138 | shimClient.respond(connack,4); 139 | 140 | PubSubClient client(server, 1883, callback, shimClient); 141 | int rc = client.connect((char*)"client_test1"); 142 | IS_TRUE(rc); 143 | 144 | int length = MQTT_MAX_PACKET_SIZE+1; 145 | byte publish[] = {0x30,length-2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; 146 | byte bigPublish[length]; 147 | memset(bigPublish,'A',length); 148 | bigPublish[length] = 'B'; 149 | memcpy(bigPublish,publish,16); 150 | shimClient.respond(bigPublish,length); 151 | 152 | rc = client.loop(); 153 | 154 | IS_TRUE(rc); 155 | 156 | IS_FALSE(callback_called); 157 | 158 | IS_FALSE(shimClient.error()); 159 | 160 | END_IT 161 | } 162 | 163 | int test_drop_invalid_remaining_length_message() { 164 | IT("drops invalid remaining length message"); 165 | reset_callback(); 166 | 167 | ShimClient shimClient; 168 | shimClient.setAllowConnect(true); 169 | 170 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 171 | shimClient.respond(connack,4); 172 | 173 | PubSubClient client(server, 1883, callback, shimClient); 174 | int rc = client.connect((char*)"client_test1"); 175 | IS_TRUE(rc); 176 | 177 | byte publish[] = {0x30,0x92,0x92,0x92,0x92,0x01,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; 178 | shimClient.respond(publish,20); 179 | 180 | rc = client.loop(); 181 | 182 | IS_FALSE(rc); 183 | 184 | IS_FALSE(callback_called); 185 | 186 | IS_FALSE(shimClient.error()); 187 | 188 | END_IT 189 | } 190 | 191 | 192 | int test_receive_oversized_stream_message() { 193 | IT("drops an oversized message"); 194 | reset_callback(); 195 | 196 | Stream stream; 197 | 198 | ShimClient shimClient; 199 | shimClient.setAllowConnect(true); 200 | 201 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 202 | shimClient.respond(connack,4); 203 | 204 | PubSubClient client(server, 1883, callback, shimClient, stream); 205 | int rc = client.connect((char*)"client_test1"); 206 | IS_TRUE(rc); 207 | 208 | int length = MQTT_MAX_PACKET_SIZE+1; 209 | byte publish[] = {0x30,length-2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; 210 | 211 | byte bigPublish[length]; 212 | memset(bigPublish,'A',length); 213 | bigPublish[length] = 'B'; 214 | memcpy(bigPublish,publish,16); 215 | 216 | shimClient.respond(bigPublish,length); 217 | stream.expect(bigPublish+9,length-9); 218 | 219 | rc = client.loop(); 220 | 221 | IS_TRUE(rc); 222 | 223 | IS_TRUE(callback_called); 224 | IS_TRUE(strcmp(lastTopic,"topic")==0); 225 | IS_TRUE(lastLength == length-9); 226 | 227 | IS_FALSE(stream.error()); 228 | IS_FALSE(shimClient.error()); 229 | 230 | END_IT 231 | } 232 | 233 | int test_receive_qos1() { 234 | IT("receives a qos1 message"); 235 | reset_callback(); 236 | 237 | ShimClient shimClient; 238 | shimClient.setAllowConnect(true); 239 | 240 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 241 | shimClient.respond(connack,4); 242 | 243 | PubSubClient client(server, 1883, callback, shimClient); 244 | int rc = client.connect((char*)"client_test1"); 245 | IS_TRUE(rc); 246 | 247 | byte publish[] = {0x32,0x10,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x12,0x34,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64}; 248 | shimClient.respond(publish,18); 249 | 250 | byte puback[] = {0x40,0x2,0x12,0x34}; 251 | shimClient.expect(puback,4); 252 | 253 | rc = client.loop(); 254 | 255 | IS_TRUE(rc); 256 | 257 | IS_TRUE(callback_called); 258 | IS_TRUE(strcmp(lastTopic,"topic")==0); 259 | IS_TRUE(memcmp(lastPayload,"payload",7)==0); 260 | IS_TRUE(lastLength == 7); 261 | 262 | IS_FALSE(shimClient.error()); 263 | 264 | END_IT 265 | } 266 | 267 | int main() 268 | { 269 | SUITE("Receive"); 270 | test_receive_callback(); 271 | test_receive_stream(); 272 | test_receive_max_sized_message(); 273 | test_drop_invalid_remaining_length_message(); 274 | test_receive_oversized_message(); 275 | test_receive_oversized_stream_message(); 276 | test_receive_qos1(); 277 | 278 | FINISH 279 | } 280 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/src/subscribe_spec.cpp: -------------------------------------------------------------------------------- 1 | #include "PubSubClient.h" 2 | #include "ShimClient.h" 3 | #include "Buffer.h" 4 | #include "BDDTest.h" 5 | #include "trace.h" 6 | 7 | 8 | byte server[] = { 172, 16, 0, 2 }; 9 | 10 | void callback(char* topic, byte* payload, unsigned int length) { 11 | // handle message arrived 12 | } 13 | 14 | int test_subscribe_no_qos() { 15 | IT("subscribe without qos defaults to 0"); 16 | ShimClient shimClient; 17 | shimClient.setAllowConnect(true); 18 | 19 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 20 | shimClient.respond(connack,4); 21 | 22 | PubSubClient client(server, 1883, callback, shimClient); 23 | int rc = client.connect((char*)"client_test1"); 24 | IS_TRUE(rc); 25 | 26 | byte subscribe[] = { 0x82,0xa,0x0,0x2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x0 }; 27 | shimClient.expect(subscribe,12); 28 | byte suback[] = { 0x90,0x3,0x0,0x2,0x0 }; 29 | shimClient.respond(suback,5); 30 | 31 | rc = client.subscribe((char*)"topic"); 32 | IS_TRUE(rc); 33 | 34 | IS_FALSE(shimClient.error()); 35 | 36 | END_IT 37 | } 38 | 39 | int test_subscribe_qos_1() { 40 | IT("subscribes qos 1"); 41 | ShimClient shimClient; 42 | shimClient.setAllowConnect(true); 43 | 44 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 45 | shimClient.respond(connack,4); 46 | 47 | PubSubClient client(server, 1883, callback, shimClient); 48 | int rc = client.connect((char*)"client_test1"); 49 | IS_TRUE(rc); 50 | 51 | byte subscribe[] = { 0x82,0xa,0x0,0x2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x1 }; 52 | shimClient.expect(subscribe,12); 53 | byte suback[] = { 0x90,0x3,0x0,0x2,0x1 }; 54 | shimClient.respond(suback,5); 55 | 56 | rc = client.subscribe((char*)"topic",1); 57 | IS_TRUE(rc); 58 | 59 | IS_FALSE(shimClient.error()); 60 | 61 | END_IT 62 | } 63 | 64 | int test_subscribe_not_connected() { 65 | IT("subscribe fails when not connected"); 66 | ShimClient shimClient; 67 | 68 | PubSubClient client(server, 1883, callback, shimClient); 69 | 70 | int rc = client.subscribe((char*)"topic"); 71 | IS_FALSE(rc); 72 | 73 | IS_FALSE(shimClient.error()); 74 | 75 | END_IT 76 | } 77 | 78 | int test_subscribe_invalid_qos() { 79 | IT("subscribe fails with invalid qos values"); 80 | ShimClient shimClient; 81 | shimClient.setAllowConnect(true); 82 | 83 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 84 | shimClient.respond(connack,4); 85 | 86 | PubSubClient client(server, 1883, callback, shimClient); 87 | int rc = client.connect((char*)"client_test1"); 88 | IS_TRUE(rc); 89 | 90 | rc = client.subscribe((char*)"topic",2); 91 | IS_FALSE(rc); 92 | rc = client.subscribe((char*)"topic",254); 93 | IS_FALSE(rc); 94 | 95 | IS_FALSE(shimClient.error()); 96 | 97 | END_IT 98 | } 99 | 100 | int test_subscribe_too_long() { 101 | IT("subscribe fails with too long topic"); 102 | ShimClient shimClient; 103 | shimClient.setAllowConnect(true); 104 | 105 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 106 | shimClient.respond(connack,4); 107 | 108 | PubSubClient client(server, 1883, callback, shimClient); 109 | int rc = client.connect((char*)"client_test1"); 110 | IS_TRUE(rc); 111 | 112 | // max length should be allowed 113 | // 0 1 2 3 4 5 6 7 8 9 0 1 2 114 | rc = client.subscribe((char*)"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"); 115 | IS_TRUE(rc); 116 | 117 | // 0 1 2 3 4 5 6 7 8 9 0 1 2 118 | rc = client.subscribe((char*)"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"); 119 | IS_FALSE(rc); 120 | 121 | IS_FALSE(shimClient.error()); 122 | 123 | END_IT 124 | } 125 | 126 | 127 | int test_unsubscribe() { 128 | IT("unsubscribes"); 129 | ShimClient shimClient; 130 | shimClient.setAllowConnect(true); 131 | 132 | byte connack[] = { 0x20, 0x02, 0x00, 0x00 }; 133 | shimClient.respond(connack,4); 134 | 135 | PubSubClient client(server, 1883, callback, shimClient); 136 | int rc = client.connect((char*)"client_test1"); 137 | IS_TRUE(rc); 138 | 139 | byte unsubscribe[] = { 0xA2,0x9,0x0,0x2,0x0,0x5,0x74,0x6f,0x70,0x69,0x63 }; 140 | shimClient.expect(unsubscribe,12); 141 | byte unsuback[] = { 0xB0,0x2,0x0,0x2 }; 142 | shimClient.respond(unsuback,4); 143 | 144 | rc = client.unsubscribe((char*)"topic"); 145 | IS_TRUE(rc); 146 | 147 | IS_FALSE(shimClient.error()); 148 | 149 | END_IT 150 | } 151 | 152 | int test_unsubscribe_not_connected() { 153 | IT("unsubscribe fails when not connected"); 154 | ShimClient shimClient; 155 | 156 | PubSubClient client(server, 1883, callback, shimClient); 157 | 158 | int rc = client.unsubscribe((char*)"topic"); 159 | IS_FALSE(rc); 160 | 161 | IS_FALSE(shimClient.error()); 162 | 163 | END_IT 164 | } 165 | 166 | int main() 167 | { 168 | SUITE("Subscribe"); 169 | test_subscribe_no_qos(); 170 | test_subscribe_qos_1(); 171 | test_subscribe_not_connected(); 172 | test_subscribe_invalid_qos(); 173 | test_subscribe_too_long(); 174 | test_unsubscribe(); 175 | test_unsubscribe_not_connected(); 176 | FINISH 177 | } 178 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/testcases/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alcar21/WemosEM/90f029c280fc198d436d2481c994b29a755ef94b/WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/testcases/__init__.py -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/testcases/mqtt_basic.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import settings 3 | import time 4 | import mosquitto 5 | 6 | 7 | def on_message(mosq, obj, msg): 8 | obj.message_queue.append(msg) 9 | 10 | 11 | class mqtt_basic(unittest.TestCase): 12 | 13 | message_queue = [] 14 | 15 | @classmethod 16 | def setUpClass(self): 17 | self.client = mosquitto.Mosquitto("pubsubclient_ut", clean_session=True, obj=self) 18 | self.client.connect(settings.server_ip) 19 | self.client.on_message = on_message 20 | self.client.subscribe("outTopic", 0) 21 | 22 | @classmethod 23 | def tearDownClass(self): 24 | self.client.disconnect() 25 | 26 | def test_one(self): 27 | i = 30 28 | while len(self.message_queue) == 0 and i > 0: 29 | self.client.loop() 30 | time.sleep(0.5) 31 | i -= 1 32 | self.assertTrue(i > 0, "message receive timed-out") 33 | self.assertEqual(len(self.message_queue), 1, "unexpected number of messages received") 34 | msg = self.message_queue[0] 35 | self.assertEqual(msg.mid, 0, "message id not 0") 36 | self.assertEqual(msg.topic, "outTopic", "message topic incorrect") 37 | self.assertEqual(msg.payload, "hello world") 38 | self.assertEqual(msg.qos, 0, "message qos not 0") 39 | self.assertEqual(msg.retain, False, "message retain flag incorrect") 40 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/testcases/mqtt_publish_in_callback.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import settings 3 | import time 4 | import mosquitto 5 | 6 | 7 | def on_message(mosq, obj, msg): 8 | obj.message_queue.append(msg) 9 | 10 | 11 | class mqtt_publish_in_callback(unittest.TestCase): 12 | 13 | message_queue = [] 14 | 15 | @classmethod 16 | def setUpClass(self): 17 | self.client = mosquitto.Mosquitto("pubsubclient_ut", clean_session=True, obj=self) 18 | self.client.connect(settings.server_ip) 19 | self.client.on_message = on_message 20 | self.client.subscribe("outTopic", 0) 21 | 22 | @classmethod 23 | def tearDownClass(self): 24 | self.client.disconnect() 25 | 26 | def test_connect(self): 27 | i = 30 28 | while len(self.message_queue) == 0 and i > 0: 29 | self.client.loop() 30 | time.sleep(0.5) 31 | i -= 1 32 | self.assertTrue(i > 0, "message receive timed-out") 33 | self.assertEqual(len(self.message_queue), 1, "unexpected number of messages received") 34 | msg = self.message_queue.pop(0) 35 | self.assertEqual(msg.mid, 0, "message id not 0") 36 | self.assertEqual(msg.topic, "outTopic", "message topic incorrect") 37 | self.assertEqual(msg.payload, "hello world") 38 | self.assertEqual(msg.qos, 0, "message qos not 0") 39 | self.assertEqual(msg.retain, False, "message retain flag incorrect") 40 | 41 | def test_publish(self): 42 | self.assertEqual(len(self.message_queue), 0, "message queue not empty") 43 | payload = "abcdefghij" 44 | self.client.publish("inTopic", payload) 45 | 46 | i = 30 47 | while len(self.message_queue) == 0 and i > 0: 48 | self.client.loop() 49 | time.sleep(0.5) 50 | i -= 1 51 | 52 | self.assertTrue(i > 0, "message receive timed-out") 53 | self.assertEqual(len(self.message_queue), 1, "unexpected number of messages received") 54 | msg = self.message_queue.pop(0) 55 | self.assertEqual(msg.mid, 0, "message id not 0") 56 | self.assertEqual(msg.topic, "outTopic", "message topic incorrect") 57 | self.assertEqual(msg.payload, payload) 58 | self.assertEqual(msg.qos, 0, "message qos not 0") 59 | self.assertEqual(msg.retain, False, "message retain flag incorrect") 60 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/testcases/settings.py: -------------------------------------------------------------------------------- 1 | server_ip = "172.16.0.2" 2 | arduino_ip = "172.16.0.100" 3 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/PubSubClient-EspEasy-2.7.12/tests/testsuite.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import os.path 4 | import sys 5 | import shutil 6 | from subprocess import call 7 | import importlib 8 | import unittest 9 | import re 10 | 11 | from testcases import settings 12 | 13 | 14 | class Workspace(object): 15 | 16 | def __init__(self): 17 | self.root_dir = os.getcwd() 18 | self.build_dir = os.path.join(self.root_dir, "tmpbin") 19 | self.log_dir = os.path.join(self.root_dir, "logs") 20 | self.tests_dir = os.path.join(self.root_dir, "testcases") 21 | self.examples_dir = os.path.join(self.root_dir, "../PubSubClient/examples") 22 | self.examples = [] 23 | self.tests = [] 24 | if not os.path.isdir("../PubSubClient"): 25 | raise Exception("Cannot find PubSubClient library") 26 | try: 27 | return __import__('ino') 28 | except ImportError: 29 | raise Exception("ino tool not installed") 30 | 31 | def init(self): 32 | if os.path.isdir(self.build_dir): 33 | shutil.rmtree(self.build_dir) 34 | os.mkdir(self.build_dir) 35 | if os.path.isdir(self.log_dir): 36 | shutil.rmtree(self.log_dir) 37 | os.mkdir(self.log_dir) 38 | 39 | os.chdir(self.build_dir) 40 | call(["ino", "init"]) 41 | 42 | shutil.copytree("../../PubSubClient", "lib/PubSubClient") 43 | 44 | filenames = [] 45 | for root, dirs, files in os.walk(self.examples_dir): 46 | filenames += [os.path.join(root, f) for f in files if f.endswith(".ino")] 47 | filenames.sort() 48 | for e in filenames: 49 | self.examples.append(Sketch(self, e)) 50 | 51 | filenames = [] 52 | for root, dirs, files in os.walk(self.tests_dir): 53 | filenames += [os.path.join(root, f) for f in files if f.endswith(".ino")] 54 | filenames.sort() 55 | for e in filenames: 56 | self.tests.append(Sketch(self, e)) 57 | 58 | def clean(self): 59 | shutil.rmtree(self.build_dir) 60 | 61 | 62 | class Sketch(object): 63 | def __init__(self, wksp, fn): 64 | self.w = wksp 65 | self.filename = fn 66 | self.basename = os.path.basename(self.filename) 67 | self.build_log = os.path.join(self.w.log_dir, "%s.log" % (os.path.basename(self.filename),)) 68 | self.build_err_log = os.path.join(self.w.log_dir, "%s.err.log" % (os.path.basename(self.filename),)) 69 | self.build_upload_log = os.path.join(self.w.log_dir, "%s.upload.log" % (os.path.basename(self.filename),)) 70 | 71 | def build(self): 72 | sys.stdout.write(" Build: ") 73 | sys.stdout.flush() 74 | 75 | # Copy sketch over, replacing IP addresses as necessary 76 | fin = open(self.filename, "r") 77 | lines = fin.readlines() 78 | fin.close() 79 | fout = open(os.path.join(self.w.build_dir, "src", "sketch.ino"), "w") 80 | for l in lines: 81 | if re.match(r"^byte server\[\] = {", l): 82 | fout.write("byte server[] = { %s };\n" % (settings.server_ip.replace(".", ", "),)) 83 | elif re.match(r"^byte ip\[\] = {", l): 84 | fout.write("byte ip[] = { %s };\n" % (settings.arduino_ip.replace(".", ", "),)) 85 | else: 86 | fout.write(l) 87 | fout.flush() 88 | fout.close() 89 | 90 | # Run build 91 | fout = open(self.build_log, "w") 92 | ferr = open(self.build_err_log, "w") 93 | rc = call(["ino", "build"], stdout=fout, stderr=ferr) 94 | fout.close() 95 | ferr.close() 96 | if rc == 0: 97 | sys.stdout.write("pass") 98 | sys.stdout.write("\n") 99 | return True 100 | else: 101 | sys.stdout.write("fail") 102 | sys.stdout.write("\n") 103 | with open(self.build_err_log) as f: 104 | for line in f: 105 | print(" " + line) 106 | return False 107 | 108 | def upload(self): 109 | sys.stdout.write(" Upload: ") 110 | sys.stdout.flush() 111 | fout = open(self.build_upload_log, "w") 112 | rc = call(["ino", "upload"], stdout=fout, stderr=fout) 113 | fout.close() 114 | if rc == 0: 115 | sys.stdout.write("pass") 116 | sys.stdout.write("\n") 117 | return True 118 | else: 119 | sys.stdout.write("fail") 120 | sys.stdout.write("\n") 121 | with open(self.build_upload_log) as f: 122 | for line in f: 123 | print(" " + line) 124 | return False 125 | 126 | def test(self): 127 | # import the matching test case, if it exists 128 | try: 129 | basename = os.path.basename(self.filename)[:-4] 130 | i = importlib.import_module("testcases." + basename) 131 | except: 132 | sys.stdout.write(" Test: no tests found") 133 | sys.stdout.write("\n") 134 | return 135 | c = getattr(i, basename) 136 | 137 | testmethods = [m for m in dir(c) if m.startswith("test_")] 138 | testmethods.sort() 139 | tests = [] 140 | for m in testmethods: 141 | tests.append(c(m)) 142 | 143 | result = unittest.TestResult() 144 | c.setUpClass() 145 | if self.upload(): 146 | sys.stdout.write(" Test: ") 147 | sys.stdout.flush() 148 | for t in tests: 149 | t.run(result) 150 | print(str(result.testsRun - len(result.failures) - len(result.errors)) + "/" + str(result.testsRun)) 151 | if not result.wasSuccessful(): 152 | if len(result.failures) > 0: 153 | for f in result.failures: 154 | print("-- " + str(f[0])) 155 | print(f[1]) 156 | if len(result.errors) > 0: 157 | print(" Errors:") 158 | for f in result.errors: 159 | print("-- " + str(f[0])) 160 | print(f[1]) 161 | c.tearDownClass() 162 | 163 | 164 | if __name__ == '__main__': 165 | run_tests = True 166 | 167 | w = Workspace() 168 | w.init() 169 | 170 | for e in w.examples: 171 | print("--------------------------------------") 172 | print("[" + e.basename + "]") 173 | if e.build() and run_tests: 174 | e.test() 175 | for e in w.tests: 176 | print("--------------------------------------") 177 | print("[" + e.basename + "]") 178 | if e.build() and run_tests: 179 | e.test() 180 | 181 | w.clean() 182 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/README: -------------------------------------------------------------------------------- 1 | 2 | This directory is intended for project specific (private) libraries. 3 | PlatformIO will compile them to static libraries and link into executable file. 4 | 5 | The source code of each library should be placed in a an own separate directory 6 | ("lib/your_library_name/[here are source files]"). 7 | 8 | For example, see a structure of the following two libraries `Foo` and `Bar`: 9 | 10 | |--lib 11 | | | 12 | | |--Bar 13 | | | |--docs 14 | | | |--examples 15 | | | |--src 16 | | | |- Bar.c 17 | | | |- Bar.h 18 | | | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html 19 | | | 20 | | |--Foo 21 | | | |- Foo.c 22 | | | |- Foo.h 23 | | | 24 | | |- README --> THIS FILE 25 | | 26 | |- platformio.ini 27 | |--src 28 | |- main.c 29 | 30 | and a contents of `src/main.c`: 31 | ``` 32 | #include 33 | #include 34 | 35 | int main (void) 36 | { 37 | ... 38 | } 39 | 40 | ``` 41 | 42 | PlatformIO Library Dependency Finder will find automatically dependent 43 | libraries scanning project source files. 44 | 45 | More information about PlatformIO Library Dependency Finder 46 | - https://docs.platformio.org/page/librarymanager/ldf.html 47 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/WiFiManager/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 tzapu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/WiFiManager/examples/AutoConnect/AutoConnect.ino: -------------------------------------------------------------------------------- 1 | #include //https://github.com/esp8266/Arduino 2 | 3 | //needed for library 4 | #include 5 | #include 6 | #include //https://github.com/tzapu/WiFiManager 7 | 8 | 9 | void setup() { 10 | // put your setup code here, to run once: 11 | Serial.begin(115200); 12 | 13 | //WiFiManager 14 | //Local intialization. Once its business is done, there is no need to keep it around 15 | WiFiManager wifiManager; 16 | //reset saved settings 17 | //wifiManager.resetSettings(); 18 | 19 | //set custom ip for portal 20 | //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); 21 | 22 | //fetches ssid and pass from eeprom and tries to connect 23 | //if it does not connect it starts an access point with the specified name 24 | //here "AutoConnectAP" 25 | //and goes into a blocking loop awaiting configuration 26 | wifiManager.autoConnect("AutoConnectAP"); 27 | //or use this for auto generated name ESP + ChipID 28 | //wifiManager.autoConnect(); 29 | 30 | 31 | //if you get here you have connected to the WiFi 32 | Serial.println("connected...yeey :)"); 33 | } 34 | 35 | void loop() { 36 | // put your main code here, to run repeatedly: 37 | 38 | } 39 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/WiFiManager/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino: -------------------------------------------------------------------------------- 1 | #include //this needs to be first, or it all crashes and burns... 2 | 3 | #include //https://github.com/esp8266/Arduino 4 | 5 | //needed for library 6 | #include 7 | #include 8 | #include //https://github.com/tzapu/WiFiManager 9 | 10 | #include //https://github.com/bblanchon/ArduinoJson 11 | 12 | //define your default values here, if there are different values in config.json, they are overwritten. 13 | char mqtt_server[40]; 14 | char mqtt_port[6] = "8080"; 15 | char blynk_token[34] = "YOUR_BLYNK_TOKEN"; 16 | 17 | //flag for saving data 18 | bool shouldSaveConfig = false; 19 | 20 | //callback notifying us of the need to save config 21 | void saveConfigCallback () { 22 | Serial.println("Should save config"); 23 | shouldSaveConfig = true; 24 | } 25 | 26 | 27 | void setup() { 28 | // put your setup code here, to run once: 29 | Serial.begin(115200); 30 | Serial.println(); 31 | 32 | //clean FS, for testing 33 | //SPIFFS.format(); 34 | 35 | //read configuration from FS json 36 | Serial.println("mounting FS..."); 37 | 38 | if (SPIFFS.begin()) { 39 | Serial.println("mounted file system"); 40 | if (SPIFFS.exists("/config.json")) { 41 | //file exists, reading and loading 42 | Serial.println("reading config file"); 43 | File configFile = SPIFFS.open("/config.json", "r"); 44 | if (configFile) { 45 | Serial.println("opened config file"); 46 | size_t size = configFile.size(); 47 | // Allocate a buffer to store contents of the file. 48 | std::unique_ptr buf(new char[size]); 49 | 50 | configFile.readBytes(buf.get(), size); 51 | DynamicJsonBuffer jsonBuffer; 52 | JsonObject& json = jsonBuffer.parseObject(buf.get()); 53 | json.printTo(Serial); 54 | if (json.success()) { 55 | Serial.println("\nparsed json"); 56 | 57 | strcpy(mqtt_server, json["mqtt_server"]); 58 | strcpy(mqtt_port, json["mqtt_port"]); 59 | strcpy(blynk_token, json["blynk_token"]); 60 | 61 | } else { 62 | Serial.println("failed to load json config"); 63 | } 64 | configFile.close(); 65 | } 66 | } 67 | } else { 68 | Serial.println("failed to mount FS"); 69 | } 70 | //end read 71 | 72 | 73 | 74 | // The extra parameters to be configured (can be either global or just in the setup) 75 | // After connecting, parameter.getValue() will get you the configured value 76 | // id/name placeholder/prompt default length 77 | WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); 78 | WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); 79 | WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 32); 80 | 81 | //WiFiManager 82 | //Local intialization. Once its business is done, there is no need to keep it around 83 | WiFiManager wifiManager; 84 | 85 | //set config save notify callback 86 | wifiManager.setSaveConfigCallback(saveConfigCallback); 87 | 88 | //set static ip 89 | wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); 90 | 91 | //add all your parameters here 92 | wifiManager.addParameter(&custom_mqtt_server); 93 | wifiManager.addParameter(&custom_mqtt_port); 94 | wifiManager.addParameter(&custom_blynk_token); 95 | 96 | //reset settings - for testing 97 | //wifiManager.resetSettings(); 98 | 99 | //set minimu quality of signal so it ignores AP's under that quality 100 | //defaults to 8% 101 | //wifiManager.setMinimumSignalQuality(); 102 | 103 | //sets timeout until configuration portal gets turned off 104 | //useful to make it all retry or go to sleep 105 | //in seconds 106 | //wifiManager.setTimeout(120); 107 | 108 | //fetches ssid and pass and tries to connect 109 | //if it does not connect it starts an access point with the specified name 110 | //here "AutoConnectAP" 111 | //and goes into a blocking loop awaiting configuration 112 | if (!wifiManager.autoConnect("AutoConnectAP", "password")) { 113 | Serial.println("failed to connect and hit timeout"); 114 | delay(3000); 115 | //reset and try again, or maybe put it to deep sleep 116 | ESP.reset(); 117 | delay(5000); 118 | } 119 | 120 | //if you get here you have connected to the WiFi 121 | Serial.println("connected...yeey :)"); 122 | 123 | //read updated parameters 124 | strcpy(mqtt_server, custom_mqtt_server.getValue()); 125 | strcpy(mqtt_port, custom_mqtt_port.getValue()); 126 | strcpy(blynk_token, custom_blynk_token.getValue()); 127 | 128 | //save the custom parameters to FS 129 | if (shouldSaveConfig) { 130 | Serial.println("saving config"); 131 | DynamicJsonBuffer jsonBuffer; 132 | JsonObject& json = jsonBuffer.createObject(); 133 | json["mqtt_server"] = mqtt_server; 134 | json["mqtt_port"] = mqtt_port; 135 | json["blynk_token"] = blynk_token; 136 | 137 | File configFile = SPIFFS.open("/config.json", "w"); 138 | if (!configFile) { 139 | Serial.println("failed to open config file for writing"); 140 | } 141 | 142 | json.printTo(Serial); 143 | json.printTo(configFile); 144 | configFile.close(); 145 | //end save 146 | } 147 | 148 | Serial.println("local ip"); 149 | Serial.println(WiFi.localIP()); 150 | 151 | } 152 | 153 | void loop() { 154 | // put your main code here, to run repeatedly: 155 | 156 | 157 | } 158 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/WiFiManager/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino: -------------------------------------------------------------------------------- 1 | #include //this needs to be first, or it all crashes and burns... 2 | 3 | #include //https://github.com/esp8266/Arduino 4 | 5 | //needed for library 6 | #include 7 | #include 8 | #include //https://github.com/tzapu/WiFiManager 9 | 10 | #include //https://github.com/bblanchon/ArduinoJson 11 | 12 | //define your default values here, if there are different values in config.json, they are overwritten. 13 | //length should be max size + 1 14 | char mqtt_server[40]; 15 | char mqtt_port[6] = "8080"; 16 | char blynk_token[33] = "YOUR_BLYNK_TOKEN"; 17 | //default custom static IP 18 | char static_ip[16] = "10.0.1.56"; 19 | char static_gw[16] = "10.0.1.1"; 20 | char static_sn[16] = "255.255.255.0"; 21 | 22 | //flag for saving data 23 | bool shouldSaveConfig = false; 24 | 25 | //callback notifying us of the need to save config 26 | void saveConfigCallback () { 27 | Serial.println("Should save config"); 28 | shouldSaveConfig = true; 29 | } 30 | 31 | void setup() { 32 | // put your setup code here, to run once: 33 | Serial.begin(115200); 34 | Serial.println(); 35 | 36 | //clean FS, for testing 37 | //SPIFFS.format(); 38 | 39 | //read configuration from FS json 40 | Serial.println("mounting FS..."); 41 | 42 | if (SPIFFS.begin()) { 43 | Serial.println("mounted file system"); 44 | if (SPIFFS.exists("/config.json")) { 45 | //file exists, reading and loading 46 | Serial.println("reading config file"); 47 | File configFile = SPIFFS.open("/config.json", "r"); 48 | if (configFile) { 49 | Serial.println("opened config file"); 50 | size_t size = configFile.size(); 51 | // Allocate a buffer to store contents of the file. 52 | std::unique_ptr buf(new char[size]); 53 | 54 | configFile.readBytes(buf.get(), size); 55 | DynamicJsonBuffer jsonBuffer; 56 | JsonObject& json = jsonBuffer.parseObject(buf.get()); 57 | json.printTo(Serial); 58 | if (json.success()) { 59 | Serial.println("\nparsed json"); 60 | 61 | strcpy(mqtt_server, json["mqtt_server"]); 62 | strcpy(mqtt_port, json["mqtt_port"]); 63 | strcpy(blynk_token, json["blynk_token"]); 64 | 65 | if(json["ip"]) { 66 | Serial.println("setting custom ip from config"); 67 | //static_ip = json["ip"]; 68 | strcpy(static_ip, json["ip"]); 69 | strcpy(static_gw, json["gateway"]); 70 | strcpy(static_sn, json["subnet"]); 71 | //strcat(static_ip, json["ip"]); 72 | //static_gw = json["gateway"]; 73 | //static_sn = json["subnet"]; 74 | Serial.println(static_ip); 75 | /* Serial.println("converting ip"); 76 | IPAddress ip = ipFromCharArray(static_ip); 77 | Serial.println(ip);*/ 78 | } else { 79 | Serial.println("no custom ip in config"); 80 | } 81 | } else { 82 | Serial.println("failed to load json config"); 83 | } 84 | } 85 | } 86 | } else { 87 | Serial.println("failed to mount FS"); 88 | } 89 | //end read 90 | Serial.println(static_ip); 91 | Serial.println(blynk_token); 92 | Serial.println(mqtt_server); 93 | 94 | 95 | // The extra parameters to be configured (can be either global or just in the setup) 96 | // After connecting, parameter.getValue() will get you the configured value 97 | // id/name placeholder/prompt default length 98 | WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); 99 | WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5); 100 | WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 34); 101 | 102 | //WiFiManager 103 | //Local intialization. Once its business is done, there is no need to keep it around 104 | WiFiManager wifiManager; 105 | 106 | //set config save notify callback 107 | wifiManager.setSaveConfigCallback(saveConfigCallback); 108 | 109 | //set static ip 110 | IPAddress _ip,_gw,_sn; 111 | _ip.fromString(static_ip); 112 | _gw.fromString(static_gw); 113 | _sn.fromString(static_sn); 114 | 115 | wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); 116 | 117 | //add all your parameters here 118 | wifiManager.addParameter(&custom_mqtt_server); 119 | wifiManager.addParameter(&custom_mqtt_port); 120 | wifiManager.addParameter(&custom_blynk_token); 121 | 122 | //reset settings - for testing 123 | //wifiManager.resetSettings(); 124 | 125 | //set minimu quality of signal so it ignores AP's under that quality 126 | //defaults to 8% 127 | wifiManager.setMinimumSignalQuality(); 128 | 129 | //sets timeout until configuration portal gets turned off 130 | //useful to make it all retry or go to sleep 131 | //in seconds 132 | //wifiManager.setTimeout(120); 133 | 134 | //fetches ssid and pass and tries to connect 135 | //if it does not connect it starts an access point with the specified name 136 | //here "AutoConnectAP" 137 | //and goes into a blocking loop awaiting configuration 138 | if (!wifiManager.autoConnect("AutoConnectAP", "password")) { 139 | Serial.println("failed to connect and hit timeout"); 140 | delay(3000); 141 | //reset and try again, or maybe put it to deep sleep 142 | ESP.reset(); 143 | delay(5000); 144 | } 145 | 146 | //if you get here you have connected to the WiFi 147 | Serial.println("connected...yeey :)"); 148 | 149 | //read updated parameters 150 | strcpy(mqtt_server, custom_mqtt_server.getValue()); 151 | strcpy(mqtt_port, custom_mqtt_port.getValue()); 152 | strcpy(blynk_token, custom_blynk_token.getValue()); 153 | 154 | //save the custom parameters to FS 155 | if (shouldSaveConfig) { 156 | Serial.println("saving config"); 157 | DynamicJsonBuffer jsonBuffer; 158 | JsonObject& json = jsonBuffer.createObject(); 159 | json["mqtt_server"] = mqtt_server; 160 | json["mqtt_port"] = mqtt_port; 161 | json["blynk_token"] = blynk_token; 162 | 163 | json["ip"] = WiFi.localIP().toString(); 164 | json["gateway"] = WiFi.gatewayIP().toString(); 165 | json["subnet"] = WiFi.subnetMask().toString(); 166 | 167 | File configFile = SPIFFS.open("/config.json", "w"); 168 | if (!configFile) { 169 | Serial.println("failed to open config file for writing"); 170 | } 171 | 172 | json.prettyPrintTo(Serial); 173 | json.printTo(configFile); 174 | configFile.close(); 175 | //end save 176 | } 177 | 178 | Serial.println("local ip"); 179 | Serial.println(WiFi.localIP()); 180 | Serial.println(WiFi.gatewayIP()); 181 | Serial.println(WiFi.subnetMask()); 182 | } 183 | 184 | void loop() { 185 | // put your main code here, to run repeatedly: 186 | 187 | 188 | } 189 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/WiFiManager/examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino: -------------------------------------------------------------------------------- 1 | #include //https://github.com/esp8266/Arduino 2 | 3 | //needed for library 4 | #include 5 | #include 6 | #include "WiFiManager.h" //https://github.com/tzapu/WiFiManager 7 | 8 | void configModeCallback (WiFiManager *myWiFiManager) { 9 | Serial.println("Entered config mode"); 10 | Serial.println(WiFi.softAPIP()); 11 | //if you used auto generated SSID, print it 12 | Serial.println(myWiFiManager->getConfigPortalSSID()); 13 | } 14 | 15 | void setup() { 16 | // put your setup code here, to run once: 17 | Serial.begin(115200); 18 | 19 | //WiFiManager 20 | //Local intialization. Once its business is done, there is no need to keep it around 21 | WiFiManager wifiManager; 22 | //reset settings - for testing 23 | //wifiManager.resetSettings(); 24 | 25 | //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode 26 | wifiManager.setAPCallback(configModeCallback); 27 | 28 | //fetches ssid and pass and tries to connect 29 | //if it does not connect it starts an access point with the specified name 30 | //here "AutoConnectAP" 31 | //and goes into a blocking loop awaiting configuration 32 | if(!wifiManager.autoConnect()) { 33 | Serial.println("failed to connect and hit timeout"); 34 | //reset and try again, or maybe put it to deep sleep 35 | ESP.reset(); 36 | delay(1000); 37 | } 38 | 39 | //if you get here you have connected to the WiFi 40 | Serial.println("connected...yeey :)"); 41 | 42 | } 43 | 44 | void loop() { 45 | // put your main code here, to run repeatedly: 46 | 47 | } 48 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/WiFiManager/examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino: -------------------------------------------------------------------------------- 1 | #include //https://github.com/esp8266/Arduino 2 | 3 | //needed for library 4 | #include 5 | #include 6 | #include //https://github.com/tzapu/WiFiManager 7 | 8 | //for LED status 9 | #include 10 | Ticker ticker; 11 | 12 | void tick() 13 | { 14 | //toggle state 15 | int state = digitalRead(BUILTIN_LED); // get the current state of GPIO1 pin 16 | digitalWrite(BUILTIN_LED, !state); // set pin to the opposite state 17 | } 18 | 19 | //gets called when WiFiManager enters configuration mode 20 | void configModeCallback (WiFiManager *myWiFiManager) { 21 | Serial.println("Entered config mode"); 22 | Serial.println(WiFi.softAPIP()); 23 | //if you used auto generated SSID, print it 24 | Serial.println(myWiFiManager->getConfigPortalSSID()); 25 | //entered config mode, make led toggle faster 26 | ticker.attach(0.2, tick); 27 | } 28 | 29 | void setup() { 30 | // put your setup code here, to run once: 31 | Serial.begin(115200); 32 | 33 | //set led pin as output 34 | pinMode(BUILTIN_LED, OUTPUT); 35 | // start ticker with 0.5 because we start in AP mode and try to connect 36 | ticker.attach(0.6, tick); 37 | 38 | //WiFiManager 39 | //Local intialization. Once its business is done, there is no need to keep it around 40 | WiFiManager wifiManager; 41 | //reset settings - for testing 42 | //wifiManager.resetSettings(); 43 | 44 | //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode 45 | wifiManager.setAPCallback(configModeCallback); 46 | 47 | //fetches ssid and pass and tries to connect 48 | //if it does not connect it starts an access point with the specified name 49 | //here "AutoConnectAP" 50 | //and goes into a blocking loop awaiting configuration 51 | if (!wifiManager.autoConnect()) { 52 | Serial.println("failed to connect and hit timeout"); 53 | //reset and try again, or maybe put it to deep sleep 54 | ESP.reset(); 55 | delay(1000); 56 | } 57 | 58 | //if you get here you have connected to the WiFi 59 | Serial.println("connected...yeey :)"); 60 | ticker.detach(); 61 | //keep LED on 62 | digitalWrite(BUILTIN_LED, LOW); 63 | } 64 | 65 | void loop() { 66 | // put your main code here, to run repeatedly: 67 | 68 | } 69 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/WiFiManager/examples/AutoConnectWithReset/AutoConnectWithReset.ino: -------------------------------------------------------------------------------- 1 | #include //this needs to be first, or it all crashes and burns... 2 | 3 | #include //https://github.com/esp8266/Arduino 4 | 5 | //needed for library 6 | #include 7 | #include 8 | #include //https://github.com/tzapu/WiFiManager 9 | 10 | void setup() { 11 | // put your setup code here, to run once: 12 | Serial.begin(115200); 13 | Serial.println(); 14 | 15 | //WiFiManager 16 | //Local intialization. Once its business is done, there is no need to keep it around 17 | WiFiManager wifiManager; 18 | 19 | //exit after config instead of connecting 20 | wifiManager.setBreakAfterConfig(true); 21 | 22 | //reset settings - for testing 23 | //wifiManager.resetSettings(); 24 | 25 | 26 | //tries to connect to last known settings 27 | //if it does not connect it starts an access point with the specified name 28 | //here "AutoConnectAP" with password "password" 29 | //and goes into a blocking loop awaiting configuration 30 | if (!wifiManager.autoConnect("AutoConnectAP", "password")) { 31 | Serial.println("failed to connect, we should reset as see if it connects"); 32 | delay(3000); 33 | ESP.reset(); 34 | delay(5000); 35 | } 36 | 37 | //if you get here you have connected to the WiFi 38 | Serial.println("connected...yeey :)"); 39 | 40 | 41 | Serial.println("local ip"); 42 | Serial.println(WiFi.localIP()); 43 | } 44 | 45 | void loop() { 46 | // put your main code here, to run repeatedly: 47 | 48 | 49 | } 50 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/WiFiManager/examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino: -------------------------------------------------------------------------------- 1 | #include //this needs to be first, or it all crashes and burns... 2 | 3 | #include //https://github.com/esp8266/Arduino 4 | 5 | //needed for library 6 | #include 7 | #include 8 | #include //https://github.com/tzapu/WiFiManager 9 | 10 | 11 | /************************************************************************************** 12 | * this example shows how to set a static IP configuration for the ESP 13 | * although the IP shows in the config portal, the changes will revert 14 | * to the IP set in the source file. 15 | * if you want the ability to configure and persist the new IP configuration 16 | * look at the FS examples, which save the config to file 17 | *************************************************************************************/ 18 | 19 | 20 | 21 | //default custom static IP 22 | //char static_ip[16] = "10.0.1.59"; 23 | //char static_gw[16] = "10.0.1.1"; 24 | //char static_sn[16] = "255.255.255.0"; 25 | 26 | void setup() { 27 | // put your setup code here, to run once: 28 | Serial.begin(115200); 29 | Serial.println(); 30 | 31 | //WiFiManager 32 | //Local intialization. Once its business is done, there is no need to keep it around 33 | WiFiManager wifiManager; 34 | 35 | //reset settings - for testing 36 | //wifiManager.resetSettings(); 37 | 38 | //set static ip 39 | //block1 should be used for ESP8266 core 2.1.0 or newer, otherwise use block2 40 | 41 | //start-block1 42 | //IPAddress _ip,_gw,_sn; 43 | //_ip.fromString(static_ip); 44 | //_gw.fromString(static_gw); 45 | //_sn.fromString(static_sn); 46 | //end-block1 47 | 48 | //start-block2 49 | IPAddress _ip = IPAddress(10, 0, 1, 78); 50 | IPAddress _gw = IPAddress(10, 0, 1, 1); 51 | IPAddress _sn = IPAddress(255, 255, 255, 0); 52 | //end-block2 53 | 54 | wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); 55 | 56 | 57 | //tries to connect to last known settings 58 | //if it does not connect it starts an access point with the specified name 59 | //here "AutoConnectAP" with password "password" 60 | //and goes into a blocking loop awaiting configuration 61 | if (!wifiManager.autoConnect("AutoConnectAP", "password")) { 62 | Serial.println("failed to connect, we should reset as see if it connects"); 63 | delay(3000); 64 | ESP.reset(); 65 | delay(5000); 66 | } 67 | 68 | //if you get here you have connected to the WiFi 69 | Serial.println("connected...yeey :)"); 70 | 71 | 72 | Serial.println("local ip"); 73 | Serial.println(WiFi.localIP()); 74 | } 75 | 76 | void loop() { 77 | // put your main code here, to run repeatedly: 78 | 79 | 80 | } 81 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/WiFiManager/examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino: -------------------------------------------------------------------------------- 1 | #include //https://github.com/esp8266/Arduino 2 | 3 | //needed for library 4 | #include 5 | #include 6 | #include //https://github.com/tzapu/WiFiManager 7 | 8 | 9 | 10 | void setup() { 11 | // put your setup code here, to run once: 12 | Serial.begin(115200); 13 | 14 | //WiFiManager 15 | //Local intialization. Once its business is done, there is no need to keep it around 16 | WiFiManager wifiManager; 17 | //reset settings - for testing 18 | //wifiManager.resetSettings(); 19 | 20 | //sets timeout until configuration portal gets turned off 21 | //useful to make it all retry or go to sleep 22 | //in seconds 23 | wifiManager.setTimeout(180); 24 | 25 | //fetches ssid and pass and tries to connect 26 | //if it does not connect it starts an access point with the specified name 27 | //here "AutoConnectAP" 28 | //and goes into a blocking loop awaiting configuration 29 | if(!wifiManager.autoConnect("AutoConnectAP")) { 30 | Serial.println("failed to connect and hit timeout"); 31 | delay(3000); 32 | //reset and try again, or maybe put it to deep sleep 33 | ESP.reset(); 34 | delay(5000); 35 | } 36 | 37 | //if you get here you have connected to the WiFi 38 | Serial.println("connected...yeey :)"); 39 | 40 | } 41 | 42 | void loop() { 43 | // put your main code here, to run repeatedly: 44 | 45 | } 46 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/WiFiManager/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino: -------------------------------------------------------------------------------- 1 | #include //https://github.com/esp8266/Arduino 2 | 3 | //needed for library 4 | #include 5 | #include 6 | #include //https://github.com/tzapu/WiFiManager 7 | 8 | // select which pin will trigger the configuration portal when set to LOW 9 | // ESP-01 users please note: the only pins available (0 and 2), are shared 10 | // with the bootloader, so always set them HIGH at power-up 11 | #define TRIGGER_PIN 0 12 | 13 | 14 | void setup() { 15 | // put your setup code here, to run once: 16 | Serial.begin(115200); 17 | Serial.println("\n Starting"); 18 | 19 | pinMode(TRIGGER_PIN, INPUT); 20 | } 21 | 22 | 23 | void loop() { 24 | // is configuration portal requested? 25 | if ( digitalRead(TRIGGER_PIN) == LOW ) { 26 | //WiFiManager 27 | //Local intialization. Once its business is done, there is no need to keep it around 28 | WiFiManager wifiManager; 29 | 30 | //reset settings - for testing 31 | //wifiManager.resetSettings(); 32 | 33 | //sets timeout until configuration portal gets turned off 34 | //useful to make it all retry or go to sleep 35 | //in seconds 36 | //wifiManager.setTimeout(120); 37 | 38 | //it starts an access point with the specified name 39 | //here "AutoConnectAP" 40 | //and goes into a blocking loop awaiting configuration 41 | 42 | //WITHOUT THIS THE AP DOES NOT SEEM TO WORK PROPERLY WITH SDK 1.5 , update to at least 1.5.1 43 | //WiFi.mode(WIFI_STA); 44 | 45 | if (!wifiManager.startConfigPortal("OnDemandAP")) { 46 | Serial.println("failed to connect and hit timeout"); 47 | delay(3000); 48 | //reset and try again, or maybe put it to deep sleep 49 | ESP.reset(); 50 | delay(5000); 51 | } 52 | 53 | //if you get here you have connected to the WiFi 54 | Serial.println("connected...yeey :)"); 55 | } 56 | 57 | 58 | // put your main code here, to run repeatedly: 59 | 60 | } 61 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/WiFiManager/extras/WiFiManager.template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | {v} 7 | 8 | 9 | 18 | 19 | 20 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 38 | 39 | 43 | 44 | 45 | 46 |



47 | 48 | 49 |
{v} {r}%
50 |
PMisa 100%
51 | 52 |
PMisa 8%
53 | 54 | 55 |
{v} {r}%
56 | 57 | 58 |


59 | 60 | 61 |
62 | 63 | 64 |
65 | 66 | 67 |
68 | 69 | 70 |
Credentials Saved
Trying to connect ESP to network.
If it fails reconnect to AP to try again
71 | 72 | 73 | 74 | 75 | 76 | 77 |
78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /WemosEM-Mqtt-Power-Sensor/lib/WiFiManager/extras/parse.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | 5 | console.log('starting'); 6 | 7 | const inFile = 'WiFiManager.template.html'; 8 | const outFile = 'template.h'; 9 | 10 | const defineRegEx = //gm; 11 | console.log('parsing', inFile); 12 | 13 | fs.readFile(inFile, 'utf8', function (err,data) { 14 | if (err) { 15 | return console.log(err); 16 | } 17 | //console.log(data); 18 | 19 | let defines = data.match(defineRegEx); 20 | 21 | //console.log(defines); 22 | var stream = fs.createWriteStream(outFile); 23 | stream.once('open', function(fd) { 24 | for (const i in defines) { 25 | 26 | const start = defines[i]; 27 | const end = start.replace('