<commit_before>/*
  ESPMetRED.cpp - A blend of ESP8266 MQTT and Node-Red.
  <NAME>
  http://espmetred.hobbytronics.com.pk
*/

#include <Arduino.h>
#include <ESPMetRED.h>

extern const char* WIFI_SSID;
extern const char* WIFI_PASSWORD;
extern const char* MQTT_SERVER;
extern const char* MQTT_USER;
extern const char* MQTT_PASSWORD;
extern const char* MQTT_PUBLISH_TOPIC;
extern const char* MQTT_SUBSCRIBE_TOPIC;
extern const char* CLIENT_ID;

WiFiClient _Client;
PubSubClient MQTTClient(_Client);

ESPMetRED::ESPMetRED()
{ 
	Serial.begin(115200);
	SPIFFS.begin();
	WiFi.mode(WIFI_STA);
	MQTTClient.setServer(MQTT_SERVER, 1883);
	MQTTClient.setCallback([this] (char* topic, byte* payload, unsigned int length) { this->callback(topic, payload, length); });
	Serial.println("ESP8266 started");
	NTP = ReadSPIFFS("Time");
	Serial.print("Time: ");
	Serial.println(NTP);
}

void ESPMetRED::joinWiFi()
{
	boolean access_point_check = WiFiScanner();
	if ((access_point_check) && (WiFi.status() != WL_CONNECTED))
	{
		Serial.println("Connecting to WiFi Access Point");
		WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
	} else if ((access_point_check) && (WiFi.status() == WL_CONNECTED))
	{
		Serial.println("WiFi connected");
	}
}

boolean ESPMetRED::WiFiScanner()
{
	Serial.println("Scanning WiFi Network");
	int n = WiFi.scanNetworks();
	delay(300);
	for (int i = 0; i < n; ++i)
	{
		if (WiFi.SSID(i) == WIFI_SSID)
		{
			Serial.println("WiFi Network Available");
			return true;
		}
	}
	Serial.println("WiFi Network NOT Available");
	return false;
}

void ESPMetRED::joinMqTT()
{
	MQTTClient.connect(CLIENT_ID, MQTT_USER, MQTT_PASSWORD);
	
	if (MQTTClient.connected()) {
		MQTTClient.subscribe(MQTT_SUBSCRIBE_TOPIC);
		MQTTClient.subscribe("ntp/OUT");
		Publish("debug", String(CLIENT_ID) + " [LOGGED IN]");
		Publish("ntp/IN", JsonString(String(MQTT_SUBSCRIBE_TOPIC), ""));
	} else {
		Serial.print("Failed to connect to mqtt server, rc=");
		Serial.print(MQTTClient.state());
		Serial.println("");
	}
}

void ESPMetRED::keepalive()
{
	if (((millis() - connection_watchdog) > 12000UL) && (WiFi.status() != WL_CONNECTED))
	{
		connection_watchdog = millis();
		joinWiFi();
	} else if (((millis() - connection_watchdog) > 12000UL) && (WiFi.status() == WL_CONNECTED) && (!MQTTClient.connected()))
	{
		joinMqTT();
	}
	if ((millis() - Time_Log) > 300000UL)
	{
		Time_Log = millis();
		WriteSPIFFS("Time", _Time);
	}
	
	MQTTClient.loop();
	Timer();
	
	if(_Time > 86400000L)
	{
		NTP = (0 - (millis()));
		Timer();
	}
	
	PublishACK();
	
	delay(1);
}

void ESPMetRED::callback(char* topic, byte* payload, unsigned int length)
{	
	
//	Generating String from received payload	
	String message = String();
	for (int i = 0; i < length; i++) {
		char input_char = (char)payload[i];
		message += input_char;
	}
//	Converting String to JSON Array	
	char jsonChar[100];
	message.toCharArray(jsonChar, message.length()+1);
	StaticJsonBuffer<500> jsonBuffer;
	JsonObject& root = jsonBuffer.parseObject(jsonChar);
	String Topic = root["TOPIC"];
	
//	Reactions on received message
		
	if (Topic == "SYSTEM")
	{
		String Payload = root["PAYLOAD"];
		
		if (Payload == "INFO")
		{
			systemInfo();
		} 
		else if (Payload == "NTP")
		{
			unsigned long _NTP = root["NTP"];
			NTP = ((_NTP + 1000) - millis());
			_Sunrise = root["SUNRISE"];
			_Sunset = root["SUNSET"];
			ReturnACK(String(CLIENT_ID) + " [" + Payload + " OK]");
			WriteSPIFFS("Time", _Time);
		}
		else if (Payload == "OTA")
		{
			Publish("debug", String(CLIENT_ID) + " [" + Payload + " OK]");
			String Link = "/" + String(CLIENT_ID) + ".bin";
			ESPhttpUpdate.update(MQTT_SERVER, 82, Link);
		}
		else if (Payload == "REBOOT")
		{
			Publish("debug", String(CLIENT_ID) + " [" + Payload + " OK]");
			ESP.restart();
		}
	}
	
	else if (Topic == "GPIO")
	{
		int Pin = root["PIN"];
		int Value = root["VALUE"];
		setOverride(Pin, Value);
		WriteGPIO(Pin, Value);
	}
	
	else if (Topic == "OVERRIDE?")
	{
		int Pin = root["PIN"];
		Publish("debug", "OVERRIDE[" + String(gpio_override[Pin]) + "]");
	}
	else if (Topic == "GPIO?")
	{
		int Pin = root["PIN"];
		Publish("debug", "Pin[" + String(Pin) + " " + String(digitalRead(Pin)) + "]");
	}
	else if (Topic == "SPIFF")
	{
		String Object = root["OBJECT"];<commit_msg>OTA, directly from Arduino IDE<commit_after>/*
  ESPMetRED.cpp - A blend of ESP8266 MQTT and Node-Red.
  <NAME>
  http://espmetred.hobbytronics.com.pk
*/

#include <Arduino.h>
#include <ESPMetRED.h>

extern const char* WIFI_SSID;
extern const char* WIFI_PASSWORD;
extern const char* MQTT_SERVER;
extern const char* MQTT_USER;
extern const char* MQTT_PASSWORD;
extern const char* MQTT_PUBLISH_TOPIC;
extern const char* MQTT_SUBSCRIBE_TOPIC;
extern const char* CLIENT_ID;

WiFiClient _Client;
PubSubClient MQTTClient(_Client);

ESPMetRED::ESPMetRED()
{ 
	Serial.begin(115200);
	SPIFFS.begin();
	WiFi.mode(WIFI_STA);
	MQTTClient.setServer(MQTT_SERVER, 1883);
	MQTTClient.setCallback([this] (char* topic, byte* payload, unsigned int length) { this->callback(topic, payload, length); });
	Serial.println("ESP8266 started");
	NTP = ReadSPIFFS("Time");
	Serial.print("Time: ");
	Serial.println(NTP);
	
	ArduinoOTA.setHostname(CLIENT_ID);
	ArduinoOTA.setPassword((const char *)MQTT_PASSWORD);
}

void ESPMetRED::joinWiFi()
{
	boolean access_point_check = WiFiScanner();
	if ((access_point_check) && (WiFi.status() != WL_CONNECTED))
	{
		Serial.println("Connecting to WiFi Access Point");
		WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
	} else if ((access_point_check) && (WiFi.status() == WL_CONNECTED))
	{
		Serial.println("WiFi connected");
	}
}

boolean ESPMetRED::WiFiScanner()
{
	Serial.println("Scanning WiFi Network");
	int n = WiFi.scanNetworks();
	delay(300);
	for (int i = 0; i < n; ++i)
	{
		if (WiFi.SSID(i) == WIFI_SSID)
		{
			Serial.println("WiFi Network Available");
			return true;
		}
	}
	Serial.println("WiFi Network NOT Available");
	return false;
}

void ESPMetRED::joinMqTT()
{
	MQTTClient.connect(CLIENT_ID, MQTT_USER, MQTT_PASSWORD);
	
	if (MQTTClient.connected()) {
		MQTTClient.subscribe(MQTT_SUBSCRIBE_TOPIC);
		MQTTClient.subscribe("ntp/OUT");
		Publish("debug", String(CLIENT_ID) + " [LOGGED IN]");
		Publish("ntp/IN", JsonString(String(MQTT_SUBSCRIBE_TOPIC), ""));
	} else {
		Serial.print("Failed to connect to mqtt server, rc=");
		Serial.print(MQTTClient.state());
		Serial.println("");
	}
}

void ESPMetRED::keepalive()
{
	if (((millis() - connection_watchdog) > 12000UL) && (WiFi.status() != WL_CONNECTED))
	{
		connection_watchdog = millis();
		joinWiFi();
	} else if (((millis() - connection_watchdog) > 12000UL) && (WiFi.status() == WL_CONNECTED) && (!MQTTClient.connected()))
	{
		joinMqTT();
	}
	
	if(WiFi.status() == WL_CONNECTED)
	{
		if (!OTA_Begin)
		{
			OTA_Begin = true;
			ArduinoOTA.begin();
		}
		else
		{
			ArduinoOTA.handle();
		}
	}
	
	if ((millis() - Time_Log) > 300000UL)
	{
		Time_Log = millis();
		WriteSPIFFS("Time", _Time);
	}
	
	MQTTClient.loop();
	Timer();
	
	if(_Time > 86400000L)
	{
		NTP = (0 - (millis()));
		Timer();
	}
	
	PublishACK();
	
	delay(1);
}

void ESPMetRED::callback(char* topic, byte* payload, unsigned int length)
{	
	
//	Generating String from received payload	
	String message = String();
	for (int i = 0; i < length; i++) {
		char input_char = (char)payload[i];
		message += input_char;
	}
//	Converting String to JSON Array	
	char jsonChar[100];
	message.toCharArray(jsonChar, message.length()+1);
	StaticJsonBuffer<500> jsonBuffer;
	JsonObject& root = jsonBuffer.parseObject(jsonChar);
	String Topic = root["TOPIC"];
	
//	Reactions on received message
		
	if (Topic == "SYSTEM")
	{
		String Payload = root["PAYLOAD"];
		
		if (Payload == "INFO")
		{
			systemInfo();
		} 
		else if (Payload == "NTP")
		{
			unsigned long _NTP = root["NTP"];
			NTP = ((_NTP + 1000) - millis());
			_Sunrise = root["SUNRISE"];
			_Sunset = root["SUNSET"];
			ReturnACK(String(CLIENT_ID) + " [" + Payload + " OK]");
			WriteSPIFFS("Time", _Time);
		}
		// else if (Payload == "OTA")
		// {
			// Publish("debug", String(CLIENT_ID) + " [" + Payload + " OK]");
			// String Link = "/" + String(CLIENT_ID) + ".bin";
			// ESPhttpUpdate.update(MQTT_SERVER, 82, Link);
		// }
		else if (Payload == "REBOOT")
		{
			Publish("debug", String(CLIENT_ID) + " [" + Payload + " OK]");
			ESP.restart();
		}
	}
	
	else if (Topic == "GPIO")
	{
		int Pin = root["PIN"];
		int Value = root["VALUE"];
		setOverride(Pin, Value);
		WriteGPIO(Pin, Value);
	}
	
	else if (Topic == "OVERRIDE?")
	{
		int Pin = root["PIN"];
		Publish("debug", "OVERRIDE[" + String(gpio_override[Pin]) + "]");
	}
	else if (Topic == "GPIO?")
	{
		int Pin = root["PIN"];
		Publish("debug", "Pin[" + String(Pin) + " " + String(digitalRead(Pin)) + "]");
	}
	else if (Topic == "SPIFF")
	{
		String Object = root["OBJECT"];
{'fraction_non_alphanumeric': 0.17686609686609686, 'fraction_numerical': 0.014131054131054132, 'mean_word_length': 4.322013341419042, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3780413', 'n_tokens_mistral': 3759, 'n_tokens_neox': 3403, 'n_words': 688}