Generate node id when request come from MQTT broker

I want to generate dynamic node id in openHAB2.x when request come from mosquitto broker with some topic, it has to persist that id as well as gateway with same topic. If anyone knows pls give the documentation.

You have provided far to few details to even begin to help. My first reaction is “you are trying to do what? Are you sure you understand what OH is designed to do?”

Beyond the initial impression that you are potentially trying to do something with OH that it isn’t designed to do, all I can recommend is you will need to write a bunch of rules.

In my project sensor will request to gate-way to generate ID for that sensor, from gateway openHAB has to receive that request for generating ID to that sensor through MQTT protocol. so, generating ID in openHAB has to assign to that sensor through MQTT broker.

sensor---->gateway---->MQTT---->openHAB(ID has to generate here)—>MQTT---->gateway—>sensor(ID has to assigned here)

MySensors.

As far as im aware you cannot using MQTT gateway. I just assign the nodeid in each sensor.
@lakshmipathi256 - You could try to write this function.

OK, this is doable but it is probably more appropriate for some other server outside of OH to do it for you (e.g. python script with a database). This is not the sort of problem that OH was designed to solve and keeping a running list of all currently assigned IDs will be challenging.

The ID needs to be unique, but are there any other requirements? For example, do they need to be sequential, a certain number of digits long, random, etc?

That will drive how this would work.

If I assume that the IDs need merely be sequential and you do not have to keep track of already assigned IDs you can do something like the following:

Prerequisites:

  • MQTT binding and MQTT Action installed
  • Persistence set up and CurrNodeID (see below) persisted with restoreOnStartup

Items:

String RequestID { mqtt="<[config]" } // config to subscribe to request for ID topic, message is the topic to publish the new ID to
Number CurrNodeID

Rules:

import java.util.concurrent.locks.ReentrantLock

val ReentrantLock idLock = new ReentrantLock()

rule "Next ID was requested"
when
    Item RequestID received command
then
    idLock.lock
    try {
        val nextId = (CurrNodeID.state as Number) + 1
        CurrNodeID.postUpdate(nextId)

        publish("brokername", receivedCommand, nextId.toString)
    }
    catch(Exception e){
        logError("ID", "Error calculating next Node ID: " + e.toString)
    }
    finally {
        idLock.unlock
    }
end

If you need more than sequential IDs and/or need to guarantee the nodes are unique, OH is not the best place to implement this.

Usual warning, I just typed in the above, there are likely errors.

1 Like

Thank you