Mosquitto in my brain

Hi everyone, I don’t like asking for help but I can’t understand why if I publish from the rasp2 terminal to HA:

‘mosquitto_pub -h 192.168.XXX.XXX -m “30” -t rasp2_temp’

everything goes great,

while with the following script (thanks pplucky):

#! / Bin / bash
PATH = / bin: / usr / bin

VALUE = $ (cat / sys / class / thermal / thermal_zone0 / temp | awk -v FS = “” ‘{print $ 1/1000 “”}’ | cut -c1-5)

if [["$ VALUE" == “”]]

curl -X POST
-H “Content-Type: application / json”
-H “x-ha-access: XXXXX”
-d ‘{“payload”: "’" $ VALUE “’”, “topic”: “rasp2_temp”, “retain”: “True”}’
http://192.168.XXX.XXX:1883/api/services/mqtt/publish> / dev / null 2> & 1 &

exit 0

the client isn’t recognized by the broker: “socket error on client unknown”.

I’m a beginner, I’m working, but I don’t understand: the client isn’t correct?
A little help, please … I’m in total confusion!

Can you explain why you are trying to send an MQTT message via HA?

If you want to send an MQTT message you could just use mosquitto_pub in your script, or alternatively you could use the api to update a sensor directly.

And can you format your code so its easy to read using the instructions in the blue box at the top of the page.

If you have all this spaces in your script, this will not work.

Here’s an example:

I’m sorry, I had problems with the pc … what a bad luck!


# Get CPU Temperature in degrees celsius
VALUE=$( cat /sys/class/thermal/thermal_zone0/temp | awk -v FS=" " '{print $1/1000""}' | cut -c1-5 )

if [[ "$VALUE" == "" ]]

curl -X POST \
     -H "Content-Type: application/json" \
     -H "x-ha-access: XXXXXXX" \
     -d '{"payload": "'"$VALUE"'", "topic": "rasp2_temp", "retain": "True"}' \
     http://192.168.XXX.XXX:1883/api/services/mqtt/publish > /dev/null 2>&1 &
exit 0

This doesn’t make sense.

You publish mqtt messages to a mqtt broker, and then HA would consume it. You don’t send HA an MQTT message and have it publish itself to consume itself. It doesn’t make any sense.

Either use mosquitto_pub in the script or update the sensor directly like @gpbenton mentioned.

As others have said, it seems like you’re over-complicating this unnecessarily.

You can easily update the sensor directly via HTTP POST with: /api/states/sensor.whatever

For the data use “state”:"$VALUE"

You’re right, but I would like to succeed with both methods: mosquitto is very fascinating! I’m trying to understand … but I’m very poor on the subject …

Then use mosquitto properly and in your script call mosquitto_pub. Stop trying to use HA incorrectly for that.

Maybe I understand … now I put into practice …


# Get CPU Temperature in degrees celsius
VALUE=$( cat /sys/class/thermal/thermal_zone0/temp | awk -v FS=" " '{print $1/1000""}' | cut -c1-5 )
if [[ "$VALUE" == "" ]]
/usr/bin/mosquitto_pub -r -t "$TOPIC" -m "$PAYLOAD" -h "$MQTT"

Thanks guys, I did it, but only thanks to you all … I have so much to learn!
But with your help everything is easier.