93 lines
2.3 KiB
C++
93 lines
2.3 KiB
C++
#include "LinkService.h"
|
||
#include "../config/BoardPins.h"
|
||
#include "../config/AppConfig.h"
|
||
#include "../core/Log.h"
|
||
|
||
namespace svc {
|
||
|
||
LinkService link;
|
||
|
||
// 自定义帧:AA 55 | cmd | len | payload... | checksum
|
||
// 副控若使用别的格式,改这里即可,上层无感。
|
||
static const uint8_t HDR0 = 0xAA;
|
||
static const uint8_t HDR1 = 0x55;
|
||
|
||
void LinkService::begin() {
|
||
Serial1.begin(UART_BAUD, SERIAL_8N1, PIN_UART_RX, PIN_UART_TX);
|
||
LOG("LINK", "uart1 ready tx=%d rx=%d @%d", PIN_UART_TX, PIN_UART_RX, UART_BAUD);
|
||
}
|
||
|
||
void LinkService::sendRaw(const uint8_t* data, size_t len) {
|
||
Serial1.write(data, len);
|
||
Serial1.flush();
|
||
}
|
||
|
||
static void hexAppend(String& s, const uint8_t* d, size_t n) {
|
||
char b[4];
|
||
for (size_t i = 0; i < n; i++) {
|
||
snprintf(b, sizeof(b), "%02X ", d[i]);
|
||
s += b;
|
||
}
|
||
}
|
||
|
||
void LinkService::setVolume(uint8_t vol) {
|
||
uint8_t f[6] = {HDR0, HDR1, 0x10, 0x01, vol, (uint8_t)(0x10 + vol)};
|
||
sendRaw(f, sizeof(f));
|
||
LOG("LINK", "tx vol=%u", vol);
|
||
}
|
||
|
||
void LinkService::playPause() {
|
||
uint8_t f[5] = {HDR0, HDR1, 0x11, 0x00, 0x11};
|
||
sendRaw(f, sizeof(f));
|
||
LOG("LINK", "tx play/pause");
|
||
}
|
||
|
||
void LinkService::next() {
|
||
uint8_t f[5] = {HDR0, HDR1, 0x12, 0x00, 0x12};
|
||
sendRaw(f, sizeof(f));
|
||
}
|
||
|
||
void LinkService::prev() {
|
||
uint8_t f[5] = {HDR0, HDR1, 0x13, 0x00, 0x13};
|
||
sendRaw(f, sizeof(f));
|
||
}
|
||
|
||
void LinkService::feed(uint8_t b) {
|
||
_rxCount++;
|
||
_lastRxMs = millis();
|
||
if (_bufLen < sizeof(_buf)) _buf[_bufLen++] = b;
|
||
else {
|
||
memmove(_buf, _buf + 1, sizeof(_buf) - 1);
|
||
_buf[sizeof(_buf) - 1] = b;
|
||
}
|
||
|
||
// 留一份可读日志给调试页看(最多 512 字节的十六进制)
|
||
if (_rxLog.length() < 1024) {
|
||
hexAppend(_rxLog, &b, 1);
|
||
} else {
|
||
_rxLog = _rxLog.substring(64);
|
||
}
|
||
}
|
||
|
||
void LinkService::parse() {
|
||
// 第一版只做帧头探测,用来确认副控是否在主动上报
|
||
for (size_t i = 0; i + 1 < _bufLen; i++) {
|
||
if (_buf[i] == HDR0 && _buf[i + 1] == HDR1) {
|
||
_gotAnyPacket = true;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
void LinkService::loop() {
|
||
bool got = false;
|
||
while (Serial1.available()) {
|
||
feed((uint8_t)Serial1.read());
|
||
got = true;
|
||
if (_bufLen > 8) break;
|
||
}
|
||
if (got) parse();
|
||
}
|
||
|
||
} // namespace svc
|