Utilize SmartHome.MqttService in AddOn


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"/>
      <provide interface="org.eclipse.smarthome.core.thing.binding.ThingHandlerFactory"/>
      <provide interface="org.osgi.service.cm.ManagedService" />
    <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"/>


In my implementation class:

public void updated(Dictionary<String, ?> properties) throws ConfigurationException {

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