阿里云IoT平台将设备事件上报划分为三类:信息、告警与故障。简单来说,事件是指设备主动发出的通知消息,后台系统需要及时响应和处理。
1)定义事件
登录阿里云物联网控制台,进入产品管理页面,在“自定义功能”中选择添加一个事件。具体操作步骤可参考以下截图。


2)上传事件的方法
CZGL.AliIoTClient 提供了四种灵活的事件上传方式,满足不同场景需求:
public int Thing_Event_Post(string eventName, string content, [bool isToLower = True])
public int Thing_Event_Post(string eventName, string content, [bool isToLower = True], [System.Text.Encoding encoding = null])
public int Thing_Event_Post(TModel model, string eventName, [bool isToLower = True])
public int Thing_Event_Post(TModel model, string eventName, [bool isToLower = True], [System.Text.Encoding encoding = null])
参数说明:
- eventName:事件标识符名称
- content:Alink JSON 内容
- isToLower:是否将 JSON 转换为小写
- encoding:自定义 Alink JSON 的编码方式
- model:与事件对应的模型对象
第一种方法需要手动拼接 JSON 后再上传;第二种在第一种基础上增加了编码自定义选项;第三、四种则直接传入模型对象,由库内部自动完成 JSON 序列化。
3)编写事件模型
每次只能上传一个事件,每个事件对应一个模型或一个 Alink JSON。使用 CZGL.AliIoTClient 时,每次上传都需指定事件名称。
按照之前在控制台定义的事件结构,我们来构建一个模型。先看一下最终要生成的 Alink JSON 格式:
{
"id": "123",
"version": "1.0",
"params": {
"value": {
"temperature": 100.1
},
"time": 1524448722000
},
"method": "thing.event.cpuerror.post"
}
对应的 C# 模型代码如下:
public class Cpuerror
{
public Cpuerror()
{
@params = new Params();
}
public string id { get { return DateTime.Now.Ticks.ToString(); } set { } }
public string version { get { return "1.0"; } set { } }
public Params @params { get; set; }
public class Params
{
public Params()
{
value = new Value();
}
public Value value { get; set; }
public long time { get { return AliIoTClientJson.GetUnixTime(); } set { } }
public class Value
{
public float temperature { get; set; }
}
}
public string @method { get { return "thing.event.cpuerror.post"; } set { } }
}
一个事件对应一个类。如果事件包含多个输出参数,在 Value 类中全部定义即可:
public class Value
{
public float temperature { get; set; }
/** 定义多个输出参数 */
}
上报事件的写法如下:
Cpuerror cpuerror = new Cpuerror();
cpuerror.@params.value.temperature = 100.1F;
client.Thing_Event_Post(cpuerror, "cpuerror", false);
4)容错
事件上传所用的 Alink JSON 具备一定的“容错”能力——也就是说,你可以在代码中增加额外属性或简化写法,系统仍能正常工作,这为编码提供了很大的便利。
比如将上面的代码稍作调整:
public class Cpuerror
{
public string name = "cpuerror";
public Cpuerror()
{
@params = new Params();
}
public string id { get { return DateTime.Now.Ticks.ToString(); } set { } }
public string version { get { return "1.0"; } set { } }
public Params @params { get; set; }
public class Params
{
public Params()
{
value = new Value();
}
public Value value { get; set; }
public long time { get { return AliIoTClientJson.GetUnixTime(); } set { } }
public class Value
{
public float temperature { get; set; }
}
}
public string @method { get { return $"thing.event.{name}.post"; } set { } }
}
Cpuerror cpuerror = new Cpuerror();
cpuerror.@params.value.temperature = 100.2F;
client.Thing_Event_Post(cpuerror, cpuerror.name, false);
消息 ID 这类字段是必须的,“可多不可少”——其他无关字段加入后不会影响上报和使用,就像上面示例中增加的 name 属性一样。

5)补充说明
(此处原文缺少后续内容,如有补充将在此处添加。)
