GCC Code Coverage Report


Directory: ./
File: firmware/console/binary/tunerstudio.cpp
Date: 2025-12-30 16:19:43
Coverage Exec Excl Total
Lines: 25.1% 43 0 171
Functions: 40.0% 10 0 25
Branches: 21.7% 15 0 69
Decisions: 27.7% 13 - 47

Line Branch Decision Exec Source
1 /**
2 * @file tunerstudio.cpp
3 * @brief Binary protocol implementation
4 *
5 * This implementation would not happen without the documentation
6 * provided by Jon Zeeff (jon@zeeff.com)
7 *
8 *
9 * @brief Integration with EFI Analytics Tuner Studio software
10 *
11 * Tuner Studio has a really simple protocol, a minimal implementation
12 * capable of displaying current engine state on the gauges would
13 * require only two commands: queryCommand and ochGetCommand
14 *
15 * queryCommand:
16 * Communication initialization command. TunerStudio sends a single byte H
17 * ECU response:
18 * One of the known ECU id strings.
19 *
20 * ochGetCommand:
21 * Request for output channels state.TunerStudio sends a single byte O
22 * ECU response:
23 * A snapshot of output channels as described in [OutputChannels] section of the .ini file
24 * The length of this block is 'ochBlockSize' property of the .ini file
25 *
26 * These two commands are enough to get working gauges. In order to start configuring the ECU using
27 * tuner studio, three more commands should be implemented:
28 *
29 * See also https://www.efianalytics.com/TunerStudio/docs/EFI%20Analytics%20ECU%20Definition%20files.pdf
30 *
31 *
32 * @date Oct 22, 2013
33 * @author Andrey Belomutskiy, (c) 2012-2020
34 *
35 * This file is part of rusEfi - see http://rusefi.com
36 *
37 * rusEfi is free software; you can redistribute it and/or modify it under the terms of
38 * the GNU General Public License as published by the Free Software Foundation; either
39 * version 3 of the License, or (at your option) any later version.
40 *
41 * rusEfi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
42 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
43 * GNU General Public License for more details.
44 *
45 * You should have received a copy of the GNU General Public License along with this program.
46 * If not, see <http://www.gnu.org/licenses/>.
47 *
48 *
49 * This file is part of rusEfi - see http://rusefi.com
50 *
51 * rusEfi is free software; you can redistribute it and/or modify it under the terms of
52 * the GNU General Public License as published by the Free Software Foundation; either
53 * version 3 of the License, or (at your option) any later version.
54 *
55 * rusEfi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
56 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
57 * GNU General Public License for more details.
58 *
59 * You should have received a copy of the GNU General Public License along with this program.
60 * If not, see <http://www.gnu.org/licenses/>.
61 *
62 */
63
64 #include "pch.h"
65
66
67 #include "tunerstudio.h"
68 #include "tunerstudio_impl.h"
69
70 #include "main_trigger_callback.h"
71 #include "flash_main.h"
72
73 #include "tunerstudio_io.h"
74 #include "malfunction_central.h"
75 #include "console_io.h"
76 #include "bluetooth.h"
77 #include "tunerstudio_io.h"
78 #include "trigger_scope.h"
79 #include "electronic_throttle.h"
80 #include "live_data.h"
81 #include "efi_quote.h"
82
83 #include <string.h>
84 #include "bench_test.h"
85 #include "status_loop.h"
86 #include "mmc_card.h"
87
88 #if EFI_SIMULATOR
89 #include "rusEfiFunctionalTest.h"
90 #endif /* EFI_SIMULATOR */
91
92 #include "board_overrides.h"
93
94 #if EFI_TUNER_STUDIO
95
96 // We have TS protocol limitation: offset within one settings page is uin16_t type.
97 static_assert(sizeof(*config) <= 65536);
98
99 static void printErrorCounters() {
100 efiPrintf("TunerStudio size=%d / total=%d / errors=%d / H=%d / O=%d / P=%d / B=%d / 9=%d",
101 sizeof(engine->outputChannels), tsState.totalCounter, tsState.errorCounter, tsState.queryCommandCounter,
102 tsState.outputChannelsCommandCounter, tsState.readPageCommandsCounter, tsState.burnCommandCounter,
103 tsState.readScatterCommandsCounter);
104 efiPrintf("TunerStudio C=%d",
105 tsState.writeChunkCommandCounter);
106 efiPrintf("TunerStudio errors: underrun=%d / overrun=%d / crc=%d / unrecognized=%d / outofrange=%d / other=%d",
107 tsState.errorUnderrunCounter, tsState.errorOverrunCounter, tsState.errorCrcCounter,
108 tsState.errorUnrecognizedCommand, tsState.errorOutOfRange, tsState.errorOther);
109 }
110
111 namespace {
112 Timer calibrationsVeWriteTimer;
113 }
114
115 #if 0
116 static void printScatterList(TsChannelBase* tsChannel) {
117 efiPrintf("Scatter list (global)");
118 for (size_t i = 0; i < TS_SCATTER_OFFSETS_COUNT; i++) {
119 uint16_t packed = tsChannel->highSpeedOffsets[i];
120 uint16_t type = packed >> 13;
121 uint16_t offset = packed & 0x1FFF;
122
123 if (type == 0)
124 continue;
125 size_t size = 1 << (type - 1);
126
127 efiPrintf("%02d offset 0x%04x size %d", i, offset, size);
128 }
129 }
130 #endif
131
132 /* 1S */
133 #define TS_COMMUNICATION_TIMEOUT TIME_MS2I(1000)
134 /* 10mS when receiving byte by byte */
135 #define TS_COMMUNICATION_TIMEOUT_SHORT TIME_MS2I(10)
136
137 static void resetTs() {
138 memset(&tsState, 0, sizeof(tsState));
139 }
140
141 static void printTsStats(void) {
142 #ifdef EFI_CONSOLE_RX_BRAIN_PIN
143 efiPrintf("Primary UART RX %s", hwPortname(EFI_CONSOLE_RX_BRAIN_PIN));
144 efiPrintf("Primary UART TX %s", hwPortname(EFI_CONSOLE_TX_BRAIN_PIN));
145 #endif /* EFI_CONSOLE_RX_BRAIN_PIN */
146
147 #if EFI_USB_SERIAL
148 printUsbConnectorStats();
149 #endif // EFI_USB_SERIAL
150
151 printErrorCounters();
152
153 // TODO: find way to get all tsChannel
154 //printScatterList();
155 }
156
157 static void setTsSpeed(int value) {
158 engineConfiguration->tunerStudioSerialSpeed = value;
159 printTsStats();
160 }
161
162 void tunerStudioDebug(TsChannelBase* tsChannel, const char *msg) {
163 #if EFI_TUNER_STUDIO_VERBOSE
164 efiPrintf("%s: %s", tsChannel->name, msg);
165 #endif /* EFI_TUNER_STUDIO_VERBOSE */
166 }
167
168 1 static uint8_t* getWorkingPageAddr(TsChannelBase* tsChannel, size_t page, size_t offset) {
169 // TODO: validate offset?
170
1/3
✓ Branch 0 taken 1 time.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
1 switch (page) {
171
1/1
✓ Decision 'true' taken 1 time.
1 case TS_PAGE_SETTINGS:
172 // TODO: why engineConfiguration, not config
173 // TS has access to whole persistent_config_s
174 1 return (uint8_t*)engineConfiguration + offset;
175 #if EFI_TS_SCATTER
176 case TS_PAGE_SCATTER_OFFSETS:
177 return (uint8_t *)tsChannel->page1.highSpeedOffsets + offset;
178 #endif
179 #if EFI_LTFT_CONTROL
180 case TS_PAGE_LTFT_TRIMS:
181 return (uint8_t *)ltftGetTsPage() + offset;
182 #endif
183 default:
184 // technical dept: TS seems to try to read the 3 pages sequentially, does not look like we properly handle 'EFI_TS_SCATTER=FALSE'
185 tunerStudioError(tsChannel, "ERROR: page address out of range");
186 return nullptr;
187 }
188 }
189
190 1 static constexpr size_t getTunerStudioPageSize(size_t page) {
191
1/3
✓ Branch 0 taken 1 time.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
1 switch (page) {
192
1/1
✓ Decision 'true' taken 1 time.
1 case TS_PAGE_SETTINGS:
193 1 return TOTAL_CONFIG_SIZE;
194 #if EFI_TS_SCATTER
195 case TS_PAGE_SCATTER_OFFSETS:
196 return PAGE_SIZE_1;
197 #endif
198 #if EFI_LTFT_CONTROL
199 case TS_PAGE_LTFT_TRIMS:
200 return ltftGetTsPageSize();
201 #endif
202 default:
203 return 0;
204 }
205 }
206
207 // Validate whether the specified offset and count would cause an overrun in the tune.
208 // Returns true if an overrun would occur.
209 1 static bool validateOffsetCount(size_t page, size_t offset, size_t count, TsChannelBase* tsChannel) {
210 1 size_t allowedSize = getTunerStudioPageSize(page);
211
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 time.
1/2
✗ Decision 'true' not taken.
✓ Decision 'false' taken 1 time.
1 if (offset + count > allowedSize) {
212 efiPrintf("TS: Project mismatch? Too much configuration requested %d+%d>%d", offset, count, allowedSize);
213 tunerStudioError(tsChannel, "ERROR: out of range");
214 sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE, "bad_offset");
215 return true;
216 }
217
218 1 return false;
219 }
220
221 1 static void sendOkResponse(TsChannelBase *tsChannel) {
222 1 tsChannel->sendResponse(TS_CRC, nullptr, 0);
223 1 }
224
225 void sendErrorCode(TsChannelBase *tsChannel, uint8_t code, const char *msg) {
226 //TODO uncomment once I have test it myself
227 UNUSED(msg);
228 //if (msg != DO_NOT_LOG) {
229 // efiPrintf("TS <- Err: %d [%s]", code, msg);
230 //}
231
232 switch (code) {
233 case TS_RESPONSE_UNDERRUN:
234 tsState.errorUnderrunCounter++;
235 break;
236 case TS_RESPONSE_OVERRUN:
237 tsState.errorOverrunCounter++;
238 break;
239 case TS_RESPONSE_CRC_FAILURE:
240 tsState.errorCrcCounter++;
241 break;
242 case TS_RESPONSE_UNRECOGNIZED_COMMAND:
243 tsState.errorUnrecognizedCommand++;
244 break;
245 case TS_RESPONSE_OUT_OF_RANGE:
246 tsState.errorOutOfRange++;
247 break;
248 default:
249 tsState.errorOther++;
250 break;
251 }
252
253 tsChannel->writeCrcResponse(code);
254 }
255
256 void TunerStudio::sendErrorCode(TsChannelBase* tsChannel, uint8_t code, const char *msg) {
257 ::sendErrorCode(tsChannel, code, msg);
258 }
259
260 PUBLIC_API_WEAK bool isBoardAskingTriggerTsRefresh() {
261 return false;
262 }
263
264 531079 bool needToTriggerTsRefresh() {
265 531079 return !engine->engineTypeChangeTimer.hasElapsedSec(1);
266 }
267
268 void onApplyPreset() {
269 engine->engineTypeChangeTimer.reset();
270 }
271
272 1 PUBLIC_API_WEAK bool isTouchingVe(uint16_t offset, uint16_t count) {
273 1 return isTouchingArea(offset, count, offsetof(persistent_config_s, veTable), sizeof(config->veTable));
274 }
275
276 1 static void onCalibrationWrite(uint16_t page, uint16_t offset, uint16_t count) {
277
3/6
✓ Branch 0 taken 1 time.
✗ Branch 1 not taken.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 time.
✗ Branch 5 not taken.
✓ Branch 6 taken 1 time.
1/2
✗ Decision 'true' not taken.
✓ Decision 'false' taken 1 time.
1 if ((page == TS_PAGE_SETTINGS) && isTouchingVe(offset, count)) {
278 calibrationsVeWriteTimer.reset();
279 }
280 1 }
281
282 3 bool isTouchingArea(uint16_t offset, uint16_t count, int areaStart, int areaSize) {
283
2/2
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 1 time.
2/2
✓ Decision 'true' taken 2 times.
✓ Decision 'false' taken 1 time.
3 if (offset + count < areaStart) {
284 // we are touching below for instance VE table
285 2 return false;
286 }
287
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 time.
1/2
✗ Decision 'true' not taken.
✓ Decision 'false' taken 1 time.
1 if (offset > areaStart + areaSize) {
288 // we are touching after for instance VE table
289 return false;
290 }
291 // else - we are touching it!
292 1 return true;
293 }
294
295 /**
296 * This command is needed to make the whole transfer a bit faster
297 */
298 1 void TunerStudio::handleWriteChunkCommand(TsChannelBase* tsChannel, uint16_t page, uint16_t offset, uint16_t count,
299 void *content) {
300 1 tsState.writeChunkCommandCounter++;
301
302 1 efiPrintf("TS -> Page %d write chunk offset %d count %d (output_count=%d)",
303 page, offset, count, tsState.outputChannelsCommandCounter);
304
305
306
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 1 time.
1/2
✗ Decision 'true' not taken.
✓ Decision 'false' taken 1 time.
1 if (validateOffsetCount(page, offset, count, tsChannel)) {
307 tunerStudioError(tsChannel, "ERROR: WR out of range");
308 sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE);
309 return;
310 }
311
312 1 uint8_t * addr = getWorkingPageAddr(tsChannel, page, offset);
313
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 time.
1/2
✗ Decision 'true' not taken.
✓ Decision 'false' taken 1 time.
1 if (addr == nullptr) {
314 sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE, "ERROR: WR invalid page");
315 return;
316 }
317
318 1 onCalibrationWrite(page, offset, count);
319
320 // Special case
321
1/2
✓ Branch 0 taken 1 time.
✗ Branch 1 not taken.
1/2
✓ Decision 'true' taken 1 time.
✗ Decision 'false' not taken.
1 if (page == TS_PAGE_SETTINGS) {
322
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 1 time.
1/2
✗ Decision 'true' not taken.
✓ Decision 'false' taken 1 time.
1 if (isLockedFromUser()) {
323 sendErrorCode(tsChannel, TS_RESPONSE_UNRECOGNIZED_COMMAND, "locked");
324 return;
325 }
326
327 // Skip the write if a preset was just loaded - we don't want to overwrite it
328 // [tag:popular_vehicle]
329
1/2
✓ Branch 1 taken 1 time.
✗ Branch 2 not taken.
1/2
✓ Decision 'true' taken 1 time.
✗ Decision 'false' not taken.
1 if (!needToTriggerTsRefresh()) {
330 1 memcpy(addr, content, count);
331 } else {
332 efiPrintf("Ignoring TS -> Page %d write chunk offset %d count %d (output_count=%d)",
333 page,
334 offset,
335 count,
336 tsState.outputChannelsCommandCounter
337 );
338 }
339 // Force any board configuration options that humans shouldn't be able to change
340 // huh, why is this NOT within above 'needToTriggerTsRefresh()' condition?
341 1 call_board_override(custom_board_ConfigOverrides);
342 } else {
343 memcpy(addr, content, count);
344 }
345
346 1 sendOkResponse(tsChannel);
347 }
348
349 void TunerStudio::handleCrc32Check(TsChannelBase *tsChannel, uint16_t page, uint16_t offset, uint16_t count) {
350 tsState.crc32CheckCommandCounter++;
351
352 // Ensure we are reading from in bounds
353 if (validateOffsetCount(page, offset, count, tsChannel)) {
354 tunerStudioError(tsChannel, "ERROR: CRC out of range");
355 sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE);
356 return;
357 }
358
359 const uint8_t* start = getWorkingPageAddr(tsChannel, page, offset);
360 if (start == nullptr) {
361 sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE, "ERROR: CRC invalid page");
362 return;
363 }
364
365 uint32_t crc = SWAP_UINT32(crc32(start, count));
366 tsChannel->sendResponse(TS_CRC, (const uint8_t *) &crc, 4);
367 efiPrintf("TS <- Get CRC page %d offset %d count %d result %08x", page, offset, count, (unsigned int)crc);
368 // todo: rename to onConfigCrc?
369 ConfigurationWizard::onConfigOnStartUpOrBurn(false);
370 }
371
372 #if EFI_TS_SCATTER
373 void TunerStudio::handleScatteredReadCommand(TsChannelBase* tsChannel) {
374 tsState.readScatterCommandsCounter++;
375
376 int totalResponseSize = 0;
377 for (size_t i = 0; i < TS_SCATTER_OFFSETS_COUNT; i++) {
378 uint16_t packed = tsChannel->page1.highSpeedOffsets[i];
379 uint16_t type = packed >> 13;
380
381 size_t size = type == 0 ? 0 : 1 << (type - 1);
382 #if EFI_SIMULATOR
383 // printf("handleScatteredReadCommand 0x%x %d %d\n", packed, size, offset);
384 #endif /* EFI_SIMULATOR */
385 totalResponseSize += size;
386 }
387 #if EFI_SIMULATOR
388 // printf("totalResponseSize %d\n", totalResponseSize);
389 #endif /* EFI_SIMULATOR */
390
391 // Command part of CRC
392 uint32_t crc = tsChannel->writePacketHeader(TS_RESPONSE_OK, totalResponseSize);
393
394 uint8_t dataBuffer[8];
395 for (size_t i = 0; i < TS_SCATTER_OFFSETS_COUNT; i++) {
396 uint16_t packed = tsChannel->page1.highSpeedOffsets[i];
397 uint16_t type = packed >> 13;
398 uint16_t offset = packed & 0x1FFF;
399
400 if (type == 0)
401 continue;
402 size_t size = 1 << (type - 1);
403
404 // write each data point and CRC incrementally
405 copyRange(dataBuffer, getLiveDataFragments(), offset, size);
406 tsChannel->write(dataBuffer, size, false);
407 crc = crc32inc((void*)dataBuffer, crc, size);
408 }
409 #if EFI_SIMULATOR
410 // printf("CRC %x\n", crc);
411 #endif /* EFI_SIMULATOR */
412 // now write total CRC
413 *(uint32_t*)dataBuffer = SWAP_UINT32(crc);
414 tsChannel->write(dataBuffer, 4, true);
415 tsChannel->flush();
416 }
417 #endif // EFI_TS_SCATTER
418
419 void TunerStudio::handlePageReadCommand(TsChannelBase* tsChannel, uint16_t page, uint16_t offset, uint16_t count) {
420 tsState.readPageCommandsCounter++;
421 efiPrintf("TS <- Page %d read chunk offset %d count %d", page, offset, count);
422
423 if (validateOffsetCount(page, offset, count, tsChannel)) {
424 tunerStudioError(tsChannel, "ERROR: RD out of range");
425 sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE);
426 return;
427 }
428
429 uint8_t* addr = getWorkingPageAddr(tsChannel, page, offset);
430 if (page == TS_PAGE_SETTINGS) {
431 if (isLockedFromUser()) {
432 // to have rusEFI console happy just send all zeros within a valid packet
433 addr = (uint8_t*)&tsChannel->scratchBuffer + TS_PACKET_HEADER_SIZE;
434 memset(addr, 0, count);
435 }
436 }
437
438 if (addr == nullptr) {
439 sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE, "ERROR: RD invalid page");
440 return;
441 }
442
443 tsChannel->sendResponse(TS_CRC, addr, count);
444 #if EFI_TUNER_STUDIO_VERBOSE
445 // efiPrintf("Sending %d done", count);
446 #endif
447 }
448 #endif // EFI_TUNER_STUDIO
449
450 void requestBurn() {
451 #if !EFI_UNIT_TEST
452 onBurnRequest();
453
454 #if EFI_CONFIGURATION_STORAGE
455 setNeedToWriteConfiguration();
456 #endif /* EFI_CONFIGURATION_STORAGE */
457 #endif // !EFI_UNIT_TEST
458 }
459
460 #if EFI_TUNER_STUDIO
461 /**
462 * 'Burn' command is a command to commit the changes
463 */
464 static void handleBurnCommand(TsChannelBase* tsChannel, uint16_t page) {
465 if (page == TS_PAGE_SETTINGS) {
466 Timer t;
467 t.reset();
468
469 tsState.burnCommandCounter++;
470
471 efiPrintf("TS -> Burn");
472 validateConfigOnStartUpOrBurn(true);
473
474 // problem: 'popular vehicles' dialog has 'Burn' which is very NOT helpful on that dialog
475 // since users often click both buttons producing a conflict between ECU desire to change settings
476 // and TS desire to send TS calibration snapshot into ECU
477 // Skip the burn if a preset was just loaded - we don't want to overwrite it
478 // [tag:popular_vehicle]
479 if (!needToTriggerTsRefresh()) {
480 efiPrintf("TS -> Burn, we are allowed to burn");
481 requestBurn();
482 }
483 efiPrintf("Burned in %.1fms", t.getElapsedSeconds() * 1e3);
484 #if EFI_TS_SCATTER
485 } else if (page == TS_PAGE_SCATTER_OFFSETS) {
486 /* do nothing */
487 #endif
488 } else {
489 sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE, "ERROR: Burn invalid page");
490 return;
491 }
492
493 tsChannel->writeCrcResponse(TS_RESPONSE_BURN_OK);
494 }
495
496 #if (EFI_PROD_CODE || EFI_SIMULATOR)
497
498 static bool isKnownCommand(char command) {
499 return command == TS_HELLO_COMMAND || command == TS_READ_COMMAND || command == TS_OUTPUT_COMMAND
500 || command == TS_BURN_COMMAND
501 || command == TS_CHUNK_WRITE_COMMAND || command == TS_EXECUTE
502 || command == TS_IO_TEST_COMMAND
503 #if EFI_SIMULATOR
504 || command == TS_SIMULATE_CAN
505 #endif // EFI_SIMULATOR
506 #if EFI_TS_SCATTER
507 || command == TS_GET_SCATTERED_GET_COMMAND
508 #endif
509 || command == TS_SET_LOGGER_SWITCH
510 || command == TS_GET_COMPOSITE_BUFFER_DONE_DIFFERENTLY
511 || command == TS_GET_TEXT
512 || command == TS_CRC_CHECK_COMMAND
513 || command == TS_GET_FIRMWARE_VERSION
514 || command == TS_PERF_TRACE_BEGIN
515 || command == TS_PERF_TRACE_GET_BUFFER
516 || command == TS_GET_CONFIG_ERROR
517 || command == TS_QUERY_BOOTLOADER;
518 }
519
520 /**
521 * rusEfi own test command
522 */
523 static void handleTestCommand(TsChannelBase* tsChannel) {
524 tsState.testCommandCounter++;
525 char testOutputBuffer[64];
526 /**
527 * this is NOT a standard TunerStudio command, this is my own
528 * extension of the protocol to simplify troubleshooting
529 */
530 tunerStudioDebug(tsChannel, "got T (Test)");
531 tsChannel->write((const uint8_t*)QUOTE(SIGNATURE_HASH), sizeof(QUOTE(SIGNATURE_HASH)));
532
533 chsnprintf(testOutputBuffer, sizeof(testOutputBuffer), " %d %d", engine->engineState.warnings.lastErrorCode, tsState.testCommandCounter);
534 tsChannel->write((const uint8_t*)testOutputBuffer, strlen(testOutputBuffer));
535
536 chsnprintf(testOutputBuffer, sizeof(testOutputBuffer), " uptime=%ds ", (int)getTimeNowS());
537 tsChannel->write((const uint8_t*)testOutputBuffer, strlen(testOutputBuffer));
538
539 chsnprintf(testOutputBuffer, sizeof(testOutputBuffer), __DATE__ " %s\r\n", PROTOCOL_TEST_RESPONSE_TAG);
540 tsChannel->write((const uint8_t*)testOutputBuffer, strlen(testOutputBuffer));
541
542 if (hasFirmwareError()) {
543 const char* error = getCriticalErrorMessage();
544 chsnprintf(testOutputBuffer, sizeof(testOutputBuffer), "error=%s\r\n", error);
545 tsChannel->write((const uint8_t*)testOutputBuffer, strlen(testOutputBuffer));
546 }
547 tsChannel->flush();
548 }
549
550 static void handleGetConfigErorr(TsChannelBase* tsChannel) {
551 const char* errorMessage = hasFirmwareError() ? getCriticalErrorMessage() : getConfigErrorMessage();
552 if (strlen(errorMessage) == 0) {
553 // Check for engine's warning code
554 errorMessage = engine->engineState.warnings.getWarningMessage();
555 }
556 tsChannel->sendResponse(TS_CRC, reinterpret_cast<const uint8_t*>(errorMessage), strlen(errorMessage), true);
557 }
558
559 /**
560 * this command is part of protocol initialization
561 *
562 * Query with CRC takes place while re-establishing connection
563 * Query without CRC takes place on TunerStudio startup
564 */
565 void TunerStudio::handleQueryCommand(TsChannelBase* tsChannel, ts_response_format_e mode) {
566 tsState.queryCommandCounter++;
567 const char *signature = getTsSignature();
568
569 efiPrintf("TS <- Query signature: %s", signature);
570 tsChannel->sendResponse(mode, (const uint8_t *)signature, strlen(signature) + 1);
571 }
572
573 /**
574 * handle non CRC wrapped command
575 *
576 * @return true if legacy command was processed, false otherwise
577 */
578 bool TunerStudio::handlePlainCommand(TsChannelBase* tsChannel, uint8_t command) {
579 // Bail fast if guaranteed not to be a plain command
580 if (command == 0) {
581 return false;
582 } else if (command == TS_HELLO_COMMAND || command == TS_QUERY_COMMAND) {
583 // We interpret 'Q' as TS_HELLO_COMMAND, since TS uses hardcoded 'Q' during ECU detection (scan all serial ports)
584 efiPrintf("Got naked Query command");
585 handleQueryCommand(tsChannel, TS_PLAIN);
586 return true;
587 } else if (command == TS_TEST_COMMAND || command == 'T') {
588 handleTestCommand(tsChannel);
589 return true;
590 } else if (command == TS_COMMAND_F) {
591 /**
592 * http://www.msextra.com/forums/viewtopic.php?f=122&t=48327
593 * Response from TS support: This is an optional command *
594 * "The F command is used to find what ini. file needs to be loaded in TunerStudio to match the controller.
595 * If you are able to just make your firmware ignore the command that would work.
596 * Currently on some firmware versions the F command is not used and is just ignored by the firmware as a unknown command."
597 */
598
599 tunerStudioDebug(tsChannel, "not ignoring F");
600 tsChannel->write((const uint8_t *)TS_PROTOCOL, strlen(TS_PROTOCOL));
601 tsChannel->flush();
602 return true;
603 } else {
604 // This wasn't a valid command
605 return false;
606 }
607 }
608
609 TunerStudio tsInstance;
610
611 static int tsProcessOne(TsChannelBase* tsChannel) {
612 assertStack("communication", ObdCode::STACK_USAGE_COMMUNICATION, EXPECTED_REMAINING_STACK, -1);
613
614 if (!tsChannel->isReady()) {
615 chThdSleepMilliseconds(10);
616 return -1;
617 }
618
619 tsState.totalCounter++;
620
621 uint8_t firstByte;
622 size_t received = tsChannel->readTimeout(&firstByte, 1, TS_COMMUNICATION_TIMEOUT);
623 #if EFI_SIMULATOR
624 logMsg("received %d\r\n", received);
625 #endif // EFI_SIMULATOR
626
627 if (received != 1) {
628 //tunerStudioError("ERROR: no command");
629 #if EFI_BLUETOOTH_SETUP
630 if (tsChannel == getBluetoothChannel()) {
631 // no data in a whole second means time to disconnect BT
632 // assume there's connection loss and notify the bluetooth init code
633 bluetoothSoftwareDisconnectNotify(getBluetoothChannel());
634 }
635 #endif /* EFI_BLUETOOTH_SETUP */
636 tsChannel->in_sync = false;
637 return -1;
638 }
639
640 if (tsInstance.handlePlainCommand(tsChannel, firstByte)) {
641 return 0;
642 }
643
644 uint8_t secondByte;
645 /* second byte should be received within minimal delay */
646 received = tsChannel->readTimeout(&secondByte, 1, TS_COMMUNICATION_TIMEOUT_SHORT);
647 if (received != 1) {
648 tunerStudioError(tsChannel, "TS: ERROR: no second byte");
649 tsChannel->in_sync = false;
650 return -1;
651 }
652
653 uint16_t incomingPacketSize = firstByte << 8 | secondByte;
654 size_t expectedSize = incomingPacketSize + TS_PACKET_TAIL_SIZE;
655
656 if ((incomingPacketSize == 0) || (expectedSize > sizeof(tsChannel->scratchBuffer))) {
657 if (tsChannel->in_sync) {
658 efiPrintf("process_ts: channel=%s invalid size: %d", tsChannel->name, incomingPacketSize);
659 tunerStudioError(tsChannel, "process_ts: ERROR: packet size");
660 /* send error only if previously we were in sync */
661 sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE, "invalid size");
662 }
663 tsChannel->in_sync = false;
664 return -1;
665 }
666
667 char command;
668 if (tsChannel->in_sync) {
669 /* we are in sync state, packet size should be correct so lets receive full packet and then check if command is supported
670 * otherwise (if abort reception in middle of packet) it will break synchronization and cause error on next packet */
671 received = tsChannel->readTimeout((uint8_t*)(tsChannel->scratchBuffer), expectedSize, TS_COMMUNICATION_TIMEOUT);
672 command = tsChannel->scratchBuffer[0];
673
674 if (received != expectedSize) {
675 /* print and send error as we were in sync */
676 efiPrintf("Got only %d bytes while expecting %d for command 0x%02x", received,
677 expectedSize, command);
678 tunerStudioError(tsChannel, "ERROR: not enough bytes in stream");
679 // MS serial protocol spec: There was a timeout before all data was received. (25ms per character.)
680 sendErrorCode(tsChannel, TS_RESPONSE_UNDERRUN, "underrun");
681 tsChannel->in_sync = false;
682 return -1;
683 }
684
685 if (!isKnownCommand(command)) {
686 /* print and send error as we were in sync */
687 efiPrintf("unexpected command %x", command);
688 sendErrorCode(tsChannel, TS_RESPONSE_UNRECOGNIZED_COMMAND, "unknown");
689 tsChannel->in_sync = false;
690 return -1;
691 }
692 } else {
693 /* receive only command byte to check if it is supported */
694 received = tsChannel->readTimeout((uint8_t*)(tsChannel->scratchBuffer), 1, TS_COMMUNICATION_TIMEOUT_SHORT);
695 command = tsChannel->scratchBuffer[0];
696
697 if (!isKnownCommand(command)) {
698 /* do not report any error as we are not in sync */
699 return -1;
700 }
701
702 received = tsChannel->readTimeout((uint8_t*)(tsChannel->scratchBuffer) + 1, expectedSize - 1, TS_COMMUNICATION_TIMEOUT);
703 if (received != expectedSize - 1) {
704 /* do not report any error as we are not in sync */
705 return -1;
706 }
707 }
708
709 #if EFI_SIMULATOR
710 logMsg("command %c\r\n", command);
711 #endif
712
713 uint32_t expectedCrc = *(uint32_t*) (tsChannel->scratchBuffer + incomingPacketSize);
714
715 expectedCrc = SWAP_UINT32(expectedCrc);
716
717 uint32_t actualCrc = crc32(tsChannel->scratchBuffer, incomingPacketSize);
718 if (actualCrc != expectedCrc) {
719 /* send error only if previously we were in sync */
720 if (tsChannel->in_sync) {
721 efiPrintf("TunerStudio: command %c actual CRC %x/expected %x", tsChannel->scratchBuffer[0],
722 (unsigned int)actualCrc, (unsigned int)expectedCrc);
723 tunerStudioError(tsChannel, "ERROR: CRC issue");
724 sendErrorCode(tsChannel, TS_RESPONSE_CRC_FAILURE, "crc_issue");
725 tsChannel->in_sync = false;
726 }
727 return -1;
728 }
729
730 /* we were able to receive known command with correct crc and size! */
731 tsChannel->in_sync = true;
732
733 int success = tsInstance.handleCrcCommand(tsChannel, tsChannel->scratchBuffer, incomingPacketSize);
734
735 if (!success) {
736 efiPrintf("got unexpected TunerStudio command %x:%c", command, command);
737 return -1;
738 }
739
740 return 0;
741 }
742
743 void TunerstudioThread::ThreadTask() {
744 auto channel = setupChannel();
745
746 // No channel configured for this thread, cancel.
747 if (!channel || !channel->isConfigured()) {
748 return;
749 }
750
751 // Until the end of time, process incoming messages.
752 while (true) {
753 if (tsProcessOne(channel) == 0) {
754 onDataArrived(true);
755 } else {
756 onDataArrived(false);
757 }
758 }
759 }
760
761 #endif // EFI_PROD_CODE || EFI_SIMULATOR
762 tunerstudio_counters_s tsState;
763
764 void tunerStudioError(TsChannelBase* tsChannel, const char *msg) {
765 tunerStudioDebug(tsChannel, msg);
766 printErrorCounters();
767 tsState.errorCounter++;
768 }
769
770 #if EFI_PROD_CODE || EFI_SIMULATOR
771
772 extern CommandHandler console_line_callback;
773
774 // see also handleQueryCommand
775 // see also printVersionForConsole
776 static void handleGetVersion(TsChannelBase* tsChannel) {
777 char versionBuffer[32];
778 chsnprintf(versionBuffer, sizeof(versionBuffer), "%s v%d@%u", FRONTEND_TITLE_BAR_NAME, getRusEfiVersion(), SIGNATURE_HASH);
779 tsChannel->sendResponse(TS_CRC, (const uint8_t *) versionBuffer, strlen(versionBuffer) + 1);
780 }
781
782 #if EFI_TEXT_LOGGING
783 static void handleGetText(TsChannelBase* tsChannel) {
784 tsState.textCommandCounter++;
785
786 printOverallStatus();
787
788 size_t outputSize;
789 const char* output = swapOutputBuffers(&outputSize);
790 #if EFI_SIMULATOR
791 logMsg("get test sending [%d]\r\n", outputSize);
792 #endif
793
794 tsChannel->writeCrcPacket(TS_RESPONSE_OK, reinterpret_cast<const uint8_t*>(output), outputSize, true);
795 #if EFI_SIMULATOR
796 logMsg("sent [%d]\r\n", outputSize);
797 #endif // EFI_SIMULATOR
798 }
799 #endif // EFI_TEXT_LOGGING
800
801 void TunerStudio::handleExecuteCommand(TsChannelBase* tsChannel, char *data, int incomingPacketSize) {
802 data[incomingPacketSize] = 0;
803 char *trimmed = efiTrim(data);
804 #if EFI_SIMULATOR
805 logMsg("execute [%s]\r\n", trimmed);
806 #endif // EFI_SIMULATOR
807 (console_line_callback)(trimmed);
808
809 tsChannel->writeCrcResponse(TS_RESPONSE_OK);
810 }
811
812 int TunerStudio::handleCrcCommand(TsChannelBase* tsChannel, char *data, int incomingPacketSize) {
813 ScopePerf perf(PE::TunerStudioHandleCrcCommand);
814
815 char command = data[0];
816 data++;
817
818 const uint16_t* data16 = reinterpret_cast<uint16_t*>(data);
819
820 // only few command have page argument, default page is 0
821 uint16_t page = 0;
822 uint16_t offset = 0;
823 uint16_t count = 0;
824
825 // command may not have offset field - keep safe default value
826 // not used by .ini at the moment TODO actually use that version of the command in the .ini
827 if (incomingPacketSize >= 3) {
828 offset = data16[0];
829 }
830 // command may not have count/size filed - keep safe default value
831 if (incomingPacketSize >= 5) {
832 count = data16[1];
833 }
834
835 switch(command)
836 {
837 case TS_OUTPUT_COMMAND:
838 if (incomingPacketSize == 1) {
839 // Read command with no offset and size - read whole livedata
840 count = TS_TOTAL_OUTPUT_SIZE;
841 }
842 cmdOutputChannels(tsChannel, offset, count);
843 break;
844 case TS_OUTPUT_ALL_COMMAND:
845 offset = 0;
846 count = TS_TOTAL_OUTPUT_SIZE;
847 // TS will not use this command until ochBlockSize is bigger than blockingFactor and prefer ochGetCommand :(
848 cmdOutputChannels(tsChannel, offset, count);
849 break;
850 case TS_GET_SCATTERED_GET_COMMAND:
851 #if EFI_TS_SCATTER
852 handleScatteredReadCommand(tsChannel);
853 #else
854 criticalError("Slow/wireless mode not supported");
855 #endif // EFI_TS_SCATTER
856 break;
857 case TS_HELLO_COMMAND:
858 tunerStudioDebug(tsChannel, "got Query command");
859 handleQueryCommand(tsChannel, TS_CRC);
860 break;
861 case TS_GET_FIRMWARE_VERSION:
862 handleGetVersion(tsChannel);
863 break;
864 #if EFI_TEXT_LOGGING
865 case TS_GET_TEXT:
866 handleGetText(tsChannel);
867 break;
868 #endif // EFI_TEXT_LOGGING
869 case TS_EXECUTE:
870 handleExecuteCommand(tsChannel, data, incomingPacketSize - 1);
871 break;
872 case TS_CHUNK_WRITE_COMMAND:
873 /* command with page argument */
874 page = data16[0];
875 offset = data16[1];
876 count = data16[2];
877 handleWriteChunkCommand(tsChannel, page, offset, count, data + sizeof(TunerStudioPageRWChunkRequest));
878 break;
879 case TS_CRC_CHECK_COMMAND:
880 /* command with page argument */
881 page = data16[0];
882 offset = data16[1];
883 count = data16[2];
884 handleCrc32Check(tsChannel, page, offset, count);
885 break;
886 case TS_BURN_COMMAND:
887 /* command with page argument */
888 page = data16[0];
889 handleBurnCommand(tsChannel, page);
890 break;
891 case TS_READ_COMMAND:
892 /* command with page argument */
893 page = data16[0];
894 offset = data16[1];
895 count = data16[2];
896 handlePageReadCommand(tsChannel, page, offset, count);
897 break;
898 case TS_TEST_COMMAND:
899 [[fallthrough]];
900 case 'T':
901 handleTestCommand(tsChannel);
902 break;
903 case TS_GET_CONFIG_ERROR:
904 handleGetConfigErorr(tsChannel);
905 break;
906 #if EFI_SIMULATOR
907 case TS_SIMULATE_CAN:
908 void handleWrapCan(TsChannelBase* tsChannel, char *data, int incomingPacketSize);
909 handleWrapCan(tsChannel, data, incomingPacketSize - 1);
910 break;
911 #endif // EFI_SIMULATOR
912 case TS_IO_TEST_COMMAND:
913 #if EFI_SIMULATOR || EFI_PROD_CODE
914 //TODO: Why did we process `TS_IO_TEST_COMMAND` only in prod code? I've just turned it on for simulator as well, because
915 // I need test this functionality with simulator as well. We need to review the cases when we really need to turn off
916 // `TS_IO_TEST_COMMAND` processing. Do we really need guards below?
917 {
918 uint16_t subsystem = SWAP_UINT16(data16[0]);
919 uint16_t index = SWAP_UINT16(data16[1]);
920
921 executeTSCommand(subsystem, index);
922 }
923 #endif /* EFI_SIMULATOR || EFI_PROD_CODE */
924 sendOkResponse(tsChannel);
925 break;
926 #if EFI_TOOTH_LOGGER
927 case TS_SET_LOGGER_SWITCH:
928 switch(data[0]) {
929 case TS_COMPOSITE_ENABLE:
930 EnableToothLogger();
931 break;
932 case TS_COMPOSITE_DISABLE:
933 DisableToothLogger();
934 break;
935 case TS_COMPOSITE_READ:
936 {
937 auto toothBuffer = GetToothLoggerBufferNonblocking();
938
939 if (toothBuffer) {
940 tsChannel->sendResponse(TS_CRC, reinterpret_cast<const uint8_t*>(toothBuffer->buffer), toothBuffer->nextIdx * sizeof(composite_logger_s), true);
941
942 ReturnToothLoggerBuffer(toothBuffer);
943 } else {
944 // TS asked for a tooth logger buffer, but we don't have one to give it.
945 sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE, DO_NOT_LOG);
946 }
947 }
948 break;
949 #ifdef TRIGGER_SCOPE
950 case TS_TRIGGER_SCOPE_ENABLE:
951 triggerScopeEnable();
952 break;
953 case TS_TRIGGER_SCOPE_DISABLE:
954 triggerScopeDisable();
955 break;
956 case TS_TRIGGER_SCOPE_READ:
957 {
958 const auto& buffer = triggerScopeGetBuffer();
959
960 if (buffer) {
961 tsChannel->sendResponse(TS_CRC, buffer.get<uint8_t>(), buffer.size(), true);
962 } else {
963 // TS asked for a tooth logger buffer, but we don't have one to give it.
964 sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE, DO_NOT_LOG);
965 }
966 }
967 break;
968 #endif // TRIGGER_SCOPE
969 default:
970 // dunno what that was, send NAK
971 return false;
972 }
973
974 sendOkResponse(tsChannel);
975
976 break;
977 case TS_GET_COMPOSITE_BUFFER_DONE_DIFFERENTLY:
978 {
979 EnableToothLoggerIfNotEnabled();
980
981 auto toothBuffer = GetToothLoggerBufferNonblocking();
982
983 if (toothBuffer) {
984 tsChannel->sendResponse(TS_CRC, reinterpret_cast<const uint8_t*>(toothBuffer->buffer), toothBuffer->nextIdx * sizeof(composite_logger_s), true);
985
986 ReturnToothLoggerBuffer(toothBuffer);
987 } else {
988 // TS asked for a tooth logger buffer, but we don't have one to give it.
989 sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE, DO_NOT_LOG);
990 }
991 }
992
993 break;
994 #else // EFI_TOOTH_LOGGER
995 case TS_GET_COMPOSITE_BUFFER_DONE_DIFFERENTLY:
996 sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE, DO_NOT_LOG);
997 break;
998 #endif /* EFI_TOOTH_LOGGER */
999 #if ENABLE_PERF_TRACE
1000 case TS_PERF_TRACE_BEGIN:
1001 perfTraceEnable();
1002 sendOkResponse(tsChannel);
1003 break;
1004 case TS_PERF_TRACE_GET_BUFFER:
1005 {
1006 auto trace = perfTraceGetBuffer();
1007 tsChannel->sendResponse(TS_CRC, trace.get<uint8_t>(), trace.size(), true);
1008 }
1009
1010 break;
1011 #else
1012 case TS_PERF_TRACE_BEGIN:
1013 criticalError("TS_PERF_TRACE not supported");
1014 break;
1015 case TS_PERF_TRACE_GET_BUFFER:
1016 criticalError("TS_PERF_TRACE_GET_BUFFER not supported");
1017 break;
1018 #endif /* ENABLE_PERF_TRACE */
1019 case TS_QUERY_BOOTLOADER: {
1020 uint8_t bldata = TS_QUERY_BOOTLOADER_NONE;
1021 #if EFI_USE_OPENBLT
1022 bldata = TS_QUERY_BOOTLOADER_OPENBLT;
1023 #endif
1024
1025 tsChannel->sendResponse(TS_CRC, &bldata, 1, false);
1026 break;
1027 }
1028 default:
1029 sendErrorCode(tsChannel, TS_RESPONSE_UNRECOGNIZED_COMMAND, "unknown_command");
1030 static char tsErrorBuff[80];
1031 chsnprintf(tsErrorBuff, sizeof(tsErrorBuff), "ERROR: ignoring unexpected command %d [%c]", command, command);
1032 tunerStudioError(tsChannel, tsErrorBuff);
1033 return false;
1034 }
1035
1036 return true;
1037 }
1038
1039 #endif // EFI_PROD_CODE || EFI_SIMULATOR
1040
1041
1/1
✓ Decision 'true' taken 60 times.
60 bool isTuningVeNow() {
1042
1/2
✓ Branch 0 taken 60 times.
✗ Branch 1 not taken.
60 int tuningDetector = engineConfiguration->isTuningDetectorEnabled ? 0 : 20;
1043 60 return !calibrationsVeWriteTimer.hasElapsedSec(tuningDetector);
1044 }
1045
1046 void startTunerStudioConnectivity() {
1047 // Assert tune & output channel struct sizes
1048 static_assert(sizeof(persistent_config_s) == TOTAL_CONFIG_SIZE, "TS datapage size mismatch");
1049 // useful trick if you need to know how far off is the static_assert
1050 //char (*__kaboom)[sizeof(persistent_config_s)] = 1;
1051 // another useful trick
1052 //static_assert(offsetof (engine_configuration_s,HD44780_e) == 700);
1053
1054 memset(&tsState, 0, sizeof(tsState));
1055
1056 addConsoleAction("tsinfo", printTsStats);
1057 addConsoleAction("reset_ts", resetTs);
1058 addConsoleActionI("set_ts_speed", setTsSpeed);
1059
1060 #if EFI_BLUETOOTH_SETUP
1061 // module initialization start (it waits for disconnect and then communicates to the module)
1062 // Usage: "bluetooth_hc06 <baud> <name> <pincode>"
1063 // Example: "bluetooth_hc06 38400 rusefi 1234"
1064 // bluetooth_jdy 115200 alphax 1234
1065 addConsoleActionSSS("bluetooth_hc05", [](const char *baudRate, const char *name, const char *pinCode) {
1066 bluetoothStart(BLUETOOTH_HC_05, baudRate, name, pinCode);
1067 });
1068 addConsoleActionSSS("bluetooth_hc06", [](const char *baudRate, const char *name, const char *pinCode) {
1069 bluetoothStart(BLUETOOTH_HC_06, baudRate, name, pinCode);
1070 });
1071 addConsoleActionSSS("bluetooth_bk", [](const char *baudRate, const char *name, const char *pinCode) {
1072 bluetoothStart(BLUETOOTH_BK3231, baudRate, name, pinCode);
1073 });
1074 addConsoleActionSSS("bluetooth_jdy", [](const char *baudRate, const char *name, const char *pinCode) {
1075 bluetoothStart(BLUETOOTH_JDY_3x, baudRate, name, pinCode);
1076 });
1077 addConsoleActionSSS("bluetooth_jdy31", [](const char *baudRate, const char *name, const char *pinCode) {
1078 bluetoothStart(BLUETOOTH_JDY_31, baudRate, name, pinCode);
1079 });
1080 #endif /* EFI_BLUETOOTH_SETUP */
1081 }
1082
1083 #endif // EFI_TUNER_STUDIO
1084