1 Star 3 Fork 1

yyz116 / paho-mqtt

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 8.83 KB
一键复制 编辑 原始数据 按行查看 历史
yyz116 提交于 2024-02-19 17:57 . 修改单元测试

jsbn

简介

本软件是移植开源软件 paho.mqtt.javascript 源码在OpenHarmony上进行功能适配,在OpenHarmony上已支持原库mqtt客户端的功能。 注意,该库底层使用的是websocket通信,因此只支持ws或wss开头的websocket连接方式的MQttBooker服务。 移植还参考了微信小程序版的paho.mqtt.wxapp,移植参考教程文档第三方开源js库移植适配指南.

下载安装

ohpm  install @yyz116/paho-mqtt 

OpenHarmony ohpm 环境配置等更多内容,请参考如何安装 OpenHarmony ohpm 包

使用说明

  1. 引入依赖
最新版本支持
  import MQTT from '@yyz116/paho-mqtt'
  1. 使用举例
 import MQTT from '@yyz116/paho-mqtt'
 
 let client = new MQTT.Client("broker.emqx.io",8083,"/mqtt", "mqttx_2");
      client.trace = msg => {
        console.log(msg.message);
        hilog.info(0x0000, 'testTag',`mqtt trace msg: ${msg.message}`);
      };
      client.connect({
        timeout: 10,
        //userName: "username",
        //password: "111111",
        keepAliveInterval: 60,
        cleanSession: true,
        useSSL: false,
        // invocationContext: {
        //   asdf: true,
        // },
        onSuccess: o => {
          //console.log("connected: ", o.invocationContext.asdf);
          hilog.info(0x0000, 'testTag',`mqtt trace msg: connect ok`);
        },
        mqttVersion: 3,
        onFailure: e => {
          console.error("could not connect: ", e.errorMessage);
        },
        //hosts: ["broker.emqx.io"],
        //ports: [8083],
        //mqttVersionExplicit: true,
        reconnect: false,
      });

      console.log(`created new client on "${client.host}:${client.port}/${client.path}" with id "${client.clientId}"`);

      client.onMessageArrived = msg => {
          console.log(`arrived: ${msg.destinationName}: ${msg.payloadString}`);
          console.log(
            `len: ${msg.payloadBytes.byteLength}, retained: ${msg.retained}, dup: ${msg.duplicate}, qos: ${msg.qos}`,
          );
        };

        client.onConnectionLost = err => {
          console.log(`connection lost (code ${err.errorCode}): ${err.errorMessage}`);
        };

        client.onMessageDelivered = msg => {
          console.log(`delivered: ${msg.destinationName}: ${msg.payloadString}`);
          console.log(
            `len: ${msg.payloadBytes.byteLength}, retained: ${msg.retained}, dup: ${msg.duplicate}, qos: ${msg.qos}`,
          );
        };

        client.send("test/topic", "123456", 0, true);
        client.subscribe("test/topic", {
          qos: 0,
          onSuccess: o => {
            console.log(`subscribed: ${o.invocationContext.asdf}`);
          },
          onFailure: e => {
            console.error("error subscribing: ", e.errorMessage);
          },
          timeout: 10,
        });

        client.unsubscribe("test/topic", {
          //invocationContext: { asdf: true },
          onSuccess: o => {
            console.log(`subscribed: ${o.invocationContext.asdf}`);
          },
          onFailure: e => {
            console.error("error subscribing: ", e.errorMessage);
          },
          timeout: 10,
        });

        client.send("test/topic2", "hello world,csdn.net/qq8864", 0, true);
        client.send("test/topic3", "hello world 2!", 1);
        client.send("test/topic4", new ArrayBuffer(3));
  1. 注意事项 在ets中使用的是es6的模块使用规范,使用import而不是require。另外需注意,原库使用 Namepsace Paho.MQTT,本库则是MQTT.

以下是原库的介绍内容

Eclipse Paho JavaScript client

Build Status

The Paho JavaScript Client is an MQTT browser-based client library written in Javascript that uses WebSockets to connect to an MQTT Broker.

Project description:

The Paho project has been created to provide reliable open-source implementations of open and standard messaging protocols aimed at new, existing, and emerging applications for Machine-to-Machine (M2M) and Internet of Things (IoT). Paho reflects the inherent physical and cost constraints of device connectivity. Its objectives include effective levels of decoupling between devices and applications, designed to keep markets open and encourage the rapid growth of scalable Web and Enterprise middleware and applications.

Links

Using the Paho Javascript Client

Downloading

A zip file containing the full and a minified version the Javascript client can be downloaded from the Paho downloads page

Alternatively the Javascript client can be downloaded directly from the projects git repository: https://raw.githubusercontent.com/eclipse/paho.mqtt.javascript/master/src/paho-mqtt.js.

Please do not link directly to this url from your application.

Building from source

There are two active branches on the Paho Java git repository, master which is used to produce stable releases, and develop where active development is carried out. By default cloning the git repository will download the master branch, to build from develop make sure you switch to the remote branch: git checkout -b develop remotes/origin/develop

The project contains a maven based build that produces a minified version of the client, runs unit tests and generates it's documentation.

To run the build:

$ mvn

The output of the build is copied to the target directory.

Tests

The client uses the Jasmine test framework. The tests for the client are in:

src/tests

To run the tests with maven, use the following command:

$ mvn test

The parameters passed in should be modified to match the broker instance being tested against.

Documentation

Reference documentation is online at: http://www.eclipse.org/paho/files/jsdoc/index.html

Compatibility

The client should work in any browser fully supporting WebSockets, http://caniuse.com/websockets lists browser compatibility.

Getting Started

The included code below is a very basic sample that connects to a server using WebSockets and subscribes to the topic World, once subscribed, it then publishes the message Hello to that topic. Any messages that come into the subscribed topic will be printed to the Javascript console.

This requires the use of a broker that supports WebSockets natively, or the use of a gateway that can forward between WebSockets and TCP.

// Create a client instance
var client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId");

// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;

// connect the client
client.connect({onSuccess:onConnect});


// called when the client connects
function onConnect() {
  // Once a connection has been made, make a subscription and send a message.
  console.log("onConnect");
  client.subscribe("World");
  message = new Paho.MQTT.Message("Hello");
  message.destinationName = "World";
  client.send(message);
}

// called when the client loses its connection
function onConnectionLost(responseObject) {
  if (responseObject.errorCode !== 0) {
    console.log("onConnectionLost:"+responseObject.errorMessage);
  }
}

// called when a message arrives
function onMessageArrived(message) {
  console.log("onMessageArrived:"+message.payloadString);
}

Breaking Changes

Previously the Client's Namepsace was Paho.MQTT, as of version 1.1.0 (develop branch) this has now been simplified to Paho. You should be able to simply do a find and replace in your code to resolve this, for example all instances of Paho.MQTT.Client will now be Paho.Client and Paho.MQTT.Message will be Paho.Message.

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yyz116/paho-mqtt.git
git@gitee.com:yyz116/paho-mqtt.git
yyz116
paho-mqtt
paho-mqtt
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891