【CAPL】this关键字 及 在on signal, on message中的使用
this关键字
this关键字的介绍
- this是一个特殊的关键字,
- 用于指代当前事件处理函数中引用当前触发事件的对象(如信号、消息、定时器等),简化代码编写。
- 其具体含义取决于所在的事件上下文。
![图片]()
1. 在信号事件(on signal)中使用
- 在on signal 信号名事件中,this表示当前触发事件的信号值,等价于
$信号名。 - 示例:
on signal VehicleSpeed{}中:write("当前车速:", this, " km/h");- this 等价于
$VehicleSpeed,代表当前信号值
- this 等价于
2. 在消息事件(on message)中使用
- 在on message 消息名/ID事件中,this表示当前接收到的消息对象,
- 可通过
this.信号名或this.byte(n)访问消息的信号或原始数据。 - 示例:
on message ABS_1{}或on message 0xC0{}中- on message + (message ID)也可
write("收到消息,ID:", this.id, ",数据长度:", this.dlc);write("消息中的车速信号:", this.VehicleSpeed);
- 注意:
- on message中,正确的语法是
this.信号名,(不加$) - 而
this.$信号名:会导致 “parse error”
- on message中,正确的语法是
3. 在定时器事件(on timer)中使用
- 在on timer 定时器名事件中,this表示当前触发的定时器对象,
- 通常用于获取定时器的剩余时间(较少使用)
- 示例:on timer myTimer {}中的
- this 代表当前定时器对象
write("定时器触发,剩余时间:", this.time); // 通常为0(触发时已到期)
4. 在系统事件中使用
- 在一些系统事件(如on error、on key等)中,this表示事件相关的参数。
- on key 示例:
// 捕获键盘按键事件 on key { // this 代表按下的键值(如 'a'、'1' 等) write("按下了按键:", this); } - on error示例:
// 捕获错误事件 on error { // this 代表错误代码 write("发生错误,错误代码:", this); }
注意
- 在
on signal和on message中,用this即可,就不使用$了
代码示例:on signal中的this
-
on signal中,this表示当前信号signal
// 当VehicleSpeed信号更新时,立即判断其值 on signal VehicleSpeed { // 获取当前信号值(this表示当前信号) float currentSpeed; currentSpeed = this;//注:变量必须先声明,后赋值,否则报错 // 判断逻辑 if(currentSpeed > 120) { write("警告:车速超过120km/h!当前值:", currentSpeed); } else if(currentSpeed <= 0 && currentSpeed != -1) // 假设-1表示无效值 { write("提示:车速为0或负值,当前值:", currentSpeed); } }
代码示例:on message中的this
-
on message中,this表示当前报文message
// 当接收到ABS_1消息(包含VehicleSpeed信号)时判断 on message ABS_1 { // 从消息中提取信号值 float speed; speed = this.VehicleSpeed; // 结合消息信息判断(如消息ID、DLC等) if(this.id == 0xC0 && this.dlc == 8) // 确认消息ID和长度 { if(speed > 80) { write("ABS_1消息:车速超过80km/h,当前值:", speed); } } }


浙公网安备 33010602011771号