#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define RELAY 0 // relay connected to GPIO0
const char* ssid = "NAZWA_SIECI";
const char* password = "HASLO_SIECI";
const char* mqttServer = "10.0.0.138"; //IP SERVERA MQTT
const int mqttPort = 1883; //PORT SERVERA MQTT
const char* mqttUser = "USER"; //LOGIN SERVERA MQTT
const char* mqttPassword = "PASSWORD"; //HASLO SERVERA MQTT
const char* device_name = "Test Switch";
//TOPICS
const char* main_topic = "switches/bench/main";
const char* temp_topic = "sensors/bench/temperature";
void callback(char* topic, byte* payload, unsigned int length);
uint counter = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void setup()
{
pinMode(RELAY, OUTPUT);
Serial.begin(9600);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
WiFi.hostname(device_name);
// Serial.println("Connected");
delay(500);
}
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected())
{
if (client.connect(device_name , mqttUser, mqttPassword))
{
}
else
{
delay(2000);
}
}
client.publish(main_topic, "0");
client.publish(temp_topic, "40");
client.subscribe(main_topic);
}
void loop()
{
if(client.connected())
{
client.loop();
//simulate temperatures
counter++;
if(counter >= 1000000)
{
int temp = (rand() % 40 + 1);
client.publish(temp_topic, String(temp).c_str(), true);
Serial.println(temp);
counter = 0;
}
}
else
{
client.connect(device_name , mqttUser, mqttPassword);
}
}
void callback(char* topic, byte* payload, unsigned int length)
{
String message = "";
for (uint i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.println(message);
if(message == "1")
{
digitalWrite(RELAY, HIGH);
}
else
{
digitalWrite(RELAY, LOW);
}
}
{"html5":"htmlmixed","css":"css","javascript":"javascript","php":"php","python":"python","ruby":"ruby","lua":"text\/x-lua","bash":"text\/x-sh","go":"go","c":"text\/x-csrc","cpp":"text\/x-c++src","diff":"diff","latex":"stex","sql":"sql","xml":"xml","apl":"apl","asterisk":"asterisk","c_loadrunner":"text\/x-csrc","c_mac":"text\/x-csrc","coffeescript":"text\/x-coffeescript","csharp":"text\/x-csharp","d":"d","ecmascript":"javascript","erlang":"erlang","groovy":"text\/x-groovy","haskell":"text\/x-haskell","haxe":"text\/x-haxe","html4strict":"htmlmixed","java":"text\/x-java","java5":"text\/x-java","jquery":"javascript","mirc":"mirc","mysql":"sql","ocaml":"text\/x-ocaml","pascal":"text\/x-pascal","perl":"perl","perl6":"perl","plsql":"sql","properties":"text\/x-properties","q":"text\/x-q","scala":"scala","scheme":"text\/x-scheme","tcl":"text\/x-tcl","vb":"text\/x-vb","verilog":"text\/x-verilog","yaml":"text\/x-yaml","z80":"text\/x-z80"}