· 6 years ago · Dec 27, 2019, 12:10 PM
1#include <FS.h> //this needs to be first, or it all crashes and burns..
2
3#include <ESP8266WiFi.h>
4#include <DNSServer.h> //Local DNS Server used for redirecting all requests to the configuration portal
5#include <ESP8266WebServer.h> //Local WebServer used to serve the configuration portal
6#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager WiFi Configuration Magic
7#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
8//#include <MQTT.h>
9//#include <PubSubClient.h>
10//#include <PubSubClient_JSON.h>
11#include "Adafruit_MQTT.h"
12#include "Adafruit_MQTT_Client.h"
13
14//flag for saving data
15bool shouldSaveConfig = false;
16
17#include <Wire.h>
18#include <energyic_UART.h>
19#if !defined(ARDUINO_ARCH_SAMD)
20#include <SoftwareSerial.h>
21#else
22
23#endif
24
25// #include <Adafruit_GFX.h>
26
27/************************* WiFi Access Point *********************************/
28
29#define WLAN_SSID "my"
30#define WLAN_PASS ""
31
32/************************* Adafruit.io Setup *********************************/
33
34#define AIO_SERVER "io.adafruit.com"
35#define AIO_SERVERPORT 1883 // use 8883 for SSL
36#define AIO_USERNAME "anirudhpsingh"
37#define AIO_KEY "aio_AsjG74uMAnWsqPd54uJI7ABBhBby"
38
39/************ Global State (you don't need to change this!) ******************/
40
41// Create an ESP8266 WiFiClient class to connect to the MQTT server.
42WiFiClient client;
43// or... use WiFiFlientSecure for SSL
44//WiFiClientSecure client;
45
46// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
47Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
48
49/****************************** Feeds ***************************************/
50
51// Setup a feed called 'photocell' for publishing.
52// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
53Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/photocell");
54
55// Setup a feed called 'onoff' for subscribing to changes.
56Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/onoff");
57
58/*************************** Sketch Code ************************************/
59
60
61
62#if defined(ESP8266)
63//NOTE: Version 1.0 and 1.1 of featherwing use pins 14,12
64//version 1.2 and above using pins 13,14
65//SoftwareSerial ATMSerial(14, 12, false, 256); //RX, TX v1.0-1.1
66SoftwareSerial ATMSerial(13, 14, false, 256); //RX, TX v1.2+
67//SoftwareSerial ATMSerial(D4, D3, false, 256); //NodeMCU v1.0
68#endif
69
70#ifdef AVR_ATmega32U4 //32u4 board
71SoftwareSerial ATMSerial(11, 13); //RX, TX
72#endif
73
74#if defined(ARDUINO_ARCH_SAMD)
75#include "wiring_private.h" // pinPeripheral() function
76//Feather M0
77#define PIN_SerialATM_RX 12ul
78#define PIN_SerialATM_TX 11ul
79#define PAD_SerialATM_RX (SERCOM_RX_PAD_3)
80#define PAD_SerialATM_TX (UART_TX_PAD_0)
81
82// Using SERCOM1 on M0 to communicate with ATM90E26
83Uart ATMSerial(&sercom1, PIN_SerialATM_RX, PIN_SerialATM_TX, PAD_SerialATM_RX, PAD_SerialATM_TX);
84#endif
85
86ATM90E26_UART eic(&ATMSerial);
87
88
89
90char server[50] = "api.minionlabs.tech";
91// Sign up on thingspeak and get WRITE API KEY.
92char auth[36] = "CRM67VQ1O";
93
94//WiFiClient client;
95
96
97
98//callback notifying us of the need to save config
99void saveConfigCallback () {
100 Serial.println("Should save config");
101 shouldSaveConfig = true;
102}
103// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
104// for some reason (only affects ESP8266, likely an arduino-builder bug).
105
106void MQTT_connect();
107
108void setup() {
109 Serial.begin(115200);
110 delay(10);
111 Serial.println(F("Adafruit MQTT demo"));
112
113 // Connect to WiFi access point.
114 Serial.println(); Serial.println();
115 Serial.print("Connecting to ");
116 Serial.println(WLAN_SSID);
117
118 WiFi.begin(WLAN_SSID, WLAN_PASS);
119 while (WiFi.status() != WL_CONNECTED) {
120 delay(500);
121 Serial.print(".");
122 }
123 Serial.println();
124
125 Serial.println("WiFi connected");
126 Serial.println("IP address: "); Serial.println(WiFi.localIP());
127 // The extra parameters to be configured (can be either global or just in the setup)
128 // After connecting, parameter.getValue() will get you the configured value
129 // id/name placeholder/prompt default length
130 WiFiManagerParameter custom_ts_token("ts", "Thingspeak Key", auth, 33);
131 WiFiManagerParameter custom_server("serv", "Server", server, 50);
132
133 //Use wifi manager to get config
134 WiFiManager wifiManager;
135 wifiManager.setDebugOutput(false);
136
137 //set config save notify callback
138 wifiManager.setSaveConfigCallback(saveConfigCallback);
139
140 //add all your parameters here
141 wifiManager.addParameter(&custom_ts_token);
142 wifiManager.addParameter(&custom_server);
143 //first parameter is name of access point, second is the password
144 wifiManager.autoConnect("Minion", "password");
145 //if you get here you have connected to the WiFi
146 Serial.println("connected...yeey :)");
147 Serial.print("Key:");
148 Serial.println(auth);
149 Serial.print("Server:");
150 Serial.println(server);
151 //read updated parameters
152 strcpy(auth, custom_ts_token.getValue());
153 strcpy(server, custom_server.getValue());
154
155 delay(1000);
156
157 //void MQTT_connect();
158
159 // Setup MQTT subscription for onoff feed.
160 mqtt.subscribe(&onoffbutton);
161}
162uint32_t x = 0;
163//Serial.begin(115200);
164#if defined(ARDUINO_ARCH_SAMD)
165pinPeripheral(PIN_SerialATM_RX, PIO_SERCOM);
166pinPeripheral(PIN_SerialATM_TX, PIO_SERCOM);
167#endif
168/*
169 //Must begin ATMSerial before IC init
170 ATMSerial.begin(9600);
171 eic.InitEnergyIC();
172*/
173
174//Wire.begin();
175
176//Read previous config
177
178// The extra parameters to be configured (can be either global or just in the setup)
179// After connecting, parameter.getValue() will get you the configured value
180// id/name placeholder/prompt default length
181WiFiManagerParameter custom_ts_token("ts", "Thingspeak Key", auth, 33);
182WiFiManagerParameter custom_server("serv", "Server", server, 50);
183/*
184 //Use wifi manager to get config
185 WiFiManager wifiManager;
186 wifiManager.setDebugOutput(false);
187
188 //set config save notify callback
189 wifiManager.setSaveConfigCallback(saveConfigCallback);
190
191 //add all your parameters here
192 wifiManager.addParameter(&custom_ts_token);
193 wifiManager.addParameter(&custom_server);
194*/
195/*
196 //first parameter is name of access point, second is the password
197 wifiManager.autoConnect("Minion", "password");
198*/
199/*
200 //if you get here you have connected to the WiFi
201 Serial.println("connected...yeey :)");
202 Serial.print("Key:");
203 Serial.println(auth);
204 Serial.print("Server:");
205 Serial.println(server);
206*/
207/*
208 //read updated parameters
209 strcpy(auth, custom_ts_token.getValue());
210 strcpy(server, custom_server.getValue());
211
212 delay(1000);
213 }
214*/
215
216void loop() {
217 /*Repeatedly fetch some values from the ATM90E26 */
218 unsigned short s_status = eic.GetSysStatus();
219 if (s_status == 0xFFFF)
220 {
221#if defined(ESP8266)
222 //Read failed reset ESP, this is heavy
223 ESP.restart();
224 //Must begin ATMSerial before IC init
225 ATMSerial.begin(9600);
226 eic.InitEnergyIC();
227#endif
228 }
229 Wire.begin();
230 // Ensure the connection to the MQTT server is alive (this will make the first
231 // connection and automatically reconnect when disconnected). See the MQTT_connect
232 // function definition further below.
233 MQTT_connect();
234
235 // this is our 'wait for incoming subscription packets' busy subloop
236 // try to spend your time here
237
238 Adafruit_MQTT_Subscribe *subscription;
239 while ((subscription = mqtt.readSubscription(5000))) {
240 if (subscription == &onoffbutton) {
241 Serial.print(F("Got: "));
242 Serial.println((char *)onoffbutton.lastread);
243 }
244 }
245
246 float id = ESP.getChipId();
247 float Vrms1 = eic.GetLineVoltage();
248 float Crms1 = eic.GetLineCurrent();
249 float realPower1 = eic.GetActivePower();
250 float powerFactor1 = eic.GetPowerFactor();
251 float freq1 = eic.GetFrequency();
252 //float imp1 = eic.GetImportEnergy();
253 //float exp1 = eic.GetExportEnergy();
254
255
256 Serial.print(id);
257 Serial.print(",");
258 Serial.print(Vrms1);
259 Serial.print(",");
260 Serial.print(Crms1);
261 Serial.print(",");
262 Serial.print(realPower1);
263 Serial.print(",");
264 Serial.print(powerFactor1);
265 Serial.print(",");
266 Serial.print(freq1);
267 // Serial.print(",");
268 //Serial.print(imp1);
269 //Serial.print(",");
270 //Serial.print(exp1);
271 // Now we can publish stuff!
272 Serial.print(F("\nSending photocell val "));
273 Serial.print(x);
274 Serial.print("...");
275 if (! photocell.publish(x++)) {
276 Serial.println(F("Failed"));
277 } else {
278 Serial.println(F("OK!"));
279 void MQTT_connect() {
280 int8_t ret;
281
282 // Stop if already connected.
283 if (mqtt.connected()) {
284 return;
285 }
286
287 Serial.print("Connecting to MQTT... ");
288
289 uint8_t retries = 3;
290 while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
291 Serial.println(mqtt.connectErrorString(ret));
292 Serial.println("Retrying MQTT connection in 5 seconds...");
293 mqtt.disconnect();
294 delay(5000); // wait 5 seconds
295 retries--;
296 if (retries == 0) {
297 // basically die and wait for WDT to reset me
298 while (1);
299 }
300 }
301 Serial.println("MQTT Connected!");
302 }
303
304
305
306 if (client.connect(server, 80)) { // "184.106.153.149" or api.thingspeak.com
307 String postStr = String(auth);
308 postStr += "&field1=";
309 postStr += String(id);
310 postStr += "&field2=";
311 postStr += String(Vrms1);
312 postStr += "&field3=";
313 postStr += String(Crms1);
314 postStr += "&field4=";
315 postStr += String(realPower1);
316 postStr += "&field5=";
317 postStr += String(powerFactor1);
318 postStr += "&field6=";
319 postStr += String(freq1);
320 // postStr +="&field7=";
321 // postStr += String(imp1);
322 // postStr +="&field8=";
323 // postStr += String(exp1);
324 postStr += "\r\n\r\n";
325
326 client.print("POST /api/data/CRM67VQ1O HTTP/1.1\r\n");
327 client.print("Host: api.minionlabs.tech\r\n");
328 client.print("Connection: close\r\n");
329 client.print("Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n");
330 client.print("Content-Length: ");
331 client.print(postStr.length());
332 client.print("\r\n\r\n");
333 client.print(postStr);
334 }
335 client.stop();
336
337 delay(14000);
338 }