HarmonyOS实现MQTT消息监听展示

开发 后端 OpenHarmony
因为harmonyOS暂时没有发现现成的mqtt的js包,所以使用Java进行Mqtt消息的接收,使用JS去定时调用Java接收到消息并展示。

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

思路

因为harmonyOS暂时没有发现现成的mqtt的js包,所以使用Java进行Mqtt消息的接收,使用JS去定时调用Java接收到消息并展示

首先是JS调用Java,JS FA(Feature Ability)调用Java PA(Particle Ability)有两种方式,Ability和Internal Ability,这里使用的是第一种Ability

然后是Java端的Mqtt消息接收,使用paho的第三方库进行消息接收,页面启动时JS端调用Java端实现Mqtt消息接收开始,使用异步挂起,接收消息并缓存,随后JS端每次调用Java端拿到的都是最新缓存的信息

具体代码

hml页面:

  1. <div class="container"
  2.     <div> 
  3.         <text class="title"
  4.             {{ title }} 
  5.         </text> 
  6.     </div> 
  7.     <div> 
  8.         <text class="title" onclick="mqttMessage"
  9.             开始mqtt 
  10.         </text> 
  11.     </div> 
  12.     <div> 
  13.         <text class="title" onclick="stopMqtt"
  14.             停止mqtt 
  15.         </text> 
  16.     </div> 
  17. </div> 

JS代码:

  1. const ABILITY_TYPE_EXTERNAL = 0; 
  2. const ACTION_SYNC = 0; 
  3. const ACTION_MESSAGE_CODE_START_MQTT = 1001; 
  4. const ACTION_MESSAGE_CODE_MQTT_MESSAGE = 1002; 
  5. const BUNDLE_NAME = 'com.example.mqttapplication'
  6. const ABILITY_NAME = 'com.example.mqttapplication.PlayAbility'
  7.  
  8. export const playAbility = { 
  9.     startMqtt: async function() { 
  10.         FeatureAbility.callAbility({ 
  11.             messageCode: ACTION_MESSAGE_CODE_START_MQTT, 
  12.             abilityType: ABILITY_TYPE_EXTERNAL, 
  13.             syncOption: ACTION_SYNC, 
  14.             bundleName: BUNDLE_NAME, 
  15.             abilityName: ABILITY_NAME 
  16.         }); 
  17.     }, 
  18.     mqttMessage: async function(that) { 
  19.         var result = await FeatureAbility.callAbility({ 
  20.             messageCode: ACTION_MESSAGE_CODE_MQTT_MESSAGE, 
  21.             abilityType: ABILITY_TYPE_EXTERNAL, 
  22.             syncOption: ACTION_SYNC, 
  23.             bundleName: BUNDLE_NAME, 
  24.             abilityName: ABILITY_NAME 
  25.         }); 
  26.         var ret = JSON.parse(result); 
  27.         if (ret.code == 0) { 
  28.             console.info('mqtt is:' + JSON.stringify(ret.abilityResult)); 
  29.             that.title = 'mqtt is:' + JSON.stringify(ret.abilityResult); 
  30.         } else { 
  31.             console.error('mqtt error code:' + JSON.stringify(ret.code)); 
  32.         } 
  33.     } 
  34. export default { 
  35.     data: { 
  36.         title: ""
  37.         timer: null 
  38.     }, 
  39.     task() { 
  40.         playAbility.mqttMessage(this); 
  41.     }, 
  42.     mqttMessage() { 
  43.         this.title = "开始获取MQTT消息"
  44.         this.task() 
  45.         this.timer=setInterval(this.task,200) 
  46.     }, 
  47.     stopMqtt() { 
  48.         clearInterval(this.timer) 
  49.     } 
  50. //初始化Java端Mqtt消息接收 
  51. playAbility.startMqtt() 

Java端代码(接收Mqtt消息,异步)

  1. import org.eclipse.paho.client.mqttv3.*; 
  2. import org.eclipse.paho.client.mqttv3.MqttMessage; 
  3. import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; 
  4.  
  5. import java.util.List; 
  6.  
  7.  
  8. public class MqttThread implements Runnable { 
  9.  
  10.     /**地址*/ 
  11.     public static final String MQTT_BROKER_HOST = "tcp://xxx.xxx.xxx.xxx:1883"
  12.     /**客户端唯一标识*/ 
  13.     public static final String MQTT_CLIENT_ID = "client"
  14.     /**订阅标识*/ 
  15.     public static final String MQTT_TOPIC = "HarmonyTest"
  16.     /**客户端*/ 
  17.     private volatile static MqttClient mqttClient; 
  18.     /**连接选项*/ 
  19.     private static MqttConnectOptions options; 
  20.     /**消息*/ 
  21.     private final List<String> message; 
  22.  
  23.     public MqttThread(List<String> message) { 
  24.         this.message = message; 
  25.     } 
  26.  
  27.     public void run() { 
  28.         try { 
  29.             mqttClient = new MqttClient(MQTT_BROKER_HOST, MQTT_CLIENT_ID, new MemoryPersistence()); 
  30.             options = new MqttConnectOptions(); 
  31.             options.setCleanSession(true); 
  32.             options.setConnectionTimeout(20); 
  33.             options.setKeepAliveInterval(20); 
  34.             mqttClient.connect(options); 
  35.             mqttClient.subscribe(MQTT_TOPIC); 
  36.             mqttClient.setCallback(new MqttCallback() { 
  37.                 @Override 
  38.                 public void connectionLost(Throwable throwable) { } 
  39.                 @Override 
  40.                 public void messageArrived(String s, MqttMessage mqttMessage) { 
  41.                     message.clear(); 
  42.                     message.add(mqttMessage.toString()); 
  43.                     System.out.println("接收到mqtt消息:" + mqttMessage.toString()); 
  44.                 } 
  45.                 @Override 
  46.                 public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { } 
  47.             }); 
  48.         } catch (Exception e) { 
  49.             e.printStackTrace(); 
  50.         } 
  51.     } 

Java端代码(Particle Ability)

  1. import com.example.mqttapplication.mqtt.MqttThread; 
  2. import ohos.aafwk.ability.Ability; 
  3. import ohos.aafwk.content.Intent; 
  4. import ohos.hiviewdfx.HiLog; 
  5. import ohos.hiviewdfx.HiLogLabel; 
  6. import ohos.rpc.*; 
  7. import ohos.utils.zson.ZSONObject; 
  8.  
  9. import java.util.ArrayList; 
  10. import java.util.HashMap; 
  11. import java.util.List; 
  12. import java.util.Map; 
  13.  
  14. public class PlayAbility extends Ability { 
  15.  
  16.     static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 1, "MY_TAG"); 
  17.  
  18.     private static final int ERROR = -1; 
  19.     private static final int SUCCESS = 0; 
  20.     private static final int START_MQTT = 1001; 
  21.     private static final int MQTT_MESSAGE = 1002; 
  22.  
  23.     @Override 
  24.     protected void onStart(Intent intent) { 
  25.         super.onStart(intent); 
  26.     } 
  27.  
  28.     @Override 
  29.     protected IRemoteObject onConnect(Intent intent) { 
  30.         super.onConnect(intent); 
  31.         PlayRemote remote = new PlayRemote(); 
  32.         return remote.asObject(); 
  33.     } 
  34.  
  35.     static class PlayRemote extends RemoteObject implements IRemoteBroker { 
  36.  
  37.         private List<String> message; 
  38.  
  39.         private Thread thread; 
  40.  
  41.         public PlayRemote() { 
  42.             super("PlayRemote"); 
  43.         } 
  44.  
  45.         @Override 
  46.         public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) { 
  47.             // 开始mqtt 
  48.             else if (code == START_MQTT) { 
  49.                 Map<String, Object> result = new HashMap<>(); 
  50.                 result.put("code", SUCCESS); 
  51.                 result.put("abilityResult""成功开始mqtt"); 
  52.                 try { 
  53.                     message = new ArrayList<>(); 
  54.                     MqttThread mqttThread = new MqttThread(message); 
  55.                     thread = new Thread(mqttThread); 
  56.                     thread.start(); 
  57.                     System.out.println("mqtt启动成功"); 
  58.                 } 
  59.                 catch (Exception e) { 
  60.                     result.put("code", ERROR); 
  61.                     result.put("abilityResult""启动失败"); 
  62.                 } 
  63.                 reply.writeString(ZSONObject.toZSONString(result)); 
  64.             } 
  65.             // 获取mqtt消息 
  66.             else if (code == MQTT_MESSAGE) { 
  67.                 Map<String, Object> result = new HashMap<>(); 
  68.                 result.put("code", SUCCESS); 
  69.                 if (message.isEmpty()) { 
  70.                     result.put("abilityResult""未接收到MQTT消息"); 
  71.                 } 
  72.                 else { 
  73.                     ZSONObject zsonObject = ZSONObject.stringToZSON(message.get(0)); 
  74.                     result.put("abilityResult", zsonObject.getString("message")); 
  75.                 } 
  76.                 reply.writeString(ZSONObject.toZSONString(result)); 
  77.             } 
  78.             else { 
  79.                 Map<String, Object> result = new HashMap<>(); 
  80.                 result.put("abilityError", ERROR); 
  81.                 reply.writeString(ZSONObject.toZSONString(result)); 
  82.                 return false
  83.             } 
  84.             return true
  85.         } 
  86.  
  87.         @Override 
  88.         public IRemoteObject asObject() { 
  89.             return this; 
  90.         } 
  91.     } 

另外启动网络连接还需要往config.json里加点东西获取权限

  1.   ... 
  2.   "module": { 
  3.     ... 
  4.     "reqPermissions": [ 
  5.       { 
  6.         "name""ohos.permission.GET_NETWORK_INFO" 
  7.       }, 
  8.       { 
  9.         "name""ohos.permission.INTERNET" 
  10.       }, 
  11.       { 
  12.         "name""ohos.permission.SET_NETWORK_INFO" 
  13.       }, 
  14.       { 
  15.         "name""ohos.permission.MANAGE_WIFI_CONNECTION" 
  16.       }, 
  17.       { 
  18.         "name""ohos.permission.SET_WIFI_INFO" 
  19.       }, 
  20.       { 
  21.         "name""ohos.permission.GET_WIFI_INFO" 
  22.       } 
  23.     ] 
  24.   } 

 最后写了个python的脚本用来发送mqtt消息,很简单就一行

  1. import paho.mqtt.publish as publish 
  2. publish.single('HarmonyTest''{"message":"BongShakalaka"}', hostname='xxx.xxx.xxx.xxx'

附:mqtt消息是要有mqtt服务器的,这个就自己搭或者买吧

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

 

责任编辑:jianghua 来源: 鸿蒙社区
相关推荐

2020-11-18 11:36:35

鸿蒙系统

2022-07-12 17:33:00

消息定时提醒鸿蒙

2020-12-07 12:47:22

MQTT鸿蒙hi3861

2016-11-28 14:40:00

MQTT消息协议

2022-07-01 17:14:03

消息通知鸿蒙

2022-05-23 09:30:00

MQTT车联网QoS

2023-09-24 23:18:50

2020-11-17 08:59:28

MQTT

2021-05-27 09:57:55

Inotify监控系统

2017-05-27 06:32:36

JSONC代码函数

2022-05-18 10:07:29

EMQ车联网MQTT

2017-03-20 09:50:35

消息队列架构消息

2023-05-08 19:54:39

微软Windows 11

2020-11-24 09:52:22

MQTT

2023-01-04 07:39:39

2021-02-24 08:20:33

MQTT物联网网关开发物联网

2009-08-25 17:43:17

C#串口监听

2020-08-26 07:17:19

通信

2024-03-22 12:10:39

Redis消息队列数据库

2021-02-21 08:31:45

物联网MQTT消息
点赞
收藏

51CTO技术栈公众号