#include "NextionUI.h" #include // RGB565 colors as Nextion expects them. static constexpr uint16_t COL_ON = 2016; // green static constexpr uint16_t COL_OFF = 50712; // Nextion default light gray static constexpr uint16_t COL_DANGER = 63488; // red static constexpr uint16_t COL_WARN = 64512; // orange static constexpr uint16_t COL_TEXT = 65535; // white (top bar text) static constexpr uint16_t COL_DIM = 33808; // gray (no data) // The default 64-byte TX buffer would make a full redraw (~1 kB at 115200 // baud) block the TX loop for ~90 ms. Give it room to queue. static uint8_t tx_extra[2048]; static uint8_t rx_extra[128]; static const char* const LEG_NAMES[6] = { "FR", "MR", "RR", "RL", "ML", "FL" }; // robot leg order static const char* const JOINT_NAMES[3] = { "coxa", "femur", "tibia" }; void NextionUI::begin() { NEXTION_SERIAL.begin(NEXTION_BAUD); NEXTION_SERIAL.addMemoryForWrite(tx_extra, sizeof(tx_extra)); NEXTION_SERIAL.addMemoryForRead(rx_extra, sizeof(rx_extra)); cmd("bkcmd=0"); // no success/fail replies - we never need them (and a write // to a component that isn't on the showing page is ignored) cmd("sendme"); // which page is showing? (the display may have kept running) force_full_ = true; } void NextionUI::cmd(const char* fmt, ...) { char buf[96]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); NEXTION_SERIAL.print(buf); NEXTION_SERIAL.write(0xFF); NEXTION_SERIAL.write(0xFF); NEXTION_SERIAL.write(0xFF); } void NextionUI::put(const char* fmt, ...) { char buf[96]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); uint32_t h = 2166136261u; // FNV-1a for (const char* c = buf; *c; c++) h = (h ^ (uint8_t)*c) * 16777619u; h |= 1; // 0 = empty slot bool cached = slot_ < MAX_SLOTS; if (cached && !full_ && cache_[slot_] == h) { slot_++; return; } if (cached) cache_[slot_] = h; slot_++; NEXTION_SERIAL.print(buf); NEXTION_SERIAL.write(0xFF); NEXTION_SERIAL.write(0xFF); NEXTION_SERIAL.write(0xFF); } void NextionUI::setPage(uint8_t page) { page_ = page; force_full_ = true; // a newly shown page has its HMI defaults: write everything } // ---- Receive ---- bool NextionUI::decodeCustom(UiEvent& out) { out.value = body_len_ > 1 ? body_[1] : 0; switch (body_[0]) { case 'A': out.cmd = UiCmd::ToggleArm; break; case 'K': out.cmd = UiCmd::Disarm; break; case 'S': out.cmd = UiCmd::ToggleStand; break; case 'G': out.cmd = UiCmd::ToggleGait; break; case 'M': out.cmd = UiCmd::ToggleWalkMode; break; case 'X': out.cmd = UiCmd::ToggleRStickXlate; break; case 'R': out.cmd = UiCmd::ToggleRemoteGyro; break; case 'B': out.cmd = UiCmd::ToggleRobotGyro; break; case 'V': out.cmd = UiCmd::SetSpeed; break; case 'H': out.cmd = UiCmd::SetHeight; break; case 'Z': out.cmd = UiCmd::ZeroGyro; break; case 'C': out.cmd = UiCmd::CalStartSave; break; case 'Q': out.cmd = UiCmd::CalCancel; break; case 'U': out.cmd = UiCmd::UploadRequest; break; case 'O': out.cmd = UiCmd::ServoCalToggle; break; case 'L': out.cmd = UiCmd::ServoCalLeg; break; case 'J': out.cmd = UiCmd::ServoCalJoint; break; case 'T': out.cmd = UiCmd::ServoCalTrim; break; case 'W': out.cmd = UiCmd::ServoCalSave; break; case 'E': out.cmd = UiCmd::ServoCalRevert; break; case 'P': if (out.value == page_) return false; // same page again: nothing changes setPage(out.value); out.cmd = UiCmd::PageShown; break; default: return false; } return true; } // Standard Nextion frames (terminated FF FF FF). Two matter: // 0x88 / 0x00 display (re)started -> redraw everything (its start page // then reports itself with 'P') // 0x66 page reply to `sendme`: the page that is showing bool NextionUI::decodeNative(UiEvent& out) { if (native_buf_[0] == 0x88 || native_buf_[0] == 0x00) { force_full_ = true; return false; } if (native_buf_[0] == 0x66 && native_len_ >= 5) { if (native_buf_[1] == page_) return false; setPage(native_buf_[1]); out.cmd = UiCmd::PageShown; out.value = native_buf_[1]; return true; } return false; } bool NextionUI::poll(UiEvent& out) { while (NEXTION_SERIAL.available()) { uint8_t b = NEXTION_SERIAL.read(); switch (rx_) { case Rx::Idle: if (b == '#') { rx_ = Rx::CustomLen; } else { rx_ = Rx::Native; native_buf_[0] = b; native_len_ = 1; ff_run_ = (b == 0xFF) ? 1 : 0; } break; case Rx::CustomLen: if (b >= 1 && b <= sizeof(body_)) { body_len_ = b; body_got_ = 0; rx_ = Rx::CustomBody; } else { rx_ = Rx::Idle; // garbage - resync on the next '#' } break; case Rx::CustomBody: body_[body_got_++] = b; if (body_got_ == body_len_) { rx_ = Rx::Idle; if (decodeCustom(out)) return true; } break; case Rx::Native: if (native_len_ < sizeof(native_buf_)) native_buf_[native_len_] = b; native_len_++; ff_run_ = (b == 0xFF) ? ff_run_ + 1 : 0; if (ff_run_ == 3) { rx_ = Rx::Idle; if (decodeNative(out)) return true; } else if (native_len_ > 16) { rx_ = Rx::Idle; // not a frame we understand } break; } } return false; } // ---- Render ---- static const char* robotStateName(uint8_t s) { switch (s) { case TSTATE_DISARMED: return "DISARMED"; case TSTATE_SIT: return "SIT"; case TSTATE_STAND: return "STAND"; case TSTATE_WALKING: return "WALKING"; case TSTATE_SERVO_CAL: return "SERVO CAL"; default: return "?"; } } // "7.2V", or "--" when the battery isn't measured. static const char* volts(char* buf, size_t n, uint16_t mv) { if (mv == 0) snprintf(buf, n, "--"); else snprintf(buf, n, "%u.%uV", mv / 1000, (mv % 1000) / 100); return buf; } // Angles are shown to 0.5 deg, so sensor noise doesn't repaint every frame. static float halfDeg(float d) { return roundf(d * 2.0f) / 2.0f; } void NextionUI::renderTopBar(const UiView& v) { if (v.link_ok) put("tLink.txt=\"LINK %u%%\"", v.link_pct); else put("tLink.txt=\"NO LINK\""); put("tLink.pco=%u", v.link_ok ? COL_ON : COL_DANGER); char b[8]; if (v.tele_ok) put("tState.txt=\"ROBOT %s %s\"", robotStateName(v.tele.state), volts(b, sizeof(b), v.tele.battery_mv)); else put("tState.txt=\"ROBOT: NO DATA\""); put("tState.pco=%u", v.tele_ok ? COL_TEXT : COL_DIM); } void NextionUI::renderDrive(const UiView& v) { put("bArm.txt=\"%s\"", v.armed ? "ARMED" : "DISARMED"); put("bArm.bco=%u", v.armed ? COL_DANGER : COL_OFF); put("bStand.txt=\"%s\"", v.stand ? "STAND" : "SIT"); put("bStand.bco=%u", v.stand ? COL_ON : COL_OFF); put("bGait.txt=\"%s\"", v.gait_wave ? "WAVE" : "TRIPOD"); put("bMode.txt=\"%s\"", v.mode_b ? "HEADING" : "DIRECT"); put("bRs.txt=\"%s\"", v.rstick_xlate ? "R: MOVE" : "R: ROTATE"); put("bRGyro.bco=%u", v.remote_gyro ? COL_ON : COL_OFF); put("bBGyro.bco=%u", v.robot_gyro ? COL_ON : COL_OFF); put("hSpeed.val=%u", v.speed_target); put("tSpeed.txt=\"%u%%\"", (v.speed_target * 100 + 127) / 255); put("hHeight.val=%d", v.height / 10 + 100); // slider 0..200, 100 = default put("tHeight.txt=\"%+d%%\"", v.height / 10); put("tMsg.txt=\"%s\"", v.message); } void NextionUI::renderStatus(const UiView& v) { // Handset IMU, sliders 0..90 = -45..+45 deg if (v.imu_ok) { put("tRRoll.txt=\"roll %+.1f\"", halfDeg(v.imu_roll)); put("tRPitch.txt=\"pitch %+.1f\"", halfDeg(v.imu_pitch)); } else { put("tRRoll.txt=\"roll no IMU\""); put("tRPitch.txt=\"pitch no IMU\""); } put("hRRoll.val=%d", (int)constrain(lroundf(v.imu_roll) + 45, 0L, 90L)); put("hRPitch.val=%d", (int)constrain(lroundf(v.imu_pitch) + 45, 0L, 90L)); // Robot IMU, from telemetry float br = v.tele.roll_ddeg / 10.0f, bp = v.tele.pitch_ddeg / 10.0f; bool robot_imu = v.tele_ok && (v.tele.status & TSTAT_IMU_OK); if (robot_imu) { put("tBRoll.txt=\"roll %+.1f\"", halfDeg(br)); put("tBPitch.txt=\"pitch %+.1f\"", halfDeg(bp)); } else { put("tBRoll.txt=\"roll %s\"", v.tele_ok ? "no IMU" : "--"); put("tBPitch.txt=\"pitch %s\"", v.tele_ok ? "no IMU" : "--"); } put("hBRoll.val=%d", robot_imu ? (int)constrain(lroundf(br) + 45, 0L, 90L) : 45); put("hBPitch.val=%d", robot_imu ? (int)constrain(lroundf(bp) + 45, 0L, 90L) : 45); // Sticks, sliders 0..200 = -1000..+1000 static const char* const STICKS[NUM_AXES] = { "hLX", "hLY", "hLT", "hRX", "hRY", "hRT" }; for (int i = 0; i < NUM_AXES; i++) put("%s.val=%d", STICKS[i], (v.sticks[i] + 1000) / 10); char a[8], b[8]; put("tBatt.txt=\"battery remote %s robot %s\"", volts(a, sizeof(a), v.battery_mv), v.tele_ok ? volts(b, sizeof(b), v.tele.battery_mv) : "--"); if (!v.link_ok) put("tRadio.txt=\"radio no link\""); else if (v.tele_ok) put("tRadio.txt=\"radio %u%% acked, robot hears %u/s\"", v.link_pct, v.tele.rx_per_sec); else put("tRadio.txt=\"radio %u%% acked, no telemetry\"", v.link_pct); } void NextionUI::renderServos(const UiView& v) { for (int i = 0; i < 18; i++) { int joint = i % 3; if (v.tele_ok) { int deg = v.tele.joint_deg[i] - (joint == 2 ? TELEMETRY_TIBIA_OFFSET_DEG : 0); // Bar = position within the servo's travel: coxa/femur -90..90, tibia -180..0. int pct = (deg + (joint == 2 ? 180 : 90)) * 100 / 180; put("tJ%d.txt=\"%-5s %+4d\"", i, JOINT_NAMES[joint], deg); put("jJ%d.val=%d", i, constrain(pct, 0, 100)); } else { put("tJ%d.txt=\"%-5s --\"", i, JOINT_NAMES[joint]); put("jJ%d.val=0", i); } } const char* s = !v.tele_ok ? "NO DATA" : v.tele.state == TSTATE_SERVO_CAL ? "CENTRE" : (v.tele.status & TSTAT_SERVOS_ON) ? "LIVE" : "RELAXED"; put("tSrv.txt=\"%s\"", s); put("tSrv.pco=%u", !v.tele_ok ? COL_DIM : (v.tele.status & TSTAT_SERVOS_ON) ? COL_ON : 0); } void NextionUI::renderCal(const UiView& v) { put("bCalOn.txt=\"%s\"", v.servo_cal ? "STOP" : "START"); put("bCalOn.bco=%u", v.servo_cal ? COL_WARN : COL_OFF); for (int i = 0; i < 6; i++) put("bL%d.bco=%u", i, v.servo_sel / 3 == i ? COL_ON : COL_OFF); for (int j = 0; j < 3; j++) put("bJ%d.bco=%u", j, v.servo_sel % 3 == j ? COL_ON : COL_OFF); const char* leg = LEG_NAMES[v.servo_sel / 3]; const char* joint = JOINT_NAMES[v.servo_sel % 3]; if (!v.servo_cal) put("tTrim.txt=\"%s %s\"", leg, joint); else if (!v.trim_synced) put("tTrim.txt=\"%s %s ...\"", leg, joint); else put("tTrim.txt=\"%s %s %+dus\"", leg, joint, v.trim_us); bool dirty = v.tele_ok && (v.tele.status & TSTAT_CAL_DIRTY); put("bSave.bco=%u", dirty ? COL_WARN : COL_OFF); const char* hint = v.message[0] ? v.message : !v.servo_cal ? "Robot on a stand, disarmed: START" : !v.tele_ok ? "No telemetry from the robot" : v.tele.state != TSTATE_SERVO_CAL ? "Waiting for the robot" : dirty ? "Unsaved trims: SAVE keeps them" : "Trim until the horn is square"; put("tMsg.txt=\"%s\"", hint); } void NextionUI::renderSetup(const UiView& v) { put("bCal.txt=\"%s\"", v.stick_calibrating ? "SAVE CAL" : "CAL STICKS"); put("bCal.bco=%u", v.stick_calibrating ? COL_WARN : COL_OFF); put("bUpd.txt=\"%s\"", v.upload_confirm ? "TAP AGAIN" : "UPDATE DISPLAY"); put("bUpd.bco=%u", v.upload_confirm ? COL_WARN : COL_OFF); put("tVer.txt=\"remote fw %s protocol v%u radio ch %u\"", __DATE__, HXP_PROTOCOL_VERSION, HXP_RADIO_CHANNEL); put("tMsg.txt=\"%s\"", v.message); } void NextionUI::render(const UiView& v, uint32_t now_ms) { uint32_t interval = page_ == PAGE_SERVOS ? NEXTION_SERVOS_RENDER_MS : NEXTION_RENDER_MS; if (!force_full_ && (now_ms - last_render_ms_) < interval) return; // Never block the TX loop on the display: wait for the buffer to drain. if (NEXTION_SERIAL.availableForWrite() < NEXTION_TX_MIN_FREE) return; last_render_ms_ = now_ms; full_ = force_full_ || (now_ms - last_full_ms_) >= NEXTION_FULL_REFRESH_MS; if (full_) { force_full_ = false; last_full_ms_ = now_ms; if (page_ == PAGE_UNKNOWN) cmd("sendme"); // still don't know the page: ask again } slot_ = 0; switch (page_) { case PAGE_DRIVE: renderTopBar(v); renderDrive(v); break; case PAGE_STATUS: renderTopBar(v); renderStatus(v); break; case PAGE_SERVOS: renderTopBar(v); renderServos(v); break; case PAGE_CAL: renderTopBar(v); renderCal(v); break; case PAGE_SETUP: renderTopBar(v); renderSetup(v); break; default: break; // splash / upload / unknown: nothing to show } } // ---- Upload passthrough ---- // Lets Nextion Editor upload a new .tft through the remote's USB port, with // the display still in the case: show the upload page, then wire USB serial // straight through to the display, forever (power-cycle to leave). Nextion // Editor switches baud rate mid-upload; Teensy's USB serial reports the // rate the PC asked for, so the display side follows it. void NextionUI::runUploadPassthrough() { cmd("page " NEXTION_UPLOAD_PAGE); NEXTION_SERIAL.flush(); delay(100); uint32_t baud = NEXTION_BAUD; for (;;) { uint32_t want = Serial.baud(); if (want >= 2400 && want != baud) { NEXTION_SERIAL.flush(); NEXTION_SERIAL.begin(want); baud = want; } while (Serial.available()) NEXTION_SERIAL.write(Serial.read()); while (NEXTION_SERIAL.available()) Serial.write(NEXTION_SERIAL.read()); } }