CAPL报文信号接收和发送
CAPL报文接收实现
CAPL通过on message事件处理程序实现报文接收功能,这是CAPL的核心特性之一。
一、基本接收语法
// 全家变量
byte gsignal;
// xxx->报文IP
on message xxx
{// 处理接收到的CAN消息// 比如把报文中的某个信号赋值给全局变量xxx.signal=gsignal;
}
实例:
includes {
}variables {// 声明变量用于存储接收到的数据int engineSpeed;
}// 接收ID为0x100的报文
on message 0x100 {// 通过this访问接收到的报文对象engineSpeed = this.word(0); // 从第0字节读取2字节数据write("Engine Speed: %d RPM", engineSpeed);// 访问报文其他属性write("Message ID: 0x%X", this.id);write("DLC: %d", this.dlc);write("Channel: %d", this.can);
}// 接收所有报文(通配符*)
on message * {write("Received Message - ID: 0x%X", this.id);
}
二、CAPL报文发送实现
CAPL使用output()函数发送CAN报文,支持单次发送和周期性发送
基本发送语法
message <ID或名称> msg;
msg.byte(n) = value; // 设置数据字节
output(msg); // 发送报文
发送示例代码
includes {
}variables {message 0x200 msgToSend; // 定义要发送的报文msTimer sendTimer; // 定义定时器用于周期发送int sendCount = 0; // 发送计数器
}// 启动时初始化并开始周期发送
on start {msgToSend.dlc = 8; // 设置数据长度setTimerCyclic(sendTimer, 100); // 启动100ms周期定时器
}// 定时器回调函数
on timer sendTimer {// 设置报文数据msgToSend.byte(0) = sendCount % 256;msgToSend.byte(1) = 0x12;// 发送报文output(msgToSend);write("Sent message, count: %d", sendCount);sendCount++;setTimer(sendTimer, 100); // 重置定时器
}// 按键触发发送
on key 'a' {msgToSend.byte(0) = 0xFF;output(msgToSend);write("Sent special message on key press");
}
三、信号级操作
对于DBC中定义的信号,CAPL提供了更高级的信号操作方式
{
}variables {message EngineStatus msgEngine; // DBC中定义的报文double currentSpeed;
}// 接收信号值变化
on signal VehicleSpeed {currentSpeed = getSignal(VehicleSpeed); // 获取信号物理值write("Vehicle speed changed to: %.1f km/h", currentSpeed);
}// 修改并发送信号
on key 's' {// 两种方式设置信号值msgEngine.EngineRPM = 1500; // 直接赋值setSignal(EngineTemp, 85.5); // 使用setSignal函数output(msgEngine);write("Sent engine status with modified signals");
}