Search in sources :

Example 1 with MqttActionPayload

use of org.thingsboard.server.extensions.mqtt.action.MqttActionPayload in project thingsboard by thingsboard.

the class MqttMsgHandler method process.

@Override
public void process(PluginContext ctx, TenantId tenantId, RuleId ruleId, RuleToPluginMsg<?> msg) throws RuleException {
    if (!(msg instanceof MqttActionMsg)) {
        throw new RuleException("Unsupported message type " + msg.getClass().getName() + "!");
    }
    MqttActionPayload payload = ((MqttActionMsg) msg).getPayload();
    MqttMessage mqttMsg = new MqttMessage(payload.getMsgBody().getBytes(StandardCharsets.UTF_8));
    try {
        mqttClient.publish(payload.getTopic(), mqttMsg, null, new IMqttActionListener() {

            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                log.debug("Message [{}] was successfully delivered to topic [{}]!", msg.toString(), payload.getTopic());
                if (payload.isSync()) {
                    ctx.reply(new ResponsePluginToRuleMsg(msg.getUid(), tenantId, ruleId, BasicStatusCodeResponse.onSuccess(payload.getMsgType(), payload.getRequestId())));
                }
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable e) {
                log.warn("Failed to deliver message [{}] to topic [{}]!", msg.toString(), payload.getTopic());
                if (payload.isSync()) {
                    ctx.reply(new ResponsePluginToRuleMsg(msg.getUid(), tenantId, ruleId, BasicStatusCodeResponse.onError(payload.getMsgType(), payload.getRequestId(), new Exception(e))));
                }
            }
        });
    } catch (MqttException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
Also used : MqttActionPayload(org.thingsboard.server.extensions.mqtt.action.MqttActionPayload) MqttActionMsg(org.thingsboard.server.extensions.mqtt.action.MqttActionMsg) ResponsePluginToRuleMsg(org.thingsboard.server.extensions.api.plugins.msg.ResponsePluginToRuleMsg) RuleException(org.thingsboard.server.extensions.api.rules.RuleException) RuleException(org.thingsboard.server.extensions.api.rules.RuleException)

Aggregations

ResponsePluginToRuleMsg (org.thingsboard.server.extensions.api.plugins.msg.ResponsePluginToRuleMsg)1 RuleException (org.thingsboard.server.extensions.api.rules.RuleException)1 MqttActionMsg (org.thingsboard.server.extensions.mqtt.action.MqttActionMsg)1 MqttActionPayload (org.thingsboard.server.extensions.mqtt.action.MqttActionPayload)1