Compare commits
8 Commits
ec9ca8890c
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 883f536d21 | |||
| 3531430661 | |||
| 4e991a71b5 | |||
| b6b6ea799a | |||
| 789331ebd1 | |||
| 61be466a41 | |||
| de055dbf93 | |||
| 6dae4519e3 |
@@ -0,0 +1,134 @@
|
||||
#include <Adafruit_PWMServoDriver.h>
|
||||
#include <HardwareSerial.h>
|
||||
#include <SoftwareSerial.h>
|
||||
#include <Wire.h>
|
||||
|
||||
// Self Made Lib
|
||||
#include <JackBotEmotes.h>
|
||||
|
||||
// Verbindung
|
||||
Adafruit_PWMServoDriver board0 = Adafruit_PWMServoDriver(0x40);
|
||||
Adafruit_PWMServoDriver board1 = Adafruit_PWMServoDriver(0x41);
|
||||
SoftwareSerial BTSerial(11, 10); // RX | TX
|
||||
|
||||
// Konstanten
|
||||
#define SERVOMIN 125 // this is the 'minimum' pulse length count (out of 4096)
|
||||
#define SERVOMAX 625 // this is the 'maximum' pulse length count (out of 4096)
|
||||
#define BUFFERSIZE 128
|
||||
|
||||
// Variablen
|
||||
const int numRows = 6;
|
||||
const int numCols = 3;
|
||||
int legarray[numRows][numCols];
|
||||
char legBuffer[BUFFERSIZE];
|
||||
int bufIndex = 0;
|
||||
boolean reading = false;
|
||||
|
||||
JackBotEmotes face;
|
||||
|
||||
void setup() {
|
||||
// USB
|
||||
//Serial.begin(9600);
|
||||
// Bluetooth
|
||||
BTSerial.begin(38400);
|
||||
|
||||
board0.begin();
|
||||
board0.setPWMFreq(50);
|
||||
board1.begin();
|
||||
board1.setPWMFreq(50);
|
||||
pinMode(3, OUTPUT); //Define TX Pin as output
|
||||
pinMode(2, INPUT); //Define RX Pin as input
|
||||
|
||||
// Initialiesieren der Start Position
|
||||
for (int i = 0; i < 6; i++) {
|
||||
for (int j = 0; j < 3; j++) {
|
||||
legarray[i][j] = 90;
|
||||
}
|
||||
}
|
||||
ServoControll(legarray);
|
||||
|
||||
face.begin();
|
||||
face.showText("Hello JackBot!", 1, 0);
|
||||
}
|
||||
|
||||
|
||||
void loop() {
|
||||
face.update();
|
||||
|
||||
while (BTSerial.available()) {
|
||||
char c = BTSerial.read();
|
||||
|
||||
if (c == '<') {
|
||||
// reset buffer for new frame
|
||||
bufIndex = 0;
|
||||
reading = true;
|
||||
}
|
||||
else if (c == '>') {
|
||||
// end of frame
|
||||
if (reading) {
|
||||
legBuffer[bufIndex] = '\0'; // null-terminate string
|
||||
if (stringToArray(String(legBuffer))) {
|
||||
ServoControll(legarray);
|
||||
face.smile();
|
||||
face.showText("Moving!", 4, 1);
|
||||
} else {
|
||||
face.showText("Data Err!", 3, 1);
|
||||
}
|
||||
}
|
||||
reading = false;
|
||||
}
|
||||
else if (reading) {
|
||||
if (bufIndex < BUFFERSIZE - 1) {
|
||||
legBuffer[bufIndex++] = c;
|
||||
} else {
|
||||
// buffer overflow → discard this frame
|
||||
reading = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Funktion: Ansteuern der Servos
|
||||
void ServoControll(int leg[6][3]) {
|
||||
for (int i = 0; i < 6; i++) {
|
||||
for (int j = 0; j < 3; j++) {
|
||||
if (i < 3) {
|
||||
board0.setPWM(i * 3 + j, 0, angleToPulse(leg[i][j]));
|
||||
} else {
|
||||
board1.setPWM((i - 3) * 3 + j, 0, angleToPulse(leg[i][j]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Funktion: Konvertiert den Winkel in PWM
|
||||
int angleToPulse(int ang) {
|
||||
return map(ang, 0, 180, SERVOMIN, SERVOMAX);
|
||||
}
|
||||
|
||||
// Funktion: Konvertiert den String in das Array
|
||||
bool stringToArray(String input) {
|
||||
input.replace("\n", ",");
|
||||
char buffer[input.length() + 1];
|
||||
input.toCharArray(buffer, sizeof(buffer));
|
||||
|
||||
char *token = strtok(buffer, ",");
|
||||
int row = 0, col = 0;
|
||||
int count = 0;
|
||||
|
||||
while (token != NULL && row < numRows) {
|
||||
legarray[row][col] = atoi(token);
|
||||
count++;
|
||||
col++;
|
||||
if (col >= numCols) {
|
||||
col = 0;
|
||||
row++;
|
||||
}
|
||||
token = strtok(NULL, ",");
|
||||
}
|
||||
|
||||
return count == (numRows * numCols);
|
||||
}
|
||||
|
Before Width: | Height: | Size: 370 KiB After Width: | Height: | Size: 370 KiB |
@@ -0,0 +1,96 @@
|
||||
#include <Wire.h>
|
||||
#include <string.h>
|
||||
#include "BotNetwork.h"
|
||||
#include "MotionController.h"
|
||||
#include "DisplayManager.h"
|
||||
|
||||
// Initialize Objects
|
||||
BotNetwork botNetwork("PfLANze", "isteinbisschenengandiehals", "JackBot-AP", "robot-control");
|
||||
MotionController motion;
|
||||
DisplayManager display(5, 16, 17); // TFT_CS, TFT_DC, TFT_RST
|
||||
|
||||
static QueueHandle_t motionQueue = nullptr;
|
||||
static QueueHandle_t configQueue = nullptr;
|
||||
static QueueHandle_t displayQueue = nullptr;
|
||||
|
||||
static void servoTask(void*) {
|
||||
TickType_t lastWakeTime = xTaskGetTickCount();
|
||||
const TickType_t updatePeriod = pdMS_TO_TICKS(5);
|
||||
MotionFrame frame;
|
||||
MotionConfig config;
|
||||
|
||||
for (;;) {
|
||||
if (xQueueReceive(configQueue, &config, 0) == pdTRUE) {
|
||||
motion.setConfigs(config.minPulse, config.maxPulse, config.intervalMs);
|
||||
}
|
||||
if (xQueueReceive(motionQueue, &frame, 0) == pdTRUE) {
|
||||
motion.setTarget(frame);
|
||||
}
|
||||
motion.update();
|
||||
vTaskDelayUntil(&lastWakeTime, updatePeriod);
|
||||
}
|
||||
}
|
||||
|
||||
static void displayTask(void*) {
|
||||
display.begin();
|
||||
DisplayMessage message;
|
||||
|
||||
for (;;) {
|
||||
if (xQueueReceive(displayQueue, &message, pdMS_TO_TICKS(10)) == pdTRUE) {
|
||||
display.drawCenteredText(message.text, message.color);
|
||||
}
|
||||
display.update();
|
||||
}
|
||||
}
|
||||
|
||||
static void queueDisplayText(const char* text, uint16_t color) {
|
||||
if (!displayQueue) return;
|
||||
|
||||
DisplayMessage message;
|
||||
size_t length = strlen(text);
|
||||
if (length >= sizeof(message.text)) length = sizeof(message.text) - 1;
|
||||
memcpy(message.text, text, length);
|
||||
message.text[length] = '\0';
|
||||
message.color = color;
|
||||
xQueueOverwrite(displayQueue, &message);
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
delay(500);
|
||||
Wire.begin();
|
||||
Wire.setClock(400000);
|
||||
motion.begin();
|
||||
|
||||
motionQueue = xQueueCreate(1, sizeof(MotionFrame));
|
||||
configQueue = xQueueCreate(1, sizeof(MotionConfig));
|
||||
displayQueue = xQueueCreate(1, sizeof(DisplayMessage));
|
||||
if (!motionQueue || !configQueue || !displayQueue) {
|
||||
Serial.println("Failed to create task queues");
|
||||
while (true) delay(1000);
|
||||
}
|
||||
|
||||
if (xTaskCreate(servoTask, "Servo", 4096, nullptr, 3, nullptr) != pdPASS ||
|
||||
xTaskCreate(displayTask, "Display", 8192, nullptr, 1, nullptr) != pdPASS) {
|
||||
Serial.println("Failed to create application tasks");
|
||||
while (true) delay(1000);
|
||||
}
|
||||
|
||||
queueDisplayText("Connecting...", ST77XX_YELLOW);
|
||||
if (botNetwork.begin(3323)) {
|
||||
queueDisplayText("WiFi: Connected", ST77XX_CYAN);
|
||||
} else {
|
||||
queueDisplayText("AP: JackBot", ST77XX_MAGENTA);
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
uint8_t buffer[512];
|
||||
int size = botNetwork.readPacket(buffer, 512);
|
||||
|
||||
if (size > 0) {
|
||||
botNetwork.parsePacket(buffer, size, motionQueue, configQueue, displayQueue);
|
||||
}
|
||||
|
||||
delay(1);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
#include <Wire.h>
|
||||
#include <string.h>
|
||||
#include "BotNetwork.h"
|
||||
#include "MotionController.h"
|
||||
#include "DisplayManager.h"
|
||||
|
||||
// Initialize Objects
|
||||
BotNetwork botNetwork("PfLANze", "isteinbisschenengandiehals", "JackBot-AP", "robot-control");
|
||||
MotionController motion;
|
||||
DisplayManager display(5, 3, 2); // TFT_CS, TFT_DC, TFT_RST
|
||||
|
||||
static QueueHandle_t motionQueue = nullptr;
|
||||
static QueueHandle_t configQueue = nullptr;
|
||||
static QueueHandle_t displayQueue = nullptr;
|
||||
|
||||
static void servoTask(void*) {
|
||||
TickType_t lastWakeTime = xTaskGetTickCount();
|
||||
const TickType_t updatePeriod = pdMS_TO_TICKS(5);
|
||||
MotionFrame frame;
|
||||
MotionConfig config;
|
||||
|
||||
for (;;) {
|
||||
if (xQueueReceive(configQueue, &config, 0) == pdTRUE) {
|
||||
motion.setConfigs(config.minPulse, config.maxPulse, config.intervalMs);
|
||||
}
|
||||
if (xQueueReceive(motionQueue, &frame, 0) == pdTRUE) {
|
||||
motion.setTarget(frame);
|
||||
}
|
||||
motion.update();
|
||||
vTaskDelayUntil(&lastWakeTime, updatePeriod);
|
||||
}
|
||||
}
|
||||
|
||||
static void displayTask(void*) {
|
||||
display.begin();
|
||||
DisplayMessage message;
|
||||
|
||||
for (;;) {
|
||||
if (xQueueReceive(displayQueue, &message, pdMS_TO_TICKS(10)) == pdTRUE) {
|
||||
display.drawCenteredText(message.text, message.color);
|
||||
}
|
||||
display.update();
|
||||
}
|
||||
}
|
||||
|
||||
static void queueDisplayText(const char* text, uint16_t color) {
|
||||
if (!displayQueue) return;
|
||||
|
||||
DisplayMessage message;
|
||||
size_t length = strlen(text);
|
||||
if (length >= sizeof(message.text)) length = sizeof(message.text) - 1;
|
||||
memcpy(message.text, text, length);
|
||||
message.text[length] = '\0';
|
||||
message.color = color;
|
||||
xQueueOverwrite(displayQueue, &message);
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
Wire.begin(6,7);
|
||||
Wire.setClock(400000);
|
||||
|
||||
motion.begin();
|
||||
|
||||
motionQueue = xQueueCreate(1, sizeof(MotionFrame));
|
||||
configQueue = xQueueCreate(1, sizeof(MotionConfig));
|
||||
displayQueue = xQueueCreate(1, sizeof(DisplayMessage));
|
||||
if (!motionQueue || !configQueue || !displayQueue) {
|
||||
Serial.println("Failed to create task queues");
|
||||
while (true) delay(1000);
|
||||
}
|
||||
|
||||
if (xTaskCreate(servoTask, "Servo", 4096, nullptr, 3, nullptr) != pdPASS ||
|
||||
xTaskCreate(displayTask, "Display", 4096, nullptr, 1, nullptr) != pdPASS) {
|
||||
Serial.println("Failed to create application tasks");
|
||||
while (true) delay(1000);
|
||||
}
|
||||
|
||||
queueDisplayText("Connecting...", ST77XX_YELLOW);
|
||||
if (botNetwork.begin(3323)) {
|
||||
queueDisplayText("WiFi: Connected", ST77XX_CYAN);
|
||||
} else {
|
||||
queueDisplayText("AP: JackBot", ST77XX_MAGENTA);
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
uint8_t buffer[512];
|
||||
int size = botNetwork.readPacket(buffer, 512);
|
||||
|
||||
if (size > 0) {
|
||||
botNetwork.parsePacket(buffer, size, motionQueue, configQueue, displayQueue);
|
||||
}
|
||||
|
||||
delay(1);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
# JackBot Board Firmware
|
||||
|
||||
`BoardCode/` contains the firmware sketches for running JackBot on microcontroller
|
||||
boards. The Python simulator, manual-control application, and host-side communication
|
||||
configuration are documented in the [main README](../README.md).
|
||||
|
||||
## Sketches
|
||||
|
||||
| Sketch | Purpose |
|
||||
| --- | --- |
|
||||
| [`JackBotEsp32/JackBotEsp32.ino`](JackBotEsp32/JackBotEsp32.ino) | ESP32 firmware using the shared JackBot library and UDP networking. |
|
||||
| [`JackBotEsp32C3/JackBotEsp32C3.ino`](JackBotEsp32C3/JackBotEsp32C3.ino) | ESP32-C3 variant of the networked firmware. It initializes I2C on GPIO 6 and 7. |
|
||||
| [`JackBotArd/JackBotArd.ino`](JackBotArd/JackBotArd.ino) | Separate Arduino sketch using Bluetooth serial and PCA9685 servo boards. |
|
||||
|
||||
The ESP32 sketches use [`libaries/JackBot/`](libaries/JackBot/) (the directory name is
|
||||
spelled `libaries` in this repository). That library contains:
|
||||
|
||||
* `BotNetwork` for Wi-Fi/UDP packet handling;
|
||||
* `MotionController` for PCA9685 servo output and motion interpolation;
|
||||
* `DisplayManager` for the ST7789 display; and
|
||||
* `Protocol.h` for packet type and header definitions.
|
||||
|
||||
The `JackBotArd` sketch is a separate, older implementation; it does not use this
|
||||
shared ESP32 library.
|
||||
|
||||
## Build and upload
|
||||
|
||||
1. Install the Arduino IDE or Arduino CLI and the Espressif ESP32 board support
|
||||
package.
|
||||
2. Install the libraries required by the selected sketch. The ESP32 sketches use
|
||||
Adafruit PWM Servo Driver, Adafruit GFX, and Adafruit ST7735 and ST7789. The
|
||||
classic `JackBotArd` sketch uses Adafruit PWM Servo Driver and additionally
|
||||
includes `JackBotEmotes.h`; that dependency is not present in the shared
|
||||
`libaries/JackBot` library.
|
||||
3. Add `libaries/JackBot` as a local Arduino library (or copy it into your Arduino
|
||||
libraries directory) before building either ESP32 sketch.
|
||||
4. Open the desired `.ino` file, select the matching ESP32 board and serial port,
|
||||
then build and upload it.
|
||||
|
||||
Check the pin assignments in the selected sketch and the board's wiring before
|
||||
powering servos or displays. The ESP32-C3 sketch explicitly sets I2C to GPIO 6/7;
|
||||
the classic ESP32 sketch uses the board's default `Wire` pins. Display pins are
|
||||
specified when `DisplayManager` is constructed in each sketch.
|
||||
|
||||
## Network connection
|
||||
|
||||
The ESP32 sketches listen for UDP packets on port `3323` through `BotNetwork`. The
|
||||
network library is configured in the sketch constructor with Wi-Fi and fallback
|
||||
access-point settings. Set these to the values for your installation before upload;
|
||||
do not commit real network passwords to source control.
|
||||
|
||||
For host-side use, set `cfg.backend` to `BackendType.ESP32` and configure the ESP32
|
||||
address and port in the root project's `config.py`. The host communication layer
|
||||
and heartbeat behavior are described in the [main README](../README.md).
|
||||
|
||||
## Protocol and runtime notes
|
||||
|
||||
`Protocol.h` defines versioned packet types for motion commands, configuration,
|
||||
display messages, and ping/pong packets. `BotNetwork` parses received packets and
|
||||
passes motion/configuration/display updates to the sketch. The ESP32 sketches use
|
||||
FreeRTOS tasks and queues so servo updates and display updates run separately from
|
||||
packet reception.
|
||||
|
||||
The classic Arduino sketch instead reads framed Bluetooth serial input and drives
|
||||
two PCA9685 boards. It has a different transport and firmware path from the ESP32
|
||||
UDP implementation.
|
||||
@@ -0,0 +1,8 @@
|
||||
name=JackBot
|
||||
version=1.0.0
|
||||
author=JackM
|
||||
maintainer=JackM
|
||||
sentence=Shared JackBot board code
|
||||
paragraph=Shared code for JackBot Arduino sketches.
|
||||
category=Device Control
|
||||
architectures=esp32
|
||||
@@ -0,0 +1,117 @@
|
||||
#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;
|
||||
}
|
||||
|
||||
static void enqueueDisplayText(QueueHandle_t displayQueue, const uint8_t* data, size_t length) {
|
||||
if (!displayQueue) return;
|
||||
|
||||
DisplayMessage message;
|
||||
size_t textLength = length < sizeof(message.text) - 1 ? length : sizeof(message.text) - 1;
|
||||
memcpy(message.text, data, textLength);
|
||||
message.text[textLength] = '\0';
|
||||
message.color = 0x07E0;
|
||||
xQueueOverwrite(displayQueue, &message);
|
||||
}
|
||||
|
||||
void BotNetwork::parsePacket(uint8_t *buffer, size_t size, QueueHandle_t motionQueue,
|
||||
QueueHandle_t configQueue, QueueHandle_t displayQueue) {
|
||||
if (size < sizeof(PacketHeader)) return;
|
||||
PacketHeader *header = (PacketHeader *)buffer;
|
||||
if (header->version != PACKET_VERSION) return;
|
||||
if (header->payload_len > size - sizeof(PacketHeader)) return;
|
||||
|
||||
if (header->packet_id == PKT_PING && header->payload_len == 0) {
|
||||
PacketHeader response = {
|
||||
PKT_PONG,
|
||||
PACKET_VERSION,
|
||||
0,
|
||||
millis()
|
||||
};
|
||||
_udp.beginPacket(_udp.remoteIP(), _udp.remotePort());
|
||||
_udp.write((const uint8_t *)&response, sizeof(response));
|
||||
_udp.endPacket();
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t *payload = buffer + sizeof(PacketHeader);
|
||||
size_t pos = 0;
|
||||
|
||||
static int currentServoMin = 125;
|
||||
static int currentServoMax = 625;
|
||||
static int currentPythonInterval = 50;
|
||||
|
||||
while (pos < header->payload_len) {
|
||||
if (header->payload_len - pos < 3) return;
|
||||
uint8_t f_type = payload[pos++];
|
||||
uint16_t f_len = payload[pos] | (payload[pos+1] << 8);
|
||||
pos += 2;
|
||||
if (f_len > header->payload_len - pos) return;
|
||||
uint8_t *data = payload + pos;
|
||||
|
||||
if (header->packet_id == PKT_COMMAND) {
|
||||
if (f_type == FT_ARRAY_F32 && f_len == 18 && motionQueue) {
|
||||
MotionFrame frame;
|
||||
for (int i=0; i<6; i++) {
|
||||
for (int j=0; j<3; j++) frame.leg[i][j] = data[i*3+j];
|
||||
}
|
||||
xQueueOverwrite(motionQueue, &frame);
|
||||
} else if (f_type == FT_STRING) {
|
||||
enqueueDisplayText(displayQueue, data, f_len);
|
||||
}
|
||||
} else if (header->packet_id == PKT_DISPLAY) {
|
||||
if (f_type == FT_STRING) {
|
||||
enqueueDisplayText(displayQueue, data, f_len);
|
||||
}
|
||||
} else if (header->packet_id == PKT_CONFIG) {
|
||||
if (f_type == FT_CONFIG_VAL && f_len >= 3) {
|
||||
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;
|
||||
|
||||
MotionConfig config;
|
||||
config.minPulse = currentServoMin;
|
||||
config.maxPulse = currentServoMax;
|
||||
config.intervalMs = currentPythonInterval;
|
||||
if (configQueue) xQueueOverwrite(configQueue, &config);
|
||||
Serial.printf("Config Sync: ID %d -> %d\n", id, val);
|
||||
}
|
||||
}
|
||||
pos += f_len;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#ifndef BOTMANAGER_H
|
||||
#define BOTMANAGER_H
|
||||
|
||||
#include <WiFi.h>
|
||||
#include <WiFiUdp.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/queue.h>
|
||||
#include "Protocol.h"
|
||||
#include "MotionController.h"
|
||||
#include "DisplayManager.h"
|
||||
|
||||
class BotNetwork {
|
||||
public:
|
||||
BotNetwork(const char* ssid, const char* pass, const char* ap_ssid, const char* ap_pass);
|
||||
bool begin(uint16_t port); // Returns true if WiFi, false if AP
|
||||
int readPacket(uint8_t* buffer, size_t maxSize);
|
||||
|
||||
void parsePacket(uint8_t *buffer, size_t size, QueueHandle_t motionQueue,
|
||||
QueueHandle_t configQueue, QueueHandle_t displayQueue);
|
||||
|
||||
private:
|
||||
const char* _ssid;
|
||||
const char* _pass;
|
||||
const char* _ap_ssid;
|
||||
const char* _ap_pass;
|
||||
WiFiUDP _udp;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,133 @@
|
||||
#include "DisplayManager.h"
|
||||
#include "img/image_cards_hearts_bits.h"
|
||||
#include "img/image_paint_3_bits.h"
|
||||
#include "img/tenor.h"
|
||||
#include <string.h>
|
||||
|
||||
|
||||
DisplayManager::DisplayManager(int8_t cs, int8_t dc, int8_t rst)
|
||||
: _tft(cs, dc, rst) {}
|
||||
|
||||
static void drawAnimationFrame(Adafruit_ST7789& tft, int16_t x, uint8_t frame) {
|
||||
uint16_t pixels[240];
|
||||
const uint8_t* bitmap = tenor_frames[frame];
|
||||
|
||||
tft.startWrite();
|
||||
tft.setAddrWindow(x, 0, 240, 240);
|
||||
for (int16_t y = 0; y < 240; y++) {
|
||||
for (int16_t byteIndex = 0; byteIndex < 30; byteIndex++) {
|
||||
uint8_t bits = pgm_read_byte(&bitmap[y * 30 + byteIndex]);
|
||||
for (uint8_t bit = 0; bit < 8; bit++) {
|
||||
pixels[byteIndex * 8 + bit] = (bits & (0x80 >> bit)) ? ST77XX_WHITE : ST77XX_BLACK;
|
||||
}
|
||||
}
|
||||
tft.writePixels(pixels, 240);
|
||||
}
|
||||
tft.endWrite();
|
||||
}
|
||||
|
||||
void DisplayManager::begin() {
|
||||
_tft.init(240, 320);
|
||||
_tft.setRotation(1);
|
||||
clear();
|
||||
drawFaceScreen();
|
||||
}
|
||||
|
||||
void DisplayManager::clear() {
|
||||
_tft.fillScreen(ST77XX_BLACK);
|
||||
}
|
||||
|
||||
void DisplayManager::setState(DisplayState state) {
|
||||
_currentState = state;
|
||||
// Force a redraw when state changes
|
||||
if (_currentState == STATE_FACE) {
|
||||
drawFaceScreen();
|
||||
} else {
|
||||
drawMenuScreen();
|
||||
}
|
||||
}
|
||||
|
||||
void DisplayManager::toggleState() {
|
||||
if (_currentState == STATE_FACE) {
|
||||
setState(STATE_MENU);
|
||||
} else {
|
||||
setState(STATE_FACE);
|
||||
}
|
||||
}
|
||||
|
||||
void DisplayManager::update() {
|
||||
if (_currentState != STATE_FACE) return;
|
||||
|
||||
unsigned long now = millis();
|
||||
if (_showingText) {
|
||||
if (now - _textShownAt < 2000) return;
|
||||
drawFaceScreen();
|
||||
}
|
||||
|
||||
if (now - _lastScreenUpdate < 71) return;
|
||||
_lastScreenUpdate = now;
|
||||
|
||||
int16_t x = (_tft.width() - 240) / 2;
|
||||
drawAnimationFrame(_tft, x, _animationFrame);
|
||||
_tft.drawBitmap(x + 105, 14, image_cards_hearts_bits, 30, 32, 0xE8EC);
|
||||
_animationFrame = (_animationFrame + 1) % 8;
|
||||
}
|
||||
|
||||
// --- DESIGNED VIA LOPAKA.APP ---
|
||||
void DisplayManager::drawFaceScreen() {
|
||||
_showingText = false;
|
||||
_animationFrame = 0;
|
||||
clear();
|
||||
int16_t x = (_tft.width() - 240) / 2;
|
||||
_tft.drawBitmap(x, 0, image_paint_3_bits, 240, 240, ST77XX_WHITE);
|
||||
_tft.drawBitmap(x + 105, 14, image_cards_hearts_bits, 30, 32, 0xE8EC);
|
||||
}
|
||||
|
||||
void DisplayManager::drawMenuScreen() {
|
||||
_showingText = false;
|
||||
clear();
|
||||
|
||||
// Example Menu/Stats UI layout adapted from Lopaka export
|
||||
_tft.drawRect(10, 10, 300, 220, ST77XX_BLUE); // Outer box
|
||||
|
||||
_tft.setTextColor(ST77XX_WHITE);
|
||||
_tft.setTextSize(2);
|
||||
_tft.setCursor(30, 30);
|
||||
_tft.print("-- JACKBOT CONFIG --");
|
||||
|
||||
_tft.setTextSize(1);
|
||||
_tft.setCursor(30, 80);
|
||||
_tft.print("Status: Connected (UDP)");
|
||||
|
||||
_tft.setCursor(30, 110);
|
||||
_tft.print("Servo Profile: Standard");
|
||||
|
||||
_tft.setCursor(30, 140);
|
||||
_tft.print("Press button to exit menu");
|
||||
}
|
||||
|
||||
void DisplayManager::drawCenteredText(const char* text, uint16_t color) {
|
||||
if (_currentState != STATE_FACE || text == nullptr) return;
|
||||
if (strcmp(text, _lastText) == 0) return;
|
||||
|
||||
size_t textLength = strlen(text);
|
||||
if (textLength >= sizeof(_lastText)) textLength = sizeof(_lastText) - 1;
|
||||
memcpy(_lastText, text, textLength);
|
||||
_lastText[textLength] = '\0';
|
||||
|
||||
_showingText = true;
|
||||
_textShownAt = millis();
|
||||
clear();
|
||||
_tft.setTextSize(2);
|
||||
_tft.setTextColor(color);
|
||||
|
||||
int16_t x1, y1;
|
||||
uint16_t w, h;
|
||||
_tft.getTextBounds(text, 0, 0, &x1, &y1, &w, &h);
|
||||
|
||||
int16_t cx = (_tft.width() - w) / 2;
|
||||
int16_t cy = (_tft.height() - h) / 2;
|
||||
|
||||
_tft.setCursor(cx, cy);
|
||||
_tft.print(text);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
#ifndef DISPLAYMANAGER_H
|
||||
#define DISPLAYMANAGER_H
|
||||
|
||||
#include <Adafruit_GFX.h>
|
||||
#include <Adafruit_ST7789.h>
|
||||
|
||||
enum DisplayState {
|
||||
STATE_FACE,
|
||||
STATE_MENU
|
||||
};
|
||||
|
||||
struct DisplayMessage {
|
||||
char text[64];
|
||||
uint16_t color;
|
||||
};
|
||||
|
||||
class DisplayManager {
|
||||
public:
|
||||
DisplayManager(int8_t cs, int8_t dc, int8_t rst);
|
||||
|
||||
void begin();
|
||||
void update();
|
||||
|
||||
void drawCenteredText(const char* text, uint16_t color);
|
||||
void setState(DisplayState state);
|
||||
void toggleState(); // Switches between Face and Menu
|
||||
|
||||
// Lopaka-generated screen renderers
|
||||
void drawFaceScreen();
|
||||
void drawMenuScreen();
|
||||
void clear();
|
||||
|
||||
private:
|
||||
Adafruit_ST7789 _tft;
|
||||
DisplayState _currentState = STATE_FACE;
|
||||
unsigned long _lastScreenUpdate = 0;
|
||||
unsigned long _textShownAt = 0;
|
||||
bool _showingText = false;
|
||||
uint8_t _animationFrame = 0;
|
||||
char _lastText[64] = {};
|
||||
};
|
||||
|
||||
#endif
|
||||
Binary file not shown.
@@ -0,0 +1,71 @@
|
||||
#include "MotionController.h"
|
||||
#include <math.h>
|
||||
|
||||
MotionController::MotionController() : board0(0x40), board1(0x41) {}
|
||||
|
||||
void MotionController::begin() {
|
||||
board0.begin(); board0.setPWMFreq(50);
|
||||
board1.begin(); board1.setPWMFreq(50);
|
||||
// Initialize current position at 90 degrees
|
||||
for(int i=0; i<6; i++) {
|
||||
for(int j=0; j<3; j++) {
|
||||
currentLegF[i][j] = 90.0;
|
||||
targetLeg[i][j] = 90.0;
|
||||
}
|
||||
}
|
||||
writeServos(currentLegF);
|
||||
}
|
||||
|
||||
void MotionController::update() {
|
||||
bool moved = false;
|
||||
for(int i=0; i<6; i++) {
|
||||
for(int j=0; j<3; j++) {
|
||||
float remaining = targetLeg[i][j] - currentLegF[i][j];
|
||||
float step = stepSize[i][j];
|
||||
if (fabsf(remaining) > fabsf(step)) {
|
||||
currentLegF[i][j] += step;
|
||||
} else {
|
||||
currentLegF[i][j] = targetLeg[i][j];
|
||||
}
|
||||
if (currentLegF[i][j] != targetLeg[i][j] || remaining != 0.0f) {
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (moved) {
|
||||
writeServos(currentLegF);
|
||||
}
|
||||
}
|
||||
|
||||
void MotionController::setTarget(const MotionFrame& frame) {
|
||||
int numSteps = (_pythonInterval + 4) / 5;
|
||||
if (numSteps < 1) numSteps = 1;
|
||||
|
||||
for(int i=0; i<6; i++) {
|
||||
for(int j=0; j<3; j++) {
|
||||
targetLeg[i][j] = (float)frame.leg[i][j];
|
||||
stepSize[i][j] = (targetLeg[i][j] - currentLegF[i][j]) / (float)numSteps;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MotionController::setConfigs(int minP, int maxP, int interval) {
|
||||
_servoMin = minP;
|
||||
_servoMax = maxP;
|
||||
_pythonInterval = interval < 5 ? 5 : interval;
|
||||
}
|
||||
|
||||
void MotionController::writeServos(float leg[6][3]) {
|
||||
for (int i = 0; i < 6; i++) {
|
||||
for (int j = 0; j < 3; j++) {
|
||||
int pulse = map((int)leg[i][j], 0, 180, _servoMin, _servoMax);
|
||||
if (i < 3) board0.setPWM(i * 3 + j, 0, pulse);
|
||||
else board1.setPWM((i - 3) * 3 + j, 0, pulse);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int MotionController::degToPulse(int deg) {
|
||||
return map(deg, 0, 180, _servoMin, _servoMax);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
#ifndef MOTIONCONTROLLER_H
|
||||
#define MOTIONCONTROLLER_H
|
||||
|
||||
#include <Adafruit_PWMServoDriver.h>
|
||||
#include "Protocol.h"
|
||||
|
||||
struct MotionFrame { int leg[6][3]; };
|
||||
struct MotionConfig { int minPulse; int maxPulse; int intervalMs; };
|
||||
|
||||
class MotionController {
|
||||
public:
|
||||
MotionController();
|
||||
void begin();
|
||||
void update();
|
||||
void setTarget(const MotionFrame& frame);
|
||||
void setConfigs(int minP, int maxP, int interval);
|
||||
|
||||
private:
|
||||
void writeServos(float leg[6][3]);
|
||||
int degToPulse(int deg);
|
||||
|
||||
Adafruit_PWMServoDriver board0;
|
||||
Adafruit_PWMServoDriver board1;
|
||||
|
||||
// Movement state
|
||||
float targetLeg[6][3];
|
||||
float currentLegF[6][3];
|
||||
float stepSize[6][3];
|
||||
|
||||
// Configs
|
||||
int _servoMin = 125;
|
||||
int _servoMax = 625;
|
||||
int _pythonInterval = 50;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,22 @@
|
||||
#ifndef PROTOCOL_H
|
||||
#define PROTOCOL_H
|
||||
|
||||
#define PACKET_VERSION 1
|
||||
#define PKT_COMMAND 1
|
||||
#define PKT_CONFIG 2
|
||||
#define PKT_DISPLAY 3
|
||||
#define PKT_PING 4
|
||||
#define PKT_PONG 5
|
||||
|
||||
#define FT_ARRAY_F32 1
|
||||
#define FT_STRING 2
|
||||
#define FT_UINT8 3
|
||||
#define FT_CONFIG_VAL 4
|
||||
|
||||
struct PacketHeader {
|
||||
uint8_t packet_id;
|
||||
uint8_t version;
|
||||
uint16_t payload_len;
|
||||
uint32_t timestamp;
|
||||
};
|
||||
#endif
|
||||
@@ -0,0 +1,8 @@
|
||||
#ifndef IMAGE_CARDS_HEARTS_BITS_H
|
||||
#define IMAGE_CARDS_HEARTS_BITS_H
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
static const unsigned char PROGMEM image_cards_hearts_bits[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0f,0xc0,0x0f,0xc0,0x0f,0xc0,0x0f,0xc0,0x3f,0xf0,0x3f,0xf0,0x3f,0xf0,0x3f,0xf0,0xff,0xfc,0xff,0xfc,0xff,0xfc,0xff,0xfc,0xff,0xff,0xff,0xfc,0xff,0xff,0xff,0xfc,0xff,0xff,0xff,0xfc,0xff,0xff,0xff,0xfc,0xff,0xff,0xff,0xfc,0xff,0xff,0xff,0xfc,0x3f,0xff,0xff,0xf0,0x3f,0xff,0xff,0xf0,0x0f,0xff,0xff,0xc0,0x0f,0xff,0xff,0xc0,0x03,0xff,0xff,0x00,0x03,0xff,0xff,0x00,0x00,0xff,0xfc,0x00,0x00,0xff,0xfc,0x00,0x00,0x3f,0xf0,0x00,0x00,0x3f,0xf0,0x00,0x00,0x0f,0xc0,0x00,0x00,0x0f,0xc0,0x00,0x00,0x03,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
|
||||
|
||||
#endif // IMAGE_CARDS_HEARTS_BITS_H
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+166
-31
@@ -2,8 +2,8 @@ import socket
|
||||
import struct
|
||||
import time
|
||||
import numpy as np
|
||||
from threading import Thread, Event
|
||||
from queue import Queue
|
||||
from threading import Thread, Event, Lock
|
||||
from queue import Empty, Full, Queue
|
||||
|
||||
from config import cfg
|
||||
import DataTypes as dt
|
||||
@@ -15,6 +15,8 @@ PACKET_VERSION = 1
|
||||
PKT_COMMAND = 1
|
||||
PKT_CONFIG = 2
|
||||
PKT_DISPLAY = 3
|
||||
PKT_PING = 4
|
||||
PKT_PONG = 5
|
||||
|
||||
FT_ARRAY_F32 = 1
|
||||
FT_STRING = 2
|
||||
@@ -23,6 +25,9 @@ FT_CONFIG_VAL = 4
|
||||
|
||||
HEADER_FMT = "<B B H I" # ID, Ver, Len, Timestamp
|
||||
TLV_FMT = "<B H"
|
||||
HEARTBEAT_INTERVAL = 0.5
|
||||
CONNECTION_TIMEOUT = 2.0
|
||||
RECONNECT_TIMEOUT = 30.0
|
||||
|
||||
class ESP32Communication(Thread):
|
||||
def __init__(self, host=None, port=None, ip=None):
|
||||
@@ -33,29 +38,125 @@ class ESP32Communication(Thread):
|
||||
port = cfg.esp32_port if port is None else port
|
||||
self.addr = (host, port)
|
||||
|
||||
# UDP Socket - Zero Lag
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self.sock.settimeout(0.1)
|
||||
|
||||
self.tx_queue = Queue()
|
||||
self.tx_queue = Queue(maxsize=1)
|
||||
self._motion_lock = Lock()
|
||||
self._latest_motion_packet = None
|
||||
self._config_packet = None
|
||||
self._config_pending = False
|
||||
self._config_generation = 0
|
||||
self.running = Event()
|
||||
self.running.set()
|
||||
self.last_motion_data = None
|
||||
self._connection_status = "connecting"
|
||||
self._last_pong_time = None
|
||||
self._reconnect_deadline = time.monotonic() + RECONNECT_TIMEOUT
|
||||
self._next_heartbeat_time = 0.0
|
||||
self._receiver_thread = None
|
||||
print(f"Communication Initialized: Target {host}:{port}")
|
||||
|
||||
@property
|
||||
def connection_status(self):
|
||||
return self._connection_status
|
||||
|
||||
def run(self):
|
||||
# --- THE FIX: Send Configs immediately upon starting the thread ---
|
||||
self.sync_robot_configs()
|
||||
|
||||
self._receiver_thread = Thread(target=self._receive_loop, daemon=True)
|
||||
self._receiver_thread.start()
|
||||
next_motion_time = time.monotonic()
|
||||
|
||||
try:
|
||||
while self.running.is_set():
|
||||
now = time.monotonic()
|
||||
if self._connection_status != "disconnected" and now >= self._next_heartbeat_time:
|
||||
self._send_packet(self._build_packet(PKT_PING, []), "heartbeat")
|
||||
self._next_heartbeat_time = now + HEARTBEAT_INTERVAL
|
||||
|
||||
if self._connection_status == "connected":
|
||||
self._send_pending_config()
|
||||
if now >= next_motion_time:
|
||||
with self._motion_lock:
|
||||
motion_packet = self._latest_motion_packet
|
||||
if motion_packet is not None:
|
||||
self._send_packet(motion_packet, "motion")
|
||||
try:
|
||||
queued_packet = self.tx_queue.get_nowait()
|
||||
except Empty:
|
||||
pass
|
||||
else:
|
||||
self._send_packet(queued_packet, "queued")
|
||||
|
||||
next_motion_time += cfg.tick_duration
|
||||
if next_motion_time <= now:
|
||||
next_motion_time = now + cfg.tick_duration
|
||||
|
||||
sleep_time = min(0.01, max(0.0, next_motion_time - time.monotonic()))
|
||||
time.sleep(sleep_time)
|
||||
finally:
|
||||
try:
|
||||
self.sock.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _send_packet(self, packet, packet_type):
|
||||
try:
|
||||
self.sock.sendto(packet, self.addr)
|
||||
except OSError as exc:
|
||||
if self.running.is_set():
|
||||
print(f"UDP {packet_type.capitalize()} Send Error: {exc}")
|
||||
|
||||
def _send_pending_config(self):
|
||||
with self._motion_lock:
|
||||
packet = self._config_packet if self._config_pending else None
|
||||
generation = self._config_generation
|
||||
if packet is None:
|
||||
return
|
||||
|
||||
try:
|
||||
self.sock.sendto(packet, self.addr)
|
||||
except OSError as exc:
|
||||
if self.running.is_set():
|
||||
print(f"UDP Config Send Error: {exc}")
|
||||
else:
|
||||
with self._motion_lock:
|
||||
if generation == self._config_generation:
|
||||
self._config_pending = False
|
||||
|
||||
def _receive_loop(self):
|
||||
while self.running.is_set():
|
||||
if not self.tx_queue.empty():
|
||||
data = self.tx_queue.get()
|
||||
try:
|
||||
self.sock.sendto(data, self.addr)
|
||||
except Exception as e:
|
||||
print(f"UDP Send Error: {e}")
|
||||
|
||||
# Tiny sleep to prevent 100% CPU usage
|
||||
time.sleep(0.001)
|
||||
try:
|
||||
data, sender = self.sock.recvfrom(1024)
|
||||
except socket.timeout:
|
||||
pass
|
||||
except ConnectionRefusedError:
|
||||
pass
|
||||
except OSError as exc:
|
||||
if self.running.is_set():
|
||||
print(f"UDP Receive Error: {exc}")
|
||||
time.sleep(0.1)
|
||||
continue
|
||||
return
|
||||
else:
|
||||
self._handle_response(data, sender)
|
||||
|
||||
now = time.monotonic()
|
||||
if (
|
||||
self._connection_status == "connected"
|
||||
and self._last_pong_time is not None
|
||||
and now - self._last_pong_time > CONNECTION_TIMEOUT
|
||||
):
|
||||
self._connection_status = "reconnecting"
|
||||
self._reconnect_deadline = now + RECONNECT_TIMEOUT
|
||||
self._clear_tx_queue()
|
||||
elif (
|
||||
self._connection_status in ("connecting", "reconnecting")
|
||||
and now >= self._reconnect_deadline
|
||||
):
|
||||
self._connection_status = "disconnected"
|
||||
self._clear_tx_queue()
|
||||
self.running.clear()
|
||||
return
|
||||
|
||||
def sync_robot_configs(self):
|
||||
"""
|
||||
@@ -82,24 +183,18 @@ class ESP32Communication(Thread):
|
||||
fields.append(struct.pack(TLV_FMT, FT_CONFIG_VAL, len(payload)) + payload)
|
||||
|
||||
packet = self._build_packet(PKT_CONFIG, fields)
|
||||
self.tx_queue.put(packet)
|
||||
with self._motion_lock:
|
||||
self._config_packet = packet
|
||||
self._config_pending = True
|
||||
self._config_generation += 1
|
||||
|
||||
def send_motion(self, radial_array: dt.RadArray):
|
||||
"""Sends motion only if the data has changed."""
|
||||
# 1. Convert to degrees/uint8 as you did before
|
||||
"""Store the latest command for transmission at the configured tick rate."""
|
||||
new_data = np.degrees(radial_array.data).astype(np.uint8)
|
||||
|
||||
# 2. Check if it's different from the last sent packet
|
||||
if self.last_motion_data is not None:
|
||||
if np.array_equal(new_data, self.last_motion_data):
|
||||
return # Skip sending if data is identical
|
||||
|
||||
# 3. Update the tracker and send
|
||||
self.last_motion_data = new_data.copy()
|
||||
|
||||
fields = [self._tlv(FT_ARRAY_F32, new_data.tobytes())]
|
||||
packet = self._build_packet(PKT_COMMAND, fields)
|
||||
self.tx_queue.put(packet)
|
||||
with self._motion_lock:
|
||||
self._latest_motion_packet = packet
|
||||
|
||||
def send_text(self, text=""):
|
||||
"""Sends a dedicated display packet independent of motion."""
|
||||
@@ -112,7 +207,47 @@ class ESP32Communication(Thread):
|
||||
# Build the packet using the PKT_DISPLAY (ID 3)
|
||||
packet = self._build_packet(PKT_DISPLAY, [field])
|
||||
|
||||
self.tx_queue.put(packet)
|
||||
self._queue_latest(packet)
|
||||
|
||||
def _handle_response(self, data, sender):
|
||||
if self._connection_status == "disconnected":
|
||||
return
|
||||
|
||||
if sender != self.addr:
|
||||
return
|
||||
|
||||
header_size = struct.calcsize(HEADER_FMT)
|
||||
if len(data) != header_size:
|
||||
return
|
||||
|
||||
packet_id, version, payload_length, _ = struct.unpack(HEADER_FMT, data)
|
||||
if packet_id != PKT_PONG or version != PACKET_VERSION or payload_length != 0:
|
||||
return
|
||||
|
||||
was_connected = self._connection_status == "connected"
|
||||
self._connection_status = "connected"
|
||||
self._last_pong_time = time.monotonic()
|
||||
if not was_connected:
|
||||
with self._motion_lock:
|
||||
self._config_pending = True
|
||||
self._config_generation += 1
|
||||
|
||||
def _queue_latest(self, packet):
|
||||
try:
|
||||
self.tx_queue.put_nowait(packet)
|
||||
except Full:
|
||||
try:
|
||||
self.tx_queue.get_nowait()
|
||||
except Empty:
|
||||
pass
|
||||
self.tx_queue.put_nowait(packet)
|
||||
|
||||
def _clear_tx_queue(self):
|
||||
while True:
|
||||
try:
|
||||
self.tx_queue.get_nowait()
|
||||
except Empty:
|
||||
return
|
||||
|
||||
def _tlv(self, ftype, data):
|
||||
return struct.pack(TLV_FMT, ftype, len(data)) + data
|
||||
@@ -132,7 +267,7 @@ class ESP32Communication(Thread):
|
||||
self.running.clear()
|
||||
try:
|
||||
self.sock.close()
|
||||
except Exception:
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
|
||||
+713
-822
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,158 @@
|
||||
<?xml version="1.0"?>
|
||||
<robot name="JackBot" xmlns:xacro="http://www.ros.org/wiki/xacro">
|
||||
<xacro:property name="coxa_length" value="0.0627"/>
|
||||
<xacro:property name="coxa_diagonal_x" value="0.098574"/>
|
||||
<xacro:property name="coxa_diagonal_y" value="0.068584"/>
|
||||
<xacro:property name="coxa_center_x" value="0"/>
|
||||
<xacro:property name="coxa_center_y" value="0.08565"/>
|
||||
<xacro:property name="femur_length" value="0.0602"/>
|
||||
<xacro:property name="tibia_length" value="0.08055"/>
|
||||
<xacro:property name="leg_radius" value="0.005"/>
|
||||
<xacro:property name="tip_radius" value="0.01"/>
|
||||
<xacro:property name="base_size" value="0.200 0.140 0.090"/>
|
||||
<xacro:property name="joint_lower_limit" value="0.2618"/>
|
||||
<xacro:property name="joint_upper_limit" value="2.8798"/>
|
||||
<xacro:property name="joint_effort" value="1"/>
|
||||
<xacro:property name="joint_velocity" value="1"/>
|
||||
|
||||
<xacro:macro name="default_inertial" params="">
|
||||
<inertial>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<mass value="1"/>
|
||||
<inertia
|
||||
ixx="0.001" ixy="0" ixz="0"
|
||||
iyy="0.001" iyz="0"
|
||||
izz="0.001"/>
|
||||
</inertial>
|
||||
</xacro:macro>
|
||||
|
||||
<link name="base_link">
|
||||
<xacro:default_inertial/>
|
||||
<visual>
|
||||
<geometry>
|
||||
<box size="${base_size}"/>
|
||||
</geometry>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<material name="red">
|
||||
<color rgba="1 0 0 0.5"/>
|
||||
</material>
|
||||
</visual>
|
||||
<collision>
|
||||
<geometry>
|
||||
<box size="${base_size}"/>
|
||||
</geometry>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
</collision>
|
||||
</link>
|
||||
|
||||
<xacro:macro name="leg" params="id x y yaw femur_roll">
|
||||
<link name="leg${id}_coxa">
|
||||
<xacro:default_inertial/>
|
||||
<visual>
|
||||
<geometry>
|
||||
<cylinder length="${coxa_length}" radius="${leg_radius}"/>
|
||||
</geometry>
|
||||
<origin xyz="${coxa_length / 2} 0 0" rpy="0 1.5708 0"/>
|
||||
<material name="green">
|
||||
<color rgba="0 1 0 1"/>
|
||||
</material>
|
||||
</visual>
|
||||
<collision>
|
||||
<geometry>
|
||||
<cylinder length="${coxa_length}" radius="${leg_radius}"/>
|
||||
</geometry>
|
||||
<origin xyz="${coxa_length / 2} 0 0" rpy="0 1.5708 0"/>
|
||||
</collision>
|
||||
</link>
|
||||
<joint name="leg${id}_coxa_joint" type="revolute">
|
||||
<parent link="base_link"/>
|
||||
<child link="leg${id}_coxa"/>
|
||||
<origin xyz="${x} ${y} 0" rpy="0 0 ${yaw}"/>
|
||||
<axis xyz="0 0 1"/>
|
||||
<limit lower="${joint_lower_limit}" upper="${joint_upper_limit}" effort="${joint_effort}" velocity="${joint_velocity}"/>
|
||||
</joint>
|
||||
|
||||
<link name="leg${id}_femur">
|
||||
<xacro:default_inertial/>
|
||||
<visual>
|
||||
<geometry>
|
||||
<cylinder length="${femur_length}" radius="${leg_radius}"/>
|
||||
</geometry>
|
||||
<origin xyz="0 0 -${femur_length / 2}" rpy="0 0 0"/>
|
||||
<material name="blue">
|
||||
<color rgba="0 0 1 1"/>
|
||||
</material>
|
||||
</visual>
|
||||
<collision>
|
||||
<geometry>
|
||||
<cylinder length="${femur_length}" radius="${leg_radius}"/>
|
||||
</geometry>
|
||||
<origin xyz="0 0 -${femur_length / 2}" rpy="0 0 0"/>
|
||||
</collision>
|
||||
</link>
|
||||
<joint name="leg${id}_femur_joint" type="revolute">
|
||||
<parent link="leg${id}_coxa"/>
|
||||
<child link="leg${id}_femur"/>
|
||||
<origin xyz="${coxa_length} 0 0" rpy="${femur_roll} 0 0"/>
|
||||
<axis xyz="0 -1 0"/>
|
||||
<limit lower="${joint_lower_limit}" upper="${joint_upper_limit}" effort="${joint_effort}" velocity="${joint_velocity}"/>
|
||||
</joint>
|
||||
|
||||
<link name="leg${id}_tibia">
|
||||
<xacro:default_inertial/>
|
||||
<visual>
|
||||
<geometry>
|
||||
<cylinder length="${tibia_length}" radius="${leg_radius}"/>
|
||||
</geometry>
|
||||
<origin xyz="${tibia_length / 2} 0 0" rpy="0 1.5708 0"/>
|
||||
<material name="yellow">
|
||||
<color rgba="0 1 1 1"/>
|
||||
</material>
|
||||
</visual>
|
||||
<collision>
|
||||
<geometry>
|
||||
<cylinder length="${tibia_length}" radius="${leg_radius}"/>
|
||||
</geometry>
|
||||
<origin xyz="${tibia_length / 2} 0 0" rpy="0 1.5708 0"/>
|
||||
</collision>
|
||||
</link>
|
||||
<joint name="leg${id}_tibia_joint" type="revolute">
|
||||
<parent link="leg${id}_femur"/>
|
||||
<child link="leg${id}_tibia"/>
|
||||
<origin xyz="0 0 -${femur_length}" rpy="0 0 0"/>
|
||||
<axis xyz="0 1 0"/>
|
||||
<limit lower="${joint_lower_limit}" upper="${joint_upper_limit}" effort="${joint_effort}" velocity="${joint_velocity}"/>
|
||||
</joint>
|
||||
|
||||
<link name="leg${id}_tip">
|
||||
<xacro:default_inertial/>
|
||||
<visual>
|
||||
<geometry>
|
||||
<sphere radius="${tip_radius}"/>
|
||||
</geometry>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<material name="purple">
|
||||
<color rgba="1 0 1 1"/>
|
||||
</material>
|
||||
</visual>
|
||||
<collision>
|
||||
<geometry>
|
||||
<sphere radius="${tip_radius}"/>
|
||||
</geometry>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
</collision>
|
||||
</link>
|
||||
<joint name="leg${id}_tip_joint" type="fixed">
|
||||
<parent link="leg${id}_tibia"/>
|
||||
<child link="leg${id}_tip"/>
|
||||
<origin xyz="${tibia_length} 0 0" rpy="0 0 0"/>
|
||||
</joint>
|
||||
</xacro:macro>
|
||||
|
||||
<xacro:leg id="1" x="${coxa_diagonal_x}" y="${coxa_diagonal_y}" yaw="-0.7854" femur_roll="0"/>
|
||||
<xacro:leg id="2" x="${coxa_center_x}" y="${coxa_center_y}" yaw="0" femur_roll="0"/>
|
||||
<xacro:leg id="3" x="-${coxa_diagonal_x}" y="${coxa_diagonal_y}" yaw="0.7854" femur_roll="0"/>
|
||||
<xacro:leg id="4" x="-${coxa_diagonal_x}" y="-${coxa_diagonal_y}" yaw="2.3562" femur_roll="3.1416"/>
|
||||
<xacro:leg id="5" x="${coxa_center_x}" y="-${coxa_center_y}" yaw="3.1416" femur_roll="3.1416"/>
|
||||
<xacro:leg id="6" x="${coxa_diagonal_x}" y="-${coxa_diagonal_y}" yaw="-2.3562" femur_roll="3.1416"/>
|
||||
</robot>
|
||||
@@ -43,7 +43,8 @@ In the current codebase, the practical workflow is:
|
||||
* **Kinematics (`kinematics.py`)**: Converts target foot positions into joint angles using IKPy chains for each leg.
|
||||
* **Simulation (`simulation.py`)**: Manages PyBullet scene loading, stepping, joint actuation, base pose queries, and physics telemetry.
|
||||
* **Inputs (`inputs/`)**: Receives commands from GUI sliders, Pygame gamepads, and random command generation.
|
||||
* **ML Subsystem (`ml/`)**: Contains the Gymnasium environment (`env.py`), PPO training (`run_train.py`), evaluation (`run_eval.py`), BC pretraining (`pretrain_bc.py`), callbacks, and metrics overlays.
|
||||
* **ML Subsystem (`ml/`)**: Gymnasium/PyBullet environment and learning workflows; see the [ML README](ml/README.md).
|
||||
* **Board firmware (`BoardCode/`)**: Arduino and ESP32 sketches with a shared ESP32 library; see the [BoardCode README](BoardCode/README.md).
|
||||
* **States (`states/`)**: Contains additional state-machine classes such as `IdleState`, `WalkingState`, and `WaveState`. These exist in the repository, but the current active runtime in `main.py` does not currently drive them through `Robot.tick()`.
|
||||
|
||||
---
|
||||
@@ -77,16 +78,13 @@ JackBot/
|
||||
│
|
||||
├── gui/ # GUI/dashboard control layer
|
||||
│ └── MainWindow.py
|
||||
├── BoardCode/ # Arduino and ESP32 firmware
|
||||
│ ├── JackBotArd/
|
||||
│ ├── JackBotEsp32/
|
||||
│ ├── JackBotEsp32C3/
|
||||
│ └── libaries/JackBot/ # Shared ESP32 Arduino library
|
||||
│
|
||||
├── ml/ # Gymnasium RL training + evaluation stack
|
||||
│ ├── env.py # RL environment + reward logic
|
||||
│ ├── callbacks.py # SB3 callbacks for logs/curriculum
|
||||
│ ├── pretrain_bc.py # Behavior cloning pretraining
|
||||
│ ├── run_train.py # PPO training entry point
|
||||
│ ├── run_eval.py # Evaluation of saved checkpoints
|
||||
│ ├── run_eval_training.py # Kinematics-mode benchmark script
|
||||
│ ├── MetricsOverlay.py # 3D in-scene metrics HUD
|
||||
│ └── checkpoints/ # Model checkpoints + saved runs
|
||||
├── ml/ # RL environment and workflows; see ml/README.md
|
||||
│
|
||||
├── EspCommunication.py # ESP32 UDP communication layer
|
||||
├── ArduinoCommunication.py # Arduino serial communication layer
|
||||
@@ -113,7 +111,17 @@ The repository contains a few pieces that are still present but not fully connec
|
||||
|
||||
* **Python:** 3.12 recommended
|
||||
* **OS:** Windows 10/11 or Linux
|
||||
* **Dependencies:** `pybullet`, `gymnasium`, `stable-baselines3`, `torch`, `numpy`, `pygame`, `ikpy`, `pyserial`, `matplotlib`, `dearpygui`
|
||||
* **Dependencies:** `pybullet`, `gymnasium`, `stable-baselines3`, `torch`, `numpy`, `pygame`, `ikpy`, `pyserial`, `matplotlib`, `dearpygui`, `xacro`
|
||||
|
||||
## Robot model
|
||||
|
||||
Edit [`JackBotUrdf.xacro`](JackBotUrdf.xacro), which defines shared leg dimensions, coxa starting-position properties, and a reusable leg macro. Regenerate the checked-in URDF after changing the model:
|
||||
|
||||
```bash
|
||||
xacro JackBotUrdf.xacro -o JackBotUrdf.urdf
|
||||
```
|
||||
|
||||
The `xacro` dependency is included in `requirements.txt`. Keep `JackBotUrdf.urdf` as generated output; the simulator and kinematics continue loading that file.
|
||||
|
||||
---
|
||||
|
||||
@@ -170,6 +178,11 @@ Supported configuration values in the current code include:
|
||||
* `tick_rate_hz`, `step_duration`
|
||||
* `step_height`, `step_length`
|
||||
|
||||
In ESP32 mode, the GUI uses UDP heartbeat replies to show the robot connection
|
||||
state. If the connection is lost, it retries for up to 30 seconds and then
|
||||
shows **Robot Disconnected**; press **STOP ROBOT** to end the active session.
|
||||
The ESP32 must run firmware containing the heartbeat reply support.
|
||||
|
||||
### GUI input sources
|
||||
|
||||
The current GUI (`gui/MainWindow.py`) exposes these input sources:
|
||||
@@ -184,212 +197,9 @@ The active `main.py` runtime resolves commands through `resolve_active_command(.
|
||||
|
||||
## Machine Learning Pipeline (`ml/`)
|
||||
|
||||
The ML subsystem currently uses:
|
||||
|
||||
* **Gymnasium** as the environment API
|
||||
* **PyBullet** as the physics engine
|
||||
* **Stable-Baselines3 PPO** as the learning algorithm
|
||||
* **Curriculum phases** to gradually expose more difficult command spaces
|
||||
|
||||
### Current ML scripts
|
||||
|
||||
* `ml/run_train.py` — PPO training entry point
|
||||
* `ml/run_eval.py` — phase-based model evaluation
|
||||
* `ml/run_eval_training.py` — reward benchmark for kinematics mode
|
||||
* `ml/pretrain_bc.py` — collect teacher data from the kinematics solver and pretrain a base policy
|
||||
* `ml/env.py` — environment definition and reward logic
|
||||
* `ml/callbacks.py` — reward logging and curriculum callbacks
|
||||
|
||||
### Training flow
|
||||
|
||||
Training is launched with:
|
||||
|
||||
```bash
|
||||
python ml/run_train.py --total-timesteps 1500000 --gui
|
||||
```
|
||||
|
||||
The current training script creates a vectorized PPO environment, optionally loads a pre-trained checkpoint, and saves results into `ml/checkpoints/` and `ml/logs/`.
|
||||
|
||||
### Evaluation flow
|
||||
|
||||
Evaluation is launched with:
|
||||
|
||||
```bash
|
||||
python ml/run_eval.py --model ml/checkpoints/jackbot_kinematics_base.zip --episodes-per-phase 5 --gui
|
||||
```
|
||||
|
||||
This script runs a multi-phase deterministic evaluation suite with fixed command vectors for:
|
||||
|
||||
* `FORWARD`
|
||||
* `TURN_AND_DIRECTION`
|
||||
* `OMNI_DIRECTION`
|
||||
* `FULL_COMMAND`
|
||||
|
||||
### Behavioral cloning pretraining
|
||||
|
||||
The repository also contains a behavioral cloning route:
|
||||
|
||||
```bash
|
||||
python ml/pretrain_bc.py --num-samples 100000 --epochs 15 --save-path ml/checkpoints/jackbot_kinematics_base.zip
|
||||
```
|
||||
|
||||
This script gathers `(observation, action)` data from the kinematics teacher and trains a PPO policy to act as a learned base model.
|
||||
|
||||
---
|
||||
|
||||
## What the Reward Is Trying to Teach
|
||||
|
||||
The reward function in `ml/env.py` is designed to teach several things at once:
|
||||
|
||||
* survival and stability,
|
||||
* following the commanded direction,
|
||||
* avoiding lateral drift,
|
||||
* maintaining base height,
|
||||
* reducing abrupt control changes,
|
||||
* staying close to a stable stance when the command is zero.
|
||||
|
||||
The environment uses several reward components, including:
|
||||
|
||||
* height reward,
|
||||
* stability reward,
|
||||
* pose closeness reward,
|
||||
* smoothness reward,
|
||||
* linear velocity tracking,
|
||||
* angular velocity tracking,
|
||||
* jitter penalty,
|
||||
* stand-by penalty when the command is zero.
|
||||
|
||||
### Detailed reward structure
|
||||
|
||||
The reward is built step by step inside `JackBotEnv._compute_reward()` in `ml/env.py`. It is not a single binary success signal; it is a dense shaping signal that rewards good behavior continuously throughout the episode.
|
||||
|
||||
At each control step, the environment measures:
|
||||
|
||||
* current body height,
|
||||
* roll and pitch angles,
|
||||
* current joint configuration,
|
||||
* measured linear and angular velocities,
|
||||
* the active command vector `[vx, vy, omega]`,
|
||||
* the difference between the current action and the previous actions.
|
||||
|
||||
From these values, it computes a set of sub-rewards:
|
||||
|
||||
* `height reward`: a Gaussian-style reward based on how close the robot body is to the target height.
|
||||
* `stability reward`: a reward for keeping roll/pitch low and the body well balanced.
|
||||
* `pose closeness reward`: rewards staying near the default standing joint posture.
|
||||
* `smoothness reward`: rewards actions that change gradually instead of abruptly.
|
||||
* `linear velocity reward`: encourages the robot to move in the commanded direction and speed.
|
||||
* `angular velocity reward`: rewards matching the commanded turning rate.
|
||||
|
||||
The environment then adds two kinds of correction terms:
|
||||
|
||||
* `jitter penalty`: subtracts a small amount when action changes are noisy or jerky.
|
||||
* `stand_penalty`: when the command is effectively zero, penalizes unintended movement and yaw drift.
|
||||
|
||||
This makes the reward function behave as a soft guidance system: the agent gets a steady gradient that says “this is closer to what we want” or “this is worse than the desired behavior.”
|
||||
|
||||
### Standing mode vs. walking mode
|
||||
|
||||
The reward code handles two cases differently:
|
||||
|
||||
#### 1. Standing mode
|
||||
When the command vector is close to zero (`cmd_norm < 0.05` and `abs(cmd_yaw) < 0.05`), the agent is not supposed to move much. In that case the reward focuses on:
|
||||
|
||||
* keeping the body at the correct height,
|
||||
* staying stable,
|
||||
* maintaining a clean posture,
|
||||
* staying smooth.
|
||||
|
||||
A small `stand_penalty` is then applied to discourage unintended speed and yaw drift while the robot is supposed to hold position.
|
||||
|
||||
#### 2. Walking mode
|
||||
When a non-zero command is active, the robot is rewarded for moving in the intended direction and turning at the requested rate. The reward then emphasizes:
|
||||
|
||||
* matching the commanded linear velocity,
|
||||
* matching the commanded yaw rate,
|
||||
* continuing to maintain height and stability,
|
||||
* staying smooth in its control inputs.
|
||||
|
||||
If the command expects movement but the robot is effectively still, the code now applies a stronger `stillness_penalty` instead of a neutral reward. This means standing while the command says to move is explicitly discouraged.
|
||||
|
||||
### Why the reward is shaped this way
|
||||
|
||||
The goal is not just to teach the robot to stay alive. The reward is designed so that a PPO agent learns multiple useful habits at once:
|
||||
|
||||
* do not collapse or tip over,
|
||||
* keep the body at a sensible height,
|
||||
* follow directional commands,
|
||||
* avoid unstable oscillations,
|
||||
* avoid overreactive control jumps,
|
||||
* stay near a normal standing pose when no motion is requested.
|
||||
|
||||
This is why the environment is not based on a single sparse reward such as “+1 for success, 0 otherwise.” Instead, it uses dense reward shaping so the policy receives useful feedback on every step.
|
||||
|
||||
### Are the penalties real penalties?
|
||||
|
||||
Yes — in the reward function they are real negative contributions. For example:
|
||||
|
||||
* `jitter_penalty` subtracts from the step reward when action changes are too abrupt,
|
||||
* `stand_penalty` subtracts when the robot moves unnecessarily while standing,
|
||||
* `stillness_penalty` subtracts when movement is commanded but the robot remains essentially frozen.
|
||||
|
||||
In the current implementation, a non-zero command that is not followed by meaningful motion now yields an explicit penalty instead of a neutral reward. This is the main behavior change requested for the training setup: standing while the command says to move is now actively discouraged.
|
||||
|
||||
The code does this:
|
||||
|
||||
```python
|
||||
final_reward = step_reward + jitter_penalty + alive_bonus
|
||||
```
|
||||
|
||||
That means:
|
||||
|
||||
* negative penalty terms can now reduce the reward below zero,
|
||||
* the reward is no longer clipped to zero in this path,
|
||||
* and the episode is still only ended by the separate failure check in `_update_robot_failure()`.
|
||||
|
||||
So the answer is:
|
||||
|
||||
* the penalties are real reward penalties,
|
||||
* they are now strong enough to discourage command-mismatch behavior,
|
||||
* and the actual terminal condition remains the failure check in `_update_robot_failure()`.
|
||||
|
||||
### What actually ends an episode?
|
||||
|
||||
The episode ends when the robot is considered failed, not when a reward penalty is applied. In `ml/env.py`, the environment marks the robot as failed if:
|
||||
|
||||
* it is too tilted (`roll` or `pitch` exceed the configured failure threshold), or
|
||||
* it has collapsed below a minimum body-height threshold.
|
||||
|
||||
That is a hard termination condition. In other words:
|
||||
|
||||
* reward penalties discourage bad behavior,
|
||||
* failure conditions stop the episode when the robot is clearly unstable or collapsed.
|
||||
|
||||
### Practical interpretation
|
||||
|
||||
A good mental model is:
|
||||
|
||||
* the reward function teaches the robot what “good locomotion” looks like,
|
||||
* the failure check prevents the robot from continuing when it is physically broken or unstable,
|
||||
* and the curriculum gradually increases the difficulty of the commands as the robot becomes more capable.
|
||||
|
||||
This combination is a common reinforcement-learning setup for locomotion: dense rewards shape the desired behavior, while hard failure conditions protect the training process from degenerate states.
|
||||
|
||||
This reward shaping encourages the robot to learn locomotion patterns rather than simply freezing in place.
|
||||
|
||||
---
|
||||
|
||||
## Curriculum / Phase Progression
|
||||
|
||||
The environment currently uses the following curriculum stages:
|
||||
|
||||
* **STAND_ONLY**
|
||||
* **FORWARD**
|
||||
* **TURN_AND_DIRECTION**
|
||||
* **OMNI_DIRECTION**
|
||||
* **FULL_COMMAND**
|
||||
|
||||
The training environment gradually advances phase complexity based on survival, stability, and movement metrics. `ml/callbacks.py` includes custom curriculum-handling logic for the online learning loop.
|
||||
The ML project has its own guide covering environment behavior, reward and curriculum
|
||||
design, setup, training, pretraining, evaluation, and generated outputs:
|
||||
[ml/README.md](ml/README.md).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ from ArduinoCommunication import ArduinoCommunication
|
||||
|
||||
class RobotBackend(Protocol):
|
||||
"""Protocol defining hardware abstraction for both Simulation and Hardware backends."""
|
||||
@property
|
||||
def connection_status(self) -> Optional[str]: ...
|
||||
def send_angles(self, rad_array: dt.RadArray) -> None: ...
|
||||
def step_simulation(self) -> None: ...
|
||||
def hard_reset_joints(self, target_angles: np.ndarray) -> None: ...
|
||||
@@ -35,6 +37,10 @@ class HardwareBackend:
|
||||
self.comm_channel = comm_channel
|
||||
self.internal_angles = np.zeros(18, dtype=np.float32)
|
||||
|
||||
@property
|
||||
def connection_status(self) -> Optional[str]:
|
||||
return getattr(self.comm_channel, "connection_status", None)
|
||||
|
||||
def send_angles(self, rad_array: dt.RadArray) -> None:
|
||||
self.internal_angles = rad_array.data.flatten().copy()
|
||||
if self.comm_channel:
|
||||
@@ -71,6 +77,10 @@ class PyBulletBackend:
|
||||
def __init__(self, sim_instance: Simulation):
|
||||
self.sim = sim_instance
|
||||
|
||||
@property
|
||||
def connection_status(self) -> Optional[str]:
|
||||
return None
|
||||
|
||||
def send_angles(self, rad_array: dt.RadArray) -> None:
|
||||
if self.sim:
|
||||
self.sim.set_robot_joint_angles(rad_array)
|
||||
@@ -171,6 +181,10 @@ class Robot:
|
||||
if self.backend:
|
||||
self.backend.send_angles(self.current_rad)
|
||||
|
||||
@property
|
||||
def connection_status(self) -> Optional[str]:
|
||||
return self.backend.connection_status
|
||||
|
||||
def step_sim(self) -> None:
|
||||
if self.backend:
|
||||
self.backend.step_simulation()
|
||||
|
||||
@@ -128,6 +128,19 @@ def create_parameter_gui(on_start_callback=None, on_stop_callback=None):
|
||||
dpg.show_viewport()
|
||||
|
||||
|
||||
def update_robot_status(status: str):
|
||||
"""Update the robot connection label from the GUI event loop."""
|
||||
labels = {
|
||||
"connecting": ("Status: CONNECTING TO ROBOT", (255, 200, 0)),
|
||||
"connected": ("Status: RUNNING", (0, 255, 0)),
|
||||
"reconnecting": ("Robot Disconnected - Reconnecting...", (255, 150, 0)),
|
||||
"disconnected": ("Robot Disconnected", (255, 100, 100)),
|
||||
}
|
||||
label, color = labels.get(status, ("Status: RUNNING", (0, 255, 0)))
|
||||
if dpg.is_dearpygui_running():
|
||||
dpg.configure_item("status_text", default_value=label, color=color)
|
||||
|
||||
|
||||
def resolve_active_command(gamepad_cmd: dict | None) -> dict:
|
||||
"""Selects motion vector based on current active source in GUI."""
|
||||
source = input_config["source"]
|
||||
|
||||
@@ -10,7 +10,8 @@ from gui.MainWindow import (
|
||||
create_parameter_gui,
|
||||
render_gui_frame,
|
||||
stop_gui,
|
||||
resolve_active_command
|
||||
resolve_active_command,
|
||||
update_robot_status,
|
||||
)
|
||||
from inputs.PygameController import controller_loop
|
||||
|
||||
@@ -62,6 +63,8 @@ def main_event_loop(control_queue: Queue):
|
||||
robot_instance.robot_state = active_cmd["state"]
|
||||
robot_instance.vector_dirmov = active_cmd["dirmov"]
|
||||
robot_instance.tick()
|
||||
if robot_instance.connection_status is not None:
|
||||
update_robot_status(robot_instance.connection_status)
|
||||
|
||||
render_gui_frame()
|
||||
|
||||
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
# JackBot Machine Learning
|
||||
|
||||
This folder contains the Gymnasium/PyBullet environment and the scripts for
|
||||
behavioral-cloning pretraining, PPO training, and policy evaluation. For the
|
||||
robot's manual-control application, simulator setup, and project overview, see the
|
||||
[main README](../README.md).
|
||||
|
||||
## Setup
|
||||
|
||||
Install the project's Python dependencies from the repository root, following the
|
||||
[main setup instructions](../README.md#installation--setup):
|
||||
|
||||
```bash
|
||||
python -m pip install -r requirements.txt
|
||||
```
|
||||
|
||||
Run the commands below from the repository root. The environment loads the robot
|
||||
model and runs a PyBullet simulation; `--gui` opens the PyBullet window where that
|
||||
option is available.
|
||||
|
||||
## Workflows
|
||||
|
||||
### Behavioral-cloning pretraining
|
||||
|
||||
`pretrain_bc.py` collects observation/action examples from the kinematics controller
|
||||
and trains an initial PPO policy to imitate those actions:
|
||||
|
||||
```bash
|
||||
python ml/pretrain_bc.py --num-samples 100000 --epochs 15 \
|
||||
--save-path ml/checkpoints/jackbot_kinematics_base.zip
|
||||
```
|
||||
|
||||
Use `--gui` to visualize data collection. Defaults are 100,000 samples, 15 epochs,
|
||||
and the checkpoint path shown above.
|
||||
|
||||
### PPO training
|
||||
|
||||
`run_train.py` trains a PPO policy in parallel environments and saves checkpoints:
|
||||
|
||||
```bash
|
||||
python ml/run_train.py --total-timesteps 1500000
|
||||
```
|
||||
|
||||
Useful options include `--num-workers`, `--save-freq`, `--log-dir`, `--save-dir`,
|
||||
`--pretrained-model`, and `--gui`. By default, the script uses 16 workers, saves
|
||||
checkpoints under `ml/checkpoints/`, and writes TensorBoard logs under `ml/logs/`.
|
||||
To continue from a pretraining or previous checkpoint, pass its `.zip` path with
|
||||
`--pretrained-model`.
|
||||
|
||||
### Policy evaluation
|
||||
|
||||
`run_eval.py` runs deterministic episodes for fixed movement commands and reports
|
||||
mean reward, steps survived, and maximum distance for each phase:
|
||||
|
||||
```bash
|
||||
python ml/run_eval.py \
|
||||
--model ml/checkpoints/jackbot_kinematics_base.zip \
|
||||
--episodes-per-phase 5
|
||||
```
|
||||
|
||||
The model path is required. Other options include `--max-steps-per-episode`,
|
||||
`--gui`, and `--save-metrics path/to/report.json`.
|
||||
|
||||
### Kinematics benchmark
|
||||
|
||||
`run_eval_training.py` benchmarks the kinematics controller against fixed commands
|
||||
and prints reward-component averages and movement metrics. It currently has no
|
||||
command-line options and enables the PyBullet GUI:
|
||||
|
||||
```bash
|
||||
python ml/run_eval_training.py
|
||||
```
|
||||
|
||||
## Environment and training concepts
|
||||
|
||||
[`env.py`](env.py) defines `JackBotEnv`. Each observation contains 18 joint angles
|
||||
and a three-value movement command `[vx, vy, omega]`; the policy outputs 18
|
||||
normalized joint actions. The environment can use direct policy actions or the
|
||||
kinematics controller, and provides reward and robot metrics to the training and
|
||||
evaluation scripts.
|
||||
|
||||
The reward is shaped to encourage survival, body height and stability, following
|
||||
the requested linear and angular motion, smooth actions, and a stable stance when
|
||||
the command is zero. It also discourages unintended movement while standing and
|
||||
remaining still when movement is requested. Negative reward contributions are
|
||||
not the same as episode termination: an episode ends on a failure condition (such
|
||||
as excessive tilt or a collapsed body) or when the configured step limit is
|
||||
reached.
|
||||
|
||||
The curriculum in `env.py` progresses through these command stages:
|
||||
|
||||
1. `STAND_ONLY`
|
||||
2. `FORWARD`
|
||||
3. `TURN_AND_DIRECTION`
|
||||
4. `OMNI_DIRECTION`
|
||||
5. `FULL_COMMAND`
|
||||
|
||||
`callbacks.py` contains reward logging and curriculum callbacks. `MetricsOverlay.py`
|
||||
displays simulation metrics when the GUI is in use.
|
||||
|
||||
## Outputs
|
||||
|
||||
Training checkpoints are written to `ml/checkpoints/` and TensorBoard logs and
|
||||
evaluation results to `ml/logs/` by default. These directories can also contain
|
||||
large generated artifacts; keep or remove them according to your experiment needs.
|
||||
@@ -13,3 +13,4 @@ stable-baselines3[extra]
|
||||
gymnasium
|
||||
shimmy
|
||||
tensorboard
|
||||
xacro
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
|
||||
import DataTypes as dt
|
||||
import robot_init as ri
|
||||
from Robot import Robot
|
||||
|
||||
|
||||
class DummyBackend:
|
||||
def __init__(self):
|
||||
self.sent = None
|
||||
self.step_count = 0
|
||||
|
||||
def send_angles(self, rad_array):
|
||||
self.sent = np.array(rad_array.data, copy=True)
|
||||
|
||||
def step_simulation(self):
|
||||
self.step_count += 1
|
||||
|
||||
def hard_reset_joints(self, target_angles):
|
||||
self.sent = np.array(target_angles, copy=True)
|
||||
|
||||
def reset_base(self, position=None, orientation=None):
|
||||
pass
|
||||
|
||||
def get_joint_angles(self):
|
||||
return np.zeros((6, 3), dtype=np.float32)
|
||||
|
||||
def get_base_pose_and_rpy(self):
|
||||
return [0.0, 0.0, 0.0], (0.0, 0.0, 0.0)
|
||||
|
||||
def get_base_velocity(self):
|
||||
return [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]
|
||||
|
||||
def cleanup(self):
|
||||
pass
|
||||
|
||||
|
||||
class RobotSmoothingTests(unittest.TestCase):
|
||||
def test_tick_runs_requested_physics_substeps(self):
|
||||
backend = DummyBackend()
|
||||
robot = Robot(backend_type=backend)
|
||||
|
||||
robot.tick(physics_substeps=4)
|
||||
|
||||
self.assertEqual(backend.step_count, 4)
|
||||
|
||||
def test_tick_defaults_to_one_physics_step(self):
|
||||
backend = DummyBackend()
|
||||
robot = Robot(backend_type=backend)
|
||||
|
||||
robot.tick()
|
||||
|
||||
self.assertEqual(backend.step_count, 1)
|
||||
|
||||
def test_set_joint_angles_respects_max_joint_delta(self):
|
||||
backend = DummyBackend()
|
||||
robot = Robot(backend_type=backend)
|
||||
robot.max_joint_delta = 0.15
|
||||
|
||||
previous = robot.current_rad.data.copy()
|
||||
target = dt.RadArray(np.full((6, 3), 3.0))
|
||||
robot.set_joint_angles(target)
|
||||
|
||||
sent = robot.backend.sent
|
||||
max_delta = np.max(np.abs(sent - previous))
|
||||
|
||||
self.assertLessEqual(max_delta, robot.max_joint_delta + 1e-6)
|
||||
|
||||
def test_set_joint_angles_locks_coxa_at_90_degrees(self):
|
||||
backend = DummyBackend()
|
||||
robot = Robot(backend_type=backend)
|
||||
target = dt.RadArray(np.full((6, 3), 2.0))
|
||||
|
||||
robot.set_joint_angles(target)
|
||||
|
||||
expected = np.full(6, np.pi / 2.0)
|
||||
np.testing.assert_allclose(backend.sent[:, 0], expected)
|
||||
np.testing.assert_allclose(robot.current_rad.data[:, 0], expected)
|
||||
|
||||
def test_idle_transitions_route_through_stopping_state(self):
|
||||
robot = Robot(backend_type=DummyBackend())
|
||||
robot.transition_to("walking")
|
||||
|
||||
robot.transition_to("idle")
|
||||
|
||||
self.assertEqual(robot.current_state_key, "stopping")
|
||||
|
||||
def test_stopping_slews_to_idle_pose_then_enters_idle(self):
|
||||
robot = Robot(backend_type=DummyBackend())
|
||||
robot.current_rad = dt.RadArray(np.full((6, 3), 2.4))
|
||||
robot.transition_to("stopping")
|
||||
|
||||
for _ in range(50):
|
||||
robot.tick()
|
||||
if robot.current_state_key == "idle":
|
||||
break
|
||||
|
||||
expected = ri.init_deg.to_rad().data
|
||||
self.assertEqual(robot.current_state_key, "idle")
|
||||
np.testing.assert_allclose(robot.current_rad.data, expected, atol=1e-6)
|
||||
|
||||
def test_compute_ik_does_not_crash_on_unreachable_target(self):
|
||||
backend = DummyBackend()
|
||||
robot = Robot(backend_type=backend)
|
||||
robot.current_pos = dt.PosArray(np.tile([0.05, 0.0, 0.12], (6, 1)))
|
||||
|
||||
unreachable = dt.PosArray(np.tile([2.0, 2.0, 2.0], (6, 1)))
|
||||
result = robot.compute_ik(unreachable)
|
||||
|
||||
self.assertEqual(result.data.shape, (6, 3))
|
||||
self.assertTrue(np.all(np.isfinite(result.data)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user