io.netty.handler.codec.mqtt.MqttMessage Java Examples
The following examples show how to use
io.netty.handler.codec.mqtt.MqttMessage.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MqttServerChannelHandler.java From spring-boot-protocol with Apache License 2.0 | 6 votes |
@Override public void onMessageReceived(ChannelHandlerContext ctx, MqttMessage msg) throws Exception { if (msg.fixedHeader() == null) { throw new IOException("Unknown packet"); } MqttConnection mqttConnection = mqttConnection(ctx.channel()); mqttConnection.setAuthFlushed(ctx.pipeline().context(MqttAutoFlushChannelHandler.class) != null); try { mqttConnection.handleMessage(msg); } catch (Throwable ex) { //ctx.fireExceptionCaught(ex); logger.error("Error processing protocol message: "+ msg.fixedHeader().messageType(), ex); ctx.channel().close().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { logger.info("Closed client channel due to exception in processing"); } }); } }
Example #2
Source File: SubscribeProcessor.java From jmqtt with Apache License 2.0 | 6 votes |
@Override public void processRequest(ChannelHandlerContext ctx, MqttMessage mqttMessage) { MqttSubscribeMessage subscribeMessage = (MqttSubscribeMessage) mqttMessage; String clientId = NettyUtil.getClientId(ctx.channel()); int messageId = subscribeMessage.variableHeader().messageId(); ClientSession clientSession = ConnectManager.getInstance().getClient(clientId); List<Topic> validTopicList =validTopics(clientSession,subscribeMessage.payload().topicSubscriptions()); if(validTopicList == null || validTopicList.size() == 0){ log.warn("[Subscribe] -> Valid all subscribe topic failure,clientId:{}",clientId); return; } List<Integer> ackQos = getTopicQos(validTopicList); MqttMessage subAckMessage = MessageUtil.getSubAckMessage(messageId,ackQos); ctx.writeAndFlush(subAckMessage); // send retain messages List<Message> retainMessages = subscribe(clientSession,validTopicList); dispatcherRetainMessage(clientSession,retainMessages); }
Example #3
Source File: PubRelReceiver.java From lannister with Apache License 2.0 | 6 votes |
protected void handle(ChannelHandlerContext ctx, Session session, int messageId) { // TODO what if the PUBREL is resented one? Topic topic = Topic.NEXUS.get(session.clientId(), messageId, ClientType.PUBLISHER); if (topic == null) { logger.error("PUBREL target does not exist [clientId={}, messageId={}]", session.clientId(), messageId); session.dispose(true); // [MQTT-3.3.5-2] return; } MqttMessage toSend = MqttMessageFactory.pubcomp(messageId); final String log = toSend.toString(); session.send(toSend, f -> { if (!f.isSuccess()) { logger.error("packet outgoing failed [{}] {}", log, f.cause()); return; } InboundMessageStatus.NEXUS.removeByKey(messageId, session.clientId()); logger.debug("Inbound message status REMOVED [clientId={}, messageId={}]", session.clientId(), messageId); }); }
Example #4
Source File: UnSubscribe.java From WeEvent with Apache License 2.0 | 6 votes |
@Override public Optional<MqttMessage> process(MqttMessage req, String clientId, String remoteIp) { MqttUnsubscribeMessage msg = (MqttUnsubscribeMessage) req; log.info("UNSUBSCRIBE, {}", msg.payload().topics()); if (msg.payload().topics().isEmpty()) { log.error("empty topic, skip it"); return Optional.empty(); } this.sessionStore.unSubscribe(clientId, msg.payload().topics()); MqttMessage rsp = MqttMessageFactory.newMessage(new MqttFixedHeader(MqttMessageType.UNSUBACK, false, MqttQoS.AT_LEAST_ONCE, false, ProtocolProcess.fixLengthOfMessageId), MqttMessageIdVariableHeader.from(msg.variableHeader().messageId()), null); return Optional.of(rsp); }
Example #5
Source File: UnSubscribeProcessor.java From iot-mqtt with Apache License 2.0 | 6 votes |
@Override public void processRequest(ChannelHandlerContext ctx, MqttMessage mqttMessage) { MqttUnsubscribeMessage unsubscribeMessage = (MqttUnsubscribeMessage) mqttMessage; MqttUnsubscribePayload unsubscribePayload = unsubscribeMessage.payload(); List<String> topics = unsubscribePayload.topics(); String clientId = NettyUtil.getClientId(ctx.channel()); ClientSession clientSession = ConnectManager.getInstance().getClient(clientId); if(Objects.isNull(clientSession)){ log.warn("[UnSubscribe] -> The client is not online.clientId={}",clientId); } topics.forEach( topic -> { subscriptionMatcher.unSubscribe(topic,clientId); subscriptionStore.removeSubscription(clientId,topic); //停止发送系统信息 if(SysToipc.SYS.equals(topic)) { sysMessageService.removeClient(clientSession.getClientId()); } }); MqttUnsubAckMessage unsubAckMessage = MessageUtil.getUnSubAckMessage(MessageUtil.getMessageId(mqttMessage)); ctx.writeAndFlush(unsubAckMessage); }
Example #6
Source File: JsonMqttAdaptor.java From IOT-Technical-Guide with Apache License 2.0 | 6 votes |
public static void convertToMsg(SessionMsgType type, MqttMessage inbound) throws AdaptorException { switch (type) { case POST_TELEMETRY_REQUEST: convertToTelemetryUploadRequest( (MqttPublishMessage) inbound); break; case POST_ATTRIBUTES_REQUEST: convertToUpdateAttributesRequest((MqttPublishMessage) inbound); break; case SUBSCRIBE_ATTRIBUTES_REQUEST: System.out.println("{\"key1\":\"value1\"}"); break; case GET_ATTRIBUTES_REQUEST: convertToGetAttributesRequest((MqttPublishMessage) inbound); break; } }
Example #7
Source File: JsonMqttAdaptor.java From IOT-Technical-Guide with Apache License 2.0 | 6 votes |
public static void convertToMsg(SessionMsgType type, MqttMessage inbound) throws AdaptorException { switch (type) { case POST_TELEMETRY_REQUEST: convertToTelemetryUploadRequest( (MqttPublishMessage) inbound); break; case POST_ATTRIBUTES_REQUEST: convertToUpdateAttributesRequest((MqttPublishMessage) inbound); break; case SUBSCRIBE_ATTRIBUTES_REQUEST: System.out.println("{\"key1\":\"value1\"}"); break; case GET_ATTRIBUTES_REQUEST: convertToGetAttributesRequest((MqttPublishMessage) inbound); break; } }
Example #8
Source File: Publish.java From WeEvent with Apache License 2.0 | 6 votes |
@Override public Optional<MqttMessage> process(MqttMessage req, String clientId, String remoteIp) throws BrokerException { MqttPublishMessage msg = (MqttPublishMessage) req; log.info("PUBLISH, {} Qos: {}", msg.variableHeader().topicName(), msg.fixedHeader().qosLevel()); switch (msg.fixedHeader().qosLevel()) { case AT_MOST_ONCE: { this.sessionStore.publishMessage(msg, false); return Optional.empty(); } case AT_LEAST_ONCE: { boolean result = this.sessionStore.publishMessage(msg, false); MqttQoS qos = result ? MqttQoS.AT_LEAST_ONCE : MqttQoS.FAILURE; MqttMessage rsp = MqttMessageFactory.newMessage(new MqttFixedHeader(MqttMessageType.PUBACK, false, qos, false, ProtocolProcess.fixLengthOfMessageId), MqttMessageIdVariableHeader.from(msg.variableHeader().packetId()), null); return Optional.of(rsp); } case EXACTLY_ONCE: default: { log.error("DOT NOT support Qos=2, close"); throw new BrokerException(ErrorCode.MQTT_NOT_SUPPORT_QOS2); } } }
Example #9
Source File: MqttPingHandler.java From smartacus-mqtt-broker with Apache License 2.0 | 6 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof MqttMessage)) { System.out.println("=============收到非Mqtt==========="); ctx.fireChannelRead(msg); ctx.close(); return; } MqttMessage message = (MqttMessage) msg; if(message.fixedHeader().messageType() == MqttMessageType.PINGREQ){ System.out.println("===========服务端收到了ping请求=========="); this.handlePingReq(ctx.channel()); } else if(message.fixedHeader().messageType() == MqttMessageType.PINGRESP){ System.out.println("===========服务端收到了ping响应=========="); this.handlePingResp(); }else{ ctx.fireChannelRead(ReferenceCountUtil.retain(msg)); } }
Example #10
Source File: PubRelProcessor.java From iot-mqtt with Apache License 2.0 | 6 votes |
@Override public void processRequest(ChannelHandlerContext ctx, MqttMessage mqttMessage) { String clientId = NettyUtil.getClientId(ctx.channel()); int messageId = MessageUtil.getMessageId(mqttMessage); if(ConnectManager.getInstance().containClient(clientId)){ Message message = flowMessageStore.releaseRecMsg(clientId,messageId); if(Objects.nonNull(message)){ super.processMessage(message); }else{ log.warn("[PubRelMessage] -> the message is not exist,clientId={},messageId={}.",clientId,messageId); } MqttMessage pubComMessage = MessageUtil.getPubComMessage(messageId); ctx.writeAndFlush(pubComMessage); }else{ log.warn("[PubRelMessage] -> the client:{} disconnect to this server.",clientId); NettyUtil.closeChannel(ctx.channel()); } }
Example #11
Source File: SubscribeProcessor.java From iot-mqtt with Apache License 2.0 | 6 votes |
@Override public void processRequest(ChannelHandlerContext ctx, MqttMessage mqttMessage) { MqttSubscribeMessage subscribeMessage = (MqttSubscribeMessage) mqttMessage; String clientId = NettyUtil.getClientId(ctx.channel()); int messageId = subscribeMessage.variableHeader().messageId(); ClientSession clientSession = ConnectManager.getInstance().getClient(clientId); List<Topic> validTopicList =validTopics(clientSession,subscribeMessage.payload().topicSubscriptions()); if(validTopicList == null || validTopicList.size() == 0){ log.warn("[Subscribe] -> Valid all subscribe topic failure,clientId:{}",clientId); return; } List<Integer> ackQos = getTopicQos(validTopicList); MqttMessage subAckMessage = MessageUtil.getSubAckMessage(messageId,ackQos); ctx.writeAndFlush(subAckMessage); // send retain messages List<Message> retainMessages = subscribe(clientSession,validTopicList); dispatcherRetainMessage(clientSession,retainMessages); }
Example #12
Source File: UnSubscribeProcessor.java From jmqtt with Apache License 2.0 | 6 votes |
@Override public void processRequest(ChannelHandlerContext ctx, MqttMessage mqttMessage) { MqttUnsubscribeMessage unsubscribeMessage = (MqttUnsubscribeMessage) mqttMessage; MqttUnsubscribePayload unsubscribePayload = unsubscribeMessage.payload(); List<String> topics = unsubscribePayload.topics(); String clientId = NettyUtil.getClientId(ctx.channel()); ClientSession clientSession = ConnectManager.getInstance().getClient(clientId); if(Objects.isNull(clientSession)){ log.warn("[UnSubscribe] -> The client is not online.clientId={}",clientId); } topics.forEach( topic -> { subscriptionMatcher.unSubscribe(topic,clientId); subscriptionStore.removeSubscription(clientId,topic); }); MqttUnsubAckMessage unsubAckMessage = MessageUtil.getUnSubAckMessage(MessageUtil.getMessageId(mqttMessage)); ctx.writeAndFlush(unsubAckMessage); }
Example #13
Source File: MqttCommandInvocation.java From joyqueue with Apache License 2.0 | 6 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { if (ctx.channel().isActive()) { if (msg instanceof MqttMessage) { MqttMessage message = (MqttMessage) msg; if (message.decoderResult().isSuccess()) { Handler handler = mqttHandlerDispatcher.getHandler(message.fixedHeader().messageType()); HandlerExecutor executor = new HandlerExecutor(handler, ctx, message); if (handler instanceof ExecutorsProvider) { ((ExecutorsProvider) handler).getExecutorService().submit(executor); } else { executor.execute(); } } } } else { LOG.error("The channel is not active!" + ctx.channel()); } } catch (Throwable th) { LOG.error("MqttCommandInvocation got exception: ", th); ctx.fireExceptionCaught(th); } }
Example #14
Source File: MQTTProtocolHandler.java From activemq-artemis with Apache License 2.0 | 5 votes |
private void sendToClient(MqttMessage message) { if (this.protocolManager.invokeOutgoing(message, connection) != null) { return; } MQTTUtil.logMessage(session.getSessionState(), message, false); ctx.write(message); ctx.flush(); }
Example #15
Source File: MQTTTestSupport.java From activemq-artemis with Apache License 2.0 | 5 votes |
@Override public boolean intercept(MqttMessage packet, RemotingConnection connection) throws ActiveMQException { if (packet.getClass() == MqttPublishMessage.class) { messageCount++; } return true; }
Example #16
Source File: MqttServerBadClientTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
private MqttMessage createConnectPacket(MqttClientOptions options) { MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttConnectVariableHeader variableHeader = new MqttConnectVariableHeader( PROTOCOL_NAME, PROTOCOL_VERSION, options.hasUsername(), options.hasPassword(), options.isWillRetain(), options.getWillQoS(), options.isWillFlag(), options.isCleanSession(), options.getKeepAliveTimeSeconds() ); MqttConnectPayload payload = new MqttConnectPayload( options.getClientId() == null ? "" : options.getClientId(), options.getWillTopic(), options.getWillMessage() != null ? options.getWillMessage().getBytes(StandardCharsets.UTF_8) : null, options.hasUsername() ? options.getUsername() : null, options.hasPassword() ? options.getPassword().getBytes(StandardCharsets.UTF_8) : null ); return MqttMessageFactory.newMessage(fixedHeader, variableHeader, payload); }
Example #17
Source File: PublishProcessor.java From iot-mqtt with Apache License 2.0 | 5 votes |
private void processQos2(ChannelHandlerContext ctx,Message innerMsg){ log.debug("[PubMessage] -> Process qos2 message,clientId={}",innerMsg.getClientId()); boolean flag = flowMessageStore.cacheRecMsg(innerMsg.getClientId(),innerMsg); if(!flag){ log.warn("[PubMessage] -> cache qos2 pub message failure,clientId={}",innerMsg.getClientId()); } MqttMessage pubRecMessage = MessageUtil.getPubRecMessage(innerMsg.getMsgId()); ctx.writeAndFlush(pubRecMessage); }
Example #18
Source File: PubAckProcessor.java From iot-mqtt with Apache License 2.0 | 5 votes |
@Override public void processRequest(ChannelHandlerContext ctx, MqttMessage mqttMessage) { String clientId = NettyUtil.getClientId(ctx.channel()); int messageId = MessageUtil.getMessageId(mqttMessage); log.debug("[PubAck] -> Recieve PubAck message,clientId={},msgId={}",clientId,messageId); if(!flowMessageStore.containSendMsg(clientId,messageId)){ log.warn("[PubAck] -> The message is not cached in Flow,clientId={},msgId={}",clientId,messageId); return; } flowMessageStore.releaseSendMsg(clientId,messageId); }
Example #19
Source File: MqttClientHandler.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msgx) throws Exception { if (msgx == null) {return ;} MqttMessage msg = (MqttMessage) msgx; NettyLog.debug("read: {}", msg.fixedHeader().messageType()); MqttFixedHeader mqttFixedHeader = msg.fixedHeader(); switch (mqttFixedHeader.messageType()) { case CONNACK: clientProtocolProcess.processConnectBack(ctx.channel(), (MqttConnAckMessage) msg); break; case UNSUBACK: clientProtocolProcess.processUnSubBack(ctx.channel(), msg); break; case PUBLISH: clientProtocolProcess.processPublish(ctx.channel(), (MqttPublishMessage) msg); break; case PUBACK: clientProtocolProcess.processPubAck(ctx.channel(), msg); break; case PUBREC: clientProtocolProcess.processPubRec(ctx.channel(), msg); break; case PUBREL: clientProtocolProcess.processPubRel(ctx.channel(), msg); break; case PUBCOMP: clientProtocolProcess.processPubComp(ctx.channel(), msg); break; case SUBACK: clientProtocolProcess.processSubAck(ctx.channel(), (MqttSubAckMessage) msg); break; default: break; } }
Example #20
Source File: PubRecProcessor.java From iot-mqtt with Apache License 2.0 | 5 votes |
@Override public void processRequest(ChannelHandlerContext ctx, MqttMessage mqttMessage) { String clientId = NettyUtil.getClientId(ctx.channel()); int messageId = MessageUtil.getMessageId(mqttMessage); log.debug("[PubRec] -> Recieve PubRec message,clientId={},msgId={}",clientId,messageId); if(!flowMessageStore.containSendMsg(clientId,messageId)){ log.warn("[PubRec] -> The message is not cached in Flow,clientId={},msgId={}",clientId,messageId); } MqttMessage pubRelMessage = MessageUtil.getPubRelMessage(messageId); ctx.writeAndFlush(pubRelMessage); }
Example #21
Source File: MqttMessageFactory.java From lannister with Apache License 2.0 | 5 votes |
public static MqttMessage pubcomp(int messageId) { MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBCOMP, false, MqttQoS.AT_MOST_ONCE, false, 2); MqttMessageIdVariableHeader variableHeader = MqttMessageIdVariableHeader.from(messageId); return new MqttMessage(fixedHeader, variableHeader); }
Example #22
Source File: ProtocolProcess.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
/** * P - B, S - B * @param channel * @param msg */ public void processDisConnect(Channel channel, MqttMessage msg) { String clientId = NettyUtil.getClientId(channel); boolean isCleanSession = sessionService.isCleanSession(clientId); NettyLog.debug("DISCONNECT - clientId: {}, cleanSession: {}", clientId, isCleanSession); if (isCleanSession) { this.topicProcess.removeByCleanSession(clientId); this.consumerProcess.removeByCleanSession(clientId); this.procedureProcess.removeByCleanSession(clientId); } sessionService.remove(clientId); channel.close(); }
Example #23
Source File: PubCompProcessor.java From iot-mqtt with Apache License 2.0 | 5 votes |
@Override public void processRequest(ChannelHandlerContext ctx, MqttMessage mqttMessage) { String clientId = NettyUtil.getClientId(ctx.channel()); int messageId = MessageUtil.getMessageId(mqttMessage); boolean isContain = flowMessageStore.releaseSendMsg(clientId,messageId); log.debug("[PubComp] -> Recieve PubCom and remove the flow message,clientId={},msgId={}",clientId,messageId); if(!isContain){ log.warn("[PubComp] -> The message is not in Flow cache,clientId={},msgId={}",clientId,messageId); } }
Example #24
Source File: PubCompProcessor.java From jmqtt with Apache License 2.0 | 5 votes |
@Override public void processRequest(ChannelHandlerContext ctx, MqttMessage mqttMessage) { String clientId = NettyUtil.getClientId(ctx.channel()); int messageId = MessageUtil.getMessageId(mqttMessage); boolean isContain = flowMessageStore.releaseSendMsg(clientId,messageId); log.debug("[PubComp] -> Recieve PubCom and remove the flow message,clientId={},msgId={}",clientId,messageId); if(!isContain){ log.warn("[PubComp] -> The message is not in Flow cache,clientId={},msgId={}",clientId,messageId); } }
Example #25
Source File: ClientProtocolProcess.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
/** * B - S(Qos2) * @param channel * @param mqttMessage */ public void processPubRel(Channel channel, MqttMessage mqttMessage) { MqttMessageIdVariableHeader messageIdVariableHeader = (MqttMessageIdVariableHeader) mqttMessage .variableHeader(); int messageId = messageIdVariableHeader.messageId(); this.consumerProcess.processPubRel(messageId); this.consumerProcess.sendPubCompMessage(messageId); this.consumerProcess.delMesage(messageId); }
Example #26
Source File: ClientProtocolProcess.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
/** * B - P (Qos2) * @param channel * @param mqttMessage */ public void processPubComp(Channel channel, MqttMessage mqttMessage) { MqttMessageIdVariableHeader messageIdVariableHeader = (MqttMessageIdVariableHeader) mqttMessage .variableHeader(); int messageId = messageIdVariableHeader.messageId(); producerProcess.processPubComp(messageId); producerProcess.delMessage(messageId); }
Example #27
Source File: ClientProtocolProcess.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
/** * B- P(Qos2) * @param channel * @param mqttMessage */ public void processPubRec(Channel channel, MqttMessage mqttMessage) { MqttMessageIdVariableHeader messageIdVariableHeader = (MqttMessageIdVariableHeader) mqttMessage .variableHeader(); int messageId = messageIdVariableHeader.messageId(); producerProcess.processPubRec(messageId); producerProcess.sendPubRel(messageId); }
Example #28
Source File: ClientProtocolProcess.java From ext-opensource-netty with Mozilla Public License 2.0 | 5 votes |
/** * B - P (Qos1) * @param channel * @param mqttMessage */ public void processPubAck(Channel channel, MqttMessage mqttMessage) { MqttMessageIdVariableHeader messageIdVariableHeader = (MqttMessageIdVariableHeader) mqttMessage .variableHeader(); int messageId = messageIdVariableHeader.messageId(); producerProcess.processPubAck(messageId); producerProcess.delMessage(messageId); }
Example #29
Source File: DeviceSessionCtx.java From iotplatform with Apache License 2.0 | 5 votes |
@Override public void onMsg(SessionCtrlMsg msg) throws SessionException { if (msg instanceof SessionCloseMsg) { pushToNetwork( new MqttMessage(new MqttFixedHeader(MqttMessageType.DISCONNECT, false, MqttQoS.AT_MOST_ONCE, false, 0))); channel.close(); } }
Example #30
Source File: SessionContext.java From WeEvent with Apache License 2.0 | 5 votes |
public void sendRemote(MqttMessage rsp) { if (this.session != null) { WebSocketMqtt.send2Remote(this.session, rsp); return; } if (this.channel != null) { TcpHandler.sendRemote(this.channel, rsp); } }