Community discussions

MikroTik App
 
User avatar
mrangics
just joined
Topic Author
Posts: 1
Joined: Wed Oct 11, 2023 6:30 pm
Contact:

Reading Modbus coils and registers

Mon Jan 29, 2024 7:23 pm

Hi,

I'm trying to create a script reading Modbus coils and registers with the new command, transceive and publish it with MQTT to a broker.
In the Terminal, the values return as expected using the transceive command, but cannot publish it with MQTT.

This is the line I use for the ModBus query:
:local modbus ([/iot modbus transceive address=1 function=3 data=00090010]->"values")
Then publish this with MQTT:
:local message "{$[:tostr $modbus]}"
/iot mqtt publish broker=$broker topic=$topic message="{\"Values\":\"$message\"}"
This produces an empty string.
Is there an option to get the values from the ModBus qurery? (The "old" read holding registers is not an option, because I must use other than 3 codes also.)

Thank you!
Last edited by mrangics on Mon Jan 29, 2024 10:32 pm, edited 1 time in total.
 
User avatar
DenSyo77
just joined
Posts: 24
Joined: Tue Jan 09, 2024 10:38 am
Contact:

Re: Reading Modbus coils and registers

Tue Jan 30, 2024 11:31 am

Forgot about as-value
:local modbus ([/iot modbus transceive address=1 function=3 data=00090010 as-value]->"values")

When the RS485 device is unavailable, the script will throw error, so make a modbus request with error handling
:local modbus
:local message
:do { :set modbus [/iot modbus transceive address=3 function=3 data=00090010 as-value] } on-error={}
:if ([:typeof $modbus] != "nothing") do={
  :set message "\"{$[:tostr ($modbus->"values")]}\""
} else={
  :set message "null"
}
:do={ /iot mqtt publish broker=$broker topic=$topic message="{\"Values\":$message}" } on-error={}

I don’t know whether it is necessary to send a message to the broker in the error handler, check the script with the broker-server turned off. Also check how to send a message to the broker with missing parameters, null with or without quotes, or some other way.

Who is online

Users browsing this forum: GoogleOther [Bot], Nullcaller and 6 guests