have to reload Sketch every time I start Yun

Hi Developers,

I am new to Arduino and IoT. Got my hands on Yun and loaded a simple Sketch to subscribe to a topic. I am receiving messages (have setup a PHP script and broker on server which takes care of the messages) and can turn ON and OFF LED, L13. But when I disconnect the Yun from my PC and connect it again (to power it up), it stops receiving messages. I have to load the Sketch again to make it work. Here is my code,

#include <spi.h>
#include <pubsubclient.h>
#include <yunclient.h>

byte server[] = { 192, 168, 1, 196 };
int port = 1883;
char* pubTopic = "fromYun";
char* subTopic = "sensor/light";

void callback(char* topic, byte* payload, unsigned int length)
{
//convert byte to char
payload[length] = '\0';
String strPayload = String((char*)payload);
// Serial.println(topic); Serial.println(strPayload);

// handle message arrived
if(strPayload == "ON")
{
digitalWrite(13, HIGH);
}
else if(strPayload == "OFF")
{
digitalWrite(13, LOW);
}
else{}
}

YunClient yun;
PubSubClient mqtt(server, port, callback, yun);

void setup()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
digitalWrite(13, LOW);

Bridge.begin();
if (mqtt.connect("arduinoClient"))
{
mqtt.publish(pubTopic,"hello world!");
mqtt.subscribe(subTopic);
}
}

void loop()
{
mqtt.loop();
}

I am using Mosquitto MQTT. Am I missing something?

I referred this post and PubSubClient → mqtt_basic.ino for making this Sketch. I don’t understand why is mqtt.connect(“arduinoClient”). I mean, why is this string “arduinoClient”? In one INO on GitHub I saw it as “yun”…

Any help is much appreciated.

Thanks in advance!

Plan B:

MQTT Broker(Server) on Arduino YUN

Confirm yun is connected to pc mqtt server

Python code for mqtt client

The key concept:

  • Loose couple programing, Python could run or debug independently
  • Scale up programing, move as much processing to faster CPU
  • Loose couple communicating, Python send to local mqtt server, then config local mqtt server forward to remote mqtt server to support Loose couple communicating. The link between local and remote could be loose.