Files
JackBotEsp32/JackBot/BotNetwork.cpp
T
2026-10-23 21:46:37 +02:00

90 lines
3.1 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;
}
// THE FIX: Access motion and display using '->'
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];
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 COMMANDS ---
if (header->packet_id == PKT_COMMAND) {
if (f_type == FT_ARRAY_F32 && f_len == 18) {
int tempLeg[6][3];
for (int i=0; i<6; i++) for (int j=0; j<3; j++) tempLeg[i][j] = data[i*3+j];
motion->pushFrame(tempLeg);
}
}
// --- BRANCH 2: DISPLAY COMMANDS (The Independent Part) ---
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';
// Draw to screen immediately
display->drawCenteredText(textBuffer, 0x07E0);
}
}
// --- BRANCH 3: CONFIGS ---
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);
// NOTE: To make this dynamic, we pass it to the motion controller
if (id == 1 || id == 2 || id == 3) {
// Normally you'd read the current configs, update one, and push back.
// For now, I've added a config method to your MotionController below.
Serial.printf("Config Sync received.\n");
}
}
}
pos += f_len;
}
}