Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Oak MQTT test
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <string.h>
// Update with values suitable for your network.
const char* mqtt_server = "pine64";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
const byte ledPin = 1; // Pin with LED on Digistump Oak
long lastReconnectAttempt = 0;
void setup()
{
pinMode(ledPin, OUTPUT);
Particle.publish("MQTT ledStatus sketch starting...");
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
lastReconnectAttempt = 0;
}
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++)
{
char receivedChar = (char)payload[i];
Serial.print(receivedChar);
if (receivedChar == '0')
digitalWrite(ledPin, LOW);
if (receivedChar == '1')
digitalWrite(ledPin, HIGH);
}
Serial.println();
}
boolean reconnect()
{
if (client.connect("OAK"))
{
// Once connected, publish an announcement...
client.publish("outTopic/stat", "hello world");
// ... and resubscribe
client.subscribe("ledStatus");
}
return client.connected();
}
void loop()
{
long now = millis();
if (!client.connected())
{
if (now - lastReconnectAttempt > 5000)
{
lastReconnectAttempt = now;
// Attempt to reconnect
if (reconnect())
{
lastReconnectAttempt = 0;
}
}
}
else
{
client.loop();
}
delay(20);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.