thingsboard官网: https://thingsboard.io/

thingsboard GitHub: https://github.com/thingsboard/thingsboard

thingsboard提供的体验地址: http://demo.thingsboard.io/

 

BY Thingsboard team

以下内容是在原文基础上演绎的译文。除非另行注明,页面上所有内容采用知识共享-署名(CC BY 2.5 AU)协议共享。

原文地址: ThingsBoard API参考:CoAP设备API


 

CoAP是一种在物联网世界的类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的头都几十个B了。

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

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

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

安装node.js,然后执行以下命令:

  1. npm install coap-cli -g

 

  1. Usage: coap [command] [options] url
  2. Commands:
  3. get performs a GET request
  4. put performs a PUT request
  5. post performs a POST request
  6. delete performs a DELETE request
  7. Options:
  8. -h, --help output usage information
  9. -V, --version output the version number
  10. -o, --observe Observe the given resource
  11. -n, --no-new-line No new line at the end of the stream
  12. -p, --payload <payload> The payload for POST and PUT requests
  13. -b, --block2 <option> set the block2 size option
  14. -q, --quiet Do not print status codes of received packets
  15. -c, --non-confirmable non-confirmable
  16. -t, --timeout <seconds> The maximum send time in seconds
  17. -T, --show-timing Print request time, handy for simple performance tests
  18. -O, --coap-option <key,value> Add COAP-Option to the request (repeatable)

 

PUT和POST

PUT和POST请求如下例所示

  1. echo -n 'hello world' | coap post coap://localhost/message

 


 

因为Thingsboard最新release,是基于微服务架构,不利用单独理解代码。

Thingsboard CoAP设备传输协议源代码:https://github.com/thingsboard/thingsboard/tree/release-2.0/transport/coap

本文基于上面源代码后,剔除相关的安全验证和处理之后搭建简易的讲解项目:

https://github.com/sanshengshui/IOT-Technical-Guide/tree/master/IOT-Guide-Coap

 


Thingsboard的CoAP设备传输协议是基于Californium。Californium 是一款基于Java实现的Coap技术框架,该项目实现了Coap协议的各种请求响应定义,支持CON/NON不同的可靠性传输模式。 Californium 基于分层设计且高度可扩展,其内部模块设计及接口定义存在许多学习之处;

值得一提的是,在同类型的 Coap技术实现中,Californium的性能表现是比较突出的,如下图:

更多的数据可以参考Californium-可扩展云服务白皮书 本文以框架的源码分析为主,其他内容不做展开。

 

  1. .
  2. └── main
  3. └── java
  4. ├── com
  5. └── sanshengshui
  6. └── coap
  7. ├── adaptors
  8. └── JsonCoapAdaptor.java
  9. ├── CoapTransportResource.java
  10. ├── common
  11. └── FeatureType.java
  12. └── session
  13. └── SessionMsgType.java
  14. └── IOTCoapServer.java

 

 

  1. 1 public class IOTCoapServer {
  2. 2
  3. 3 private static final String V1 = "v1";
  4. 4 private static final String API = "api";
  5. 5
  6. 6
  7. 7 private static String host = "127.0.0.1";
  8. 8 private static Integer port = 5683;
  9. 9 private static long timeout = 10000;
  10. 10
  11. 11 public static void main(String[] args) throws UnknownHostException {
  12. 12 CoapServer coapServer = new CoapServer();
  13. 13 CoapResource api = new CoapResource(API);
  14. 14 api.add(new CoapTransportResource(V1,timeout));
  15. 15 coapServer.add(api);
  16. 16 InetAddress addr = InetAddress.getByName(host);
  17. 17 InetSocketAddress sockAddr = new InetSocketAddress(addr, port);
  18. 18 coapServer.addEndpoint(new CoapEndpoint(sockAddr));
  19. 19 coapServer.start();
  20. 20
  21. 21 }
  22. 22
  23. 23 }

 

  • 第12行代码: CoapServer用作创建服务端。

  • 第12-15行: CoapResourceresource的基本实现,扩展这个类来编写您自己的资源。通过向资源添加“v1”、”api”和超时时间的设置,则coap的基础url为:coap://localhost:port/api/v1/

  • 第16-18行: Endpoint负责与网络进行通信, 如果没有一个Endpoint与CoapServer进行绑定,那就创建一个默认的Endpoint,默认就是ucp实现传输层。

  • 第19行,启动CoAP服务。

 

以下图片展示服务端的基础架构:


 

此类负责处理请求

  1.  
  1. @Override
  2. public void handleGET(CoapExchange exchange) {
  3. Optional<FeatureType> featureType = getFeatureType(exchange.advanced().getRequest());
  4. if (!featureType.isPresent()) {
  5. } else if (featureType.get() == FeatureType.TELEMETRY) {
  6. exchange.respond(CoAP.ResponseCode.BAD_REQUEST);
  7. } else if (featureType.get() == FeatureType.ATTRIBUTES) {
  8. processRequest(exchange, SessionMsgType.GET_ATTRIBUTES_REQUEST);
  9. } else {
  10. exchange.respond(CoAP.ResponseCode.BAD_REQUEST);
  11. }
  12. }

 

  • 如果我们客户端发起的是GET请求,那么将会进入到handleGET(CoapExchange exchange)方法。

  • getFeatureType(Request request)判断coap协议长度是否大于3。当大于等于3,获取/api/v1/${param}param元素。

  1. public static final int FEATURE_TYPE_POSITION = 3;
  2. private Optional<FeatureType> getFeatureType(Request request) {
  3. List<String> uriPath = request.getOptions().getUriPath();
  4. try {
  5. if (uriPath.size() >= FEATURE_TYPE_POSITION) {
  6. return Optional.of(FeatureType.valueOf(uriPath.get(FEATURE_TYPE_POSITION - 1).toUpperCase()));
  7. }
  8. } catch (RuntimeException e) {
  9. }
  10. return Optional.empty();
  11. }

 

  • 通过判断param是否是temperature还是attributes进行相关的逻辑操作。

  • 当不是上述类型,回复状态为BAD_REQUEST的状态码。

 

  1.  
  1. @Override
  2. public void handlePOST(CoapExchange exchange) {
  3. Optional<FeatureType> featureType = getFeatureType(exchange.advanced().getRequest());
  4. if (!featureType.isPresent()) {
  5. exchange.respond(CoAP.ResponseCode.BAD_REQUEST);
  6. } else {
  7. switch (featureType.get()) {
  8. case ATTRIBUTES:
  9. processRequest(exchange, SessionMsgType.POST_ATTRIBUTES_REQUEST);
  10. break;
  11. case TELEMETRY:
  12. processRequest(exchange, SessionMsgType.POST_TELEMETRY_REQUEST);
  13. break;
  14. }
  15. }
  16. }

 

  • 如果我们客户端发起的是POST请求,那么将会进入到handlePOST(CoapExchange exchange)方法。

  • 对获取的uri的类型是temperature还是attributes来做相关的逻辑操作。

 

  1.  
  1. private void processRequest(CoapExchange exchange, SessionMsgType type) {
  2. exchange.accept();
  3. Exchange advanced = exchange.advanced();
  4. Request request = advanced.getRequest();
  5. try {
  6. switch (type) {
  7. case GET_ATTRIBUTES_REQUEST:
  8. case POST_TELEMETRY_REQUEST:
  9. case POST_ATTRIBUTES_REQUEST:
  10. //这个类在之前的物模型博文中有所讲解,大家可以翻看!
  11. JsonCoapAdaptor.convertToMsg(type,request);
  12. break;
  13. default:
  14. throw new IllegalArgumentException("Unsupported msg type: " + type);
  15. }
  16. exchange.respond("Data has been received");
  17. } catch (AdaptorException e){
  18. exchange.respond(CoAP.ResponseCode.BAD_REQUEST, e.getMessage());
  19. } catch (IllegalArgumentException e) {
  20. exchange.respond(CoAP.ResponseCode.INTERNAL_SERVER_ERROR, e.getMessage());
  21. }
  22. }

 


 

要将遥测数据发布到服务器节点,请将POST请求发送到以下URL:

  1.  
  1. coap://host/api/v1/telemetry

 

最简单的支持数据格式是:

  1.  
  1. {"key1":"value1", "key2":"value2"}

 

要么

  1.  
  1. [{"key1":"value1"}, {"key2":"value2"}]

 

请注意,在这种情况下,服务器端时间戳将分配给上传的数据!

如果您的设备能够获取客户端时间戳,您可以使用以下格式:

  1. {"ts":1451649600512, "values":{"key1":"value1", "key2":"value2"}}

 

在上面的示例中,我们假设“1451649600512”是具有毫秒精度的unix时间戳。例如,值’1451649600512’对应于’Fri,2016年1月1日12:00:00.512 GMT’

例子:

  1. echo -n '{"size":21,"type":"device"}' | coap post coap://demo.thingsboard.io/api/v1/telemetry

 

  1. 结果:
  1. key= 1564105084015
  2. 属性名=size 属性值=21
  3. 属性名=type 属性值=device

 

属性API允许设备

  • 将客户端设备属性上载到服务器。

  • 从服务器请求客户端和共享设备属性。

要将客户端设备属性发布到ThingsBoard服务器节点,请将POST请求发送到以下URL:

  1. coap://host/api/v1/attributes

 

例子:

  1. echo -n '{"size":21,"type":"device","status":true}' | coap post coap://localhost:5683/api/v1/attributes

结果:

  1.  
  1. key= 1564105158573
  2. 属性名=size 属性值=21
  3. 属性名=type 属性值=device
  4. 属性名=status 属性值=true
  1.  

要向ThingsBoard服务器节点请求客户端或共享设备属性,请将GET请求发送到以下URL:

  1.  
  1. coap://host/api/v1/attributes?clientKeys=attribute1,attribute2&sharedKeys=shared1,shared2

  1.  

例子:

  1. coap get coap://localhost:5683/api/v1/attributes?clientKeys=attribute1,attribute2&sharedKeys=shared1,shared2

 

结果:

  1. (2.05) Data has been received

 

到此,物联网时代,相信大家对IOT架构下的CoAP协议有所了解了,感谢大家的阅读!

 

版权声明:本文为sanshengshui原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/sanshengshui/p/11229139.html