如何使用 MQTT 和 CoAP 协议使树莓派与 EdgerOS 进行数据交互,一文看懂!

leecactus0 2022-04-21 17:15:32

纵观人类的通讯史,人类的通讯方式仍在不断的进化。从最开始的烽火传军情、飞鸽传书,到 1873 年英国物理学家麦克斯韦发现发现电磁波,后人在电磁波基础上人们创造了无线通讯,至此结束了几个世纪的远程通讯消息延时的困扰。

 

紧随其后互联网诞生,而通讯方式也随着历史的迭代,从最初需要使用专门的小型计算机执行消息转换 (IMP) ,到 NPC、MAC、直到现在我们最常接触到的 TCP/IP、HTTP 等网络通讯,而这一次次的迭代都在促使网络通讯变得稳定,安全,可靠。

 

直到今天,全世界都在憧憬着万物互联的未来,这也随之带来了又一次通讯领域技术的革新。那么作为边缘计算操作系统的 EdgerOS ,要实现与多种不同协议的设备进行通讯,那么自身也必须拥有多种协议的通讯能力。接下来就以树莓派作为设备端带大家了解两个 EdgerOS 所支持的通讯协议。看看物联网设备端可以使用哪些协议与 EdgerOS 进行通讯。

 

MQTT

MQTT 是一个基于客户端-服务器的消息发布/订阅传输协议。MQTT 协议是轻量、简单、开放和易于实现的,这些特点使它适用范围非常广泛。在很多情况下,包括受限的环境中,如:机器与机器(M2M)通信和物联网(IoT)。在卫星链路通信传感器、偶尔拨号的医疗设备、智能家居、及一些小型化设备中已广泛使用。

 

想必经常关注我们的官方活动的小伙伴,一定对新年之际我们上线的许愿树还有一些印象,在许愿树项目中 EdgerOS 之所以可以完成的灯光音乐灯效果控制,其中所使用的通讯协议便是 MQTT。并且 EdgerOS 中系统原生已集成 MQTT 服务能力,对于开发者的我们只需要进行客户端的接入便可以与服务器中其他设备和应用进行通讯。

客户端:https://baike.baidu.com/item/%e5%ae%a2%e6%88%b7%e7%ab%af/101081

 

MQTT 服务器信息通过以下步骤进行查看与修改:

1.打开爱智桌面上的“设备”应用

 

2.进入应用后选择“设置”

 

 

3.便可以看到 MQTT 服务相关信息,点击“设置”可查看详细的配置信息

 

 

接下来我们就要通过 MQTT 服务器,使树莓派和爱智应用完成通讯。

 

01爱智应用


const EventEmitter = require('events');
const mqtt = require('mqtt');
const socket = require('socket');

/**
 * 生成 MQTT 实例
 */
class MqttInstance extends EventEmitter {

  constructor(config) {
    super();
    this.config = config;
    this.client = null;
    this.init();
  }

  /**
   * 初始化 MQTT CLIENT 对象
   */
  init() {
    const serAddr = socket.sockaddr(this.config.host, this.config.port);

    this.client = mqtt.open(serAddr, undefined, 5000);

    if (!this.client) {
      console.error('Can not connect to broker.请检查是否拥有 MQTT 权限!');
    } else {
      this.client.on('connect', () => {
        console.log('MqttClient running...');
        this.emit('connect');
      });
      this.client.on('disconnect', () => {
        console.error('Mqtt 连接断开.');
        this.emit('disconnect');
      });
      this.client.on('close', () => {
        console.error('Mqtt 连接关闭.');
        this.emit('close');
      });
      this.client.on('error', () => {
        console.error('Mqtt 连接异常.');
        this.emit('error');
      });
      this.client.on('message', (data) => {
        this.emit('message', data);
      });

      this.client.connect({
        client: this.config.clientId || 'mqtt_edgeros',
        user: this.config.user || 'user',
        passwd: this.config.password || 'passwd',
        keepalive: 60,
        will: false,
        topic: '',
        message: '',
        qos: 0
      });
    }
  }

  /**
   * 发布消息
   * @param {*} topic 
   * @param {*} message 
   */
  publish(topic, message) {
    this.client.publish(topic, message);
  }

  /**
   * 订阅消息
   */
  subscribe(topic) {
    this.client.subscribe(topic, { qos: 1 });
  }

  /**
   * 取消订阅
   */
  unsubscribe(topic) {
    this.client.unsubscribe(topic);
  }
}

// 创建mqtt客户端
const mqttClient = new MqttInstance({
  host: '192.168.128.1',
  port: 1883,
  user: 'user',
  password: 'passwd'
});
mqttClient.on('connect', () => {
  mqttClient.subscribe('paspberry_msg');
})
mqttClient.on('message', (data) => {
  console.log("应用输出 topic:", data.topic);
  console.log("应用输出 message:", data.message.toString());
  mqttClient.publish('edgeros_app', data.topic, data.message.toString());
})

module.exports = mqttClient;

 

02树莓派 Node.js

const mqtt = require('mqtt');

const client = mqtt.connect('mqtt://192.168.128.1', {
  clientId: 'paspberry_pi',
  username: 'user',
  password: 'passwd'
});

client.on('connect', function () {
  client.subscribe('edgeros_app');
  client.publish('paspberry_msg', "hello edgeros");
});

client.on('message', function (topic, message) {
  console.log('接收到消息 topic:', topic);
  console.log('接收到消息 message: ', message.toString());
});

 

 

CoAP

 

 

CoAP(Constrained Application Protocol)是一种在物联网世界的类 WEB 协议,它的详细规范定义在 RFC 7252。CoAP 名字翻译来就是“受限应用协议”,顾名思义,使用在资源受限的物联网设备上。物联网设备的 ram,rom 通常都非常小,运行 TCP 和 HTTP 是不可以接受的。

 

1.CoAP 协议网络传输层由 TCP 改为 UDP。

 

 

2.它基于 REST,Server 的资源地址和互联网一样也有类似 URL 的格式,客户端同样有 POST,GET,PUT,DELETE 方法来访问 Server,对 HTTP 做了简化。

 

3.CoAP 是二进制格式的,HTTP 是文本格式的,CoAP 比 HTTP 更加紧凑。

 

4.轻量化,CoAP 最小长度仅仅 4B,一个 HTTP 的头都几十个 Byte 了。

 

5.支持可靠传输,数据重传,块传输。确保数据可靠到达。

 

6.支持 IP 多播, 即可以同时向多个设备发送请求。

 

7.非长连接通信,适用于低功耗物联网场景。

 

CoAP 的使用途径也非常广泛,在之前推文中有一篇 DIY 云台摄像头的内容,而这个项目中实现云台控制的协议就是 CoAP。

我们使用爱智应用来构建一个 CoAP 服务,使用树莓派作为客户端,来实现树莓派与爱智应用的数据交互。

 

01爱智应用


const EventEmitter = require('events');
const Udp = require('udp');
const coap = require('coap');

/**
 * 创建 COAP 服务
 */
class CoapServerInstance extends EventEmitter {
  constructor(config) {
    super();
    this.config = config;
    this.server = null;
    this.init();
  }

  /**
   * 初始化 COAP 服务
   */
  init() {
    const saddr = Udp.sockaddr(Udp.INADDR_ANY, this.config.port);
    this.server = coap.createServer(saddr);

    this.server.on('start', () => {
      console.log('CoAP server running ...');
    });
    this.server.on('stop', () => {
      console.error('CoAP server stop ...');
    });
    this.server.on('request', (req, res) => {
      this.emit('request', req, res);
      if (req.payload) {
        console.log('Recv message:', req.payload.toString());
      }
    });
    this.server.start();
  }
}

//创建 coap 服务实例
const coapServer = new CoapServerInstance({
  port: 5683
});
coapServer.on('request', (req, res) => {
  console.log("COAP 请求路径:", req.path);
  // 请求回声
  res.end('request path to ' + req.path);
})

module.exports = coapServer;

 

02树莓派 Node.js


const coap = require('coap');

const req = coap.request({
  host: '192.168.128.1',
  prot: 5683,
  pathname: '/path_one',
});
req.on('response', (res) => {
  console.log('请求路径回声消息:', res.payload.toString());
  // call path_one
  call();
});
req.end();

function call() {
  const req2 = coap.request({
    host: '192.168.128.1',
    prot: 5683,
    pathname: '/path_two',
  });
  req2.on('response', (res) => {
    console.log('请求路径回声消息:', res.payload.toString());
  });
  req2.end();
}

 

注意:在使用 MQTT 或 CoAP 协议时,要确定已赋予该应用对应权限

 

经过上面两个例子相信大家已经大概清楚如何使用 MQTT 和 CoAP 协议使树莓派与 EdgerOS 进行数据交互了,而这不仅仅是针对树莓派,任何可以使用这两种协议的设备都可以通过上述方法与 EdgerOS 进行通讯 。

 

而 EdgerOS 除了上面协议外也推出了 SDDC 和 ZDDC 协议。SDDC (Smart Device Discovery & Control) 是 EdgerOS 专门为使用 Wi-Fi 和以太网通信技术的物联网设备定义的一套智能设备发现与控制通信协议。ZDDC (ZigBee Device Discovery & Control) 是 EdgerOS 专门为 ZigBee 物联网设备定义的一套智能设备发现与控制通信协议。使用 SDDC、ZDDC 协议开发的物联网设备均能被 EdgerOS 自动管理,因此大家也可以使用 SDDC、ZDDC 通信协议。对单片机感兴趣的同学也可以使用这两种方式进行数据通讯。

...全文
1961 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

1,582

社区成员

发帖
与我相关
我的任务
社区描述
爱智开发者平台是一个开放的物联网平台,通过爱智世界,应用开发者可以把自己的应用分发到亿万用户的设备上,硬件开发者能够把设备能力开放给海量的开发者,让优质的应用脱颖而出,为用户提供更优秀的使用体验。
边缘计算物联网javascript 企业社区
社区管理员
  • EdgerOS
  • Lumos_zbj
  • dayinfinite
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧