1. What is CoAP
“The Constrained Application Protocol (CoAP) is a specialized web transfer protocol for use with constrained nodes and constrained networks in the Internet of Things. The protocol is designed for machine-to-machine (M2M) applications such as smart energy and building automation.”
2. Features
- 基于REST架构:Servers make resources available under a URL, and clients access these resources using methods such as GET, PUT, POST, and DELETE.
- UDP binding with reliability and multicast support.
- Secure: Default choice of DTLS (Datagram Transport Layer Security) parameters is equivalent to 3072-bit RSA key.
- Asynchronous message exchanges.
- Simple proxy and caching capabilities.
- Optional observation[RFC7641] and block transfer[draft-ietf-core-block-19-Block-wise transfers]
3. Protocol Overview
3.1 A two-layer approach
CoAP messaging layer used to deal with UDP and the asynchronous nature of the interactions.
Request/response interactions using Method Code and Response Code.
3.2 Messaging Model
Reliability is provided by marking a message as Confirmable (CON) message.
A message that does not require reliable transmission can be sent as a Non-confirmable message (NON).
3.3 Request/Response Model
CoAP request and response semantics are carried in CoAP messages, which include either a Method Codeor Response Code.
Request的Method code有GET, POST, PUT, DELETE四种。
Response有Piggybacked Response, Separate Response, Non-confirmable Response.
4. Format
Version (Ver): 2-bit unsigned integer. Implementations of this specification MUST set this field to 1 (01 binary).
Type (T): 2-bit unsigned integer. Indicates if this message is of type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or Reset (3).
Token Length (TKL): 4-bit unsigned integer. Indicates the length of the variable-length Token field (0-8 bytes).
Code:8-bit unsigned integer, split into a 3-bit class (most significant bits) and a 5-bit detail (least significant bits).一般写成c.dd的形式,可以参考CoAP Code Registries.
Message ID: 16-bit unsigned integer in network byte order. Used to match messages of type Acknowledgement/Reset to messages of type Confirmable/Nonconfirmable.
Token: Used to match a response with a request.[0-8bytes].
Option: 在CoAP mesage中可以携带一些列的options (以Option Number表示)。每一个option组成如下:
Option Delta:4-bit unsigned integer. A value between 0 and 12.
如果Option Delta == 13, 那么Option Delta (extended)部分为1 byte,Option Delta = 13+Option Delta (extended)
如果Option Delta == 14, 那么Option Delta (extended)部分为2 byte,Option Delta = 14+255+Option Delta (extended)
Option Delta == 15无效。
Option Length:4-bit unsigned integer. A value between 0 and 12.
如果Option Length== 13, 那么Option Length(extended)部分为1 byte,Option Length= 13+Option Length(extended)
如果Option Length== 14, 那么Option Length(extended)部分为2 byte,Option Length= 14+255+Option Length(extended)
Option Delta == 15无效。
Option Number的计算:
Option Number从option delta中得到。The Option Number is calculated by simply summing the Option Delta values of this and all previous options before it.也就是说某一个option的option number就是它之前所有Option的Option delta和它自己的option delta加起来的值。
5. Message Transmission
有四种消息类型: Confirmable (0), Non-confirmable (1), Acknowledgement (2), or Reset (3).
5.1 Messages Transmitted Reliably
- 使用Confirmable (CON) message,Request和Response都可以使用这种Type.
- 收到Confirmable (CON) message后有两种选择,(a)回Acknowledgement message (b)Reject the message.
- 如果要拒绝Confirmable (CON) message,则发送Reset (RST) message,然后忽略这个消息。
- 重传。UDP不可靠,Sender发出Confirmable (CON) message后依靠a timeout and a retransmission counter来确定重传时机。
5.2 Messages Transmitted without Reliability
- Request和Response都可以使用这种Type.
- 不需要对方回Acknowledgement.
- 果要拒绝Non-confirmable (NON) message,则发送Reset (RST) message,然后忽略这个消息。
总结下Mesage Type的使用如下:
*表示不是正常的操作,只是为了引起对方回Reset message(CoAP ping)。
6. Request/Response
6.1 Requset
- CoAP supports the basic methods of GET, POST, PUT, and DELETE.
6.1.1 Method Code
- GET:获取Server上的资源。Server可能回2.05 (Content) or 2.03 (Valid) Response Code。
- POST:通常用来创建新的资源或者更新资源。如果资源已经被创建,Server回2.01 (Created) Response Code;如果PSOT成功但是Server没有创建资源,Server回2.04 (Changed) Response Code;如果POST成功导致目标资源删除,Server回2.02 (Deleted) Response Code。
- PUT:更新Server上的资源。如果资源存在,回2.04(Changed) Response Code;如果资源不存在,则Server可能会创建资源,回2.01 (Created) Response Code。如果资源不能被创建或修改,则回Error Response.
- DELETE:删除Server上的资源。回2.02 (Deleted) Response Code。
6.2 Response
有Piggybacked Response, Separate Response, Non-confirmable Response三种类型。
- Piggybacked Response. 最常用的类型,Reponse内容直接放在acknowledges中。
- Separate Response. Server暂时没办法直接回(可能需要更多的时间准备),直接回Empty Acknowledgement。当Server准备好了,给Client发Confirmable message(也可以是Non-confirmable message),最后Client回Acknowledgement。如果Server在回复Clinet之前又收到Client的重传,那么也回Empty Acknowledgement。
- Non-confirmable Response. Client发出Non-confirmable message,Server一般也回Non-confirmable message。Spec说Server也可以发Confirmable message[P14].
三个Response类型的例子:
可以看到Server回Separate Response的时候,Token和Client的Request时的Token是一致的,但是Message ID已经变掉了。
6.2.1 Response Code
- Success:2.xx
- Client Error:4.xx
- Server Error:5.xx
Success 2.xx
- 2.01 Created. 回复POST或者PUT。
- 2.02 Deleted.回复DELETE,有些情况下的POST。
- 2.03 Valid.Indicate that the response identified by the entity-tag identified by the included ETag Option is valid.所以,Response必须带ETag Option。
- 2.04 Changed.回复POST和PUT。
- 2.05 Content.回复GET。
Client Error 4.xx
- 4.00 Bad Resuest.
- 4.01 Unauthorized
- 4.02 Bad Option
- 4.03 Forbidden
- 4.04 Not Found
- 4.05 Method Not Allowed
- 4.06 Not Acceptable
- 4.12 Precondition Failed
- 4.13 Request Entity Too Large
- 4.15 Unsupported Content-Format
Server Error 5.xx
- 5.00 Internal Server Error
- 5.01 Not Implemented
- 5.02 Bad Gateway
- 5.03 Service Unavailable
- 5.03 Service Unavailable
- 5.05 Proxying Not Supported
7. Options
7.1 Option Numbers
不同的Option有不同Option Number来表示。
Critical = (onum & 1);
UnSafe = (onum & 2);
NoCacheKey = ((onum & 0x1e) == 0x1c);
7.2 Option Value formats
- empty: zero-length sequence of bytes.
- opaque: An opaque sequence of bytes.
- uint: non-negative integer that is represented in network byte.
- string:Unicode string that is encoded using UTF-8 [RFC3629] in Net-Unicode form.
Critical/Elective Option:
根据对于未识别的Option的处理分为Critical/Elective Option。
--如果某个Option未被识别,如果是Elective Option,直接忽略;如果是Confirmable request中的Critical Option,Server回4.02 (Bad Option)。
--Confirmable response或者Nonconfirmable message中的Critical Option,对端需要Reject the message。
--只适用于non-proxying endpoints。
Unsafe or Safe-to-Forward:
根据Proxy对于未被识别的Option的处理分为Unsafe or Safe-to-Forward Option。
Cache-Key:
Repeatable:在一个mesage中可能有一个或者多个这样的option。
7.3 Base specification Options
7.3.1 Uri-Host, Uri-Port, Uri-Path, and Uri-Query
表示一个Resource的地址。
- Uri-Host Option specifies the Internet host of the resource being requested.
- Uri-Port Option specifies the transport-layer port number of the resource.
- Uri-Path Option specifies one segment of the absolute path to the resource.
- Uri-Query Option specifies one argument parameterizing the resource.
7.3.2 Proxy-Uri and Proxy-Scheme
用于forward-proxy。
7.3.3 Content-Format
表示Message中Payload的类型。
7.3.4 Accept
表明Client可以接受哪种content format。如果Server不能回复此种content format,则回4.06 "Not Acceptable"。
7.3.5 Max-Age
表示Cached reposne 为Fresh状态的最大时间,超过这个时间,Cached Response为Not Fresh。
7.3.6 ETag
提供Resource的Server产生这个Tag,表示的是同一个Resourc。
- Response中的ETag.
- Request中的Etag.
7.3.7 Location-Path and Location-Query
Relative URI to request URL that consists either of an absolute path, a query string, or both.
7.3.8 Conditional Request Options
使Client在某种特定情况下才向Server发Request。如果条件不满足Client发了request,Server会回4.12 (Precondition Failed) Response code。
7.3.8.1 if-Match
- 通常用在resource update(PUT),条件是目标Resource或者Resource的Etag存在。
- If-Match Option的Value可以是empty string或者一个ETag。
- 有多个If-Macth Option的话,只要满足一个即可。
7.3.8.2 None-Match
- 通常用在resource update(PUT),条件是目标Resource不存在。If-Match Option没有Value。
7.3.11Size1
常用在Block-wise Transfer中。
也用在当Client的包太大时,Server回复4.13 Response code,带上Size1 Option告诉Client能接受的最大值。
7. Chching
CoAP includes a simple caching model
Cacheability determined by response code
An option number mask determines if it is a cache key
7.1 Freshness model
Freshness checked using the Max-Age Option。
- 当一个response是“Fresh”状态时,它可以直接用来处理Request,而不用去访问origin server。
- Origin server提供一个explicit expiration time(利用Max-Age Option)来决定某个response的“freshness”。
- Max-Age option默认值是60s。
- 如果Origin server不希望caching,可以设置Max-Age option的value为0。
7.2 Validation model
Validity checked using the Etag Option。
- 当一个endpoint有多个cached response,但都不“fresh”时,Request可以使用ETag Option,作用是给origin server一个机会来选择一个stored response,并且update这个resposne的freshness。这个过程叫做“validating"”或者“revalidating”。
- Server回复2.03 (Valid) response with Etag option。收到后就就会更新cached response的freshness。
所以我的理解是ETag就是一个标签(entity-tag),由提供Resource的Server生成,标签表示的是随时间变化的同一个Resource。
8. Proxying
对于Safe-to-Forward options必须forward。
Forward-Proxies
作用是代理发往Server的Request。在Request message中使用Proxy-Uri Option表明Proxy,使用Uri-Host, Uri-Port, Uri-Path, and Uri-Query Options表明origin server。
Reverse-Proxies
不使用Proxy-Uri Option。