當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。