Build and send JSON via MQTT

Hi all, pretty new to OpenHAB.
My implementation uses JSON structures to communicate via an MQTT broker (mosquitto).
I can send a JSON structure from my device to OpenHAB and extract the JSON using the jsonpath transform. What I can’t manage to do is populate a JSON structure to be sent via MQTT to my device to control it.

Example: I want to switch on a switch implemented on some hardware using the topic “controller-out/5/cmd/” and as message body the JSON string:
{“port”:0, // This indicates on the receiver which “relay” to target. So for each item it will be a unique number.
“cmd”:1, // This indicates to my controller that it is a command not a status update or internal message
"type":0, // This indicates the type of switch/device being targeted, not important
"value":0} // This is the physical command. In this case 0 is ON and 1 is OFF

I have several items defined in a group:

Group gCliviaIrrigation      "Clivia irrigation zones"  <rain>
Switch Switch_Zone1      "Irrigation Zone1"     <water>    (gCliviaIrrigation) { mqtt=">[mosquitto:controller-out/5/cmd/:command:*:xxxxx]" }   
Switch Switch_Zone2      "Irrigation Zone2"     <water>    (gCliviaIrrigation) { mqtt=">[mosquitto:controller-out/5/cmd/:command:*:xxxxx]" }   
Switch Switch_Zone3      "Irrigation Zone3"     <water>    (gCliviaIrrigation) { mqtt=">[mosquitto:controller-out/5/cmd/:command:*:xxxxx]" }   
Switch Switch_Zone4      "Irrigation Zone4"     <water>    (gCliviaIrrigation) { mqtt=">[mosquitto:controller-out/5/cmd/:command:*:xxxxx]" }   
Switch Switch_Zone5      "Irrigation Zone5"     <water>    (gCliviaIrrigation) { mqtt=">[mosquitto:controller-out/5/cmd/:command:*:xxxxx]" }   
Switch Switch_Zone6      "Irrigation Zone6"     <water>    (gCliviaIrrigation) { mqtt=">[mosquitto:controller-out/5/cmd/:command:*:xxxxx]" }

So there are two problems really. The first is to set the “port” in the JSON to a unique number that gets derived from the switch being toggled. The second problem is compiling the JSON structure oand getting MQTT to send it. I have looked at having a rule to trigger but I have no idea how to “pass” data. I am struggling not to think in C !

1 Like

Similar problem here, trying to send JSON through MQTT.

Found the solution! double backslash ("\") escapes the colon!

Hello dear, can you please give me an example how to send and receive json format over mqtt because I can’t understand the way :frowning:

With node red I did it and working but I can’t with openhab

Thank you in advance

Best regards
Tasos

Γειά σου Τάσο!

there are many examples in the forum:
Send: [SOLVED] Send json with mqtt command
Receive: Problem with MQTT - How to configure the item?

1 Like

Γεία σου καλέ μου φίλε Άγγελε ! ! !

Είσαι φοβερός ! ! !

Με έσωσες ! ! !

You Are Perfect ! ! !

You safe me a lot ! ! !

Thank you very much ! ! !

1 Like