Rover


#include <WiFi.h>

#include <PubSubClient.h>

// Connection info.

const char* ssid = "hobye";

const char* password = "XXXX";

const char* mqttServer = "mqtt.pndsn.com";

const int mqttPort = 1883;

const char* clientID = "pub-c-ce059109-494f-44d5-9567-1b9f275d9f88/sub-c-9844966a-2c1c-11ec-b636-021bdbd01fcd/CLIENT_ID";

const char* channelName = "channel1";

WiFiClient MQTTclient;

PubSubClient client(MQTTclient);

void callback(char* topic, byte* payload, unsigned int length) {

String payload_buff;

for (int i=0;i<length;i++) {

payload_buff = payload_buff+String((char)payload[i]);

}

Serial.println(payload_buff); // Print out messages.

}

long lastReconnectAttempt = 0;

boolean reconnect() {

if (client.connect(clientID)) {

client.subscribe(channelName); // Subscribe to channel.

}

return client.connected();

}

void setup() {

Serial.begin(9600);

Serial.println("Attempting to connect...");

WiFi.begin(ssid, password); // Connect to WiFi.

if(WiFi.waitForConnectResult() != WL_CONNECTED) {

Serial.println("Couldn't connect to WiFi.");

while(1) delay(100);

}

client.setServer(mqttServer, mqttPort); // Connect to PubNub.

client.setCallback(callback);

lastReconnectAttempt = 0;

}

void loop() {

if (!client.connected()) {

long now = millis();

if (now - lastReconnectAttempt > 5000) { // Try to reconnect.

lastReconnectAttempt = now;

if (reconnect()) { // Attempt to reconnect.

lastReconnectAttempt = 0;

}

}

} else { // Connected.

client.loop();

client.publish(channelName,"Hello world!"); // Publish message.

delay(5000);

}

}