Created
June 30, 2018 03:28
-
-
Save starhopp3r/d23fa5e38d62673761cb8be8e553b4ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// esp8266-mqtt-client.ino | |
// Beverly | |
// | |
// Created by Nikhil Raghavendra on 25/6/18. | |
// Copyright © 2018 Nikhil Raghavendra. All rights reserved. | |
// | |
#include <Arduino.h> | |
#include <Stream.h> | |
// ESP8266 WiFi | |
#include <ESP8266WiFi.h> | |
#include <ESP8266WiFiMulti.h> | |
// Arduino JSON parsing | |
#include <ArduinoJson.h> | |
// AWS dependencies | |
#include "sha256.h" | |
#include "Utils.h" | |
// WebSockets | |
#include <Hash.h> | |
#include <WebSocketsClient.h> | |
// MQTT PubSub client | |
#include <PubSubClient.h> | |
// AWS MQTT WebSocket | |
#include "Client.h" | |
#include "AWSWebSocketClient.h" | |
#include "CircularByteBuffer.h" | |
// Pump pin configuration | |
#define pumpOne 16 | |
#define pumpTwo 5 | |
#define pumpThree 4 | |
#define pumpFour 0 | |
// Pump time of the pumps | |
#define pumpTime 10000 | |
extern "C" { | |
#include "user_interface.h" | |
} | |
// Set up ESP8266 WiFi, AWS WebSocket client and PubSub client | |
ESP8266WiFiMulti WiFiMulti; | |
AWSWebSocketClient awsWSclient(1000); | |
PubSubClient client(awsWSclient); | |
// AWS IoT credentials and configurations | |
char wifi_ssid[] = "AndroidAP"; | |
char wifi_password[] = "vnfd5483"; | |
char aws_endpoint[] = "<aws endpoint>"; | |
char aws_key[] = "<aws key>"; | |
char aws_secret[] = "<aws secret>"; | |
char aws_region[] = "us-east-1"; | |
const char* aws_topic = "<aws topic>"; | |
int port = 443; | |
// MQTT configuration | |
const int maxMQTTpackageSize = 512; | |
const int maxMQTTMessageHandlers = 1; | |
// Number of connections | |
long connection = 0; | |
// Count the number of messages arrived | |
int arrivedcount = 0; | |
// Initialize JSON payload | |
String json = ""; | |
// Initialize global variables to check pump status | |
// Default status is set to 0 (off) to prevent accidental pumping | |
int Pump_Status_P1 = 0; | |
int Pump_Status_P2 = 0; | |
int Pump_Status_P3 = 0; | |
int Pump_Status_P4 = 0; | |
// Generate random MQTT ClientID | |
char* generateClientID() { | |
char* cID = new char[23](); | |
for(int i=0; i<22; i+=1) | |
cID[i] =(char) random(1, 256); | |
return cID; | |
} | |
void activatePump(int PumpStatus[]) { | |
if (PumpStatus[0] == 1) { | |
digitalWrite(pumpOne, HIGH); | |
delay(pumpTime); | |
digitalWrite(pumpOne, LOW); | |
} else if (PumpStatus[1] == 1) { | |
digitalWrite(pumpTwo, HIGH); | |
delay(pumpTime); | |
digitalWrite(pumpTwo, LOW); | |
} else if (PumpStatus[2] == 1) { | |
digitalWrite(pumpThree, HIGH); | |
delay(pumpTime); | |
digitalWrite(pumpThree, LOW); | |
} else if (PumpStatus[3] == 1) { | |
digitalWrite(pumpFour, HIGH); | |
delay(pumpTime); | |
digitalWrite(pumpFour, LOW); | |
} | |
} | |
// Callback to handle payload | |
void callback(char* topic, byte* payload, unsigned int length) { | |
// Print the payload to the console | |
Serial.print("Message arrived ["); | |
Serial.print(topic); | |
Serial.print("] "); | |
for(int i = 0; i < length; i++) { | |
// Append payload objects to JSON string | |
json.concat((char) payload[i]); | |
} | |
// Display the JSON object | |
Serial.println(json); | |
// Parse the JSON object and extract values | |
const size_t bufferSize = JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(4) + 40; | |
DynamicJsonBuffer jsonBuffer(bufferSize); | |
// Get root of JSON object | |
JsonObject& root = jsonBuffer.parseObject(json); | |
JsonObject& Pump_Status = root["Pump Status"]; | |
// Pump status | |
Pump_Status_P1 = Pump_Status["P1"]; | |
Pump_Status_P2 = Pump_Status["P2"]; | |
Pump_Status_P3 = Pump_Status["P3"]; | |
Pump_Status_P4 = Pump_Status["P4"]; | |
// Display the pump status | |
Serial.print("Pump 1 Status: "); | |
Serial.println(Pump_Status_P1); | |
Serial.print("Pump 2 Status: "); | |
Serial.println(Pump_Status_P2); | |
Serial.print("Pump 3 Status: "); | |
Serial.println(Pump_Status_P3); | |
Serial.print("Pump 4 Status: "); | |
Serial.println(Pump_Status_P4); | |
// Activate pump | |
int pumpStatus[] = {Pump_Status_P1, Pump_Status_P2, Pump_Status_P3, Pump_Status_P4}; | |
activatePump(pumpStatus); | |
// Empty the JSON object | |
json = ""; | |
} | |
// Connects to WebSocket layer and MQTT layer | |
bool connect() { | |
if(client.connected()) { | |
client.disconnect(); | |
} | |
// Delay is not necessary. It just help us to get a trustful heap space value. | |
delay(1000); | |
Serial.print(millis()); | |
Serial.print(" - conn: "); | |
Serial.print(++connection); | |
Serial.print(" -("); | |
Serial.print(ESP.getFreeHeap()); | |
Serial.println(")"); | |
// Creating random ClientID | |
char* clientID = generateClientID(); | |
// Connect to AWS IoT end point | |
client.setServer(aws_endpoint, port); | |
if(client.connect(clientID)) { | |
Serial.println("connected"); | |
return true; | |
} else { | |
Serial.print("failed, rc="); | |
Serial.print(client.state()); | |
return false; | |
} | |
} | |
// Subscribe to an MQTT topic | |
void subscribe() { | |
client.setCallback(callback); | |
client.subscribe(aws_topic); | |
// Subscribe to an MQTT topic | |
Serial.println("MQTT subscribed"); | |
} | |
// Inform AWS IoT that the ESP8266 has connected to the MQTT broker | |
void connectedAck() { | |
// Send connection acknowledgement to AWS IoT | |
char buf[100]; | |
strcpy(buf, "{\"state\":{\"reported\":{\"on\": true}, \"desired\":{\"on\": true}}}"); | |
int rc = client.publish(aws_topic, buf); | |
} | |
void setup() { | |
// GPIO pin configuration | |
pinMode(pumpOne, OUTPUT); | |
pinMode(pumpTwo, OUTPUT); | |
pinMode(pumpThree, OUTPUT); | |
pinMode(pumpFour, OUTPUT); | |
// WiFi and serial monitor configuration | |
wifi_set_sleep_type(NONE_SLEEP_T); | |
Serial.begin(115200); | |
delay(2000); | |
Serial.setDebugOutput(1); | |
// Fill with SSID and WiFi password | |
WiFiMulti.addAP(wifi_ssid, wifi_password); | |
Serial.println("connecting to wifi"); | |
while(WiFiMulti.run() != WL_CONNECTED) { | |
delay(100); | |
Serial.print("."); | |
} | |
Serial.println("\nconnected"); | |
// Fill AWS parameters | |
awsWSclient.setAWSRegion(aws_region); | |
awsWSclient.setAWSDomain(aws_endpoint); | |
awsWSclient.setAWSKeyID(aws_key); | |
awsWSclient.setAWSSecretKey(aws_secret); | |
awsWSclient.setUseSSL(true); | |
// Connect to WebSocket layer and MQTT layer | |
if(connect()){ | |
// Subscribe to the MQTT topic | |
subscribe(); | |
// Send a connection acknowledgement message to AWS IoT | |
connectedAck(); | |
} | |
} | |
void loop() { | |
// Keep the MQTT up and running | |
if(awsWSclient.connected()) { | |
client.loop(); | |
} else { | |
// Handle reconnection | |
if(connect()){ | |
subscribe(); | |
// Send a connection acknowledgement message to AWS IoT | |
connectedAck(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment