Created
June 9, 2020 16:26
-
-
Save programmersommer/42792c4a44551111a92810008b04af8b to your computer and use it in GitHub Desktop.
Скетч для связи NodeMCU с AWS
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
// based on https://electronicsinnovation.com/how-to-connect-nodemcu-esp8266-with-aws-iot-core-using-arduino-ide-mqtt/ | |
// install https://github.com/esp8266/arduino-esp8266fs-plugin and upload certificates | |
#include "FS.h" | |
#include <ESP8266WiFi.h> | |
#include <PubSubClient.h> | |
#include <NTPClient.h> | |
#include <WiFiUdp.h> | |
// Update these with values suitable for your network. | |
const char* ssid = "введите-имя-сети"; | |
const char* password = "введите_пароль-от-сети-WIFI"; | |
WiFiUDP ntpUDP; | |
NTPClient timeClient(ntpUDP, "pool.ntp.org"); | |
const char* AWS_endpoint = "xxxxxxxxxxxxxx-ats.iot.eu-west-3.amazonaws.com"; // MQTT broker ip замените на свое | |
void callback(char* topic, byte* payload, unsigned int length) { | |
Serial.print("Message arrived ["); | |
Serial.print(topic); | |
Serial.print("] "); | |
String message = ""; | |
for (int i = 0; i < length; i++) { | |
Serial.print((char)payload[i]); | |
message = String(message + (char)payload[i]); | |
} | |
Serial.println(); | |
Serial.println(message); | |
if (message == "ON") { | |
digitalWrite(D0, HIGH); | |
} | |
else if (message == "OFF") { | |
digitalWrite(D0, LOW); | |
} | |
} | |
WiFiClientSecure espClient; | |
PubSubClient client(AWS_endpoint, 8883, callback, espClient); //set MQTT port number to 8883 as per //standard | |
long lastMsg = 0; | |
char msg[50]; | |
int value = 0; | |
void setup_wifi() { | |
delay(10); | |
// We start by connecting to a WiFi network | |
espClient.setBufferSizes(512, 512); | |
Serial.println(); | |
Serial.print("Connecting to "); | |
Serial.println(ssid); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println(""); | |
Serial.println("WiFi connected"); | |
Serial.println("IP address: "); | |
Serial.println(WiFi.localIP()); | |
timeClient.begin(); | |
while (!timeClient.update()) { | |
timeClient.forceUpdate(); | |
} | |
espClient.setX509Time(timeClient.getEpochTime()); | |
} | |
void reconnect() { | |
// Loop until we're reconnected | |
while (!client.connected()) { | |
Serial.print("Attempting MQTT connection..."); | |
// Attempt to connect Замените ESPthing на любое имя | |
if (client.connect("ESPthing")) { | |
Serial.println("connected"); | |
// Once connected, publish an announcement... | |
client.publish("outTopic", "hello world"); | |
// ... and resubscribe | |
client.subscribe("inTopic"); | |
} else { | |
Serial.print("failed, rc="); | |
Serial.print(client.state()); | |
Serial.println(" try again in 5 seconds"); | |
char buf[256]; | |
espClient.getLastSSLError(buf, 256); | |
Serial.print("WiFiClientSecure SSL error: "); | |
Serial.println(buf); | |
// Wait 5 seconds before retrying | |
delay(5000); | |
} | |
} | |
} | |
void setup() { | |
pinMode(D0, OUTPUT); | |
Serial.begin(115200); | |
Serial.setDebugOutput(true); | |
// initialize digital pin LED_BUILTIN as an output. | |
pinMode(LED_BUILTIN, OUTPUT); | |
setup_wifi(); | |
delay(1000); | |
if (!SPIFFS.begin()) { | |
Serial.println("Failed to mount file system"); | |
return; | |
} | |
Serial.print("Heap: "); Serial.println(ESP.getFreeHeap()); | |
// Load certificate file | |
File cert = SPIFFS.open("/cert.der", "r"); //replace cert.crt eith your uploaded file name | |
if (!cert) { | |
Serial.println("Failed to open cert file"); | |
} | |
else | |
Serial.println("Success to open cert file"); | |
delay(1000); | |
if (espClient.loadCertificate(cert)) | |
Serial.println("cert loaded"); | |
else | |
Serial.println("cert not loaded"); | |
// Load private key file | |
File private_key = SPIFFS.open("/private.der", "r"); //replace private eith your uploaded file name | |
if (!private_key) { | |
Serial.println("Failed to open private cert file"); | |
} | |
else | |
Serial.println("Success to open private cert file"); | |
delay(1000); | |
if (espClient.loadPrivateKey(private_key)) | |
Serial.println("private key loaded"); | |
else | |
Serial.println("private key not loaded"); | |
// Load CA file | |
File ca = SPIFFS.open("/ca.der", "r"); //replace ca eith your uploaded file name | |
if (!ca) { | |
Serial.println("Failed to open ca "); | |
} | |
else | |
Serial.println("Success to open ca"); | |
delay(1000); | |
if (espClient.loadCACert(ca)) | |
Serial.println("ca loaded"); | |
else | |
Serial.println("ca failed"); | |
Serial.print("Heap: "); Serial.println(ESP.getFreeHeap()); | |
} | |
void loop() { | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.loop(); | |
long now = millis(); | |
if (now - lastMsg > 2000) { | |
lastMsg = now; | |
value = analogRead(17); // от 0 до 1024 | |
// перенос из одного диапазона в другой | |
value = map(value, 0, 1023, 0, 100); | |
// значение строго от 0 до 100 | |
value = constrain(value, 0, 100); | |
snprintf (msg, 75, "{\"key\":\"%ld\", \"light\": \"%ld\"}", timeClient.getEpochTime(), value); // %ld - long | |
Serial.print("Publish message: "); | |
Serial.println(msg); | |
client.publish("outTopic", msg); | |
Serial.print("Heap: "); Serial.println(ESP.getFreeHeap()); //Low heap can cause problems | |
} | |
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) | |
delay(1000); // wait for a second | |
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW | |
delay(1000); // wait for a second | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment