Created
July 4, 2016 08:26
-
-
Save pfeerick/66ae60399e8074e04d02b9f5d9f9dd40 to your computer and use it in GitHub Desktop.
Oak MQTT test
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
#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