Files
JackBotEsp32/BotNetwork.cpp
T

100 lines
3.5 KiB
C++

#include "BotNetwork.h"
IPAddress local_IP(192, 168, 188, 32);
IPAddress gateway(192, 168, 188, 1);
IPAddress subnet(255, 255, 255, 0);
BotNetwork::BotNetwork(const char* ssid, const char* pass, const char* ap_ssid, const char* ap_pass)
: _ssid(ssid), _pass(pass), _ap_ssid(ap_ssid), _ap_pass(ap_pass) {}
bool BotNetwork::begin(uint16_t port) {
WiFi.mode(WIFI_STA);
WiFi.config(local_IP, gateway, subnet);
WiFi.begin(_ssid, _pass);
unsigned long start = millis();
while (WiFi.status() != WL_CONNECTED && millis() - start < 8000) {
delay(200);
}
bool isWifi = true;
if (WiFi.status() != WL_CONNECTED) {
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(local_IP, local_IP, subnet);
WiFi.softAP(_ap_ssid, _ap_pass);
isWifi = false;
}
_udp.begin(port);
return isWifi;
}
int BotNetwork::readPacket(uint8_t* buffer, size_t maxSize) {
int size = _udp.parsePacket();
if (size > 0) return _udp.read(buffer, maxSize);
return 0;
}
void BotNetwork::parsePacket(uint8_t *buffer, size_t size, MotionController* motion, DisplayManager* display) {
if (size < sizeof(PacketHeader)) return;
PacketHeader *header = (PacketHeader *)buffer;
if (header->version != PACKET_VERSION) return;
uint8_t *payload = buffer + sizeof(PacketHeader);
size_t pos = 0;
int tempLeg[6][3];
// Temporary trackers for config values so we can update them cleanly
static int currentServoMin = 125;
static int currentServoMax = 625;
static int currentPythonInterval = 50;
while (pos < header->payload_len) {
uint8_t f_type = payload[pos++];
uint16_t f_len = payload[pos] | (payload[pos+1] << 8);
pos += 2;
uint8_t *data = payload + pos;
// --- BRANCH 1: MOTION & DISPLAY COMMANDS ---
if (header->packet_id == PKT_COMMAND) {
if (f_type == FT_ARRAY_F32 && f_len == 18) {
for (int i=0; i<6; i++) for (int j=0; j<3; j++) tempLeg[i][j] = data[i*3+j];
motion->pushFrame(tempLeg);
} else if (f_type == FT_STRING) {
char textBuffer[64];
size_t len = min((size_t)f_len, (size_t)63);
memcpy(textBuffer, data, len);
textBuffer[len] = '\0';
display->drawCenteredText(textBuffer, 0x07E0); // Green text
}
}
// --- BRANCH 2: DISPLAY PACKET (If your Python sends separate PKT_DISPLAY) ---
else if (header->packet_id == PKT_DISPLAY) {
if (f_type == FT_STRING) {
char textBuffer[64];
size_t len = min((size_t)f_len, (size_t)63);
memcpy(textBuffer, data, len);
textBuffer[len] = '\0';
display->drawCenteredText(textBuffer, 0x07E0);
}
}
// --- BRANCH 3: CONFIGS (FIXED) ---
else if (header->packet_id == PKT_CONFIG) {
if (f_type == FT_CONFIG_VAL) {
uint8_t id = data[0];
int16_t val = data[1] | (data[2] << 8);
if (id == 1) currentServoMin = val;
if (id == 2) currentServoMax = val;
if (id == 3) currentPythonInterval = val;
// Push the updated configs down into the MotionController
motion->setConfigs(currentServoMin, currentServoMax, currentPythonInterval);
Serial.printf("Config Sync: ID %d -> %d\n", id, val);
}
}
pos += f_len;
}
}