GCC Code Coverage Report


Directory: ./
Coverage: low: ≥ 0% medium: ≥ 75.0% high: ≥ 90.0%
Coverage Exec / Excl / Total
Lines: 24.7% 43 / 0 / 174
Functions: 40.0% 10 / 0 / 25
Branches: 20.8% 15 / 0 / 72
Decisions: 25.5% 13 / - / 51

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