当前位置: 首页>>代码示例>>Java>>正文


Java MqttMessage类代码示例

本文整理汇总了Java中org.eclipse.paho.client.mqttv3.MqttMessage的典型用法代码示例。如果您正苦于以下问题:Java MqttMessage类的具体用法?Java MqttMessage怎么用?Java MqttMessage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


MqttMessage类属于org.eclipse.paho.client.mqttv3包,在下文中一共展示了MqttMessage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: mqttCallback

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
protected void mqttCallback() {
    client.setCallback(new MqttCallback() {
        @Override
        public void connectionLost(Throwable cause) {
            msg("Connection lost...");
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            TextView tvMessage = (TextView) findViewById(R.id.tvMessage);
            tvMessage.setText(message.toString());
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    });
}
 
开发者ID:chooka888,项目名称:ConAir,代码行数:20,代码来源:ACController.java

示例2: messageArrived

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
  String payload = new String(message.getPayload());
  System.out.println("Red'c command:  " + payload);
  JsonObject jsonObject = parser.parse(payload).getAsJsonObject();
  String cmd = extractCommandData(jsonObject, CMD_KEY);
  switch (cmd) {
    case "ping":
      sendResponse(pingResponse(jsonObject));
      break;
    case "randnum":
      sendResponse(randResponse(jsonObject));
      break;
    default:
      sendResponse(payload);
  }
  msgRecd = true;
}
 
开发者ID:edgexfoundry,项目名称:device-mqtt,代码行数:19,代码来源:TestMqttDeviceCommandRec.java

示例3: onDeviceConnect

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
@Override
public MqttDeliveryFuture onDeviceConnect(final String deviceName, final String deviceType) {
    final int msgId = msgIdSeq.incrementAndGet();
    ObjectNode node = newNode().put("device", deviceName);
    if (!StringUtils.isEmpty(deviceType)) {
        node.put("type", deviceType);
    }
    MqttMessage msg = new MqttMessage(toBytes(node));
    msg.setId(msgId);
    log.info("[{}] Device Connected!", deviceName);
    devices.putIfAbsent(deviceName, new DeviceInfo(deviceName, deviceType));
    return publishAsync(GATEWAY_CONNECT_TOPIC, msg,
            token -> {
                log.info("[{}][{}] Device connect event is reported to Thingsboard!", deviceName, msgId);
            },
            error -> log.warn("[{}][{}] Failed to report device connection!", deviceName, msgId, error));
}
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:18,代码来源:MqttGatewayService.java

示例4: testMQtt

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
@Test
public void testMQtt() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    MqttClient client = new MqttClient("tcp://localhost:" + MQTT_PORT, MqttClient.generateClientId(), new MemoryPersistence());
    client.connect();
    MqttComponent mqtt = new MqttComponent();
    mqtt.client = client;
    Publisher<byte[]> fromTopic = mqtt.from("input", byte[].class);
    Subscriber<byte[]> toTopic = mqtt.to("output", byte[].class);
    Flux.from(fromTopic)
        .log()
        .subscribe(toTopic);
    
    client.subscribe("output", (topic, message) -> {
        result = new Integer(new String(message.getPayload()));
        latch.countDown();
    });
    client.publish("input", new MqttMessage(new Integer(2).toString().getBytes()));
    client.publish("input", new MqttMessage(new Integer(2).toString().getBytes()));
    latch.await(100, TimeUnit.SECONDS);
    Assert.assertEquals(2, result, 0.1);
    client.disconnect();
    client.close();
}
 
开发者ID:cschneider,项目名称:reactive-components,代码行数:25,代码来源:MqttTest.java

示例5: onDeviceAttributesUpdate

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
@Override
public MqttDeliveryFuture onDeviceAttributesUpdate(String deviceName, List<KvEntry> attributes) {
    final int msgId = msgIdSeq.incrementAndGet();
    log.trace("[{}][{}] Updating device attributes: {}", deviceName, msgId, attributes);
    checkDeviceConnected(deviceName);
    ObjectNode node = newNode();
    ObjectNode deviceNode = node.putObject(deviceName);
    attributes.forEach(kv -> putToNode(deviceNode, kv));
    final int packSize = attributes.size();
    MqttMessage msg = new MqttMessage(toBytes(node));
    msg.setId(msgId);
    return publishAsync(GATEWAY_ATTRIBUTES_TOPIC, msg,
            token -> {
                log.debug("[{}][{}] Device attributes were delivered!", deviceName, msgId);
                attributesCount.addAndGet(packSize);
            },
            error -> log.warn("[{}][{}] Failed to report device attributes!", deviceName, msgId, error));
}
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:19,代码来源:MqttGatewayService.java

示例6: onDeviceTelemetry

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
@Override
public MqttDeliveryFuture onDeviceTelemetry(String deviceName, List<TsKvEntry> telemetry) {
    final int msgId = msgIdSeq.incrementAndGet();
    log.trace("[{}][{}] Updating device telemetry: {}", deviceName, msgId, telemetry);
    checkDeviceConnected(deviceName);
    ObjectNode node = newNode();
    Map<Long, List<TsKvEntry>> tsMap = telemetry.stream().collect(Collectors.groupingBy(v -> v.getTs()));
    ArrayNode deviceNode = node.putArray(deviceName);
    tsMap.entrySet().forEach(kv -> {
        Long ts = kv.getKey();
        ObjectNode tsNode = deviceNode.addObject();
        tsNode.put("ts", ts);
        ObjectNode valuesNode = tsNode.putObject("values");
        kv.getValue().forEach(v -> putToNode(valuesNode, v));
    });
    final int packSize = telemetry.size();
    MqttMessage msg = new MqttMessage(toBytes(node));
    msg.setId(msgId);
    return publishAsync(GATEWAY_TELEMETRY_TOPIC, msg,
            token -> {
                log.debug("[{}][{}] Device telemetry published to Thingsboard!", msgId, deviceName);
                telemetryCount.addAndGet(packSize);
            },
            error -> log.warn("[{}][{}] Failed to publish device telemetry!", deviceName, msgId, error));
}
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:26,代码来源:MqttGatewayService.java

示例7: onDeviceAttributeRequest

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
@Override
public void onDeviceAttributeRequest(AttributeRequest request, Consumer<AttributeResponse> listener) {
    final int msgId = msgIdSeq.incrementAndGet();
    String deviceName = request.getDeviceName();
    AttributeRequestKey requestKey = new AttributeRequestKey(request.getRequestId(), request.getDeviceName());
    log.trace("[{}][{}] Requesting {} attribute: {}", deviceName, msgId, request.isClientScope() ? "client" : "shared", request.getAttributeKey());
    checkDeviceConnected(deviceName);

    ObjectNode node = newNode();
    node.put("id", request.getRequestId());
    node.put("client", request.isClientScope());
    node.put("device", request.getDeviceName());
    node.put("key", request.getAttributeKey());
    MqttMessage msg = new MqttMessage(toBytes(node));

    msg.setId(msgId);
    pendingAttrRequestsMap.put(requestKey, new AttributeRequestListener(request, listener));
    publishAsync(GATEWAY_REQUESTS_ATTRIBUTES_TOPIC, msg,
            token -> {
                log.debug("[{}][{}] Device attributes request was delivered!", deviceName, msgId);
            },
            error -> {
                log.warn("[{}][{}] Failed to report device attributes!", deviceName, msgId, error);
                pendingAttrRequestsMap.remove(requestKey);
            });
}
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:27,代码来源:MqttGatewayService.java

示例8: onDeviceRpcResponse

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
@Override
public void onDeviceRpcResponse(RpcCommandResponse response) {
    final int msgId = msgIdSeq.incrementAndGet();
    int requestId = response.getRequestId();
    String deviceName = response.getDeviceName();
    String data = response.getData();
    checkDeviceConnected(deviceName);

    ObjectNode node = newNode();
    node.put("id", requestId);
    node.put("device", deviceName);
    node.put("data", data);
    MqttMessage msg = new MqttMessage(toBytes(node));
    msg.setId(msgId);
    publishAsync(GATEWAY_RPC_TOPIC, msg,
            token -> {
                log.debug("[{}][{}] RPC response from device was delivered!", deviceName, requestId);
            },
            error -> {
                log.warn("[{}][{}] Failed to report RPC response from device!", deviceName, requestId, error);
            });
}
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:23,代码来源:MqttGatewayService.java

示例9: reportStats

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
private void reportStats() {
    if (tbClient == null) {
        log.info("Can't report stats because client was not initialized yet!");
        return;
    }
    ObjectNode node = newNode();
    node.put("ts", System.currentTimeMillis());
    ObjectNode valuesNode = node.putObject("values");

    valuesNode.put("devicesOnline", devices.size());
    valuesNode.put("attributesUploaded", attributesCount.getAndSet(0));
    valuesNode.put("telemetryUploaded", telemetryCount.getAndSet(0));
    if (error != null) {
        valuesNode.put("latestError", JsonTools.toString(error));
        error = null;
    }
    MqttMessage msg = new MqttMessage(toBytes(node));
    msg.setId(msgIdSeq.incrementAndGet());
    publishAsync(DEVICE_TELEMETRY_TOPIC, msg,
            token -> log.info("Gateway statistics {} reported!", node),
            error -> log.warn("Failed to report gateway statistics!", error));
}
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:23,代码来源:MqttGatewayService.java

示例10: onAttributesUpdate

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
private void onAttributesUpdate(MqttMessage message) {
    JsonNode payload = fromString(new String(message.getPayload(), StandardCharsets.UTF_8));
    String deviceName = payload.get("device").asText();
    Set<AttributesUpdateListener> listeners = attributeUpdateSubs.stream()
            .filter(sub -> sub.matches(deviceName)).map(sub -> sub.getListener())
            .collect(Collectors.toSet());
    if (!listeners.isEmpty()) {
        JsonNode data = payload.get("data");
        List<KvEntry> attributes = getKvEntries(data);
        listeners.forEach(listener -> callbackExecutor.submit(() -> {
            try {
                listener.onAttributesUpdated(deviceName, attributes);
            } catch (Exception e) {
                log.error("[{}] Failed to process attributes update", deviceName, e);
            }
        }));
    }
}
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:19,代码来源:MqttGatewayService.java

示例11: onRpcCommand

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
private void onRpcCommand(MqttMessage message) {
    JsonNode payload = fromString(new String(message.getPayload(), StandardCharsets.UTF_8));
    String deviceName = payload.get("device").asText();
    Set<RpcCommandListener> listeners = rpcCommandSubs.stream()
            .filter(sub -> sub.matches(deviceName)).map(RpcCommandSubscription::getListener)
            .collect(Collectors.toSet());
    if (!listeners.isEmpty()) {
        JsonNode data = payload.get("data");
        RpcCommandData rpcCommand = new RpcCommandData();
        rpcCommand.setRequestId(data.get("id").asInt());
        rpcCommand.setMethod(data.get("method").asText());
        rpcCommand.setParams(JsonTools.toString(data.get("params")));
        listeners.forEach(listener -> callbackExecutor.submit(() -> {
            try {
                listener.onRpcCommand(deviceName, rpcCommand);
            } catch (Exception e) {
                log.error("[{}][{}] Failed to process rpc command", deviceName, rpcCommand.getRequestId(), e);
            }
        }));
    } else {
        log.warn("No listener registered for RPC command to device {}!", deviceName);
    }
}
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:24,代码来源:MqttGatewayService.java

示例12: convert

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
@Override
public List<DeviceData> convert(String topic, MqttMessage msg) throws Exception {
    String data = new String(msg.getPayload(), StandardCharsets.UTF_8);
    log.trace("Parsing json message: {}", data);

    if (!filterExpression.isEmpty()) {
        try {
            log.debug("Data before filtering {}", data);
            DocumentContext document = JsonPath.parse(data);
            document = JsonPath.parse((Object) document.read(filterExpression));
            data = document.jsonString();
            log.debug("Data after filtering {}", data);
        } catch (RuntimeException e) {
            log.debug("Failed to apply filter expression: {}", filterExpression);
            throw new RuntimeException("Failed to apply filter expression " + filterExpression);
        }
    }

    JsonNode node = mapper.readTree(data);
    List<String> srcList;
    if (node.isArray()) {
        srcList = new ArrayList<>(node.size());
        for (int i = 0; i < node.size(); i++) {
            srcList.add(mapper.writeValueAsString(node.get(i)));
        }
    } else {
        srcList = Collections.singletonList(data);
    }

    return parse(topic, srcList);
}
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:32,代码来源:MqttJsonConverter.java

示例13: sendMessage

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
public synchronized boolean sendMessage(byte[] messagePayload) {
	logger.info("sending message");
	if (client != null) {
		try {
			MqttMessage message = new MqttMessage(messagePayload);
			message.setQos(qos);
			message.setRetained(false);
			client.publish(topic, message);
			return true;
		} catch (Exception e) {
			logger.error("Failed to send outbound message to topic:  " + topic + " - unexpected issue: " + new String(messagePayload));
			e.printStackTrace();
		}
	} else {
		logger.info("client is null");
	}
	return false;
}
 
开发者ID:edgexfoundry,项目名称:export-distro,代码行数:19,代码来源:IotCoreMQTTSender.java

示例14: sendMessage

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
public boolean sendMessage(byte[] messagePayload) {
	if (client != null) {
		try {
			MqttMessage message = new MqttMessage(messagePayload);
			message.setQos(qos);
			message.setRetained(false);
			client.publish(topic, message);
			return true;
		} catch (Exception e) {
			logger.error("Failed to send outbound message to topic:  " + topic + " - unexpected issue: "
					+ new String(messagePayload));
			e.printStackTrace();
		}
	}
	return false;
}
 
开发者ID:edgexfoundry,项目名称:export-distro,代码行数:17,代码来源:MQTTSender.java

示例15: convert

import org.eclipse.paho.client.mqttv3.MqttMessage; //导入依赖的package包/类
public AttributeRequest convert(String topic, MqttMessage msg) {
    deviceNameTopicPattern = checkAndCompile(deviceNameTopicPattern, deviceNameTopicExpression);
    attributeKeyTopicPattern = checkAndCompile(attributeKeyTopicPattern, attributeKeyTopicExpression);
    requestIdTopicPattern = checkAndCompile(requestIdTopicPattern, requestIdTopicExpression);

    String data = new String(msg.getPayload(), StandardCharsets.UTF_8);
    DocumentContext document = JsonPath.parse(data);

    AttributeRequest.AttributeRequestBuilder builder = AttributeRequest.builder();
    builder.deviceName(eval(topic, deviceNameTopicPattern, document, deviceNameJsonExpression));
    builder.attributeKey(eval(topic, attributeKeyTopicPattern, document, attributeKeyJsonExpression));
    builder.requestId(Integer.parseInt(eval(topic, requestIdTopicPattern, document, requestIdJsonExpression)));

    builder.clientScope(this.isClientScope());
    builder.topicExpression(this.getResponseTopicExpression());
    builder.valueExpression(this.getValueExpression());
    return builder.build();
}
 
开发者ID:thingsboard,项目名称:thingsboard-gateway,代码行数:19,代码来源:AttributeRequestsMapping.java


注:本文中的org.eclipse.paho.client.mqttv3.MqttMessage类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。