Skip to content

Instantly share code, notes, and snippets.

View pgsamila's full-sized avatar
:octocat:
W I P

Amila Sampath pgsamila

:octocat:
W I P
View GitHub Profile
#include <stdio.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>
#define HTTP_REST_PORT 80
#define WIFI_RETRY_DELAY 500
#define MAX_WIFI_INIT_RETRY 50
const char* wifi_ssid = "wifi_ssid_name";
const char* wifi_passwd = "wifi_password";
/**
Function To Initialize WiFi
*/
int init_wifi() {
int retries = 0;
Serial.println("Connecting to WiFi ...");
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_passwd);
// check the status of WiFi connection to be WL_CONNECTED
/**
Function Of Rest API - /tempdata
This function will execute when a HTTP GET is called
*/
void get_temp_data() {
Serial.println("HTTP GET called");
// Create JSON object to send data
StaticJsonBuffer<200> jsonBuffer;
JsonObject& jsonObj = jsonBuffer.createObject();
/**
config REST API function
*/
void config_rest_server_routing() {
http_rest_server.on("/", HTTP_GET, []() {
http_rest_server.send(200, "text/html", "Welcome to REST Web Server");
});
// Add your REST APIs & the functions to be run when call those APIs
// http://192.168.1.7/tempdata
void setup(void) {
Serial.begin(115200);
Serial.println("MCU Program Started...");
if (init_wifi() == WL_CONNECTED) {
Serial.println("WIFI Connetted");
Serial.print(wifi_ssid);
Serial.print("--- IP: ");
Serial.println(WiFi.localIP());
}
else {
void loop(void) {
http_rest_server.handleClient();
}
// Update these with values suitable for your network.
const char* ssid = "........";
const char* password = "........";
const char* mqtt_server = "192.168.1.6"; // server link
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
@pgsamila
pgsamila / gist:fac96596c4b59458701de598387fc9c3
Created May 1, 2021 05:55
MQTT subscribe callback function
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Do something with node MCU
void reconnect() {
// Loop until we’ re reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");