---
# System prepended metadata

title: 自訂義訊息

---

自訂義訊息
===

檔案結構
---
:::spoiler core
> :::spoiler bin
> 二進檔案存放
> :::
> :::spoiler core
>> :::spoiler include
>> 抬頭檔 
>> :::
>> :::spoiler src
>> 文件檔
>> :::
> :::
> :::spoiler msg
> 訊息檔案添加區
> :::
:::

新增檔案
---
在<font face="monospace" color="green">msg</font>區選擇合適的<font face="monospace" color="green">.hpp</font>檔中，加入你需要的訊息定義，格式如範例<font face="monospace" color="green">motor_msg.hpp</font>：

```cpp=
struct MotorModule : public BaseMsg
{
    public:
    double angle[2] = {0, 0};
    double twist[2] = {0, 0};
    double current[2] = {0, 0};
    double torque[2] = {0, 0};
    bool state[2] = {false, false};
    double pid[6] = {0, 0, 0, 0, 0, 0}; // pidpid

    template<class Archive>
    void serialize( Archive & ar )
    { 
        ar( CEREAL_NVP(state), CEREAL_NVP(angle), CEREAL_NVP(twist), CEREAL_NVP(current), CEREAL_NVP(pid), CEREAL_NVP(torque) ); 
    }

    virtual void record(std::string name, core::FileArchive &fa) override
    {
        fa(name, CORE_NVP(angle), CORE_NVP(twist), CORE_NVP(current), CORE_NVP(state), CORE_NVP(pid), CORE_NVP(torque));
    }
    virtual void show() override
    {
        std::cout << "Motor Module\n";
        std::cout << "state:\t" << state[0] << "\t" << state[1] << "\n";
        std::cout << "angle:\t" << angle[0] << "\t" << angle[1] << "\n";
        std::cout << "twist:\t" << twist[0] << "\t" << twist[1] << "\n";
        std::cout << "current:\t" << current[0] << "\t" << current[1] << "\n";
        std::cout << "torque:\t" << torque[0] << "\t" << torque[1] << "\n";
        std::cout << "pid 1:\t" << pid[0] << "\t" << pid[1] << "\t" << pid[2] << "\n";
        std::cout << "pid 2:\t" << pid[3] << "\t" << pid[4] << "\t" << pid[5] << "\n";
    }
};

```
public中定義需要存放的資料，例如angle、twist等，serialize的函數定義是只要序列化的資料，基本上格式就是CEREAL_NVP(your-data)，record函數是用於記錄的函數，格式定義一樣如上，最後是show函數是用以debug時使用的，定義你想輸出的訊息即可，若這些都有定義了即可使用預先編譯的紀錄功能與debug功能，詳見教學篇[讀寫檔案]()。

```cpp=
CEREAL_REGISTER_TYPE(motor_msg::MotorModule);
CEREAL_REGISTER_POLYMORPHIC_RELATION(BaseMsg, motor_msg::MotorModule)
```
最後在文件尾部加入這兩行即可。

重新編譯
---

與[**README**](https://hackmd.io/@peichunhuang/SypJOLSlh)的<font face="monospace" color="ultramarine blue">**“專案核心：編譯與安裝”**</font>篇一致。