CoAP 驱动
PlantPulse Edge 的 CoAP 驱动是一个封装了 Eclipse Californium 3.13.0 库的 Java 实现。 它通过 GET / PUT 访问低功耗 IoT 设备(RFC 7252)的资源 URI。
源码:plantpulse.driver.protocol.coap.*
| 类 | 职责 |
|---|---|
CoAPDriver | ProtocolDriver 实现 — connect/read(GET)/write(PUT)/close,按资源维护 CoapClient 缓存 |
库:
lib/californium-core-3.13.0.jarlib/element-connector-3.13.0.jar
操作流程
[connect] CoapClient(baseUri) 생성 → setConnected(true)
↓
[read] resource path → resourceUri = baseUri + "/" + path
→ resourceClients.computeIfAbsent(uri, CoapClient::new)
→ CoapClient.get() (synchronous)
→ resp.isSuccess() ? resp.getResponseText() : ""
↓
[write] resourceClients.computeIfAbsent(uri, CoapClient::new)
→ CoapClient.put(value, MediaTypeRegistry.TEXT_PLAIN /* 0 */)
→ resp.isSuccess()
↓
[close] 모든 CoapClient.shutdown() + resourceClients.clear()
CoAP 基于 UDP,因此是 无连接 的 — 仅创建客户端对象即被视为 "已连接"。 实际设备可用性在首次读取时才确认。
选项(BasicDriverSource.options)
此驱动没有选项。 连接所使用的值只有 host 和 port。
dtls、psk-identity、psk-key 也无效驱动始终以 coap:// 创建连接 URI。即使在选项中添加 dtls=true,或
将 port 指定为 DTLS 标准端口 5684,仍会以明文 CoAP 发送 — 且不会报错,
因此很容易误以为已加密。
对于需要 DTLS 的设备,请在设备前部署 DTLS 终结网关,并从该网关的 明文侧使用本驱动进行读取。
请求超时也无法指定。将直接应用 Californium 的默认值。
对于响应较慢的设备,请通过增加采集周期(timecycle)来代替超时设置。
地址(资源路径)格式
| 格式 | 转换结果 |
|---|---|
/sensors/temperature | coap://host:5683/sensors/temperature |
sensors/temperature | coap://host:5683/sensors/temperature(自动补充前导 /) |
/.well-known/core | 设备的资源发现 — 已注册资源列表(CoRE Link Format) |
每个资源的 CoapClient 会被缓存以复用 socket。在 close() 时全部关闭。
响应处理
| Californium 响应 | 驱动处理 |
|---|---|
resp == null | read = "",write = false |
resp.isSuccess()(2.xx) | read = resp.getResponseText(),write = true |
resp.getCode() 错误(4.xx / 5.xx) | 警告日志 + read = "",write = false |
CoAP 响应文本与 mediaType 无关,直接作为 String 返回 — 如果设备以 JSON 响应,
则由调用方(PlantPulse 的 JsonExtract)负责解码。CBOR 响应会以文本形式展示,因此需要单独的解码器(当前不支持)。
单元测试
test/java/plantpulse/driver/protocol/coap/CoAPDriverTest.java — 13 个方法:
- 类加载 + 初始状态
- 元数据(isWriteSupported / isExternal / getDriverSource)
- 未连接时 read / write 安全性(无 NPE)
- close() 安全性
baseUri()— 显式 / 默认端口resourceUri()— 前导/自动补充getDebugBaseUrl()—coap://host:port
无网络调用的构建隔离测试(./gradlew test 绿色)。