fork/GramFirmware

git clone https://git.julia.blue/fork/GramFirmware

CarVacrebase to configurator818d962

gram
8.4 KiB276 linesraw
1/*
2 * This file is part of HayBox
3 * Copyright (C) 2024 Jonathan Haylett
4 *
5 * HayBox is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation.
8 *
9 * This software is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this software. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "comms/ConfiguratorBackend.hpp"
19
20#include "core/InputSource.hpp"
21#include "core/Persistence.hpp"
22#include "reboot.hpp"
23
24#include <pb_arduino.h>
25#include <pb_decode.h>
26#include <pb_encode.h>
27
28ConfiguratorBackend::ConfiguratorBackend(
29    InputState &inputs,
30    InputSource **input_sources,
31    size_t input_source_count,
32    Config &config,
33    Stream &stream
34)
35    : CommunicationBackend(inputs, input_sources, input_source_count),
36      _in(stream),
37      _out(stream),
38      _base_stream(stream),
39      _config(config) {}
40
41CommunicationBackendId ConfiguratorBackend::BackendId() {
42    return COMMS_BACKEND_CONFIGURATOR;
43}
44
45void ConfiguratorBackend::SendReport() {
46    int data = ReadByte();
47    if (data < 0) {
48        if (data == _in.EOP) {
49            SkipToNextPacket();
50        }
51        return;
52    }
53
54    Command command = (Command)data;
55    switch (command) {
56        case CMD_GET_DEVICE_INFO:
57            HandleGetDeviceInfo();
58            break;
59        case CMD_GET_CONFIG:
60            HandleGetConfig();
61            break;
62        case CMD_SET_CONFIG:
63            HandleSetConfig();
64            break;
65        case CMD_REBOOT_FIRMWARE:
66            reboot_firmware();
67            break;
68        case CMD_REBOOT_BOOTLOADER:
69            reboot_bootloader();
70            break;
71        case CMD_UNSPECIFIED:
72        default:
73            HandleUnknownCommand(command);
74            break;
75    }
76
77    SkipToNextPacket();
78}
79
80size_t ConfiguratorBackend::ReadPacket(uint8_t *buffer, size_t max_len) {
81    size_t bytes_read = 0;
82    while (!_in.available()) {
83        delay(1);
84    }
85    while (true) {
86        int result = _in.read();
87        if (result == _in.EOF) {
88            continue;
89        }
90        if (result == _in.EOP) {
91            break;
92        }
93        buffer[bytes_read++] = result;
94        if (bytes_read >= max_len) {
95            _in.next();
96            return bytes_read;
97        }
98    }
99    _in.next();
100
101    return bytes_read;
102}
103
104int ConfiguratorBackend::ReadByte() {
105    if (!_base_stream.available()) {
106        return -1;
107    }
108    return _in.read();
109}
110
111void ConfiguratorBackend::SkipToNextPacket() {
112    _in.next();
113}
114
115bool ConfiguratorBackend::WritePacket(Command command_id, uint8_t *buffer, size_t len) {
116    _out.write((uint8_t)command_id);
117    for (size_t i = 0; i < len; i++) {
118        _out.write(buffer[i]);
119    }
120    return _out.end();
121}
122
123bool ConfiguratorBackend::HandleGetDeviceInfo() {
124    static const DeviceInfo device_info = {
125        FIRMWARE_NAME,
126        FIRMWARE_VERSION,
127        DEVICE_NAME,
128    };
129
130    // Ensure device info encodes correctly.
131    size_t size;
132    if (!pb_get_encoded_size(&size, DeviceInfo_fields, &device_info)) {
133        char errmsg[] = "Failed to encode device info";
134        WritePacket(CMD_ERROR, (uint8_t *)errmsg, sizeof(errmsg));
135        return false;
136    }
137
138    _out.write(CMD_SET_DEVICE_INFO);
139    pb_ostream_t ostream = as_pb_ostream(_out);
140    pb_encode(&ostream, DeviceInfo_fields, &device_info);
141    return _out.end();
142}
143
144bool ConfiguratorBackend::HandleGetConfig() {
145    if (!persistence.CheckSavedConfig()) {
146        char errmsg[] = "Config file is invalid";
147        WritePacket(CMD_ERROR, (uint8_t *)errmsg, sizeof(errmsg));
148        return false;
149    }
150
151    // Write raw config data to output stream.
152    _out.write(CMD_SET_CONFIG);
153    persistence.LoadConfigRaw(_out, false);
154    return _out.end();
155}
156
157bool ConfiguratorBackend::HandleSetConfig() {
158    // Reset config defaults first, so config is completely replaced rather than merged.
159    _config = Config_init_default;
160
161    pb_istream_t istream = as_pb_istream(_in);
162    if (!pb_decode(&istream, Config_fields, &_config)) {
163        char errmsg[100];
164        size_t errmsg_len =
165            snprintf(errmsg, sizeof(errmsg), "Failed to decode config: %s", istream.errmsg);
166        WritePacket(CMD_ERROR, (uint8_t *)errmsg, errmsg_len);
167
168        // Restore old config.
169        persistence.LoadConfig(_config);
170        return false;
171    }
172
173    if (_config.default_backend_config > _config.communication_backend_configs_count) {
174        char errmsg[75];
175        size_t errmsg_len = snprintf(
176            errmsg,
177            sizeof(errmsg),
178            "Default backend ID is %d but only %d backend configs are defined",
179            (uint8_t)_config.default_backend_config,
180            (uint8_t)_config.communication_backend_configs_count
181        );
182        WritePacket(CMD_ERROR, (uint8_t *)errmsg, errmsg_len);
183        return false;
184    }
185
186    for (size_t i = 0; i < _config.communication_backend_configs_count; i++) {
187        uint8_t default_mode_id = _config.communication_backend_configs[i].default_mode_config;
188        if (default_mode_id > _config.game_mode_configs_count) {
189            char errmsg[75];
190            size_t errmsg_len = snprintf(
191                errmsg,
192                sizeof(errmsg),
193                "Default mode ID is %d for backend %d but only %d modes are defined",
194                (uint8_t)default_mode_id,
195                (uint8_t)i + 1,
196                (uint8_t)_config.game_mode_configs_count
197            );
198            WritePacket(CMD_ERROR, (uint8_t *)errmsg, errmsg_len);
199            return false;
200        }
201    }
202
203    for (size_t i = 0; i < _config.game_mode_configs_count; i++) {
204        const GameModeConfig &gamemode_config = _config.game_mode_configs[i];
205        uint8_t keyboard_mode_id = gamemode_config.keyboard_mode_config;
206        uint8_t custom_mode_id = gamemode_config.custom_mode_config;
207
208        if (keyboard_mode_id > 0 && gamemode_config.mode_id != MODE_KEYBOARD) {
209            char errmsg[80];
210            size_t errmsg_len = snprintf(
211                errmsg,
212                sizeof(errmsg),
213                "keyboard_mode_id is set for game mode %d but mode_id is not MODE_KEYBOARD",
214                (uint8_t)i + 1
215            );
216            WritePacket(CMD_ERROR, (uint8_t *)errmsg, errmsg_len);
217            return false;
218        }
219
220        if (custom_mode_id > 0 && gamemode_config.mode_id != MODE_CUSTOM) {
221            char errmsg[75];
222            size_t errmsg_len = snprintf(
223                errmsg,
224                sizeof(errmsg),
225                "custom_mode_id is set for game mode %d but mode_id is not MODE_CUSTOM",
226                (uint8_t)i + 1
227            );
228            WritePacket(CMD_ERROR, (uint8_t *)errmsg, errmsg_len);
229            return false;
230        }
231
232        if (keyboard_mode_id > _config.keyboard_modes_count) {
233            char errmsg[85];
234            size_t errmsg_len = snprintf(
235                errmsg,
236                sizeof(errmsg),
237                "Keyboard mode ID %d is for game mode %d but only %d keyboard modes are defined",
238                (uint8_t)keyboard_mode_id,
239                (uint8_t)i + 1,
240                (uint8_t)_config.keyboard_modes_count
241            );
242            WritePacket(CMD_ERROR, (uint8_t *)errmsg, errmsg_len);
243            return false;
244        }
245
246        if (custom_mode_id > _config.custom_modes_count) {
247            char errmsg[85];
248            size_t errmsg_len = snprintf(
249                errmsg,
250                sizeof(errmsg),
251                "Custom mode ID %d is for game mode config %d but only %d custom modes are defined",
252                (uint8_t)custom_mode_id,
253                (uint8_t)i + 1,
254                (uint8_t)_config.custom_modes_count
255            );
256            WritePacket(CMD_ERROR, (uint8_t *)errmsg, errmsg_len);
257            return false;
258        }
259    }
260
261    if (!persistence.SaveConfig(_config)) {
262        char errmsg[] = "Failed to save config to memory";
263        WritePacket(CMD_ERROR, (uint8_t *)errmsg, sizeof(errmsg));
264        return false;
265    }
266
267    WritePacket(CMD_SUCCESS, nullptr, 0);
268    return true;
269}
270
271bool ConfiguratorBackend::HandleUnknownCommand(Command command) {
272    char errmsg[50];
273    size_t errmsg_len =
274        snprintf(errmsg, sizeof(errmsg), "Unknown command ID: %d", (uint8_t)command);
275    return WritePacket(CMD_ERROR, (uint8_t *)errmsg, errmsg_len);
276}