Utilize SmartHome.MqttService in AddOn

Hi,

Is there any example how to use MqttService in OpenHAB2 AddOn development?

I am able to use Declarative Service to pass MqttService to my newly developed AddOn package. However, I am not able to publish any message. Here are some of the codes i use. After i register the producer, the senderChannel remains null, is this normal? Or i have to manually instantiante an MqttSenderChannel and push it to “publisher” before sending a message? Thanks

        //MqttMessagePublisher  is a new implementation class for MqttMessageProducer
        publisher = new MqttMessagePublisher(parentHandler.gatewayConfig.broker, deviceConfig.mqttTopic);
 
        mqttservice.registerMessageProducer(parentHandler.gatewayConfig.broker, publisher);
        publisher.publish(deviceConfig.mqttTopic, "test".getBytes());

[Update] Again, looks like i solved it faster than response :smile:

It turns out that I need to pass the .cfg configurations into MQTTService Declarative Service. For those that is interested (i am not sure whether this is a right approach, but it works) this is my XML file in OSGI-INF:

<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" immediate="true" name="org.openhab.binding.testmqtt.internal.TestMQTTHandlerFactory">

   <implementation class="org.openhab.binding.testmqtt.internal.TestMQTTHandlerFactory"/>
   <service>
      <provide interface="org.eclipse.smarthome.core.thing.binding.ThingHandlerFactory"/>
      <provide interface="org.osgi.service.cm.ManagedService" />
   </service>
    <property name="service.pid" type="String" value="org.openhab.testmqtt" />

  <reference bind="setMqttService" cardinality="1..1" 
        interface="org.eclipse.smarthome.io.transport.mqtt.MqttService" name="MqttService" 
        policy="static" unbind="unsetMqttService"/>

</scr:component>

In my implementation class:

@Override
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
this.mqttService.updated(properties);
}

As mentioned in Retrieve settings from /services/xxx.cfg, you should not use ManagedService, but rather have the configuration injected into the activate method.

Regards,
Kai