rusEFI
The most advanced open source ECU
tunerstudio.cpp
Go to the documentation of this file.
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  *
30  * @date Oct 22, 2013
31  * @author Andrey Belomutskiy, (c) 2012-2020
32  *
33  * This file is part of rusEfi - see http://rusefi.com
34  *
35  * rusEfi is free software; you can redistribute it and/or modify it under the terms of
36  * the GNU General Public License as published by the Free Software Foundation; either
37  * version 3 of the License, or (at your option) any later version.
38  *
39  * rusEfi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
40  * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41  * GNU General Public License for more details.
42  *
43  * You should have received a copy of the GNU General Public License along with this program.
44  * If not, see <http://www.gnu.org/licenses/>.
45  *
46  *
47  * This file is part of rusEfi - see http://rusefi.com
48  *
49  * rusEfi is free software; you can redistribute it and/or modify it under the terms of
50  * the GNU General Public License as published by the Free Software Foundation; either
51  * version 3 of the License, or (at your option) any later version.
52  *
53  * rusEfi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
54  * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
55  * GNU General Public License for more details.
56  *
57  * You should have received a copy of the GNU General Public License along with this program.
58  * If not, see <http://www.gnu.org/licenses/>.
59  *
60  */
61 
62 #include "pch.h"
63 
64 
65 #include "tunerstudio.h"
66 #include "tunerstudio_impl.h"
67 
68 #include "main_trigger_callback.h"
69 #include "flash_main.h"
70 
71 #include "tunerstudio_io.h"
72 #include "malfunction_central.h"
73 #include "console_io.h"
74 #include "bluetooth.h"
75 #include "tunerstudio_io.h"
76 #include "trigger_scope.h"
77 #include "software_knock.h"
78 #include "electronic_throttle.h"
79 #include "live_data.h"
80 
81 #include <string.h>
82 #include "bench_test.h"
83 #include "svnversion.h"
84 #include "status_loop.h"
85 #include "mmc_card.h"
86 
87 #if EFI_SIMULATOR
88 #include "rusEfiFunctionalTest.h"
89 #endif /* EFI_SIMULATOR */
90 
91 #if EFI_TUNER_STUDIO
92 
93 static void printErrorCounters() {
94  efiPrintf("TunerStudio size=%d / total=%d / errors=%d / H=%d / O=%d / P=%d / B=%d",
97  efiPrintf("TunerStudio W=%d / C=%d / P=%d", tsState.writeValueCommandCounter,
99 }
100 
101 static void printScatterList() {
102  efiPrintf("Scatter list (global)");
103  for (int i = 0; i < HIGH_SPEED_COUNT; i++) {
104  uint16_t packed = engineConfiguration->highSpeedOffsets[i];
105  uint16_t type = packed >> 13;
106  uint16_t offset = packed & 0x1FFF;
107 
108  if (type == 0)
109  continue;
110  size_t size = 1 << (type - 1);
111 
112  efiPrintf("%02d offset 0x%04x size %d", i, offset, size);
113  }
114 }
115 
116 /* 1S */
117 #define TS_COMMUNICATION_TIMEOUT TIME_MS2I(1000)
118 /* 10mS when receiving byte by byte */
119 #define TS_COMMUNICATION_TIMEOUT_SHORT TIME_MS2I(10)
120 
121 static void resetTs() {
122  memset(&tsState, 0, sizeof(tsState));
123 }
124 
125 static void printTsStats(void) {
126 #ifdef EFI_CONSOLE_RX_BRAIN_PIN
127  efiPrintf("Primary UART RX %s", hwPortname(EFI_CONSOLE_RX_BRAIN_PIN));
128  efiPrintf("Primary UART TX %s", hwPortname(EFI_CONSOLE_TX_BRAIN_PIN));
129 #endif /* EFI_CONSOLE_RX_BRAIN_PIN */
130 
131 #if EFI_USB_SERIAL
133 #endif // EFI_USB_SERIAL
134 
136 
138 }
139 
140 static void setTsSpeed(int value) {
142  printTsStats();
143 }
144 
145 void tunerStudioDebug(TsChannelBase* tsChannel, const char *msg) {
146 #if EFI_TUNER_STUDIO_VERBOSE
147  efiPrintf("%s: %s", tsChannel->name, msg);
148 #endif /* EFI_TUNER_STUDIO_VERBOSE */
149 }
150 
151 uint8_t* getWorkingPageAddr() {
152  return (uint8_t*)engineConfiguration;
153 }
154 
156  tsChannel->sendResponse(mode, NULL, 0);
157 }
158 
159 void sendErrorCode(TsChannelBase *tsChannel, uint8_t code) {
160  tsChannel->writeCrcPacket(code, nullptr, 0);
161 }
162 
163 void TunerStudio::sendErrorCode(TsChannelBase* tsChannel, uint8_t code) {
164  ::sendErrorCode(tsChannel, code);
165 }
166 
169 
170  sendOkResponse(tsChannel, mode);
171 }
172 
173 bool validateOffsetCount(size_t offset, size_t count, TsChannelBase* tsChannel);
174 
175 extern bool rebootForPresetPending;
176 
177 /**
178  * This command is needed to make the whole transfer a bit faster
179  * @note See also handleWriteValueCommand
180  */
181 void TunerStudio::handleWriteChunkCommand(TsChannelBase* tsChannel, ts_response_format_e mode, uint16_t offset, uint16_t count,
182  void *content) {
184  if (isLockedFromUser()) {
185  sendErrorCode(tsChannel, TS_RESPONSE_UNRECOGNIZED_COMMAND);
186  return;
187  }
188 
189  efiPrintf("WRITE CHUNK mode=%d o=%d s=%d", mode, offset, count);
190 
191  if (validateOffsetCount(offset, count, tsChannel)) {
192  return;
193  }
194 
195  // Skip the write if a preset was just loaded - we don't want to overwrite it
196  if (!rebootForPresetPending) {
197  uint8_t * addr = (uint8_t *) (getWorkingPageAddr() + offset);
198  memcpy(addr, content, count);
199  }
200  // Force any board configuration options that humans shouldn't be able to change
202 
203  sendOkResponse(tsChannel, mode);
204 }
205 
206 void TunerStudio::handleCrc32Check(TsChannelBase *tsChannel, ts_response_format_e mode, uint16_t offset, uint16_t count) {
208 
209  // Ensure we are reading from in bounds
210  if (validateOffsetCount(offset, count, tsChannel)) {
211  return;
212  }
213 
214 #if EFI_TS_SCATTER
215  /*
216  * highSpeedOffsets is noMsqSave, but located on settings page,
217  * zero highSpeedOffsets as TS expect all noMsqSave data to be zero during CRC matching
218  * TODO:
219  * Move highSpeedOffsets to separate page as it is done on MS devices
220  * Zero highSpeedOffsets on start and reconnect
221  * TODO:
222  * Is Crc check commang good sing of new TS session?
223  * TODO:
224  * Support settings pages!
225  */
227 #endif // EFI_TS_SCATTER
228 
229  const uint8_t* start = getWorkingPageAddr() + offset;
230 
231  uint32_t crc = SWAP_UINT32(crc32(start, count));
232  tsChannel->sendResponse(mode, (const uint8_t *) &crc, 4);
233 }
234 
235 #if EFI_TS_SCATTER
237  int totalResponseSize = 0;
238  for (int i = 0; i < HIGH_SPEED_COUNT; i++) {
239  uint16_t packed = engineConfiguration->highSpeedOffsets[i];
240  uint16_t type = packed >> 13;
241 
242  size_t size = type == 0 ? 0 : 1 << (type - 1);
243 #if EFI_SIMULATOR
244 // printf("handleScatteredReadCommand 0x%x %d %d\n", packed, size, offset);
245 #endif /* EFI_SIMULATOR */
246  totalResponseSize += size;
247  }
248 #if EFI_SIMULATOR
249 // printf("totalResponseSize %d\n", totalResponseSize);
250 #endif /* EFI_SIMULATOR */
251 
252 
253  // Command part of CRC
254  uint32_t crc = tsChannel->writePacketHeader(TS_RESPONSE_OK, totalResponseSize);
255 
256  uint8_t dataBuffer[8];
257  for (int i = 0; i < HIGH_SPEED_COUNT; i++) {
258  uint16_t packed = engineConfiguration->highSpeedOffsets[i];
259  uint16_t type = packed >> 13;
260  uint16_t offset = packed & 0x1FFF;
261 
262  if (type == 0)
263  continue;
264  size_t size = 1 << (type - 1);
265 
266  // write each data point and CRC incrementally
267  copyRange(dataBuffer, getLiveDataFragments(), offset, size);
268  tsChannel->write(dataBuffer, size, false);
269  crc = crc32inc((void*)dataBuffer, crc, size);
270  }
271 #if EFI_SIMULATOR
272 // printf("CRC %x\n", crc);
273 #endif /* EFI_SIMULATOR */
274  // now write total CRC
275  *(uint32_t*)dataBuffer = SWAP_UINT32(crc);
276  tsChannel->write(reinterpret_cast<uint8_t*>(dataBuffer), 4, true);
277  tsChannel->flush();
278 }
279 #endif // EFI_TS_SCATTER
280 
281 /**
282  * 'Write' command receives a single value at a given offset
283  * @note Writing values one by one is pretty slow
284  */
285 void TunerStudio::handleWriteValueCommand(TsChannelBase* tsChannel, ts_response_format_e mode, uint16_t offset, uint8_t value) {
286  UNUSED(tsChannel);
287  UNUSED(mode);
288 
290  if (isLockedFromUser()) {
291  sendErrorCode(tsChannel, TS_RESPONSE_UNRECOGNIZED_COMMAND);
292  return;
293  }
294 
295  tunerStudioDebug(tsChannel, "got W (Write)"); // we can get a lot of these
296 
297  if (validateOffsetCount(offset, 1, tsChannel)) {
298  return;
299  }
300 
301  // Skip the write if a preset was just loaded - we don't want to overwrite it
302  if (!rebootForPresetPending) {
303  getWorkingPageAddr()[offset] = value;
304  }
305  // Force any board configuration options that humans shouldn't be able to change
307 }
308 
309 void TunerStudio::handlePageReadCommand(TsChannelBase* tsChannel, ts_response_format_e mode, uint16_t offset, uint16_t count) {
311 
313  sendErrorCode(tsChannel, TS_RESPONSE_UNRECOGNIZED_COMMAND);
314  return;
315  }
316 
317 #if EFI_TUNER_STUDIO_VERBOSE
318  efiPrintf("READ mode=%d offset=%d size=%d", mode, offset, count);
319 #endif
320 
321  if (validateOffsetCount(offset, count, tsChannel)) {
322  return;
323  }
324 
325  uint8_t* addr;
326  if (isLockedFromUser()) {
327  // to have rusEFI console happy just send all zeros within a valid packet
328  addr = (uint8_t*)&tsChannel->scratchBuffer + SCRATCH_BUFFER_PREFIX_SIZE;
329  memset(addr, 0, count);
330  } else {
331  addr = getWorkingPageAddr() + offset;
332  }
333  tsChannel->sendResponse(mode, addr, count);
334 #if EFI_TUNER_STUDIO_VERBOSE
335 // efiPrintf("Sending %d done", count);
336 #endif
337 }
338 #endif // EFI_TUNER_STUDIO
339 
340 void requestBurn() {
341 #if !EFI_UNIT_TEST
342  onBurnRequest();
343 
344 #if EFI_CONFIGURATION_STORAGE
346 #endif /* EFI_CONFIGURATION_STORAGE */
347 #endif // !EFI_UNIT_TEST
348 }
349 
350 #if EFI_TUNER_STUDIO
351 static void sendResponseCode(ts_response_format_e mode, TsChannelBase *tsChannel, const uint8_t responseCode) {
352  if (mode == TS_CRC) {
353  tsChannel->writeCrcPacket(responseCode, nullptr, 0);
354  }
355 }
356 
357 /**
358  * 'Burn' command is a command to commit the changes
359  */
360 static void handleBurnCommand(TsChannelBase* tsChannel, ts_response_format_e mode) {
361  Timer t;
362  t.reset();
363 
365 
366  efiPrintf("got B (Burn) %s", mode == TS_PLAIN ? "plain" : "CRC");
367 
368  // Skip the burn if a preset was just loaded - we don't want to overwrite it
369  if (!rebootForPresetPending) {
370  requestBurn();
371  }
372 
373  sendResponseCode(mode, tsChannel, TS_RESPONSE_BURN_OK);
374  efiPrintf("BURN in %dms", (int)(t.getElapsedSeconds() * 1e3));
375 }
376 
377 #if (EFI_PROD_CODE || EFI_SIMULATOR)
378 
379 static bool isKnownCommand(char command) {
380  return command == TS_HELLO_COMMAND || command == TS_READ_COMMAND || command == TS_OUTPUT_COMMAND
381  || command == TS_PAGE_COMMAND || command == TS_BURN_COMMAND || command == TS_SINGLE_WRITE_COMMAND
382  || command == TS_CHUNK_WRITE_COMMAND || command == TS_EXECUTE
383  || command == TS_IO_TEST_COMMAND
384 #if EFI_SIMULATOR
385  || command == TS_SIMULATE_CAN
386 #endif // EFI_SIMULATOR
387 #if EFI_TS_SCATTER
388  || command == TS_GET_SCATTERED_GET_COMMAND
389 #endif
390  || command == TS_SET_LOGGER_SWITCH
391  || command == TS_GET_COMPOSITE_BUFFER_DONE_DIFFERENTLY
392  || command == TS_GET_TEXT
393  || command == TS_CRC_CHECK_COMMAND
394  || command == TS_GET_FIRMWARE_VERSION
395 #ifdef KNOCK_SPECTROGRAM
396  || command == TS_KNOCK_SPECTROGRAM_ENABLE
397  || command == TS_KNOCK_SPECTROGRAM_DISABLE
398 #endif
399  || command == TS_PERF_TRACE_BEGIN
400  || command == TS_PERF_TRACE_GET_BUFFER
401  || command == TS_GET_CONFIG_ERROR
402  || command == TS_QUERY_BOOTLOADER;
403 }
404 
405 /**
406  * rusEfi own test command
407  */
408 static void handleTestCommand(TsChannelBase* tsChannel) {
410  char testOutputBuffer[64];
411  /**
412  * this is NOT a standard TunerStudio command, this is my own
413  * extension of the protocol to simplify troubleshooting
414  */
415  tunerStudioDebug(tsChannel, "got T (Test)");
416  tsChannel->write((const uint8_t*)VCS_VERSION, sizeof(VCS_VERSION));
417 
418  chsnprintf(testOutputBuffer, sizeof(testOutputBuffer), " %d %d", engine->engineState.warnings.lastErrorCode, tsState.testCommandCounter);
419  tsChannel->write((const uint8_t*)testOutputBuffer, strlen(testOutputBuffer));
420 
421  chsnprintf(testOutputBuffer, sizeof(testOutputBuffer), " uptime=%ds ", (int)getTimeNowS());
422  tsChannel->write((const uint8_t*)testOutputBuffer, strlen(testOutputBuffer));
423 
424  chsnprintf(testOutputBuffer, sizeof(testOutputBuffer), __DATE__ " %s\r\n", PROTOCOL_TEST_RESPONSE_TAG);
425  tsChannel->write((const uint8_t*)testOutputBuffer, strlen(testOutputBuffer));
426 
427  if (hasFirmwareError()) {
428  const char* error = getCriticalErrorMessage();
429  chsnprintf(testOutputBuffer, sizeof(testOutputBuffer), "error=%s\r\n", error);
430  tsChannel->write((const uint8_t*)testOutputBuffer, strlen(testOutputBuffer));
431  }
432  tsChannel->flush();
433 }
434 
435 /**
436  * this command is part of protocol initialization
437  *
438  * Query with CRC takes place while re-establishing connection
439  * Query without CRC takes place on TunerStudio startup
440  */
443 #if EFI_TUNER_STUDIO_VERBOSE
444  efiPrintf("got S/H (queryCommand) mode=%d", mode);
445  printTsStats();
446 #endif // EFI_TUNER_STUDIO_VERBOSE
447  const char *signature = getTsSignature();
448  tsChannel->sendResponse(mode, (const uint8_t *)signature, strlen(signature) + 1);
449 }
450 
451 /**
452  * handle non CRC wrapped command
453  *
454  * @return true if legacy command was processed, false otherwise
455  */
456 bool TunerStudio::handlePlainCommand(TsChannelBase* tsChannel, uint8_t command) {
457  // Bail fast if guaranteed not to be a plain command
458  if (command == 0) {
459  return false;
460  } else if (command == TS_HELLO_COMMAND || command == TS_QUERY_COMMAND) {
461  // We interpret 'Q' as TS_HELLO_COMMAND, since TS uses hardcoded 'Q' during ECU detection (scan all serial ports)
462  efiPrintf("Got naked Query command");
463  handleQueryCommand(tsChannel, TS_PLAIN);
464  return true;
465  } else if (command == TS_TEST_COMMAND || command == 'T') {
466  handleTestCommand(tsChannel);
467  return true;
468  } else if (command == TS_COMMAND_F) {
469  /**
470  * http://www.msextra.com/forums/viewtopic.php?f=122&t=48327
471  * Response from TS support: This is an optional command *
472  * "The F command is used to find what ini. file needs to be loaded in TunerStudio to match the controller.
473  * If you are able to just make your firmware ignore the command that would work.
474  * Currently on some firmware versions the F command is not used and is just ignored by the firmware as a unknown command."
475  */
476 
477  tunerStudioDebug(tsChannel, "not ignoring F");
478  tsChannel->write((const uint8_t *)TS_PROTOCOL, strlen(TS_PROTOCOL));
479  tsChannel->flush();
480  return true;
481  } else {
482  // This wasn't a valid command
483  return false;
484  }
485 }
486 
488 
489 static int tsProcessOne(TsChannelBase* tsChannel) {
490  assertStack("communication", ObdCode::STACK_USAGE_COMMUNICATION, EXPECTED_REMAINING_STACK, -1);
491 
492  if (!tsChannel->isReady()) {
493  chThdSleepMilliseconds(10);
494  return -1;
495  }
496 
498 
499  uint8_t firstByte;
500  size_t received = tsChannel->readTimeout(&firstByte, 1, TS_COMMUNICATION_TIMEOUT);
501 #if EFI_SIMULATOR
502  logMsg("received %d\r\n", received);
503 #endif // EFI_SIMULATOR
504 
505  if (received != 1) {
506 // tunerStudioError("ERROR: no command");
507 #if EFI_BLUETOOTH_SETUP
508  if (tsChannel == getBluetoothChannel()) {
509  // no data in a whole second means time to disconnect BT
510  // assume there's connection loss and notify the bluetooth init code
512  }
513 #endif /* EFI_BLUETOOTH_SETUP */
514  tsChannel->in_sync = false;
515  return -1;
516  }
517 
518  if (tsInstance.handlePlainCommand(tsChannel, firstByte)) {
519  return 0;
520  }
521 
522  uint8_t secondByte;
523  /* second byte should be received within minimal delay */
524  received = tsChannel->readTimeout(&secondByte, 1, TS_COMMUNICATION_TIMEOUT_SHORT);
525  if (received != 1) {
526  tunerStudioError(tsChannel, "TS: ERROR: no second byte");
527  tsChannel->in_sync = false;
528  return -1;
529  }
530 
531  uint16_t incomingPacketSize = firstByte << 8 | secondByte;
532  size_t expectedSize = incomingPacketSize + CRC_VALUE_SIZE;
533 
534  if (incomingPacketSize == 0 || expectedSize > sizeof(tsChannel->scratchBuffer)) {
535  if (tsChannel->in_sync) {
536  efiPrintf("process_ts: channel=%s invalid size: %d", tsChannel->name, incomingPacketSize);
537  tunerStudioError(tsChannel, "process_ts: ERROR: CRC header size");
538  /* send error only if previously we were in sync */
539  sendErrorCode(tsChannel, TS_RESPONSE_UNDERRUN);
540  }
541  tsChannel->in_sync = false;
542  return -1;
543  }
544 
545  char command;
546  if (tsChannel->in_sync) {
547  /* we are in sync state, packet size should be correct so lets receive full packet and then check if command is supported
548  * otherwise (if abort reception in middle of packet) it will break synchronization and cause error on next packet */
549  received = tsChannel->readTimeout((uint8_t*)(tsChannel->scratchBuffer), expectedSize, TS_COMMUNICATION_TIMEOUT);
550  command = tsChannel->scratchBuffer[0];
551 
552  if (received != expectedSize) {
553  /* print and send error as we were in sync */
554  efiPrintf("Got only %d bytes while expecting %d for command 0x%02x", received,
555  expectedSize, command);
556  tunerStudioError(tsChannel, "ERROR: not enough bytes in stream");
557  sendErrorCode(tsChannel, TS_RESPONSE_UNDERRUN);
558  tsChannel->in_sync = false;
559  return -1;
560  }
561 
562  if (!isKnownCommand(command)) {
563  /* print and send error as we were in sync */
564  efiPrintf("unexpected command %x", command);
565  sendErrorCode(tsChannel, TS_RESPONSE_UNRECOGNIZED_COMMAND);
566  tsChannel->in_sync = false;
567  return -1;
568  }
569  } else {
570  /* receive only command byte to check if it is supported */
571  received = tsChannel->readTimeout((uint8_t*)(tsChannel->scratchBuffer), 1, TS_COMMUNICATION_TIMEOUT_SHORT);
572  command = tsChannel->scratchBuffer[0];
573 
574  if (!isKnownCommand(command)) {
575  /* do not report any error as we are not in sync */
576  return -1;
577  }
578 
579  received = tsChannel->readTimeout((uint8_t*)(tsChannel->scratchBuffer) + 1, expectedSize - 1, TS_COMMUNICATION_TIMEOUT);
580  if (received != expectedSize - 1) {
581  /* do not report any error as we are not in sync */
582  return -1;
583  }
584  }
585 
586 #if EFI_SIMULATOR
587  logMsg("command %c\r\n", command);
588 #endif
589 
590  uint32_t expectedCrc = *(uint32_t*) (tsChannel->scratchBuffer + incomingPacketSize);
591 
592  expectedCrc = SWAP_UINT32(expectedCrc);
593 
594  uint32_t actualCrc = crc32(tsChannel->scratchBuffer, incomingPacketSize);
595  if (actualCrc != expectedCrc) {
596  /* send error only if previously we were in sync */
597  if (tsChannel->in_sync) {
598  efiPrintf("TunerStudio: command %c actual CRC %x/expected %x", tsChannel->scratchBuffer[0],
599  actualCrc, expectedCrc);
600  tunerStudioError(tsChannel, "ERROR: CRC issue");
601  sendErrorCode(tsChannel, TS_RESPONSE_CRC_FAILURE);
602  tsChannel->in_sync = false;
603  }
604  return -1;
605  }
606 
607  /* we were able to receive known command with correct crc and size! */
608  tsChannel->in_sync = true;
609 
610  int success = tsInstance.handleCrcCommand(tsChannel, tsChannel->scratchBuffer, incomingPacketSize);
611 
612  if (!success) {
613  efiPrintf("got unexpected TunerStudio command %x:%c", command, command);
614  return -1;
615  }
616 
617  return 0;
618 }
619 
621  auto channel = setupChannel();
622 
623  // No channel configured for this thread, cancel.
624  if (!channel || !channel->isConfigured()) {
625  return;
626  }
627 
628  // Until the end of time, process incoming messages.
629  while (true) {
630  if (tsProcessOne(channel) == 0) {
631  onDataArrived(true);
632  } else {
633  onDataArrived(false);
634  }
635  }
636 }
637 
638 #endif // EFI_PROD_CODE || EFI_SIMULATOR
640 
641 void tunerStudioError(TsChannelBase* tsChannel, const char *msg) {
642  tunerStudioDebug(tsChannel, msg);
645 }
646 
647 #if EFI_PROD_CODE || EFI_SIMULATOR
648 
650 
651 static void handleGetVersion(TsChannelBase* tsChannel) {
652  char versionBuffer[32];
653  chsnprintf(versionBuffer, sizeof(versionBuffer), "rusEFI v%d@%s", getRusEfiVersion(), VCS_VERSION);
654  tsChannel->sendResponse(TS_CRC, (const uint8_t *) versionBuffer, strlen(versionBuffer) + 1);
655 }
656 
657 #if EFI_TEXT_LOGGING
658 static void handleGetText(TsChannelBase* tsChannel) {
660 
662 
663  size_t outputSize;
664  const char* output = swapOutputBuffers(&outputSize);
665 #if EFI_SIMULATOR
666  logMsg("get test sending [%d]\r\n", outputSize);
667 #endif
668 
669  tsChannel->writeCrcPacket(TS_RESPONSE_COMMAND_OK, reinterpret_cast<const uint8_t*>(output), outputSize, true);
670 #if EFI_SIMULATOR
671  logMsg("sent [%d]\r\n", outputSize);
672 #endif // EFI_SIMULATOR
673 }
674 #endif // EFI_TEXT_LOGGING
675 
676 void TunerStudio::handleExecuteCommand(TsChannelBase* tsChannel, char *data, int incomingPacketSize) {
677  data[incomingPacketSize] = 0;
678  char *trimmed = efiTrim(data);
679 #if EFI_SIMULATOR
680  logMsg("execute [%s]\r\n", trimmed);
681 #endif // EFI_SIMULATOR
682  (console_line_callback)(trimmed);
683 
684  tsChannel->writeCrcPacket(TS_RESPONSE_COMMAND_OK, nullptr, 0);
685 }
686 
687 int TunerStudio::handleCrcCommand(TsChannelBase* tsChannel, char *data, int incomingPacketSize) {
689 
690  char command = data[0];
691  data++;
692 
693  const uint16_t* data16 = reinterpret_cast<uint16_t*>(data);
694 
695  uint16_t offset = data16[0];
696  uint16_t count = data16[1];
697 
698  switch(command)
699  {
700  case TS_OUTPUT_COMMAND:
701  cmdOutputChannels(tsChannel, offset, count);
702  break;
703  case TS_HELLO_COMMAND:
704  tunerStudioDebug(tsChannel, "got Query command");
705  handleQueryCommand(tsChannel, TS_CRC);
706  break;
707  case TS_GET_FIRMWARE_VERSION:
708  handleGetVersion(tsChannel);
709  break;
710 #if EFI_TEXT_LOGGING
711  case TS_GET_TEXT:
712  handleGetText(tsChannel);
713  break;
714 #endif // EFI_TEXT_LOGGING
715  case TS_EXECUTE:
716  handleExecuteCommand(tsChannel, data, incomingPacketSize - 1);
717  break;
718  case TS_PAGE_COMMAND:
719  handlePageSelectCommand(tsChannel, TS_CRC);
720  break;
721  case TS_CHUNK_WRITE_COMMAND:
722  handleWriteChunkCommand(tsChannel, TS_CRC, offset, count, data + sizeof(TunerStudioWriteChunkRequest));
723  break;
724  case TS_SINGLE_WRITE_COMMAND:
725  {
726  uint8_t value = data[4];
727  handleWriteValueCommand(tsChannel, TS_CRC, offset, value);
728  }
729  break;
730  case TS_GET_SCATTERED_GET_COMMAND:
731 #if EFI_TS_SCATTER
732  handleScatteredReadCommand(tsChannel);
733 #else
734  criticalError("Slow/wireless mode not supported");
735 #endif // EFI_TS_SCATTER
736  break;
737  case TS_CRC_CHECK_COMMAND:
738  handleCrc32Check(tsChannel, TS_CRC, offset, count);
739  break;
740  case TS_BURN_COMMAND:
741  handleBurnCommand(tsChannel, TS_CRC);
742  break;
743  case TS_READ_COMMAND:
744  handlePageReadCommand(tsChannel, TS_CRC, offset, count);
745  break;
746  case TS_TEST_COMMAND:
747  [[fallthrough]];
748  case 'T':
749  handleTestCommand(tsChannel);
750  break;
751 #if EFI_SIMULATOR
752  case TS_SIMULATE_CAN:
753  void handleWrapCan(TsChannelBase* tsChannel, char *data, int incomingPacketSize);
754  handleWrapCan(tsChannel, data, incomingPacketSize - 1);
755  break;
756 #endif // EFI_SIMULATOR
757  case TS_IO_TEST_COMMAND:
758  {
759 #if EFI_PROD_CODE
760  uint16_t subsystem = SWAP_UINT16(data16[0]);
761  uint16_t index = SWAP_UINT16(data16[1]);
762 
763  executeTSCommand(subsystem, index);
764 #endif /* EFI_PROD_CODE */
765  sendOkResponse(tsChannel, TS_CRC);
766  }
767  break;
768 #if EFI_TOOTH_LOGGER
769  case TS_SET_LOGGER_SWITCH:
770  switch(data[0]) {
771  case TS_COMPOSITE_ENABLE:
773  break;
774  case TS_COMPOSITE_DISABLE:
776  break;
777  case TS_COMPOSITE_READ:
778  {
779  auto toothBuffer = GetToothLoggerBufferNonblocking();
780 
781  if (toothBuffer) {
782  tsChannel->sendResponse(TS_CRC, reinterpret_cast<const uint8_t*>(toothBuffer->buffer), toothBuffer->nextIdx * sizeof(composite_logger_s), true);
783 
784  ReturnToothLoggerBuffer(toothBuffer);
785  } else {
786  // TS asked for a tooth logger buffer, but we don't have one to give it.
787  sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE);
788  }
789  }
790  break;
791 #ifdef TRIGGER_SCOPE
792  case TS_TRIGGER_SCOPE_ENABLE:
794  break;
795  case TS_TRIGGER_SCOPE_DISABLE:
797  break;
798  case TS_TRIGGER_SCOPE_READ:
799  {
800  const auto& buffer = triggerScopeGetBuffer();
801 
802  if (buffer) {
803  tsChannel->sendResponse(TS_CRC, buffer.get<uint8_t>(), buffer.size(), true);
804  } else {
805  // TS asked for a tooth logger buffer, but we don't have one to give it.
806  sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE);
807  }
808  }
809  break;
810 #endif // TRIGGER_SCOPE
811  default:
812  // dunno what that was, send NAK
813  return false;
814  }
815 
816  sendOkResponse(tsChannel, TS_CRC);
817 
818  break;
819  case TS_GET_COMPOSITE_BUFFER_DONE_DIFFERENTLY:
820  {
822 
823  auto toothBuffer = GetToothLoggerBufferNonblocking();
824 
825  if (toothBuffer) {
826  tsChannel->sendResponse(TS_CRC, reinterpret_cast<const uint8_t*>(toothBuffer->buffer), toothBuffer->nextIdx * sizeof(composite_logger_s), true);
827 
828  ReturnToothLoggerBuffer(toothBuffer);
829  } else {
830  // TS asked for a tooth logger buffer, but we don't have one to give it.
831  sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE);
832  }
833  }
834 
835  break;
836 #else // EFI_TOOTH_LOGGER
837  case TS_GET_COMPOSITE_BUFFER_DONE_DIFFERENTLY:
838  sendErrorCode(tsChannel, TS_RESPONSE_OUT_OF_RANGE);
839  break;
840 #endif /* EFI_TOOTH_LOGGER */
841 #ifdef KNOCK_SPECTROGRAM
842  case TS_KNOCK_SPECTROGRAM_ENABLE:
844  sendOkResponse(tsChannel, TS_CRC);
845  break;
846  case TS_KNOCK_SPECTROGRAM_DISABLE:
848  sendOkResponse(tsChannel, TS_CRC);
849  break;
850 #endif /* KNOCK_SPECTROGRAM */
851 #if ENABLE_PERF_TRACE
852  case TS_PERF_TRACE_BEGIN:
853  perfTraceEnable();
854  sendOkResponse(tsChannel, TS_CRC);
855  break;
856  case TS_PERF_TRACE_GET_BUFFER:
857  {
858  auto trace = perfTraceGetBuffer();
859  tsChannel->sendResponse(TS_CRC, trace.get<uint8_t>(), trace.size(), true);
860  }
861 
862  break;
863 #endif /* ENABLE_PERF_TRACE */
864  case TS_GET_CONFIG_ERROR: {
865  const char* configError = getCriticalErrorMessage();
866 #if HW_CHECK_MODE
867  // analog input errors are returned as firmware error in QC mode
868  if (!hasFirmwareError()) {
869  strcpy((char*)configError, "FACTORY_MODE_PLEASE_CONTACT_SUPPORT");
870  }
871 #endif // HW_CHECK_MODE
872  tsChannel->sendResponse(TS_CRC, reinterpret_cast<const uint8_t*>(configError), strlen(configError), true);
873  break;
874  }
875  case TS_QUERY_BOOTLOADER: {
876  uint8_t bldata = TS_QUERY_BOOTLOADER_NONE;
877 #if EFI_USE_OPENBLT
878  bldata = TS_QUERY_BOOTLOADER_OPENBLT;
879 #endif
880 
881  tsChannel->sendResponse(TS_CRC, &bldata, 1, false);
882  break;
883  }
884  default:
885  sendErrorCode(tsChannel, TS_RESPONSE_UNRECOGNIZED_COMMAND);
886 static char tsErrorBuff[80];
887  chsnprintf(tsErrorBuff, sizeof(tsErrorBuff), "ERROR: ignoring unexpected command %d [%c]", command, command);
888  tunerStudioError(tsChannel, tsErrorBuff);
889  return false;
890  }
891 
892  return true;
893 }
894 
895 #endif // EFI_PROD_CODE || EFI_SIMULATOR
896 
898  // Assert tune & output channel struct sizes
899  static_assert(sizeof(persistent_config_s) == TOTAL_CONFIG_SIZE, "TS datapage size mismatch");
900 // useful trick if you need to know how far off is the static_assert
901 // char (*__kaboom)[sizeof(persistent_config_s)] = 1;
902 // another useful trick
903 // static_assert(offsetof (engine_configuration_s,HD44780_e) == 700);
904 
905  memset(&tsState, 0, sizeof(tsState));
906 
907  addConsoleAction("tsinfo", printTsStats);
908  addConsoleAction("reset_ts", resetTs);
909  addConsoleActionI("set_ts_speed", setTsSpeed);
910 
911 #if EFI_BLUETOOTH_SETUP
912  // module initialization start (it waits for disconnect and then communicates to the module)
913  // Usage: "bluetooth_hc06 <baud> <name> <pincode>"
914  // Example: "bluetooth_hc06 38400 rusefi 1234"
915  // bluetooth_jdy 115200 alphax 1234
916  addConsoleActionSSS("bluetooth_hc05", [](const char *baudRate, const char *name, const char *pinCode) {
917  bluetoothStart(BLUETOOTH_HC_05, baudRate, name, pinCode);
918  });
919  addConsoleActionSSS("bluetooth_hc06", [](const char *baudRate, const char *name, const char *pinCode) {
920  bluetoothStart(BLUETOOTH_HC_06, baudRate, name, pinCode);
921  });
922  addConsoleActionSSS("bluetooth_bk", [](const char *baudRate, const char *name, const char *pinCode) {
923  bluetoothStart(BLUETOOTH_BK3231, baudRate, name, pinCode);
924  });
925  addConsoleActionSSS("bluetooth_jdy", [](const char *baudRate, const char *name, const char *pinCode) {
926  bluetoothStart(BLUETOOTH_JDY_3x, baudRate, name, pinCode);
927  });
928  addConsoleActionSSS("bluetooth_jdy31", [](const char *baudRate, const char *name, const char *pinCode) {
929  bluetoothStart(BLUETOOTH_JDY_31, baudRate, name, pinCode);
930  });
931 #endif /* EFI_BLUETOOTH_SETUP */
932 }
933 
934 #endif // EFI_TUNER_STUDIO
constexpr uint8_t addr
Definition: ads1015.cpp:5
void setBoardConfigOverrides()
void executeTSCommand(uint16_t subsystem, uint16_t index)
Definition: bench_test.cpp:541
Utility methods related to bench testing.
void bluetoothSoftwareDisconnectNotify(SerialTsChannelBase *tsChannel)
Definition: bluetooth.cpp:363
uint8_t code
Definition: bluetooth.cpp:39
void bluetoothStart(bluetooth_module_e moduleType, const char *baudRate, const char *name, const char *pinCode)
Definition: bluetooth.cpp:300
@ BLUETOOTH_HC_05
Definition: bluetooth.h:22
@ BLUETOOTH_BK3231
Definition: bluetooth.h:27
@ BLUETOOTH_JDY_3x
Definition: bluetooth.h:29
@ BLUETOOTH_JDY_31
Definition: bluetooth.h:30
@ BLUETOOTH_HC_06
Definition: bluetooth.h:23
size_t size() const
Definition: big_buffer.h:43
const TBuffer * get() const
Definition: big_buffer.h:34
EngineState engineState
Definition: engine.h:315
TunerStudioOutputChannels outputChannels
Definition: engine.h:99
WarningCodeState warnings
Definition: engine_state.h:41
virtual bool isReady() const
virtual void flush()
const char * name
uint32_t writePacketHeader(const uint8_t responseCode, const size_t size)
char scratchBuffer[BLOCKING_FACTOR+30]
virtual void writeCrcPacket(uint8_t responseCode, const uint8_t *buf, size_t size, bool allowLongPackets=false)
virtual void write(const uint8_t *buffer, size_t size, bool isEndOfPacket=false)=0
virtual size_t readTimeout(uint8_t *buffer, size_t size, int timeout)=0
void sendResponse(ts_response_format_e mode, const uint8_t *buffer, int size, bool allowLongPackets=false)
void handleScatteredReadCommand(TsChannelBase *tsChannel)
bool handlePlainCommand(TsChannelBase *tsChannel, uint8_t command)
void handleCrc32Check(TsChannelBase *tsChannel, ts_response_format_e mode, uint16_t offset, uint16_t count)
void handleWriteChunkCommand(TsChannelBase *tsChannel, ts_response_format_e mode, uint16_t offset, uint16_t count, void *content)
void handleQueryCommand(TsChannelBase *tsChannel, ts_response_format_e mode)
void handleWriteValueCommand(TsChannelBase *tsChannel, ts_response_format_e mode, uint16_t offset, uint8_t value)
void handlePageSelectCommand(TsChannelBase *tsChannel, ts_response_format_e mode)
void cmdOutputChannels(TsChannelBase *tsChannel, uint16_t offset, uint16_t count) override
'Output' command sends out a snapshot of current values Gauges refresh
void sendErrorCode(TsChannelBase *tsChannel, uint8_t code)
void handlePageReadCommand(TsChannelBase *tsChannel, ts_response_format_e mode, uint16_t offset, uint16_t count)
int handleCrcCommand(TsChannelBase *tsChannel, char *data, int incomingPacketSize)
void handleExecuteCommand(TsChannelBase *tsChannel, char *data, int incomingPacketSize)
void ThreadTask() override
virtual TsChannelBase * setupChannel()=0
ObdCode lastErrorCode
Definition: engine_parts.h:63
void addConsoleAction(const char *token, Void callback)
Register console action without parameters.
void addConsoleActionSSS(const char *token, VoidCharPtrCharPtrCharPtr callback)
void addConsoleActionI(const char *token, VoidInt callback)
Register a console command with one Integer parameter.
void onDataArrived(bool valid)
Definition: console_io.cpp:49
void(* CommandHandler)(char *)
Definition: console_io.h:10
void printUsbConnectorStats()
Definition: usb_console.cpp:60
char * efiTrim(char *param)
Definition: efilib.cpp:39
uint32_t SWAP_UINT32(uint32_t x)
Definition: efilib.h:27
uint16_t SWAP_UINT16(uint16_t x)
Definition: efilib.h:22
efitimesec_t getTimeNowS()
Current system time in seconds (32 bits)
Definition: efitime.cpp:42
bool isLockedFromUser()
Definition: engine2.cpp:255
void onBurnRequest()
Engine * engine
const char * getCriticalErrorMessage(void)
int getRusEfiVersion(void)
void setNeedToWriteConfiguration()
Definition: flash_main.cpp:79
UNUSED(samplingTimeSeconds)
FragmentList getLiveDataFragments()
Definition: live_data.cpp:223
const char * swapOutputBuffers(size_t *actualOutputBufferSize)
Main logic header.
This data structure holds current malfunction codes.
@ STACK_USAGE_COMMUNICATION
const BigBufferHandle perfTraceGetBuffer()
Definition: perf_trace.cpp:132
void perfTraceEnable()
Definition: perf_trace.cpp:119
@ TunerStudioHandleCrcCommand
engine_configuration_s * engineConfiguration
const char * hwPortname(brain_pin_e brainPin)
const char * getTsSignature()
Definition: signature.cpp:31
void knockSpectrogramEnable()
void knockSpectrogramDisable()
void printOverallStatus()
composite packet size
void DisableToothLogger()
void EnableToothLogger()
CompositeBuffer * GetToothLoggerBufferNonblocking()
void ReturnToothLoggerBuffer(CompositeBuffer *buffer)
void EnableToothLoggerIfNotEnabled()
composite_logger_s
Definition: tooth_logger.h:48
void triggerScopeEnable()
const BigBufferHandle & triggerScopeGetBuffer()
static BigBufferHandle buffer
void triggerScopeDisable()
static bool isKnownCommand(char command)
void sendErrorCode(TsChannelBase *tsChannel, uint8_t code)
static void handleGetVersion(TsChannelBase *tsChannel)
void sendOkResponse(TsChannelBase *tsChannel, ts_response_format_e mode)
tunerstudio_counters_s tsState
TunerStudio tsInstance
static void setTsSpeed(int value)
CommandHandler console_line_callback
Definition: console_io.cpp:53
static void resetTs()
void startTunerStudioConnectivity(void)
static void printScatterList()
static void sendResponseCode(ts_response_format_e mode, TsChannelBase *tsChannel, const uint8_t responseCode)
static void handleGetText(TsChannelBase *tsChannel)
bool validateOffsetCount(size_t offset, size_t count, TsChannelBase *tsChannel)
void requestBurn()
bool rebootForPresetPending
static void handleTestCommand(TsChannelBase *tsChannel)
static int tsProcessOne(TsChannelBase *tsChannel)
void tunerStudioDebug(TsChannelBase *tsChannel, const char *msg)
static void printErrorCounters()
Definition: tunerstudio.cpp:93
uint8_t * getWorkingPageAddr()
static void handleBurnCommand(TsChannelBase *tsChannel, ts_response_format_e mode)
static void printTsStats(void)
void tunerStudioError(TsChannelBase *tsChannel, const char *msg)
ts_response_format_e
@ TS_CRC
@ TS_PLAIN
SerialTsChannelBase * getBluetoothChannel()