add tauri app

pull/1/head
lambda 3 months ago
parent 7df0a9a413
commit c2b03b84ba
Signed by: lambda
GPG Key ID: 07006F27729676AE

55
.gitignore vendored

@ -0,0 +1,55 @@
# dependency directories
node_modules/
# Optional npm and yarn cache directory
.npm/
.yarn/
# Output of 'npm pack'
*.tgz
# dotenv environment variables file
.env
# .vscode workspace settings file
.vscode/settings.json
.vscode/launch.json
.vscode/tasks.json
# npm, yarn and bun lock files
package-lock.json
yarn.lock
bun.lockb
# rust compiled folders
target/
# test video for streaming example
streaming_example_test_video.mp4
# examples /gen directory
/examples/**/src-tauri/gen/
/bench/**/src-tauri/gen/
# logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# runtime data
pids
*.pid
*.seed
*.pid.lock
# miscellaneous
/.vs
.DS_Store
.Thumbs.db
*.sublime*
.idea
debug.log
TODO.md
.aider*

@ -1,13 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Ridein</title>
</head>
<body>
<button id="start">start</button>
<button id="hr">hr</button>
<script type="module" src="js/main.js"></script>
</body>
</html>

@ -1,48 +0,0 @@
const GATT = Object.freeze({
Battery: Object.freeze({
service: 0x180f,
level: "0x2A19", // Battery Level (Read / Notify)
}),
HeartRate: Object.freeze({
service: 0x180d,
measurement: "0x2A37", // Heart Rate Measurement (Notify)
bodySensorLocation: "0x2A38", // Body Sensor Location (Read)
controlPoint: "0x2A39", // Heart Rate Control Point (Write)
}),
Cadence: Object.freeze({
service: "0x1816",
measurement: "0x2A5B", // CSC Measurement (Notify)
feature: "0x2A5C", // CSC Feature (Read)
location: "0x2A5D", // Sensor Location (Read)
}),
PowerMeter: Object.freeze({
service: "0x1818",
measurement: "0x2A63", // Cycling Power Measurement (Notify)
feature: "0x2A64", // Cycling Power Feature (Read)
controlPoint: "0x2A65", // Cycling Power Control Point (Write)
location: "0x2A66", // Sensor Location (Read)
}),
SmartTrainer: Object.freeze({
service: "0x1826", // Fitness Machine Service
status: "0x2AD9", // Fitness Machine Status (Notify)
controlPoint: "0x2ACC", // Fitness Machine Control Point (Write/Indicate)
feature: "0x2ADA", // Fitness Machine Feature (Read)
indoorBikeData: "0x2ADB", // Indoor Bike Data (Notify)
trainingStatus: "0x2ADC", // Training Status (Notify)
supportedResistance: "0x2ADD", // Supported Resistance Level (Read)
}),
DeviceInfo: Object.freeze({
service: 0x180a, // Device Information Service
manufacturerName: "0x2A29", // Manufacturer Name String (Read)
modelNumber: "0x2A24", // Model Number String (Read)
serialNumber: "0x2A25", // Serial Number String (Read)
firmwareRevision: "0x2A26", // Firmware Revision String (Read)
}),
});
export { GATT };

@ -1,17 +0,0 @@
import { GATT } from "./gatt.js";
const hrSensorOptions = {
filters: [{ services: [GATT.HeartRate.service] }],
optionalServices: [GATT.DeviceInfo.service, GATT.Battery.service],
};
const requestHRSensor = async () => {
try {
return await navigator.bluetooth.requestDevice(hrSensorOptions);
} catch (err) {
console.log(err);
return null;
}
};
export { requestHRSensor };

@ -1,15 +0,0 @@
const CadenceQuality = Object.freeze({
HIGH: "high",
MEDIUM: "medium",
LOW: "low",
UNKNOWN: "unknown",
});
function validateCadenceQuality(v) {
const set = CadenceQuality;
if (!v) return set.UNKNOWN;
const vals = Object.values(set);
return vals.includes(v) ? v : set.UNKNOWN;
}
export { validateCadenceQuality, CadenceQuality };

@ -1,34 +0,0 @@
import { deepFreeze, isFiniteNumber } from "../../utils/index.js";
import { CyclingPowerCapabilities } from "./cyclingPower.js";
export class Control {
constructor({
supportsERG = false,
controlCharacteristic,
maxPowerWatts,
minPowerWatts,
ergRampRateWattsPerSec,
cyclingPower,
} = {}) {
this.supportsERG = Boolean(supportsERG);
this.controlCharacteristic = controlCharacteristic;
this.maxPowerWatts = isFiniteNumber(maxPowerWatts)
? Number(maxPowerWatts)
: undefined;
this.minPowerWatts = isFiniteNumber(minPowerWatts)
? Number(minPowerWatts)
: undefined;
this.ergRampRateWattsPerSec = isFiniteNumber(ergRampRateWattsPerSec)
? Number(ergRampRateWattsPerSec)
: undefined;
this.cyclingPower =
cyclingPower instanceof CyclingPowerCapabilities
? cyclingPower
: cyclingPower
? new CyclingPowerCapabilities(cyclingPower)
: undefined;
deepFreeze(this);
}
merge = (partial) => new Control(Object.assign({}, this, partial));
}

@ -1,35 +0,0 @@
import { deepFreeze } from "../../utils/index.js";
export class Core {
constructor({
supportsBattery = false,
supportsManufacturerData = false,
gattServices,
gattCharacteristics,
manufacturer,
model,
firmwareVersion,
serial,
reconnectOnDisconnect = true,
requiresPairing = false,
} = {}) {
this.supportsBattery = Boolean(supportsBattery);
this.supportsManufacturerData = Boolean(supportsManufacturerData);
this.gattServices = Array.isArray(gattServices)
? gattServices.slice()
: undefined;
this.gattCharacteristics =
gattCharacteristics && typeof gattCharacteristics === "object"
? Object.assign({}, gattCharacteristics)
: undefined;
this.manufacturer = manufacturer;
this.model = model;
this.firmwareVersion = firmwareVersion;
this.serial = serial;
this.reconnectOnDisconnect = Boolean(reconnectOnDisconnect);
this.requiresPairing = Boolean(requiresPairing);
deepFreeze(this);
}
merge = (partial) => new Core(Object.assign({}, this, partial));
}

@ -1,17 +0,0 @@
import { deepFreeze } from "../../utils/index.js";
export class CyclingPowerCapabilities {
constructor({ controlOpcodes = [], supportsCrankTorque = false } = {}) {
/*
* Если в конструктор передали ссылку на внешний массив,
* slice() возвращает новый массив. О бъект получает собственную копию,
* и дальнейшие изменения исходного массива снаружи не повлияют на
* this.controlOpcodes.
*/
this.controlOpcodes = Array.isArray(controlOpcodes)
? controlOpcodes.slice()
: [];
this.supportsCrankTorque = Boolean(supportsCrankTorque);
deepFreeze(this);
}
}

@ -1,5 +0,0 @@
import { Control } from "./control.js";
import { Sensors } from "./sensors.js";
import { Core } from "./core.js";
export { Control, Sensors, Core };

@ -1,31 +0,0 @@
import { deepFreeze, isFiniteNumber } from "../../utils/index.js";
import { validateCadenceQuality } from "../cadence.js";
export class Sensors {
constructor({
supportsHeartRate = false,
supportsCadence = false,
supportsPower = false,
hrSamplingHz,
cadenceSamplingHz,
powerSamplingHz,
cadenceSourceQuality,
} = {}) {
this.supportsHeartRate = Boolean(supportsHeartRate);
this.supportsCadence = Boolean(supportsCadence);
this.supportsPower = Boolean(supportsPower);
this.hrSamplingHz = isFiniteNumber(hrSamplingHz)
? Number(hrSamplingHz)
: undefined;
this.cadenceSamplingHz = isFiniteNumber(cadenceSamplingHz)
? Number(cadenceSamplingHz)
: undefined;
this.powerSamplingHz = isFiniteNumber(powerSamplingHz)
? Number(powerSamplingHz)
: undefined;
this.cadenceSourceQuality = validateCadenceQuality(cadenceSourceQuality);
deepFreeze(this);
}
merge = (partial) => new Sensors(Object.assign({}, this, partial));
}

@ -1,68 +0,0 @@
import { Control, Sensors, Core } from "./capabilities/index.js";
import { deepFreeze } from "../utils/index.js";
const DeviceType = Object.freeze({
HEART_RATE: "heart_rate",
CADENCE: "cadence",
TRAINER: "trainer",
UNKNOWN: "unknown",
});
class Device {
constructor({
id,
name,
type,
core,
sensors,
control,
connected = false,
lastSeen,
} = {}) {
if (!id) throw new Error("Device requires id");
this.id = id;
this.name = name || id;
this.type = type;
this.core = core instanceof Core ? core : core ? new Core(core) : undefined;
this.sensors =
sensors instanceof Sensors
? sensors
: sensors
? new Sensors(sensors)
: undefined;
this.control =
control instanceof Control
? control
: control
? new Control(control)
: undefined;
this.connected = Boolean(connected);
this.lastSeen = lastSeen;
deepFreeze(this);
}
withCore = (partial) =>
new Device(
Object.assign({}, this, {
core: this.core ? this.core.merge(partial) : new Core(partial),
}),
);
withSensors = (partial) =>
new Device(
Object.assign({}, this, {
sensors: this.sensors
? this.sensors.merge(partial)
: new Sensors(partial),
}),
);
withControl = (partial) =>
new Device(
Object.assign({}, this, {
control: this.control
? this.control.merge(partial)
: new Control(partial),
}),
);
}
export { Device, Core };

@ -1,151 +0,0 @@
import { Core } from "./device/index.js";
import { requestHRSensor } from "./ble/index.js";
const startButton = document.getElementById("start");
const hrButton = document.getElementById("hr");
hrButton.addEventListener("click", async () => {
function parseHeartRate(dataView) {
// Flags are in the first byte
const flags = dataView.getUint8(0);
const hrFormatUint16 = flags & 0x01; // 0 = 8bit, 1 = 16bit
if (hrFormatUint16) {
return dataView.getUint16(1, /*littleEndian=*/ true);
}
return dataView.getUint8(1);
}
try {
const device = await requestHRSensor();
console.log("D", device);
if (!device) return;
const server = await device.gatt.connect();
const partialCore = new Core({
supportsBattery: true,
supportsManufacturerData: true,
gattServices: [
0x180a, // Device Information
0x180d, // Heart Rate
],
gattCharacteristics: [
0x2a29, // Manufacturer Name
0x2a24, // Model Number
0x2a25, // Serial number
0x2a26, // Firmware version
0x2a37, // Heart Rate Measurement
],
});
const info = await server.getPrimaryService(partialCore.gattServices[0]);
const [manufacturer, model, firmwareVersion] = await Promise.all([
info.getCharacteristic(0x2a29).then((c) => c.readValue()),
info.getCharacteristic(0x2a24).then((c) => c.readValue()),
info.getCharacteristic(0x2a26).then((c) => c.readValue()),
//info.getCharacteristic(0x2a25).then((c) => c.readValue()),
]);
// const [infoService, hrService] = await Promise.all([
// server.getPrimaryService(0x180a), // Device Information
// server.getPrimaryService(0x180d), // Heart Rate
// ]);
// const [manufVal, modelVal, hrChar] = await Promise.all([
// infoService.getCharacteristic(0x2a29).then((c) => c.readValue()), // Manufacturer Name (0x2A29)
// infoService.getCharacteristic(0x2a24).then((c) => c.readValue()), // Model Number (0x2A24)
// hrService
// .getCharacteristic(0x2a37)
// .then((c) => c.startNotifications().then(() => c)), // Heart Rate Measurement
// ]);
const dec = new TextDecoder("utf-8");
const core = partialCore.merge({
manufacturer: dec.decode(manufacturer),
model: dec.decode(model),
firmwareVersion: dec.decode(firmwareVersion),
//serial: dec.decode(serial),
});
console.log(core);
// hrChar.addEventListener("characteristicvaluechanged", (ev) =>
// console.log("❤️", parseHeartRate(ev.target.value), "bpm"),
// );
} catch (error) {
console.error(error);
}
});
const devices = await navigator.bluetooth.getDevices();
console.log("CONNECTED", devices);
// devices.forEach(async (device) => {
// const gattServer = await device.gatt.connect();
// const primaryService = await gattServer.getPrimaryService(0x1800);
// const MANUFACTURER_UUID = 0x2a29;
// const MODEL_UUID = 0x2a0a;
// const char = await primaryService.getCharacteristic(MODEL_UUID);
// const val = await char.readValue();
// //const char2 = await primaryService.getCharacteristic(MODEL_UUID);
// //const val2 = await char2.readValue();
// const decoder = new TextDecoder("utf-8");
// const manufacturer = decoder.decode(val);
// //const model = decoder.decode(val2);
// console.log("Manufacturer:", manufacturer);
// });
startButton.addEventListener("click", async () => {
try {
const devices = await navigator.bluetooth.getDevices();
console.log(2, devices);
const device = await navigator.bluetooth.requestDevice({
filters: [{ services: [0x180d] }],
optionalServices: [
0x1818, // Cycling Power watts, torque, crank torque, etc.
0x1816, // Cycling Speed & Cadence speed, cadence, distance
0x180d, // Heart Rate optional, if the trainer includes an HR sensor
0x180f, // Battery Service trainer battery level (if batterypowered)
0x180a, // Device Information manufacturer, model, firmware version
0x1800,
// add any custom 128bit UUIDs as strings, e.g.
// '0000abcd-0000-1000-8000-00805f9b34fb'
],
acceptAllDevices: true,
});
const server = await device.gatt.connect();
console.log(await server.getPrimaryServices());
} catch (error) {
console.log(error);
}
});
// startButton.addEventListener("click", async () => {
// try {
// const devices = await navigator.bluetooth.getDevices();
// console.log(2, devices);
// const device = await navigator.bluetooth.requestDevice({
// //filters: [{ services: ["heart_rate"] }],
// optionalServices: [
// 0x1818, // Cycling Power watts, torque, crank torque, etc.
// 0x1816, // Cycling Speed & Cadence speed, cadence, distance
// 0x180d, // Heart Rate optional, if the trainer includes an HR sensor
// 0x180f, // Battery Service trainer battery level (if batterypowered)
// 0x180a, // Device Information manufacturer, model, firmware version
// 0x1800,
// // add any custom 128bit UUIDs as strings, e.g.
// // '0000abcd-0000-1000-8000-00805f9b34fb'
// ],
// acceptAllDevices: true,
// });
// const server = await device.gatt.connect();
// console.log(await server.getPrimaryServices());
// } catch (error) {
// console.log(error);
// }
// });

@ -1,86 +0,0 @@
// 1⃣ Request a HRmonitor device
const hrOptions = {
// Show only devices that advertise the Heart Rate service (0x180D)
filters: [{ services: [0x180d] }],
// After the user picks a device we also want to read the Device
// Information service (optional, no extra prompt)
optionalServices: [0x180a], // Device Information
};
navigator.bluetooth
.requestDevice(hrOptions)
.then((device) => {
console.log("✅ Selected:", device.name);
// 2⃣ Connect to the GATT server
return device.gatt.connect();
})
.then((server) => {
// 3⃣ Get the Heart Rate service
return server.getPrimaryService(0x180d);
})
.then((hrService) => {
// 4⃣ Get the Heart Rate Measurement characteristic (0x2A37)
return hrService.getCharacteristic(0x2a37);
})
.then((hrChar) => {
// 5⃣ Enable notifications the monitor will push new readings
return hrChar.startNotifications().then(() => hrChar);
})
.then((hrChar) => {
console.log("🔔 Listening for heartrate measurements...");
hrChar.addEventListener("characteristicvaluechanged", (ev) => {
const value = ev.target.value; // DataView
const heartRate = parseHeartRate(value);
console.log("❤️ Heart Rate:", heartRate, "bpm");
});
})
.catch((err) => console.error("❌ Bluetooth error:", err));
/**
* Parse the Heart Rate Measurement characteristic (Bluetooth SIG spec).
* Returns the BPM as a Number.
*/
function parseHeartRate(dataView) {
// Flags are in the first byte
const flags = dataView.getUint8(0);
const hrFormatUint16 = flags & 0x01; // 0 = 8bit, 1 = 16bit
if (hrFormatUint16) {
return dataView.getUint16(1, /*littleEndian=*/ true);
}
return dataView.getUint8(1);
}
// After the HR connection succeeds, you can also fetch the Device Info service:
navigator.bluetooth
.requestDevice(hrOptions) // reuse the same options
.then((d) => d.gatt.connect())
.then((server) =>
Promise.all([
server.getPrimaryService(0x180a), // Device Information
server.getPrimaryService(0x180d), // Heart Rate
]),
)
.then(([infoService, hrService]) =>
Promise.all([
// Manufacturer Name (0x2A29)
infoService.getCharacteristic(0x2a29).then((c) => c.readValue()),
// Model Number (0x2A24)
infoService.getCharacteristic(0x2a24).then((c) => c.readValue()),
// Heart Rate Measurement (as before)
hrService
.getCharacteristic(0x2a37)
.then((c) => c.startNotifications().then(() => c)),
]),
)
.then(([manufVal, modelVal, hrChar]) => {
const dec = new TextDecoder("utf-8");
console.log("🏭 Manufacturer:", dec.decode(manufVal));
console.log("📦 Model:", dec.decode(modelVal));
hrChar.addEventListener("characteristicvaluechanged", (ev) =>
console.log("❤️", parseHeartRate(ev.target.value), "bpm"),
);
})
.catch(console.error);

@ -1,5 +0,0 @@
const connectHRSensor = () => {};
const connectCadenceSensor = () => {};
const connectTrainer = () => {};
export { connectHRSensor, connectCadenceSensor, connectTrainer };

@ -1,14 +0,0 @@
const deepFreeze = (obj) => {
if (obj && typeof obj === "object" && !Object.isFrozen(obj)) {
Object.getOwnPropertyNames(obj).forEach((prop) => {
const value = obj[prop];
if (value && typeof value === "object") deepFreeze(value);
});
Object.freeze(obj);
}
return obj;
};
const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);
export { deepFreeze, isFiniteNumber };

@ -1,2 +1,9 @@
Minimalistic web application for running
zwo workouts in browser.
Minimalistic web application for running zwo workouts.
# Tauri + Vanilla
This template should help get you started developing with Tauri in vanilla HTML, CSS and Javascript.
## Recommended IDE Setup
- [VS Code](https://code.visualstudio.com/) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)

@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas

5527
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

@ -0,0 +1,38 @@
[package]
name = "rideinn"
version = "0.1.0"
description = "A Tauri App"
authors = ["you"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
# The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name.
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
name = "rideinn_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
btleplug = "0.11.8"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] }
hex = "0.4"
uuid = "1.16.0"
[profile.dev]
incremental = true # Compile your binary in smaller steps.
[profile.release]
codegen-units = 1 # Allows LLVM to perform better optimization.
lto = true # Enables link-time-optimizations.
opt-level = "s" # Prioritizes small binary size. Use `3` if you prefer speed.
panic = "abort" # Higher performance by disabling panic handlers.
strip = true # Ensures debug symbols are removed.

@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

@ -0,0 +1,10 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
"opener:default"
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 974 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 903 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

@ -0,0 +1,10 @@
#[derive(Debug)]
pub enum BleError {
SystemBleError
}
impl From<btleplug::Error> for BleError {
fn from(_: btleplug::Error) -> Self {
BleError::SystemBleError
}
}

@ -0,0 +1,6 @@
mod error;
mod utils;
mod scanner;
pub use scanner::scan_devices;
pub use utils::normalize_uuid;

@ -0,0 +1,81 @@
use btleplug::api::{Central, Manager as _, Peripheral, ScanFilter, bleuuid::uuid_from_u16};
use btleplug::platform::Manager;
use std::time::Duration;
use tokio::time;
use crate::ble::error::BleError;
use crate::device::Device;
use hex;
use uuid::{Uuid};
static TARGET_UUIDS: &[Uuid] = &[
uuid_from_u16(0x180D), // Heart Rate
uuid_from_u16(0x1816), // Cycling Speed and Cadence
uuid_from_u16(0x1826), // Fitness Machine (FTMS)
uuid_from_u16(0x180F), // Battery Level
uuid_from_u16(0x180A), // Device info
uuid_from_u16(0x1818), // Power meter
];
pub async fn scan_devices(scan_seconds: u64) -> Result<Vec<Device>, BleError> {
let manager = Manager::new().await?;
let adapters = manager.adapters().await?;
let central = adapters.into_iter().next().ok_or(BleError::SystemBleError)?;
let target_vec: Vec<Uuid> = TARGET_UUIDS.to_vec();
central.start_scan(ScanFilter { services: target_vec.clone() }).await?;
time::sleep(Duration::from_secs(scan_seconds)).await;
let mut devices = Vec::new();
for peripheral in central.peripherals().await? {
if let Some(props) = peripheral.properties().await? {
let svc_match = props.services.iter().any(|s| TARGET_UUIDS.iter().any(|t| t == s));
if !svc_match { continue; }
let manuf = props.manufacturer_data.iter().next().map(|(_,v)| hex::encode(v));
let mut characteristics: Vec<String> = Vec::new();
let is_connected = peripheral.is_connected().await.unwrap_or(false);
if !is_connected {
let _ = tokio::time::timeout(Duration::from_secs(5), peripheral.connect()).await;
}
let _ = tokio::time::timeout(Duration::from_secs(5), peripheral.discover_services()).await;
let chars = peripheral.characteristics();
if !chars.is_empty() {
for ch in chars.iter() {
let entry = format!("{}::{}", ch.service_uuid, ch.uuid);
characteristics.push(entry);
}
} else {
for svc in peripheral.services().iter() {
for ch in svc.characteristics.iter() {
let entry = format!("{}::{}", svc.uuid, ch.uuid);
characteristics.push(entry);
}
}
}
if !is_connected {
let _ = tokio::time::timeout(Duration::from_secs(2), peripheral.disconnect()).await;
}
devices.push(Device {
id: peripheral.id().to_string(),
address: props.address.to_string(),
display_name: props.local_name,
rssi: props.rssi,
service_uuids: props.services.iter().map(|u| u.to_string()).collect(),
manufacturer_data: manuf,
metadata: None,
characteristics,
});
}
}
central.stop_scan().await.ok();
println!("{:?}", devices);
Ok(devices)
}

@ -0,0 +1,9 @@
pub fn normalize_uuid(u: &str) -> String {
let s = u.trim().to_ascii_lowercase();
const BASE_SUFFIX: &str = "-0000-1000-8000-00805f9b34fb";
if s.ends_with(BASE_SUFFIX) && s.len() >= BASE_SUFFIX.len() + 4 {
let start = s.len() - BASE_SUFFIX.len() - 4;
return s[start..start + 4].to_string();
}
s
}

@ -0,0 +1,90 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::ble::normalize_uuid;
#[derive(Debug, Serialize, Clone, Deserialize)]
pub struct Device {
pub id: String,
pub address: String,
pub display_name: Option<String>,
pub rssi: Option<i16>,
pub service_uuids: Vec<String>,
pub characteristics: Vec<String>,
pub manufacturer_data: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
}
impl Device {}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum DeviceType {
HrSensor,
CadSensor,
Trainer
}
pub fn get_device_types(device: &Device) -> Vec<DeviceType> {
let hr_services = ["180d"];
let hr_characteristics = ["2a37"];
let csc_services = ["1816"];
let csc_characteristics = ["2a5b"];
// trainer / cycling power / fitness machine / indoor bike
let trainer_services = ["1818", "1826"];
let trainer_characteristics = ["2a63", "2ad2", "2acc"]; // 2AD2 = Indoor Bike Data, 2ACC = Fitness Machine Characteristics, 2A63 = Cycling Power Measurement
// любые 2ADx характеристики (indoor bike related) — учитывать как признак каденса доступного в тренажёре
let indoor_bike_chars_prefix = "2ad"; // covers 2ad2,2ad5,2ad6,2ad8,2ad9,2ada etc.
// Нормализуем все UUIDs
let mut norms = Vec::with_capacity(device.service_uuids.len() + device.characteristics.len());
for u in device.service_uuids.iter().chain(device.characteristics.iter()) {
// Для характеристик, которые приходят в виде "service::characteristic", извлечём часть после "::"
let part = if let Some(idx) = u.find("::") {
&u[idx + 2..]
} else {
u.as_str()
};
norms.push(normalize_uuid(part));
}
let contains_any = |candidates: &[&str]| -> bool {
for cand in candidates {
let cand = cand.to_ascii_lowercase();
if norms.iter().any(|n| n == &cand || n.ends_with(&cand)) {
return true;
}
}
false
};
let mut out = Vec::new();
// Heart rate
if contains_any(&hr_services) || contains_any(&hr_characteristics) {
out.push(DeviceType::HrSensor);
}
// CSC / Cadence
if contains_any(&csc_services) || contains_any(&csc_characteristics) {
out.push(DeviceType::CadSensor);
}
// Trainer/Cycling power/Indoor bike
let is_trainer = contains_any(&trainer_services) || contains_any(&trainer_characteristics);
if is_trainer {
out.push(DeviceType::Trainer);
}
// Доп. логика: если найдены Indoor Bike Data (любые 2ADx characteristics), считаем, что устройство может отдавать cadence —
// добавляем CadSensor, даже если CSC (0x1816/0x2A5B) отсутствует.
let has_indoor_bike_char = norms.iter().any(|n| n.starts_with(indoor_bike_chars_prefix));
if has_indoor_bike_char && !out.contains(&DeviceType::CadSensor) {
out.push(DeviceType::CadSensor);
}
out
}

@ -0,0 +1,2 @@
pub mod device;
pub use device::Device;

@ -0,0 +1,14 @@
#[derive(Debug)]
pub enum RepoError {
Creation,
Empty,
Serialization
}
impl From<std::io::Error> for RepoError {
fn from(_: std::io::Error) -> Self { RepoError::Creation }
}
impl From<serde_json::Error> for RepoError {
fn from(_: serde_json::Error) -> Self { RepoError::Serialization }
}

@ -0,0 +1,4 @@
mod repo;
mod error;
pub use repo::{try_from_file, try_write, repo_from_devices, Repo};

@ -0,0 +1,59 @@
use std::{fs::{read_to_string, write}};
use serde::{Deserialize, Serialize};
use crate::{device::{device::{get_device_types, DeviceType}, Device}, device_repo::error::RepoError};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Repo {
#[serde(default)]
hr_sensors: Vec<Device>,
#[serde(default)]
cad_sensors: Vec<Device>,
#[serde(default)]
trainers: Vec<Device>
}
impl Repo {
pub fn new() -> Self {
Self {
hr_sensors: Vec::new(),
cad_sensors: Vec::new(),
trainers: Vec::new(),
}
}
}
const STATIC_PATH: &str = "devices.json";
pub fn try_write(repo: &Repo) -> Result<Repo, RepoError> {
let json = serde_json::to_string_pretty(repo)?;
write(STATIC_PATH, json)?;
Ok(repo.clone())
}
pub fn try_from_file() -> Result<Repo, RepoError> {
let contents = match read_to_string(STATIC_PATH) {
Ok(s) if !s.trim().is_empty() => s,
_ => return Err(RepoError::Empty),
};
let repo: Repo = serde_json::from_str(&contents)?;
Ok(repo)
}
pub fn repo_from_devices(devices: Vec<Device>) -> Repo {
let mut repo = Repo::new();
for dev in devices.into_iter() {
let types = get_device_types(&dev);
for t in types {
match t {
DeviceType::HrSensor => repo.hr_sensors.push(dev.clone()),
DeviceType::CadSensor => repo.cad_sensors.push(dev.clone()),
DeviceType::Trainer => repo.trainers.push(dev.clone()),
}
}
}
repo
}

@ -0,0 +1,31 @@
mod device;
mod ble;
mod device_repo;
use crate::{ble::scan_devices, device::Device, device_repo::{repo_from_devices, try_from_file, Repo}};
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
async fn read_repo() -> Vec<Device> {
vec![]
}
#[tauri::command]
async fn scan() -> Repo {
match try_from_file() {
Ok(repo) => repo,
Err(_) => {
let devices = (scan_devices(20).await).unwrap_or_default();
repo_from_devices(devices)
}
}
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.invoke_handler(tauri::generate_handler![read_repo, scan])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
rideinn_lib::run()
}

@ -0,0 +1,33 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "rideinn",
"version": "0.1.0",
"identifier": "com.cyclocrust.ridein",
"build": {
"frontendDist": "../src"
},
"app": {
"withGlobalTauri": true,
"windows": [
{
"title": "rideinn",
"width": 800,
"height": 600
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="32" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path fill="#F7DF1E" d="M0 0h256v256H0V0Z"></path><path d="m67.312 213.932l19.59-11.856c3.78 6.701 7.218 12.371 15.465 12.371c7.905 0 12.89-3.092 12.89-15.12v-81.798h24.057v82.138c0 24.917-14.606 36.259-35.916 36.259c-19.245 0-30.416-9.967-36.087-21.996m85.07-2.576l19.588-11.341c5.157 8.421 11.859 14.607 23.715 14.607c9.969 0 16.325-4.984 16.325-11.858c0-8.248-6.53-11.17-17.528-15.98l-6.013-2.58c-17.357-7.387-28.87-16.667-28.87-36.257c0-18.044 13.747-31.792 35.228-31.792c15.294 0 26.292 5.328 34.196 19.247l-18.732 12.03c-4.125-7.389-8.591-10.31-15.465-10.31c-7.046 0-11.514 4.468-11.514 10.31c0 7.217 4.468 10.14 14.778 14.608l6.014 2.577c20.45 8.765 31.963 17.7 31.963 37.804c0 21.654-17.012 33.51-39.867 33.51c-22.339 0-36.774-10.654-43.819-24.574"></path></svg>

After

Width:  |  Height:  |  Size: 995 B

@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

@ -0,0 +1,20 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="styles.css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tauri App</title>
<script type="module" src="/main.js" defer></script>
</head>
<body>
<main class="container">
<h1>Welcome to RideInn</h1>
<div class="row">
<span id="msg">Подключаем устройства...</span>
<button id="find">поиск</button>
</div>
</main>
</body>
</html>

@ -0,0 +1,28 @@
const { invoke } = window.__TAURI__.core;
let greetInputEl;
let greetMsgEl;
async function readRepo() {
return await invoke("read_repo");
}
async function scan() {
return await invoke("scan");
}
window.addEventListener("DOMContentLoaded", async () => {
const messageContainer = document.getElementById("msg");
const findButton = document.getElementById("find");
const connectedDeviced = await readRepo();
if (connectedDeviced.length === 0) {
messageContainer.innerText = "Ищем устройства...";
}
findButton.addEventListener("click", async () => {
const lol = await scan();
console.log("devices", lol);
});
});

@ -0,0 +1,112 @@
.logo.vanilla:hover {
filter: drop-shadow(0 0 2em #ffe21c);
}
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color: #0f0f0f;
background-color: #f6f6f6;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
.container {
margin: 0;
padding-top: 10vh;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: 0.75s;
}
.logo.tauri:hover {
filter: drop-shadow(0 0 2em #24c8db);
}
.row {
display: flex;
justify-content: center;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
h1 {
text-align: center;
}
input,
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
color: #0f0f0f;
background-color: #ffffff;
transition: border-color 0.25s;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
}
button {
cursor: pointer;
}
button:hover {
border-color: #396cd8;
}
button:active {
border-color: #396cd8;
background-color: #e8e8e8;
}
input,
button {
outline: none;
}
#greet-input {
margin-right: 5px;
}
@media (prefers-color-scheme: dark) {
:root {
color: #f6f6f6;
background-color: #2f2f2f;
}
a:hover {
color: #24c8db;
}
input,
button {
color: #ffffff;
background-color: #0f0f0f98;
}
button:active {
background-color: #0f0f0f69;
}
}
Loading…
Cancel
Save