采用 领域模型(Domain Model)+ 设备能力模型(Capability)+ 属性模型(Property)+ 服务模型(Service) 的设计方式
智能家居中可能有:
温湿度传感器:温度、湿度、电池电量。
智能开关:开关状态、功率、电压、电流。
空调:开关、模式、温度、风速、摆风。
扫地机器人:运行状态、清扫模式、电量、清扫区域。
门锁:门锁状态、用户、密码、开锁记录。
这些设备的属性差异很大,而且同一种设备也可能支持不同的功能。
核心思路是:设备本身只描述身份和基本信息,具体功能通过动态能力和属性扩展。
MongoDB:设备数据解构
- devices
- device_services
- device_properties
- device_states
2.3 属性模型
实际项目中,将动态属性值使用 JsonElement 表示,尤其是需要兼容不同设备协议和 JSON 数据源时。
using System.Text.Json;
public class DeviceProperty
{
public string Id { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
// temperature、humidity、power、on
public string Code { get; set; } = string.Empty;
// bool、int、long、float、double、string
public string DataType { get; set; } = "string";
// 属性值
public JsonElement Value { get; set; }
// 单位
public string? Unit { get; set; }
// read、write、notify
public List<string> Access { get; set; } = [];
// MIoT PIID
public int? InstanceId { get; set; }
public DateTime? UpdatedAt { get; set; }
}赋值:
var temperature = new DeviceProperty
{
Id = "temperature",
Code = "temperature",
DataType = "float",
Value = JsonSerializer.SerializeToElement(26.5),
Unit = "celsius"
};
var power = new DeviceProperty
{
Id = "power",
Code = "power",
DataType = "float",
Value = JsonSerializer.SerializeToElement(120.5),
Unit = "watt"
};
var isOn = new DeviceProperty
{
Id = "on",
Code = "on",
DataType = "bool",
Value = JsonSerializer.SerializeToElement(true)
};读取:
double temp = temperature.Value.GetDouble();
double watts = power.Value.GetDouble();
bool status = isOn.Value.GetBoolean();JSON 序列化时,数字仍然是数字,布尔值仍然是布尔值
output
{
"id": "device-001",
"name": "客厅空调",
"manufacturer": "Xiaomi",
"model": "AC-001",
"deviceType": "climate",
"protocol": "MIOT",
"identifier": "123456789",
"isOnline": true,
"services": [
{
"id": "service-001",
"name": "空调服务",
"type": "climate",
"instanceId": 2,
"properties": [
{
"id": "prop-001",
"name": "开关",
"code": "on",
"dataType": "bool",
"value": true,
"access": ["read", "write", "notify"]
},
{
"id": "prop-002",
"name": "目标温度",
"code": "target_temperature",
"dataType": "float",
"value": 25,
"unit": "celsius",
"access": ["read", "write", "notify"]
}
],
"actions": [],
"events": []
}
]
}