Reduce the size of the AVRDriver code.

Colorize the changed parameter.
Warning reduction across all files.
This commit is contained in:
2026-02-07 14:38:35 -06:00
parent 49edca0238
commit adad03c7df
10 changed files with 583 additions and 1429 deletions

View File

@@ -15,13 +15,12 @@
//#include "AVRCommandDecoder.h" //#include "AVRCommandDecoder.h"
#include "ConsoleHandler.h" #include "ConsoleHandler.h"
enum enum {
{
COM_NO_PORT = -1, COM_NO_PORT = -1,
COM_MIN_PORT = 1, COM_MIN_PORT = 1,
COM_MAX_PORT = 99 COM_MAX_PORT = 99
}; };
CSerialPort avrPort; CSerialPort rs232Port;
int avrOnPort = COM_NO_PORT; // Serial Port 1, 2, ... taking note that some USB adapters can be up toward channel 11, 12, ... int avrOnPort = COM_NO_PORT; // Serial Port 1, 2, ... taking note that some USB adapters can be up toward channel 11, 12, ...
unsigned avrBaud = 9600; unsigned avrBaud = 9600;
@@ -30,6 +29,7 @@ const uint32_t retryInterval = 1000; // ms
AVRInterface *avr; AVRInterface *avr;
#if 0
// Each DT is the hex-character from the stream // Each DT is the hex-character from the stream
// //
// //
@@ -198,7 +198,7 @@ typedef struct {
//AVR_StatusHeader_T avrStatusHeader; //AVR_StatusHeader_T avrStatusHeader;
//AVR_Configuration_T avrConfigData; //AVR_Configuration_T avrConfigData;
AVR_Status_T avrStatus; AVR_Status_T avrStatus;
#endif
typedef enum { typedef enum {
EXIT_OK = 0, EXIT_OK = 0,
@@ -224,7 +224,7 @@ int DetachSerialPort();
// @param[in] len is the count of bytes in the message // @param[in] len is the count of bytes in the message
// @returns true if the serial interface accepted it. // @returns true if the serial interface accepted it.
// //
bool SerialSend(const uint8_t *p, uint16_t len); bool SerialSend(const uint8_t *message, uint32_t len);
// Just big enough to hold an OSD message which is a 1 message command, 4 messages with text // Just big enough to hold an OSD message which is a 1 message command, 4 messages with text
#define SERIALQUEUESIZE 5 #define SERIALQUEUESIZE 5
@@ -237,7 +237,7 @@ static SerialQueue_T serialQueue[SERIALQUEUESIZE];
static int serialQueueCount = 0; static int serialQueueCount = 0;
// ProcessSerialQueue // SendMessageToSerial
// //
// If there are parameters passed, insert a message into the queue. // If there are parameters passed, insert a message into the queue.
// Process the queue (with zero or more messages) to send // Process the queue (with zero or more messages) to send
@@ -246,7 +246,7 @@ static int serialQueueCount = 0;
// @param[in] len is the count of bytes in the message // @param[in] len is the count of bytes in the message
// @returns false if the queue (which is a fixed size) is full. // @returns false if the queue (which is a fixed size) is full.
// //
//bool ProcessSerialQueue(const uint8_t *p = NULL, uint16_t len = 0); //bool SendMessageToSerial(const uint8_t *p = NULL, uint16_t len = 0);
// ProcessSerialReceive // ProcessSerialReceive
@@ -256,7 +256,7 @@ static int serialQueueCount = 0;
// @returns true if a message was processed. // @returns true if a message was processed.
// //
SerialQueue_T ProcessSerialReceive(void); SerialQueue_T ProcessSerialReceive(void);
void HandleMessage(uint8_t *szBuffer, uint32_t num); //void HandleMessage(uint8_t *szBuffer, uint32_t num);
void EnumerateComPorts(); void EnumerateComPorts();
unsigned long Hex2Dec(uint8_t *p, int dig); unsigned long Hex2Dec(uint8_t *p, int dig);
@@ -268,6 +268,7 @@ void GetAndSendOSDMessage();
bool SendExtendedMessage(char *buf); bool SendExtendedMessage(char *buf);
void EmitRuntimeHelp(); void EmitRuntimeHelp();
DWORD AppTime();
bool UserExitRequested = false; bool UserExitRequested = false;
bool SystemExitRequested = false; bool SystemExitRequested = false;
@@ -313,6 +314,7 @@ BOOL WINAPI ControlIntercept(DWORD CtrlType) {
void ProcessWindowsMessage(void) { void ProcessWindowsMessage(void) {
MSG msgx; MSG msgx;
bool msgReturn; bool msgReturn;
msgReturn = PeekMessage(&msgx, NULL, WM_QUIT, WM_QUIT, PM_NOREMOVE); msgReturn = PeekMessage(&msgx, NULL, WM_QUIT, WM_QUIT, PM_NOREMOVE);
if (msgReturn == true && msgx.message == WM_QUIT) { if (msgReturn == true && msgx.message == WM_QUIT) {
SystemExitRequested = true; SystemExitRequested = true;
@@ -320,12 +322,10 @@ void ProcessWindowsMessage(void) {
} }
bool SerialSend(const uint8_t *p, uint16_t len) { bool SerialSend(const uint8_t *message, uint32_t len) {
bool retVal = false; bool retVal = false;
//Console_SetCursor(0, -1);
//EmitBuffer("> ", p, len); if (rs232Port.Write((const LPVOID)message, len) == len) {
//Console_ScrollBottomRegion();
if (avrPort.Write((const LPVOID)p, len) == len) {
retVal = true; retVal = true;
} else { } else {
Console_WriteAt(0, -1, "***** Failed to send. Port not open?"); Console_WriteAt(0, -1, "***** Failed to send. Port not open?");
@@ -337,6 +337,7 @@ bool SerialSend(const uint8_t *p, uint16_t len) {
void EmitSpinner() { void EmitSpinner() {
static int x = 0; static int x = 0;
const char arrow[] = "|/-\\|/-\\"; const char arrow[] = "|/-\\|/-\\";
printf("%c\b", arrow[x++]); printf("%c\b", arrow[x++]);
if (x == 8) x = 0; if (x == 8) x = 0;
} }
@@ -407,10 +408,10 @@ void ProcessKeyboard(void) {
int c = CS_GetChar(); int c = CS_GetChar();
switch (c) { switch (c) {
case 'P': case 'P':
avr->AVRCommand(AVRInterface::subMain, AVRInterface::fncPower, AVRInterface::eOn); avr->AVRCommand(AVRSubsystem_T::subMain, AVRFunction_T::fncPower, AVRArg_T::eOn);
break; break;
case 'p': case 'p':
avr->AVRCommand(AVRInterface::subMain, AVRInterface::fncPower, AVRInterface::eOff); avr->AVRCommand(AVRSubsystem_T::subMain, AVRFunction_T::fncPower, AVRArg_T::eOff);
break; break;
case 'O': case 'O':
GetAndSendOSDMessage(); GetAndSendOSDMessage();
@@ -426,19 +427,18 @@ void ProcessKeyboard(void) {
break; break;
case '/': case '/':
avr->ReportAllStatus(); avr->ReportAllStatus();
//ShowAllStatusInfo();
break; break;
case '\x1B': case '\x1B':
UserExitRequested = true; UserExitRequested = true;
break; break;
case 'S': case 'S':
avrPort.Set_RTS_State(TRUE); rs232Port.Set_RTS_State(TRUE);
Console_SetCursor(0, -1); Console_SetCursor(0, -1);
printf("RTS set ON"); printf("RTS set ON");
Console_ScrollBottomRegion(); Console_ScrollBottomRegion();
break; break;
case 's': case 's':
avrPort.Set_RTS_State(FALSE); rs232Port.Set_RTS_State(FALSE);
Console_SetCursor(0, -1); Console_SetCursor(0, -1);
printf("RTS set OFF"); printf("RTS set OFF");
Console_ScrollBottomRegion(); Console_ScrollBottomRegion();
@@ -446,8 +446,8 @@ void ProcessKeyboard(void) {
default: default:
for (int i = 0; i < sizeof(UserCommands) / sizeof(UserCmd_T); i++) { for (int i = 0; i < sizeof(UserCommands) / sizeof(UserCmd_T); i++) {
if (UserCommands[i].Char == c) { if (UserCommands[i].Char == c) {
//ProcessSerialQueue((const uint8_t *)UserCommands[i].TxMsg.pMsg, UserCommands[i].TxMsg.MsgLen); //SendMessageToSerial((const uint8_t *)UserCommands[i].TxMsg.pMsg, UserCommands[i].TxMsg.MsgLen);
avr->ProcessSerialQueue((const uint8_t *)UserCommands[i].TxMsg.pMsg, UserCommands[i].TxMsg.MsgLen); avr->SendMessageToSerial(UserCommands[i].TxMsg.pMsg, UserCommands[i].TxMsg.MsgLen);
cmdFound = true; cmdFound = true;
break; break;
} }
@@ -499,19 +499,58 @@ void EmitRuntimeHelp() {
Console_AdvanceToNextLineIfNotRoomFor((short)strlen(buf), 1); Console_AdvanceToNextLineIfNotRoomFor((short)strlen(buf), 1);
Console_Write(buf); Console_Write(buf);
} }
if (avrPort.IsOpen()) { if (rs232Port.IsOpen()) {
Console_ScrollBottomRegion(); Console_ScrollBottomRegion();
Console_SetCursor(0, -1); Console_SetCursor(0, -1);
printf(" Com Status: RTS: %-3s ", avrPort.Get_RTS_State() ? "ON" : "OFF"); printf(" Com Status: RTS: %-3s ", rs232Port.Get_RTS_State() ? "ON" : "OFF");
printf("DTR: %-3s ", avrPort.Get_DTR_State() ? "ON" : "OFF"); printf("DTR: %-3s ", rs232Port.Get_DTR_State() ? "ON" : "OFF");
printf("CTS: %-3s ", avrPort.Get_CTS_State() ? "ON" : "OFF"); printf("CTS: %-3s ", rs232Port.Get_CTS_State() ? "ON" : "OFF");
printf("DSR: %-3s ", avrPort.Get_DSR_State() ? "ON" : "OFF"); printf("DSR: %-3s ", rs232Port.Get_DSR_State() ? "ON" : "OFF");
printf("RI: %-3s", avrPort.Get_RI_State() ? "ON" : "OFF"); printf("RI: %-3s", rs232Port.Get_RI_State() ? "ON" : "OFF");
Console_ScrollBottomRegion(); Console_ScrollBottomRegion();
Console_SetCursor(0, -1); Console_SetCursor(0, -1);
} }
} }
void EmitBuffer(const char *prefix, const uint8_t *buf, size_t len = 0, bool appendReturn = false) {
int i = 0;
const char *p = (const char *)buf;
char txtBuf[MAXTEXTLEN] = "";
if (len == 0) len = strlen((const char *)buf);
sprintf_s(txtBuf, MAXTEXTLEN, "%7.3f: [%3d]%s", (float)(AppTime())/1000.0, (int)strlen(p), prefix);
Console_Write(txtBuf);
while (*p && ((unsigned)(p - (const char *)buf) < len)) {
if (isprint((char)*p)) {
putchar(*p);
i++;
} else if (*p == '\r') {
putchar('\n');
Console_ScrollBottomRegion();
} else if (*p == '\n') {
// skip it
} else {
printf("[%02X]", (unsigned char)*p);
}
if ((i & 3) == 0) {
if (Console_AdvanceToNextLineIfNotRoomFor(12, 1)) {
//Console_ScrollBottomRegion();
printf(" "); // sized to get past the timestamp, length, and prefix
i = 0;
} else {
printf(" ");
}
}
p++;
}
if (appendReturn) {
Console_ScrollBottomRegion(); // putch('\r');
} else {
//putch('\n');
//Console_ScrollBottomRegion();
}
}
void HexUppercase(char *p) { void HexUppercase(char *p) {
const char *hex = "0123456789ABCDEF"; const char *hex = "0123456789ABCDEF";
while (*p) { while (*p) {
@@ -561,7 +600,7 @@ void GetAndSendCustomMessage() {
} else { } else {
Console_ScrollBottomRegion(); Console_ScrollBottomRegion();
sprintf_s(msg, sizeof(msg), "\x02%s\x03", buf); sprintf_s(msg, sizeof(msg), "\x02%s\x03", buf);
avr->ProcessSerialQueue(msg, (uint16_t)strlen(msg)); avr->SendMessageToSerial(msg, (uint16_t)strlen(msg));
} }
} }
@@ -579,7 +618,7 @@ bool SendExtendedMessage(char * buf) {
} while (*p && (p < msg + 70)); // 70 < 75 to generously reserve space for SUM0,SUM1,ETX,\0 } while (*p && (p < msg + 70)); // 70 < 75 to generously reserve space for SUM0,SUM1,ETX,\0
sprintf_s(p, 75 - strlen(msg), "%02X\x03", checksum); sprintf_s(p, 75 - strlen(msg), "%02X\x03", checksum);
Console_ScrollBottomRegion(); Console_ScrollBottomRegion();
avr->ProcessSerialQueue(msg, (uint16_t)strlen(msg)); avr->SendMessageToSerial(msg, (uint16_t)strlen(msg));
return true; return true;
} }
return false; return false;
@@ -612,32 +651,78 @@ void GetProgName(char *name) {
} }
void InformationUpdate(AVRInterface::AVRMessageType_T type, const char *msg) { bool InformationUpdate(AVRMessageType_T type, const void *message, uint32_t attrib) {
const char *msg = (const char *)message;
char buf[MAXTEXTLEN] = ""; char buf[MAXTEXTLEN] = "";
if (verboseMode) { if (verboseMode) {
switch (type) { switch (type) {
case AVRInterface::AVRMessageType_T::mtStatus: case mtState:
sprintf_s(buf, MAXTEXTLEN, "AVR Status: %-60s", msg); sprintf_s(buf, MAXTEXTLEN, "AVR Status: %-60s", avr->GetStateLabel(attrib));
Console_SetColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
Console_WriteAt(0, 1, buf); Console_WriteAt(0, 1, buf);
Console_RestoreColor();
break; break;
case AVRInterface::AVRMessageType_T::mtInfo: case mtInfo:
Console_WriteAt(0, -1, msg); Console_WriteAt(0, -1, msg);
Console_ScrollBottomRegion(); Console_ScrollBottomRegion();
break; break;
case AVRInterface::AVRMessageType_T::mtModelInfo: case mtModelInfo:
Console_WriteAt(0, 2, msg); Console_WriteAt(0, 2, msg);
break; break;
case AVRInterface::AVRMessageType_T::mtStreamStart: case mtStreamStart:
Console_SetCursor(0, 3); Console_SetCursor(0, 3);
// break; // fall through // break; // fall through
case AVRInterface::AVRMessageType_T::mtStream: case mtStream:
Console_AdvanceToNextLineIfNotRoomFor(40); // @TODO hard-coded - ick Console_AdvanceToNextLineIfNotRoomFor(40); // @TODO hard-coded - ick
if (attrib) {
Console_SetColor(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
}
Console_Write(msg); Console_Write(msg);
if (attrib) {
Console_RestoreColor();
}
break;
case mtXmtdMsg:
Console_SetCursor(0, -1);
EmitBuffer(">", (const uint8_t *)msg, attrib, true);
break;
case mtRcvdMsg:
Console_SetCursor(0, -1);
EmitBuffer("<", (const uint8_t *)msg, attrib, true);
break;
case mtExtendedResp:
Console_SetCursor(0, -1);
EmitBuffer("[", (const uint8_t *)msg, attrib, true);
break;
case mtStatusMsg:
Console_SetCursor(0, -1);
EmitBuffer("}", (const uint8_t *)msg, attrib, true);
break;
case mtOperationResp:
// This is just the echo of the command
// so there is nothing to report that wouldn't be a duplicate
//Console_SetCursor(0, -1);
//EmitBuffer("{", (const uint8_t *)msg, attrib, true);
break;
case mtParamUpdated:
message = "x";
break;
case mtErrNotFound:
sprintf_s(buf, MAXTEXTLEN, "AVRCommand(%02X,%02X,%02X) -- not found", (attrib >> 16), (attrib >> 8) & 0xFF, attrib & 0xFF);
Console_WriteAt(0, -1, buf);
break;
case mtErrRxLength:
break;
case mtErrMalloc:
break;
case mtFailed:
break; break;
default: default:
break; break;
} }
} }
return true;
} }
void EmitCommandLineHelp() { void EmitCommandLineHelp() {
@@ -668,7 +753,7 @@ void EmitCommandLineHelp() {
printf("\n"); printf("\n");
printf("Options:\n"); printf("Options:\n");
printf("\n"); printf("\n");
printf(" -SerialPort=X[,yyyy] Set to Com port X to baud rate yyyy.\n"); printf(" -SerialPort=X[,yyyy] Set to Serial Port X to baud rate yyyy.\n");
printf(" Defaults baud is %d\n", avrBaud); printf(" Defaults baud is %d\n", avrBaud);
printf(" NOTE: At least for the RX-V2400, 9600,8,N,1 is required.\n"); printf(" NOTE: At least for the RX-V2400, 9600,8,N,1 is required.\n");
printf(" NOTE: At least for the RX-V2400, the host must assert RTS.\n"); printf(" NOTE: At least for the RX-V2400, the host must assert RTS.\n");
@@ -779,7 +864,7 @@ int __cdecl main(int argc, char *argv[]) {
short consoleWidth = 122; short consoleWidth = 122;
short consoleHeight = 80; short consoleHeight = 80;
short consoleScrollHeight = 30; short consoleScrollHeight = 30;
short consoleLeft = 15; short consoleLeft = 50;
short consoleTop = 15; short consoleTop = 15;
int CommandToExecute[4] = { -1, -1, -1, -1 }; int CommandToExecute[4] = { -1, -1, -1, -1 };
float db; float db;
@@ -790,8 +875,7 @@ int __cdecl main(int argc, char *argv[]) {
GetProgName(argv[0]); GetProgName(argv[0]);
UserCommandsSanityCheck(); // If the table is bad, we exit here UserCommandsSanityCheck(); // If the table is bad, we exit here
avr = new AVRInterface(SerialSend); avr = new AVRInterface(InformationUpdate, SerialSend);
avr->RegisterInformationCallback(InformationUpdate);
ReadIniFile(); ReadIniFile();
@@ -822,10 +906,10 @@ int __cdecl main(int argc, char *argv[]) {
// //
switch (parseCount) { switch (parseCount) {
case 1: case 1:
CommandToExecute[1] = AVRInterface::AVRFunction_E::fncFunctionCount; CommandToExecute[1] = AVRFunction_T::fncFunctionCount;
// break; // fall thru on purpose // break; // fall thru on purpose
case 2: case 2:
CommandToExecute[2] = AVRInterface::AVRArg_T::eARGCount; CommandToExecute[2] = AVRArg_T::eARGCount;
// break; // fall thru on purpose // break; // fall thru on purpose
default: default:
// nothing to do // nothing to do
@@ -833,32 +917,32 @@ int __cdecl main(int argc, char *argv[]) {
} }
bool saveVerbose = verboseMode; bool saveVerbose = verboseMode;
verboseMode = true; verboseMode = true;
avr->ExportInformation((AVRInterface::AVRSubsystem_T)CommandToExecute[0], avr->ExportInformation((AVRSubsystem_T)CommandToExecute[0],
(AVRInterface::AVRFunction_E)CommandToExecute[1], (AVRFunction_T)CommandToExecute[1],
(AVRInterface::AVRArg_T)CommandToExecute[2]); (AVRArg_T)CommandToExecute[2]);
verboseMode = saveVerbose; verboseMode = saveVerbose;
exit(EXIT_OK); exit(EXIT_OK);
} else if (0 == strcmp(argv[i], "-Power=On")) { } else if (0 == strcmp(argv[i], "-Power=On")) {
CommandToExecute[0] = AVRInterface::subMain; CommandToExecute[0] = subMain;
CommandToExecute[1] = AVRInterface::fncPower; CommandToExecute[1] = fncPower;
CommandToExecute[2] = AVRInterface::eOn; CommandToExecute[2] = eOn;
} else if (0 == strcmp(argv[i], "-Power=Off")) { } else if (0 == strcmp(argv[i], "-Power=Off")) {
CommandToExecute[0] = AVRInterface::subMain; CommandToExecute[0] = subMain;
CommandToExecute[1] = AVRInterface::fncPower; CommandToExecute[1] = fncPower;
CommandToExecute[2] = AVRInterface::eOff; CommandToExecute[2] = eOff;
} else if (0 == strcmp(argv[i], "-Mute=On")) { } else if (0 == strcmp(argv[i], "-Mute=On")) {
CommandToExecute[0] = AVRInterface::subMain; CommandToExecute[0] = subMain;
CommandToExecute[1] = AVRInterface::fncMute; CommandToExecute[1] = fncMute;
CommandToExecute[2] = AVRInterface::eOn; CommandToExecute[2] = eOn;
} else if (0 == strcmp(argv[i], "-Mute=Off")) { } else if (0 == strcmp(argv[i], "-Mute=Off")) {
CommandToExecute[0] = AVRInterface::subMain; CommandToExecute[0] = subMain;
CommandToExecute[1] = AVRInterface::fncMute; CommandToExecute[1] = fncMute;
CommandToExecute[2] = AVRInterface::eOff; CommandToExecute[2] = eOff;
} else if (1 == sscanf_s(argv[i], "-Zone1Volume=%4f", &db)) { } else if (1 == sscanf_s(argv[i], "-Zone1Volume=%4f", &db)) {
if (db >= -80.0f && db <= +16.5f) { if (db >= -80.0f && db <= +16.5f) {
CommandToExecute[0] = AVRInterface::sysCommand; CommandToExecute[0] = sysCommand;
CommandToExecute[1] = AVRInterface::fncSetValue; CommandToExecute[1] = fncSetValue;
CommandToExecute[2] = AVRInterface::eMasterVol; CommandToExecute[2] = eMasterVol;
CommandToExecute[3] = avr->VolumeDBtoAPIValue(db); CommandToExecute[3] = avr->VolumeDBtoAPIValue(db);
} else { } else {
printf("***** Volume %+4.1f not in the range '-80.0 <= value <= 16.5' *****\n", db); printf("***** Volume %+4.1f not in the range '-80.0 <= value <= 16.5' *****\n", db);
@@ -866,9 +950,9 @@ int __cdecl main(int argc, char *argv[]) {
} }
} else if (1 == sscanf_s(argv[i], "-Zone2Volume=%4f", &db)) { } else if (1 == sscanf_s(argv[i], "-Zone2Volume=%4f", &db)) {
if (db >= -80.0f && db <= +16.5f) { if (db >= -80.0f && db <= +16.5f) {
CommandToExecute[0] = AVRInterface::sysCommand; CommandToExecute[0] = sysCommand;
CommandToExecute[1] = AVRInterface::fncSetValue; CommandToExecute[1] = fncSetValue;
CommandToExecute[2] = AVRInterface::eZone2Vol; CommandToExecute[2] = eZone2Vol;
CommandToExecute[3] = avr->VolumeDBtoAPIValue(db); CommandToExecute[3] = avr->VolumeDBtoAPIValue(db);
} else { } else {
printf("***** Volume %+4.1f not in the range '-80.0 <= value <= 16.5' *****\n", db); printf("***** Volume %+4.1f not in the range '-80.0 <= value <= 16.5' *****\n", db);
@@ -876,9 +960,9 @@ int __cdecl main(int argc, char *argv[]) {
} }
} else if (1 == sscanf_s(argv[i], "-Zone3Volume=%4f", &db)) { } else if (1 == sscanf_s(argv[i], "-Zone3Volume=%4f", &db)) {
if (db >= -80.0f && db <= +16.5f) { if (db >= -80.0f && db <= +16.5f) {
CommandToExecute[0] = AVRInterface::sysCommand; CommandToExecute[0] = sysCommand;
CommandToExecute[1] = AVRInterface::fncSetValue; CommandToExecute[1] = fncSetValue;
CommandToExecute[2] = AVRInterface::eZone3Vol; CommandToExecute[2] = eZone3Vol;
CommandToExecute[3] = avr->VolumeDBtoAPIValue(db); CommandToExecute[3] = avr->VolumeDBtoAPIValue(db);
} else { } else {
printf("***** Volume %+4.1f not in the range '-80.0 <= value <= 16.5' *****\n", db); printf("***** Volume %+4.1f not in the range '-80.0 <= value <= 16.5' *****\n", db);
@@ -900,7 +984,7 @@ int __cdecl main(int argc, char *argv[]) {
DWORD refTime = AppTime(); DWORD refTime = AppTime();
DWORD nowTime = AppTime(); DWORD nowTime = AppTime();
DWORD elapsedTime = nowTime - refTime; DWORD elapsedTime = nowTime - refTime;
AVRInterface::AVRState_T state = AVRInterface::stPoweringUp; AVRInterface::AVRState_T state = AVRInterface::stMaxStates;
do { do {
state = avr->Tick(nowTime); state = avr->Tick(nowTime);
Sleep(10); // @TODO how long to wait should not be based on lucky timing Sleep(10); // @TODO how long to wait should not be based on lucky timing
@@ -916,9 +1000,9 @@ int __cdecl main(int argc, char *argv[]) {
if (pExtendedMessage) { if (pExtendedMessage) {
SendExtendedMessage(pExtendedMessage); SendExtendedMessage(pExtendedMessage);
} else { } else {
avr->AVRCommand((AVRInterface::AVRSubsystem_T)CommandToExecute[0], avr->AVRCommand((AVRSubsystem_T)CommandToExecute[0],
(AVRInterface::AVRFunction_E)CommandToExecute[1], (AVRFunction_T)CommandToExecute[1],
(AVRInterface::AVRArg_T)CommandToExecute[2], (AVRArg_T)CommandToExecute[2],
(uint8_t)CommandToExecute[3]); (uint8_t)CommandToExecute[3]);
} }
refTime = nowTime = AppTime(); refTime = nowTime = AppTime();
@@ -952,14 +1036,15 @@ int __cdecl main(int argc, char *argv[]) {
ProcessKeyboard(); ProcessKeyboard();
SerialQueue_T anyRcvdMsg = ProcessSerialReceive(); SerialQueue_T anyRcvdMsg = ProcessSerialReceive();
if (anyRcvdMsg.len) { if (anyRcvdMsg.len) {
bool showAllFlag = avr->HandleMessage(anyRcvdMsg.message, anyRcvdMsg.len); uint8_t offsetChanged = avr->HandleMessage(anyRcvdMsg.message, anyRcvdMsg.len);
if (showAllFlag) { if (offsetChanged) {
bool priorState = Console_SetCursorVisibility(false); bool priorState = Console_SetCursorVisibility(false);
avr->ReportAllStatus(); avr->ReportAllStatus(offsetChanged);
Console_SetCursorVisibility(priorState); Console_SetCursorVisibility(priorState);
} }
} }
Sleep(10);
ProcessWindowsMessage(); ProcessWindowsMessage();
} while (!UserExitRequested && !SystemExitRequested); } while (!UserExitRequested && !SystemExitRequested);
DetachSerialPort(); DetachSerialPort();
@@ -1024,57 +1109,6 @@ bool CheckTheChecksum(uint8_t *szBuffer, uint32_t num) {
} }
// HandleMessage
//
// Given a response string, typically of the form:
// [11] .... [03]
// [12] .... [03]
// ... etc
//
//
void HandleMessage(uint8_t *szBuffer, uint32_t num) {
switch (szBuffer[0]) {
case 0x02: // STX
//ProcessReportResponse(szBuffer, num);
break;
case 0x11: // DC1
break;
case 0x12: // DC2
if (CheckTheChecksum(szBuffer, num)) {
if (num == 21) {
memcpy(&avrStatus.header, &szBuffer[1], sizeof(AVR_StatusHeader_T));
num = Hex2Dec(&avrStatus.header.length[0], 2);
memcpy(&avrStatus.config.DT0, &szBuffer[9], num); // Copy bits of the config
avrStatus.headerValid = true;
} else if (num == 150) {
memcpy(&avrStatus.header, &szBuffer[1], sizeof(AVR_StatusHeader_T));
num = Hex2Dec(&avrStatus.header.length[0], 2);
memcpy(&avrStatus.config.DT0, &szBuffer[9], num); // Copy the config
//memcpy(&avrStatus.header, &szBuffer[1], sizeof(AVR_StatusHeader_T) + sizeof(AVR_Configuration_T));
avrStatus.headerValid = true;
avrStatus.configValid = true;
} else {
printf("***** Received message of unexpected length [%u]\n", num);
}
} else {
Console_WriteAt(0, -1, "Checksum failure on Status Header");
}
//PrintConfiguration(szBuffer);
break;
case 0x14: // DC4 Extended Response
//DecodeExtended(szBuffer);
// Decode Extended response
break;
case '0':
//rcmd = Hex2Dec(&szBuffer[0], 2);
//DecodeString(rcmd, &szBuffer[2]);
break;
default:
//printf("[%d] %s\n", i, szBuffer);
break;
}
}
// ProcessSerialReceive // ProcessSerialReceive
// //
@@ -1089,7 +1123,8 @@ SerialQueue_T ProcessSerialReceive() {
static uint8_t *p = messageBuf[bufInUse]; // used to fill the partialRx as data comes in static uint8_t *p = messageBuf[bufInUse]; // used to fill the partialRx as data comes in
SerialQueue_T retInfo = { NULL, 0 }; SerialQueue_T retInfo = { NULL, 0 };
uint32_t num = avrPort.Read(partialRx, MAXTEXTLEN); #include <stdio.h>
uint32_t num = rs232Port.Read(partialRx, MAXTEXTLEN);
if (num) { if (num) {
for (uint32_t i = 0; i < num; i++) { for (uint32_t i = 0; i < num; i++) {
*p = partialRx[i]; *p = partialRx[i];
@@ -1102,10 +1137,12 @@ SerialQueue_T ProcessSerialReceive() {
bufInUse = (++bufInUse & 1); bufInUse = (++bufInUse & 1);
p = messageBuf[bufInUse]; // Reset the buffer for the next message, which might be in partialRx p = messageBuf[bufInUse]; // Reset the buffer for the next message, which might be in partialRx
*p = '\0'; *p = '\0';
} else {
*p = '\0'; // keep it null terminated
} }
} }
if (messageBuf[0]) { if (messageBuf[0]) {
//EmitBuffer("~", messageBuf, 0, true); // Show them the partial receipt if anything is there //EmitBuffer("~", (const uint8_t *)messageBuf, 0, true); // Show them the partial receipt if anything is there
} }
} }
return retInfo; return retInfo;
@@ -1114,7 +1151,7 @@ SerialQueue_T ProcessSerialReceive() {
void EnumerateComPorts() { void EnumerateComPorts() {
printf("Com Port Scan:\n"); printf("Serial Port Scan:\n");
int foundPorts = 0; int foundPorts = 0;
for (int pNum = COM_MIN_PORT; pNum < COM_MAX_PORT; pNum++) { for (int pNum = COM_MIN_PORT; pNum < COM_MAX_PORT; pNum++) {
char cBuf[20]; // generously sized char cBuf[20]; // generously sized
@@ -1135,18 +1172,18 @@ void EnumerateComPorts() {
CloseHandle(port); CloseHandle(port);
} }
if (portFound) { if (portFound) {
printf(" Com Port %d found.\n", pNum); printf(" Serial Port %d found.\n", pNum);
} }
} }
if (foundPorts == 0) { if (foundPorts == 0) {
printf(" No Com Ports found, perhaps you need to plug in an adapter?\n"); printf(" No Serial Ports found, perhaps you need to plug in an adapter?\n");
} }
} }
int DetachSerialPort() { int DetachSerialPort() {
if (avrPort.IsOpen()) { if (rs232Port.IsOpen()) {
avrPort.Close(); rs232Port.Close();
} }
return true; return true;
} }
@@ -1158,11 +1195,11 @@ int AttachToSerialPort() {
sprintf_s(buf, sizeof(buf), "\\\\.\\COM%d", avrOnPort); sprintf_s(buf, sizeof(buf), "\\\\.\\COM%d", avrOnPort);
uint32_t Access = GENERIC_WRITE | GENERIC_READ; uint32_t Access = GENERIC_WRITE | GENERIC_READ;
if (avrPort.Open(buf, avrBaud, 8, NOPARITY, ONESTOPBIT, Access)) { if (rs232Port.Open(buf, avrBaud, 8, NOPARITY, ONESTOPBIT, Access)) {
success = true; success = true;
avrPort.Set_RTS_State(false); rs232Port.Set_RTS_State(false);
Sleep(50); Sleep(50);
avrPort.Set_RTS_State(true); rs232Port.Set_RTS_State(true);
Sleep(50); Sleep(50);
} }
} }

View File

@@ -129,12 +129,14 @@
<ItemGroup> <ItemGroup>
<ClCompile Include="AVR.cpp" /> <ClCompile Include="AVR.cpp" />
<ClCompile Include="AVRCommandDecoder.cpp" /> <ClCompile Include="AVRCommandDecoder.cpp" />
<ClCompile Include="AVRDriver.cpp" />
<ClCompile Include="AVRInterface.cpp" /> <ClCompile Include="AVRInterface.cpp" />
<ClCompile Include="ConsoleHandler.cpp" /> <ClCompile Include="ConsoleHandler.cpp" />
<ClCompile Include="SerialPort\SerialPort.cpp" /> <ClCompile Include="SerialPort\SerialPort.cpp" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="AVRCommandDecoder.h" /> <ClInclude Include="AVRCommandDecoder.h" />
<ClInclude Include="AVRDriver.h" />
<ClInclude Include="AVRInterface.h" /> <ClInclude Include="AVRInterface.h" />
<ClInclude Include="ConsoleHandler.h" /> <ClInclude Include="ConsoleHandler.h" />
<ClInclude Include="SerialPort\SerialPort.h" /> <ClInclude Include="SerialPort\SerialPort.h" />

View File

@@ -30,6 +30,9 @@
<ClCompile Include="AVRInterface.cpp"> <ClCompile Include="AVRInterface.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="AVRDriver.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="SerialPort\SerialPort.h"> <ClInclude Include="SerialPort\SerialPort.h">
@@ -44,5 +47,8 @@
<ClInclude Include="AVRInterface.h"> <ClInclude Include="AVRInterface.h">
<Filter>Header Files</Filter> <Filter>Header Files</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="AVRDriver.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LocalDebuggerCommandArguments>-SerialPort=2 -Command=0,1,4</LocalDebuggerCommandArguments> <LocalDebuggerCommandArguments>-SerialPort=2</LocalDebuggerCommandArguments>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup> </PropertyGroup>
</Project> </Project>

View File

@@ -392,14 +392,14 @@ const char *Mode1Mode2Text(uint8_t val) {
const char *ZonePower(uint8_t val) { const char *ZonePower(uint8_t val) {
static char buf[60]; static char buf[60];
const char *powerList[8] = { const char *powerList[8] = {
/* 0 */ "All Off (Main, Zone 2, Zone 3)", /* 0 */ "All Off",
/* 1 */ "All On (Main, Zone 2, Zone 3)", /* 1 */ "All On",
/* 2 */ "Main On | Zone 2 Off | Zone 3 Off", /* 2 */ "Zone 1 On | 2,3 Off",
/* 3 */ "Main Off | Zone 2 On | Zone 3 On ", /* 3 */ "Zone 1 Off | 2,3 On",
/* 4 */ "Main On | Zone 2 On | Zone 3 Off", /* 4 */ "Zone 1,2 On | 3 Off",
/* 5 */ "Main On | Zone 2 Off | Zone 3 Off", /* 5 */ "Zone 1 On | 2,3 Off",
/* 6 */ "Main Off | Zone 2 On | Zone 3 On ", /* 6 */ "Zone 1 Off | 2,3 On",
/* 7 */ "Main Off | Zone 2 Off | Zone 3 On ", /* 7 */ "Zone 1,2 Off | 3 On",
}; };
if (val < 8) if (val < 8)
strcpy_s(buf, sizeof(buf), powerList[val]); strcpy_s(buf, sizeof(buf), powerList[val]);

File diff suppressed because it is too large Load Diff

View File

@@ -1,42 +1,19 @@
#pragma once #pragma once
#include <stdint.h> #include <stdint.h>
#include "AVRDriver.h"
class AVRInterface { class AVRInterface : public AVRDriver {
public: public:
/// @brief /// @brief
/// @param SendMessage is the function this AVRInterface calls to send a message to the device /// @param SendMessage is the function this AVRInterface calls to send a message to the device
/// ///
AVRInterface(bool (*SendMessage)(const uint8_t *buffer, uint16_t len)); AVRInterface(
NotifyCallBack notifyCB, ///<! used to notify the host of internal events
SendCallBack sendCB ///<! used to send to the RS-232 interface
);
~AVRInterface(); ~AVRInterface();
/// @brief internal operating states of the AVR interface
typedef enum {
stPoweringUp, ///<! powering up
stAwaitingReadyResponse, ///<! waiting for the special ready response
stInitializing, ///<! initializing
stRetryInitializing, ///<! retrying initialization
stReady, ///<! ready for commands
stAwaitingResponse, ///<! waiting for a response to a command
stFailed, ///<! failed to establish contact
stMaxStates ///<! maximum states
} AVRState_T;
/// @brief Call this periodically so timed activities can be handled.
///
/// Every 1 or even 50 to 100 msec is ok.
///
/// @param[in] milliseconds since the program started
/// @returns the current state of the AVR interface
///
AVRState_T Tick(uint32_t millisec);
/// @brief When the system receives something from the device, give it to this function to handle it
/// @param buffer
/// @param len
/// @return true if it was handled
///
bool HandleMessage(const uint8_t *buffer, uint16_t len);
/// @brief Initialize the AVR interface and issue the ready command. /// @brief Initialize the AVR interface and issue the ready command.
/// ///
@@ -44,274 +21,16 @@ public:
/// ///
/// @return true if initialized /// @return true if initialized
/// ///
bool Initialize(); //bool Initialize();
typedef enum {
sysCommand, // even with power off
subMain, // after power is on
subRadio,
subAudio,
subZone1,
subZone2,
subZone3,
subsystemCount
} AVRSubsystem_T;
typedef enum {
fncPower,
fncVolume,
fncMute,
fncVolumeMemory,
fncVolumeRecall,
fncSpeakerAOnOff,
fncSpeakerBOnOff,
fncSpeakerBZone,
fncZone2SpeakerOnOff,
fncNightModeOnOff,
fncEffect,
fncDSPSoundScape,
fncInput,
fncRadioBand,
fncRadioTune,
fncRadioPresetPage,
fncRadioPresetNumber,
fncRadioPresetMemory,
fncRadioPresetRecall,
fncSleep,
fncOSD,
fnc6ChInput,
fncEx_EsOnOff,
fncInputMode,
fncDualMono,
fncDC1TrigControl,
fncDC2TrigControl,
fncDC1OnOff,
fncDC2OnOff,
fncReady,
fncReportEnable,
fncReportDelay,
fncRequest,
fncSetValue,
fncFunctionCount
} AVRFunction_E;
typedef enum {
eOn = 0, //
eOff,
eStandby,
eUp, //
eDown,
eMuteOn, //
eMuteOff,
eFM, //
eAM,
eA, //
eB,
eC,
eD,
eE,
eF,
e1, //
e2,
e3,
e4,
e5,
e6,
e7,
e8,
eSleepOff, //
eSleep120,
eSleep90,
eSleep60,
eSleep30,
ePhono, //
eCD,
eTuner,
eCDR,
eMD_Tape,
eDVD,
eDTV,
eCable,
eSat,
eVCR1,
eVCR2_DVR,
eVCR3,
eV_Aux,
eOSDOff, //
eOSDShort,
eOSDFull,
eOnMatrix, //
eESESOff,
eAuto,
eDiscrete, //
eEffectOn,
eStereo,
eMain, //
eZone1,
eZone2,
eZone3,
eZoneOR,
Hall_A, //
Hall_B,
Hall_C,
Hall_USA,
Hall_E,
Live_Concert,
Tokyo,
Freiburg,
Royaumont,
Village_Gate,
Village_Vanguard,
The_Bottom_Line,
The_Roxy_Theater,
Warehouse_Loft,
Arena,
Disco,
Party,
Game,
Stereo_6_8Ch,
Pop_Rock,
DJ,
Opera,
Pavillion,
Mono_Movie,
Variety_Sports,
Spectacre,
Sci_Fi,
Adventure,
General,
Normal,
Enhanced,
PLII_Movie,
PLII_Music,
Neo_6_Movie,
Neo_6_Music,
Direct_2Ch,
Stereo_2Ch,
THX_Ultra_PL,
THX_Music,
THX_Ultra_PL2,
THX_Ultra_NEO6,
eInpAuto, //
eDD_RF,
eDTS,
eDigital,
eAnalog,
eAAC,
eDualMain, //
eDualSub,
eDualAll,
e0ms,
e50ms,
e100ms,
e150ms,
e200ms,
e250ms,
e300ms,
e350ms,
e400ms,
eTuningFreq,
eMainVolDB,
eZone2VolDB,
eInputName,
eZone2InputName,
eZoneXVolDB,
eZoneXInputName,
eMasterVol,
eZone2Vol,
eMainLRBal,
eMainLevel,
eZone3Vol,
eMainLevelR,
eMainLevelL,
eCenterLevel,
eRearR,
eRearL,
eFrontR,
eFrontL,
eSurBackR,
eSurBackL,
eSwfr1,
eSwfr2,
eARGCount
} AVRArg_T;
/// @brief The single command path to control the AVR
///
/// This lets you send a command to the AVR using this single interface, by choosing
/// the AVR Subsystem of interest, the Function of interest, and passing an argument.
///
/// @param[in] subsystem: Main | Zone 1 | Zone 2 | Zone 3
/// @param[in] function : Power, Speaker, Volume, etc.
/// @param[in] arg: on/off, etc.
/// @param[in] variableData is for those functions where it needs to integrate variable value, such as setting the volume directly
/// @return true if accepted
///
bool AVRCommand(AVRSubsystem_T subsystem,
AVRFunction_E function,
AVRArg_T arg,
uint8_t variableData = 0);
/// @brief AVRMessageType_T
///
/// Indicates the type of message being sent to the status change callback
///
typedef enum {
mtModelInfo, ///<! Model information
mtStatus, ///<! Special State machine status (possibly useful in a dedicate place on the UI)
mtInfo, ///<! General purpose information (chunks of information that might be useful in a small scroll region)
mtStreamStart, ///<! Stream start of the status, each chunk is a generally a same-length string, totaling 100s of bytes.
mtStream, ///<! Status stream that word-wraps...
} AVRMessageType_T;
/// @brief StatusChangeCallback
///
/// This is the function prototype for the status change callback from the AVR interface.
/// This can be used to interpret, or more commonly to display, various types of status information.
///
/// @param[in] type is the type of message being sent
/// @param[in] msg is the text message
///
typedef void (*StatusChangeCallback)(AVRMessageType_T type, const char *msg);
/// @brief allows the host to register a callback for status changes
///
/// the callback information is always text
///
/// @param[in] cb is the callback function, or register NULL to unregister
/// @return true always
///
bool RegisterInformationCallback(StatusChangeCallback cb);
/// ReportAllStatus /// ReportAllStatus
/// ///
/// @brief This will loop through the DT array and report the status of everything via the registered callback /// @brief This will loop through the DT array and report the status of everything via the registered callback
/// @param[in] offsetChanged indicates what index into the big buffer changed
/// which can be used to highlight the fresh data
/// ///
void ReportAllStatus(); void ReportAllStatus(uint8_t offsetChanged = 0);
/// ProcessSerialQueue
///
/// @brief This is public to start, maybe forever because it offers the generic capability
/// @param[in] p the message to send
/// @param[in] len of the message
/// @return true
///
bool ProcessSerialQueue(const void *p = NULL, uint16_t len = NULL);
/// AVRSendOSDMessage
///
/// @brief Send a text message to the AVR for display on the connected TV
/// @param[in] msg is a text string, which must not exceed 16 characters in length, is null terminated
/// and is restricted to the following characters:
/// " !#%&()*+,-.0123456789:<=>?ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_abcdefghijklmnopqrstuvwxyz"
/// @return true if the message was accepted for sending, false if it is too long or has invalid characters.
///
bool AVRSendOSDMessage(const char *msg);
/// ExportInformation /// ExportInformation
/// ///
@@ -321,8 +40,8 @@ public:
/// @param[in] function : Power, Speaker, Volume, etc. /// @param[in] function : Power, Speaker, Volume, etc.
/// @param[in] arg: on/off, etc. /// @param[in] arg: on/off, etc.
/// ///
void ExportInformation(AVRInterface::AVRSubsystem_T subsystem = subsystemCount, void ExportInformation(AVRSubsystem_T subsystem = subsystemCount,
AVRInterface::AVRFunction_E function = fncFunctionCount, AVRFunction_T function = fncFunctionCount,
AVRArg_T arg = eARGCount); AVRArg_T arg = eARGCount);
/// VolumeDBtoAPIValue /// VolumeDBtoAPIValue
@@ -333,219 +52,38 @@ public:
/// ///
uint8_t VolumeDBtoAPIValue(float db); uint8_t VolumeDBtoAPIValue(float db);
/// @brief permits snooping on what the driver intends to send to the AVR via RS-232
///
/// @param message
/// @param len
/// @return true
//bool HostSendPassthru(const uint8_t * message, uint32_t len);
const char *GetStateLabel(uint32_t st);
private: private:
uint32_t sentAtTime_ms; // Instance pointer used by the C-style NotifyCallBack trampoline.
// There is only one AVRInterface instance expected in this design.
static AVRInterface *s_instance;
AVRState_T state = stPoweringUp; // The application supplied notify callback -- invoked by this interface
AVRState_T oldState = stMaxStates; // after the driver's notifications are processed by AVRInterface.
NotifyCallBack AppNotify;
AVRState_T GetState() {
return state;
}
// Each DT is the hex-character from the stream
//
// This could be simplified to uint8_t DT[138]
//
typedef struct {
uint8_t DT0; // * Baud Rate '@'
uint8_t DT1; // * Receive Buffer 'E'
uint8_t DT2; // * Receive Buffer '0'
uint8_t DT3; // * '1'
uint8_t DT4; // * Command Timeout '9'
uint8_t DT5; // * '0'
uint8_t DT6; // * '0'
uint8_t DT7; // * System '0':Ok, '1':Busy
uint8_t DT8; // * Power 0:Off, 1:On
uint8_t DT9; // Input 0: Phono, 1:CD, 2:Tuner, 3:CD-R, 4:MD-Tape, 5:DVD, 6:D-TV, 7:Cbl, 9:VCR1, A:VCR2
uint8_t DT10; // 6ch input 0:Off, 1:On
uint8_t DT11; // Input Mode 0:AUTO, 2:DTS, 4:Analog, 5:Analog Only
uint8_t DT12; // Audio Mute 0:Off, 1:On
uint8_t DT13; // Zone2 Input 0: PHONO / 1: CD / 2: TUNER / 3: CD-R / 4: MD-TAPE / 5: DVD / 6: D-TV-LD / 7: CBL-SAT / 9: VCR1 / A: VCR2-DVR / C: V-AUX
uint8_t DT14; // Zone2 Mute 0: OFF / 1: ON
uint8_t DT15; // Master Volume Upper 4 bit
uint8_t DT16; // Master Volume Lower 4 bit
uint8_t DT17; // Zone2 Volume Upper 4 bit
uint8_t DT18; // Zone2 Volume Lower 4 bit
uint8_t DT19; // Program Upper 4 bit
uint8_t DT20; // Program Lower 4 bit
uint8_t DT21; // Effect 0: OFF / 1: ON
uint8_t DT22; // 6.1/ES key status 0: OFF / 1: MATRIX ON / 2: DISCRETE ON / 3: AUTO
uint8_t DT23; // OSD* 0: FULL / 1: SHORT / 2: OFF
uint8_t DT24; // Sleep 0: 120 / 2: 90 / 3: 60 / 4: 30 / 5: OFF
uint8_t DT25; // Tuner Page 0: Page A / 1: Page B / 2: Page C / 3: Page D / 4: PageE
uint8_t DT26; // Tuner No. 0: No.1 / 1: No.2 / 2: No.3 / 3: No.4 / 4: No.5 / 5: No.6 / 6: No.7 / 7: No.8
uint8_t DT27; // Night mode 0: OFF / 1: ON
uint8_t DT28; // Care
uint8_t DT29; // Speaker relay A 0: OFF / 1: ON
uint8_t DT30; // Speaker relay B 0: OFF / 1: ON
uint8_t DT31; // Playback 0: 6ch input / 1: Analog / 2: PCM / 3: DD*(except 2.0) / 4: DD(2.0) / 5: DD.Karaoke / 6: DD.EX / 7: DTS / 8: DTS-ES / 9: Other DIGITAL / A: DTS Analog Mute / B: DTS ES Discrete
uint8_t DT32; // Fs 0: Analog / 1: 32kHz / 2: 44.1kHz / 3: 48kiHz / 4: 64kHz / 5: 88.2kHz / 6: 96kHz / 7: Unknown B: DTS 96/24
uint8_t DT33; // EX/ES playback 0: OFF / 1: MATRIX ON / 2: DISCRETE ON
uint8_t DT34; // Thr / Bypass 0: Normal / 1: Bypass
uint8_t DT35; // RED dts 0: Release / 1: Wait
uint8_t DT36; // Head Phone 0: OFF / 1: ON
uint8_t DT37; // TUNER BAND 0: FM / 1: AM
uint8_t DT38; // TUNER TUNED 0: NOT TUNED / 1: TUNED
uint8_t DT39; // DC1 Control Out 0: LOW / 1: HIGH
uint8_t DT40; // Dont care
uint8_t DT41; // Don't Care
uint8_t DT42; // 0-2 DC1 TRG Ctrl. 0: Zone1 / 1: Zone2 / 2: Zone1&2
uint8_t DT43; // 0/1 dts 96/24 0: OFF / 1: ON
uint8_t DT44; // 0-2 DC2 TRG Ctrl. 0: Zone1 / 1: Zone2 / 2: Zone1&2
uint8_t DT45; // 0/1 DC2 Trigger 0: LOW / 1: HIGH
uint8_t DT46; // SP B set 0: Zone1 / 1: Zone2
uint8_t DT47; // Zone 2 SP out 0: OFF / 1: ON
uint8_t DT48; // MAIN R Upper 4bit
uint8_t DT49; // Lower 4bit
uint8_t DT50; // MAIN L Upper 4bit
uint8_t DT51; // Lower 4bit
uint8_t DT52; // CENTER Upper 4bit
uint8_t DT53; // Lower 4bit
uint8_t DT54; // REAR R Upper 4bit
uint8_t DT55; // Lower 4bit
uint8_t DT56; // REAR L Upper 4bit
uint8_t DT57; // Lower 4bit
uint8_t DT58; // SUR BACK Upper 4bit
uint8_t DT59; // R Lower 4bit
uint8_t DT60; // SUR BACK Upper 4bit
uint8_t DT61; // L Lower 4bit
uint8_t DT62; // FRONT R Upper 4bit
uint8_t DT63; // Lower 4bit
uint8_t DT64; // FRONT L Upper 4bit
uint8_t DT65; // Lower 4bit
uint8_t DT66; // SWFR 1 Upper 4bit
uint8_t DT67; // Lower 4bit
uint8_t DT68; // Don't Care
uint8_t DT69; // Don't Care
uint8_t DT70; // Don't Care
uint8_t DT71; // Don't Care
uint8_t DT72; // Don't Care
uint8_t DT73; // Don't Care
uint8_t DT74; // LFE Lvl. SP Upper 4bit
uint8_t DT75; // Lower 4bit
uint8_t DT76; // LFE Lvl. HP Upper 4bit
uint8_t DT77; // Lower 4bit
uint8_t DT78; // Audio Delay Upper 4bit
uint8_t DT79; // Lower 4bit
uint8_t DT80; // Don't Care
uint8_t DT81; // Don't Care
uint8_t DT82; // Don't Care
uint8_t DT83; // Don't Care
uint8_t DT84; // Input mode set 0: AUTO / 1: LAST
uint8_t DT85; // Dimmer 0: -4 / 1: -3 / 2: -2 / 3: -1 / 4: 0
uint8_t DT86; // OSD Message
uint8_t DT87; // OSD shift Upper 4bit
uint8_t DT88; // Lower 4bit
uint8_t DT89; // Glay back 0: OFF / 1: AUTO
uint8_t DT90; // Video conversion 0: OFF / 1: ON
uint8_t DT91; // D. Range SP 0: MAX / 1: STD / 2: MIN
uint8_t DT92; // HP 0: MAX / 1: STD / 2: MIN
uint8_t DT93; // Zone 2 vol. Out
uint8_t DT94; // Don't Care
uint8_t DT95; // Memory guard 0: OFF / 1: ON
uint8_t DT96; // SP set Center 0: Large / 1: Small / 2: None
uint8_t DT97; // Main 0: Large / 1: Small
uint8_t DT98; // Rear L/R 0: Large / 1: Small / 2: None
uint8_t DT99; // Rear CT 0: Large / 1: Small / 2: None
uint8_t DT100; // Front 0: Yes / 1: None
uint8_t DT101; // LFE/BASS 0: SWFR / 1: Main / 2: Both
uint8_t DT102; // 6CH Center 0: Center / 1: Main
uint8_t DT103; // SWFR 0: SWFR / 1: Main
uint8_t DT104; // Main level 0: Normal / 1: -10dB
uint8_t DT105; // Test mode 0: OFF / 1: Dolby / 2: DTS
uint8_t DT106; // Don't Care
uint8_t DT107; // LVL 6CH MAIN L Upper 4bit
uint8_t DT108; // Lower 4bit
uint8_t DT109; // MAIN R Upper 4bit
uint8_t DT110; // Lower 4bit
uint8_t DT111; // CENTER Upper 4bit
uint8_t DT112; // Lower 4bit
uint8_t DT113; // SL Upper 4bit
uint8_t DT114; // Lower 4bit
uint8_t DT115; // SR Upper 4bit
uint8_t DT116; // Lower 4bit
uint8_t DT117; // SBL Upper 4bit
uint8_t DT118; // Lower 4bit
uint8_t DT119; // SBR Upper 4bit
uint8_t DT120; // Lower 4bit
uint8_t DT121; // FRONT L Upper 4bit
uint8_t DT122; // Lower 4bit
uint8_t DT123; // FRONT R Upper 4bit
uint8_t DT124; // Lower 4bit
uint8_t DT125; // SWFR Upper 4bit
uint8_t DT126; // Lower 4bit
uint8_t DT127; // 0 - C Z3 Input
uint8_t DT128; // 0/1 Z3 Mute
uint8_t DT129; // 0 - F Z3 Volume Upper 4bit
uint8_t DT130; // 0 - F Lower 4bit
uint8_t DT131; // Don't Care
uint8_t DT132; // MULTI_CH SELECT 00:6CH / 01:8CH TUNER / 02: 8CH CD / 04: 8CH CD-R / 05: 8CH DVD / 06: DTV / 07: 8CH CBL/SAT / 09: 8CH VCR1 / 0A: VCR2/DVR / 0C: VAUX
uint8_t DT133; // MULTI_CH SURROUND to 00: Surround / 01: Main
uint8_t DT134; // SP SET SW1 00: L-R / 01: F-R / 02: NONE
uint8_t DT135; // SP SET CROSSOVER 00: 40Hz / 01: 60Hz / 02: 80Hz / 03: 90Hz / 04: 100Hz / 05: 110Hz / 06: 120Hz / 07: 160Hz / 08: 200Hz
uint8_t DT136; // COMPONENT OSD 00: OFF / 01: ON
uint8_t DT137; // PB/SB SELECT 00: PR / 01: SB
uint8_t DT138[100]; // From here on is just buffer in case it sends more data
} AVR_Configuration_T;
typedef struct {
uint8_t type[5]; // Model ID
uint8_t version; // A-Z
uint8_t length[2]; // 1 - 255
} AVR_StatusHeader_T;
typedef struct {
bool headerValid;
bool configValid;
AVR_StatusHeader_T header;
AVR_Configuration_T config;
} AVR_Status_T;
//AVR_StatusHeader_T avrStatusHeader;
//AVR_Configuration_T avrConfigData;
AVR_Status_T avrStatus;
bool commandResponseReceived; // a response to the last command was received
bool readyResponsReceived; // the special system ready response was received
int readyTries;
#define RETRY_INTERVAL_ms 500
#define MAXTRIES 5
#define SERIALQUEUESIZE 5
typedef struct {
uint8_t *messageToSend;
uint16_t len;
} SerialQueue_T;
SerialQueue_T serialQueue[SERIALQUEUESIZE];
int serialQueueCount = 0;
bool bFirstTickInitialized;
uint32_t firstTick_ms; // basically the time when the program started
uint32_t lastTick_ms; // @TODO instead of this, offer a way for the class to get the current time
// Trampoline used to set the AVRDriver::NotifyHost to a function
// that dispatches into the instance method ProcessReportResponse.
static bool NotifyTrampoline(AVRMessageType_T type, const void *message, uint32_t attrib);
bool IsSanityCheckOK(); bool IsSanityCheckOK();
void MessageHandlerSanityCheck(); void MessageHandlerSanityCheck();
// host provided method to send to the AVR
bool (*SendMethod)(const uint8_t *buffer, uint16_t bufferSize);
// host provided method to update the user with a text message // host provided method to update the user with a text message
void(*ReportInformation)(AVRMessageType_T type, const char * message); //void(*ReportInformation)(AVRMessageType_T type, const char * message);
void PCMessage(const char *msg, int len, uint8_t **src, const char *(fncHelper)(uint8_t val) = NULL); uint8_t PCMessage(const char *msg, uint8_t len, uint8_t **src, const char *(fncHelper)(uint8_t val) = NULL, bool highlight = false);
bool ProcessReportResponse(const uint8_t *szBuffer, uint32_t len); bool ProcessReportResponse(AVRMessageType_T type, const void * message, uint32_t attrib);
void MessageReport(const char *prefix, const void *buf, size_t len = 0); void MessageReport(const char *prefix, const void *buf, size_t len = 0);
const char *MessageToText(const char *msg, size_t len); const char *MessageToText(const char *msg, size_t len);
bool CheckTheChecksum(const uint8_t *szBuffer, uint32_t num);
uint16_t Hex2Dec(const uint8_t *p, int dig);
void FreeMemory();
}; };

View File

@@ -1,4 +1,30 @@
// Something for later
//
// #include <windows.h>
// #include <stdio.h>
//
// void enable_ansi_escape_sequences(void) {
// HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
// DWORD mode = 0;
//
// if (!GetConsoleMode(hOut, &mode)) {
// return; // handle error if needed
// }
//
// mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
//
// SetConsoleMode(hOut, mode);
// }
//
// int main() {
// enable_ansi_escape_sequences();
//
// printf("\x1b[32mGreen text\x1b[0m\n");
// printf("\x1b[31mRed text\x1b[0m\n");
//
// return 0;
// }
#include "stdafx.h" #include "stdafx.h"
#include <Windows.h> #include <Windows.h>
@@ -17,6 +43,14 @@ static short consoleHeight = 0;
static short scrollBot = 0; // set at init: consoleHeight - 1 static short scrollBot = 0; // set at init: consoleHeight - 1
static short scrollTop = 0; // set at init: consoleHeight - consoleScrollHeight - 1 static short scrollTop = 0; // set at init: consoleHeight - consoleScrollHeight - 1
void Console_SetColor(WORD color) {
SetConsoleTextAttribute(hStdout, color);
}
void Console_RestoreColor() {
SetConsoleTextAttribute(hStdout, wOldColorAttrs);
}
void Console_Init(short Left, short Top, short Width, short Height, short bottomScrollHeight) { void Console_Init(short Left, short Top, short Width, short Height, short bottomScrollHeight) {
hStdin = GetStdHandle(STD_INPUT_HANDLE); hStdin = GetStdHandle(STD_INPUT_HANDLE);
hStdout = GetStdHandle(STD_OUTPUT_HANDLE); hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
@@ -24,6 +58,8 @@ void Console_Init(short Left, short Top, short Width, short Height, short bottom
fprintf(stderr, "Error: Unable to get console buffer info. Code: %lu\n", GetLastError()); fprintf(stderr, "Error: Unable to get console buffer info. Code: %lu\n", GetLastError());
exit(1); exit(1);
} }
wOldColorAttrs = csbi.wAttributes;
consoleWidth = Width; consoleWidth = Width;
consoleHeight = Height; consoleHeight = Height;
@@ -31,7 +67,7 @@ void Console_Init(short Left, short Top, short Width, short Height, short bottom
scrollTop = consoleHeight - bottomScrollHeight - 1; scrollTop = consoleHeight - bottomScrollHeight - 1;
// Desired size (width x height) // Desired size (width x height)
COORD newSize; COORD newSize = { 0, 0 };
newSize.X = consoleWidth; // columns newSize.X = consoleWidth; // columns
newSize.Y = consoleHeight; // rows newSize.Y = consoleHeight; // rows
@@ -42,7 +78,7 @@ void Console_Init(short Left, short Top, short Width, short Height, short bottom
} }
// Step 3: Set final window size to match buffer // Step 3: Set final window size to match buffer
SMALL_RECT newWindow; SMALL_RECT newWindow = { 0 };
newWindow.Left = 0; newWindow.Left = 0;
newWindow.Top = 0; newWindow.Top = 0;
newWindow.Right = newSize.X - 1; newWindow.Right = newSize.X - 1;
@@ -56,8 +92,6 @@ void Console_Init(short Left, short Top, short Width, short Height, short bottom
Console_SetWindowPosition(Left, Top); Console_SetWindowPosition(Left, Top);
wOldColorAttrs = csbi.wAttributes;
//SetConsoleTextAttribute(hStdout, FOREGROUND_RED | FOREGROUND_INTENSITY);
} }
void Console_Close() { void Console_Close() {

View File

@@ -6,6 +6,11 @@ void Console_Cls();
void Console_SetWindowPosition(int x, int y); void Console_SetWindowPosition(int x, int y);
bool Console_SetCursorVisibility(bool visible); bool Console_SetCursorVisibility(bool visible);
void Console_SetCursor(short x, short y); void Console_SetCursor(short x, short y);
//
// FOREGROUND_RED, FOREGROUND_GREEN, FOREGROUND_BLUE, FOREGROUND_INTENSITY
// BACKGROUND_RED, BACKGROUND_GREEN, BACKGROUND_BLUE, BACKGROUND_INTENSITY
void Console_SetColor(WORD color);
void Console_RestoreColor();
void Console_Write(const char *text); void Console_Write(const char *text);
void Console_WriteAt(short x, short y, const char *text); void Console_WriteAt(short x, short y, const char *text);
void Console_ScrollBottomRegion(); void Console_ScrollBottomRegion();

View File

@@ -37,7 +37,7 @@ bool CSerialPort::Open(LPCTSTR PortName, uint32_t BaudRate, BYTE ByteSize, BYTE
Close(); Close();
m_PortHandle = CreateFile(PortName, DesiredAccess, 0, NULL, OPEN_EXISTING, 0, 0); m_PortHandle = CreateFile(PortName, DesiredAccess, 0, NULL, OPEN_EXISTING, 0, 0);
if (m_PortHandle != INVALID_HANDLE_VALUE) { if (m_PortHandle != INVALID_HANDLE_VALUE) {
DCB dcb; DCB dcb = { 0 };
CString s; CString s;
dcb.DCBlength = sizeof(dcb); dcb.DCBlength = sizeof(dcb);
GetCommState(m_PortHandle, &dcb); GetCommState(m_PortHandle, &dcb);
@@ -66,7 +66,7 @@ bool CSerialPort::Open(LPCTSTR PortName, uint32_t BaudRate, BYTE ByteSize, BYTE
SetCommState(m_PortHandle, &dcb); SetCommState(m_PortHandle, &dcb);
COMMTIMEOUTS touts; COMMTIMEOUTS touts = { 0 };;
touts.ReadIntervalTimeout = UINT32_MAX; // This, plus the zero timeouts causes immediate return touts.ReadIntervalTimeout = UINT32_MAX; // This, plus the zero timeouts causes immediate return
touts.ReadTotalTimeoutMultiplier = 0; touts.ReadTotalTimeoutMultiplier = 0;
touts.ReadTotalTimeoutConstant = 0; touts.ReadTotalTimeoutConstant = 0;