diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d52fa35..0416fba 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -48,6 +48,53 @@ jobs: with: draft: true + # Every app release carries the current library package, even when the library + # did not change. The library has its own version (tags `alientek-el15-v*`, which + # do not match `v*` and so do not trigger this workflow) and is published to + # crates.io by hand. + package-library: + name: package alientek-el15 + needs: [create-release] + if: ${{ !cancelled() && needs.create-release.result != 'failure' }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - uses: dtolnay/rust-toolchain@stable + + - uses: Swatinem/rust-cache@v2 + + - name: Package library crate + id: library + shell: bash + run: | + set -euo pipefail + cargo package --locked -p alientek-el15 --no-verify + crate_file=$(find target/package -maxdepth 1 -name 'alientek-el15-*.crate' -print -quit) + crate_name=$(basename "$crate_file") + mkdir -p dist + cp "$crate_file" "dist/$crate_name" + shasum -a 256 "dist/$crate_name" | awk '{print $1}' > "dist/$crate_name.sha256" + echo "crate_name=$crate_name" >> "$GITHUB_OUTPUT" + + - name: Release library package + if: startsWith(github.ref, 'refs/tags/') + uses: softprops/action-gh-release@v3 + with: + files: | + dist/${{ steps.library.outputs.crate_name }} + dist/${{ steps.library.outputs.crate_name }}.sha256 + + - name: Upload workflow_dispatch library package + if: github.event_name == 'workflow_dispatch' + uses: actions/upload-artifact@v7 + with: + name: alientek-el15 + path: | + dist/${{ steps.library.outputs.crate_name }} + dist/${{ steps.library.outputs.crate_name }}.sha256 + retention-days: 7 + build: name: build (${{ matrix.platform.label }}-${{ matrix.platform.arch }}) needs: [create-release] diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 5e88aaa..1048e2b 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -53,4 +53,18 @@ jobs: run: cargo test --workspace - name: Clippy - run: cargo clippy --workspace -- -D warnings + run: cargo clippy --workspace --all-targets -- -D warnings + + - name: Library without Bluetooth + run: | + cargo clippy -p alientek-el15 --all-targets --no-default-features -- -D warnings + cargo test -p alientek-el15 --no-default-features + + # The library is published on crates.io; check what docs.rs and crates.io would get. + - name: Library docs + run: cargo doc -p alientek-el15 --no-deps + env: + RUSTDOCFLAGS: -D warnings + + - name: Library package + run: cargo publish -p alientek-el15 --dry-run diff --git a/Cargo.lock b/Cargo.lock index 40fbf7c..e9ec565 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -46,6 +46,20 @@ dependencies = [ "memchr", ] +[[package]] +name = "alientek-el15" +version = "0.1.0" +dependencies = [ + "btleplug", + "futures", + "serde", + "thiserror 1.0.69", + "tokio", + "tokio-stream", + "tracing", + "uuid", +] + [[package]] name = "aligned" version = "0.4.3" @@ -1209,12 +1223,12 @@ checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" name = "el15-app" version = "0.1.4" dependencies = [ + "alientek-el15", "anyhow", "chrono", "clap", "confy", "csv", - "el15-bt", "el15-scpi", "embed-resource", "futures", @@ -1238,26 +1252,12 @@ dependencies = [ "winapi", ] -[[package]] -name = "el15-bt" -version = "0.1.4" -dependencies = [ - "btleplug", - "futures", - "serde", - "thiserror 1.0.69", - "tokio", - "tokio-stream", - "tracing", - "uuid", -] - [[package]] name = "el15-scpi" version = "0.1.4" dependencies = [ + "alientek-el15", "chrono", - "el15-bt", "futures", "thiserror 1.0.69", "tokio", diff --git a/Cargo.toml b/Cargo.toml index 3ac3124..c1bcf8c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] members = [ - "el15-bt", + "alientek-el15", "el15-scpi", "el15-app", "scripts/scpi-test", diff --git a/README.md b/README.md index fdb9132..4c06fb8 100644 --- a/README.md +++ b/README.md @@ -35,11 +35,27 @@ Supported features: GUI, CLI, BLE, USB DFU, SCPI | Crate | Type | Purpose | | ------------------- | ---- | ------------------------------------------------------------------------------------- | -| `el15-bt` | lib | BLE protocol implementation, ported from [DM40GUI](https://github.com/maj113/DM40GUI) | +| `alientek-el15` | lib | BLE protocol library, published on crates.io (see [its README](alientek-el15/README.md)) | | `el15-scpi` | lib | SCPI/LXI raw-socket server emulating a RIGOL DL3000 electronic load | | `el15-app` | bin | Single `el15` binary: iced GUI, headless CLI, USB DFU, and SCPI server | | `scripts/scpi-test` | bin | Smoke tester for the built-in SCPI server | +## Library + +The Bluetooth LE protocol is a separate crate, [`alientek-el15`](alientek-el15/README.md), +published on crates.io with its own version (tags `alientek-el15-v*`; the app keeps `v*`). +The app builds it from the local sources. The protocol was reverse-engineered from the +Bluetooth traffic of ALIENTEK's official Android app, ATK-xTOOL, and cross-checked against +the Python project [DM40GUI](https://github.com/maj113/DM40GUI). + +To use a local checkout of the library in another project, depend on it by path, or keep the +crates.io dependency and override it: + +```toml +[patch.crates-io] +alientek-el15 = { path = "../el15/alientek-el15" } +``` + ## Build from source ### Requirements diff --git a/alientek-el15/CHANGELOG.md b/alientek-el15/CHANGELOG.md new file mode 100644 index 0000000..bd46463 --- /dev/null +++ b/alientek-el15/CHANGELOG.md @@ -0,0 +1,60 @@ +# Changelog + +All notable changes to the `alientek-el15` crate. The companion app has its own release notes +on GitHub. + +## Unreleased + +## 0.1.0 + +First release under this name. Earlier versions lived in the app repository as `el15-bt` +(up to 0.1.4, following the app's version) and were not published on crates.io. + +- Command frames and the checksum: init, info, poll, load on/off, lock, set mode, set setpoint, + set and read the CAP discharge current. +- Parsers for the status notification, the firmware version and the CAP discharge current. +- Scanning, connecting, and a `Device` handle that sends commands, paced + `INTER_COMMAND_GAP` apart, and turns notifications into `DeviceEvent`s. + +Compared with `el15-bt` 0.1.4: + +- Renamed: the crate `el15-bt` is now `alientek-el15` (`use alientek_el15::...`); the tracing + target is `alientek_el15`. +- It requires only tokio's `rt`, `sync` and `time` features; applications bring their own + runtime (`Device::connect` spawns a task, so it must run inside one). +- Renamed: `EL15Status` is now `Status`, `EL15_SERVICE_UUID` is `SERVICE_UUID`, `HEADER` is + `STATUS_HEADER`. +- `Status::dcr_mohm` is documented as milliohms. Measured on a cell (173.6 mΩ from the + voltage drop between the two test currents, 173.15 reported); earlier notes said Ohms. +- `parse_status_packet` returns `Result` and rejects a wrong length, + header or **checksum**. Before, a corrupted packet came back with `crc_pass: false` but + `valid: true`, and `Device` emitted it as a measurement. `DeviceEvent::Status` now only + carries packets that passed; the rest still arrive as `RawNotification`. +- `parse_firmware_version` returns a `FirmwareVersion` (it displays as before, + `HW:2.0 SW:1.7`) instead of a `String`, and so does `DeviceEvent::FirmwareVersion`. + It and `parse_cap_current` now check the reply's checksum and exact length. +- `Status` keeps measurements only. Removed: `raw_hex`, `crc_pass`, `valid` (see + `RawNotification` and `ParseError`), `mode_name`, `setpoint_unit`, `setpoint_decimals` and + `setpoint_label` (use `Status::mode()`, `Mode::as_str()` / `Display` and + `Mode::setpoint_info()`). `warning` is an `Option` (`Reverse`, `Undervoltage`, + `Protection(code)`) instead of a `String`; `Display` gives the old `REV` / `UVP` / `PROT x`. +- `runtime_s` is read as an unsigned integer instead of a signed one cast to unsigned. +- Removed: `MODE_NAMES` (its type was not nameable; use `Mode::as_str`) and + `Device::watch_central_events` (it exposed btleplug's event type). +- `Error` is `#[non_exhaustive]` and keeps only the variants the crate returns: + `Bluetooth`, `NoAdapter`, `CharacteristicNotFound`. +- New exports: `STATUS_LEN`, `CAP_CURRENT_HEADER`, `FAN_SPEED_MAX`. +- Bluetooth LE is the default feature `ble`; without it the crate needs no Bluetooth stack or + async runtime and depends only on `thiserror`. `INTER_COMMAND_GAP` moved to `protocol` and + is available either way. +- `serde` is no longer a default feature. +- `Device::send` keeps `INTER_COMMAND_GAP` (120 ms) since the previous write from any task, + and writes never overlap. Before, only `send_sequence` paced, and `init_handshake` sent its + two frames back-to-back. Measured on the device: a 3-command burst without pacing lost the + mode switch 4 times out of 6; paced, 6 out of 6 took effect. +- `Device::connect` only uses characteristics of the EL15 service `FFF0`, preferring `FFF1`. + Before, it fell back to any writable or notifying characteristic of the peripheral. +- `build_set_setpoint_cmd` and `build_set_cap_current_cmd` return + `Result, InvalidValue>` and refuse NaN, infinity and negative values. The CAP + current above `CAP_CURRENT_MAX_A` (12 A) is refused instead of clamped; a setpoint above + `SETPOINT_MAX` (7500, CR's limit) is refused. Before, NaN reached the wire (`clamp` keeps it). diff --git a/alientek-el15/Cargo.toml b/alientek-el15/Cargo.toml new file mode 100644 index 0000000..6964382 --- /dev/null +++ b/alientek-el15/Cargo.toml @@ -0,0 +1,43 @@ +[package] +name = "alientek-el15" +# Released on its own (tags `alientek-el15-v*`), independent of the apps' version. +version = "0.1.0" +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +description = "Unofficial client for the ALIENTEK EL15 DC electronic load over Bluetooth LE: command frames, status parsing, scanning and a connection" +documentation = "https://docs.rs/alientek-el15" +readme = "README.md" +keywords = ["alientek", "el15", "electronic-load", "bluetooth", "ble"] +categories = ["hardware-support"] +include = ["src/**/*.rs", "examples/**/*.rs", "Cargo.toml", "README.md", "CHANGELOG.md", "LICENSE"] + +[features] +default = ["ble"] +# Bluetooth LE: scanning, connecting and `Device`. Without it the crate keeps the command +# frames, the checksum and the reply parsers, and needs no Bluetooth stack or async runtime. +ble = ["dep:btleplug", "dep:tokio", "dep:tokio-stream", "dep:futures", "dep:uuid", "dep:tracing"] +# Serialize/Deserialize for `Status`, `Mode`, `Warning` and `FirmwareVersion`. +serde = ["dep:serde"] + +[dependencies] +thiserror.workspace = true +serde = { workspace = true, optional = true } +btleplug = { workspace = true, optional = true } +# Only what the library uses; applications bring their own runtime. +tokio = { version = "1", features = ["rt", "sync", "time"], optional = true } +tokio-stream = { workspace = true, optional = true } +futures = { workspace = true, optional = true } +uuid = { workspace = true, optional = true } +tracing = { workspace = true, optional = true } + +[dev-dependencies] +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } + +[[example]] +name = "status" +required-features = ["ble"] + +[package.metadata.docs.rs] +all-features = true diff --git a/alientek-el15/LICENSE b/alientek-el15/LICENSE new file mode 100644 index 0000000..1490cff --- /dev/null +++ b/alientek-el15/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Roman Samarev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/alientek-el15/README.md b/alientek-el15/README.md new file mode 100644 index 0000000..b1e158c --- /dev/null +++ b/alientek-el15/README.md @@ -0,0 +1,90 @@ +# alientek-el15 + +Unofficial Rust client for the **ALIENTEK EL15** programmable DC electronic load over +Bluetooth LE. Not affiliated with or endorsed by ALIENTEK. + +- Command frames: init, poll, load on/off, panel lock, mode (CC, CV, CR, CP, CAP, DCR), + setpoint, and the CAP discharge current, each with its checksum. +- Parsers for the 28-byte status notification (voltage, current, power, temperature, + setpoint, capacity, energy, DCR result, fan, load and lock state, protection warnings), + the firmware version and the CAP discharge current. +- Scanning, connecting, and a `Device` handle that sends commands and turns notifications + into `DeviceEvent`s. + +Cargo feature `ble` (default) brings Bluetooth LE through `btleplug`. With +`default-features = false` the crate builds without a Bluetooth stack or async runtime and +keeps the command frames, the checksum and the reply parsers, for use over your own link. +Feature `serde` adds `Serialize`/`Deserialize` to the status and version types. + +The protocol was reverse-engineered from the Bluetooth traffic of ALIENTEK's official +Android app, ATK-xTOOL, and cross-checked against the Python project DM40GUI. Verified +against an EL15 with hardware 2.0 and firmware 1.7. The full description, with the evidence +for each field, is in +[docs/BT_PROTOCOL.md](https://github.com/rssdev10/el15/blob/main/docs/BT_PROTOCOL.md). + +## Example + +Print a few readings from the first EL15 in range (read only: the load stays as it is): + +```rust,no_run +use alientek_el15::{scan_devices, Device, DeviceEvent}; +use tokio_stream::StreamExt; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let info = scan_devices(None).await?.into_iter().next().ok_or("no EL15 found")?; + let (device, mut events) = Device::connect(&info).await?; + // Without the handshake the device reports zeros for temperature and setpoint. + device.init_handshake().await?; + + for _ in 0..5 { + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + device.poll().await?; + while let Some(event) = events.next().await { + if let DeviceEvent::Status(s) = event { + println!("{:.3} V {:.3} A {:.1} °C", s.voltage, s.current, s.temperature); + break; + } + } + } + + device.disconnect().await?; + Ok(()) +} +``` + +A complete version is in [examples/status.rs](examples/status.rs). + +The device silently drops commands written back-to-back. `Device::send` keeps +`INTER_COMMAND_GAP` (120 ms) since the previous write, from any task, so a shared `Device` +is safe to use; if you write frames over your own link (without the `ble` feature), keep the +same gap yourself. + +## Using local sources + +To try changes to this crate in another project before they are published, point the +dependency at a checkout: + +```toml +[dependencies] +alientek-el15 = { path = "../el15/alientek-el15" } +``` + +or keep the crates.io dependency and override it in the project's `Cargo.toml`: + +```toml +[patch.crates-io] +alientek-el15 = { path = "../el15/alientek-el15" } +``` + +## Safety + +The EL15 sinks up to 150 W from the source under test. A wrong mode or setpoint can +over-discharge a battery or overload a power supply. The device's own protections are the +last line of defence, not a substitute for correct settings. Only hardware 2.0 with firmware +1.7 has been tested; other firmware may differ. + +## Companion app + +The [repository](https://github.com/rssdev10/el15) also holds `el15`, a GUI, CLI and +SCPI server built on this crate, released as binaries. diff --git a/alientek-el15/examples/status.rs b/alientek-el15/examples/status.rs new file mode 100644 index 0000000..3eb7696 --- /dev/null +++ b/alientek-el15/examples/status.rs @@ -0,0 +1,60 @@ +//! Connects to the first EL15 in range and prints a few status readings. +//! +//! Read only: it never switches the load on, changes the mode or writes a setpoint. +//! +//! `cargo run -p alientek-el15 --example status` + +use std::time::Duration; + +use alientek_el15::{scan_devices, Device, DeviceEvent, INTER_COMMAND_GAP}; +use tokio_stream::StreamExt; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let info = scan_devices(None) + .await? + .into_iter() + .next() + .ok_or("no EL15 found")?; + println!("connecting to {}", info.display_label()); + + let (device, mut events) = Device::connect(&info).await?; + // Without the handshake the device reports zeros for temperature and setpoint. + device.init_handshake().await?; + + let mut readings = 0; + while readings < 5 { + tokio::time::sleep(INTER_COMMAND_GAP.max(Duration::from_millis(500))).await; + device.poll().await?; + + // Drain what arrived; stop waiting after a second without a status reply. + let deadline = tokio::time::sleep(Duration::from_secs(1)); + tokio::pin!(deadline); + loop { + tokio::select! { + event = events.next() => match event { + Some(DeviceEvent::FirmwareVersion(v)) => println!("firmware {v}"), + Some(DeviceEvent::Status(s)) => { + println!( + "{:<4} {:7.3} V {:7.3} A {:7.2} W {:5.1} °C load {}", + s.mode().map_or("?", |m| m.as_str()), + s.voltage, + s.current, + s.power, + s.temperature, + if s.load_on { "ON" } else { "off" }, + ); + readings += 1; + break; + } + Some(DeviceEvent::Disconnected) | None => return Err("device disconnected".into()), + Some(_) => {} + }, + _ = &mut deadline => break, + } + } + } + + device.disconnect().await?; + Ok(()) +} diff --git a/el15-bt/src/device.rs b/alientek-el15/src/device.rs similarity index 63% rename from el15-bt/src/device.rs rename to alientek-el15/src/device.rs index 78cad7c..616b2c7 100644 --- a/el15-bt/src/device.rs +++ b/alientek-el15/src/device.rs @@ -15,42 +15,28 @@ use std::time::Duration; use btleplug::api::{ - Central, CentralEvent, Manager as _, Peripheral as _, ScanFilter, WriteType, + Central, CentralEvent, CharPropFlags, Characteristic, Manager as _, Peripheral as _, + ScanFilter, WriteType, }; use btleplug::platform::{Adapter, Manager, Peripheral}; use futures::StreamExt; -use tokio::sync::mpsc; +use tokio::sync::{mpsc, Mutex}; +use tokio::time::Instant; use tokio_stream::wrappers::ReceiverStream; use tracing::{debug, info}; use uuid::{uuid, Uuid}; use crate::error::{Error, Result}; use crate::protocol::{ - parse_cap_current, parse_status_packet, parse_firmware_version, EL15Status, HEADER, POLL_PKT, - CMD_INIT, CMD_INFO, CMD_GET_CAP_CURRENT, + parse_cap_current, parse_status_packet, parse_firmware_version, FirmwareVersion, Status, + STATUS_HEADER, POLL_PKT, CMD_INIT, CMD_INFO, CMD_GET_CAP_CURRENT, INTER_COMMAND_GAP, }; const SCAN_DURATION: Duration = Duration::from_secs(5); /// GATT service UUID exposed by ALIENTEK EL15 (short UUID 0xFFF0). /// The writable and notify characteristics live under this service. -pub const EL15_SERVICE_UUID: Uuid = uuid!("0000fff0-0000-1000-8000-00805f9b34fb"); - -/// Minimum gap between two consecutive command writes. -/// -/// The write characteristic advertises WRITE_WITHOUT_RESPONSE, so [`Device::send`] -/// uses it — and that has no flow control: frames written back-to-back are -/// silently dropped, with no error on this side. -/// -/// Measured on HW:2.0 / SW:1.7. Three commands sent with no gap (set mode, set -/// setpoint, set CAP current) landed **none** of the trailing two — the CAP -/// current read back unchanged three times running, and one reply came back -/// corrupted (`df 01 04 39 …`, containing bytes of the outgoing frame). The -/// same three spaced 120 ms apart took effect 3 times out of 3. -/// -/// This is why a burst of commands used to need several button presses before -/// one "took". -pub const INTER_COMMAND_GAP: Duration = Duration::from_millis(120); +pub const SERVICE_UUID: Uuid = uuid!("0000fff0-0000-1000-8000-00805f9b34fb"); /// Friendly name prefixes used as a fallback when advertisement data does not /// carry the service UUID list (some BT stacks strip 128-bit UUIDs from the @@ -86,16 +72,21 @@ fn short_id(id: &str) -> String { suffix.chars().rev().collect::().to_uppercase() } +/// What the notification pump of a connected [`Device`] reports. #[derive(Debug, Clone)] pub enum DeviceEvent { - Status(EL15Status), - FirmwareVersion(String), + /// A valid status packet (checked length, header and checksum). + Status(Status), + /// The reply to the init handshake. + FirmwareVersion(FirmwareVersion), /// CAP discharge current in Amps, from a `DF 07 03 0A` response. /// /// Only emitted in reply to [`Device::request_cap_current`]; the device /// never reports this value in the periodic status packet. CapCurrent(f32), + /// Every notification, unfiltered, including those that failed to parse. RawNotification(Vec), + /// The notification stream ended. Disconnected, } @@ -139,7 +130,7 @@ pub async fn scan_for_device(target_id: &str, timeout: Duration) -> Result Result> { // the service UUID in their GATT table (not in advertisement data). // So we always scan unfiltered on Apple platforms and post-filter. ScanFilter { - services: vec![EL15_SERVICE_UUID], + services: vec![SERVICE_UUID], } } else { ScanFilter::default() @@ -211,7 +202,7 @@ pub async fn scan_devices_with(opts: ScanOptions) -> Result> { for p in central.peripherals().await? { let props = p.properties().await?.unwrap_or_default(); let name = props.local_name.clone().unwrap_or_default(); - let advertises_el15 = props.services.contains(&EL15_SERVICE_UUID); + let advertises_el15 = props.services.contains(&SERVICE_UUID); let name_match = !name.is_empty() && NAME_PREFIXES .iter() @@ -255,11 +246,52 @@ pub async fn scan_devices_with(opts: ScanOptions) -> Result> { Ok(out) } +/// The characteristic the device both accepts commands on and notifies from (`FFF1`). +const DATA_CHAR_UUID: Uuid = uuid!("0000fff1-0000-1000-8000-00805f9b34fb"); + +fn is_writable(c: &Characteristic) -> bool { + c.properties.contains(CharPropFlags::WRITE) + || c.properties.contains(CharPropFlags::WRITE_WITHOUT_RESPONSE) +} + +fn is_notifying(c: &Characteristic) -> bool { + c.properties.contains(CharPropFlags::NOTIFY) || c.properties.contains(CharPropFlags::INDICATE) +} + +/// Pick the write and notify characteristics, only from the EL15 service. +/// +/// The EL15 (HW:2.0 / SW:1.7) exposes `FFF1` (write without response + notify), +/// `FFF2` (read + notify) and `FFF3` (write without response) under `FFF0`. `FFF1` +/// carries both directions and is preferred; another characteristic of the service is +/// used only if `FFF1` lacks the property. A characteristic outside the service is never +/// used: on a peripheral that is not an EL15 that would mean writing EL15 commands to an +/// unrelated characteristic. +fn select_characteristics( + chars: &std::collections::BTreeSet, +) -> Result<(Characteristic, Characteristic)> { + let pick = |wanted: fn(&Characteristic) -> bool| { + let on_service = || chars.iter().filter(|c| c.service_uuid == SERVICE_UUID && wanted(c)); + on_service() + .find(|c| c.uuid == DATA_CHAR_UUID) + .or_else(|| on_service().next()) + .cloned() + }; + let write = pick(is_writable).ok_or(Error::CharacteristicNotFound("writable on service FFF0"))?; + let notify = pick(is_notifying).ok_or(Error::CharacteristicNotFound("notify on service FFF0"))?; + Ok((write, notify)) +} + /// Connected EL15 handle. +/// +/// Every write goes through [`Device::send`], which keeps [`INTER_COMMAND_GAP`] between +/// consecutive writes, so callers on several tasks can share one `Device` (e.g. in an +/// `Arc`) without their commands being dropped. pub struct Device { peripheral: Peripheral, - write_char: btleplug::api::Characteristic, - notify_char: btleplug::api::Characteristic, + write_char: Characteristic, + notify_char: Characteristic, + /// When the last write finished; held across a write so writes never overlap. + last_write: Mutex>, } impl Device { @@ -291,43 +323,11 @@ impl Device { async fn build_device(p: Peripheral) -> Result<(Self, ReceiverStream)> { p.discover_services().await?; - let mut write_char = None; - let mut notify_char = None; - let mut write_char_fallback = None; - let mut notify_char_fallback = None; - - for c in p.characteristics() { - let props = c.properties; - let writable = props.contains(btleplug::api::CharPropFlags::WRITE) - || props.contains(btleplug::api::CharPropFlags::WRITE_WITHOUT_RESPONSE); - let notifies = props.contains(btleplug::api::CharPropFlags::NOTIFY) - || props.contains(btleplug::api::CharPropFlags::INDICATE); - let on_el15_service = c.service_uuid == EL15_SERVICE_UUID; - - if writable { - if on_el15_service && write_char.is_none() { - debug!("write characteristic on EL15 service: {}", c.uuid); - write_char = Some(c.clone()); - } else if write_char_fallback.is_none() { - write_char_fallback = Some(c.clone()); - } - } - if notifies { - if on_el15_service && notify_char.is_none() { - debug!("notify characteristic on EL15 service: {}", c.uuid); - notify_char = Some(c.clone()); - } else if notify_char_fallback.is_none() { - notify_char_fallback = Some(c.clone()); - } - } - } - - let write_char = write_char - .or(write_char_fallback) - .ok_or(Error::CharacteristicNotFound("writable"))?; - let notify_char = notify_char - .or(notify_char_fallback) - .ok_or(Error::CharacteristicNotFound("notify"))?; + let (write_char, notify_char) = select_characteristics(&p.characteristics())?; + debug!( + "EL15 characteristics: write {}, notify {}", + write_char.uuid, notify_char.uuid + ); p.subscribe(¬ify_char).await?; @@ -343,10 +343,13 @@ impl Device { while let Some(notif) = stream.next().await { let data = notif.value; let _ = tx.send(DeviceEvent::RawNotification(data.clone())).await; - if data.len() >= 4 && data[..4] == HEADER { - let status = parse_status_packet(&data); - if status.valid { - let _ = tx.send(DeviceEvent::Status(status)).await; + if data.starts_with(&STATUS_HEADER) { + match parse_status_packet(&data) { + Ok(status) => { + let _ = tx.send(DeviceEvent::Status(status)).await; + } + // Corrupted or truncated: never report it as a measurement. + Err(e) => debug!("dropped status notification: {e}"), } } else if let Some(ver) = parse_firmware_version(&data) { let _ = tx.send(DeviceEvent::FirmwareVersion(ver)).await; @@ -362,16 +365,31 @@ impl Device { peripheral: p, write_char, notify_char, + last_write: Mutex::new(None), }, ReceiverStream::new(rx), )) } + /// Write one command frame. + /// + /// Waits until [`INTER_COMMAND_GAP`] has passed since the previous write (from any + /// task), because the device silently drops frames written closer together. pub async fn send(&self, payload: &[u8]) -> Result<()> { + let mut last_write = self.last_write.lock().await; + if let Some(at) = *last_write { + tokio::time::sleep_until(at + INTER_COMMAND_GAP).await; + } + let result = self.write_now(payload).await; + *last_write = Some(Instant::now()); + result + } + + async fn write_now(&self, payload: &[u8]) -> Result<()> { let kind = if self .write_char .properties - .contains(btleplug::api::CharPropFlags::WRITE_WITHOUT_RESPONSE) + .contains(CharPropFlags::WRITE_WITHOUT_RESPONSE) { WriteType::WithoutResponse } else { @@ -383,15 +401,10 @@ impl Device { Ok(()) } - /// Send several commands in order, pausing [`INTER_COMMAND_GAP`] between them. - /// - /// Always prefer this over consecutive [`Device::send`] calls: commands - /// written back-to-back are silently dropped (see the constant's docs). + /// Send several commands in order, [`INTER_COMMAND_GAP`] apart, stopping at the + /// first error. pub async fn send_sequence(&self, frames: &[Vec]) -> Result<()> { - for (i, frame) in frames.iter().enumerate() { - if i > 0 { - tokio::time::sleep(INTER_COMMAND_GAP).await; - } + for frame in frames { self.send(frame).await?; } Ok(()) @@ -412,6 +425,8 @@ impl Device { /// Send the init handshake and info request to wake up the device's /// full status reporting (temperature, setpoint, etc.). + /// + /// The two frames go out [`INTER_COMMAND_GAP`] apart, like every write. pub async fn init_handshake(&self) -> Result<()> { self.send(&CMD_INIT).await?; self.send(&CMD_INFO).await?; @@ -431,15 +446,72 @@ impl Device { self.peripheral.disconnect().await?; Ok(()) } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeSet; + + fn ch(service: u16, uuid: u16, properties: CharPropFlags) -> Characteristic { + let full = |short: u16| { + Uuid::from_u128(((short as u128) << 96) | 0x0000_0000_0000_1000_8000_0080_5f9b_34fb) + }; + Characteristic { + uuid: full(uuid), + service_uuid: full(service), + properties, + descriptors: BTreeSet::new(), + } + } + + /// The layout the real device (HW:2.0 / SW:1.7) reports. + fn el15_layout() -> BTreeSet { + [ + ch(0xFFF0, 0xFFF1, CharPropFlags::WRITE_WITHOUT_RESPONSE | CharPropFlags::NOTIFY), + ch(0xFFF0, 0xFFF2, CharPropFlags::READ | CharPropFlags::NOTIFY), + ch(0xFFF0, 0xFFF3, CharPropFlags::WRITE_WITHOUT_RESPONSE), + ] + .into_iter() + .collect() + } + + #[test] + fn uuid_helper_matches_constants() { + assert_eq!(ch(0xFFF0, 0xFFF1, CharPropFlags::NOTIFY).service_uuid, SERVICE_UUID); + assert_eq!(ch(0xFFF0, 0xFFF1, CharPropFlags::NOTIFY).uuid, DATA_CHAR_UUID); + } + + #[test] + fn real_device_uses_fff1_both_ways() { + let (w, n) = select_characteristics(&el15_layout()).unwrap(); + assert_eq!(w.uuid, DATA_CHAR_UUID); + assert_eq!(n.uuid, DATA_CHAR_UUID); + } + + #[test] + fn falls_back_within_the_service_only() { + // FFF1 without notify: notify comes from FFF2, still on FFF0. + let mut chars = el15_layout(); + chars.retain(|c| c.uuid != DATA_CHAR_UUID); + chars.insert(ch(0xFFF0, 0xFFF1, CharPropFlags::WRITE_WITHOUT_RESPONSE)); + let (w, n) = select_characteristics(&chars).unwrap(); + assert_eq!(w.uuid, DATA_CHAR_UUID); + assert_eq!(n.uuid, ch(0xFFF0, 0xFFF2, CharPropFlags::NOTIFY).uuid); + } - pub async fn watch_central_events() -> Result> { - let manager = Manager::new().await?; - let adapter = manager - .adapters() - .await? - .into_iter() - .next() - .ok_or(Error::NoAdapter)?; - Ok(adapter.events().await?) + #[test] + fn never_uses_another_service() { + // A peripheral that is not an EL15: writable and notifying, but not on FFF0. + let chars: BTreeSet<_> = [ + ch(0x180A, 0x2A29, CharPropFlags::READ), + ch(0xFFE0, 0xFFE1, CharPropFlags::WRITE | CharPropFlags::NOTIFY), + ] + .into_iter() + .collect(); + assert!(matches!( + select_characteristics(&chars), + Err(Error::CharacteristicNotFound(_)) + )); } } diff --git a/el15-bt/src/error.rs b/alientek-el15/src/error.rs similarity index 54% rename from el15-bt/src/error.rs rename to alientek-el15/src/error.rs index 8ffd760..5dcae1f 100644 --- a/el15-bt/src/error.rs +++ b/alientek-el15/src/error.rs @@ -1,30 +1,21 @@ use thiserror::Error; +/// Errors from scanning, connecting and sending. #[derive(Debug, Error)] +#[non_exhaustive] pub enum Error { + /// The Bluetooth stack reported an error. #[error("Bluetooth error: {0}")] Bluetooth(#[from] btleplug::Error), + /// The system has no Bluetooth adapter. #[error("No Bluetooth adapter found")] NoAdapter, - #[error("Device not connected")] - NotConnected, - - #[error("Device disconnected")] - Disconnected, - + /// The connected peripheral lacks the EL15 characteristic named here. #[error("Required GATT characteristic not found ({0})")] CharacteristicNotFound(&'static str), - - #[error("Protocol error: {0}")] - Protocol(String), - - #[error("Timeout waiting for {0}")] - Timeout(&'static str), - - #[error("IO error: {0}")] - Io(#[from] std::io::Error), } +/// `Result` with this crate's [`Error`](enum@Error). pub type Result = std::result::Result; diff --git a/alientek-el15/src/lib.rs b/alientek-el15/src/lib.rs new file mode 100644 index 0000000..9d0f13f --- /dev/null +++ b/alientek-el15/src/lib.rs @@ -0,0 +1,42 @@ +//! Unofficial client for the **ALIENTEK EL15** DC electronic load over Bluetooth LE. +//! Not affiliated with or endorsed by ALIENTEK. +//! +//! The protocol was reverse-engineered from the Bluetooth traffic of ALIENTEK's official +//! Android app, ATK-xTOOL, and cross-checked against the Python project DM40GUI. +//! The full description, with the evidence for each field, is in +//! [docs/BT_PROTOCOL.md](https://github.com/rssdev10/el15/blob/main/docs/BT_PROTOCOL.md). +//! +//! - [`protocol`]: command frames, the checksum, and parsers for the device's replies. +//! - `device` (feature `ble`): scanning, connecting, and a `Device` handle that sends +//! commands and turns notifications into `DeviceEvent`s. +//! +//! ## Cargo features +//! +//! - `ble` (default): Bluetooth LE through `btleplug` — `scan_devices`, `Device::connect` +//! and the notification pump. Without it the crate keeps the command frames, the checksum +//! and the reply parsers, and needs no Bluetooth stack or async runtime to build. +//! - `serde`: `Serialize`/`Deserialize` for [`Status`], [`Mode`], [`Warning`] and +//! [`FirmwareVersion`]. + +pub mod protocol; +#[cfg(feature = "ble")] +pub mod device; +#[cfg(feature = "ble")] +pub mod error; + +#[cfg(feature = "ble")] +pub use error::{Error, Result}; +pub use protocol::{ + Status, Mode, Warning, FirmwareVersion, ParseError, InvalidValue, + STATUS_HEADER, STATUS_LEN, CAP_CURRENT_HEADER, POLL_PKT, + CMD_LOAD_ON, CMD_LOAD_OFF, CMD_LOCK, CMD_INIT, CMD_INFO, CMD_GET_CAP_CURRENT, + CAP_CURRENT_MAX_A, SETPOINT_MAX, FAN_SPEED_MAX, + build_set_setpoint_cmd, build_set_cap_current_cmd, build_mode_cmd, + parse_status_packet, parse_cap_current, checksum, + parse_firmware_version, INTER_COMMAND_GAP, +}; +#[cfg(feature = "ble")] +pub use device::{ + scan_devices, scan_devices_with, scan_for_device, Device, DeviceEvent, DeviceInfo, ScanOptions, + SERVICE_UUID, +}; diff --git a/alientek-el15/src/protocol.rs b/alientek-el15/src/protocol.rs new file mode 100644 index 0000000..b48b7d9 --- /dev/null +++ b/alientek-el15/src/protocol.rs @@ -0,0 +1,761 @@ +//! EL15 packet protocol: command frames, the checksum, and reply parsers. +//! +//! All numeric framing is little-endian. + +use std::fmt; +use std::time::Duration; + +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; + +// --------------------------------------------------------------------------- +// Wire constants +// --------------------------------------------------------------------------- + +/// Header of the status notification coming *from* the device. +pub const STATUS_HEADER: [u8; 4] = [0xDF, 0x07, 0x03, 0x08]; + +/// Length of a status notification, checksum included. +pub const STATUS_LEN: usize = 28; + +/// Pre-computed poll packet (CMD_QUERY prefix + checksum byte 0x3F). +pub const POLL_PKT: [u8; 6] = [0xAF, 0x07, 0x03, 0x08, 0x00, 0x3F]; + +/// Init/handshake packet — device responds with firmware version. +pub const CMD_INIT: [u8; 6] = [0xAF, 0xFF, 0xFF, 0x00, 0x00, 0x53]; + +/// Device info request — device responds with its stored name. +pub const CMD_INFO: [u8; 6] = [0xAF, 0x07, 0x03, 0x07, 0x00, 0x40]; + +/// Switch the load on. +pub const CMD_LOAD_ON: [u8; 7] = [0xAF, 0x07, 0x03, 0x09, 0x01, 0x04, 0x39]; +/// Switch the load off. +pub const CMD_LOAD_OFF: [u8; 7] = [0xAF, 0x07, 0x03, 0x09, 0x01, 0x00, 0x3D]; +/// Lock the front panel. +pub const CMD_LOCK: [u8; 7] = [0xAF, 0x07, 0x03, 0x09, 0x01, 0x01, 0x3C]; + +/// Prefix of a "set mode" command — append the mode byte + checksum. +const CMD_MODE_PREFIX: [u8; 5] = [0xAF, 0x07, 0x03, 0x03, 0x01]; + +/// Prefix of a "set setpoint" command — append the f32 LE bytes + checksum. +/// +/// Applies to CC/CV/CR/CP only. In CAP and DCR the device acknowledges this +/// command with status `0x00` and then ignores it — use [`CMD_SET_CAP_CURRENT_PREFIX`] +/// for the CAP discharge current. +const CMD_SETPOINT_PREFIX: [u8; 5] = [0xAF, 0x07, 0x03, 0x04, 0x04]; + +/// Prefix of a "set CAP discharge current" command (cmd `0x05`, f32 LE Amps). +/// +/// Separate opcode from the ordinary setpoint. Verified on HW:2.0 / SW:1.7: +/// writing here changes the value that [`CMD_GET_CAP_CURRENT`] reads back and +/// the current shown on the device's capacity-test screen. +const CMD_SET_CAP_CURRENT_PREFIX: [u8; 5] = [0xAF, 0x07, 0x03, 0x05, 0x04]; + +/// Read the CAP discharge current — device replies `DF 07 03 0A 04 `. +/// +/// The device applies its own quantisation (it stores milliamps), so a value +/// written as `5.0` reads back as `5.0000010`. +pub const CMD_GET_CAP_CURRENT: [u8; 6] = [0xAF, 0x07, 0x03, 0x0A, 0x00, 0x3D]; + +/// Header of the CAP discharge-current response. +pub const CAP_CURRENT_HEADER: [u8; 5] = [0xDF, 0x07, 0x03, 0x0A, 0x04]; + +/// Minimum gap between two consecutive command writes. +/// +/// The write characteristic advertises WRITE_WITHOUT_RESPONSE, so `Device::send` +/// (feature `ble`) uses it — and that has no flow control: frames written +/// back-to-back are silently dropped, with no error on this side. +/// +/// Measured on HW:2.0 / SW:1.7: three commands sent with no gap (set mode CAP, +/// set setpoint, set CAP current) lost the mode switch 4 times out of 6, and +/// earlier one reply came back corrupted (`df 01 04 39 …`, containing bytes of +/// the outgoing frame). The same three 120 ms apart took effect 6 times out of 6. +/// Read-only queries were never lost. See `docs/BT_PROTOCOL.md`. +/// +/// This is why a burst of commands used to need several button presses before +/// one "took". With the `ble` feature, `Device::send` keeps this gap itself. +pub const INTER_COMMAND_GAP: Duration = Duration::from_millis(120); + +/// Compute the checksum byte that makes `sum(packet) % 256 == 0`. +pub fn checksum(data: &[u8]) -> u8 { + let sum: u8 = data.iter().fold(0u8, |acc, &b| acc.wrapping_add(b)); + 0u8.wrapping_sub(sum) +} + +/// True when the bytes, checksum included, add up to 0 modulo 256. +fn checksum_ok(data: &[u8]) -> bool { + data.iter().fold(0u8, |acc, &b| acc.wrapping_add(b)) == 0 +} + +// --------------------------------------------------------------------------- +// Modes +// --------------------------------------------------------------------------- + +/// Operating mode, as the byte the device uses on the wire. +/// +/// CC, CV, CR, CP, CAP and DCR can be selected over BLE; the others are front-panel +/// screens the device may report (see [`Mode::is_unreachable`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[repr(u8)] +pub enum Mode { + CC = 0x01, + CAP = 0x02, + DT = 0x03, + ADV = 0x04, + CV = 0x09, + DCR = 0x0A, + POWER = 0x0B, + AdvScan = 0x0C, + PowerRpt = 0x0D, + CR = 0x11, + CP = 0x19, +} + +impl Mode { + /// The mode for a wire byte, or `None` for a byte no mode uses. + pub fn from_byte(b: u8) -> Option { + Some(match b { + 0x01 => Mode::CC, + 0x02 => Mode::CAP, + 0x03 => Mode::DT, + 0x04 => Mode::ADV, + 0x09 => Mode::CV, + 0x0A => Mode::DCR, + 0x0B => Mode::POWER, + 0x0C => Mode::AdvScan, + 0x0D => Mode::PowerRpt, + 0x11 => Mode::CR, + 0x19 => Mode::CP, + _ => return None, + }) + } + + /// Short label, as on the device screen (`"CC"`, `"CAP"`, `"POW [DT]"`, …). + pub fn as_str(self) -> &'static str { + match self { + Mode::CC => "CC", + Mode::CAP => "CAP", + Mode::DT => "POW [DT]", + Mode::ADV => "ADV [L]", + Mode::CV => "CV", + Mode::DCR => "DCR", + Mode::POWER => "POW [A]", + Mode::AdvScan => "ADV [S]", + Mode::PowerRpt => "POW [RPT]", + Mode::CR => "CR", + Mode::CP => "CP", + } + } + + /// `(unit, decimal_places, label)` of the mode's setpoint. + pub fn setpoint_info(self) -> (&'static str, u8, &'static str) { + match self { + Mode::CC | Mode::CAP | Mode::DCR => ("A", 3, "Current"), + Mode::CV => ("V", 3, "Voltage"), + Mode::CR => ("Ω", 1, "Resistance"), + Mode::CP => ("W", 2, "Power"), + _ => ("", 3, ""), + } + } + + /// CAP and DCR: the battery-capacity and internal-resistance tests. + pub fn is_advanced(self) -> bool { + matches!(self, Mode::CAP | Mode::DCR) + } + + /// Front-panel screens that cannot be selected over BLE. + pub fn is_unreachable(self) -> bool { + matches!( + self, + Mode::ADV | Mode::POWER | Mode::DT | Mode::AdvScan | Mode::PowerRpt + ) + } +} + +impl fmt::Display for Mode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +// --------------------------------------------------------------------------- +// Status packet +// --------------------------------------------------------------------------- + +const STATUS_LOAD_BIT: u8 = 0x02; +const STATUS_LOCK_BIT: u8 = 0x04; +const MODE_MASK: u8 = 0x1F; +const B5_WARN_FLAG: u8 = 0x06; // bits 1+2 simultaneously => protection +/// Highest value of [`Status::fan_speed`]. +pub const FAN_SPEED_MAX: u8 = 5; + +/// Protection warning reported in a status packet. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[non_exhaustive] +pub enum Warning { + /// Reverse polarity on the input (code `0x6`). + Reverse, + /// Under-voltage protection (code `0x9`). + Undervoltage, + /// Another protection trip, with its 4-bit code. + Protection(u8), +} + +impl Warning { + fn from_code(code: u8) -> Self { + match code { + 0x6 => Warning::Reverse, + 0x9 => Warning::Undervoltage, + other => Warning::Protection(other), + } + } +} + +impl fmt::Display for Warning { + /// The device's abbreviation: `REV`, `UVP` or `PROT `. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Warning::Reverse => f.write_str("REV"), + Warning::Undervoltage => f.write_str("UVP"), + Warning::Protection(code) => write!(f, "PROT {code:X}"), + } + } +} + +/// One status notification, decoded. +/// +/// Which fields carry data depends on the mode: [`setpoint`](Self::setpoint) and +/// [`temperature`](Self::temperature) in CC/CV/CR/CP, [`capacity_ah`](Self::capacity_ah) +/// and [`energy_wh`](Self::energy_wh) in CAP, the `dcr_*` fields in DCR. The others are 0. +#[derive(Debug, Clone, Default, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct Status { + /// Input voltage, V. + pub voltage: f32, + /// Load current, A. + pub current: f32, + /// `voltage * current`, W. + pub power: f32, + /// Time the load has been on, s (0 in DCR). + pub runtime_s: u32, + /// Heat-sink temperature, °C (CC/CV/CR/CP). + pub temperature: f32, + /// Setpoint of the current mode, in its unit (see [`Mode::setpoint_info`]). + pub setpoint: f32, + + /// Energy discharged in CAP mode, Wh. + pub energy_wh: f32, + /// Capacity discharged in CAP mode, Ah. + pub capacity_ah: f32, + + /// Internal resistance measured in DCR mode, **mΩ** (milliohms). + pub dcr_mohm: f32, + /// First DCR test current, A (set on the front panel). + pub dcr_i1: f32, + /// Second DCR test current, A (set on the front panel). + pub dcr_i2: f32, + + /// Mode byte; [`Status::mode`] decodes it. + pub mode_byte: u8, + + /// Fan speed, 0 to [`FAN_SPEED_MAX`]. + pub fan_speed: u8, + /// The load is on. + pub load_on: bool, + /// The front panel is locked. + pub lock_on: bool, + /// The device is ready (no protection trip). + pub ready: bool, + + /// The packet carries a setpoint (CC/CV/CR/CP). + pub setpoint_in_packet: bool, + /// Protection warning, if one is active. + pub warning: Option, +} + +impl Status { + /// The decoded mode, or `None` for a mode byte no mode uses. + pub fn mode(&self) -> Option { + Mode::from_byte(self.mode_byte) + } +} + +/// Why a notification is not a valid status packet. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[non_exhaustive] +pub enum ParseError { + /// The packet does not have [`STATUS_LEN`] bytes. + #[error("status packet has {0} bytes, expected {STATUS_LEN}")] + WrongLength(usize), + /// The packet does not start with [`STATUS_HEADER`]. + #[error("not a status packet (header {0:02X?})")] + WrongHeader([u8; 4]), + /// The bytes do not add up to 0 modulo 256: the packet was corrupted. + #[error("status packet checksum mismatch")] + Checksum, +} + +fn read_f32_le(buf: &[u8]) -> f32 { + f32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) +} +fn read_u32_le(buf: &[u8]) -> u32 { + u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) +} + +/// Parse a 28-byte status notification. +/// +/// Fails on a wrong length, a wrong header or a bad checksum; a corrupted packet is never +/// returned as a measurement. +pub fn parse_status_packet(data: &[u8]) -> Result { + if data.len() != STATUS_LEN { + return Err(ParseError::WrongLength(data.len())); + } + if data[..4] != STATUS_HEADER { + return Err(ParseError::WrongHeader([data[0], data[1], data[2], data[3]])); + } + if !checksum_ok(data) { + return Err(ParseError::Checksum); + } + + let mut s = Status { + voltage: read_f32_le(&data[7..11]), + current: read_f32_le(&data[11..15]), + ..Default::default() + }; + + let b5 = data[5]; + let b6 = data[6]; + + let warn_flag = (b5 & B5_WARN_FLAG) == B5_WARN_FLAG; + let raw_mode = if warn_flag { + b5 & (MODE_MASK & !B5_WARN_FLAG) + } else { + b5 & MODE_MASK + }; + let mode_byte = if Mode::from_byte(raw_mode).is_some() { + raw_mode + } else { + raw_mode | 0x01 + }; + + s.mode_byte = mode_byte; + let mode = Mode::from_byte(mode_byte); + + if warn_flag { + s.warning = Some(Warning::from_code(b6 >> 4)); + s.ready = false; + } else { + s.ready = (raw_mode & 0x01) != 0 + || matches!( + mode, + Some(Mode::CAP | Mode::DCR | Mode::ADV | Mode::POWER | Mode::DT | Mode::AdvScan | Mode::PowerRpt) + ); + } + + s.runtime_s = read_u32_le(&data[15..19]); + s.power = s.voltage * s.current; + s.setpoint_in_packet = true; + + match mode { + Some(Mode::CAP) => { + s.energy_wh = read_f32_le(&data[19..23]) * 0.001; + s.capacity_ah = read_f32_le(&data[23..27]) * 0.001; + s.setpoint_in_packet = false; + } + Some(Mode::DCR) => { + s.dcr_i1 = read_f32_le(&data[15..19]); + s.dcr_i2 = read_f32_le(&data[19..23]); + s.dcr_mohm = read_f32_le(&data[23..27]); + s.runtime_s = 0; + // Voltage/current/power from bytes 7–15 reflect the live + // measurement during the DCR test. + s.setpoint_in_packet = false; + } + Some(Mode::ADV | Mode::POWER | Mode::DT | Mode::PowerRpt) => { + s.runtime_s = 0; + s.setpoint_in_packet = false; + } + _ => { + s.temperature = read_f32_le(&data[19..23]); + s.setpoint = read_f32_le(&data[23..27]); + } + } + + s.fan_speed = (b5 >> 6) | ((b6 & 0x01) << 2); + s.load_on = (b6 & STATUS_LOAD_BIT) != 0; + s.lock_on = (b6 & STATUS_LOCK_BIT) != 0; + + Ok(s) +} + +// --------------------------------------------------------------------------- +// Command builders +// --------------------------------------------------------------------------- + +/// Build a "set mode" command. +pub fn build_mode_cmd(mode: Mode) -> Vec { + let mut v = Vec::with_capacity(7); + v.extend_from_slice(&CMD_MODE_PREFIX); + v.push(mode as u8); + v.push(checksum(&v)); + v +} + +/// A value a command builder refuses to put on the wire. +#[derive(Debug, Clone, Copy, PartialEq, thiserror::Error)] +#[non_exhaustive] +pub enum InvalidValue { + /// NaN or infinite. + #[error("{0} is not a finite number")] + NotFinite(f32), + /// Below zero. + #[error("{0} is negative")] + Negative(f32), + /// Above the device's limit for this command. + #[error("{value} is above the maximum {max}")] + AboveMax { value: f32, max: f32 }, +} + +fn check_value(value: f32, max: f32) -> Result { + if !value.is_finite() { + Err(InvalidValue::NotFinite(value)) + } else if value < 0.0 { + Err(InvalidValue::Negative(value)) + } else if value > max { + Err(InvalidValue::AboveMax { value, max }) + } else { + Ok(value) + } +} + +fn f32_cmd(prefix: &[u8; 5], value: f32) -> Vec { + let mut v = Vec::with_capacity(10); + v.extend_from_slice(prefix); + v.extend_from_slice(&value.to_le_bytes()); + v.push(checksum(&v)); + v +} + +/// Highest setpoint of any mode: CR's 7500 Ω. The per-mode limits (CC 12 A, CV 60 V, +/// CR 7500 Ω, CP 150 W) are the caller's to apply; this one only keeps absurd values off +/// the wire. +pub const SETPOINT_MAX: f32 = 7500.0; + +/// Build a "set setpoint" command (CC/CV/CR/CP), in the mode's unit. +/// +/// Fails for NaN, infinity, a negative value or one above [`SETPOINT_MAX`]. +pub fn build_set_setpoint_cmd(value: f32) -> Result, InvalidValue> { + let value = check_value(value, SETPOINT_MAX)?; + Ok(f32_cmd(&CMD_SETPOINT_PREFIX, value)) +} + +/// Highest CAP discharge current the device accepts (12 A = 12000 mA). +pub const CAP_CURRENT_MAX_A: f32 = 12.0; + +/// Build a "set CAP discharge current" command (`0x05`), value in **Amps**. +/// +/// Fails for NaN, infinity, a negative value or one above [`CAP_CURRENT_MAX_A`]. +pub fn build_set_cap_current_cmd(amps: f32) -> Result, InvalidValue> { + let amps = check_value(amps, CAP_CURRENT_MAX_A)?; + Ok(f32_cmd(&CMD_SET_CAP_CURRENT_PREFIX, amps)) +} + +/// Parse a CAP discharge-current response (`DF 07 03 0A 04 `). +/// +/// Returns the current in Amps, or `None` if this is not that response or its +/// checksum is wrong. +pub fn parse_cap_current(data: &[u8]) -> Option { + if data.len() != 10 || data[..5] != CAP_CURRENT_HEADER || !checksum_ok(data) { + return None; + } + Some(f32::from_le_bytes([data[5], data[6], data[7], data[8]])) +} + +/// Hardware and firmware version, from the reply to [`CMD_INIT`]. +/// +/// Displays as `HW:2.0 SW:1.7`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct FirmwareVersion { + pub hw_major: u8, + pub hw_minor: u8, + pub sw_major: u8, + pub sw_minor: u8, +} + +impl fmt::Display for FirmwareVersion { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "HW:{}.{} SW:{}.{}", + self.hw_major, self.hw_minor, self.sw_major, self.sw_minor + ) + } +} + +/// Parse the firmware version from the Init response notification. +/// +/// Packet: `DF FF FF ` (8 bytes). +/// +/// Version encoding: +/// - `hw_ver` (`data[4]`) — reverse-nibble BCD: major = low nibble, minor = high nibble. +/// e.g. `0x02` → major=2, minor=0 → "2.0" +/// - `sw_ver` (`data[7]`) — normal BCD: major = high nibble, minor = low nibble. +/// e.g. `0x17` → major=1, minor=7 → "1.7" +/// (This byte also satisfies the packet checksum invariant: sum of all 8 bytes ≡ 0 mod 256.) +/// +/// Returns `None` if this is not that response or its checksum is wrong. +pub fn parse_firmware_version(data: &[u8]) -> Option { + if data.len() != 8 || data[..3] != [0xDF, 0xFF, 0xFF] || !checksum_ok(data) { + return None; + } + let hw_byte = data[4]; + let sw_byte = data[7]; + Some(FirmwareVersion { + hw_major: hw_byte & 0x0F, + hw_minor: (hw_byte >> 4) & 0x0F, + sw_major: (sw_byte >> 4) & 0x0F, + sw_minor: sw_byte & 0x0F, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn poll_packet_checksum() { + assert_eq!(POLL_PKT, [0xAF, 0x07, 0x03, 0x08, 0x00, 0x3F]); + assert!(checksum_ok(&POLL_PKT)); + } + + #[test] + fn load_commands_checksum() { + assert!(checksum_ok(&CMD_LOAD_ON)); + assert!(checksum_ok(&CMD_LOAD_OFF)); + assert!(checksum_ok(&CMD_LOCK)); + assert!(checksum_ok(&CMD_INIT)); + assert!(checksum_ok(&CMD_INFO)); + } + + #[test] + fn empty_packet_invalid() { + assert_eq!(parse_status_packet(&[]), Err(ParseError::WrongLength(0))); + } + + #[test] + fn build_setpoint_cmd_layout() { + let cmd = build_set_setpoint_cmd(2.5).unwrap(); + assert_eq!(&cmd[..5], &CMD_SETPOINT_PREFIX); + assert_eq!(cmd.len(), 10); + let f = f32::from_le_bytes([cmd[5], cmd[6], cmd[7], cmd[8]]); + assert!((f - 2.5).abs() < 1e-6); + assert!(checksum_ok(&cmd)); + } + + /// Byte-for-byte against the frame accepted by the real device + /// (HW:2.0 / SW:1.7): `af 07 03 05 04 00 00 a0 40 5e` set 5.0 A and the + /// device acknowledged it with `df 07 03 05 01 00 11`. + #[test] + fn build_set_cap_current_matches_device_accepted_frame() { + assert_eq!( + build_set_cap_current_cmd(5.0).unwrap(), + vec![0xAF, 0x07, 0x03, 0x05, 0x04, 0x00, 0x00, 0xA0, 0x40, 0x5E] + ); + assert_eq!( + build_set_cap_current_cmd(3.3).unwrap(), + vec![0xAF, 0x07, 0x03, 0x05, 0x04, 0x33, 0x33, 0x53, 0x40, 0x45] + ); + } + + #[test] + fn cap_current_outside_device_range_is_rejected() { + assert_eq!( + build_set_cap_current_cmd(99.0), + Err(InvalidValue::AboveMax { value: 99.0, max: CAP_CURRENT_MAX_A }) + ); + assert_eq!(build_set_cap_current_cmd(-1.0), Err(InvalidValue::Negative(-1.0))); + assert!(matches!(build_set_cap_current_cmd(f32::NAN), Err(InvalidValue::NotFinite(_)))); + // The limits themselves are accepted. + let hi = build_set_cap_current_cmd(CAP_CURRENT_MAX_A).unwrap(); + assert_eq!(f32::from_le_bytes([hi[5], hi[6], hi[7], hi[8]]), CAP_CURRENT_MAX_A); + assert!(checksum_ok(&hi)); + assert!(build_set_cap_current_cmd(0.0).is_ok()); + } + + #[test] + fn setpoint_rejects_values_that_are_not_numbers() { + assert!(matches!(build_set_setpoint_cmd(f32::NAN), Err(InvalidValue::NotFinite(_)))); + assert_eq!( + build_set_setpoint_cmd(f32::INFINITY), + Err(InvalidValue::NotFinite(f32::INFINITY)) + ); + assert_eq!(build_set_setpoint_cmd(-0.5), Err(InvalidValue::Negative(-0.5))); + assert!(build_set_setpoint_cmd(SETPOINT_MAX + 1.0).is_err()); + assert!(build_set_setpoint_cmd(SETPOINT_MAX).is_ok()); + assert!(build_set_setpoint_cmd(0.0).is_ok()); + } + + #[test] + fn cap_current_read_command_checksum() { + assert_eq!(CMD_GET_CAP_CURRENT, [0xAF, 0x07, 0x03, 0x0A, 0x00, 0x3D]); + assert!(checksum_ok(&CMD_GET_CAP_CURRENT)); + } + + /// Real response captured from the device with its current set to 5000 mA. + /// Note the device quantises to milliamps, so 5.0 comes back as 5.0000010 — + /// readback must not be compared for exact equality. + #[test] + fn parse_cap_current_from_device_response() { + let resp = [0xDF, 0x07, 0x03, 0x0A, 0x04, 0x02, 0x00, 0xA0, 0x40, 0x27]; + let amps = parse_cap_current(&resp).expect("should parse"); + assert!((amps - 5.0).abs() < 1e-4, "got {amps}"); + } + + #[test] + fn parse_cap_current_rejects_other_packets() { + // Status packet header — must not be mistaken for a CAP current reply. + assert!(parse_cap_current(&[0xDF, 0x07, 0x03, 0x08, 0x16, 0, 0, 0, 0, 0]).is_none()); + // Acknowledgement of the set command, not the read reply. + assert!(parse_cap_current(&[0xDF, 0x07, 0x03, 0x05, 0x01, 0x00, 0x11]).is_none()); + assert!(parse_cap_current(&[]).is_none()); + // Real reply with one corrupted payload byte. + assert!(parse_cap_current(&[0xDF, 0x07, 0x03, 0x0A, 0x04, 0x03, 0x00, 0xA0, 0x40, 0x27]).is_none()); + } + + #[test] + fn build_mode_cmd_checksum() { + let cmd = build_mode_cmd(Mode::CC); + assert_eq!(cmd, vec![0xAF, 0x07, 0x03, 0x03, 0x01, 0x01, 0x42]); + assert!(checksum_ok(&cmd)); + assert!(checksum_ok(&build_mode_cmd(Mode::CV))); + } + + #[test] + fn build_setpoint_10_matches_hci() { + let cmd = build_set_setpoint_cmd(10.0).unwrap(); + assert_eq!(cmd, vec![0xAF, 0x07, 0x03, 0x04, 0x04, 0x00, 0x00, 0x20, 0x41, 0xDE]); + } + + #[test] + fn mode_from_byte_round_trip() { + for m in [Mode::CC, Mode::CV, Mode::CR, Mode::CP, Mode::CAP, Mode::DCR] { + assert_eq!(Mode::from_byte(m as u8), Some(m)); + } + } + + #[test] + fn mode_labels() { + assert_eq!(Mode::CC.to_string(), "CC"); + assert_eq!(Mode::DT.as_str(), "POW [DT]"); + assert_eq!(Mode::from_byte(0x05), None); + } + + /// Real CC-mode status from the HCI capture (20+8 byte fragments concatenated). + const HCI_CC_STATUS: &str = "df07030816010089acff4000000000000000000e0fb0419a99993e6c"; + + #[test] + fn parse_status_from_hci_log() { + let s = parse_status_packet(&hex_to_bytes(HCI_CC_STATUS)).expect("valid packet"); + assert_eq!(s.mode_byte, 0x01); + assert_eq!(s.mode(), Some(Mode::CC)); + assert!(!s.load_on); + assert!((s.voltage - 7.99).abs() < 0.1); + assert!((s.setpoint - 0.3).abs() < 0.01); + assert!((s.temperature - 22.0).abs() < 1.0); + assert_eq!(s.warning, None); + } + + /// DCR result from the real device (HW:2.0 / SW:1.7) on a Li-ion cell, right after + /// the test stopped: I1 = 25 mA, I2 = 1000 mA, R = 173.15 mΩ. The voltage drop between + /// the two test currents (4.1693 V at 0.0248 A, 3.9998 V at 1.0013 A) gives 173.6 mΩ, + /// which is how the field is known to be in milliohms, not Ohms. + #[test] + fn parse_dcr_status_from_device() { + let mut data = hex_to_bytes( + "df07030816\ + 0a006571854000000000cdcccc3c0000803fcc252d43\ + 00", + ); + data.truncate(STATUS_LEN - 1); + data.push(checksum(&data)); + let s = parse_status_packet(&data).expect("valid packet"); + assert_eq!(s.mode(), Some(Mode::DCR)); + assert!(!s.load_on); + assert!((s.voltage - 4.1701).abs() < 1e-3); + assert!((s.dcr_i1 - 0.025).abs() < 1e-6); + assert!((s.dcr_i2 - 1.0).abs() < 1e-6); + assert!((s.dcr_mohm - 173.15).abs() < 0.01, "got {}", s.dcr_mohm); + assert_eq!(s.runtime_s, 0); + assert_eq!(s.temperature, 0.0, "DCR packets carry no temperature"); + } + + #[test] + fn status_with_bad_checksum_is_rejected() { + let mut data = hex_to_bytes(HCI_CC_STATUS); + data[8] ^= 0x01; // flip one bit of the voltage + assert_eq!(parse_status_packet(&data), Err(ParseError::Checksum)); + } + + #[test] + fn status_with_wrong_header_or_length_is_rejected() { + let mut data = hex_to_bytes(HCI_CC_STATUS); + data[3] = 0x0A; + assert_eq!( + parse_status_packet(&data), + Err(ParseError::WrongHeader([0xDF, 0x07, 0x03, 0x0A])) + ); + let data = hex_to_bytes(HCI_CC_STATUS); + assert_eq!(parse_status_packet(&data[..20]), Err(ParseError::WrongLength(20))); + } + + #[test] + fn status_warning_is_decoded() { + // CC with the protection flag (b5 bits 1+2) and code 0x6 (reverse) in b6. + let mut data = hex_to_bytes(HCI_CC_STATUS); + data[5] = 0x01 | B5_WARN_FLAG; + data[6] = 0x60; + data[27] = 0; + data[27] = checksum(&data); + let s = parse_status_packet(&data).expect("valid packet"); + assert_eq!(s.mode(), Some(Mode::CC)); + assert_eq!(s.warning, Some(Warning::Reverse)); + assert!(!s.ready); + assert_eq!(s.warning.unwrap().to_string(), "REV"); + assert_eq!(Warning::from_code(0x9).to_string(), "UVP"); + assert_eq!(Warning::from_code(0xB).to_string(), "PROT B"); + } + + #[test] + fn parse_firmware_version_real_device() { + // Real init response observed in HCI log: DF FF FF 00 02 07 03 17 + // HW data[4]=0x02: low nibble=2 (major), high nibble=0 (minor) → HW 2.0 + // SW data[7]=0x17: high nibble=1 (major), low nibble=7 (minor) → SW 1.7 + let pkt = [0xDF, 0xFF, 0xFF, 0x00, 0x02, 0x07, 0x03, 0x17]; + let v = parse_firmware_version(&pkt).expect("should parse"); + assert_eq!( + v, + FirmwareVersion { hw_major: 2, hw_minor: 0, sw_major: 1, sw_minor: 7 } + ); + assert_eq!(v.to_string(), "HW:2.0 SW:1.7"); + } + + #[test] + fn parse_firmware_version_rejects_short() { + assert_eq!(parse_firmware_version(&[0xDF, 0xFF, 0xFF]), None); + } + + #[test] + fn parse_firmware_version_rejects_wrong_header_or_checksum() { + let status_pkt = [0xDF, 0x07, 0x03, 0x08, 0x00, 0x00, 0x00, 0x00]; + assert_eq!(parse_firmware_version(&status_pkt), None); + let corrupted = [0xDF, 0xFF, 0xFF, 0x00, 0x02, 0x07, 0x03, 0x18]; + assert_eq!(parse_firmware_version(&corrupted), None); + } + + fn hex_to_bytes(s: &str) -> Vec { + (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i+2], 16).unwrap()).collect() + } +} diff --git a/docs/BT_PROTOCOL.md b/docs/BT_PROTOCOL.md index 6796666..b2dbc3c 100644 --- a/docs/BT_PROTOCOL.md +++ b/docs/BT_PROTOCOL.md @@ -1,14 +1,12 @@ # EL15 Bluetooth LE Protocol -This document is a Rust-side mirror of the protocol implementation in -[`maj113/DM40GUI`](https://github.com/maj113/DM40GUI), specifically: +The protocol was reverse-engineered from the Bluetooth traffic of ALIENTEK's official +Android app, **ATK-xTOOL** (HCI captures), and cross-checked against the Python project +[`maj113/DM40GUI`](https://github.com/maj113/DM40GUI). Commands beyond the app's +everyday use (e.g. the CAP discharge current) were found and verified on a real device. -- [`el15/protocol_constants.py`](https://github.com/maj113/DM40GUI/blob/master/el15/protocol_constants.py) -- [`el15/app.py`](https://github.com/maj113/DM40GUI/blob/master/el15/app.py) - -The protocol was **extended using reverse-engineered commands**. - -The Rust port lives in [el15-bt/src/protocol.rs](../el15-bt/src/protocol.rs). +The Rust implementation is the [`alientek-el15`](../alientek-el15/README.md) crate: +[alientek-el15/src/protocol.rs](../alientek-el15/src/protocol.rs). ## Transport @@ -17,13 +15,13 @@ The Rust port lives in [el15-bt/src/protocol.rs](../el15-bt/src/protocol.rs). 0000fff0-0000-1000-8000-00805f9b34fb - This is exported as `el15_bt::EL15_SERVICE_UUID`. On Linux/Windows it is + This is exported as `alientek_el15::SERVICE_UUID`. On Linux/Windows it is used as a BLE scan filter; on macOS CoreBluetooth does not match this UUID in passive scan so discovery falls back to device-name prefix matching (`EL15`, `ATK-PTEL15`, `ALIENTEK`, etc.). - The service exposes three characteristics: `FFF1`, `FFF2`, `FFF3`. In - practice `FFF1` carries both WRITE + NOTIFY properties, so `el15-bt` uses + practice `FFF1` carries both WRITE + NOTIFY properties, so `alientek-el15` uses it for bidirectional communication. The DM40GUI Python code takes the same approach: discover and use whichever char has WRITE+NOTIFY under the `0xFFF0` service. @@ -43,7 +41,7 @@ The Rust port lives in [el15-bt/src/protocol.rs](../el15-bt/src/protocol.rs). The checksum is computed as `(0 - sum_of_preceding_bytes) & 0xFF`. Without a valid checksum, the device responds with error code `0x06` in the ACK. -Implementation: `el15_bt::checksum(data: &[u8]) -> u8`. +Implementation: `alientek_el15::checksum(data: &[u8]) -> u8`. ## Command pacing (required) @@ -52,8 +50,10 @@ uses it. That has **no flow control**: commands written back-to-back are silently dropped, with no error reported to the host. Leave at least **120 ms** between consecutive commands -(`el15_bt::INTER_COMMAND_GAP`). Use `Device::send_sequence()` for any burst -rather than consecutive `send()` calls. +(`alientek_el15::INTER_COMMAND_GAP`). Since `alientek-el15` 0.1.0, `Device::send` +enforces this itself: it waits until 120 ms have passed since the previous write +from any task, so `send()`, `send_sequence()` and `init_handshake()` are all paced. +A client that writes frames over its own link must do the same. Measured on HW:2.0 / SW:1.7 — three commands (set mode, set setpoint, set CAP current) sent with no gap: @@ -72,6 +72,26 @@ like a UI that needs several button presses before a command "takes". The poll timer must also be held off for the duration of a burst, otherwise the periodic poll becomes one more back-to-back write (`AppState::pause_ticks_for`). +With the library pacing every write the poll can no longer be dropped, but it +still delays the burst by one gap. + +Re-measured on HW:2.0 / SW:1.7 (macOS, load off), 6 trials per row: + +| Sequence | Gap | Commands that took effect | ACKs received | +| -------------------------------------------- | ------ | ---------------------------------- | ------------- | +| set mode CAP, set setpoint, set CAP current | 0 ms | mode 2/6, CAP current 6/6 | 9/18 | +| | 30 ms | mode 5/6, CAP current 6/6 | 12/18 | +| | 60 ms | mode 6/6, CAP current 6/6 | 13/18 | +| | 120 ms | mode 6/6, CAP current 6/6 | 18/18 | +| same, through the library's paced `send()` | (≈125 ms) | mode 6/6, CAP current 6/6 | 18/18 | +| set mode CC↔CV, set CAP current | 0–120 ms | 6/6 at every gap | all | +| poll, read CAP current (read-only) | 0–120 ms | 20/20 at every gap | — | +| init, info (`init_handshake`) | 0–120 ms | 15/15 at every gap | — | + +Losses need three writes in a row; read-only queries were never lost. ACKs go +missing even when every command took effect (60 ms row), so a missing ACK proves +nothing — confirm with a readback. Over 300 paced polls every status packet +arrived as one 28-byte notification with a valid checksum. ## Connection Handshake @@ -86,7 +106,7 @@ the init sequence to wake the device from dormant state: Without this handshake the device reports zeros for temperature, setpoint, and runtime in status packets. -Implementation: `El15Device::init_handshake()`. +Implementation: `Device::init_handshake()`. ## Frames @@ -127,7 +147,7 @@ Observed from HCI log: `DF FF FF 00 02 07 03 17` | 5–6 | `07 03`| reserved | Protocol version or device sub-type | | 7 | `17` | sw_byte | Normal BCD: major = high nibble, minor = low nibble. `0x17` → SW 1.7. Also satisfies checksum (sum of all 8 bytes ≡ 0 mod 256) | -Implementation: `el15_bt::parse_firmware_version(data)` → `Some("HW:2.0 SW:1.7")` for the example above. +Implementation: `alientek_el15::parse_firmware_version(data)` → `Some(FirmwareVersion { hw_major: 2, hw_minor: 0, sw_major: 1, sw_minor: 7 })` for the example above, displayed as `HW:2.0 SW:1.7`. A packet with a wrong checksum gives `None`. > **Implementation note:** btleplug uses an internal `broadcast::channel` for notifications. The > notification stream receiver must be obtained (via `peripheral.notifications().await`) *before* @@ -139,7 +159,10 @@ Implementation: `el15_bt::parse_firmware_version(data)` → `Some("HW:2.0 SW:1.7 `DF 07 03 07 ` -Observed: `DF 07 03 07 0A 45 4C 31 35 00 00 00 00 00 00 0F` +Observed (official app's capture): `DF 07 03 07 0A 45 4C 31 35 00 00 00 00 00 00 0F` + +The name is whatever was last written with `0x06` (see the command map notes); it is +not necessarily `EL15`. | Byte | Value | Field | Notes | | ------ | ------ | ----------- | --------------------------------------------------- | @@ -195,7 +218,7 @@ Observed: `DF 07 03 07 0A 45 4C 31 35 00 00 00 00 00 00 0F` | 11..15 | current | f32 | Amps (CC/CV/CR/CP) | | 15..19 | runtime | f32 | Seconds (or DCR I1 current in DCR mode) | | 19..23 | varies | f32 | Temperature (°C) for CC/CV/CR/CP, energy (Wh×1000) for CAP, DCR I2 | -| 23..27 | varies | f32 | Setpoint for CC/CV/CR/CP, capacity (Ah×1000) for CAP, DCR resistance (Ω) | +| 23..27 | varies | f32 | Setpoint for CC/CV/CR/CP, capacity (Ah×1000) for CAP, DCR resistance (mΩ) | | 27 | checksum | u8 | Sum of all 28 bytes ≡ 0 (mod 256) | ### Mode-specific field interpretation @@ -204,7 +227,7 @@ Observed: `DF 07 03 07 0A 45 4C 31 35 00 00 00 00 00 00 0F` | ------- | ---------------- | ----------------- | ------------------ | | CC/CV/CR/CP | runtime (s) | temperature (°C) | setpoint (mode unit)| | CAP | runtime (s) | energy (Wh×1000) | capacity (Ah×1000) | -| DCR | I1 current (A) | I2 current (A) | resistance (Ω) | +| DCR | I1 current (A) | I2 current (A) | resistance (mΩ) | ### Warning codes (byte6 high nibble when bit1+bit2 of byte5 are set) @@ -216,12 +239,12 @@ Observed: `DF 07 03 07 0A 45 4C 31 35 00 00 00 00 00 00 0F` ## DeviceEvent variants -The `el15-bt` library emits these events from the notification stream: +The `alientek-el15` library emits these events from the notification stream: | Variant | Trigger | | ---------------------------- | ----------------------------------------------------- | -| `Status(EL15Status)` | Any 28-byte notification with header `DF 07 03 08` | -| `FirmwareVersion(String)` | Init response with header `DF FF FF`; parsed by `parse_firmware_version` | +| `Status(Status)` | 28-byte notification with header `DF 07 03 08` and a valid checksum; `parse_status_packet` returns a `ParseError` otherwise and the packet only appears as `RawNotification` | +| `FirmwareVersion(FirmwareVersion)` | Init response with header `DF FF FF`; parsed by `parse_firmware_version` | | `CapCurrent(f32)` | CAP discharge-current reply `DF 07 03 0A 04 `, in Amps | | `RawNotification(Vec)` | Every notification, unfiltered (for debugging) | | `Disconnected` | GATT notification stream ends | @@ -269,7 +292,7 @@ means *read*, `len > 0` means *write*. | `0x03` | — | `len=1` mode | set mode | | `0x04` | — | `len=4` f32 | set setpoint (CC/CV/CR/CP only) | | `0x05` | code `04` | `len=4` f32 A | **set CAP discharge current** | -| `0x06` | code `04` | **only `len=10`** | **unidentified** (see notes) | +| `0x06` | code `04` | **only `len=10`** | **set device name** (see notes) | | `0x07` | device name | — | info | | `0x08` | 28-byte status | — | poll | | `0x09` | — | `len=1` | load on / off / lock | @@ -294,13 +317,19 @@ Acknowledgement status byte (`DF 07 03 01 `): the CAP cutoff these are front-panel settings (manual §3.4.2 "DCR Params"). They **are** readable: in DCR mode status bytes 15..19 and 19..23 carry I1 and I2 in Amps, so the app displays them read-only. -- **`0x06` takes a 10-byte payload — purpose unknown.** A length sweep found - that `0x06` rejects every payload length (code `04`) *except* 10, which is - acknowledged with status `00`. Three plausible 10-byte layouts were tried - (`f32 A + f32 A + u16`, `f32 mA + f32 mA + u16`, `u16 mA + u16 mA + u16 + pad`) - and none changed the reported DCR currents. It remains the best candidate for - a DCR- or CAP-parameter block, but it is **not** identified — do not guess at - it in code. +- **`0x06` sets the device name** — the 10-byte field that `0x07` (info) reads + back. A length sweep had found that `0x06` rejects every payload length (code + `04`) except 10. Three 10-byte layouts tried as DCR parameters (`f32 A + f32 A + + u16`, `f32 mA + f32 mA + u16`, `u16 mA + u16 mA + u16 + pad`) changed nothing + visible, but afterwards `0x07` returned `0A 14 00 00 00 00 00 00 00 00` — the + `u16 20 mA` probe stored as the name. Writing + `AF 07 03 06 0A 45 4C 31 35 00 00 00 00 00 00 40` ("EL15", NUL-padded) was + acknowledged with `DF 07 03 06 01 00 10`, and `0x07` then returned + `DF 07 03 07 0A 45 4C 31 35 00 00 00 00 00 00 0F`, byte-identical to the official + app's capture. Verified on HW:2.0 / SW:1.7. The name the BLE module **advertises** + (`_BLE` on the test unit) did not change on reconnect; whether it follows after a + power cycle is not known. The library has no builder for this command: probing it + with arbitrary payloads overwrites the name. - **CAP cutoff voltage and timer are not available over BLE.** Every opcode was probed; none reads or writes them. They are front-panel settings (manual §3.4.2 "CAP Params") and the protocol has no equivalent. The app must not @@ -322,13 +351,19 @@ Acknowledgement status byte (`DF 07 03 01 `): Commands go to handle `0x0009`, notifications arrive on `0x0006`. A 28-byte status notification fragments as 20+8 on Android, and the 8-byte tail can begin with `AF` by coincidence, which looks exactly like a command. -- **Characteristics:** the official Android app writes to `FFF3` and subscribes - to `FFF2`. This client uses `FFF1` for both, which the device also accepts — - `Device::connect` picks the first writable/notifying characteristic on the - `FFF0` service rather than a fixed UUID. No command has been found that works - on one characteristic but not the other. +- **Characteristics:** the device exposes, under service `FFF0`, `FFF1` + (write without response + notify), `FFF2` (read + notify) and `FFF3` (write + without response). The official Android app writes to `FFF3` and subscribes to + `FFF2`. This client uses `FFF1` for both, which the device also accepts. + `Device::connect` prefers `FFF1`, falls back to another characteristic of the + `FFF0` service with the needed property, and never uses a characteristic of + another service (it fails with `CharacteristicNotFound`). No command has been + found that works on one characteristic but not the other. - **DCR mode** auto-stops after measurement completes. The `dcr_mohm` field - reports resistance in **Ohms** (not milliohms despite the field name). + (bytes 23..27, f32) reports resistance in **milliohms**. Measured on a Li-ion + cell with I1 = 25 mA and I2 = 1000 mA: 4.1693 V at 0.0248 A and 3.9998 V at + 1.0013 A give ΔV/ΔI = 0.1736 Ω = 173.6 mΩ; the device reported `173.15`. + The field keeps the previous result until a test completes. - **Android BLE MTU:** On Android, 28-byte status notifications may arrive fragmented as 20+8 byte chunks. On macOS, they arrive as a single 28-byte notification. diff --git a/docs/GUI_DESIGN.md b/docs/GUI_DESIGN.md index 6e0a298..0c45268 100644 --- a/docs/GUI_DESIGN.md +++ b/docs/GUI_DESIGN.md @@ -60,7 +60,10 @@ Right side — three stacked info cells (mode-dependent): |------|--------|--------|--------| | CC/CV/CR/CP | Run Time | Temp (°C) | **Editable setpoint** | | CAP | Run Time | Capacity (Ah) | Energy (Wh) | -│ DCR | Run Time | Temp (°C) | Resistance (mΩ) | +| DCR | Run Time | Temp (°C), always "---" | Resistance (mΩ) | + +DCR status packets carry the two test currents where other modes carry the temperature, so +there is no temperature reading in DCR; the card shows "---" rather than a false 0.00 °C. ### 3. Mode/Output Row - Mode buttons: CC, CV, CR, CP, (spacer), CAP, DCR diff --git a/docs/SCPI_PROTOCOL.md b/docs/SCPI_PROTOCOL.md index 78f0bee..558d0d0 100644 --- a/docs/SCPI_PROTOCOL.md +++ b/docs/SCPI_PROTOCOL.md @@ -31,6 +31,7 @@ the *RIGOL DL3000 Series Programmable DC Electronic Load Programming Manual* | `MEAS:CURR?` | Q | Latest status `current` | | `MEAS:POW?` | Q | Latest `voltage * current` | | `MEAS:RES?` | Q | `voltage / current` | +| `MEAS:DCR?` | Q | Last DCR result in **Ohms** (device reports mΩ) | | `SYST:TEMP?` / `SYST:FAN?` | Q | Status temperature / fan speed | Unknown queries return `-113,"Undefined header"` (SCPI standard). diff --git a/el15-app/Cargo.toml b/el15-app/Cargo.toml index e8054e1..bd73bc8 100644 --- a/el15-app/Cargo.toml +++ b/el15-app/Cargo.toml @@ -4,6 +4,9 @@ version.workspace = true edition.workspace = true authors.workspace = true license.workspace = true +repository.workspace = true +# Released as binaries on GitHub, not on crates.io. +publish = false description = "EL15 controller — iced GUI by default, CLI with --no-gui" [[bin]] @@ -11,7 +14,7 @@ name = "el15" path = "src/main.rs" [dependencies] -el15-bt = { path = "../el15-bt" } +alientek-el15 = { path = "../alientek-el15", version = "0.1" } el15-scpi = { path = "../el15-scpi" } clap.workspace = true diff --git a/el15-app/src/cli_run.rs b/el15-app/src/cli_run.rs index 45ae2ca..0d25370 100644 --- a/el15-app/src/cli_run.rs +++ b/el15-app/src/cli_run.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use std::time::Duration; use anyhow::{Context, Result}; -use el15_bt::{ +use alientek_el15::{ build_mode_cmd, build_set_setpoint_cmd, scan_devices, Device, DeviceEvent, Mode, CMD_LOAD_OFF, CMD_LOAD_ON, CMD_LOCK, }; @@ -202,17 +202,18 @@ async fn run_debug_shell(args: &Cli) -> Result<()> { match ev { DeviceEvent::Status(s) => { let extra = if s.mode_byte == 0x0A { - format!(" DCR: I1={:.1}mA I2={:.1}mA R={:.1}Ω", s.dcr_i1 * 1000.0, s.dcr_i2 * 1000.0, s.dcr_mohm) + format!(" DCR: I1={:.1}mA I2={:.1}mA R={:.1}mΩ", s.dcr_i1 * 1000.0, s.dcr_i2 * 1000.0, s.dcr_mohm) } else if s.mode_byte == 0x02 { format!(" CAP: {:.3}Ah {:.3}Wh", s.capacity_ah, s.energy_wh) } else { - format!(" set={:.4}{}", s.setpoint, s.setpoint_unit) + format!(" set={:.4}{}", s.setpoint, s.mode().map_or("", |m| m.setpoint_info().0)) }; println!( " << STATUS: V={:.4} I={:.4} P={:.4} mode={} load={} fan={} T={:.1}°C rt={}s{} warn=\"{}\"", s.voltage, s.current, s.power, - s.mode_name, s.load_on, s.fan_speed, - s.temperature, s.runtime_s, extra, s.warning, + s.mode().map_or("?", Mode::as_str), s.load_on, s.fan_speed, + s.temperature, s.runtime_s, extra, + s.warning.map(|w| w.to_string()).unwrap_or_default(), ); } DeviceEvent::RawNotification(data) => { @@ -316,13 +317,13 @@ async fn run_debug_shell(args: &Cli) -> Result<()> { } "set" | "s" => { match arg.parse::() { - Ok(v) => { - let cmd_bytes = build_set_setpoint_cmd(v); - match dev.send(&cmd_bytes).await { + Ok(v) => match build_set_setpoint_cmd(v) { + Ok(cmd_bytes) => match dev.send(&cmd_bytes).await { Ok(()) => println!(" >> SETPOINT {v} sent ({:02x?})", cmd_bytes), Err(e) => println!(" !! send failed: {e}"), - } - } + }, + Err(e) => println!(" !! invalid setpoint: {e}"), + }, Err(_) => println!(" !! invalid float: {arg}"), } } @@ -343,7 +344,7 @@ async fn run_debug_shell(args: &Cli) -> Result<()> { println!(" Device: {}", info.display_label()); println!(" Address: {}", info.address); println!(" ID: {}", info.id); - println!(" Service UUID: {}", el15_bt::EL15_SERVICE_UUID); + println!(" Service UUID: {}", alientek_el15::SERVICE_UUID); println!(" Write char: {}", dev.write_char_uuid()); println!(" Notify char: {}", dev.notify_char_uuid()); } diff --git a/el15-app/src/gui.rs b/el15-app/src/gui.rs index 74f9121..22b274d 100644 --- a/el15-app/src/gui.rs +++ b/el15-app/src/gui.rs @@ -29,9 +29,9 @@ use tokio_stream::StreamExt; use tokio_stream::wrappers::UnboundedReceiverStream; use tracing::{debug, info, warn}; -use el15_bt::{ +use alientek_el15::{ build_mode_cmd, build_set_cap_current_cmd, build_set_setpoint_cmd, scan_devices, - scan_for_device, Device, DeviceEvent, DeviceInfo, EL15Status, Mode, CAP_CURRENT_MAX_A, + scan_for_device, Device, DeviceEvent, DeviceInfo, Mode, Status, CAP_CURRENT_MAX_A, CMD_GET_CAP_CURRENT, CMD_LOAD_OFF, CMD_LOAD_ON, INTER_COMMAND_GAP, }; @@ -217,7 +217,7 @@ pub struct AppState { selected_device: Option, device: Option>, connecting: bool, - last_status: Option, + last_status: Option, samples: VecDeque, setpoint_input: String, @@ -476,8 +476,8 @@ impl AppState { if let Some(dev) = self.device.clone() { info!("retrying mode switch to {:?} (elapsed {}ms)", target, secs); let mut frames = vec![build_mode_cmd(target.to_proto())]; - if let Some(sp) = stored_setpoint(&self.settings, target) { - frames.push(build_set_setpoint_cmd(sp)); + if let Some(f) = stored_setpoint(&self.settings, target).and_then(setpoint_frame) { + frames.push(f); } self.pause_poll_ticks = self.pause_ticks_for(frames.len()); return Task::perform( @@ -667,7 +667,8 @@ impl AppState { // commands. Without this the load button appears to do nothing // after a reconnect until the user manually clicks a mode button. let mode = self.settings.last_mode.to_proto(); - let setpoint = stored_setpoint(&self.settings, self.settings.last_mode); + let setpoint = stored_setpoint(&self.settings, self.settings.last_mode) + .and_then(setpoint_frame); return Task::perform( async move { let _ = d.init_handshake().await; @@ -677,8 +678,8 @@ impl AppState { // application-level commands. tokio::time::sleep(Duration::from_millis(500)).await; let _ = d.send(&build_mode_cmd(mode)).await; - if let Some(sp) = setpoint { - let _ = d.send(&build_set_setpoint_cmd(sp)).await; + if let Some(frame) = setpoint { + let _ = d.send(&frame).await; } Message::Noop }, @@ -742,9 +743,10 @@ impl AppState { self.trim_samples(now); // Reuse the previous sample's mode allocation — the name // only changes on an actual mode switch. + let mode_name = st.mode().map_or("?", Mode::as_str); let mode = match self.samples.back() { - Some(prev) if *prev.mode == *st.mode_name => Arc::clone(&prev.mode), - _ => Arc::from(st.mode_name.as_str()), + Some(prev) if *prev.mode == *mode_name => Arc::clone(&prev.mode), + _ => Arc::from(mode_name), }; self.samples.push_back(Sample { when: now, @@ -779,11 +781,11 @@ impl AppState { self.settings.last_mode = device_mode; } } - self.last_command_ok = st.warning.is_empty(); + self.last_command_ok = st.warning.is_none(); self.last_status = Some(st); } DeviceEvent::FirmwareVersion(ver) => { - self.firmware_version = Some(ver); + self.firmware_version = Some(ver.to_string()); } DeviceEvent::CapCurrent(amps) => { debug!("device CAP discharge current: {amps} A"); @@ -828,8 +830,8 @@ impl AppState { self.pause_poll_ticks = 3; let mut frames = vec![build_mode_cmd(mk.to_proto())]; // Also send the stored setpoint so device uses our value. - if let Some(sp) = stored_setpoint(&self.settings, mk) { - frames.push(build_set_setpoint_cmd(sp)); + if let Some(f) = stored_setpoint(&self.settings, mk).and_then(setpoint_frame) { + frames.push(f); } // CAP's discharge current never appears in the status // packet, so it must be requested explicitly to be shown. @@ -869,10 +871,10 @@ impl AppState { info!("apply setpoint {} for mode {:?}", value, mode); store_setpoint(&mut self.settings, mode, value); let _ = settings::save(&self.settings); - if let Some(dev) = self.device.clone() { + if let (Some(dev), Some(frame)) = (self.device.clone(), setpoint_frame(value)) { return Task::perform( async move { - let _ = dev.send(&build_set_setpoint_cmd(value)).await; + let _ = dev.send(&frame).await; Message::Noop }, |m| m, @@ -904,8 +906,8 @@ impl AppState { } Err(_) => stored_setpoint(&self.settings, mode), }; - if let Some(sp) = sp { - frames.push(build_set_setpoint_cmd(sp)); + if let Some(f) = sp.and_then(setpoint_frame) { + frames.push(f); } } // CAP has its own opcode. Sending the ordinary @@ -914,8 +916,8 @@ impl AppState { // wasting a slot in the burst and costing the load // command its turn. ModeKind::CAP => { - if let Ok(a) = self.settings.cap.current_input.parse::() { - frames.push(build_set_cap_current_cmd(a)); + if let Some(f) = self.settings.cap.current_input.parse::().ok().and_then(cap_current_frame) { + frames.push(f); } } // DCR takes its parameters from the front panel. @@ -1235,15 +1237,16 @@ impl AppState { return Task::none(); }; let amps = amps.clamp(0.0, CAP_CURRENT_MAX_A); + // NaN survives the clamp; the builder refuses it. + let Some(cap_frame) = cap_current_frame(amps) else { + return Task::none(); + }; self.settings.cap.current_input = format!("{amps:.3}"); let _ = settings::save(&self.settings); if let Some(dev) = self.device.clone() { // Write, then read straight back: the device quantises to // milliamps, so the stored value is the truth. - let frames = vec![ - build_set_cap_current_cmd(amps), - CMD_GET_CAP_CURRENT.to_vec(), - ]; + let frames = vec![cap_frame, CMD_GET_CAP_CURRENT.to_vec()]; self.pause_poll_ticks = self.pause_ticks_for(frames.len()); return Task::perform( async move { @@ -1313,10 +1316,10 @@ impl AppState { let value = clamp_setpoint(mode, value); store_setpoint(&mut self.settings, mode, value); let _ = settings::save(&self.settings); - if let Some(dev) = self.device.clone() { + if let (Some(dev), Some(frame)) = (self.device.clone(), setpoint_frame(value)) { return Task::perform( async move { - let _ = dev.send(&build_set_setpoint_cmd(value)).await; + let _ = dev.send(&frame).await; Message::Noop }, |m| m, @@ -1467,12 +1470,16 @@ impl AppState { Space::new().width(12.0), text(format!("{}: {}/5", t!("label.fan"), st.fan_speed)).size(13), Space::new().width(12.0), - text(format!("{}: {}", t!("label.mode"), if st.mode_name.is_empty() { "---".into() } else { st.mode_name.clone() })).size(13), + text(format!("{}: {}", t!("label.mode"), st.mode().map_or("---", Mode::as_str))).size(13), Space::new().width(12.0), text(format!("{}: {}", t!("label.dev_versions"), self.firmware_version.as_deref().unwrap_or("---"))).size(13), Space::new().width(Length::Fill), - indicator(if st.warning.is_empty() && self.last_command_ok { "OK" } else if !st.warning.is_empty() { st.warning.as_str() } else { "ERR" }, - if st.warning.is_empty() && self.last_command_ok { COLOR_LOAD_ON } else { COLOR_CURRENT }), + indicator(&match st.warning { + Some(w) => w.to_string(), + None if self.last_command_ok => "OK".to_string(), + None => "ERR".to_string(), + }, + if st.warning.is_none() && self.last_command_ok { COLOR_LOAD_ON } else { COLOR_CURRENT }), Space::new().width(12.0), badge( &load_label, @@ -1824,7 +1831,7 @@ impl AppState { .into() } - fn right_panel(&self, st: &EL15Status) -> Element<'_, Message> { + fn right_panel(&self, st: &Status) -> Element<'_, Message> { let runtime_secs = st.runtime_s; let runtime = format!( "{:02}:{:02}:{:02}", @@ -1852,7 +1859,9 @@ impl AppState { column![runtime_card, cap_card, energy_card].spacing(6).into() } ModeKind::DCR => { - let temp_card = info_card(&lbl_temperature, &format!("{:.2} °C", st.temperature)); + // DCR packets carry the test currents where the temperature + // usually is; there is no reading to show. + let temp_card = info_card(&lbl_temperature, "---"); let dcr_card = info_card(&lbl_resistance, &format!("{:.1} mΩ", st.dcr_mohm)); column![runtime_card, temp_card, dcr_card].spacing(6).into() } @@ -2719,6 +2728,20 @@ fn store_setpoint(s: &mut Settings, mode: ModeKind, value: f32) { } } +/// The setpoint frame, or `None` (logged) for a value the device must not get. +fn setpoint_frame(value: f32) -> Option> { + build_set_setpoint_cmd(value) + .map_err(|e| warn!("not sending setpoint: {e}")) + .ok() +} + +/// The CAP discharge-current frame, or `None` (logged) for a value the device must not get. +fn cap_current_frame(amps: f32) -> Option> { + build_set_cap_current_cmd(amps) + .map_err(|e| warn!("not sending CAP current: {e}")) + .ok() +} + fn clamp_setpoint(mode: ModeKind, v: f32) -> f32 { let (lo, hi) = setpoint_range(mode); v.max(lo).min(hi) @@ -3236,9 +3259,9 @@ mod tests { assert!(stored_setpoint(&settings, ModeKind::DCR).is_none()); // The CAP parameter frame must be the 0x05 opcode, not 0x04. - let cap_frame = build_set_cap_current_cmd(5.0); + let cap_frame = build_set_cap_current_cmd(5.0).unwrap(); assert_eq!(cap_frame[3], 0x05); - let setpoint_frame = build_set_setpoint_cmd(5.0); + let setpoint_frame = build_set_setpoint_cmd(5.0).unwrap(); assert_eq!(setpoint_frame[3], 0x04); assert_ne!(cap_frame, setpoint_frame); } @@ -3297,10 +3320,8 @@ mod tests { state.pending_mode_switch = Some((ModeKind::CP, std::time::Instant::now())); // Incoming status packet still reports CC — should be ignored. - let mut st = EL15Status { - valid: true, + let mut st = Status { mode_byte: 0x01, // CC - mode_name: "CC".to_string(), ..Default::default() }; let _ = state.update(Message::DeviceEvent(DeviceEvent::Status(st.clone()))); @@ -3310,7 +3331,6 @@ mod tests { // Now device confirms CP mode. st.mode_byte = 0x19; // CP - st.mode_name = "CP".to_string(); let _ = state.update(Message::DeviceEvent(DeviceEvent::Status(st))); // Pending should be cleared. assert!(state.pending_mode_switch.is_none()); diff --git a/el15-app/src/logging.rs b/el15-app/src/logging.rs index 41e92ad..3107622 100644 --- a/el15-app/src/logging.rs +++ b/el15-app/src/logging.rs @@ -11,7 +11,7 @@ pub fn init(verbose: u8, log_file: Option<&Path>, verbose_ble: bool, verbose_gui }; // Fine-grained verbose control if verbose_ble { - directives.push_str(",el15_bt=debug,btleplug=debug"); + directives.push_str(",alientek_el15=debug,btleplug=debug"); } if verbose_gui { directives.push_str(",el15_app::gui=debug"); diff --git a/el15-app/src/settings.rs b/el15-app/src/settings.rs index d159339..19ecbea 100644 --- a/el15-app/src/settings.rs +++ b/el15-app/src/settings.rs @@ -162,30 +162,30 @@ impl Default for DcrSettings { } } -/// Mirrors `el15_bt::Mode` but is Serde-stable across firmware tweaks. +/// Mirrors `alientek_el15::Mode` but is Serde-stable across firmware tweaks. #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[allow(clippy::upper_case_acronyms)] pub enum ModeKind { CC, CV, CR, CP, CAP, DCR } impl ModeKind { - pub fn to_proto(self) -> el15_bt::Mode { + pub fn to_proto(self) -> alientek_el15::Mode { match self { - ModeKind::CC => el15_bt::Mode::CC, - ModeKind::CV => el15_bt::Mode::CV, - ModeKind::CR => el15_bt::Mode::CR, - ModeKind::CP => el15_bt::Mode::CP, - ModeKind::CAP => el15_bt::Mode::CAP, - ModeKind::DCR => el15_bt::Mode::DCR, + ModeKind::CC => alientek_el15::Mode::CC, + ModeKind::CV => alientek_el15::Mode::CV, + ModeKind::CR => alientek_el15::Mode::CR, + ModeKind::CP => alientek_el15::Mode::CP, + ModeKind::CAP => alientek_el15::Mode::CAP, + ModeKind::DCR => alientek_el15::Mode::DCR, } } - pub fn from_proto(m: el15_bt::Mode) -> Option { + pub fn from_proto(m: alientek_el15::Mode) -> Option { Some(match m { - el15_bt::Mode::CC => ModeKind::CC, - el15_bt::Mode::CV => ModeKind::CV, - el15_bt::Mode::CR => ModeKind::CR, - el15_bt::Mode::CP => ModeKind::CP, - el15_bt::Mode::CAP => ModeKind::CAP, - el15_bt::Mode::DCR => ModeKind::DCR, + alientek_el15::Mode::CC => ModeKind::CC, + alientek_el15::Mode::CV => ModeKind::CV, + alientek_el15::Mode::CR => ModeKind::CR, + alientek_el15::Mode::CP => ModeKind::CP, + alientek_el15::Mode::CAP => ModeKind::CAP, + alientek_el15::Mode::DCR => ModeKind::DCR, _ => return None, }) } diff --git a/el15-bt/Cargo.toml b/el15-bt/Cargo.toml deleted file mode 100644 index c389e01..0000000 --- a/el15-bt/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "el15-bt" -version.workspace = true -edition.workspace = true -authors.workspace = true -license.workspace = true -description = "Bluetooth LE protocol library for the ALIENTEK EL15 DC electronic load" - -[dependencies] -btleplug.workspace = true -tokio.workspace = true -tokio-stream.workspace = true -futures.workspace = true -uuid.workspace = true -thiserror.workspace = true -tracing.workspace = true -serde = { workspace = true, optional = true } - -[features] -default = ["serde"] -serde = ["dep:serde"] diff --git a/el15-bt/src/lib.rs b/el15-bt/src/lib.rs deleted file mode 100644 index 40f5d27..0000000 --- a/el15-bt/src/lib.rs +++ /dev/null @@ -1,23 +0,0 @@ -//! ALIENTEK EL15 DC electronic load — Bluetooth LE protocol library. -//! -//! Reverse-engineered from the Python project DM40GUI: -//! - -//! - - -pub mod protocol; -pub mod device; -pub mod error; - -pub use error::{Error, Result}; -pub use protocol::{ - EL15Status, Mode, MODE_NAMES, HEADER, POLL_PKT, - CMD_LOAD_ON, CMD_LOAD_OFF, CMD_LOCK, CMD_INIT, CMD_INFO, CMD_GET_CAP_CURRENT, - CAP_CURRENT_MAX_A, - build_set_setpoint_cmd, build_set_cap_current_cmd, build_mode_cmd, - parse_status_packet, parse_cap_current, checksum, - parse_firmware_version, -}; -pub use device::{ - scan_devices, scan_devices_with, scan_for_device, Device, DeviceEvent, DeviceInfo, ScanOptions, - EL15_SERVICE_UUID, INTER_COMMAND_GAP, -}; diff --git a/el15-bt/src/protocol.rs b/el15-bt/src/protocol.rs deleted file mode 100644 index c0f6a9f..0000000 --- a/el15-bt/src/protocol.rs +++ /dev/null @@ -1,536 +0,0 @@ -//! EL15 BT packet protocol — port of `DM40GUI/el15/protocol_constants.py`. -//! -//! All numeric framing is little-endian (matches Python `memoryview.cast('f'/'i')`). - -#[cfg(feature = "serde")] -use serde::{Deserialize, Serialize}; - -// --------------------------------------------------------------------------- -// Wire constants -// --------------------------------------------------------------------------- - -/// Header for status notifications coming *from* the device. -pub const HEADER: [u8; 4] = [0xDF, 0x07, 0x03, 0x08]; - -/// Pre-computed poll packet (CMD_QUERY prefix + checksum byte 0x3F). -pub const POLL_PKT: [u8; 6] = [0xAF, 0x07, 0x03, 0x08, 0x00, 0x3F]; - -/// Init/handshake packet — device responds with firmware version. -pub const CMD_INIT: [u8; 6] = [0xAF, 0xFF, 0xFF, 0x00, 0x00, 0x53]; - -/// Device info request — device responds with name (e.g. "EL15"). -pub const CMD_INFO: [u8; 6] = [0xAF, 0x07, 0x03, 0x07, 0x00, 0x40]; - -pub const CMD_LOAD_ON: [u8; 7] = [0xAF, 0x07, 0x03, 0x09, 0x01, 0x04, 0x39]; -pub const CMD_LOAD_OFF: [u8; 7] = [0xAF, 0x07, 0x03, 0x09, 0x01, 0x00, 0x3D]; -pub const CMD_LOCK: [u8; 7] = [0xAF, 0x07, 0x03, 0x09, 0x01, 0x01, 0x3C]; - -/// Prefix of a "set mode" command — append the mode byte + checksum. -const CMD_MODE_PREFIX: [u8; 5] = [0xAF, 0x07, 0x03, 0x03, 0x01]; - -/// Prefix of a "set setpoint" command — append the f32 LE bytes + checksum. -/// -/// Applies to CC/CV/CR/CP only. In CAP and DCR the device acknowledges this -/// command with status `0x00` and then ignores it — use [`CMD_SET_CAP_CURRENT_PREFIX`] -/// for the CAP discharge current. -const CMD_SETPOINT_PREFIX: [u8; 5] = [0xAF, 0x07, 0x03, 0x04, 0x04]; - -/// Prefix of a "set CAP discharge current" command (cmd `0x05`, f32 LE Amps). -/// -/// Separate opcode from the ordinary setpoint. Verified on HW:2.0 / SW:1.7: -/// writing here changes the value that [`CMD_GET_CAP_CURRENT`] reads back and -/// the current shown on the device's capacity-test screen. -const CMD_SET_CAP_CURRENT_PREFIX: [u8; 5] = [0xAF, 0x07, 0x03, 0x05, 0x04]; - -/// Read the CAP discharge current — device replies `DF 07 03 0A 04 `. -/// -/// The device applies its own quantisation (it stores milliamps), so a value -/// written as `5.0` reads back as `5.0000010`. -pub const CMD_GET_CAP_CURRENT: [u8; 6] = [0xAF, 0x07, 0x03, 0x0A, 0x00, 0x3D]; - -/// Header of the CAP discharge-current response. -pub const CAP_CURRENT_HEADER: [u8; 5] = [0xDF, 0x07, 0x03, 0x0A, 0x04]; - -/// Compute the checksum byte that makes `sum(packet) % 256 == 0`. -pub fn checksum(data: &[u8]) -> u8 { - let sum: u8 = data.iter().fold(0u8, |acc, &b| acc.wrapping_add(b)); - 0u8.wrapping_sub(sum) -} - -// --------------------------------------------------------------------------- -// Modes -// --------------------------------------------------------------------------- - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[repr(u8)] -pub enum Mode { - CC = 0x01, - CAP = 0x02, - DT = 0x03, - ADV = 0x04, - CV = 0x09, - DCR = 0x0A, - POWER = 0x0B, - AdvScan = 0x0C, - PowerRpt = 0x0D, - CR = 0x11, - CP = 0x19, -} - -impl Mode { - pub fn from_byte(b: u8) -> Option { - Some(match b { - 0x01 => Mode::CC, - 0x02 => Mode::CAP, - 0x03 => Mode::DT, - 0x04 => Mode::ADV, - 0x09 => Mode::CV, - 0x0A => Mode::DCR, - 0x0B => Mode::POWER, - 0x0C => Mode::AdvScan, - 0x0D => Mode::PowerRpt, - 0x11 => Mode::CR, - 0x19 => Mode::CP, - _ => return None, - }) - } - - pub fn as_str(self) -> &'static str { - MODE_NAMES.get(&(self as u8)).unwrap_or("?") - } - - /// (unit, decimal_places, label) — matches `MODE_SETPOINT_INFO`. - pub fn setpoint_info(self) -> (&'static str, u8, &'static str) { - match self { - Mode::CC | Mode::CAP | Mode::DCR => ("A", 3, "Current"), - Mode::CV => ("V", 3, "Voltage"), - Mode::CR => ("Ω", 1, "Resistance"), - Mode::CP => ("W", 2, "Power"), - _ => ("", 3, ""), - } - } - - pub fn is_advanced(self) -> bool { - matches!(self, Mode::CAP | Mode::DCR) - } - - pub fn is_unreachable(self) -> bool { - matches!( - self, - Mode::ADV | Mode::POWER | Mode::DT | Mode::AdvScan | Mode::PowerRpt - ) - } -} - -/// Map mode byte -> short label, parallel with the Python `MODE_NAMES` dict. -pub static MODE_NAMES: phf_map_lite::Map = phf_map_lite::Map::new(&[ - (0x01, "CC"), - (0x02, "CAP"), - (0x03, "POW [DT]"), - (0x04, "ADV [L]"), - (0x09, "CV"), - (0x0A, "DCR"), - (0x0B, "POW [A]"), - (0x0C, "ADV [S]"), - (0x0D, "POW [RPT]"), - (0x11, "CR"), - (0x19, "CP"), -]); - -mod phf_map_lite { - use std::ops::Index; - pub struct Map { - entries: &'static [(u8, &'static str)], - } - impl Map { - pub const fn new(entries: &'static [(u8, &'static str)]) -> Self { - Self { entries } - } - pub fn get(&self, key: &u8) -> Option<&'static str> { - self.entries.iter().find(|(k, _)| k == key).map(|(_, v)| *v) - } - } - impl Index<&u8> for Map { - type Output = str; - fn index(&self, key: &u8) -> &str { - self.get(key).unwrap_or("?") - } - } -} - -// --------------------------------------------------------------------------- -// Status packet -// --------------------------------------------------------------------------- - -const STATUS_LOAD_BIT: u8 = 0x02; -const STATUS_LOCK_BIT: u8 = 0x04; -const MODE_MASK: u8 = 0x1F; -const B5_WARN_FLAG: u8 = 0x06; // bits 1+2 simultaneously => protection -pub const FAN_SPEED_MAX: u8 = 5; - -#[derive(Debug, Clone, Default)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub struct EL15Status { - pub raw_hex: String, - pub crc_pass: bool, - pub valid: bool, - - pub voltage: f32, - pub current: f32, - pub power: f32, - pub runtime_s: u32, - pub temperature: f32, - pub setpoint: f32, - - pub energy_wh: f32, - pub capacity_ah: f32, - - pub dcr_mohm: f32, - pub dcr_i1: f32, - pub dcr_i2: f32, - - pub mode_byte: u8, - pub mode_name: String, - - pub fan_speed: u8, - pub load_on: bool, - pub lock_on: bool, - pub ready: bool, - - pub setpoint_unit: String, - pub setpoint_decimals: u8, - pub setpoint_label: String, - pub setpoint_in_packet: bool, - pub warning: String, -} - -impl EL15Status { - pub fn mode(&self) -> Option { - Mode::from_byte(self.mode_byte) - } -} - -fn read_f32_le(buf: &[u8]) -> f32 { - f32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) -} -fn read_i32_le(buf: &[u8]) -> i32 { - i32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) -} - -/// Parse a 28-byte EL15 status notification. -pub fn parse_status_packet(data: &[u8]) -> EL15Status { - let raw_hex = data - .iter() - .map(|b| format!("{:02X}", b)) - .collect::>() - .join(" "); - let crc_pass = data.iter().fold(0u32, |a, &b| a + b as u32) & 0xFF == 0; - let mut s = EL15Status { raw_hex, crc_pass, ..Default::default() }; - - if data.len() < 28 || data[..4] != HEADER { - return s; - } - - s.voltage = read_f32_le(&data[7..11]); - s.current = read_f32_le(&data[11..15]); - - let b5 = data[5]; - let b6 = data[6]; - - let warn_flag = (b5 & B5_WARN_FLAG) == B5_WARN_FLAG; - let raw_mode = if warn_flag { - b5 & (MODE_MASK & !B5_WARN_FLAG) - } else { - b5 & MODE_MASK - }; - let mode_byte = if MODE_NAMES.get(&raw_mode).is_some() { - raw_mode - } else { - raw_mode | 0x01 - }; - - s.mode_byte = mode_byte; - let mode = Mode::from_byte(mode_byte); - - if warn_flag { - let warn_code = b6 >> 4; - s.warning = match warn_code { - 0x6 => "REV".to_string(), - 0x9 => "UVP".to_string(), - other => format!("PROT {:X}", other), - }; - s.ready = false; - } else { - s.ready = (raw_mode & 0x01) != 0 - || matches!( - mode, - Some(Mode::CAP | Mode::DCR | Mode::ADV | Mode::POWER | Mode::DT | Mode::AdvScan | Mode::PowerRpt) - ); - } - - s.runtime_s = read_i32_le(&data[15..19]) as u32; - s.power = s.voltage * s.current; - s.setpoint_in_packet = true; - - match mode { - Some(Mode::CAP) => { - s.energy_wh = read_f32_le(&data[19..23]) * 0.001; - s.capacity_ah = read_f32_le(&data[23..27]) * 0.001; - s.setpoint_in_packet = false; - } - Some(Mode::DCR) => { - s.dcr_i1 = read_f32_le(&data[15..19]); - s.dcr_i2 = read_f32_le(&data[19..23]); - s.dcr_mohm = read_f32_le(&data[23..27]); - s.runtime_s = 0; - // Keep voltage/current/power from bytes 7–15; they reflect the - // live measurement during the DCR test. - s.power = s.voltage * s.current; - s.setpoint_in_packet = false; - } - Some(Mode::ADV | Mode::POWER | Mode::DT | Mode::PowerRpt) => { - s.runtime_s = 0; - s.setpoint_in_packet = false; - } - _ => { - s.temperature = read_f32_le(&data[19..23]); - s.setpoint = read_f32_le(&data[23..27]); - } - } - - s.fan_speed = (b5 >> 6) | ((b6 & 0x01) << 2); - s.load_on = (b6 & STATUS_LOAD_BIT) != 0; - s.lock_on = (b6 & STATUS_LOCK_BIT) != 0; - s.mode_name = MODE_NAMES - .get(&mode_byte) - .map(|v| v.to_string()) - .unwrap_or_else(|| format!("?{:02X}", mode_byte)); - - let (unit, decimals, label) = mode.map(Mode::setpoint_info).unwrap_or(("?", 3, "Setpoint")); - s.setpoint_unit = unit.to_string(); - s.setpoint_decimals = decimals; - s.setpoint_label = label.to_string(); - - s.valid = true; - s -} - -// --------------------------------------------------------------------------- -// Command builders -// --------------------------------------------------------------------------- - -pub fn build_mode_cmd(mode: Mode) -> Vec { - let mut v = Vec::with_capacity(7); - v.extend_from_slice(&CMD_MODE_PREFIX); - v.push(mode as u8); - v.push(checksum(&v)); - v -} - -pub fn build_set_setpoint_cmd(value: f32) -> Vec { - let mut v = Vec::with_capacity(10); - v.extend_from_slice(&CMD_SETPOINT_PREFIX); - v.extend_from_slice(&value.to_le_bytes()); - v.push(checksum(&v)); - v -} - -/// Highest CAP discharge current the device accepts (12 A = 12000 mA). -pub const CAP_CURRENT_MAX_A: f32 = 12.0; - -/// Build a "set CAP discharge current" command (`0x05`), value in **Amps**. -/// -/// The value is clamped to the device's documented `0 – 12000 mA` range. -pub fn build_set_cap_current_cmd(amps: f32) -> Vec { - let amps = amps.clamp(0.0, CAP_CURRENT_MAX_A); - let mut v = Vec::with_capacity(10); - v.extend_from_slice(&CMD_SET_CAP_CURRENT_PREFIX); - v.extend_from_slice(&s.to_le_bytes()); - v.push(checksum(&v)); - v -} - -/// Parse a CAP discharge-current response (`DF 07 03 0A 04 `). -/// -/// Returns the current in Amps, or `None` if this is not that response. -pub fn parse_cap_current(data: &[u8]) -> Option { - if data.len() < 10 || data[..5] != CAP_CURRENT_HEADER { - return None; - } - Some(f32::from_le_bytes([data[5], data[6], data[7], data[8]])) -} - -/// Parse the firmware version from the Init response notification. -/// -/// Packet: `DF FF FF ` (8 bytes). -/// -/// Version encoding: -/// - `hw_ver` (byte[4]) — reverse-nibble BCD: major = low nibble, minor = high nibble. -/// e.g. `0x02` → major=2, minor=0 → "2.0" -/// - `sw_ver` (byte[7]) — normal BCD: major = high nibble, minor = low nibble. -/// e.g. `0x17` → major=1, minor=7 → "1.7" -/// (This byte also satisfies the packet checksum invariant: sum of all 8 bytes ≡ 0 mod 256.) -/// -/// Returns a string like `"HW:2.0 SW:1.7"`, or `None` if the header doesn't match. -pub fn parse_firmware_version(data: &[u8]) -> Option { - if data.len() < 8 || data[0] != 0xDF || data[1] != 0xFF || data[2] != 0xFF { - return None; - } - let hw_byte = data[4]; - let sw_byte = data[7]; - let hw_major = hw_byte & 0x0F; - let hw_minor = (hw_byte >> 4) & 0x0F; - let sw_major = (sw_byte >> 4) & 0x0F; - let sw_minor = sw_byte & 0x0F; - Some(format!("HW:{}.{} SW:{}.{}", hw_major, hw_minor, sw_major, sw_minor)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn poll_packet_checksum() { - assert_eq!(POLL_PKT, [0xAF, 0x07, 0x03, 0x08, 0x00, 0x3F]); - assert_eq!(POLL_PKT.iter().fold(0u8, |a, &b| a.wrapping_add(b)), 0); - } - - #[test] - fn load_commands_checksum() { - assert_eq!(CMD_LOAD_ON.iter().fold(0u8, |a, &b| a.wrapping_add(b)), 0); - assert_eq!(CMD_LOAD_OFF.iter().fold(0u8, |a, &b| a.wrapping_add(b)), 0); - assert_eq!(CMD_LOCK.iter().fold(0u8, |a, &b| a.wrapping_add(b)), 0); - assert_eq!(CMD_INIT.iter().fold(0u8, |a, &b| a.wrapping_add(b)), 0); - assert_eq!(CMD_INFO.iter().fold(0u8, |a, &b| a.wrapping_add(b)), 0); - } - - #[test] - fn empty_packet_invalid() { - let s = parse_status_packet(&[]); - assert!(!s.valid); - } - - #[test] - fn build_setpoint_cmd_layout() { - let cmd = build_set_setpoint_cmd(2.5); - assert_eq!(&cmd[..5], &CMD_SETPOINT_PREFIX); - assert_eq!(cmd.len(), 10); - let f = f32::from_le_bytes([cmd[5], cmd[6], cmd[7], cmd[8]]); - assert!((f - 2.5).abs() < 1e-6); - assert_eq!(cmd.iter().fold(0u8, |a, &b| a.wrapping_add(b)), 0); - } - - /// Byte-for-byte against the frame accepted by the real device - /// (HW:2.0 / SW:1.7): `af 07 03 05 04 00 00 a0 40 5e` set 5.0 A and the - /// device acknowledged it with `df 07 03 05 01 00 11`. - #[test] - fn build_set_cap_current_matches_device_accepted_frame() { - assert_eq!( - build_set_cap_current_cmd(5.0), - vec![0xAF, 0x07, 0x03, 0x05, 0x04, 0x00, 0x00, 0xA0, 0x40, 0x5E] - ); - assert_eq!( - build_set_cap_current_cmd(3.3), - vec![0xAF, 0x07, 0x03, 0x05, 0x04, 0x33, 0x33, 0x53, 0x40, 0x45] - ); - } - - #[test] - fn cap_current_is_clamped_to_device_range() { - let hi = build_set_cap_current_cmd(99.0); - assert_eq!(f32::from_le_bytes([hi[5], hi[6], hi[7], hi[8]]), CAP_CURRENT_MAX_A); - let lo = build_set_cap_current_cmd(-1.0); - assert_eq!(f32::from_le_bytes([lo[5], lo[6], lo[7], lo[8]]), 0.0); - assert_eq!(hi.iter().fold(0u8, |a, &b| a.wrapping_add(b)), 0); - } - - #[test] - fn cap_current_read_command_checksum() { - assert_eq!(CMD_GET_CAP_CURRENT, [0xAF, 0x07, 0x03, 0x0A, 0x00, 0x3D]); - assert_eq!( - CMD_GET_CAP_CURRENT.iter().fold(0u8, |a, &b| a.wrapping_add(b)), - 0 - ); - } - - /// Real response captured from the device with its current set to 5000 mA. - /// Note the device quantises to milliamps, so 5.0 comes back as 5.0000010 — - /// readback must not be compared for exact equality. - #[test] - fn parse_cap_current_from_device_response() { - let resp = [0xDF, 0x07, 0x03, 0x0A, 0x04, 0x02, 0x00, 0xA0, 0x40, 0x27]; - let amps = parse_cap_current(&resp).expect("should parse"); - assert!((amps - 5.0).abs() < 1e-4, "got {amps}"); - } - - #[test] - fn parse_cap_current_rejects_other_packets() { - // Status packet header — must not be mistaken for a CAP current reply. - assert!(parse_cap_current(&[0xDF, 0x07, 0x03, 0x08, 0x16, 0, 0, 0, 0, 0]).is_none()); - // Acknowledgement of the set command, not the read reply. - assert!(parse_cap_current(&[0xDF, 0x07, 0x03, 0x05, 0x01, 0x00, 0x11]).is_none()); - assert!(parse_cap_current(&[]).is_none()); - } - - #[test] - fn build_mode_cmd_checksum() { - let cmd = build_mode_cmd(Mode::CC); - assert_eq!(cmd, vec![0xAF, 0x07, 0x03, 0x03, 0x01, 0x01, 0x42]); - assert_eq!(cmd.iter().fold(0u8, |a, &b| a.wrapping_add(b)), 0); - - let cmd_cv = build_mode_cmd(Mode::CV); - assert_eq!(cmd_cv.iter().fold(0u8, |a, &b| a.wrapping_add(b)), 0); - } - - #[test] - fn build_setpoint_10_matches_hci() { - let cmd = build_set_setpoint_cmd(10.0); - assert_eq!(cmd, vec![0xAF, 0x07, 0x03, 0x04, 0x04, 0x00, 0x00, 0x20, 0x41, 0xDE]); - } - - #[test] - fn mode_from_byte_round_trip() { - for m in [Mode::CC, Mode::CV, Mode::CR, Mode::CP, Mode::CAP, Mode::DCR] { - assert_eq!(Mode::from_byte(m as u8), Some(m)); - } - } - - #[test] - fn parse_status_from_hci_log() { - // Real CC mode status from HCI capture (20+8 byte fragments concatenated) - let data = hex_to_bytes("df07030816010089acff4000000000000000000e0fb0419a99993e6c"); - let s = parse_status_packet(&data); - assert!(s.valid); - assert!(s.crc_pass); - assert_eq!(s.mode_byte, 0x01); - assert!(!s.load_on); - assert!((s.voltage - 7.99).abs() < 0.1); - assert!((s.setpoint - 0.3).abs() < 0.01); - assert!((s.temperature - 22.0).abs() < 1.0); - } - - #[test] - fn parse_firmware_version_real_device() { - // Real init response observed in HCI log: DF FF FF 00 02 07 03 17 - // HW byte[4]=0x02: low nibble=2 (major), high nibble=0 (minor) → HW 2.0 - // SW byte[7]=0x17: high nibble=1 (major), low nibble=7 (minor) → SW 1.7 - let pkt = [0xDF, 0xFF, 0xFF, 0x00, 0x02, 0x07, 0x03, 0x17]; - assert_eq!(parse_firmware_version(&pkt), Some("HW:2.0 SW:1.7".to_string())); - } - - #[test] - fn parse_firmware_version_rejects_short() { - assert_eq!(parse_firmware_version(&[0xDF, 0xFF, 0xFF]), None); - } - - #[test] - fn parse_firmware_version_rejects_wrong_header() { - let status_pkt = [0xDF, 0x07, 0x03, 0x08, 0x00, 0x00, 0x00, 0x00]; - assert_eq!(parse_firmware_version(&status_pkt), None); - } - - fn hex_to_bytes(s: &str) -> Vec { - (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i+2], 16).unwrap()).collect() - } -} diff --git a/el15-scpi/Cargo.toml b/el15-scpi/Cargo.toml index db72c7b..433a812 100644 --- a/el15-scpi/Cargo.toml +++ b/el15-scpi/Cargo.toml @@ -4,10 +4,13 @@ version.workspace = true edition.workspace = true authors.workspace = true license.workspace = true +repository.workspace = true +# Part of the el15 app, not published on crates.io. +publish = false description = "SCPI/LXI server emulating a RIGOL DL3000 Series electronic load on top of an EL15" [dependencies] -el15-bt = { path = "../el15-bt" } +alientek-el15 = { path = "../alientek-el15", version = "0.1" } tokio.workspace = true tokio-stream.workspace = true futures.workspace = true diff --git a/el15-scpi/src/handlers.rs b/el15-scpi/src/handlers.rs index e1d5e16..e7f3687 100644 --- a/el15-scpi/src/handlers.rs +++ b/el15-scpi/src/handlers.rs @@ -1,7 +1,7 @@ //! SCPI command dispatcher. Maps a subset of the RIGOL DL3000 command tree //! onto EL15 BT operations. -use el15_bt::{build_mode_cmd, build_set_setpoint_cmd, Mode, CMD_LOAD_OFF, CMD_LOAD_ON}; +use alientek_el15::{build_mode_cmd, build_set_setpoint_cmd, Mode, CMD_LOAD_OFF, CMD_LOAD_ON}; use crate::state::SharedState; @@ -146,7 +146,7 @@ async fn handle(state: &SharedState, head: &str, args: &str, is_query: bool) -> // -------- DCR mode measurement -------- "MEAS:DCR" | "MEASURE:DCR" if is_query => { - Some(format!("{:.6}", state.snapshot().await.status.dcr_mohm)) + Some(format!("{:.6}", dcr_ohms(&state.snapshot().await.status))) } _ if is_query => Some("-113,\"Undefined header\"".to_string()), @@ -154,6 +154,11 @@ async fn handle(state: &SharedState, head: &str, args: &str, is_query: bool) -> } } +/// The last DCR result in Ohms, the SCPI base unit; the device reports milliohms. +fn dcr_ohms(status: &alientek_el15::Status) -> f32 { + status.dcr_mohm / 1000.0 +} + async fn handle_setpoint(state: &SharedState, mode: Mode, args: &str, is_query: bool) -> Option { if is_query { let s = state.snapshot().await; @@ -168,6 +173,14 @@ async fn handle_setpoint(state: &SharedState, mode: Mode, args: &str, is_query: } let value: f32 = args.split_whitespace().next().and_then(|s| s.parse().ok()).unwrap_or(0.0); + // NaN, infinity or a negative value never reaches the device (or the stored state). + let frame = match build_set_setpoint_cmd(value) { + Ok(frame) => frame, + Err(e) => { + tracing::warn!("SCPI setpoint rejected: {e}"); + return None; + } + }; state.set_setpoint(mode, value).await; if let Some(d) = state.snapshot().await.device { // Make sure we are in the right mode first, then send setpoint. @@ -175,7 +188,7 @@ async fn handle_setpoint(state: &SharedState, mode: Mode, args: &str, is_query: let _ = d.send(&build_mode_cmd(mode)).await; state.set_mode(mode).await; } - let _ = d.send(&build_set_setpoint_cmd(value)).await; + let _ = d.send(&frame).await; } None } @@ -215,3 +228,15 @@ fn scpi_func(mode: Mode) -> &'static str { _ => "CURR", } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dcr_is_reported_in_ohms() { + // 173.15 mΩ, as the device reported for a Li-ion cell. + let status = alientek_el15::Status { dcr_mohm: 173.15, ..Default::default() }; + assert!((dcr_ohms(&status) - 0.17315).abs() < 1e-6); + } +} diff --git a/el15-scpi/src/state.rs b/el15-scpi/src/state.rs index 8151112..f88d159 100644 --- a/el15-scpi/src/state.rs +++ b/el15-scpi/src/state.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use tokio::sync::Mutex; -use el15_bt::{Device, EL15Status, Mode}; +use alientek_el15::{Device, Status, Mode}; /// Shared device + last-known-status used by every SCPI session. #[derive(Clone)] @@ -11,7 +11,7 @@ pub struct SharedState { struct Inner { pub device: Option>, - pub status: EL15Status, + pub status: Status, pub setpoint_cc: f32, pub setpoint_cv: f32, pub setpoint_cr: f32, @@ -24,7 +24,7 @@ impl Default for SharedState { Self { inner: Arc::new(Mutex::new(Inner { device: None, - status: EL15Status::default(), + status: Status::default(), setpoint_cc: 12.0, setpoint_cv: 5.0, setpoint_cr: 0.5, @@ -40,7 +40,7 @@ impl SharedState { self.inner.lock().await.device = dev; } - pub async fn update_status(&self, status: EL15Status) { + pub async fn update_status(&self, status: Status) { let mut g = self.inner.lock().await; if let Some(m) = status.mode() { g.last_mode = m; @@ -79,7 +79,7 @@ impl SharedState { pub struct StateSnapshot { pub device: Option>, - pub status: EL15Status, + pub status: Status, pub setpoint_cc: f32, pub setpoint_cv: f32, pub setpoint_cr: f32, diff --git a/scripts/scpi-test/Cargo.toml b/scripts/scpi-test/Cargo.toml index c67fa4a..d5350df 100644 --- a/scripts/scpi-test/Cargo.toml +++ b/scripts/scpi-test/Cargo.toml @@ -4,6 +4,9 @@ version.workspace = true edition.workspace = true authors.workspace = true license.workspace = true +repository.workspace = true +# Released as binaries on GitHub, not on crates.io. +publish = false description = "Smoke-test the SCPI server emulating a DL3000 on EL15" [[bin]]