Skip to main content

Variables

You can use key-value storage to save some state for your automatisations and scrtips. Also it can be useful to communicate with Enapter Rules.

On previous step we set variable with name check_tutorial via the following command:

mosquitto_pub -r -p 9883 -h <GATEWAY_IP_ADDRESS> -u public -P public -t "variables/v1/set/check_tutorial"  -m '{"value": "i am fine"}'

Repeat it, if you skip this step.

Now you can read the value:

mosquitto_sub -C 1 -v -p 9883 -h <GATEWAY_IP_ADDRESS> -u public -P public -t "variables/v1/set/check_tutorial"

The output should be:

variables/v1/set/check_tutorial {"value": "i am fine"}

You can use above commands to read and write variables. If you want to go deeper and understand what is MQTT subscription and message retention read the rest of article.

Subscription and Retention

MQTT is a publish-subscribe protocol. It means that mosquitto_pub publishes messages to queue and mosquitto_sub subscribe to read them.

Another important peace is "topic". MQTT use different topics inside one queue to route messages. In our example we use variables/v1/set/check_tutorial topic.

On previous steps we publish message without any active subscriptions, but receive the message, when making subscription. It works because of Retention. If you publish with -r flag message will be retained to be available for next subscriptions. You can try repeat publish without retention to see difference (but don't forget change topic or value).

Also you can spot, that mosquitto_sub prints only one value and exit. But if you subscribe to something you should expect to get stream of messages. We use -C 1 option to read only one message and exit. It usefult to work with key-value storage. To work with telemtry and commands we will use endless streaming subscription.

Try to subscribe without -C 1:

mosquitto_sub -v -p 9883 -h <GATEWAY_IP_ADDRESS> -u public -P public -t "variables/v1/set/check_tutorial"

After that open another terminal and publish new value to see pub-sub works together:

mosquitto_pub -p 9883 -h <GATEWAY_IP_ADDRESS> -u public -P public -t "variables/v1/set/check_tutorial"  -m '{"value": "i am ok"}'
Hardware diversity is welcome. Integrate any device into a unified energy network.
© 2022 Enapter
Developer toolkit
DocumentationReference