diff --git a/CHANGELOG.md b/CHANGELOG.md index 598d82d..2ea1ffb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fisheye calibration resolution (protocol V2.10) + +The wrist fisheye default moved from 640x480 to 1920x1080. Those are different +sensor crops (4:3 vs 16:9), so intrinsics cannot be rescaled from one to the +other. Leader firmware 1.2.8 / follower 1.2.18 (command set V2.10) store the +calibration resolution next to the 8 params, via two new ops on +`CameraFisheyeCal` (0x2B): `0x02` sized read and `0x03` sized write. Ops +`0x00`/`0x01` are unchanged on the wire. + +#### Added + +- **`Calibration::read_fisheye_record()` / `write_fisheye_sized(cal, w, h)` / + `supports_fisheye_size()`**, plus a `FisheyeCalRecord` (`calibration`, + `width`, `height`, `size_known()`; `0/0` = unknown). The capability probe is + the sized read (old firmware rejects it with `InvalidParam`), and its answer + is cached per `Calibration`. On old firmware the record reads back with an + unknown size, and `write_fisheye_sized()` accepts only 640x480 (through the + legacy write). Any other size raises and asks for a firmware upgrade. + Implausible values are refused before anything is sent. +- **`fisheye_cal_size_plausible()`** (the firmware's sized-write rule) and + **`infer_fisheye_cal_size()`**, which handles records without a size. The + candidates are exactly 640x480 and 1920x1080. A candidate matches when the + principal point is within 10% of its centre on each axis, and a size is + returned only when exactly one candidate matches. The PC calibration tools + use the same rule. +- **`FisheyeUndistorter(cal, calibrated_size, frame_size, balance)`**, which + requires the two sizes to be equal. In Python this is the `calibrated_size=(w, h)` + keyword. +- **`ResolvedFisheyeCal.calibrated_size` / `.size_inferred`**. In Python, + `resolve_fisheye()` now returns a `ResolvedFisheyeCal` object. It still + unpacks as the old `(calibration, is_reference, reason)` tuple. +- Protocol mirror: `CAMERA_FISHEYE_CAL_OP_READ_SIZED` / `_OP_WRITE_SIZED` / + `_SIZED_SIZE`, `CameraFisheyeCalSized`, and + `encode_camera_fisheye_cal_{read,write}_sized()` / + `decode_camera_fisheye_cal_sized()`. `scripts/check_protocol_drift.py` + now also compares these wire constants (and the legacy 0x2B ones) against + the firmware headers. + +#### Changed + +- `resolve_fisheye()` uses the recorded size. When the record has no size, it + uses the inferred one and logs a warning. When the size cannot be inferred + either, it falls back to the reference calibration ("the calibration + resolution is unknown and could not be inferred"). The reference is always + 640x480. +- The wrist undistorter that grippers install (`undistort_wrist`) is built for + the calibration's own size, so it now also works on a camera configured at + 1920x1080 with a 1080p calibration. A size mismatch still throws. +- `fisheye_cal.py set-fisheye` takes `--width/--height` (required) and stores + them with `write_fisheye_sized()`. `show` prints the size and whether it was + recorded or inferred. `read_intrinsics.py` reports `image_size` and + `image_size_source` (`assumed_image_size` is kept). `wrist_camera.py` and the + rerun viewer open the camera at the calibration's size. +- `write_fisheye()` is unchanged, but on V2.10 firmware it leaves the size + unknown, so prefer `write_fisheye_sized()`. The legacy + `FisheyeUndistorter(cal, size, balance)` still treats the params as a + 640x480 calibration. + ### High-rate IMU (candidate, not yet versioned; on top of 0.4.6) Requires leader firmware 1.2.8 / follower 1.2.18 (candidates; previous diff --git a/cpp/include/taccap/components/calibration.hpp b/cpp/include/taccap/components/calibration.hpp index c8b279c..4c5d845 100644 --- a/cpp/include/taccap/components/calibration.hpp +++ b/cpp/include/taccap/components/calibration.hpp @@ -5,6 +5,9 @@ // // - Fisheye camera intrinsics + distortion (Cmd::CameraFisheyeCal 0x2B, // command set >= V2.0) — supported on BOTH leader and follower. +// Command set V2.10 (leader 1.2.8 / follower 1.2.18) also records the +// capture resolution the params belong to (read_fisheye_record / +// write_fisheye_sized); older firmware leaves it unknown. // - Leader encoder max travel angle (Cmd::EncoderMaxCal 0x2C, // command set >= V2.1, i.e. leader >= 1.2.0) — LEADER ONLY; the follower // has no MT6816 encoder and NACKs with ErrorCode::InvalidCmd. @@ -28,6 +31,7 @@ #include #include +#include #include #include @@ -43,9 +47,6 @@ class Calibration { std::optional read_fisheye( std::chrono::milliseconds timeout = std::chrono::milliseconds{200}); - // Persists to MCU flash (survives power cycles). Throws ProtocolError if - // any value is NaN/Inf (firmware returns InvalidParam) or the flash write - // fails (SysBusy). // Ask for this unit's wrist calibration, falling back to the SDK's // reference values when it cannot supply one. // @@ -57,15 +58,53 @@ class Calibration { // themselves get the same decision the SDK makes internally rather than // re-deriving it. // + // The calibration resolution comes from read_fisheye_record(). A record + // without one (written by write_fisheye() or by pre-V2.10 firmware) gets + // infer_fisheye_cal_size()'s answer, with size_inferred set and a warning + // logged; a record whose size cannot be inferred either is treated as + // unusable and the reference calibration (640x480) stands in. + // // Never throws for a missing or unusable calibration — that is a fallback, // reported through ResolvedFisheyeCal::reason. A transport failure still // propagates. ResolvedFisheyeCal resolve_fisheye( std::chrono::milliseconds timeout = std::chrono::milliseconds(200)); + // Persists to MCU flash (survives power cycles). Throws ProtocolError if + // any value is NaN/Inf (firmware returns InvalidParam) or the flash write + // fails (SysBusy). + // + // Writes the 8 params only (CalOp::Write). On V2.10 firmware this marks the + // calibration resolution UNKNOWN; use write_fisheye_sized() to record it. void write_fisheye(const protocol::CameraFisheyeCal& cal, std::chrono::milliseconds timeout = std::chrono::milliseconds{500}); + // ---- Fisheye calibration resolution (V2.10: leader 1.2.8 / follower 1.2.18) + // True when the firmware stores the calibration resolution (answers the + // sized read, op 0x02, with Ok or CalNotSet); false when it rejects that op + // as InvalidParam, which is how older firmware answers an unknown op. The + // answer is cached for the life of this object; a transport failure + // propagates and is not cached, and so is any other NACK. + bool supports_fisheye_size( + std::chrono::milliseconds timeout = std::chrono::milliseconds{200}); + + // The params plus the resolution they belong to. Uses the sized read when + // the firmware supports it, else the legacy read with width/height 0/0 + // (unknown). Returns std::nullopt when never calibrated (CalNotSet). + std::optional read_fisheye_record( + std::chrono::milliseconds timeout = std::chrono::milliseconds{200}); + + // Persist the params together with the capture resolution they were + // measured at. Throws Error before sending anything when the values fail + // fisheye_cal_size_plausible() (the firmware's own rule). On V2.10 firmware + // this is the sized write (op 0x03); a NACK throws ProtocolError, as + // write_fisheye() does. Older firmware cannot record a size: a 640x480 + // calibration then falls back to the legacy write_fisheye(), and any other + // resolution throws Error asking for a firmware upgrade. + void write_fisheye_sized(const protocol::CameraFisheyeCal& cal, + int width, int height, + std::chrono::milliseconds timeout = std::chrono::milliseconds{500}); + // ---- Leader encoder max travel angle (leader only) --------------------- // The shaft angle (rad) at which the gripper is fully open, measured from // the encoder zero (fully closed). Returns std::nullopt when never @@ -78,7 +117,20 @@ class Calibration { std::chrono::milliseconds timeout = std::chrono::milliseconds{500}); private: - bus::Transport& t_; + // Sends the sized read (op 0x02). Returns false when the firmware rejects + // the op as InvalidParam (pre-V2.10); otherwise fills `out`, with + // std::nullopt for CalNotSet. Any other NACK throws ProtocolError. + bool read_fisheye_sized_(std::chrono::milliseconds timeout, + std::optional& out); + + // Records whether the firmware answered the sized read: -1 not yet asked, + // 0 unsupported (pre-V2.10), 1 supported. Set only from a real answer. + void note_fisheye_size_support_(bool supported) noexcept { + fisheye_size_support_.store(supported ? 1 : 0); + } + + bus::Transport& t_; + std::atomic fisheye_size_support_{-1}; }; } // namespace xense::taccap diff --git a/cpp/include/taccap/components/fisheye_undistorter.hpp b/cpp/include/taccap/components/fisheye_undistorter.hpp index 4a40b58..b6ad63a 100644 --- a/cpp/include/taccap/components/fisheye_undistorter.hpp +++ b/cpp/include/taccap/components/fisheye_undistorter.hpp @@ -20,19 +20,60 @@ #include #include +#include +#include #include namespace xense::taccap { -// The wrist camera is calibrated at 640x480 and the firmware record carries -// ONLY the 8 intrinsic/distortion floats — no image size. Rather than guess a -// scale factor for a differently-sized frame (which would silently produce a -// wrong rectification), the constructor rejects any other size outright. If a -// second calibration resolution is ever needed, the right fix is to record the -// size in the firmware payload, not to infer it here. +// The 8 intrinsic/distortion floats only hold at the capture resolution they +// were measured at. 640x480 (4:3) and 1920x1080 (16:9) are DIFFERENT sensor +// crops, not one image at two scales, so intrinsics cannot be rescaled between +// them — nor to any other size. Firmware V2.10 (leader 1.2.8 / follower 1.2.18) +// therefore records the calibration resolution next to the params +// (Calibration::read_fisheye_record / write_fisheye_sized), and the undistorter +// refuses any frame that is not at that exact resolution. +// +// 640x480 remains the resolution of the SDK's reference calibration and of the +// legacy constructor below, which predates the recorded size. inline constexpr int FISHEYE_CALIB_WIDTH = 640; inline constexpr int FISHEYE_CALIB_HEIGHT = 480; +// A fisheye record as the firmware holds it: the params plus the capture +// resolution they belong to. width/height 0/0 means the size is UNKNOWN — the +// record was written without one (CalOp::Write, or firmware older than V2.10) +// — and must not be assumed to be 640x480; see infer_fisheye_cal_size(). +struct FisheyeCalRecord { + protocol::CameraFisheyeCal calibration{}; + uint16_t width = 0; + uint16_t height = 0; + + bool size_known() const noexcept { return width != 0 && height != 0; } +}; + +// The plausibility rule the firmware applies to a write-sized (op 0x03), so a +// write can be refused host-side with a useful message rather than a bare +// InvalidParam: every value finite, fx > 0, fy > 0, 1 <= width, height <= 4096, +// and the principal point strictly inside the frame (0 < cx < width, +// 0 < cy < height). +bool fisheye_cal_size_plausible(const protocol::CameraFisheyeCal& cal, + int width, int height); + +// Best-effort calibration resolution for a record whose size is unknown. +// +// The rule, shared verbatim with the PC calibration tools so every consumer +// infers the same answer: +// - candidates are exactly 640x480 and 1920x1080; +// - a candidate W x H matches when the calibration is usable +// (is_usable_fisheye_cal) AND |cx - W/2| <= 0.10 * W AND +// |cy - H/2| <= 0.10 * H, i.e. the principal point sits within 10% of the +// frame centre on each axis; +// - the size is returned only when EXACTLY one candidate matches; zero or +// several matches return std::nullopt. +// A principal point far from both centres is not "probably 640x480": it means +// the record cannot be placed, and the caller should ask for a recalibration. +std::optional infer_fisheye_cal_size(const protocol::CameraFisheyeCal& cal); + // `balance` interpolates the output focal length between these two, matching // the PC tool's fisheye_focal_scale_for_balance() // (tc-gu-01-pc/camera_calibration/calibration/workflow.py). balance = 0 keeps @@ -40,10 +81,10 @@ inline constexpr int FISHEYE_CALIB_HEIGHT = 480; // shortens it to 0.70x for the widest field of view, at the cost of more // black border around the edges. // A reference calibration for the TC-GU-01 wrist lens, measured on a sample -// unit. It exists so a gripper whose firmware was never calibrated can still -// deliver an approximately rectified stream instead of raw fisheye — every unit -// carries the same lens and the same 640x480 sensor, so the shared numbers are -// far closer to correct than no rectification at all. +// unit at 640x480. It exists so a gripper whose firmware was never calibrated +// can still deliver an approximately rectified stream instead of raw fisheye — +// every unit carries the same lens and sensor, so the shared numbers are far +// closer to correct than no rectification at all. They hold at 640x480 ONLY. // // It is NOT a substitute for calibrating a unit. Lens placement varies between // assemblies, so the principal point in particular drifts per unit; anything @@ -70,10 +111,17 @@ inline constexpr protocol::CameraFisheyeCal FISHEYE_FALLBACK_CAL{ // UVC device, and callers that own the device themselves (the common case, since // Config::open_cameras defaults to false) get the identical answer instead of // re-deriving it and drifting. +// +// `calibrated_size` is the capture resolution `calibration` belongs to: the +// size the firmware recorded, or — for a record written without one — +// infer_fisheye_cal_size()'s answer, flagged by `size_inferred`. The reference +// calibration is always 640x480 with size_inferred false. struct ResolvedFisheyeCal { protocol::CameraFisheyeCal calibration; bool is_reference; std::string reason; + cv::Size calibrated_size{FISHEYE_CALIB_WIDTH, FISHEYE_CALIB_HEIGHT}; + bool size_inferred = false; }; inline bool is_usable_fisheye_cal(const protocol::CameraFisheyeCal& c) { @@ -85,9 +133,21 @@ inline constexpr double FISHEYE_WIDE_FOCAL_SCALE = 0.70; class FisheyeUndistorter { public: - // Throws Error when `size` is not the calibrated 640x480. `balance` is + // `calibrated_size` is the resolution `cal` was measured at (from + // FisheyeCalRecord / ResolvedFisheyeCal::calibrated_size); `frame_size` is + // what the camera actually delivers. They must be EQUAL — throws Error + // otherwise, because intrinsics do not carry over to another resolution or + // aspect ratio; recalibrate at the capture resolution instead. `balance` is // clamped to [0,1] rather than rejected — it is a taste knob, not a // correctness one. + FisheyeUndistorter(const protocol::CameraFisheyeCal& cal, + cv::Size calibrated_size, + cv::Size frame_size, + float balance = 0.0f); + + // Legacy form, from before the firmware recorded a calibration size: `cal` + // is taken to be a 640x480 calibration, so this throws Error unless `size` + // is 640x480. Prefer the form above with the record's own size. FisheyeUndistorter(const protocol::CameraFisheyeCal& cal, cv::Size size, float balance = 0.0f); diff --git a/cpp/include/taccap/follower_gripper.hpp b/cpp/include/taccap/follower_gripper.hpp index e6027a5..4c22692 100644 --- a/cpp/include/taccap/follower_gripper.hpp +++ b/cpp/include/taccap/follower_gripper.hpp @@ -257,8 +257,9 @@ class FollowerGripper { // // Degrades to raw frames with a warning when the firmware holds no // calibration or is too old to answer. Throws when the camera is not - // configured at the calibrated 640x480 — the firmware record stores no - // image size, so rescaling the intrinsics would be a guess. + // configured at the calibration's own resolution (recorded by V2.10 + // firmware, inferred for an older record, 640x480 for the reference) — + // intrinsics are never rescaled to another resolution. bool undistort_wrist = false; // 0 = the calibrated focal length (natural view, matches the PC tool's // default); 1 = 0.70x focal length for the widest field of view, with diff --git a/cpp/include/taccap/leader_gripper.hpp b/cpp/include/taccap/leader_gripper.hpp index c4128ef..5cdff60 100644 --- a/cpp/include/taccap/leader_gripper.hpp +++ b/cpp/include/taccap/leader_gripper.hpp @@ -96,8 +96,9 @@ class LeaderGripper { // // Degrades to raw frames with a warning when the firmware holds no // calibration or is too old to answer. Throws when the camera is not - // configured at the calibrated 640x480 — the firmware record stores no - // image size, so rescaling the intrinsics would be a guess. + // configured at the calibration's own resolution (recorded by V2.10 + // firmware, inferred for an older record, 640x480 for the reference) — + // intrinsics are never rescaled to another resolution. bool undistort_wrist = false; // 0 = the calibrated focal length (natural view, matches the PC tool's // default); 1 = 0.70x focal length for the widest field of view, with diff --git a/cpp/include/taccap/protocol/codec.hpp b/cpp/include/taccap/protocol/codec.hpp index d596647..6e0dac4 100644 --- a/cpp/include/taccap/protocol/codec.hpp +++ b/cpp/include/taccap/protocol/codec.hpp @@ -63,6 +63,11 @@ std::vector encode(const CalSetAllPayload&); // instead of an encode() overload (the same struct maps to two wire shapes). std::vector encode_camera_fisheye_cal_read(); // 1 byte std::vector encode_camera_fisheye_cal_write(const CameraFisheyeCal&); // 33 bytes +// V2.10 — fisheye params together with their calibration resolution. +std::vector encode_camera_fisheye_cal_read_sized(); // 1 byte +std::vector encode_camera_fisheye_cal_write_sized(const CameraFisheyeCal&, + uint16_t width, + uint16_t height); // 37 bytes std::vector encode_encoder_max_cal_read(); // 1 byte std::vector encode_encoder_max_cal_write(float max_rad); // 5 bytes @@ -141,6 +146,9 @@ CalGetResponse decode_cal_get(const uint8_t* data, std::size_t len); // V2.0/V2.1 — read responses lead with the CalOp byte echoed back (Read), not // an error byte; these decoders verify that byte and strip it. CameraFisheyeCal decode_camera_fisheye_cal(const uint8_t* data, std::size_t len); +// V2.10 — read-sized response; verifies the echoed op byte (0x02) and strips it. +// width/height 0/0 are passed through as-is (size unknown). +CameraFisheyeCalSized decode_camera_fisheye_cal_sized(const uint8_t* data, std::size_t len); float decode_encoder_max_cal(const uint8_t* data, std::size_t len); // V1.6+ SensorErrorReport decode_sensor_error(const uint8_t* data, std::size_t len); diff --git a/cpp/include/taccap/protocol/payloads.hpp b/cpp/include/taccap/protocol/payloads.hpp index 66198ae..882844b 100644 --- a/cpp/include/taccap/protocol/payloads.hpp +++ b/cpp/include/taccap/protocol/payloads.hpp @@ -934,6 +934,43 @@ struct CameraFisheyeCal { float k4; // params[7] }; +// ---- Fisheye calibration resolution (V2.10, leader 1.2.8 / follower 1.2.18) +// +// The 8 floats only hold at the capture resolution they were measured at: +// 640x480 (4:3) and 1920x1080 (16:9) are different sensor crops, so the +// intrinsics cannot be rescaled between them. V2.10 adds two more ops to +// Cmd::CameraFisheyeCal that carry that resolution alongside the params: +// +// read-sized request : [op=0x02] (1 byte) +// read-sized response: [op echo=0x02][body][width][height] (37 bytes) +// write-sized request : [op=0x03][body][width][height] (37 bytes) +// write-sized response: firmware's generic empty-response ACK +// +// width/height are u16 LE. A read answering 0/0 means "size unknown": the +// params were written with CalOp::Write (which on V2.10 marks the size +// unknown), by older firmware, or the size record no longer matches them. +// The firmware rejects a write-sized unless 1 <= width, height <= 4096, +// fx, fy > 0 and the principal point lies inside the frame. +// +// Firmware that predates V2.10 answers both new ops with InvalidParam, the +// same as any unknown op. Only the READ is a safe capability probe — on V2.10 +// a write-sized InvalidParam also means "implausible values". +// +// These are plain constants rather than CalOp enumerators because CalOp is +// shared with Cmd::EncoderMaxCal, which has no sized form. Mirror firmware +// CAMERA_FISHEYE_CAL_OP_READ_SIZED / _OP_WRITE_SIZED / _SIZED_SIZE. +constexpr uint8_t CAMERA_FISHEYE_CAL_OP_READ_SIZED = 0x02; +constexpr uint8_t CAMERA_FISHEYE_CAL_OP_WRITE_SIZED = 0x03; +constexpr std::size_t CAMERA_FISHEYE_CAL_SIZED_SIZE = 37; + +// Body of a read-sized response / write-sized request, after the op byte: +// firmware camera_fisheye_cal_sized_payload_t minus its leading `op`. +struct CameraFisheyeCalSized { + CameraFisheyeCal calibration; + uint16_t width; // capture width the params belong to; 0 = unknown + uint16_t height; // capture height; 0 = unknown +}; + // ---- WS2812 LED control (V1.9 — Cmd::Ws2812Set 0x0A / Ws2812Effect 0x0B) -- enum class Ws2812Mode : uint8_t { Off = 0, // all LEDs off @@ -1264,6 +1301,9 @@ static_assert(sizeof(Ws2812Effect) == 12); // V1.9 ws2812_effect_t // the FULL_SIZE constants are one larger. static_assert(sizeof(CameraFisheyeCal) == 32); // camera_fisheye_cal_payload_t.params static_assert(sizeof(CameraFisheyeCal) + 1 == CAMERA_FISHEYE_CAL_FULL_SIZE); +// V2.10 — sized fisheye ops: same 8 floats, plus width/height u16. +static_assert(sizeof(CameraFisheyeCalSized) == 36); +static_assert(sizeof(CameraFisheyeCalSized) + 1 == CAMERA_FISHEYE_CAL_SIZED_SIZE); static_assert(sizeof(float) + 1 == ENCODER_MAX_CAL_FULL_SIZE); static_assert(sizeof(StreamConfig) == 12); static_assert(sizeof(AckPayload) == 4); diff --git a/cpp/src/components/calibration.cpp b/cpp/src/components/calibration.cpp index 6b1b4b1..e76516f 100644 --- a/cpp/src/components/calibration.cpp +++ b/cpp/src/components/calibration.cpp @@ -3,9 +3,11 @@ #include #include +#include #include #include +#include #include #include @@ -49,6 +51,92 @@ void Calibration::write_fisheye(const protocol::CameraFisheyeCal& cal, if (err != protocol::ErrorCode::Ok) throw_nack("write_fisheye", err); } +// ---- Fisheye calibration resolution (V2.10) -------------------------------- + +bool Calibration::read_fisheye_sized_(std::chrono::milliseconds timeout, + std::optional& out) { + auto ack = t_.send_cmd(protocol::Cmd::CameraFisheyeCal, + protocol::encode_camera_fisheye_cal_read_sized(), timeout); + const auto err = ack_error_code(ack); + // Pre-V2.10 firmware answers any op it does not know with InvalidParam; + // V2.10 answers the sized read with Ok or CalNotSet and nothing else, so + // this is an unambiguous probe. (A sized WRITE's InvalidParam is not: on + // V2.10 it also means "implausible values".) + if (err == protocol::ErrorCode::InvalidParam) { + note_fisheye_size_support_(false); + return false; + } + if (err == protocol::ErrorCode::CalNotSet) { + note_fisheye_size_support_(true); + out.reset(); + return true; + } + // Not cached: an unexpected NACK says nothing about the sized ops. + if (err != protocol::ErrorCode::Ok) throw_nack("read_fisheye_record", err); + note_fisheye_size_support_(true); + const auto sized = + protocol::decode_camera_fisheye_cal_sized(ack.data.data(), ack.data.size()); + out = FisheyeCalRecord{sized.calibration, sized.width, sized.height}; + return true; +} + +bool Calibration::supports_fisheye_size(std::chrono::milliseconds timeout) { + const int cached = fisheye_size_support_.load(); + if (cached >= 0) return cached == 1; + std::optional ignored; + return read_fisheye_sized_(timeout, ignored); +} + +std::optional Calibration::read_fisheye_record( + std::chrono::milliseconds timeout) { + if (fisheye_size_support_.load() != 0) { + std::optional record; + if (read_fisheye_sized_(timeout, record)) return record; + } + // Older firmware: the params alone, size unknown. + auto cal = read_fisheye(timeout); + if (!cal) return std::nullopt; + return FisheyeCalRecord{*cal, 0, 0}; +} + +void Calibration::write_fisheye_sized(const protocol::CameraFisheyeCal& cal, + int width, int height, + std::chrono::milliseconds timeout) { + if (!fisheye_cal_size_plausible(cal, width, height)) { + char buf[384]; + std::snprintf(buf, sizeof(buf), + "Calibration::write_fisheye_sized: the calibration is not plausible " + "for %dx%d (fx=%g, fy=%g, cx=%g, cy=%g). Need every value finite, " + "fx, fy > 0, 1 <= width, height <= 4096 and the principal point " + "inside the frame (0 < cx < width, 0 < cy < height).", + width, height, cal.fx, cal.fy, cal.cx, cal.cy); + throw Error(buf); + } + if (supports_fisheye_size(timeout)) { + auto ack = t_.send_cmd(protocol::Cmd::CameraFisheyeCal, + protocol::encode_camera_fisheye_cal_write_sized( + cal, static_cast(width), + static_cast(height)), + timeout); + const auto err = ack_error_code(ack); + if (err != protocol::ErrorCode::Ok) throw_nack("write_fisheye_sized", err); + return; + } + // Older firmware has nowhere to put the size. A 640x480 calibration is + // what every pre-V2.10 host already assumes, so the legacy write is safe; + // anything else would be read back as if it were 640x480. + if (width == FISHEYE_CALIB_WIDTH && height == FISHEYE_CALIB_HEIGHT) { + write_fisheye(cal, timeout); + return; + } + throw Error( + "Calibration::write_fisheye_sized: this firmware cannot record the " + "calibration resolution, so a " + std::to_string(width) + "x" + + std::to_string(height) + " calibration cannot be stored safely — it " + "would be taken for 640x480. Upgrade the firmware to leader 1.2.8 / " + "follower 1.2.18 or later (command set V2.10), or calibrate at 640x480."); +} + // ---- Leader encoder max travel angle --------------------------------------- std::optional Calibration::read_encoder_max_rad( @@ -70,10 +158,10 @@ void Calibration::write_encoder_max_rad(float max_rad, } ResolvedFisheyeCal Calibration::resolve_fisheye(std::chrono::milliseconds timeout) { - std::optional params; + std::optional record; std::string reason; try { - params = read_fisheye(timeout); + record = read_fisheye_record(timeout); } catch (const ProtocolError& e) { // The firmware does not know Cmd::CameraFisheyeCal (0x2B). That command // belongs to command set V2.0, which follower 1.1.0 already carries — @@ -81,20 +169,55 @@ ResolvedFisheyeCal Calibration::resolve_fisheye(std::chrono::milliseconds timeou reason = std::string("the firmware would not answer the fisheye read (") + e.what() + ")"; } - if (reason.empty() && !params) { + if (reason.empty() && !record) { reason = "the wrist lens has never been calibrated"; } - if (reason.empty() && !is_usable_fisheye_cal(*params)) { + if (reason.empty() && !is_usable_fisheye_cal(record->calibration)) { // An uncalibrated unit answers with an all-zero record rather than a // NACK. Remapping with fx = fy = 0 sends every pixel outside the source // image, so the frame comes back black. reason = "the wrist lens has never been calibrated — the firmware " "answered the read with an empty record"; } + + cv::Size size; + bool inferred = false; + if (reason.empty()) { + const auto& c = record->calibration; + if (record->size_known()) { + size = cv::Size(record->width, record->height); + if (!fisheye_cal_size_plausible(c, size.width, size.height)) { + // The firmware validates a sized write, so this is a damaged + // or foreign record rather than a calibration to trust. + reason = "the recorded calibration resolution " + + std::to_string(size.width) + "x" + + std::to_string(size.height) + + " does not fit the stored intrinsics"; + } + } else if (auto guess = infer_fisheye_cal_size(c)) { + size = *guess; + inferred = true; + logger()->warn("wrist fisheye calibration carries no resolution (written " + "without one, or by firmware older than V2.10); inferred " + "{}x{} from its principal point (cx={:.1f}, cy={:.1f}). " + "Store it again with write_fisheye_sized() to record the " + "size explicitly.", size.width, size.height, c.cx, c.cy); + } else { + char buf[96]; + std::snprintf(buf, sizeof(buf), "principal point cx=%.1f, cy=%.1f", + c.cx, c.cy); + reason = std::string("the calibration resolution is unknown and could " + "not be inferred (") + buf + " fits neither " + "640x480 nor 1920x1080) — store it again with " + "write_fisheye_sized()"; + } + } + if (!reason.empty()) { - return {FISHEYE_FALLBACK_CAL, true, reason}; + return {FISHEYE_FALLBACK_CAL, true, reason, + cv::Size(FISHEYE_CALIB_WIDTH, FISHEYE_CALIB_HEIGHT), false}; } - return {*params, false, {}}; + return {record->calibration, false, {}, size, inferred}; } } // namespace xense::taccap diff --git a/cpp/src/components/fisheye_undistorter.cpp b/cpp/src/components/fisheye_undistorter.cpp index 9d0d34e..7a5c812 100644 --- a/cpp/src/components/fisheye_undistorter.cpp +++ b/cpp/src/components/fisheye_undistorter.cpp @@ -7,22 +7,84 @@ #include #include +#include #include namespace xense::taccap { +namespace { + +std::string size_text(int w, int h) { + return std::to_string(w) + "x" + std::to_string(h); +} + +// The two capture resolutions the wrist camera is calibrated at. Shared with +// the PC tools' inference rule — see infer_fisheye_cal_size() in the header. +constexpr int kInferCandidates[][2] = {{640, 480}, {1920, 1080}}; +constexpr double kInferCentreTolerance = 0.10; + +} // namespace + +bool fisheye_cal_size_plausible(const protocol::CameraFisheyeCal& cal, + int width, int height) { + const float v[] = {cal.fx, cal.fy, cal.cx, cal.cy, + cal.k1, cal.k2, cal.k3, cal.k4}; + for (float x : v) { + if (!std::isfinite(x)) return false; + } + if (!(cal.fx > 0.0f) || !(cal.fy > 0.0f)) return false; + if (width < 1 || width > 4096 || height < 1 || height > 4096) return false; + return cal.cx > 0.0f && cal.cx < static_cast(width) && + cal.cy > 0.0f && cal.cy < static_cast(height); +} + +std::optional infer_fisheye_cal_size(const protocol::CameraFisheyeCal& cal) { + if (!is_usable_fisheye_cal(cal)) return std::nullopt; + std::optional found; + int matches = 0; + for (const auto& c : kInferCandidates) { + const double w = c[0], h = c[1]; + // NaN cx/cy compare false here, so they never match. + if (std::abs(cal.cx - w / 2.0) <= kInferCentreTolerance * w && + std::abs(cal.cy - h / 2.0) <= kInferCentreTolerance * h) { + found = cv::Size(c[0], c[1]); + ++matches; + } + } + if (matches != 1) return std::nullopt; + return found; +} + FisheyeUndistorter::FisheyeUndistorter(const protocol::CameraFisheyeCal& cal, cv::Size size, float balance) - : size_(size) { - if (size.width != FISHEYE_CALIB_WIDTH || size.height != FISHEYE_CALIB_HEIGHT) { + : FisheyeUndistorter(cal, cv::Size(FISHEYE_CALIB_WIDTH, FISHEYE_CALIB_HEIGHT), + size, balance) {} + +FisheyeUndistorter::FisheyeUndistorter(const protocol::CameraFisheyeCal& cal, + cv::Size calibrated_size, + cv::Size frame_size, + float balance) + : size_(frame_size) { + if (calibrated_size.width <= 0 || calibrated_size.height <= 0) { + throw Error( + "FisheyeUndistorter: the calibration resolution is unknown (" + + size_text(calibrated_size.width, calibrated_size.height) + + "). Intrinsics only hold at the resolution they were measured at — " + "recalibrate at the capture resolution, or resolve the record with " + "Calibration::resolve_fisheye()."); + } + if (frame_size != calibrated_size) { throw Error( - "FisheyeUndistorter: the wrist fisheye intrinsics are calibrated at " + - std::to_string(FISHEYE_CALIB_WIDTH) + "x" + - std::to_string(FISHEYE_CALIB_HEIGHT) + ", got " + - std::to_string(size.width) + "x" + std::to_string(size.height) + - ". The firmware record carries no image size, so rescaling would be " - "a guess — configure the camera at the calibrated resolution."); + "FisheyeUndistorter: the wrist fisheye intrinsics belong to " + + size_text(calibrated_size.width, calibrated_size.height) + + ", but the frames are " + + size_text(frame_size.width, frame_size.height) + + ". Intrinsics must not be rescaled to another resolution or aspect " + "ratio (640x480 and 1920x1080 are different sensor crops) — " + "configure the camera at " + + size_text(calibrated_size.width, calibrated_size.height) + + ", or recalibrate at the capture resolution."); } balance_ = std::clamp(balance, 0.0f, 1.0f); diff --git a/cpp/src/protocol/codec.cpp b/cpp/src/protocol/codec.cpp index f5371cf..a57aaae 100644 --- a/cpp/src/protocol/codec.cpp +++ b/cpp/src/protocol/codec.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -82,19 +83,21 @@ std::vector encode_cal_write_request(const T& body) { } // Read responses lead with the op byte echoed back. Validate it and hand back -// a pointer to the body. +// a pointer to the body. `op` is the read op that was sent — CalOp::Read, or +// CAMERA_FISHEYE_CAL_OP_READ_SIZED for the V2.10 sized read. const uint8_t* cal_read_body(const uint8_t* data, std::size_t len, - std::size_t full_size, const char* type_name) { + std::size_t full_size, const char* type_name, + uint8_t op = static_cast(CalOp::Read)) { if (data == nullptr || len != full_size) { throw ProtocolError( std::string("decode ") + type_name + ": expected " + std::to_string(full_size) + " bytes, got " + std::to_string(len)); } - if (data[0] != static_cast(CalOp::Read)) { - throw ProtocolError( - std::string("decode ") + type_name + ": expected leading op byte " + - "0x00 (CalOp::Read), got 0x" + - std::to_string(static_cast(data[0]))); + if (data[0] != op) { + char buf[64]; + std::snprintf(buf, sizeof(buf), ": expected leading op byte 0x%02X, got 0x%02X", + static_cast(op), static_cast(data[0])); + throw ProtocolError(std::string("decode ") + type_name + buf); } return data + 1; } @@ -109,6 +112,23 @@ std::vector encode_camera_fisheye_cal_write(const CameraFisheyeCal& v) return encode_cal_write_request(v); } +std::vector encode_camera_fisheye_cal_read_sized() { + return {CAMERA_FISHEYE_CAL_OP_READ_SIZED}; +} + +std::vector encode_camera_fisheye_cal_write_sized(const CameraFisheyeCal& v, + uint16_t width, + uint16_t height) { + CameraFisheyeCalSized body{}; + body.calibration = v; + body.width = width; + body.height = height; + std::vector out(CAMERA_FISHEYE_CAL_SIZED_SIZE); + out[0] = CAMERA_FISHEYE_CAL_OP_WRITE_SIZED; + std::memcpy(out.data() + 1, &body, sizeof(body)); + return out; +} + std::vector encode_encoder_max_cal_read() { return encode_cal_read_request(); } @@ -207,6 +227,16 @@ CameraFisheyeCal decode_camera_fisheye_cal(const uint8_t* data, std::size_t len) return out; } +CameraFisheyeCalSized decode_camera_fisheye_cal_sized(const uint8_t* data, + std::size_t len) { + const uint8_t* body = cal_read_body(data, len, CAMERA_FISHEYE_CAL_SIZED_SIZE, + "CameraFisheyeCalSized", + CAMERA_FISHEYE_CAL_OP_READ_SIZED); + CameraFisheyeCalSized out{}; + std::memcpy(&out, body, sizeof(out)); + return out; +} + float decode_encoder_max_cal(const uint8_t* data, std::size_t len) { const uint8_t* body = cal_read_body(data, len, ENCODER_MAX_CAL_FULL_SIZE, "EncoderMaxCal"); diff --git a/cpp/src/wrist_fisheye.hpp b/cpp/src/wrist_fisheye.hpp index f63a856..d51b165 100644 --- a/cpp/src/wrist_fisheye.hpp +++ b/cpp/src/wrist_fisheye.hpp @@ -32,8 +32,10 @@ namespace xense::taccap::detail { // - firmware predates command set V2.0 -> ProtocolError(InvalidCmd) // // Propagates (a config bug the caller must fix, not something to paper over): -// - the camera is not running at the calibrated 640x480, so the intrinsics -// do not apply and any rectification would be quietly wrong. +// - the camera is not running at the calibration's own resolution (recorded +// by the firmware, inferred for a legacy record, 640x480 for the +// reference), so the intrinsics do not apply and any rectification would +// be quietly wrong. Intrinsics are never rescaled to fit. inline void install_wrist_undistorter(Calibration& cal, Camera& cam, float balance, @@ -53,13 +55,17 @@ inline void install_wrist_undistorter(Calibration& cal, } const cv::Size size{cam.config().width, cam.config().height}; - auto u = std::make_shared(resolved.calibration, size, - balance); + auto u = std::make_shared( + resolved.calibration, resolved.calibrated_size, size, balance); cam.set_undistorter(u); logger()->info("{}: wrist fisheye undistortion on ({}x{}, balance={:.2f}, " - "focal_scale={:.3f}, calibration={})", who, size.width, - size.height, u->balance(), u->focal_scale(), - resolved.is_reference ? "SDK reference" : "this unit"); + "focal_scale={:.3f}, calibration={}, calibrated at {}x{} ({}))", + who, size.width, size.height, u->balance(), u->focal_scale(), + resolved.is_reference ? "SDK reference" : "this unit", + resolved.calibrated_size.width, resolved.calibrated_size.height, + resolved.is_reference ? "reference" + : resolved.size_inferred ? "inferred" + : "recorded"); } } // namespace xense::taccap::detail diff --git a/cpp/tests/CMakeLists.txt b/cpp/tests/CMakeLists.txt index 6cd9a78..590ab27 100644 --- a/cpp/tests/CMakeLists.txt +++ b/cpp/tests/CMakeLists.txt @@ -16,6 +16,7 @@ add_executable(taccap_unit_tests test_controller_teardown_pty.cpp test_fisheye_undistort.cpp test_calibration_pty.cpp + test_fisheye_cal_size_pty.cpp test_ota_retry_pty.cpp test_python_compat.cpp test_stuff.cpp diff --git a/cpp/tests/fake_follower.hpp b/cpp/tests/fake_follower.hpp index b4c1e8f..c6ad3de 100644 --- a/cpp/tests/fake_follower.hpp +++ b/cpp/tests/fake_follower.hpp @@ -15,11 +15,13 @@ #include #include +#include #include #include #include #include #include +#include #include namespace taccap_test { @@ -188,6 +190,33 @@ class FakeFollower { return sn_; } + // ---- Fisheye calibration (Cmd 0x2B) ------------------------------------- + // Modelled on the firmware's camera_fisheye_cal handler. V2.10 (follower + // 1.2.18) by default; set_fisheye_size_supported(false) emulates older + // firmware, which answers the sized ops 0x02/0x03 with InvalidParam. + void set_fisheye_size_supported(bool on) { fisheye_sized_.store(on); } + // Pre-load the flash record; width/height 0/0 = size unknown. + void set_fisheye_record(const tp::CameraFisheyeCal& cal, + uint16_t width = 0, uint16_t height = 0) { + std::lock_guard lk(mu_); + fisheye_cal_ = cal; + fisheye_w_ = width; + fisheye_h_ = height; + } + std::optional stored_fisheye() const { + std::lock_guard lk(mu_); + return fisheye_cal_; + } + std::pair stored_fisheye_size() const { + std::lock_guard lk(mu_); + return {fisheye_w_, fisheye_h_}; + } + // The op byte of every 0x2B request, in arrival order. + std::vector fisheye_ops() const { + std::lock_guard lk(mu_); + return fisheye_ops_; + } + private: // Real firmware gives every frame it originates the next value of one 8-bit // counter (protocol_get_next_seq); the transport relies on that to drop a @@ -238,6 +267,9 @@ class FakeFollower { if (last_exchange_reply_) last_exchange_ = f; else last_exchange_.reset(); return; } + case tp::Cmd::CameraFisheyeCal: + handle_fisheye_(f); + return; case tp::Cmd::GetVersion: { const tp::FirmwareVersion v{fw_major_, fw_minor_, fw_patch_, 0}; pty_.send_response(f.seq, f.cmd, pod_bytes(&v, sizeof(v))); @@ -468,6 +500,79 @@ class FakeFollower { } } + // Firmware handler errors go out as protocol_send_response(seq, cmd, err, + // NULL, 0): the command byte echoed and the bare error code as payload. + void fisheye_reply_err_(const xense::taccap::bus::Frame& f, tp::ErrorCode err) { + pty_.send_response(f.seq, f.cmd, {static_cast(err)}); + } + + void handle_fisheye_(const xense::taccap::bus::Frame& f) { + if (f.payload.empty()) { fisheye_reply_err_(f, tp::ErrorCode::LengthMismatch); return; } + const uint8_t op = f.payload[0]; + std::lock_guard lk(mu_); + fisheye_ops_.push_back(op); + const bool sized = op == tp::CAMERA_FISHEYE_CAL_OP_READ_SIZED || + op == tp::CAMERA_FISHEYE_CAL_OP_WRITE_SIZED; + if (sized && !fisheye_sized_.load()) { + fisheye_reply_err_(f, tp::ErrorCode::InvalidParam); // unknown op + return; + } + auto params_finite = [](const tp::CameraFisheyeCal& c) { + for (float v : {c.fx, c.fy, c.cx, c.cy, c.k1, c.k2, c.k3, c.k4}) + if (!std::isfinite(v)) return false; + return true; + }; + if (op == static_cast(tp::CalOp::Read) || + op == tp::CAMERA_FISHEYE_CAL_OP_READ_SIZED) { + if (f.payload.size() != 1) { fisheye_reply_err_(f, tp::ErrorCode::LengthMismatch); return; } + if (!fisheye_cal_) { fisheye_reply_err_(f, tp::ErrorCode::CalNotSet); return; } + std::vector out{op}; + auto body = pod_bytes(&*fisheye_cal_, sizeof(*fisheye_cal_)); + out.insert(out.end(), body.begin(), body.end()); + if (op == tp::CAMERA_FISHEYE_CAL_OP_READ_SIZED) { + for (uint16_t v : {fisheye_w_, fisheye_h_}) { + out.push_back(static_cast(v & 0xFF)); + out.push_back(static_cast(v >> 8)); + } + } + pty_.send_response(f.seq, f.cmd, out); + return; + } + if (op == static_cast(tp::CalOp::Write)) { + if (f.payload.size() != tp::CAMERA_FISHEYE_CAL_FULL_SIZE) { + fisheye_reply_err_(f, tp::ErrorCode::LengthMismatch); + return; + } + tp::CameraFisheyeCal c{}; + std::memcpy(&c, f.payload.data() + 1, sizeof(c)); + if (!params_finite(c)) { fisheye_reply_err_(f, tp::ErrorCode::InvalidParam); return; } + fisheye_cal_ = c; + fisheye_w_ = fisheye_h_ = 0; // V2.10: a legacy write leaves the size unknown + pty_.send_ack_ok(f.seq, f.cmd); + return; + } + if (op == tp::CAMERA_FISHEYE_CAL_OP_WRITE_SIZED) { + if (f.payload.size() != tp::CAMERA_FISHEYE_CAL_SIZED_SIZE) { + fisheye_reply_err_(f, tp::ErrorCode::LengthMismatch); + return; + } + tp::CameraFisheyeCalSized b{}; + std::memcpy(&b, f.payload.data() + 1, sizeof(b)); + const auto& c = b.calibration; + const bool ok = params_finite(c) && c.fx > 0 && c.fy > 0 && + b.width >= 1 && b.width <= 4096 && + b.height >= 1 && b.height <= 4096 && + c.cx > 0 && c.cx < b.width && c.cy > 0 && c.cy < b.height; + if (!ok) { fisheye_reply_err_(f, tp::ErrorCode::InvalidParam); return; } + fisheye_cal_ = c; + fisheye_w_ = b.width; + fisheye_h_ = b.height; + pty_.send_ack_ok(f.seq, f.cmd); + return; + } + fisheye_reply_err_(f, tp::ErrorCode::InvalidParam); + } + void handle_exchange_(const xense::taccap::bus::Frame& f) { tp::ExchangeRequestHeader h{}; if (f.payload.size() < sizeof(h)) { pty_.send_nack(f.seq, tp::ErrorCode::LengthMismatch); return; } @@ -575,6 +680,10 @@ class FakeFollower { uint8_t fw_ver_[4] = {0, 0, 0, 0}; bool fw_ver_valid_ = false; uint8_t fw_ver_source_ = 0; + std::atomic fisheye_sized_{true}; + std::optional fisheye_cal_; // nullopt = never written + uint16_t fisheye_w_ = 0, fisheye_h_ = 0; + std::vector fisheye_ops_; std::atomic spec_supported_{true}; std::atomic corrupt_sn_writes_{false}; std::atomic model_from_flash_{true}; diff --git a/cpp/tests/test_codec_v21.cpp b/cpp/tests/test_codec_v21.cpp index de0053f..383fd20 100644 --- a/cpp/tests/test_codec_v21.cpp +++ b/cpp/tests/test_codec_v21.cpp @@ -133,6 +133,74 @@ TEST(CodecV21, FisheyeDecodeRejectsWrongOpByte) { // ---- Leader encoder max travel angle (Cmd 0x2C) --------------------------- +// ---- V2.10: fisheye params with their calibration resolution --------------- +// Wire bytes from firmware docs/PROTOCOL.md §6.22.1. + +TEST(CodecV210, SizedWireConstants) { + EXPECT_EQ(tp::CAMERA_FISHEYE_CAL_OP_READ_SIZED, 0x02u); + EXPECT_EQ(tp::CAMERA_FISHEYE_CAL_OP_WRITE_SIZED, 0x03u); + EXPECT_EQ(tp::CAMERA_FISHEYE_CAL_SIZED_SIZE, 37u); + EXPECT_EQ(sizeof(tp::CameraFisheyeCalSized), 36u); +} + +TEST(CodecV210, SizedReadRequestIsOpByteOnly) { + auto wire = tp::encode_camera_fisheye_cal_read_sized(); + ASSERT_EQ(wire.size(), 1u); + EXPECT_EQ(wire[0], 0x02u); +} + +TEST(CodecV210, SizedWriteIsOpEightFloatsThenWidthHeightLittleEndian) { + const tp::CameraFisheyeCal cal{477.1f, 476.8f, 968.3f, 563.2f, + -0.021f, 0.0061f, -0.0042f, 0.0011f}; + auto wire = tp::encode_camera_fisheye_cal_write_sized(cal, 1920, 1080); + ASSERT_EQ(wire.size(), tp::CAMERA_FISHEYE_CAL_SIZED_SIZE); + EXPECT_EQ(wire[0], 0x03u); + tp::CameraFisheyeCal params{}; + std::memcpy(¶ms, wire.data() + 1, sizeof(params)); + EXPECT_EQ(0, std::memcmp(&cal, ¶ms, sizeof(cal))); + // "... [32字节 params] 80 07 38 04" — 1920 = 0x0780, 1080 = 0x0438. + EXPECT_EQ(wire[33], 0x80u); + EXPECT_EQ(wire[34], 0x07u); + EXPECT_EQ(wire[35], 0x38u); + EXPECT_EQ(wire[36], 0x04u); +} + +TEST(CodecV210, SizedEncodeDecodeRoundtrip) { + const tp::CameraFisheyeCal cal{1.5f, 2.5f, 3.5f, 4.5f, 5.5f, 6.5f, 7.5f, 8.5f}; + auto wire = tp::encode_camera_fisheye_cal_write_sized(cal, 640, 480); + // Write request and read response share the body; only the op differs. + wire[0] = tp::CAMERA_FISHEYE_CAL_OP_READ_SIZED; + const auto out = tp::decode_camera_fisheye_cal_sized(wire.data(), wire.size()); + EXPECT_EQ(0, std::memcmp(&cal, &out.calibration, sizeof(cal))); + EXPECT_EQ(out.width, 640u); + EXPECT_EQ(out.height, 480u); +} + +TEST(CodecV210, SizedDecodePassesUnknownSizeThrough) { + const tp::CameraFisheyeCal cal{213.0f, 212.8f, 321.4f, 239.95f, 0, 0, 0, 0}; + auto wire = tp::encode_camera_fisheye_cal_write_sized(cal, 0, 0); + wire[0] = tp::CAMERA_FISHEYE_CAL_OP_READ_SIZED; + const auto out = tp::decode_camera_fisheye_cal_sized(wire.data(), wire.size()); + EXPECT_EQ(out.width, 0u); + EXPECT_EQ(out.height, 0u); + EXPECT_FLOAT_EQ(out.calibration.cx, 321.4f); +} + +TEST(CodecV210, SizedDecodeRejectsWrongLengthAndOp) { + // A legacy 33-byte read response is not a sized one. + auto legacy = make_read_response(tp::CameraFisheyeCal{}); + EXPECT_THROW(tp::decode_camera_fisheye_cal_sized(legacy.data(), legacy.size()), + ProtocolError); + std::vector nack{static_cast(tp::ErrorCode::InvalidParam)}; + EXPECT_THROW(tp::decode_camera_fisheye_cal_sized(nack.data(), nack.size()), + ProtocolError); + // Right length, but the op echoed is the legacy read's. + auto wire = tp::encode_camera_fisheye_cal_write_sized(tp::CameraFisheyeCal{}, 1, 1); + wire[0] = static_cast(tp::CalOp::Read); + EXPECT_THROW(tp::decode_camera_fisheye_cal_sized(wire.data(), wire.size()), + ProtocolError); +} + TEST(CodecV21, EncoderMaxReadRequestIsOpByteOnly) { auto wire = tp::encode_encoder_max_cal_read(); ASSERT_EQ(wire.size(), 1u); diff --git a/cpp/tests/test_fisheye_cal_size_pty.cpp b/cpp/tests/test_fisheye_cal_size_pty.cpp new file mode 100644 index 0000000..270e8ca --- /dev/null +++ b/cpp/tests/test_fisheye_cal_size_pty.cpp @@ -0,0 +1,321 @@ +// Copyright (c) 2026 XenseRobotics Co., Ltd. — Apache-2.0 +// +// End-to-end tests for the V2.10 fisheye calibration resolution (Cmd 0x2B ops +// 0x02 / 0x03), against the fake follower in both of its firmware personas: +// V2.10 (follower 1.2.18), which records the size, and older firmware, which +// answers the sized ops with InvalidParam. +// +// What matters here is the seam between the two: the capability probe, the +// fallbacks on old firmware (legacy read with an unknown size; legacy write +// only for 640x480), and resolve_fisheye()'s use of a recorded, inferred or +// uninferable size. + +#include "fake_follower.hpp" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace tx = xense::taccap; +namespace tb = xense::taccap::bus; +namespace tp = xense::taccap::protocol; +using taccap_test::FakeFollower; +using taccap_test::open_follower; +using taccap_test::Pty; +using taccap_test::base_config; + +namespace { + +constexpr uint8_t kRead = 0x00; +constexpr uint8_t kWrite = 0x01; +constexpr uint8_t kReadSized = tp::CAMERA_FISHEYE_CAL_OP_READ_SIZED; +constexpr uint8_t kWriteSized = tp::CAMERA_FISHEYE_CAL_OP_WRITE_SIZED; + +const tp::CameraFisheyeCal kVga{213.0303f, 212.7928f, 321.4f, 239.95f, + -0.0172f, 0.0091f, -0.0146f, 0.0051f}; +const tp::CameraFisheyeCal kHd{477.2f, 476.9f, 968.3f, 563.1f, + -0.021f, 0.0061f, -0.0042f, 0.0011f}; + +bool same(const tp::CameraFisheyeCal& a, const tp::CameraFisheyeCal& b) { + return std::memcmp(&a, &b, sizeof(a)) == 0; +} + +} // namespace + +// ---- Capability probe ----------------------------------------------------- + +TEST(FisheyeCalSizePty, NewFirmwareSupportsTheSizeEvenWhenUncalibrated) { + Pty pty; + FakeFollower fw(pty); + auto g = open_follower(pty); + // Never written: the sized read answers CalNotSet, which is still V2.10. + EXPECT_TRUE(g->calibration().supports_fisheye_size()); + EXPECT_EQ(fw.fisheye_ops(), std::vector{kReadSized}); +} + +TEST(FisheyeCalSizePty, OldFirmwareInvalidParamMeansUnsupported) { + Pty pty; + FakeFollower fw(pty); + fw.set_fisheye_size_supported(false); + fw.set_fisheye_record(kVga); + auto g = open_follower(pty); + EXPECT_FALSE(g->calibration().supports_fisheye_size()); +} + +TEST(FisheyeCalSizePty, TheAnswerIsCached) { + Pty pty; + FakeFollower fw(pty); + fw.set_fisheye_size_supported(false); + auto g = open_follower(pty); + auto& cal = g->calibration(); + EXPECT_FALSE(cal.supports_fisheye_size()); + EXPECT_FALSE(cal.supports_fisheye_size()); + // read_fisheye_record() also skips the probe once the answer is known. + fw.set_fisheye_record(kVga); + ASSERT_TRUE(cal.read_fisheye_record().has_value()); + EXPECT_EQ(fw.fisheye_ops(), (std::vector{kReadSized, kRead})); +} + +TEST(FisheyeCalSizePty, ATransportFailureIsNotCached) { + Pty pty; + tb::Transport host(base_config(pty.slave_path())); + tx::Calibration cal(host); + + // Nobody answers the first probe (nor its retries). + EXPECT_THROW((void)cal.supports_fisheye_size(), tx::IoError); + // Drop the unanswered attempts still queued on the pty. + while (pty.expect_frame(20)) {} + + std::thread fw([&]() { + auto f = pty.expect_frame(); + if (f) pty.send_response(f->seq, tp::Cmd::CameraFisheyeCal, + {static_cast(tp::ErrorCode::CalNotSet)}); + }); + bool supported = false; + EXPECT_NO_THROW(supported = cal.supports_fisheye_size()); + fw.join(); + EXPECT_TRUE(supported); +} + +// ---- read_fisheye_record -------------------------------------------------- + +TEST(FisheyeCalSizePty, ReadRecordOnNewFirmwareCarriesTheSize) { + Pty pty; + FakeFollower fw(pty); + fw.set_fisheye_record(kHd, 1920, 1080); + auto g = open_follower(pty); + const auto r = g->calibration().read_fisheye_record(); + ASSERT_TRUE(r.has_value()); + EXPECT_TRUE(same(r->calibration, kHd)); + EXPECT_EQ(r->width, 1920u); + EXPECT_EQ(r->height, 1080u); + EXPECT_TRUE(r->size_known()); + // One round trip: the read doubles as the probe. + EXPECT_EQ(fw.fisheye_ops(), std::vector{kReadSized}); +} + +TEST(FisheyeCalSizePty, ReadRecordOnNewFirmwareCanReportAnUnknownSize) { + Pty pty; + FakeFollower fw(pty); + fw.set_fisheye_record(kVga); // e.g. written with op 0x01 + auto g = open_follower(pty); + const auto r = g->calibration().read_fisheye_record(); + ASSERT_TRUE(r.has_value()); + EXPECT_FALSE(r->size_known()); +} + +TEST(FisheyeCalSizePty, ReadRecordOnOldFirmwareFallsBackToTheLegacyRead) { + Pty pty; + FakeFollower fw(pty); + fw.set_fisheye_size_supported(false); + fw.set_fisheye_record(kVga); + auto g = open_follower(pty); + const auto r = g->calibration().read_fisheye_record(); + ASSERT_TRUE(r.has_value()); + EXPECT_TRUE(same(r->calibration, kVga)); + EXPECT_EQ(r->width, 0u); + EXPECT_EQ(r->height, 0u); + EXPECT_EQ(fw.fisheye_ops(), (std::vector{kReadSized, kRead})); +} + +TEST(FisheyeCalSizePty, ReadRecordIsEmptyWhenNeverCalibrated) { + for (bool sized : {true, false}) { + Pty pty; + FakeFollower fw(pty); + fw.set_fisheye_size_supported(sized); + auto g = open_follower(pty); + EXPECT_FALSE(g->calibration().read_fisheye_record().has_value()) + << "sized=" << sized; + } +} + +// ---- write_fisheye_sized --------------------------------------------------- + +TEST(FisheyeCalSizePty, WriteSizedOnNewFirmwareRecordsTheSize) { + Pty pty; + FakeFollower fw(pty); + auto g = open_follower(pty); + g->calibration().write_fisheye_sized(kHd, 1920, 1080); + ASSERT_TRUE(fw.stored_fisheye().has_value()); + EXPECT_TRUE(same(*fw.stored_fisheye(), kHd)); + EXPECT_EQ(fw.stored_fisheye_size(), (std::pair{1920, 1080})); + EXPECT_EQ(fw.fisheye_ops(), (std::vector{kReadSized, kWriteSized})); + + // And it reads back with its size. + const auto r = g->calibration().read_fisheye_record(); + ASSERT_TRUE(r.has_value()); + EXPECT_EQ(r->width, 1920u); +} + +TEST(FisheyeCalSizePty, LegacyWriteOnNewFirmwareLeavesTheSizeUnknown) { + Pty pty; + FakeFollower fw(pty); + fw.set_fisheye_record(kHd, 1920, 1080); + auto g = open_follower(pty); + g->calibration().write_fisheye(kVga); + EXPECT_EQ(fw.stored_fisheye_size(), (std::pair{0, 0})); +} + +TEST(FisheyeCalSizePty, WriteSizedOnOldFirmwareFallsBackForVga) { + Pty pty; + FakeFollower fw(pty); + fw.set_fisheye_size_supported(false); + auto g = open_follower(pty); + g->calibration().write_fisheye_sized(kVga, 640, 480); + ASSERT_TRUE(fw.stored_fisheye().has_value()); + EXPECT_TRUE(same(*fw.stored_fisheye(), kVga)); + EXPECT_EQ(fw.fisheye_ops(), (std::vector{kReadSized, kWrite})); +} + +TEST(FisheyeCalSizePty, WriteSizedOnOldFirmwareRefuses1080p) { + Pty pty; + FakeFollower fw(pty); + fw.set_fisheye_size_supported(false); + auto g = open_follower(pty); + try { + g->calibration().write_fisheye_sized(kHd, 1920, 1080); + FAIL() << "expected Error"; + } catch (const tx::ProtocolError&) { + FAIL() << "a refusal is the host's decision, not a firmware NACK"; + } catch (const tx::Error& e) { + const std::string msg = e.what(); + EXPECT_NE(msg.find("cannot record the calibration resolution"), std::string::npos) << msg; + EXPECT_NE(msg.find("1.2.8"), std::string::npos) << msg; + EXPECT_NE(msg.find("1.2.18"), std::string::npos) << msg; + } + // Nothing was written: only the probe went out. + EXPECT_FALSE(fw.stored_fisheye().has_value()); + EXPECT_EQ(fw.fisheye_ops(), std::vector{kReadSized}); +} + +TEST(FisheyeCalSizePty, WriteSizedRejectsImplausibleValuesBeforeSending) { + Pty pty; + FakeFollower fw(pty); + auto g = open_follower(pty); + auto& cal = g->calibration(); + // The firmware's own example: 1080p params (cx ~ 968) labelled 640x480. + EXPECT_THROW(cal.write_fisheye_sized(kHd, 640, 480), tx::Error); + EXPECT_THROW(cal.write_fisheye_sized(kVga, 0, 480), tx::Error); + EXPECT_THROW(cal.write_fisheye_sized(kVga, 640, 5000), tx::Error); + auto zero_f = kVga; + zero_f.fx = 0.0f; + EXPECT_THROW(cal.write_fisheye_sized(zero_f, 640, 480), tx::Error); + auto inf_k = kVga; + inf_k.k1 = std::numeric_limits::infinity(); + EXPECT_THROW(cal.write_fisheye_sized(inf_k, 640, 480), tx::Error); + EXPECT_TRUE(fw.fisheye_ops().empty()); + EXPECT_FALSE(fw.stored_fisheye().has_value()); +} + +TEST(FisheyeCalSizePty, WriteSizedFirmwareRejectionThrowsProtocolError) { + // A V2.10 firmware NACK (raw pty, so the reply is under test control). + Pty pty; + tb::Transport host(base_config(pty.slave_path())); + tx::Calibration cal(host); + + std::vector ops; + std::thread fw([&]() { + // Probe: supported, uncalibrated. + auto f = pty.expect_frame(); + if (!f) return; + ops.push_back(f->payload.at(0)); + pty.send_response(f->seq, tp::Cmd::CameraFisheyeCal, + {static_cast(tp::ErrorCode::CalNotSet)}); + // Sized write: flash write failed. + f = pty.expect_frame(); + if (!f) return; + ops.push_back(f->payload.at(0)); + pty.send_response(f->seq, tp::Cmd::CameraFisheyeCal, + {static_cast(tp::ErrorCode::SysBusy)}); + }); + EXPECT_THROW(cal.write_fisheye_sized(kHd, 1920, 1080), tx::ProtocolError); + fw.join(); + EXPECT_EQ(ops, (std::vector{kReadSized, kWriteSized})); +} + +// ---- resolve_fisheye --------------------------------------------------------- + +TEST(FisheyeCalSizePty, ResolveUsesTheRecordedSize) { + Pty pty; + FakeFollower fw(pty); + fw.set_fisheye_record(kHd, 1920, 1080); + auto g = open_follower(pty); + const auto r = g->calibration().resolve_fisheye(); + EXPECT_FALSE(r.is_reference); + EXPECT_TRUE(r.reason.empty()); + EXPECT_TRUE(same(r.calibration, kHd)); + EXPECT_EQ(r.calibrated_size, cv::Size(1920, 1080)); + EXPECT_FALSE(r.size_inferred); +} + +TEST(FisheyeCalSizePty, ResolveInfersAnUnknownSize) { + for (bool sized : {true, false}) { + Pty pty; + FakeFollower fw(pty); + fw.set_fisheye_size_supported(sized); + fw.set_fisheye_record(kHd); // no size recorded + auto g = open_follower(pty); + const auto r = g->calibration().resolve_fisheye(); + EXPECT_FALSE(r.is_reference) << r.reason; + EXPECT_TRUE(same(r.calibration, kHd)); + EXPECT_EQ(r.calibrated_size, cv::Size(1920, 1080)); + EXPECT_TRUE(r.size_inferred); + } +} + +TEST(FisheyeCalSizePty, ResolveFallsBackWhenTheSizeCannotBeInferred) { + Pty pty; + FakeFollower fw(pty); + auto odd = kHd; + odd.cx = 600.0f; + odd.cy = 400.0f; + fw.set_fisheye_record(odd); + auto g = open_follower(pty); + const auto r = g->calibration().resolve_fisheye(); + EXPECT_TRUE(r.is_reference); + EXPECT_TRUE(same(r.calibration, tx::FISHEYE_FALLBACK_CAL)); + EXPECT_NE(r.reason.find("resolution is unknown and could not be inferred"), + std::string::npos) << r.reason; + EXPECT_EQ(r.calibrated_size, cv::Size(640, 480)); + EXPECT_FALSE(r.size_inferred); +} + +TEST(FisheyeCalSizePty, ResolveReferenceFallbackIs640x480) { + Pty pty; + FakeFollower fw(pty); // never calibrated + auto g = open_follower(pty); + const auto r = g->calibration().resolve_fisheye(); + EXPECT_TRUE(r.is_reference); + EXPECT_EQ(r.reason, "the wrist lens has never been calibrated"); + EXPECT_EQ(r.calibrated_size, cv::Size(640, 480)); + EXPECT_FALSE(r.size_inferred); +} diff --git a/cpp/tests/test_fisheye_undistort.cpp b/cpp/tests/test_fisheye_undistort.cpp index 2069abb..1e529ed 100644 --- a/cpp/tests/test_fisheye_undistort.cpp +++ b/cpp/tests/test_fisheye_undistort.cpp @@ -18,6 +18,9 @@ #include #include +#include +#include +#include namespace tp = xense::taccap::protocol; using xense::taccap::Error; @@ -53,8 +56,9 @@ tp::CameraFisheyeCal undistorted_cal() { TEST(FisheyeUndistorter, RejectsAnySizeOtherThanTheCalibratedOne) { const auto cal = distorted_cal(); - // The firmware record carries no image size, so a differently-sized frame - // cannot be served without guessing a scale factor. Refuse instead. + // The legacy constructor takes the params as a 640x480 calibration, and a + // differently-sized frame cannot be served without rescaling them, which + // would be wrong. Refuse instead. EXPECT_THROW(FisheyeUndistorter(cal, cv::Size(1280, 720)), Error); EXPECT_THROW(FisheyeUndistorter(cal, cv::Size(320, 240)), Error); EXPECT_THROW(FisheyeUndistorter(cal, cv::Size(640, 481)), Error); @@ -216,3 +220,130 @@ TEST(FisheyeUndistorter, ReportsWhatItWasBuiltFor) { EXPECT_EQ(u.size().height, kCalibSize.height); EXPECT_FLOAT_EQ(u.balance(), 0.25f); } + +// ---- Calibration resolution (V2.10) --------------------------------------- +// +// 640x480 and 1920x1080 are different sensor crops, so the intrinsics belong to +// exactly one resolution and the undistorter must never rescale them. + +namespace { + +// Measured 1920x1080 wrist calibration (shape of the PC tool's output). +tp::CameraFisheyeCal hd_cal() { + return tp::CameraFisheyeCal{ + /*fx=*/477.2f, /*fy=*/476.9f, /*cx=*/968.3f, /*cy=*/563.1f, + /*k1=*/-0.021f, /*k2=*/0.0061f, /*k3=*/-0.0042f, /*k4=*/0.0011f}; +} + +} // namespace + +TEST(FisheyeCalSize, InferenceRecognisesTheVgaReference) { + // FISHEYE_FALLBACK_CAL: cx = 321.4, cy = 239.95. + const auto s = xense::taccap::infer_fisheye_cal_size(xense::taccap::FISHEYE_FALLBACK_CAL); + ASSERT_TRUE(s.has_value()); + EXPECT_EQ(*s, cv::Size(640, 480)); +} + +TEST(FisheyeCalSize, InferenceRecognisesA1080pCalibration) { + const auto s = xense::taccap::infer_fisheye_cal_size(hd_cal()); + ASSERT_TRUE(s.has_value()); + EXPECT_EQ(*s, cv::Size(1920, 1080)); +} + +TEST(FisheyeCalSize, InferenceRefusesWhenNoCandidateMatches) { + using xense::taccap::infer_fisheye_cal_size; + // Between the two centres: within 10% of neither. + auto c = hd_cal(); + c.cx = 600.0f; c.cy = 400.0f; + EXPECT_FALSE(infer_fisheye_cal_size(c).has_value()); + // x fits 640x480 but y fits only 1920x1080: one axis is not a match. + c.cx = 321.0f; c.cy = 540.0f; + EXPECT_FALSE(infer_fisheye_cal_size(c).has_value()); + // Exactly on the 10% boundary still matches; just past it does not. + c.cx = 320.0f + 64.0f; c.cy = 240.0f; + EXPECT_EQ(infer_fisheye_cal_size(c), std::optional(cv::Size(640, 480))); + c.cx = 320.0f + 64.5f; + EXPECT_FALSE(infer_fisheye_cal_size(c).has_value()); +} + +TEST(FisheyeCalSize, InferenceRefusesAnUnusableCalibration) { + using xense::taccap::infer_fisheye_cal_size; + // All-zero record: not usable, and cx = cy = 0 fits nothing anyway. + EXPECT_FALSE(infer_fisheye_cal_size(tp::CameraFisheyeCal{}).has_value()); + // A centred principal point does not rescue fx = 0. + auto c = distorted_cal(); + c.fx = 0.0f; + EXPECT_FALSE(infer_fisheye_cal_size(c).has_value()); + c = distorted_cal(); + c.cx = std::nanf(""); + EXPECT_FALSE(infer_fisheye_cal_size(c).has_value()); +} + +TEST(FisheyeCalSize, PlausibilityMatchesTheFirmwareRule) { + using xense::taccap::fisheye_cal_size_plausible; + EXPECT_TRUE(fisheye_cal_size_plausible(distorted_cal(), 640, 480)); + EXPECT_TRUE(fisheye_cal_size_plausible(hd_cal(), 1920, 1080)); + // The firmware's own example: a 1080p calibration (cx ~ 968) at 640x480. + EXPECT_FALSE(fisheye_cal_size_plausible(hd_cal(), 640, 480)); + EXPECT_FALSE(fisheye_cal_size_plausible(distorted_cal(), 0, 480)); + EXPECT_FALSE(fisheye_cal_size_plausible(distorted_cal(), 640, 4097)); + auto c = distorted_cal(); + c.fy = -1.0f; + EXPECT_FALSE(fisheye_cal_size_plausible(c, 640, 480)); + c = distorted_cal(); + c.k3 = std::numeric_limits::infinity(); + EXPECT_FALSE(fisheye_cal_size_plausible(c, 640, 480)); + c = distorted_cal(); + c.cx = 640.0f; // on the edge is outside: 0 < cx < width + EXPECT_FALSE(fisheye_cal_size_plausible(c, 640, 480)); +} + +TEST(FisheyeCalSize, RecordSizeIsKnownOnlyWhenBothDimensionsAreSet) { + xense::taccap::FisheyeCalRecord r; + EXPECT_FALSE(r.size_known()); + r.width = 1920; + EXPECT_FALSE(r.size_known()); + r.height = 1080; + EXPECT_TRUE(r.size_known()); +} + +TEST(FisheyeUndistorter, SizedConstructorAcceptsTheCalibratedResolution) { + const cv::Size hd(1920, 1080); + FisheyeUndistorter u(hd_cal(), hd, hd); + EXPECT_EQ(u.size(), hd); + cv::Mat src(hd, CV_8UC3, cv::Scalar(10, 20, 30)); + EXPECT_EQ(u.apply(src).size(), hd); + // 640x480 through the sized form, too. + EXPECT_NO_THROW(FisheyeUndistorter(distorted_cal(), kCalibSize, kCalibSize, 0.5f)); +} + +TEST(FisheyeUndistorter, SizedConstructorRejectsAnyOtherFrameSize) { + const cv::Size hd(1920, 1080); + // Neither direction is a rescale the SDK will do: different sensor crops. + EXPECT_THROW(FisheyeUndistorter(hd_cal(), hd, kCalibSize), Error); + EXPECT_THROW(FisheyeUndistorter(distorted_cal(), kCalibSize, hd), Error); + // Same aspect ratio, half the size: still refused. + EXPECT_THROW(FisheyeUndistorter(hd_cal(), hd, cv::Size(960, 540)), Error); + // An unknown calibration size cannot be satisfied by any frame. + EXPECT_THROW(FisheyeUndistorter(hd_cal(), cv::Size(0, 0), cv::Size(0, 0)), Error); + + try { + FisheyeUndistorter(hd_cal(), hd, kCalibSize); + FAIL() << "expected Error"; + } catch (const Error& e) { + const std::string msg = e.what(); + EXPECT_NE(msg.find("1920x1080"), std::string::npos) << msg; + EXPECT_NE(msg.find("rescaled"), std::string::npos) << msg; + EXPECT_NE(msg.find("recalibrate"), std::string::npos) << msg; + } +} + +TEST(FisheyeUndistorter, LegacyConstructorStillMeans640x480) { + // Unchanged behaviour: (cal, size, balance) takes the params as 640x480. + FisheyeUndistorter legacy(distorted_cal(), kCalibSize, 0.25f); + FisheyeUndistorter sized(distorted_cal(), kCalibSize, kCalibSize, 0.25f); + EXPECT_FLOAT_EQ(legacy.balance(), sized.balance()); + EXPECT_EQ(0, cv::norm(legacy.new_camera_matrix(), sized.new_camera_matrix(), + cv::NORM_INF)); + EXPECT_THROW(FisheyeUndistorter(hd_cal(), cv::Size(1920, 1080)), Error); +} diff --git a/docs/CALIBRATION.md b/docs/CALIBRATION.md index 6a37ee6..81a8f6a 100644 --- a/docs/CALIBRATION.md +++ b/docs/CALIBRATION.md @@ -67,7 +67,7 @@ and none of them are lost on reboot: | Record | Command | Scope | Accessor | | --- | --- | --- | --- | -| Fisheye camera `fx, fy, cx, cy, k1..k4` | `0x2B` | leader + follower | `read_fisheye()` / `write_fisheye()` | +| Fisheye camera `fx, fy, cx, cy, k1..k4` (+ calibration resolution, V2.10) | `0x2B` | leader + follower | `read_fisheye_record()` / `write_fisheye_sized()` (legacy: `read_fisheye()` / `write_fisheye()`) | | Encoder max travel angle (rad) | `0x2C` | **leader only** | `read_encoder_max_rad()` / `write_encoder_max_rad()` | Both survive power cycles. A record that was never written normally reads back @@ -97,13 +97,17 @@ policy, so every consumer makes the same decision instead of re-deriving it. **Prefer it over `read_fisheye()`** unless you specifically need to know what the flash holds. -C++ returns a `ResolvedFisheyeCal` (`calibration`, `is_reference`, `reason`); -Python returns the same three as a plain tuple: +Both languages return a `ResolvedFisheyeCal` (`calibration`, `is_reference`, +`reason`, `calibrated_size`, `size_inferred`). In Python it still unpacks as the +`(calibration, is_reference, reason)` tuple it used to be, and +`calibrated_size` is a `(width, height)` tuple: ```python -cal, is_reference, reason = g.calibration.resolve_fisheye() +resolved = g.calibration.resolve_fisheye() +cal, is_reference, reason = resolved if is_reference: log.warning("rectifying with the SDK's reference intrinsics: %s", reason) +w, h = resolved.calibrated_size # open the camera at exactly this size ``` `reason` is non-empty exactly when `is_reference` is true. @@ -115,6 +119,7 @@ Three ways a unit fails to supply its own calibration, all of which fall back: | The lens was never calibrated | `read_fisheye()` → `None` (`CalNotSet`) | | Firmware answered with an all-zero record | `!is_usable_fisheye_cal()` — see above | | Firmware predates command set V2.0 | `ProtocolError` (`InvalidCmd`) on `0x2B` | +| The record has no resolution and none can be inferred | `infer_fisheye_cal_size()` → `None` — see below | What stands in is `FISHEYE_FALLBACK_CAL`, a reference calibration measured on a sample TC-GU-01 and compiled into the SDK @@ -125,8 +130,9 @@ fx 213.0303 fy 212.7928 cx 321.4000 cy 239.9500 k1 -0.0172 k2 0.0091 k3 -0.0146 k4 0.0051 ``` -Every unit carries the same lens on the same 640x480 sensor, so these shared -numbers are much closer to correct than no rectification at all — which is why +They are a **640x480** calibration. Every unit carries the same lens and +sensor, so these shared numbers are much closer to correct than no +rectification at all — which is why `install_wrist_undistorter()` now installs undistortion **always**, and logs which of the two calibrations it used. @@ -161,8 +167,43 @@ measures in pixels off a rectified frame needs this unit's own calibration — store one with `fisheye_cal.py set-fisheye`. Every fallback path warns and says so. +### The calibration resolution (V2.10: leader 1.2.8 / follower 1.2.18) + +The 8 floats hold only at the capture resolution they were measured at. The +wrist camera's default moved from 640x480 to 1920x1080, and those are +**different sensor crops** (4:3 vs 16:9), not one image at two scales — so +intrinsics cannot be rescaled from one to the other, and the SDK never tries. + +Firmware V2.10 records the resolution next to the params (`0x2B` ops +`0x02`/`0x03`): + +| Call | What it does | +| --- | --- | +| `supports_fisheye_size()` | Probes with the sized read: older firmware rejects it as `InvalidParam`. Cached per `Calibration`. | +| `read_fisheye_record()` | `FisheyeCalRecord` (`calibration`, `width`, `height`, `size_known()`); `0/0` = unknown. Older firmware: the legacy read, size `0/0`. `None` when never calibrated. | +| `write_fisheye_sized(cal, w, h)` | Checks `fisheye_cal_size_plausible()` first (the firmware's own rule: finite, `fx, fy > 0`, `1 <= w, h <= 4096`, principal point inside the frame). Older firmware: only 640x480 is accepted, through the legacy write; anything else raises and asks for a firmware upgrade. | + +`write_fisheye()` still works, but on V2.10 firmware it marks the size +**unknown**. Store calibrations with `write_fisheye_sized()`: + +```bash +python python/examples/fisheye_cal.py set-fisheye --from-npz cam.npz --width 1920 --height 1080 +``` + +A record without a size (legacy write, or written by older firmware) is not +assumed to be 640x480. `infer_fisheye_cal_size()` applies a rule shared verbatim +with the PC calibration tools: the candidates are exactly 640x480 and +1920x1080, a candidate `W x H` matches when the calibration is usable and +`|cx - W/2| <= 0.10*W` and `|cy - H/2| <= 0.10*H`, and a size is returned only +when exactly one candidate matches. `resolve_fisheye()` uses it — setting +`size_inferred` and logging a warning — and treats a record it cannot place as +unusable, falling back to the reference. + The one case that still throws rather than falling back is a camera running at -something other than the calibrated 640x480: the firmware record holds only the -8 intrinsic/distortion floats and no image size, so serving another resolution -would mean guessing a scale factor and rectifying wrongly without a trace. That -is a caller bug to fix, not something to paper over. +a resolution other than the calibration's: `FisheyeUndistorter(cal, +calibrated_size, frame_size)` requires the two to be equal (Python: +`FisheyeUndistorter(cal, w, h, calibrated_size=(cw, ch))`). The legacy +`FisheyeUndistorter(cal, size)` form takes the params to be a 640x480 +calibration, as it always has. A mismatch is a caller bug to fix — open the +camera at the calibrated size, or recalibrate at the capture size — not +something to paper over. diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md index c678c2b..6038dc3 100644 --- a/docs/EXAMPLES.md +++ b/docs/EXAMPLES.md @@ -68,7 +68,7 @@ python python/examples/ota_update.py --get-status right | 脚本 | 对设备做什么 | 说明 | |---|---|---| | `calibrate.py` | 写 flash | 编码器零点 + 行程跨度标定;完成后归一化开口度才可用。写入前检查固件支持,写入后实时显示 `raw \| cooked \| 0..1`。见 [CALIBRATION.md](CALIBRATION.md)。| -| `fisheye_cal.py` | `show` 只读,`set-*` 写 flash | 读写 flash 中的标定记录:`show`、`set-fisheye`(命令行参数或含 `K`/`D` 的 OpenCV `.npz`)、`set-encoder-max`、`measure-encoder-max`(引导式行程标定)。| +| `fisheye_cal.py` | `show` 只读,`set-*` 写 flash | 读写 flash 中的标定记录:`show`、`set-fisheye`(命令行参数或含 `K`/`D` 的 OpenCV `.npz`,并用 `--width`/`--height` 给出标定分辨率)、`set-encoder-max`、`measure-encoder-max`(引导式行程标定)。| | `read_intrinsics.py` | 只读 | 以 JSON 输出腕部相机内参。`source` 字段标明来自设备标定(`device`)还是 SDK 参考值(`reference`),`--require-device` 让后者直接失败。JSON 输出到 stdout,可以 `> cal.json` 或管道给 `jq`。| ### 相机与主爪 diff --git a/docs/USAGE-zh.md b/docs/USAGE-zh.md index 34da4e2..21bda84 100644 --- a/docs/USAGE-zh.md +++ b/docs/USAGE-zh.md @@ -524,11 +524,13 @@ g.wrist_camera.start(lambda f: print("wrist", f.frame_index)) ```python from xense.taccap import FisheyeUndistorter -cal, is_reference, reason = g.calibration.resolve_fisheye() +resolved = g.calibration.resolve_fisheye() +cal, is_reference, reason = resolved # 仍可按原来的三元组解包 if is_reference: log.warning(f"用的是 SDK 参考内参,不是这一台的:{reason}") -undist = FisheyeUndistorter(cal, width=640, height=480, balance=0.0) +w, h = resolved.calibrated_size # 相机必须正好跑在这个分辨率 +undist = FisheyeUndistorter(cal, w, h, balance=0.0, calibrated_size=(w, h)) cam.set_undistorter(undist) # 装进采集路径:read() 和回调拿到的都是矫正帧 # 或者手动:rect = undist.apply(img) ``` @@ -539,11 +541,14 @@ cam.set_undistorter(undist) # 装进采集路径:read() 和回调拿到的 不是 NACK,而是返回一条**全零**记录,它能过 `if cal is None` 检查,但 `fx = fy = 0` 会把每个像素映射到画面外 —— 得到一张纯黑的"矫正帧",全程无报错。 `resolve_fisheye()` 已经把这个策略(读 → 判可用 → 回退参考值)做在一处了。 -- **只支持 640×480**,即标定分辨率。固件记录里不带图像尺寸,所以缩放内参等于 - 猜,构造函数宁可抛错。要别的分辨率就得先在固件里存一份对应的标定。 +- **只支持标定时的那个分辨率。** 640×480(4:3)和 1920×1080(16:9)是传感器 + 的不同取景范围,内参不能互相缩放,尺寸不符时构造函数直接抛错。主爪 1.2.8 / + 从爪 1.2.18 起固件随参数一起记录标定分辨率(`read_fisheye_record()` / + `write_fisheye_sized()`);旧记录由 `resolve_fisheye()` 按主点推断 + (`size_inferred`)。要别的分辨率就得存一份在该分辨率下标定的参数。 - **参考内参是近似的**。每台的镜头装配位置有差异(尤其主点),回退到 `FISHEYE_FALLBACK_CAL` 只是比完全不矫正强,不能拿它去按像素做测量。 - 自己标定后用 `fisheye_cal.py set-fisheye --from-npz cam.npz` 写进 flash。 + 自己标定后用 `fisheye_cal.py set-fisheye --from-npz cam.npz --width W --height H` 写进 flash。 `balance` 是取景口味:0 = 保持标定焦距(自然视角,和 PC 工具默认一致), 1 = 焦距压到 0.70x 换最大视场,代价是四周更多黑边。 diff --git a/docs/USAGE.md b/docs/USAGE.md index 142cce8..337e5ca 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -611,11 +611,13 @@ intrinsics into remap tables once, after which each frame is only resampled: ```python from xense.taccap import FisheyeUndistorter -cal, is_reference, reason = g.calibration.resolve_fisheye() +resolved = g.calibration.resolve_fisheye() +cal, is_reference, reason = resolved # still unpacks as before if is_reference: log.warning(f"using the SDK reference intrinsics, not this unit's: {reason}") -undist = FisheyeUndistorter(cal, width=640, height=480, balance=0.0) +w, h = resolved.calibrated_size # the camera must run at exactly this size +undist = FisheyeUndistorter(cal, w, h, balance=0.0, calibrated_size=(w, h)) cam.set_undistorter(undist) # install into the capture path: read() and callbacks both get rectified frames # or manually: rect = undist.apply(img) ``` @@ -628,15 +630,18 @@ Three constraints you must know: get a pure black "rectified frame", with no error raised anywhere. `resolve_fisheye()` already puts that policy (read → judge usable → fall back to the reference values) in one place. -- **Only 640×480 is supported**, the calibration resolution. The firmware record - carries no image size, so scaling the intrinsics would be guessing, and the - constructor would rather throw. Another resolution means storing a matching - calibration in firmware first. +- **Only the calibration's own resolution is supported.** 640×480 (4:3) and + 1920×1080 (16:9) are different sensor crops, so the intrinsics cannot be + rescaled between them and the constructor throws on a mismatch. Firmware + leader 1.2.8 / follower 1.2.18 records the resolution with the params + (`read_fisheye_record()` / `write_fisheye_sized()`); for an older record + `resolve_fisheye()` infers it from the principal point (`size_inferred`). + Another resolution means storing a calibration measured at it. - **The reference intrinsics are an approximation.** Lens mounting varies from unit to unit (the principal point especially), so falling back to `FISHEYE_FALLBACK_CAL` is only better than not rectifying at all — do not take pixel-accurate measurements from it. Once you have calibrated your own, write it to flash with - `fisheye_cal.py set-fisheye --from-npz cam.npz`. + `fisheye_cal.py set-fisheye --from-npz cam.npz --width W --height H`. `balance` is a framing preference: 0 = keep the calibrated focal length (natural field of view, matching the PC tool's default), 1 = squeeze the focal length to 0.70x for diff --git a/python/bindings/bind_calibration.cpp b/python/bindings/bind_calibration.cpp index 8c0b8b6..eeb83e5 100644 --- a/python/bindings/bind_calibration.cpp +++ b/python/bindings/bind_calibration.cpp @@ -16,9 +16,11 @@ void bind_calibration(py::module_& m) { "Wrist-camera intrinsics and fisheye distortion, as the firmware persists\n" "them (Cmd 0x2B, command set >= V2.0). k1..k4 are the OpenCV fisheye\n" "(equidistant) coefficients, in D order.\n\n" - "Eight floats in an order fixed by the firmware. The record carries no image\n" - "size: the wrist lens is calibrated at 640x480, and FisheyeUndistorter\n" - "rejects any other frame size rather than guessing a scale factor.") + "Eight floats in an order fixed by the firmware. They hold only at the\n" + "capture resolution they were measured at -- 640x480 and 1920x1080 are\n" + "different sensor crops, so they cannot be rescaled between the two. That\n" + "resolution travels separately: see FisheyeCalRecord and\n" + "Calibration.read_fisheye_record.") .def(py::init([]() { return protocol::CameraFisheyeCal{}; }), "All-zero record. Not usable for rectification -- fx = fy = 0 maps every\n" "pixel outside the source image, so the frame comes back black.") @@ -65,6 +67,88 @@ void bind_calibration(py::module_& m) { return std::string(buf); }); + // ---- FisheyeCalRecord (V2.10 — params + calibration resolution) -------- + py::class_(m, "FisheyeCalRecord", + "A fisheye record as the firmware holds it: the params plus the capture\n" + "resolution they were measured at (Calibration.read_fisheye_record).\n\n" + "width/height 0/0 means the size is UNKNOWN -- the params were written\n" + "without one (write_fisheye, or firmware older than leader 1.2.8 /\n" + "follower 1.2.18). Do not assume 640x480 then; infer_fisheye_cal_size()\n" + "applies the shared inference rule, and resolve_fisheye() uses it.") + .def(py::init([](const protocol::CameraFisheyeCal& cal, + uint16_t width, uint16_t height) { + return FisheyeCalRecord{cal, width, height}; + }), + py::arg("calibration") = protocol::CameraFisheyeCal{}, + py::arg("width") = 0, py::arg("height") = 0, + "Build a record; width/height default to 0/0 (size unknown).") + .def_readwrite("calibration", &FisheyeCalRecord::calibration, + "The 8 params, as a CameraFisheyeCal.") + .def_readwrite("width", &FisheyeCalRecord::width, + "Capture width in px the params belong to; 0 = unknown.") + .def_readwrite("height", &FisheyeCalRecord::height, + "Capture height in px the params belong to; 0 = unknown.") + .def("size_known", &FisheyeCalRecord::size_known, + "True when width and height are both non-zero, i.e. the firmware " + "recorded the calibration resolution.") + .def("__repr__", [](const FisheyeCalRecord& r) { + char buf[256]; + std::snprintf(buf, sizeof(buf), + "FisheyeCalRecord(fx=%.3f, fy=%.3f, cx=%.3f, cy=%.3f, size=%s)", + r.calibration.fx, r.calibration.fy, r.calibration.cx, + r.calibration.cy, + r.size_known() + ? (std::to_string(r.width) + "x" + std::to_string(r.height)).c_str() + : "unknown"); + return std::string(buf); + }); + + // ---- ResolvedFisheyeCal (Calibration.resolve_fisheye's answer) --------- + // Read-only, and still unpacks as the (calibration, is_reference, reason) + // tuple resolve_fisheye() returned before the size fields existed, so + // `cal, is_reference, reason = g.calibration.resolve_fisheye()` keeps working. + py::class_(m, "ResolvedFisheyeCal", + "What to rectify the wrist camera with, from Calibration.resolve_fisheye().\n\n" + "Unpacks as (calibration, is_reference, reason) for compatibility with\n" + "code written before calibrated_size / size_inferred existed.") + .def_property_readonly("calibration", + [](const ResolvedFisheyeCal& r) { return r.calibration; }, + "The CameraFisheyeCal to rectify with.") + .def_property_readonly("is_reference", + [](const ResolvedFisheyeCal& r) { return r.is_reference; }, + "True when the SDK's shared reference values stood in.") + .def_property_readonly("reason", + [](const ResolvedFisheyeCal& r) { return r.reason; }, + "Why the reference stood in; empty when is_reference is False.") + .def_property_readonly("calibrated_size", + [](const ResolvedFisheyeCal& r) { + return py::make_tuple(r.calibrated_size.width, r.calibrated_size.height); + }, + "(width, height) the calibration belongs to: recorded by the firmware,\n" + "inferred for a record written without one (size_inferred), or\n" + "(640, 480) for the reference. Frames must be exactly this size.") + .def_property_readonly("size_inferred", + [](const ResolvedFisheyeCal& r) { return r.size_inferred; }, + "True when calibrated_size was inferred from the principal point\n" + "because the record carries no size (see infer_fisheye_cal_size).") + .def("__len__", [](const ResolvedFisheyeCal&) { return 3; }) + .def("__getitem__", [](const ResolvedFisheyeCal& r, py::ssize_t i) { + py::tuple t = py::make_tuple(r.calibration, r.is_reference, r.reason); + return py::object(t[py::int_(i < 0 ? i + 3 : i)]); + }) + .def("__iter__", [](const ResolvedFisheyeCal& r) { + return py::iter(py::make_tuple(r.calibration, r.is_reference, r.reason)); + }) + .def("__repr__", [](const ResolvedFisheyeCal& r) { + return "ResolvedFisheyeCal(is_reference=" + + std::string(r.is_reference ? "True" : "False") + + ", calibrated_size=" + std::to_string(r.calibrated_size.width) + + "x" + std::to_string(r.calibrated_size.height) + + ", size_inferred=" + (r.size_inferred ? "True" : "False") + + (r.reason.empty() ? std::string() : ", reason='" + r.reason + "'") + + ")"; + }); + // ---- Calibration (V2.0/V2.1 firmware-persisted calibration records) ---- py::class_(m, "Calibration", "The calibration records the firmware keeps in MCU flash; reach it as\n" @@ -97,10 +181,11 @@ void bind_calibration(py::module_& m) { py::gil_scoped_release nogil; r = self.resolve_fisheye(std::chrono::milliseconds(timeout_ms)); } - return py::make_tuple(r.calibration, r.is_reference, r.reason); + return r; }, py::arg("timeout_ms") = 200, - "Intrinsics to rectify with, as (calibration, is_reference, reason).\n\n" + "Intrinsics to rectify with, as a ResolvedFisheyeCal -- which still " + "unpacks as (calibration, is_reference, reason).\n\n" "Prefer this over read_fisheye() unless you need to know what the " "flash actually holds. An uncalibrated unit answers a read with an " "all-zero record rather than a NACK, and handing that to " @@ -110,7 +195,12 @@ void bind_calibration(py::module_& m) { "is_reference is True when the SDK's shared reference values stood " "in, and reason says why — empty otherwise. Warn when it is True: " "the reference intrinsics are approximate, since lens placement " - "varies per assembly.") + "varies per assembly.\n\n" + "calibrated_size is the (width, height) the intrinsics belong to: " + "the size the firmware recorded, or -- for a record written without " + "one -- infer_fisheye_cal_size()'s answer, with size_inferred True " + "and a warning logged. A record whose size cannot be inferred is " + "treated as unusable and the reference (640x480) stands in.") .def("write_fisheye", [](Calibration& self, const protocol::CameraFisheyeCal& cal, unsigned timeout_ms) { @@ -119,7 +209,53 @@ void bind_calibration(py::module_& m) { }, py::arg("cal"), py::arg("timeout_ms") = 500, "Persist fisheye parameters to MCU flash (survives power cycles). " - "NaN/Inf values are rejected by the firmware.") + "NaN/Inf values are rejected by the firmware.\n\n" + "Writes the params only: on firmware that records the calibration " + "resolution (leader 1.2.8 / follower 1.2.18+) this marks it unknown. " + "Prefer write_fisheye_sized().") + .def("supports_fisheye_size", + [](Calibration& self, unsigned timeout_ms) { + py::gil_scoped_release nogil; + return self.supports_fisheye_size(std::chrono::milliseconds(timeout_ms)); + }, + py::arg("timeout_ms") = 200, + "True when the firmware records the fisheye calibration resolution " + "(command set V2.10: leader 1.2.8 / follower 1.2.18 or later).\n\n" + "Probes with the sized read: older firmware rejects it as " + "InvalidParam. The answer is cached on this Calibration; a transport " + "failure raises and is not cached.") + .def("read_fisheye_record", + [](Calibration& self, unsigned timeout_ms) -> py::object { + std::optional v; + { + py::gil_scoped_release nogil; + v = self.read_fisheye_record(std::chrono::milliseconds(timeout_ms)); + } + if (!v) return py::none(); + return py::cast(*v); + }, + py::arg("timeout_ms") = 200, + "Read the fisheye params together with the resolution they belong to, " + "as a FisheyeCalRecord. On firmware that cannot record a size the " + "params come back with width/height 0/0 (unknown). Returns None when " + "never calibrated (ErrorCode.CalNotSet).") + .def("write_fisheye_sized", + [](Calibration& self, const protocol::CameraFisheyeCal& cal, + int width, int height, unsigned timeout_ms) { + py::gil_scoped_release nogil; + self.write_fisheye_sized(cal, width, height, + std::chrono::milliseconds(timeout_ms)); + }, + py::arg("cal"), py::arg("width"), py::arg("height"), + py::arg("timeout_ms") = 500, + "Persist fisheye params together with the capture resolution they " + "were measured at.\n\n" + "Raises RuntimeError before sending anything unless " + "fisheye_cal_size_plausible(cal, width, height). Raises " + "ProtocolError when the firmware rejects the write. Firmware that " + "cannot record a size (older than leader 1.2.8 / follower 1.2.18) " + "accepts only a 640x480 calibration, through the legacy write; any " + "other resolution raises RuntimeError asking for an upgrade.") .def("read_encoder_max_rad", [](Calibration& self, unsigned timeout_ms) -> py::object { std::optional v; diff --git a/python/bindings/bind_camera.cpp b/python/bindings/bind_camera.cpp index 90ae310..a9607ba 100644 --- a/python/bindings/bind_camera.cpp +++ b/python/bindings/bind_camera.cpp @@ -22,6 +22,27 @@ void bind_camera(py::module_& m) { "FISHEYE_FALLBACK_CAL is the reference to fall back to, with a " "warning, when it returns False."); + m.def("fisheye_cal_size_plausible", &fisheye_cal_size_plausible, + py::arg("calibration"), py::arg("width"), py::arg("height"), + "True when the calibration is plausible at width x height -- the rule " + "the firmware applies to a sized write: every value finite, fx, fy > 0, " + "1 <= width, height <= 4096, and the principal point strictly inside " + "the frame (0 < cx < width, 0 < cy < height)."); + m.def("infer_fisheye_cal_size", + [](const protocol::CameraFisheyeCal& cal) -> py::object { + const auto s = infer_fisheye_cal_size(cal); + if (!s) return py::none(); + return py::make_tuple(s->width, s->height); + }, + py::arg("calibration"), + "Best-effort (width, height) for a record whose size is unknown, or " + "None.\n\n" + "The rule (shared verbatim with the PC calibration tools): the " + "candidates are exactly 640x480 and 1920x1080; a candidate W x H " + "matches when is_usable_fisheye_cal(calibration) and " + "|cx - W/2| <= 0.10*W and |cy - H/2| <= 0.10*H. The size is returned " + "only when exactly one candidate matches."); + // ---- FisheyeUndistorter (V2.0+ wrist fisheye intrinsics) ------------- // Usable standalone on frames this SDK never captured — the common case, // since the wrist UVC device is normally owned by an external service. @@ -36,25 +57,38 @@ void bind_camera(py::module_& m) { "remap tables are built once in the constructor, so build one and reuse it;\n" "rebuilding per frame would dominate the cost.") .def(py::init([](const protocol::CameraFisheyeCal& cal, - int width, int height, float balance) { + int width, int height, float balance, + std::optional> calibrated_size) { + const cv::Size frame(width, height); + if (!calibrated_size) { + return std::make_shared(cal, frame, balance); + } return std::make_shared( - cal, cv::Size(width, height), balance); + cal, cv::Size(calibrated_size->first, calibrated_size->second), + frame, balance); }), py::arg("calibration"), - // Defaults are the only calibrated resolution; anything else - // raises, because the firmware record carries no image size. + // Defaults are the legacy calibrated resolution; anything else + // raises unless calibrated_size says the params belong to it. py::arg("width") = FISHEYE_CALIB_WIDTH, py::arg("height") = FISHEYE_CALIB_HEIGHT, // 0 = calibrated focal length (natural view, matches the PC tool); // 1 = 0.70x for the widest field of view. Clamped to [0,1]. py::arg("balance") = 0.0f, + py::kw_only(), + py::arg("calibrated_size") = py::none(), "Build the remap tables for one calibration.\n\n" - "width/height must be the calibrated 640x480 -- the firmware record\n" - "carries no image size, so any other size raises RuntimeError rather\n" - "than guessing a rescale. balance picks the output focal length: 0\n" - "keeps the calibrated one, 1 shortens it to 0.70x for the widest field\n" - "of view at the cost of more black border. It is clamped to [0, 1]\n" - "rather than rejected.") + "width/height are the frame size. calibrated_size=(w, h) is the\n" + "resolution the intrinsics were measured at -- take it from\n" + "ResolvedFisheyeCal.calibrated_size or a FisheyeCalRecord -- and the\n" + "frame size must equal it: intrinsics are never rescaled to another\n" + "resolution or aspect ratio (640x480 and 1920x1080 are different\n" + "sensor crops), so a mismatch raises RuntimeError. Omitted, the\n" + "calibration is taken to be 640x480, as before the firmware recorded\n" + "a size. balance picks the output focal length: 0 keeps the\n" + "calibrated one, 1 shortens it to 0.70x for the widest field of view\n" + "at the cost of more black border. It is clamped to [0, 1] rather\n" + "than rejected.") .def("apply", [](const FisheyeUndistorter& self, const py::array& img) { cv::Mat src = numpy_to_mat_bgr(img); cv::Mat dst; diff --git a/python/bindings/bind_gripper.cpp b/python/bindings/bind_gripper.cpp index 97dd73c..daf0197 100644 --- a/python/bindings/bind_gripper.cpp +++ b/python/bindings/bind_gripper.cpp @@ -243,7 +243,7 @@ void bind_gripper(py::module_& m) { // Wrist fisheye undistortion (needs open_cameras=True and a V2.0+ // firmware that holds a calibration). Degrades to raw frames with // a warning when it does not; raises if the camera is not at the - // calibrated 640x480. + // calibration's own resolution (never rescaled). py::arg("undistort_wrist") = false, py::arg("fisheye_balance") = 0.0f, // Channel order of the wrist frames. RGB by default, unlike the diff --git a/python/examples/_rerun.py b/python/examples/_rerun.py index b3aedf2..73a755e 100644 --- a/python/examples/_rerun.py +++ b/python/examples/_rerun.py @@ -180,16 +180,31 @@ def open_wrist(g, role, side: str, args): f"{side}: no {role} XC wrist camera under /dev/v4l/by-id — skipping it" ) return None - cam = Camera( - cams[0]["path"], width=640, height=480, fps=30.0, color_mode=ColorMode.RGB - ) + # Rectifying needs the camera at the calibration's own resolution (the + # intrinsics are never rescaled), so resolve first and open at that size. + size = (640, 480) + resolved = None if args.undistort: - cal, is_reference, reason = g.calibration.resolve_fisheye() - if is_reference: + resolved = g.calibration.resolve_fisheye() + size = resolved.calibrated_size + if resolved.is_reference: log.warning( - f"{side}: wrist undistortion uses the SDK reference intrinsics ({reason})" + f"{side}: wrist undistortion uses the SDK reference intrinsics " + f"({resolved.reason})" + ) + cam = Camera( + cams[0]["path"], + width=size[0], + height=size[1], + fps=30.0, + color_mode=ColorMode.RGB, + ) + if resolved is not None: + cam.set_undistorter( + FisheyeUndistorter( + resolved.calibration, *size, calibrated_size=resolved.calibrated_size ) - cam.set_undistorter(FisheyeUndistorter(cal)) + ) print(f"[wrist] {side}: {cams[0]['serial']}") return cam diff --git a/python/examples/fisheye_cal.py b/python/examples/fisheye_cal.py index 7ebe474..1cd6ef8 100644 --- a/python/examples/fisheye_cal.py +++ b/python/examples/fisheye_cal.py @@ -7,7 +7,9 @@ Two independent records live behind these commands: fisheye Cmd::CameraFisheyeCal (0x2B) — fx, fy, cx, cy, k1..k4 for the - middle wrist camera. Available on BOTH leader and follower. + middle wrist camera, plus (firmware V2.10: leader >= 1.2.8 / + follower >= 1.2.18) the capture resolution they were measured + at. Available on BOTH leader and follower. encoder-max Cmd::EncoderMaxCal (0x2C) — the encoder shaft angle (rad) at which the gripper is fully open, measured from the encoder zero (fully closed). LEADER ONLY. @@ -17,6 +19,13 @@ record that was never written reads back as `None` rather than zeros, so you can tell "never calibrated" from "calibrated to exactly 0". +The fisheye params hold only at the resolution they were calibrated at: +640x480 (4:3) and 1920x1080 (16:9) are different sensor crops, so they cannot +be rescaled between the two. set-fisheye therefore takes --width/--height and +stores them with the params. Older firmware has nowhere to put the size and +accepts only a 640x480 calibration; `show` then reports the size as inferred +from the principal point. + The encoder-max value is what LeaderGripper(normalize_position=True) uses to turn raw encoder radians into a 0..1 opening — see `leader_normalized_position.py`. @@ -26,13 +35,14 @@ python python/examples/fisheye_cal.py show python python/examples/fisheye_cal.py show right - # Write fisheye intrinsics + distortion - python python/examples/fisheye_cal.py set-fisheye \\ - --fx 320.5 --fy 321.0 --cx 319.5 --cy 240.2 \\ - --k1 -0.031 --k2 0.0072 --k3 -0.0013 --k4 0.0002 + # Write fisheye intrinsics + distortion, and the resolution they belong to + python python/examples/fisheye_cal.py set-fisheye --width 1920 --height 1080 \\ + --fx 477.2 --fy 476.9 --cx 968.3 --cy 563.1 \\ + --k1 -0.021 --k2 0.0061 --k3 -0.0042 --k4 0.0011 # Load them from an OpenCV-style .npz holding K (3x3) and D (4,) - python python/examples/fisheye_cal.py set-fisheye --from-npz cam_left.npz + python python/examples/fisheye_cal.py set-fisheye --from-npz cam_left.npz \\ + --width 640 --height 480 # Measure the full-open angle interactively and store it python python/examples/fisheye_cal.py measure-encoder-max @@ -59,6 +69,7 @@ FollowerGripper, LeaderGripper, ProtocolError, + infer_fisheye_cal_size, ) _TTY = sys.stdout.isatty() @@ -96,6 +107,32 @@ def open_gripper(args): # ---- show ------------------------------------------------------------------- +def _print_size(record, firmware_records_size: bool) -> None: + """Calibration resolution: recorded by the firmware, or inferred.""" + if record.size_known(): + print(f" size={record.width}x{record.height} (recorded by the firmware)") + return + why = ( + "written without one" + if firmware_records_size + else "this firmware cannot record it — leader 1.2.8 / follower 1.2.18 can" + ) + guess = infer_fisheye_cal_size(record.calibration) + if guess is None: + print( + " size=" + + _yellow("unknown") + + f" ({why}; the principal point fits neither 640x480 nor " + "1920x1080 — recalibrate)" + ) + else: + print( + f" size={guess[0]}x{guess[1]} " + + _yellow("(inferred from the principal point") + + f"; {why})" + ) + + def cmd_show(args) -> int: with open_gripper(args) as g: cal = g.calibration @@ -108,18 +145,20 @@ def cmd_show(args) -> int: print(_bold("\nFisheye camera calibration (Cmd 0x2B)")) try: - fisheye = cal.read_fisheye() + record = cal.read_fisheye_record() except ProtocolError as e: # InvalidCmd here = firmware predates V2.0 (0x2B isn't in its # command table at all). print(f" {_yellow('unavailable')} — {e}") - fisheye = None + record = None else: - if fisheye is None: + if record is None: print( " " + _yellow("not calibrated") + " — firmware returned CalNotSet" ) - if fisheye is not None: + if record is not None: + fisheye = record.calibration + _print_size(record, cal.supports_fisheye_size()) print(f" fx={fisheye.fx:.4f} fy={fisheye.fy:.4f}") print(f" cx={fisheye.cx:.4f} cy={fisheye.cy:.4f}") print( @@ -200,12 +239,25 @@ def cmd_set_fisheye(args) -> int: k4=args.k4, ) - print(f"Writing {cal}") + print(f"Writing {cal} at {args.width}x{args.height}") with open_gripper(args) as g: - g.calibration.write_fisheye(cal) - readback = g.calibration.read_fisheye() + # Refuses before sending when the principal point does not fit the + # size, and on firmware that cannot record a size refuses anything + # but 640x480 rather than store params that would be taken for VGA. + try: + g.calibration.write_fisheye_sized(cal, args.width, args.height) + except RuntimeError as e: # host-side refusal; a NACK is ProtocolError + raise SystemExit(f"error: {e}") from None + readback = g.calibration.read_fisheye_record() print(_green("written to MCU flash. Read back:")) print(f" {readback}") + if readback is not None and not readback.size_known(): + print( + " " + + _yellow("note:") + + " this firmware cannot record the size; it was stored as a " + "640x480 calibration through the legacy write" + ) return 0 @@ -272,6 +324,18 @@ def main() -> int: metavar="FILE", help="load K (3x3) and D (4,) from an OpenCV-style .npz", ) + sf.add_argument( + "--width", + type=int, + required=True, + help="capture width (px) the parameters were calibrated at", + ) + sf.add_argument( + "--height", + type=int, + required=True, + help="capture height (px) the parameters were calibrated at", + ) for name in ("fx", "fy", "cx", "cy"): sf.add_argument(f"--{name}", type=float) for name in ("k1", "k2", "k3", "k4"): diff --git a/python/examples/read_intrinsics.py b/python/examples/read_intrinsics.py index 725a444..3baea50 100644 --- a/python/examples/read_intrinsics.py +++ b/python/examples/read_intrinsics.py @@ -41,11 +41,14 @@ import _target from xense.taccap import FollowerGripper, LeaderGripper, log -# The calibration record **does not store the image size**. The SDK always uses these -# intrinsics at the 640x480 they were calibrated at; scaling them to another resolution -# is a guess — so the assumption is written explicitly into the output here, rather -# than pretending to know. -ASSUMED_IMAGE_SIZE = [640, 480] +# The intrinsics hold only at the resolution they were calibrated at — 640x480 and +# 1920x1080 are different sensor crops, so they cannot be rescaled between the two. +# `image_size` says which one, and `image_size_source` how the SDK knows: +# "recorded" the firmware stored it with the params (leader 1.2.8 / follower 1.2.18+) +# "inferred" the record carries no size; inferred from the principal point +# "reference" the SDK reference values, which are a 640x480 calibration +# `assumed_image_size` is kept, with the same value, for consumers written before +# the size was recorded. def _enum_name(v) -> str: @@ -83,7 +86,15 @@ def main() -> int: g = cls(mcu_device=ep.mcu_device) try: - cal, is_reference, reason = g.calibration.resolve_fisheye() + resolved = g.calibration.resolve_fisheye() + cal, is_reference, reason = resolved + image_size = list(resolved.calibrated_size) + if is_reference: + size_source = "reference" + elif resolved.size_inferred: + size_source = "inferred" + else: + size_source = "recorded" if is_reference: log.warning( @@ -106,7 +117,9 @@ def main() -> int: "source": "reference" if is_reference else "device", "reason": reason, "model": "fisheye_equidistant", - "assumed_image_size": ASSUMED_IMAGE_SIZE, + "image_size": image_size, + "image_size_source": size_source, + "assumed_image_size": image_size, "fx": cal.fx, "fy": cal.fy, "cx": cal.cx, diff --git a/python/examples/wrist_camera.py b/python/examples/wrist_camera.py index 82337a1..0186d9b 100755 --- a/python/examples/wrist_camera.py +++ b/python/examples/wrist_camera.py @@ -58,10 +58,14 @@ intrinsics standing in and a warning. Off-by-default is about the switch, not about whether a switched-on path might silently skip the remap. -Note the undistorter is built for the calibrated 640x480 only: the firmware -record carries no image size, so rescaling the intrinsics would be a guess and -is refused rather than silently wrong. Ask for another size and undistortion -is unavailable at that size (the script says so and stays on raw frames). +Note the undistorter is built at the calibration's own resolution only: +640x480 and 1920x1080 are different sensor crops, so rescaling the intrinsics +would be silently wrong and is refused. The resolution comes from the firmware +record (leader 1.2.8 / follower 1.2.18+ store it), is inferred from the +principal point for an older record, or is 640x480 for the reference values. +Without --width/--height the camera is opened at that resolution; ask for +another size and undistortion is unavailable at that size (the script says so +and stays on raw frames). Usage: # what is plugged in, and which of it this script can open @@ -109,11 +113,13 @@ ProtocolError, Role, Side, + infer_fisheye_cal_size, log, scan_grippers, ) -# The one resolution the firmware calibration record is defined at. +# The resolution of the SDK reference calibration, and the capture size used +# when nothing says otherwise. CALIB_W, CALIB_H = 640, 480 MODE_RAW = "raw" @@ -301,7 +307,7 @@ def cal_from_npz(path: str) -> CameraFisheyeCal: ) -def cal_from_gripper(cam: dict) -> tuple[CameraFisheyeCal, str]: +def cal_from_gripper(cam: dict) -> tuple[CameraFisheyeCal, str, tuple[int, int]]: """Read the intrinsics off the MCU of the gripper on the camera's side. The wrist camera's own serial already says which side (and which role) it @@ -341,20 +347,46 @@ def cal_from_gripper(cam: dict) -> tuple[CameraFisheyeCal, str]: # resolve_fisheye() — not read_fisheye() — because an uncalibrated unit # answers with an all-zero record rather than a NACK, and remapping with # fx = fy = 0 yields a uniformly black frame with nothing raised. - cal, is_reference, reason = g.calibration.resolve_fisheye() - if is_reference: - return cal, f"SDK reference intrinsics ({reason})" - return cal, f"read from {eps.firmware_sn or eps.mcu_device}" + resolved = g.calibration.resolve_fisheye() + size = resolved.calibrated_size + if resolved.is_reference: + return ( + resolved.calibration, + f"SDK reference intrinsics ({resolved.reason})", + size, + ) + how = "size inferred" if resolved.size_inferred else "size recorded" + return ( + resolved.calibration, + f"read from {eps.firmware_sn or eps.mcu_device} ({how})", + size, + ) -def resolve_calibration(args, cam: dict) -> tuple[CameraFisheyeCal, str, bool]: - """Returns (cal, provenance, is_reference).""" +def resolve_calibration( + args, cam: dict +) -> tuple[CameraFisheyeCal, str, bool, tuple[int, int]]: + """Returns (cal, provenance, is_reference, calibrated (width, height)).""" + reference_size = (CALIB_W, CALIB_H) if args.from_npz: - return cal_from_npz(args.from_npz), f"loaded from {args.from_npz}", False + cal = cal_from_npz(args.from_npz) + # An .npz carries no image size either; apply the SDK's inference rule. + size = infer_fisheye_cal_size(cal) + if size is None: + raise SystemExit( + f"{args.from_npz}: cannot tell which resolution these intrinsics " + "belong to (the principal point fits neither 640x480 nor 1920x1080)" + ) + return cal, f"loaded from {args.from_npz} (size inferred)", False, size if args.no_mcu: - return (FISHEYE_FALLBACK_CAL, "SDK reference intrinsics (--no-mcu)", True) + return ( + FISHEYE_FALLBACK_CAL, + "SDK reference intrinsics (--no-mcu)", + True, + reference_size, + ) try: - cal, provenance = cal_from_gripper(cam) + cal, provenance, size = cal_from_gripper(cam) except (RuntimeError, ProtocolError, OSError) as e: # The wrist camera is usable without the MCU link, so a failure here # degrades to the reference calibration rather than aborting — same @@ -363,8 +395,13 @@ def resolve_calibration(args, cam: dict) -> tuple[CameraFisheyeCal, str, bool]: f"could not read the calibration from the gripper ({e}); " "falling back to the SDK reference intrinsics" ) - return FISHEYE_FALLBACK_CAL, f"SDK reference intrinsics ({e})", True - return cal, provenance, provenance.startswith("SDK reference") + return ( + FISHEYE_FALLBACK_CAL, + f"SDK reference intrinsics ({e})", + True, + reference_size, + ) + return cal, provenance, provenance.startswith("SDK reference"), size # ---- rendering -------------------------------------------------------------- @@ -472,8 +509,16 @@ def build_parser() -> argparse.ArgumentParser: ) cam = p.add_argument_group("capture") - cam.add_argument("--width", type=int, default=CALIB_W) - cam.add_argument("--height", type=int, default=CALIB_H) + cam.add_argument( + "--width", + type=int, + help="Capture width (default: the calibration's resolution, else 640).", + ) + cam.add_argument( + "--height", + type=int, + help="Capture height (default: the calibration's resolution, else 480).", + ) cam.add_argument("--fps", type=float, default=30.0) cam.add_argument( "--no-mjpg", action="store_true", help="Request YUYV instead of MJPEG." @@ -529,33 +574,39 @@ def main(argv=None) -> int: device = cam_info["path"] color_mode = ColorMode.RGB if args.color_mode == "rgb" else ColorMode.BGR - # The remap tables are defined at the calibrated resolution only. Say so - # once, up front, instead of letting the constructor throw mid-stream. - calibrated_size = (args.width, args.height) == (CALIB_W, CALIB_H) - if not calibrated_size and (args.undistort or args.compare): - print( - _yellow( - f"undistortion needs {CALIB_W}x{CALIB_H} (the calibrated size) — " - f"you asked for {args.width}x{args.height}, so frames stay raw.\n" - "The firmware record stores no image size; rescaling the " - "intrinsics would be a guess." - ) - ) - # Resolve the intrinsics up front whenever rectification is reachable — that # includes staying raw in the viewer, where `u` can switch to rectified at # any moment and an MCU round-trip mid-loop would stall the capture. # Headless AND raw is the one case that can never rectify, so it skips the # gripper entirely rather than opening a serial link for nothing. wants_undistort = args.undistort or args.compare - reachable = calibrated_size and (wants_undistort or not args.no_display) + reachable = wants_undistort or not args.no_display undist = None - cal = provenance = None + cal = provenance = cal_size = None is_reference = False if reachable: - cal, provenance, is_reference = resolve_calibration(args, cam_info) - undist = FisheyeUndistorter(cal, CALIB_W, CALIB_H, args.balance) + cal, provenance, is_reference, cal_size = resolve_calibration(args, cam_info) + default_size = cal_size or (CALIB_W, CALIB_H) + width = args.width or default_size[0] + height = args.height or default_size[1] + + # The remap tables are defined at the calibration's own resolution only. + # Say so once, up front, instead of letting the constructor throw. + if cal_size is not None: + if (width, height) == tuple(cal_size): + undist = FisheyeUndistorter( + cal, width, height, args.balance, calibrated_size=cal_size + ) + elif wants_undistort: + print( + _yellow( + f"undistortion needs {cal_size[0]}x{cal_size[1]} (the " + f"calibrated size) — you asked for {width}x{height}, so " + "frames stay raw.\nIntrinsics do not carry over to another " + "resolution or aspect ratio; recalibrate at that size." + ) + ) mode = MODE_RAW if undist is not None: @@ -567,8 +618,8 @@ def main(argv=None) -> int: cam = Camera( device=device, - width=args.width, - height=args.height, + width=width, + height=height, fps=args.fps, use_mjpg=not args.no_mjpg, color_mode=color_mode, @@ -580,7 +631,7 @@ def main(argv=None) -> int: ) print(f" device : {device}") print( - f" format : {args.width}x{args.height} @ {args.fps:g} " + f" format : {width}x{height} @ {args.fps:g} " f"{'YUYV' if args.no_mjpg else 'MJPG'}, {args.color_mode.upper()}" ) if undist is not None: @@ -603,7 +654,7 @@ def main(argv=None) -> int: "point especially),\n so do not measure in pixels off these " "frames. Calibrate with:\n" " python python/examples/fisheye_cal.py set-fisheye " - "--from-npz cam.npz" + "--from-npz cam.npz --width W --height H" ) ) print(f"\n mode : {mode}\n") @@ -723,7 +774,9 @@ def build_canvas(frame) -> np.ndarray: balance = min(1.0, max(0.0, undist.balance + step)) # The tables are built once per undistorter, so a new balance # means a new one — cheap enough at human key-press rates. - undist = FisheyeUndistorter(cal, CALIB_W, CALIB_H, balance) + undist = FisheyeUndistorter( + cal, width, height, balance, calibrated_size=cal_size + ) apply_mode(mode) log.info( f"balance: {undist.balance:.2f} " diff --git a/python/tests/test_fisheye_cal_size.py b/python/tests/test_fisheye_cal_size.py new file mode 100644 index 0000000..5ac1a46 --- /dev/null +++ b/python/tests/test_fisheye_cal_size.py @@ -0,0 +1,210 @@ +# Copyright (c) 2026 XenseRobotics Co., Ltd. — Apache-2.0 +"""The fisheye calibration resolution, as the Python surface exposes it. + +640x480 and 1920x1080 are different sensor crops, so the 8 fisheye params only +hold at the resolution they were measured at. Firmware V2.10 (leader 1.2.8 / +follower 1.2.18) records that resolution; older firmware does not, and the SDK +infers it with a rule shared verbatim with the PC calibration tools. These +tests pin the names and shapes those tools code against: tuples for sizes, +None for "no answer", and resolve_fisheye() still unpacking as the 3-tuple it +used to be. + +Run with: pytest python/tests +""" + +from __future__ import annotations + +import os +import pty +import select +import struct +import threading +from contextlib import contextmanager + +import pytest +import xense.taccap as t + +VGA = t.CameraFisheyeCal( + 213.0303, 212.7928, 321.4, 239.95, -0.0172, 0.0091, -0.0146, 0.0051 +) +HD = t.CameraFisheyeCal(477.2, 476.9, 968.3, 563.1, -0.021, 0.0061, -0.0042, 0.0011) + +OP_READ, OP_WRITE, OP_READ_SIZED, OP_WRITE_SIZED = 0x00, 0x01, 0x02, 0x03 +ERR_INVALID_PARAM = int(t.ErrorCode.InvalidParam.value) +ERR_CAL_NOT_SET = int(t.ErrorCode.CalNotSet.value) + + +def _params(cal) -> bytes: + return struct.pack( + "<8f", cal.fx, cal.fy, cal.cx, cal.cy, cal.k1, cal.k2, cal.k3, cal.k4 + ) + + +# ---- Hardware-free ----------------------------------------------------------- + + +def test_infer_recognises_the_vga_reference(): + assert t.infer_fisheye_cal_size(t.FISHEYE_FALLBACK_CAL) == (640, 480) + + +def test_infer_recognises_1080p(): + assert t.infer_fisheye_cal_size(HD) == (1920, 1080) + + +def test_infer_returns_none_when_nothing_matches(): + assert t.infer_fisheye_cal_size(t.CameraFisheyeCal(477, 477, 600, 400)) is None + assert t.infer_fisheye_cal_size(t.CameraFisheyeCal()) is None + + +def test_plausibility_is_the_firmware_rule(): + assert t.fisheye_cal_size_plausible(HD, 1920, 1080) + assert not t.fisheye_cal_size_plausible(HD, 640, 480) + assert not t.fisheye_cal_size_plausible(VGA, 640, 4097) + + +def test_record_defaults_to_an_unknown_size(): + r = t.FisheyeCalRecord() + assert (r.width, r.height) == (0, 0) + assert not r.size_known() + r = t.FisheyeCalRecord(HD, 1920, 1080) + assert r.size_known() + assert r.calibration.cx == pytest.approx(968.3) + + +def test_undistorter_calibrated_size_keyword(): + u = t.FisheyeUndistorter(HD, 1920, 1080, calibrated_size=(1920, 1080)) + assert (u.width, u.height) == (1920, 1080) + with pytest.raises(RuntimeError, match="must not be rescaled"): + t.FisheyeUndistorter(HD, 640, 480, calibrated_size=(1920, 1080)) + # Omitted, the params are taken to be 640x480, as before. + assert t.FisheyeUndistorter(VGA).width == 640 + with pytest.raises(RuntimeError): + t.FisheyeUndistorter(HD, 1920, 1080) + + +# ---- Against a fake leader over a pty ---------------------------------------- + + +class FakeFisheyeStore: + """The firmware's 0x2B handler, V2.10 or (sized=False) older.""" + + def __init__(self, sized: bool, cal=None, width: int = 0, height: int = 0): + self.sized = sized + self.params = _params(cal) if cal is not None else None + self.size = (width, height) + self.ops: list[int] = [] + + def handle(self, payload: bytes) -> bytes: + op = payload[0] + self.ops.append(op) + if op in (OP_READ_SIZED, OP_WRITE_SIZED) and not self.sized: + return bytes([ERR_INVALID_PARAM]) + if op in (OP_READ, OP_READ_SIZED): + if self.params is None: + return bytes([ERR_CAL_NOT_SET]) + tail = struct.pack(" str: """GET_MOTOR_STATUS_EXT -> GetMotorStatusExt (then apply aliases).""" name = "".join(part.title() for part in macro_tail.split("_") if part) @@ -285,6 +309,63 @@ def fw_expr(name: str) -> str: return errors +def check_constants(firmware: Path, cc: str, cxx: str) -> list[str]: + """Compare every CONSTANT_MAP row's value, as the compiler sees it.""" + c_src = "\n".join( + ["#include ", '#include "protocol_data.h"', "int main(void) {"] + + [ + f' printf("c{i}=%lu\\n", (unsigned long)({fw}));' + for i, (fw, _) in enumerate(CONSTANT_MAP) + ] + + [" return 0;", "}", ""] + ) + cxx_src = "\n".join( + [ + "#include ", + "#include ", + "namespace tp = xense::taccap::protocol;", + "int main() {", + ] + + [ + f' std::printf("c{i}=%lu\\n", (unsigned long)({sdk}));' + for i, (_, sdk) in enumerate(CONSTANT_MAP) + ] + + [" return 0;", "}", ""] + ) + with tempfile.TemporaryDirectory() as tmpdir: + tmp = Path(tmpdir) + fw_vals, err = _emit_sizes( + tmp, + "firmware", + c_src, + cc, + [ + "-std=c11", + f"-I{firmware / 'App' / 'protocol'}", + f"-I{firmware / 'App' / 'drivers'}", + ], + ) + if err: + return [err.replace("STRUCT_MAP", "CONSTANT_MAP")] + sdk_vals, err = _emit_sizes( + tmp, + "sdk", + cxx_src, + cxx, + ["-std=c++17", f"-I{REPO / 'cpp' / 'include'}"], + ) + if err: + return [err.replace("STRUCT_MAP", "CONSTANT_MAP")] + errors = [] + for i, (label, sdk) in enumerate(CONSTANT_MAP): + fw, have = fw_vals[f"c{i}"], sdk_vals[f"c{i}"] + if fw != have: + errors.append( + f"constant mismatch: firmware {label} = {fw}, SDK {sdk} = {have}" + ) + return errors + + def indent(text: str, pad: str = " ") -> str: return "\n".join(pad + line for line in text.splitlines()) @@ -383,6 +464,9 @@ def main() -> int: ) errors += check_sizes(fw_dir, args.cc, args.cxx) + print(f"constants: {len(CONSTANT_MAP)} wire constants compared") + errors += check_constants(fw_dir, args.cc, args.cxx) + print() if errors: print(f"DRIFT: {len(errors)} problem(s)\n")