LDR mqtt payload not responding

Hi guys, I've been more of a python developer but i'm starting to learn the arduino.

I have a sketch that outputs the value of a light dependent resistor every second to a local mqtt server.
It should publish a payload to a topic when a set threshold is exceeded. The sketch appears to do just that.
But on the receiving end, i wrote a python script that should print a string upon receiving the payload from the client, but it doesn't. my conclusion is that the client does not properly publish the payload which should be "0". Kindly take a look at the sketch and see if it publishes correctly?

Here's my code

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
//  
#define lightsensor A0

// Update these with values suitable for your network.
const char* ssid = "<./>";//put your hotspot ssid here
const char* password = "pass";//put your hotspot password here
const char* mqtt_server = "192.168.50.20";//put your mqtt server address/url here


WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
int threhold=20; // you might need to adjust this value to define light on/off status
void setup_wifi() {
   delay(100);
  // We start by connecting to a WiFi network
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) 
    {
      delay(500);
      Serial.print(".");
    }
  randomSeed(micros());
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

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

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) 
  {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    //if you MQTT broker has clientID,username and password
    //please change following line to    if (client.connect(clientId,userName,passWord))
    if (client.connect(clientId.c_str()))
    {
      Serial.println("connected");
     //once connected to MQTT broker, subscribe command if any
      client.subscribe("laser");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 6 seconds before retrying
      delay(6000);
    }
  }
} //end reconnect()

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  long now = millis();
 //send data every second
  if (now - lastMsg > 500) {
     lastMsg = now;
    int val=analogRead(lightsensor);
     String msg="real time light strength: ";
     msg= msg+ val;
   if (val>threhold)
      msg="0: "+msg;
    else
      msg="1: "+msg;
     char message[58];
     msg.toCharArray(message,58);
     Serial.println(message);
  
     //publish sensor data to MQTT broker

      client.publish("laser", message);
  }
}

my conclusion is that the client does not properly publish the payload which should be "0".

No, the payload should be "0: real time light strength: 152" (or something similar, depending on the read value).

Post the Python script that is subscribing to this message!

What MQTT server are you running? Mosquitto?

I'm using paho mqtt. Here's the python script.

import paho.mqtt.client as mqtt
from subprocess import Popen
import os
import sys
import subprocess
import time

duration = 5  # second

sound1 = "/home/pi/auto_response/laser_alert.wav"
sound2 = "/home/pi/auto_response/online.wav"
sound3 = "/home/pi/auto_response/off.wav"


mqtt_topics = ["laser", "motion", "cam", "temp"] # Change to multiple topics that suits your needs. 
mqtt_broker_ip = "xxxxxxxxx" 
client = mqtt.Client() 


    # These functions handle what happens when the MQTT client connects
    # to the broker, and what happens then the topic receives a message

def on_connect(client, userdata, flags, rc):
    print "Connected!", str(rc)  # rc is the error code returned when connecting to the broker
    print_message()
    for topic in mqtt_topics:
        client.subscribe(topic) # Once the client has connected to the broker, subscribe to the topic
    # This function is called everytime the topic is published to.
    # If you want to check each message, and do something depending on
    # the content, the code to do this should be run in this function   

def on_message(client, userdata, msg):  
    if msg.payload == "1":
        os.system('play --no-show-progress %s --channels 2 synth %s' % (sound1, duration))
    elif msg.payload == "open":
        os.system('play --no-show-progress %s --channels 2 synth %s' % (sound1, duration))
    elif msg.payload == "on":
        os.system('play --no-show-progress %s --channels 2 synth %s' % (sound3, duration))
    print "Node: ", msg.topic + "\nMessage: " + str(msg.payload) 
    
# Here, we are telling the client which functions are to be run
# on connecting, and on receiving a message
client.on_connect = on_connect 
client.on_message = on_message 

# Once everything has been set up, we can (finally) connect to the broker
# 1883 is the listener port that the MQTT broker is using
client.connect(mqtt_broker_ip, 1883)

# Once we have told the client to connect, let the client object run itself
client.loop_forever()
client.disconnect()

I'm using paho mqtt.

I anticipated that for the Python library as I'm not aware of a different library for Python.

But what software do you use for the broker (server)?

Did you check that the sensor is working as expected?

Divide the problem into two parts.

MQTT servers are usually supplied with two utility programs that allow you to publish messages and subscribe to topics. In the case of the Mosquitto server they are called mosquitto_pub and mosquitto_sub.

Use the publish utility program to send a message. If your python program doesn't receive it then debug that first.

Use the subscription utility program to subscribe to topics and then send a message from the Arduino. If nothing is received then debug your Arduino program.

mikb55:
Divide the problem into two parts.

MQTT servers are usually supplied with two utility programs that allow you to publish messages and subscribe to topics. In the case of the Mosquitto server they are called mosquitto_pub and mosquitto_sub.

Use the publish utility program to send a message. If your python program doesn't receive it then debug that first.

Use the subscription utility program to subscribe to topics and then send a message from the Arduino. If nothing is received then debug your Arduino program.

The pub sub features works fine. And messages are coming through. But it seems the conditional if statement part fails.

netrosec:
The pub sub features works fine. And messages are coming through. But it seems the conditional if statement part fails.

Show the output from the mosquitto_sub utility program.

I wrote the problem you have to solve in my first answer:

pylon:
No, the payload should be "0: real time light strength: 152" (or something similar, depending on the read value).

If the payload is "1: real time light strength: 13" it will never match "1".