repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/btuuid.rs | src/btuuid.rs | //! `Uuid` extensions for Bluetooth UUIDs
use crate::Uuid;
/// This is the Bluetooth Base UUID. It is used with 16-bit and 32-bit UUIDs
/// [defined](https://www.bluetooth.com/specifications/assigned-numbers/) by the Bluetooth SIG.
pub const BLUETOOTH_BASE_UUID: u128 = 0x00000000_0000_1000_8000_00805f9b34fb;
/// Const function to create a 16-bit Bluetooth UUID
#[must_use]
pub const fn bluetooth_uuid_from_u16(uuid: u16) -> Uuid {
Uuid::from_u128(((uuid as u128) << 96) | BLUETOOTH_BASE_UUID)
}
/// Const function to create a 32-bit Bluetooth UUID
#[must_use]
pub const fn bluetooth_uuid_from_u32(uuid: u32) -> Uuid {
Uuid::from_u128(((uuid as u128) << 96) | BLUETOOTH_BASE_UUID)
}
/// Extension trait for [`Uuid`] with helper methods for dealing with Bluetooth 16-bit and 32-bit UUIDs
pub trait BluetoothUuidExt: private::Sealed {
/// Creates a 16-bit Bluetooth UUID
fn from_u16(uuid: u16) -> Self;
/// Creates a 32-bit Bluetooth UUID
fn from_u32(uuid: u32) -> Self;
/// Creates a UUID from `bytes`
///
/// # Panics
///
/// Panics if `bytes.len()` is not one of 2, 4, or 16
fn from_bluetooth_bytes(bytes: &[u8]) -> Self;
/// Returns `true` if self is a valid 16-bit Bluetooth UUID
fn is_u16_uuid(&self) -> bool;
/// Returns `true` if self is a valid 32-bit Bluetooth UUID
fn is_u32_uuid(&self) -> bool;
/// Tries to convert self into a 16-bit Bluetooth UUID
fn try_to_u16(&self) -> Option<u16>;
/// Tries to convert self into a 32-bit Bluetooth UUID
fn try_to_u32(&self) -> Option<u32>;
/// Returns a slice of octets representing the UUID. If the UUID is a valid 16- or 32-bit Bluetooth UUID, the
/// returned slice will be 2 or 4 octets long, respectively. Otherwise the slice will be 16-octets in length.
fn as_bluetooth_bytes(&self) -> &[u8];
}
impl BluetoothUuidExt for Uuid {
fn from_u16(uuid: u16) -> Self {
bluetooth_uuid_from_u16(uuid)
}
fn from_u32(uuid: u32) -> Self {
bluetooth_uuid_from_u32(uuid)
}
fn from_bluetooth_bytes(bytes: &[u8]) -> Self {
bytes
.try_into()
.map(|x| Self::from_u16(u16::from_be_bytes(x)))
.or_else(|_| bytes.try_into().map(|x| Self::from_u32(u32::from_be_bytes(x))))
.or_else(|_| bytes.try_into().map(Self::from_bytes))
.expect("invalid slice length for bluetooth UUID")
}
fn is_u16_uuid(&self) -> bool {
self.try_to_u16().is_some()
}
fn is_u32_uuid(&self) -> bool {
let u = self.as_u128();
(u & ((1 << 96) - 1)) == BLUETOOTH_BASE_UUID
}
fn try_to_u16(&self) -> Option<u16> {
self.try_to_u32().and_then(|x| x.try_into().ok())
}
fn try_to_u32(&self) -> Option<u32> {
let u = self.as_u128();
self.is_u32_uuid().then_some((u >> 96) as u32)
}
fn as_bluetooth_bytes(&self) -> &[u8] {
let bytes = self.as_bytes();
if self.is_u16_uuid() {
&bytes[2..4]
} else if self.is_u32_uuid() {
&bytes[0..4]
} else {
&bytes[..]
}
}
}
mod private {
use crate::Uuid;
pub trait Sealed {}
impl Sealed for Uuid {}
}
/// Bluetooth GATT Service 16-bit UUIDs
#[allow(missing_docs)]
pub mod services {
use super::bluetooth_uuid_from_u16;
use crate::Uuid;
pub const GENERIC_ACCESS: Uuid = bluetooth_uuid_from_u16(0x1800);
pub const GENERIC_ATTRIBUTE: Uuid = bluetooth_uuid_from_u16(0x1801);
pub const IMMEDIATE_ALERT: Uuid = bluetooth_uuid_from_u16(0x1802);
pub const LINK_LOSS: Uuid = bluetooth_uuid_from_u16(0x1803);
pub const TX_POWER: Uuid = bluetooth_uuid_from_u16(0x1804);
pub const CURRENT_TIME: Uuid = bluetooth_uuid_from_u16(0x1805);
pub const REFERENCE_TIME_UPDATE: Uuid = bluetooth_uuid_from_u16(0x1806);
pub const NEXT_DST_CHANGE: Uuid = bluetooth_uuid_from_u16(0x1807);
pub const GLUCOSE: Uuid = bluetooth_uuid_from_u16(0x1808);
pub const HEALTH_THERMOMETER: Uuid = bluetooth_uuid_from_u16(0x1809);
pub const DEVICE_INFORMATION: Uuid = bluetooth_uuid_from_u16(0x180A);
pub const HEART_RATE: Uuid = bluetooth_uuid_from_u16(0x180D);
pub const PHONE_ALERT_STATUS: Uuid = bluetooth_uuid_from_u16(0x180E);
pub const BATTERY: Uuid = bluetooth_uuid_from_u16(0x180F);
pub const BLOOD_PRESSURE: Uuid = bluetooth_uuid_from_u16(0x1810);
pub const ALERT_NOTIFICATION: Uuid = bluetooth_uuid_from_u16(0x1811);
pub const HUMAN_INTERFACE_DEVICE: Uuid = bluetooth_uuid_from_u16(0x1812);
pub const SCAN_PARAMETERS: Uuid = bluetooth_uuid_from_u16(0x1813);
pub const RUNNING_SPEED_AND_CADENCE: Uuid = bluetooth_uuid_from_u16(0x1814);
pub const AUTOMATION_IO: Uuid = bluetooth_uuid_from_u16(0x1815);
pub const CYCLING_SPEED_AND_CADENCE: Uuid = bluetooth_uuid_from_u16(0x1816);
pub const CYCLING_POWER: Uuid = bluetooth_uuid_from_u16(0x1818);
pub const LOCATION_AND_NAVIGATION: Uuid = bluetooth_uuid_from_u16(0x1819);
pub const ENVIRONMENTAL_SENSING: Uuid = bluetooth_uuid_from_u16(0x181A);
pub const BODY_COMPOSITION: Uuid = bluetooth_uuid_from_u16(0x181B);
pub const USER_DATA: Uuid = bluetooth_uuid_from_u16(0x181C);
pub const WEIGHT_SCALE: Uuid = bluetooth_uuid_from_u16(0x181D);
pub const BOND_MANAGEMENT: Uuid = bluetooth_uuid_from_u16(0x181E);
pub const CONTINUOUS_GLUCOSE_MONITORING: Uuid = bluetooth_uuid_from_u16(0x181F);
pub const INTERNET_PROTOCOL_SUPPORT: Uuid = bluetooth_uuid_from_u16(0x1820);
pub const INDOOR_POSITIONING: Uuid = bluetooth_uuid_from_u16(0x1821);
pub const PULSE_OXIMETER: Uuid = bluetooth_uuid_from_u16(0x1822);
pub const HTTP_PROXY: Uuid = bluetooth_uuid_from_u16(0x1823);
pub const TRANSPORT_DISCOVERY: Uuid = bluetooth_uuid_from_u16(0x1824);
pub const OBJECT_TRANSFER: Uuid = bluetooth_uuid_from_u16(0x1825);
pub const FITNESS_MACHINE: Uuid = bluetooth_uuid_from_u16(0x1826);
pub const MESH_PROVISIONING: Uuid = bluetooth_uuid_from_u16(0x1827);
pub const MESH_PROXY: Uuid = bluetooth_uuid_from_u16(0x1828);
pub const RECONNECTION_CONFIGURATION: Uuid = bluetooth_uuid_from_u16(0x1829);
pub const INSULIN_DELIVERY: Uuid = bluetooth_uuid_from_u16(0x183A);
pub const BINARY_SENSOR: Uuid = bluetooth_uuid_from_u16(0x183B);
pub const EMERGENCY_CONFIGURATION: Uuid = bluetooth_uuid_from_u16(0x183C);
pub const PHYSICAL_ACTIVITY_MONITOR: Uuid = bluetooth_uuid_from_u16(0x183E);
pub const AUDIO_INPUT_CONTROL: Uuid = bluetooth_uuid_from_u16(0x1843);
pub const VOLUME_CONTROL: Uuid = bluetooth_uuid_from_u16(0x1844);
pub const VOLUME_OFFSET_CONTROL: Uuid = bluetooth_uuid_from_u16(0x1845);
pub const COORDINATED_SET_IDENTIFICATION: Uuid = bluetooth_uuid_from_u16(0x1846);
pub const DEVICE_TIME: Uuid = bluetooth_uuid_from_u16(0x1847);
pub const MEDIA_CONTROL: Uuid = bluetooth_uuid_from_u16(0x1848);
pub const GENERIC_MEDIA_CONTROL: Uuid = bluetooth_uuid_from_u16(0x1849);
pub const CONSTANT_TONE_EXTENSION: Uuid = bluetooth_uuid_from_u16(0x184A);
pub const TELEPHONE_BEARER: Uuid = bluetooth_uuid_from_u16(0x184B);
pub const GENERIC_TELEPHONE_BEARER: Uuid = bluetooth_uuid_from_u16(0x184C);
pub const MICROPHONE_CONTROL: Uuid = bluetooth_uuid_from_u16(0x184D);
pub const AUDIO_STREAM_CONTROL: Uuid = bluetooth_uuid_from_u16(0x184E);
pub const BROADCAST_AUDIO_SCAN: Uuid = bluetooth_uuid_from_u16(0x184F);
pub const PUBLISHED_AUDIO_CAPABILITIES: Uuid = bluetooth_uuid_from_u16(0x1850);
pub const BASIC_AUDIO_ANNOUNCEMENT: Uuid = bluetooth_uuid_from_u16(0x1851);
pub const BROADCAST_AUDIO_ANNOUNCEMENT: Uuid = bluetooth_uuid_from_u16(0x1852);
pub const COMMON_AUDIO: Uuid = bluetooth_uuid_from_u16(0x1853);
pub const HEARING_ACCESS: Uuid = bluetooth_uuid_from_u16(0x1854);
pub const TMAS: Uuid = bluetooth_uuid_from_u16(0x1855);
pub const PUBLIC_BROADCAST_ANNOUNCEMENT: Uuid = bluetooth_uuid_from_u16(0x1856);
}
/// Bluetooth GATT Characteristic 16-bit UUIDs
#[allow(missing_docs)]
pub mod characteristics {
use super::bluetooth_uuid_from_u16;
use crate::Uuid;
pub const DEVICE_NAME: Uuid = bluetooth_uuid_from_u16(0x2A00);
pub const APPEARANCE: Uuid = bluetooth_uuid_from_u16(0x2A01);
pub const PERIPHERAL_PRIVACY_FLAG: Uuid = bluetooth_uuid_from_u16(0x2A02);
pub const RECONNECTION_ADDRESS: Uuid = bluetooth_uuid_from_u16(0x2A03);
pub const PERIPHERAL_PREFERRED_CONNECTION_PARAMETERS: Uuid = bluetooth_uuid_from_u16(0x2A04);
pub const SERVICE_CHANGED: Uuid = bluetooth_uuid_from_u16(0x2A05);
pub const ALERT_LEVEL: Uuid = bluetooth_uuid_from_u16(0x2A06);
pub const TX_POWER_LEVEL: Uuid = bluetooth_uuid_from_u16(0x2A07);
pub const DATE_TIME: Uuid = bluetooth_uuid_from_u16(0x2A08);
pub const DAY_OF_WEEK: Uuid = bluetooth_uuid_from_u16(0x2A09);
pub const DAY_DATE_TIME: Uuid = bluetooth_uuid_from_u16(0x2A0A);
pub const EXACT_TIME_256: Uuid = bluetooth_uuid_from_u16(0x2A0C);
pub const DST_OFFSET: Uuid = bluetooth_uuid_from_u16(0x2A0D);
pub const TIME_ZONE: Uuid = bluetooth_uuid_from_u16(0x2A0E);
pub const LOCAL_TIME_INFORMATION: Uuid = bluetooth_uuid_from_u16(0x2A0F);
pub const TIME_WITH_DST: Uuid = bluetooth_uuid_from_u16(0x2A11);
pub const TIME_ACCURACY: Uuid = bluetooth_uuid_from_u16(0x2A12);
pub const TIME_SOURCE: Uuid = bluetooth_uuid_from_u16(0x2A13);
pub const REFERENCE_TIME_INFORMATION: Uuid = bluetooth_uuid_from_u16(0x2A14);
pub const TIME_UPDATE_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2A16);
pub const TIME_UPDATE_STATE: Uuid = bluetooth_uuid_from_u16(0x2A17);
pub const GLUCOSE_MEASUREMENT: Uuid = bluetooth_uuid_from_u16(0x2A18);
pub const BATTERY_LEVEL: Uuid = bluetooth_uuid_from_u16(0x2A19);
pub const TEMPERATURE_MEASUREMENT: Uuid = bluetooth_uuid_from_u16(0x2A1C);
pub const TEMPERATURE_TYPE: Uuid = bluetooth_uuid_from_u16(0x2A1D);
pub const INTERMEDIATE_TEMPERATURE: Uuid = bluetooth_uuid_from_u16(0x2A1E);
pub const MEASUREMENT_INTERVAL: Uuid = bluetooth_uuid_from_u16(0x2A21);
pub const BOOT_KEYBOARD_INPUT_REPORT: Uuid = bluetooth_uuid_from_u16(0x2A22);
pub const SYSTEM_ID: Uuid = bluetooth_uuid_from_u16(0x2A23);
pub const MODEL_NUMBER_STRING: Uuid = bluetooth_uuid_from_u16(0x2A24);
pub const SERIAL_NUMBER_STRING: Uuid = bluetooth_uuid_from_u16(0x2A25);
pub const FIRMWARE_REVISION_STRING: Uuid = bluetooth_uuid_from_u16(0x2A26);
pub const HARDWARE_REVISION_STRING: Uuid = bluetooth_uuid_from_u16(0x2A27);
pub const SOFTWARE_REVISION_STRING: Uuid = bluetooth_uuid_from_u16(0x2A28);
pub const MANUFACTURER_NAME_STRING: Uuid = bluetooth_uuid_from_u16(0x2A29);
pub const IEEE_11073_20601_REGULATORY_CERTIFICATION_DATA_LIST: Uuid = bluetooth_uuid_from_u16(0x2A2A);
pub const CURRENT_TIME: Uuid = bluetooth_uuid_from_u16(0x2A2B);
pub const SCAN_REFRESH: Uuid = bluetooth_uuid_from_u16(0x2A31);
pub const BOOT_KEYBOARD_OUTPUT_REPORT: Uuid = bluetooth_uuid_from_u16(0x2A32);
pub const BOOT_MOUSE_INPUT_REPORT: Uuid = bluetooth_uuid_from_u16(0x2A33);
pub const GLUCOSE_MEASUREMENT_CONTEXT: Uuid = bluetooth_uuid_from_u16(0x2A34);
pub const BLOOD_PRESSURE_MEASUREMENT: Uuid = bluetooth_uuid_from_u16(0x2A35);
pub const INTERMEDIATE_CUFF_PRESSURE: Uuid = bluetooth_uuid_from_u16(0x2A36);
pub const HEART_RATE_MEASUREMENT: Uuid = bluetooth_uuid_from_u16(0x2A37);
pub const BODY_SENSOR_LOCATION: Uuid = bluetooth_uuid_from_u16(0x2A38);
pub const HEART_RATE_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2A39);
pub const ALERT_STATUS: Uuid = bluetooth_uuid_from_u16(0x2A3F);
pub const RINGER_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2A40);
pub const RINGER_SETTING: Uuid = bluetooth_uuid_from_u16(0x2A41);
pub const ALERT_CATEGORY_ID_BIT_MASK: Uuid = bluetooth_uuid_from_u16(0x2A42);
pub const ALERT_CATEGORY_ID: Uuid = bluetooth_uuid_from_u16(0x2A43);
pub const ALERT_NOTIFICATION_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2A44);
pub const UNREAD_ALERT_STATUS: Uuid = bluetooth_uuid_from_u16(0x2A45);
pub const NEW_ALERT: Uuid = bluetooth_uuid_from_u16(0x2A46);
pub const SUPPORTED_NEW_ALERT_CATEGORY: Uuid = bluetooth_uuid_from_u16(0x2A47);
pub const SUPPORTED_UNREAD_ALERT_CATEGORY: Uuid = bluetooth_uuid_from_u16(0x2A48);
pub const BLOOD_PRESSURE_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2A49);
pub const HID_INFORMATION: Uuid = bluetooth_uuid_from_u16(0x2A4A);
pub const REPORT_MAP: Uuid = bluetooth_uuid_from_u16(0x2A4B);
pub const HID_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2A4C);
pub const REPORT: Uuid = bluetooth_uuid_from_u16(0x2A4D);
pub const PROTOCOL_MODE: Uuid = bluetooth_uuid_from_u16(0x2A4E);
pub const SCAN_INTERVAL_WINDOW: Uuid = bluetooth_uuid_from_u16(0x2A4F);
pub const PNP_ID: Uuid = bluetooth_uuid_from_u16(0x2A50);
pub const GLUCOSE_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2A51);
pub const RECORD_ACCESS_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2A52);
pub const RSC_MEASUREMENT: Uuid = bluetooth_uuid_from_u16(0x2A53);
pub const RSC_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2A54);
pub const SC_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2A55);
pub const AGGREGATE: Uuid = bluetooth_uuid_from_u16(0x2A5A);
pub const CSC_MEASUREMENT: Uuid = bluetooth_uuid_from_u16(0x2A5B);
pub const CSC_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2A5C);
pub const SENSOR_LOCATION: Uuid = bluetooth_uuid_from_u16(0x2A5D);
pub const PLX_SPOT_CHECK_MEASUREMENT: Uuid = bluetooth_uuid_from_u16(0x2A5E);
pub const PLX_CONTINUOUS_MEASUREMENT: Uuid = bluetooth_uuid_from_u16(0x2A5F);
pub const PLX_FEATURES: Uuid = bluetooth_uuid_from_u16(0x2A60);
pub const CYCLING_POWER_MEASUREMENT: Uuid = bluetooth_uuid_from_u16(0x2A63);
pub const CYCLING_POWER_VECTOR: Uuid = bluetooth_uuid_from_u16(0x2A64);
pub const CYCLING_POWER_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2A65);
pub const CYCLING_POWER_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2A66);
pub const LOCATION_AND_SPEED: Uuid = bluetooth_uuid_from_u16(0x2A67);
pub const NAVIGATION: Uuid = bluetooth_uuid_from_u16(0x2A68);
pub const POSITION_QUALITY: Uuid = bluetooth_uuid_from_u16(0x2A69);
pub const LN_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2A6A);
pub const LN_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2A6B);
pub const ELEVATION: Uuid = bluetooth_uuid_from_u16(0x2A6C);
pub const PRESSURE: Uuid = bluetooth_uuid_from_u16(0x2A6D);
pub const TEMPERATURE: Uuid = bluetooth_uuid_from_u16(0x2A6E);
pub const HUMIDITY: Uuid = bluetooth_uuid_from_u16(0x2A6F);
pub const TRUE_WIND_SPEED: Uuid = bluetooth_uuid_from_u16(0x2A70);
pub const TRUE_WIND_DIRECTION: Uuid = bluetooth_uuid_from_u16(0x2A71);
pub const APPARENT_WIND_SPEED: Uuid = bluetooth_uuid_from_u16(0x2A72);
pub const APPARENT_WIND_DIRECTION: Uuid = bluetooth_uuid_from_u16(0x2A73);
pub const GUST_FACTOR: Uuid = bluetooth_uuid_from_u16(0x2A74);
pub const POLLEN_CONCENTRATION: Uuid = bluetooth_uuid_from_u16(0x2A75);
pub const UV_INDEX: Uuid = bluetooth_uuid_from_u16(0x2A76);
pub const IRRADIANCE: Uuid = bluetooth_uuid_from_u16(0x2A77);
pub const RAINFALL: Uuid = bluetooth_uuid_from_u16(0x2A78);
pub const WIND_CHILL: Uuid = bluetooth_uuid_from_u16(0x2A79);
pub const HEAT_INDEX: Uuid = bluetooth_uuid_from_u16(0x2A7A);
pub const DEW_POINT: Uuid = bluetooth_uuid_from_u16(0x2A7B);
pub const DESCRIPTOR_VALUE_CHANGED: Uuid = bluetooth_uuid_from_u16(0x2A7D);
pub const AEROBIC_HEART_RATE_LOWER_LIMIT: Uuid = bluetooth_uuid_from_u16(0x2A7E);
pub const AEROBIC_THRESHOLD: Uuid = bluetooth_uuid_from_u16(0x2A7F);
pub const AGE: Uuid = bluetooth_uuid_from_u16(0x2A80);
pub const ANAEROBIC_HEART_RATE_LOWER_LIMIT: Uuid = bluetooth_uuid_from_u16(0x2A81);
pub const ANAEROBIC_HEART_RATE_UPPER_LIMIT: Uuid = bluetooth_uuid_from_u16(0x2A82);
pub const ANAEROBIC_THRESHOLD: Uuid = bluetooth_uuid_from_u16(0x2A83);
pub const AEROBIC_HEART_RATE_UPPER_LIMIT: Uuid = bluetooth_uuid_from_u16(0x2A84);
pub const DATE_OF_BIRTH: Uuid = bluetooth_uuid_from_u16(0x2A85);
pub const DATE_OF_THRESHOLD_ASSESSMENT: Uuid = bluetooth_uuid_from_u16(0x2A86);
pub const EMAIL_ADDRESS: Uuid = bluetooth_uuid_from_u16(0x2A87);
pub const FAT_BURN_HEART_RATE_LOWER_LIMIT: Uuid = bluetooth_uuid_from_u16(0x2A88);
pub const FAT_BURN_HEART_RATE_UPPER_LIMIT: Uuid = bluetooth_uuid_from_u16(0x2A89);
pub const FIRST_NAME: Uuid = bluetooth_uuid_from_u16(0x2A8A);
pub const FIVE_ZONE_HEART_RATE_LIMITS: Uuid = bluetooth_uuid_from_u16(0x2A8B);
pub const GENDER: Uuid = bluetooth_uuid_from_u16(0x2A8C);
pub const HEART_RATE_MAX: Uuid = bluetooth_uuid_from_u16(0x2A8D);
pub const HEIGHT: Uuid = bluetooth_uuid_from_u16(0x2A8E);
pub const HIP_CIRCUMFERENCE: Uuid = bluetooth_uuid_from_u16(0x2A8F);
pub const LAST_NAME: Uuid = bluetooth_uuid_from_u16(0x2A90);
pub const MAXIMUM_RECOMMENDED_HEART_RATE: Uuid = bluetooth_uuid_from_u16(0x2A91);
pub const RESTING_HEART_RATE: Uuid = bluetooth_uuid_from_u16(0x2A92);
pub const SPORT_TYPE_FOR_AEROBIC_AND_ANAEROBIC_THRESHOLDS: Uuid = bluetooth_uuid_from_u16(0x2A93);
pub const THREE_ZONE_HEART_RATE_LIMITS: Uuid = bluetooth_uuid_from_u16(0x2A94);
pub const TWO_ZONE_HEART_RATE_LIMITS: Uuid = bluetooth_uuid_from_u16(0x2A95);
pub const VO2_MAX: Uuid = bluetooth_uuid_from_u16(0x2A96);
pub const WAIST_CIRCUMFERENCE: Uuid = bluetooth_uuid_from_u16(0x2A97);
pub const WEIGHT: Uuid = bluetooth_uuid_from_u16(0x2A98);
pub const DATABASE_CHANGE_INCREMENT: Uuid = bluetooth_uuid_from_u16(0x2A99);
pub const USER_INDEX: Uuid = bluetooth_uuid_from_u16(0x2A9A);
pub const BODY_COMPOSITION_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2A9B);
pub const BODY_COMPOSITION_MEASUREMENT: Uuid = bluetooth_uuid_from_u16(0x2A9C);
pub const WEIGHT_MEASUREMENT: Uuid = bluetooth_uuid_from_u16(0x2A9D);
pub const WEIGHT_SCALE_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2A9E);
pub const USER_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2A9F);
pub const MAGNETIC_FLUX_DENSITY_2D: Uuid = bluetooth_uuid_from_u16(0x2AA0);
pub const MAGNETIC_FLUX_DENSITY_3D: Uuid = bluetooth_uuid_from_u16(0x2AA1);
pub const LANGUAGE: Uuid = bluetooth_uuid_from_u16(0x2AA2);
pub const BAROMETRIC_PRESSURE_TREND: Uuid = bluetooth_uuid_from_u16(0x2AA3);
pub const BOND_MANAGEMENT_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2AA4);
pub const BOND_MANAGEMENT_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2AA5);
pub const CENTRAL_ADDRESS_RESOLUTION: Uuid = bluetooth_uuid_from_u16(0x2AA6);
pub const CGM_MEASUREMENT: Uuid = bluetooth_uuid_from_u16(0x2AA7);
pub const CGM_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2AA8);
pub const CGM_STATUS: Uuid = bluetooth_uuid_from_u16(0x2AA9);
pub const CGM_SESSION_START_TIME: Uuid = bluetooth_uuid_from_u16(0x2AAA);
pub const CGM_SESSION_RUN_TIME: Uuid = bluetooth_uuid_from_u16(0x2AAB);
pub const CGM_SPECIFIC_OPS_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2AAC);
pub const INDOOR_POSITIONING_CONFIGURATION: Uuid = bluetooth_uuid_from_u16(0x2AAD);
pub const LATITUDE: Uuid = bluetooth_uuid_from_u16(0x2AAE);
pub const LONGITUDE: Uuid = bluetooth_uuid_from_u16(0x2AAF);
pub const LOCAL_NORTH_COORDINATE: Uuid = bluetooth_uuid_from_u16(0x2AB0);
pub const LOCAL_EAST_COORDINATE: Uuid = bluetooth_uuid_from_u16(0x2AB1);
pub const FLOOR_NUMBER: Uuid = bluetooth_uuid_from_u16(0x2AB2);
pub const ALTITUDE: Uuid = bluetooth_uuid_from_u16(0x2AB3);
pub const UNCERTAINTY: Uuid = bluetooth_uuid_from_u16(0x2AB4);
pub const LOCATION_NAME: Uuid = bluetooth_uuid_from_u16(0x2AB5);
pub const URI: Uuid = bluetooth_uuid_from_u16(0x2AB6);
pub const HTTP_HEADERS: Uuid = bluetooth_uuid_from_u16(0x2AB7);
pub const HTTP_STATUS_CODE: Uuid = bluetooth_uuid_from_u16(0x2AB8);
pub const HTTP_ENTITY_BODY: Uuid = bluetooth_uuid_from_u16(0x2AB9);
pub const HTTP_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2ABA);
pub const HTTPS_SECURITY: Uuid = bluetooth_uuid_from_u16(0x2ABB);
pub const TDS_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2ABC);
pub const OTS_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2ABD);
pub const OBJECT_NAME: Uuid = bluetooth_uuid_from_u16(0x2ABE);
pub const OBJECT_TYPE: Uuid = bluetooth_uuid_from_u16(0x2ABF);
pub const OBJECT_SIZE: Uuid = bluetooth_uuid_from_u16(0x2AC0);
pub const OBJECT_FIRST_CREATED: Uuid = bluetooth_uuid_from_u16(0x2AC1);
pub const OBJECT_LAST_MODIFIED: Uuid = bluetooth_uuid_from_u16(0x2AC2);
pub const OBJECT_ID: Uuid = bluetooth_uuid_from_u16(0x2AC3);
pub const OBJECT_PROPERTIES: Uuid = bluetooth_uuid_from_u16(0x2AC4);
pub const OBJECT_ACTION_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2AC5);
pub const OBJECT_LIST_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2AC6);
pub const OBJECT_LIST_FILTER: Uuid = bluetooth_uuid_from_u16(0x2AC7);
pub const OBJECT_CHANGED: Uuid = bluetooth_uuid_from_u16(0x2AC8);
pub const RESOLVABLE_PRIVATE_ADDRESS_ONLY: Uuid = bluetooth_uuid_from_u16(0x2AC9);
pub const UNSPECIFIED: Uuid = bluetooth_uuid_from_u16(0x2ACA);
pub const DIRECTORY_LISTING: Uuid = bluetooth_uuid_from_u16(0x2ACB);
pub const FITNESS_MACHINE_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2ACC);
pub const TREADMILL_DATA: Uuid = bluetooth_uuid_from_u16(0x2ACD);
pub const CROSS_TRAINER_DATA: Uuid = bluetooth_uuid_from_u16(0x2ACE);
pub const STEP_CLIMBER_DATA: Uuid = bluetooth_uuid_from_u16(0x2ACF);
pub const STAIR_CLIMBER_DATA: Uuid = bluetooth_uuid_from_u16(0x2AD0);
pub const ROWER_DATA: Uuid = bluetooth_uuid_from_u16(0x2AD1);
pub const INDOOR_BIKE_DATA: Uuid = bluetooth_uuid_from_u16(0x2AD2);
pub const TRAINING_STATUS: Uuid = bluetooth_uuid_from_u16(0x2AD3);
pub const SUPPORTED_SPEED_RANGE: Uuid = bluetooth_uuid_from_u16(0x2AD4);
pub const SUPPORTED_INCLINATION_RANGE: Uuid = bluetooth_uuid_from_u16(0x2AD5);
pub const SUPPORTED_RESISTANCE_LEVEL_RANGE: Uuid = bluetooth_uuid_from_u16(0x2AD6);
pub const SUPPORTED_HEART_RATE_RANGE: Uuid = bluetooth_uuid_from_u16(0x2AD7);
pub const SUPPORTED_POWER_RANGE: Uuid = bluetooth_uuid_from_u16(0x2AD8);
pub const FITNESS_MACHINE_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2AD9);
pub const FITNESS_MACHINE_STATUS: Uuid = bluetooth_uuid_from_u16(0x2ADA);
pub const MESH_PROVISIONING_DATA_IN: Uuid = bluetooth_uuid_from_u16(0x2ADB);
pub const MESH_PROVISIONING_DATA_OUT: Uuid = bluetooth_uuid_from_u16(0x2ADC);
pub const MESH_PROXY_DATA_IN: Uuid = bluetooth_uuid_from_u16(0x2ADD);
pub const MESH_PROXY_DATA_OUT: Uuid = bluetooth_uuid_from_u16(0x2ADE);
pub const AVERAGE_CURRENT: Uuid = bluetooth_uuid_from_u16(0x2AE0);
pub const AVERAGE_VOLTAGE: Uuid = bluetooth_uuid_from_u16(0x2AE1);
pub const BOOLEAN: Uuid = bluetooth_uuid_from_u16(0x2AE2);
pub const CHROMATIC_DISTANCE_FROM_PLANCKIAN: Uuid = bluetooth_uuid_from_u16(0x2AE3);
pub const CHROMATICITY_COORDINATES: Uuid = bluetooth_uuid_from_u16(0x2AE4);
pub const CHROMATICITY_IN_CCT_AND_DUV_VALUES: Uuid = bluetooth_uuid_from_u16(0x2AE5);
pub const CHROMATICITY_TOLERANCE: Uuid = bluetooth_uuid_from_u16(0x2AE6);
pub const CIE_13_3_1995_COLOR_RENDERING_INDEX: Uuid = bluetooth_uuid_from_u16(0x2AE7);
pub const COEFFICIENT: Uuid = bluetooth_uuid_from_u16(0x2AE8);
pub const CORRELATED_COLOR_TEMPERATURE: Uuid = bluetooth_uuid_from_u16(0x2AE9);
pub const COUNT_16: Uuid = bluetooth_uuid_from_u16(0x2AEA);
pub const COUNT_24: Uuid = bluetooth_uuid_from_u16(0x2AEB);
pub const COUNTRY_CODE: Uuid = bluetooth_uuid_from_u16(0x2AEC);
pub const DATE_UTC: Uuid = bluetooth_uuid_from_u16(0x2AED);
pub const ELECTRIC_CURRENT: Uuid = bluetooth_uuid_from_u16(0x2AEE);
pub const ELECTRIC_CURRENT_RANGE: Uuid = bluetooth_uuid_from_u16(0x2AEF);
pub const ELECTRIC_CURRENT_SPECIFICATION: Uuid = bluetooth_uuid_from_u16(0x2AF0);
pub const ELECTRIC_CURRENT_STATISTICS: Uuid = bluetooth_uuid_from_u16(0x2AF1);
pub const ENERGY: Uuid = bluetooth_uuid_from_u16(0x2AF2);
pub const ENERGY_IN_A_PERIOD_OF_DAY: Uuid = bluetooth_uuid_from_u16(0x2AF3);
pub const EVENT_STATISTICS: Uuid = bluetooth_uuid_from_u16(0x2AF4);
pub const FIXED_STRING_16: Uuid = bluetooth_uuid_from_u16(0x2AF5);
pub const FIXED_STRING_24: Uuid = bluetooth_uuid_from_u16(0x2AF6);
pub const FIXED_STRING_36: Uuid = bluetooth_uuid_from_u16(0x2AF7);
pub const FIXED_STRING_8: Uuid = bluetooth_uuid_from_u16(0x2AF8);
pub const GENERIC_LEVEL: Uuid = bluetooth_uuid_from_u16(0x2AF9);
pub const GLOBAL_TRADE_ITEM_NUMBER: Uuid = bluetooth_uuid_from_u16(0x2AFA);
pub const ILLUMINANCE: Uuid = bluetooth_uuid_from_u16(0x2AFB);
pub const LUMINOUS_EFFICACY: Uuid = bluetooth_uuid_from_u16(0x2AFC);
pub const LUMINOUS_ENERGY: Uuid = bluetooth_uuid_from_u16(0x2AFD);
pub const LUMINOUS_EXPOSURE: Uuid = bluetooth_uuid_from_u16(0x2AFE);
pub const LUMINOUS_FLUX: Uuid = bluetooth_uuid_from_u16(0x2AFF);
pub const LUMINOUS_FLUX_RANGE: Uuid = bluetooth_uuid_from_u16(0x2B00);
pub const LUMINOUS_INTENSITY: Uuid = bluetooth_uuid_from_u16(0x2B01);
pub const MASS_FLOW: Uuid = bluetooth_uuid_from_u16(0x2B02);
pub const PERCEIVED_LIGHTNESS: Uuid = bluetooth_uuid_from_u16(0x2B03);
pub const PERCENTAGE_8: Uuid = bluetooth_uuid_from_u16(0x2B04);
pub const POWER: Uuid = bluetooth_uuid_from_u16(0x2B05);
pub const POWER_SPECIFICATION: Uuid = bluetooth_uuid_from_u16(0x2B06);
pub const RELATIVE_RUNTIME_IN_A_CURRENT_RANGE: Uuid = bluetooth_uuid_from_u16(0x2B07);
pub const RELATIVE_RUNTIME_IN_A_GENERIC_LEVEL_RANGE: Uuid = bluetooth_uuid_from_u16(0x2B08);
pub const RELATIVE_VALUE_IN_A_VOLTAGE_RANGE: Uuid = bluetooth_uuid_from_u16(0x2B09);
pub const RELATIVE_VALUE_IN_AN_ILLUMINANCE_RANGE: Uuid = bluetooth_uuid_from_u16(0x2B0A);
pub const RELATIVE_VALUE_IN_A_PERIOD_OF_DAY: Uuid = bluetooth_uuid_from_u16(0x2B0B);
pub const RELATIVE_VALUE_IN_A_TEMPERATURE_RANGE: Uuid = bluetooth_uuid_from_u16(0x2B0C);
pub const TEMPERATURE_8: Uuid = bluetooth_uuid_from_u16(0x2B0D);
pub const TEMPERATURE_8_IN_A_PERIOD_OF_DAY: Uuid = bluetooth_uuid_from_u16(0x2B0E);
pub const TEMPERATURE_8_STATISTICS: Uuid = bluetooth_uuid_from_u16(0x2B0F);
pub const TEMPERATURE_RANGE: Uuid = bluetooth_uuid_from_u16(0x2B10);
pub const TEMPERATURE_STATISTICS: Uuid = bluetooth_uuid_from_u16(0x2B11);
pub const TIME_DECIHOUR_8: Uuid = bluetooth_uuid_from_u16(0x2B12);
pub const TIME_EXPONENTIAL_8: Uuid = bluetooth_uuid_from_u16(0x2B13);
pub const TIME_HOUR_24: Uuid = bluetooth_uuid_from_u16(0x2B14);
pub const TIME_MILLISECOND_24: Uuid = bluetooth_uuid_from_u16(0x2B15);
pub const TIME_SECOND_16: Uuid = bluetooth_uuid_from_u16(0x2B16);
pub const TIME_SECOND_8: Uuid = bluetooth_uuid_from_u16(0x2B17);
pub const VOLTAGE: Uuid = bluetooth_uuid_from_u16(0x2B18);
pub const VOLTAGE_SPECIFICATION: Uuid = bluetooth_uuid_from_u16(0x2B19);
pub const VOLTAGE_STATISTICS: Uuid = bluetooth_uuid_from_u16(0x2B1A);
pub const VOLUME_FLOW: Uuid = bluetooth_uuid_from_u16(0x2B1B);
pub const CHROMATICITY_COORDINATE: Uuid = bluetooth_uuid_from_u16(0x2B1C);
pub const RC_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2B1D);
pub const RC_SETTINGS: Uuid = bluetooth_uuid_from_u16(0x2B1E);
pub const RECONNECTION_CONFIGURATION_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2B1F);
pub const IDD_STATUS_CHANGED: Uuid = bluetooth_uuid_from_u16(0x2B20);
pub const IDD_STATUS: Uuid = bluetooth_uuid_from_u16(0x2B21);
pub const IDD_ANNUNCIATION_STATUS: Uuid = bluetooth_uuid_from_u16(0x2B22);
pub const IDD_FEATURES: Uuid = bluetooth_uuid_from_u16(0x2B23);
pub const IDD_STATUS_READER_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2B24);
pub const IDD_COMMAND_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2B25);
pub const IDD_COMMAND_DATA: Uuid = bluetooth_uuid_from_u16(0x2B26);
pub const IDD_RECORD_ACCESS_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2B27);
pub const IDD_HISTORY_DATA: Uuid = bluetooth_uuid_from_u16(0x2B28);
pub const CLIENT_SUPPORTED_FEATURES: Uuid = bluetooth_uuid_from_u16(0x2B29);
pub const DATABASE_HASH: Uuid = bluetooth_uuid_from_u16(0x2B2A);
pub const BSS_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2B2B);
pub const BSS_RESPONSE: Uuid = bluetooth_uuid_from_u16(0x2B2C);
pub const EMERGENCY_ID: Uuid = bluetooth_uuid_from_u16(0x2B2D);
pub const EMERGENCY_TEXT: Uuid = bluetooth_uuid_from_u16(0x2B2E);
pub const ENHANCED_BLOOD_PRESSURE_MEASUREMENT: Uuid = bluetooth_uuid_from_u16(0x2B34);
pub const ENHANCED_INTERMEDIATE_CUFF_PRESSURE: Uuid = bluetooth_uuid_from_u16(0x2B35);
pub const BLOOD_PRESSURE_RECORD: Uuid = bluetooth_uuid_from_u16(0x2B36);
pub const BR_EDR_HANDOVER_DATA: Uuid = bluetooth_uuid_from_u16(0x2B38);
pub const BLUETOOTH_SIG_DATA: Uuid = bluetooth_uuid_from_u16(0x2B39);
pub const SERVER_SUPPORTED_FEATURES: Uuid = bluetooth_uuid_from_u16(0x2B3A);
pub const PHYSICAL_ACTIVITY_MONITOR_FEATURES: Uuid = bluetooth_uuid_from_u16(0x2B3B);
pub const GENERAL_ACTIVITY_INSTANTANEOUS_DATA: Uuid = bluetooth_uuid_from_u16(0x2B3C);
pub const GENERAL_ACTIVITY_SUMMARY_DATA: Uuid = bluetooth_uuid_from_u16(0x2B3D);
pub const CARDIORESPIRATORY_ACTIVITY_INSTANTANEOUS_DATA: Uuid = bluetooth_uuid_from_u16(0x2B3E);
pub const CARDIORESPIRATORY_ACTIVITY_SUMMARY_DATA: Uuid = bluetooth_uuid_from_u16(0x2B3F);
pub const STEP_COUNTER_ACTIVITY_SUMMARY_DATA: Uuid = bluetooth_uuid_from_u16(0x2B40);
pub const SLEEP_ACTIVITY_INSTANTANEOUS_DATA: Uuid = bluetooth_uuid_from_u16(0x2B41);
pub const SLEEP_ACTIVITY_SUMMARY_DATA: Uuid = bluetooth_uuid_from_u16(0x2B42);
pub const PHYSICAL_ACTIVITY_MONITOR_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2B43);
pub const ACTIVITY_CURRENT_SESSION: Uuid = bluetooth_uuid_from_u16(0x2B44);
pub const PHYSICAL_ACTIVITY_SESSION_DESCRIPTOR: Uuid = bluetooth_uuid_from_u16(0x2B45);
pub const PREFERRED_UNITS: Uuid = bluetooth_uuid_from_u16(0x2B46);
pub const HIGH_RESOLUTION_HEIGHT: Uuid = bluetooth_uuid_from_u16(0x2B47);
pub const MIDDLE_NAME: Uuid = bluetooth_uuid_from_u16(0x2B48);
pub const STRIDE_LENGTH: Uuid = bluetooth_uuid_from_u16(0x2B49);
pub const HANDEDNESS: Uuid = bluetooth_uuid_from_u16(0x2B4A);
pub const DEVICE_WEARING_POSITION: Uuid = bluetooth_uuid_from_u16(0x2B4B);
pub const FOUR_ZONE_HEART_RATE_LIMITS: Uuid = bluetooth_uuid_from_u16(0x2B4C);
pub const HIGH_INTENSITY_EXERCISE_THRESHOLD: Uuid = bluetooth_uuid_from_u16(0x2B4D);
pub const ACTIVITY_GOAL: Uuid = bluetooth_uuid_from_u16(0x2B4E);
pub const SEDENTARY_INTERVAL_NOTIFICATION: Uuid = bluetooth_uuid_from_u16(0x2B4F);
pub const CALORIC_INTAKE: Uuid = bluetooth_uuid_from_u16(0x2B50);
pub const TMAP_ROLE: Uuid = bluetooth_uuid_from_u16(0x2B51);
pub const AUDIO_INPUT_STATE: Uuid = bluetooth_uuid_from_u16(0x2B77);
pub const GAIN_SETTINGS_ATTRIBUTE: Uuid = bluetooth_uuid_from_u16(0x2B78);
pub const AUDIO_INPUT_TYPE: Uuid = bluetooth_uuid_from_u16(0x2B79);
pub const AUDIO_INPUT_STATUS: Uuid = bluetooth_uuid_from_u16(0x2B7A);
pub const AUDIO_INPUT_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2B7B);
pub const AUDIO_INPUT_DESCRIPTION: Uuid = bluetooth_uuid_from_u16(0x2B7C);
pub const VOLUME_STATE: Uuid = bluetooth_uuid_from_u16(0x2B7D);
pub const VOLUME_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2B7E);
pub const VOLUME_FLAGS: Uuid = bluetooth_uuid_from_u16(0x2B7F);
pub const VOLUME_OFFSET_STATE: Uuid = bluetooth_uuid_from_u16(0x2B80);
pub const AUDIO_LOCATION: Uuid = bluetooth_uuid_from_u16(0x2B81);
pub const VOLUME_OFFSET_CONTROL_POINT: Uuid = bluetooth_uuid_from_u16(0x2B82);
pub const AUDIO_OUTPUT_DESCRIPTION: Uuid = bluetooth_uuid_from_u16(0x2B83);
pub const SET_IDENTITY_RESOLVING_KEY: Uuid = bluetooth_uuid_from_u16(0x2B84);
pub const COORDINATED_SET_SIZE: Uuid = bluetooth_uuid_from_u16(0x2B85);
pub const SET_MEMBER_LOCK: Uuid = bluetooth_uuid_from_u16(0x2B86);
pub const SET_MEMBER_RANK: Uuid = bluetooth_uuid_from_u16(0x2B87);
pub const DEVICE_TIME_FEATURE: Uuid = bluetooth_uuid_from_u16(0x2B8E);
pub const DEVICE_TIME_PARAMETERS: Uuid = bluetooth_uuid_from_u16(0x2B8F);
pub const DEVICE_TIME: Uuid = bluetooth_uuid_from_u16(0x2B90);
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | true |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/android.rs | src/android.rs | use java_spaghetti::{CastError, Local};
use self::bindings::java::lang::Throwable;
use crate::error::ErrorKind;
pub mod adapter;
pub mod characteristic;
pub mod descriptor;
pub mod device;
pub mod l2cap_channel;
pub mod service;
#[allow(mismatched_lifetime_syntaxes)]
pub(crate) mod bindings;
/// A platform-specific device identifier.
/// On android it contains the Bluetooth address in the format `AB:CD:EF:01:23:45`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DeviceId(pub(crate) String);
impl std::fmt::Display for DeviceId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
impl From<Local<'_, Throwable>> for crate::Error {
fn from(e: Local<'_, Throwable>) -> Self {
Self::new(ErrorKind::Internal, None, format!("{e:?}"))
}
}
impl From<CastError> for crate::Error {
fn from(e: CastError) -> Self {
Self::new(ErrorKind::Internal, None, format!("{e:?}"))
}
}
struct JavaIterator<'env>(Local<'env, bindings::java::util::Iterator>);
impl<'env> Iterator for JavaIterator<'env> {
type Item = Local<'env, bindings::java::lang::Object>;
fn next(&mut self) -> Option<Self::Item> {
if self.0.hasNext().unwrap() {
let obj = self.0.next().unwrap().unwrap();
// upgrade lifetime to the original env.
let obj = unsafe { Local::from_raw(self.0.env(), obj.into_raw()) };
Some(obj)
} else {
None
}
}
}
trait OptionExt<T> {
fn non_null(self) -> Result<T, crate::Error>;
}
impl<T> OptionExt<T> for Option<T> {
#[track_caller]
fn non_null(self) -> Result<T, crate::Error> {
self.ok_or_else(|| crate::Error::new(ErrorKind::Internal, None, "Java call unexpectedly returned null."))
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/pairing.rs | src/pairing.rs | //! Custom Bluetooth pairing agent.
use async_trait::async_trait;
use crate::Device;
/// Bluetooth input/output capabilities for pairing
///
/// See the Bluetooth Core Specification, Vol 3, Part H, §2.3.2
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum IoCapability {
/// Can display a passkey but not accept user input
DisplayOnly,
/// Can display a passkey and request simple confirmation from the user
DisplayYesNo,
/// Can request a passkey from the user but not display anything
KeyboardOnly,
/// Cannot display anything to or request anything from the user
NoInputNoOutput,
/// Can display a passkey to and/or request a passkey or confirmation from the user
KeyboardDisplay,
}
/// An error indicating the pairing request has been rejected
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub struct PairingRejected;
impl std::fmt::Display for PairingRejected {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("pairing rejected")
}
}
impl std::error::Error for PairingRejected {}
/// An error returned when trying to convert an invalid value value into a [`Passkey`]
///
/// `Passkey`s must be a 6-digit numeric value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InvalidPasskey(());
impl std::fmt::Display for InvalidPasskey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("invalid passkey")
}
}
impl std::error::Error for InvalidPasskey {}
/// A Bluetooth 6-digit passkey
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Passkey(u32);
impl Passkey {
/// Creates a new `Passkey` from a `u32`
pub fn new(n: u32) -> Self {
assert!(n <= 999_999);
Passkey(n)
}
}
impl std::fmt::Display for Passkey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:06}", self.0)
}
}
impl From<Passkey> for u32 {
fn from(val: Passkey) -> Self {
val.0
}
}
impl std::convert::TryFrom<u32> for Passkey {
type Error = InvalidPasskey;
fn try_from(value: u32) -> Result<Self, Self::Error> {
if value <= 999_999 {
Ok(Passkey(value))
} else {
Err(InvalidPasskey(()))
}
}
}
impl std::str::FromStr for Passkey {
type Err = InvalidPasskey;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.parse::<u32>()
.map_err(|_| InvalidPasskey(()))
.and_then(Passkey::try_from)
}
}
/// A custom pairing agent responsible for interacting with the user during the peripheral pairing process.
#[async_trait]
pub trait PairingAgent: Send + Sync {
/// The input/output capabilities of this agent
fn io_capability(&self) -> IoCapability;
/// Request pairing confirmation from the user.
///
/// Must be supported if `io_capability` is `DisplayYesNo`, `KeyboardOnly`, `NoInputOutput`, or `KeyboardDisplay`
async fn confirm(&self, _device: &Device) -> Result<(), PairingRejected> {
Err(PairingRejected)
}
/// Request pairing confirmation from the user. The `passkey` should be displayed for validation.
///
/// Must be supported if `io_capability` is `DisplayYesNo`, `KeyboardOnly`, or `KeyboardDisplay`
async fn confirm_passkey(&self, _device: &Device, _passkey: Passkey) -> Result<(), PairingRejected> {
Err(PairingRejected)
}
/// Request a 6 digit numeric passkey from the user.
///
/// Must be supported if `io_capability` is `KeyboardOnly` or `KeyboardDisplay`
async fn request_passkey(&self, _device: &Device) -> Result<Passkey, PairingRejected> {
Err(PairingRejected)
}
/// Display a 6 digit numeric passkey to the user.
///
/// The passkey should be displayed until the async pair operation that triggered this method completes or is
/// cancelled.
///
/// Must be supported if `io_capability` is `DisplayOnly`, `DisplayYesNo`, or `KeyboardDisplay`
fn display_passkey(&self, _device: &Device, _passkey: Passkey) {}
}
/// The simplest possible pairing agent.
///
/// This agent does not interact with the user and automatically confirms any pairing requests that do not require
/// input or output. This allows for "JustWorks" pairing which provides encryption but not authentication or protection
/// from man-in-the-middle attacks.
pub struct NoInputOutputPairingAgent;
#[async_trait]
impl PairingAgent for NoInputOutputPairingAgent {
fn io_capability(&self) -> IoCapability {
IoCapability::NoInputNoOutput
}
async fn confirm(&self, _device: &Device) -> Result<(), PairingRejected> {
Ok(())
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/l2cap_channel.rs | src/l2cap_channel.rs | use std::pin;
use std::task::{Context, Poll};
use futures_lite::io::{AsyncRead, AsyncWrite};
use crate::sys;
#[allow(unused)]
pub(crate) const PIPE_CAPACITY: usize = 0x100000; // 1Mb
macro_rules! derive_async_read {
($type:ty, $field:tt) => {
impl AsyncRead for $type {
fn poll_read(
mut self: pin::Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<std::io::Result<usize>> {
let reader = pin::pin!(&mut self.$field);
reader.poll_read(cx, buf)
}
}
};
}
macro_rules! derive_async_write {
($type:ty, $field:tt) => {
impl AsyncWrite for $type {
fn poll_write(
mut self: pin::Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
let writer = pin::pin!(&mut self.$field);
writer.poll_write(cx, buf)
}
fn poll_flush(mut self: pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let writer = pin::pin!(&mut self.$field);
writer.poll_flush(cx)
}
fn poll_close(mut self: pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let writer = pin::pin!(&mut self.$field);
writer.poll_close(cx)
}
fn poll_write_vectored(
mut self: pin::Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[std::io::IoSlice<'_>],
) -> Poll<std::io::Result<usize>> {
let writer = pin::pin!(&mut self.$field);
writer.poll_write_vectored(cx, bufs)
}
}
};
}
pub(crate) use {derive_async_read, derive_async_write};
/// A Bluetooth LE L2CAP Connection-oriented Channel (CoC)
pub struct L2capChannel(pub(super) sys::l2cap_channel::L2capChannel);
impl L2capChannel {
/// Splits the channel into a read half and a write half
pub fn split(self) -> (L2capChannelReader, L2capChannelWriter) {
let (reader, writer) = self.0.split();
(L2capChannelReader { reader }, L2capChannelWriter { writer })
}
}
derive_async_read!(L2capChannel, 0);
derive_async_write!(L2capChannel, 0);
/// Reader half of a L2CAP Connection-oriented Channel (CoC)
#[derive(Debug)]
pub struct L2capChannelReader {
reader: sys::l2cap_channel::L2capChannelReader,
}
/// Writerhalf of a L2CAP Connection-oriented Channel (CoC)
#[derive(Debug)]
pub struct L2capChannelWriter {
writer: sys::l2cap_channel::L2capChannelWriter,
}
derive_async_read!(L2capChannelReader, reader);
derive_async_write!(L2capChannelWriter, writer);
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/adapter.rs | src/adapter.rs | #![allow(clippy::let_unit_value)]
use futures_core::Stream;
use crate::{sys, AdapterEvent, AdvertisingDevice, ConnectionEvent, Device, DeviceId, Result, Uuid};
/// The system's Bluetooth adapter interface.
///
/// The default adapter for the system may be accessed with the [`Adapter::default()`] method.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Adapter(sys::adapter::AdapterImpl);
/// Configuration options when creating the Bluetooth adapter interface.
pub type AdapterConfig = sys::adapter::AdapterConfig;
impl Adapter {
/// Creates an interface to a Bluetooth adapter using the provided config.
pub async fn with_config(config: AdapterConfig) -> Result<Self> {
sys::adapter::AdapterImpl::with_config(config).await.map(Adapter)
}
/// Creates an interface to a Bluetooth adapter using the default config.
#[inline]
#[cfg(not(target_os = "android"))]
pub async fn default() -> Result<Self> {
sys::adapter::AdapterImpl::with_config(AdapterConfig::default())
.await
.map(Adapter)
}
/// A stream of [`AdapterEvent`] which allows the application to identify when the adapter is enabled or disabled.
#[inline]
pub async fn events(&self) -> Result<impl Stream<Item = Result<AdapterEvent>> + Send + Unpin + '_> {
self.0.events().await
}
/// Check if the adapter is available
#[inline]
pub async fn is_available(&self) -> Result<bool> {
self.0.is_available().await
}
/// Asynchronously blocks until the adapter is available
#[inline]
pub async fn wait_available(&self) -> Result<()> {
self.0.wait_available().await
}
/// Attempts to create the device identified by `id`
#[inline]
pub async fn open_device(&self, id: &DeviceId) -> Result<Device> {
self.0.open_device(id).await
}
/// Finds all connected Bluetooth LE devices
#[inline]
pub async fn connected_devices(&self) -> Result<Vec<Device>> {
self.0.connected_devices().await
}
/// Finds all connected devices providing any service in `services`
///
/// # Panics
///
/// Panics if `services` is empty.
#[inline]
pub async fn connected_devices_with_services(&self, services: &[Uuid]) -> Result<Vec<Device>> {
self.0.connected_devices_with_services(services).await
}
/// Starts scanning for Bluetooth advertising packets.
///
/// Returns a stream of [`AdvertisingDevice`] structs which contain the data from the advertising packet and the
/// [`Device`] which sent it. Scanning is automatically stopped when the stream is dropped. Inclusion of duplicate
/// packets is a platform-specific implementation detail.
///
/// If `services` is not empty, returns advertisements including at least one GATT service with a UUID in
/// `services`. Otherwise returns all advertisements.
#[inline]
pub async fn scan<'a>(
&'a self,
services: &'a [Uuid],
) -> Result<impl Stream<Item = AdvertisingDevice> + Send + Unpin + 'a> {
self.0.scan(services).await
}
/// Finds Bluetooth devices providing any service in `services`.
///
/// Returns a stream of [`Device`] structs with matching connected devices returned first. If the stream is not
/// dropped before all matching connected devices are consumed then scanning will begin for devices advertising any
/// of the `services`. Scanning will continue until the stream is dropped. Inclusion of duplicate devices is a
/// platform-specific implementation detail.
#[inline]
pub async fn discover_devices<'a>(
&'a self,
services: &'a [Uuid],
) -> Result<impl Stream<Item = Result<Device>> + Send + Unpin + 'a> {
self.0.discover_devices(services).await
}
/// Connects to the [`Device`]
///
/// # Platform specifics
///
/// ## MacOS/iOS
///
/// This method must be called before any methods on the [`Device`] which require a connection are called. After a
/// successful return from this method, a connection has been established with the device (if one did not already
/// exist) and the application can then interact with the device. This connection will be maintained until either
/// [`disconnect_device`][Self::disconnect_device] is called or the `Adapter` is dropped.
///
/// ## Windows
///
/// On Windows, device connections are automatically managed by the OS. This method has no effect. Instead, a
/// connection will automatically be established, if necessary, when methods on the device requiring a connection
/// are called.
///
/// ## Linux
///
/// If the device is not yet connected to the system, this method must be called before any methods on the
/// [`Device`] which require a connection are called. After a successful return from this method, a connection has
/// been established with the device (if one did not already exist) and the application can then interact with the
/// device. This connection will be maintained until [`disconnect_device`][Self::disconnect_device] is called.
#[inline]
pub async fn connect_device(&self, device: &Device) -> Result<()> {
self.0.connect_device(device).await
}
/// Disconnects from the [`Device`]
///
/// # Platform specifics
///
/// ## MacOS/iOS
///
/// Once this method is called, the application will no longer have access to the [`Device`] and any methods
/// which would require a connection will fail. If no other application has a connection to the same device,
/// the underlying Bluetooth connection will be closed.
///
/// ## Windows
///
/// On Windows, device connections are automatically managed by the OS. This method has no effect. Instead, the
/// connection will be closed only when the [`Device`] and all its child objects are dropped.
///
/// ## Linux
///
/// This method disconnects the device from the system, even if other applications are using the device.
#[inline]
pub async fn disconnect_device(&self, device: &Device) -> Result<()> {
self.0.disconnect_device(device).await
}
/// Monitors a device for connection/disconnection events.
///
/// # Platform specifics
///
/// ## MacOS/iOS
///
/// On MacOS connection events will only be generated for calls to `connect_device` and disconnection events
/// will only be generated for devices that have been connected with `connect_device`.
///
/// On iOS/iPadOS connection and disconnection events can be generated for any device.
#[inline]
pub async fn device_connection_events<'a>(
&'a self,
device: &'a Device,
) -> Result<impl Stream<Item = ConnectionEvent> + Send + Unpin + 'a> {
self.0.device_connection_events(device).await
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/error.rs | src/error.rs | //! Bluest errors
/// The error type for Bluetooth operations
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
message: String,
}
impl Error {
pub(crate) fn new<S: ToString>(
kind: ErrorKind,
source: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
message: S,
) -> Self {
Error {
kind,
source,
message: message.to_string(),
}
}
/// Returns the corresponding [`ErrorKind`] for this error.
pub fn kind(&self) -> ErrorKind {
self.kind
}
/// Returns the message for this error.
pub fn message(&self) -> &str {
&self.message
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match (self.message.is_empty(), &self.source) {
(true, None) => write!(f, "{}", &self.kind),
(false, None) => write!(f, "{}: {}", &self.kind, &self.message),
(true, Some(err)) => write!(f, "{}: {} ({})", &self.kind, &self.message, err),
(false, Some(err)) => write!(f, "{}: {}", &self.kind, err),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_ref().map(|x| {
let x: &(dyn std::error::Error + 'static) = &**x;
x
})
}
}
/// A list of general categories of Bluetooth error.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ErrorKind {
/// the Bluetooth adapter is not available
AdapterUnavailable,
/// the Bluetooth adapter is already scanning
AlreadyScanning,
/// connection failed
ConnectionFailed,
/// the Bluetooth device isn't connected
NotConnected,
/// the Bluetooth operation is unsupported
NotSupported,
/// permission denied
NotAuthorized,
/// not ready
NotReady,
/// not found
NotFound,
/// invalid paramter
InvalidParameter,
/// timed out
Timeout,
/// protocol error: {0}
Protocol(AttError),
/// an internal error has occured
Internal,
/// the service changed and is no longer valid
ServiceChanged,
/// error
Other,
}
impl std::fmt::Display for ErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ErrorKind::AdapterUnavailable => f.write_str("the Bluetooth adapter is not available"),
ErrorKind::AlreadyScanning => f.write_str("the Bluetooth adapter is already scanning"),
ErrorKind::ConnectionFailed => f.write_str("connection failed"),
ErrorKind::NotConnected => f.write_str("the Bluetooth device isn't connected"),
ErrorKind::NotSupported => f.write_str("the Bluetooth operation is unsupported"),
ErrorKind::NotAuthorized => f.write_str("permission denied"),
ErrorKind::NotReady => f.write_str("not ready"),
ErrorKind::NotFound => f.write_str("not found"),
ErrorKind::InvalidParameter => f.write_str("invalid paramter"),
ErrorKind::Timeout => f.write_str("timed out"),
ErrorKind::Protocol(err) => write!(f, "protocol error: {err}"),
ErrorKind::Internal => f.write_str("an internal error has occured"),
ErrorKind::ServiceChanged => f.write_str("the service changed and is no longer valid"),
ErrorKind::Other => f.write_str("error"),
}
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Self {
Error {
kind,
source: None,
message: String::new(),
}
}
}
/// Bluetooth Attribute Protocol error. See the Bluetooth Core Specification, Vol 3, Part F, §3.4.1.1
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AttError(u8);
impl AttError {
/// The operation completed successfully.
pub const SUCCESS: AttError = AttError(0x00);
/// The attribute handle given was not valid on this server.
pub const INVALID_HANDLE: AttError = AttError(0x01);
/// The attribute cannot be read.
pub const READ_NOT_PERMITTED: AttError = AttError(0x02);
/// The attribute cannot be written.
pub const WRITE_NOT_PERMITTED: AttError = AttError(0x03);
/// The attribute PDU was invalid.
pub const INVALID_PDU: AttError = AttError(0x04);
/// The attribute requires authentication before it can be read or written.
pub const INSUFFICIENT_AUTHENTICATION: AttError = AttError(0x05);
/// Attribute server does not support the request received from the client.
pub const REQUEST_NOT_SUPPORTED: AttError = AttError(0x06);
/// Offset specified was past the end of the attribute.
pub const INVALID_OFFSET: AttError = AttError(0x07);
/// The attribute requires authorization before it can be read or written.
pub const INSUFFICIENT_AUTHORIZATION: AttError = AttError(0x08);
/// Too many prepare writes have been queued.
pub const PREPARE_QUEUE_FULL: AttError = AttError(0x09);
/// No attribute found within the given attribute handle range.
pub const ATTRIBUTE_NOT_FOUND: AttError = AttError(0x0a);
/// The attribute cannot be read or written using the Read Blob Request.
pub const ATTRIBUTE_NOT_LONG: AttError = AttError(0x0b);
/// The Encryption Key Size used for encrypting this link is insufficient.
pub const INSUFFICIENT_ENCRYPTION_KEY_SIZE: AttError = AttError(0x0c);
/// The attribute value length is invalid for the operation.
pub const INVALID_ATTRIBUTE_VALUE_LENGTH: AttError = AttError(0x0d);
/// The attribute request that was requested has encountered an error that was unlikely, and therefore could not be completed as requested.
pub const UNLIKELY_ERROR: AttError = AttError(0x0e);
/// The attribute requires encryption before it can be read or written.
pub const INSUFFICIENT_ENCRYPTION: AttError = AttError(0x0f);
/// The attribute type is not a supported grouping attribute as defined by a higher layer specification.
pub const UNSUPPORTED_GROUP_TYPE: AttError = AttError(0x10);
/// Insufficient Resources to complete the request.
pub const INSUFFICIENT_RESOURCES: AttError = AttError(0x11);
/// The server requests the client to rediscover the database.
pub const DATABASE_OUT_OF_SYNC: AttError = AttError(0x12);
/// The attribute parameter value was not allowed.
pub const VALUE_NOT_ALLOWED: AttError = AttError(0x13);
/// Write Request Rejected
pub const WRITE_REQUEST_REJECTED: AttError = AttError(0xfc);
/// Client Characteristic Configuration Descriptor Improperly Configured
pub const CCCD_IMPROPERLY_CONFIGURED: AttError = AttError(0xfd);
/// Procedure Already in Progress
pub const PROCEDURE_ALREADY_IN_PROGRESS: AttError = AttError(0xfe);
/// Out of Range
pub const OUT_OF_RANGE: AttError = AttError(0xff);
/// Converts a [`u8`] value to an [`AttError`].
pub const fn from_u8(val: u8) -> Self {
AttError(val)
}
/// Converts an [`AttError`] to a [`u8`] value.
pub const fn as_u8(self) -> u8 {
self.0
}
/// Checks if the error code is in the application error range.
pub fn is_application(&self) -> bool {
(0x80..0xa0).contains(&self.0)
}
/// Checks if the error code is in the common profile and service range.
pub fn is_common_profile_or_service(&self) -> bool {
self.0 >= 0xe0
}
}
impl std::fmt::Display for AttError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
AttError::SUCCESS => f.write_str("The operation completed successfully."),
AttError::INVALID_HANDLE => f.write_str("The attribute handle given was not valid on this server."),
AttError::READ_NOT_PERMITTED => f.write_str("The attribute cannot be read."),
AttError::WRITE_NOT_PERMITTED => f.write_str("The attribute cannot be written."),
AttError::INVALID_PDU => f.write_str("The attribute PDU was invalid."),
AttError::INSUFFICIENT_AUTHENTICATION => f.write_str("The attribute requires authentication before it can be read or written."),
AttError::REQUEST_NOT_SUPPORTED => f.write_str("Attribute server does not support the request received from the client."),
AttError::INVALID_OFFSET => f.write_str("Offset specified was past the end of the attribute."),
AttError::INSUFFICIENT_AUTHORIZATION => f.write_str("The attribute requires authorization before it can be read or written."),
AttError::PREPARE_QUEUE_FULL => f.write_str("Too many prepare writes have been queued."),
AttError::ATTRIBUTE_NOT_FOUND => f.write_str("No attribute found within the given attribute handle range."),
AttError::ATTRIBUTE_NOT_LONG => f.write_str("The attribute cannot be read or written using the Read Blob Request."),
AttError::INSUFFICIENT_ENCRYPTION_KEY_SIZE => f.write_str("The Encryption Key Size used for encrypting this link is insufficient."),
AttError::INVALID_ATTRIBUTE_VALUE_LENGTH => f.write_str("The attribute value length is invalid for the operation."),
AttError::UNLIKELY_ERROR => f.write_str("The attribute request that was requested has encountered an error that was unlikely, and therefore could not be completed as requested."),
AttError::INSUFFICIENT_ENCRYPTION => f.write_str("The attribute requires encryption before it can be read or written."),
AttError::UNSUPPORTED_GROUP_TYPE => f.write_str("The attribute type is not a supported grouping attribute as defined by a higher layer specification."),
AttError::INSUFFICIENT_RESOURCES => f.write_str("Insufficient Resources to complete the request."),
AttError::DATABASE_OUT_OF_SYNC => f.write_str("The server requests the client to rediscover the database."),
AttError::VALUE_NOT_ALLOWED => f.write_str("The attribute parameter value was not allowed."),
AttError::WRITE_REQUEST_REJECTED => f.write_str("Write Request Rejected"),
AttError::CCCD_IMPROPERLY_CONFIGURED => f.write_str("Client Characteristic Configuration Descriptor Improperly Configured"),
AttError::PROCEDURE_ALREADY_IN_PROGRESS => f.write_str("Procedure Already in Progress"),
AttError::OUT_OF_RANGE => f.write_str("Out of Range"),
_ => f.write_str(&format!("Unknown error 0x{:02x}", self.0)),
}
}
}
impl From<u8> for AttError {
fn from(number: u8) -> Self {
AttError(number)
}
}
impl From<AttError> for u8 {
fn from(val: AttError) -> Self {
val.0
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/service.rs | src/service.rs | use crate::{sys, Characteristic, Result, Uuid};
/// A Bluetooth GATT service
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Service(pub(crate) sys::service::ServiceImpl);
impl Service {
/// The [`Uuid`] identifying the type of this GATT service
///
/// # Panics
///
/// On Linux, this method will panic if there is a current Tokio runtime and it is single-threaded, if there is no
/// current Tokio runtime and creating one fails, or if the underlying [`Service::uuid_async()`] method
/// fails.
#[inline]
pub fn uuid(&self) -> Uuid {
self.0.uuid()
}
/// The [`Uuid`] identifying the type of this GATT service
#[inline]
pub async fn uuid_async(&self) -> Result<Uuid> {
self.0.uuid_async().await
}
/// Whether this is a primary service of the device.
///
/// # Platform specific
///
/// Returns [`NotSupported`][crate::error::ErrorKind::NotSupported] on Windows.
#[inline]
pub async fn is_primary(&self) -> Result<bool> {
self.0.is_primary().await
}
/// Discover all characteristics associated with this service.
#[inline]
pub async fn discover_characteristics(&self) -> Result<Vec<Characteristic>> {
self.0.discover_characteristics().await
}
/// Discover the characteristic(s) with the given [`Uuid`].
#[inline]
pub async fn discover_characteristics_with_uuid(&self, uuid: Uuid) -> Result<Vec<Characteristic>> {
self.0.discover_characteristics_with_uuid(uuid).await
}
/// Get previously discovered characteristics.
///
/// If no characteristics have been discovered yet, this method will perform characteristic discovery.
#[inline]
pub async fn characteristics(&self) -> Result<Vec<Characteristic>> {
self.0.characteristics().await
}
/// Discover the included services of this service.
#[inline]
pub async fn discover_included_services(&self) -> Result<Vec<Service>> {
self.0.discover_included_services().await
}
/// Discover the included service(s) with the given [`Uuid`].
#[inline]
pub async fn discover_included_services_with_uuid(&self, uuid: Uuid) -> Result<Vec<Service>> {
self.0.discover_included_services_with_uuid(uuid).await
}
/// Get previously discovered included services.
///
/// If no included services have been discovered yet, this method will perform included service discovery.
#[inline]
pub async fn included_services(&self) -> Result<Vec<Service>> {
self.0.included_services().await
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/util.rs | src/util.rs | #![allow(unused)] // used depending on the target.
use std::mem::ManuallyDrop;
pub struct ScopeGuard<F: FnOnce()> {
dropfn: ManuallyDrop<F>,
}
impl<F: FnOnce()> ScopeGuard<F> {
pub fn defuse(mut self) {
unsafe { ManuallyDrop::drop(&mut self.dropfn) }
std::mem::forget(self)
}
}
impl<F: FnOnce()> Drop for ScopeGuard<F> {
fn drop(&mut self) {
// SAFETY: This is OK because `dropfn` is `ManuallyDrop` which will not be dropped by the compiler.
let dropfn = unsafe { ManuallyDrop::take(&mut self.dropfn) };
dropfn();
}
}
pub fn defer<F: FnOnce()>(dropfn: F) -> ScopeGuard<F> {
ScopeGuard {
dropfn: ManuallyDrop::new(dropfn),
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/windows.rs | src/windows.rs | pub mod adapter;
pub mod characteristic;
pub mod descriptor;
pub mod device;
pub mod error;
pub mod service;
mod types;
mod winver;
/// A platform-specific device identifier.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DeviceId(std::ffi::OsString);
impl std::fmt::Display for DeviceId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0.to_string_lossy(), f)
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/corebluetooth/descriptor.rs | src/corebluetooth/descriptor.rs | use objc2::msg_send;
use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2_core_bluetooth::{CBDescriptor, CBPeripheralState};
use objc2_foundation::{NSData, NSNumber, NSString, NSUInteger};
use super::delegates::{PeripheralDelegate, PeripheralEvent};
use super::dispatch::Dispatched;
use crate::error::ErrorKind;
use crate::{BluetoothUuidExt, Descriptor, Error, Result, Uuid};
/// A Bluetooth GATT descriptor
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DescriptorImpl {
inner: Dispatched<CBDescriptor>,
delegate: Retained<PeripheralDelegate>,
}
fn value_to_slice(val: &AnyObject) -> Vec<u8> {
if let Some(val) = val.downcast_ref::<NSNumber>() {
// Characteristic EXtended Properties, Client Characteristic COnfiguration, Service Characteristic Configuration, or L2CAP PSM Value Characteristic
let n = val.as_u16();
n.to_le_bytes().to_vec()
} else if let Some(val) = val.downcast_ref::<NSString>() {
// Characteristic User Description
let ptr: *const u8 = unsafe { msg_send![val, UTF8String] };
let val = if ptr.is_null() {
&[]
} else {
let len: NSUInteger = unsafe { msg_send![val, lengthOfBytesUsingEncoding: 4usize] }; // NSUTF8StringEncoding
unsafe { std::slice::from_raw_parts(ptr, len) }
};
val.to_vec()
} else if let Some(val) = val.downcast_ref::<NSData>() {
// All other descriptors
val.to_vec()
} else {
Vec::new()
}
}
impl Descriptor {
pub(super) fn new(descriptor: Retained<CBDescriptor>, delegate: Retained<PeripheralDelegate>) -> Self {
Descriptor(DescriptorImpl {
inner: unsafe { Dispatched::new(descriptor) },
delegate,
})
}
}
impl DescriptorImpl {
/// The [`Uuid`] identifying the type of this GATT descriptor
pub fn uuid(&self) -> Uuid {
self.inner
.dispatch(|descriptor| unsafe { Uuid::from_bluetooth_bytes(descriptor.UUID().data().as_bytes_unchecked()) })
}
/// The [`Uuid`] identifying the type of this GATT descriptor
pub async fn uuid_async(&self) -> Result<Uuid> {
Ok(self.uuid())
}
/// The cached value of this descriptor
///
/// If the value has not yet been read, this method may either return an error or perform a read of the value.
pub async fn value(&self) -> Result<Vec<u8>> {
self.inner.dispatch(|descriptor| unsafe {
descriptor
.value()
.map(|val| value_to_slice(&val))
.ok_or_else(|| Error::new(ErrorKind::NotReady, None, "the descriptor value has not been read"))
})
}
/// Read the value of this descriptor from the device
pub async fn read(&self) -> Result<Vec<u8>> {
let mut receiver = self.delegate.sender().new_receiver();
let service = self.inner.dispatch(|descriptor| {
let service = unsafe { descriptor.characteristic().and_then(|x| x.service()) }.ok_or(Error::new(
ErrorKind::NotFound,
None,
"service not found",
))?;
let peripheral =
unsafe { service.peripheral() }.ok_or(Error::new(ErrorKind::NotFound, None, "peripheral not found"))?;
if unsafe { peripheral.state() } != CBPeripheralState::Connected {
return Err(Error::from(ErrorKind::NotConnected));
}
unsafe { peripheral.readValueForDescriptor(descriptor) };
Ok(unsafe { Dispatched::new(service) })
})?;
loop {
match receiver.recv().await.map_err(Error::from_recv_error)? {
PeripheralEvent::DescriptorValueUpdate { descriptor, error } if descriptor == self.inner => match error
{
Some(err) => return Err(Error::from_nserror(err)),
None => return self.value().await,
},
PeripheralEvent::Disconnected { error } => {
return Err(Error::from_kind_and_nserror(ErrorKind::NotConnected, error));
}
PeripheralEvent::ServicesChanged { invalidated_services }
if invalidated_services.contains(&service) =>
{
return Err(ErrorKind::ServiceChanged.into());
}
_ => (),
}
}
}
/// Write the value of this descriptor on the device to `value`
pub async fn write(&self, value: &[u8]) -> Result<()> {
let mut receiver = self.delegate.sender().new_receiver();
let service = self.inner.dispatch(|descriptor| {
let service = unsafe { descriptor.characteristic().and_then(|x| x.service()) }.ok_or(Error::new(
ErrorKind::NotFound,
None,
"service not found",
))?;
let peripheral =
unsafe { service.peripheral() }.ok_or(Error::new(ErrorKind::NotFound, None, "peripheral not found"))?;
if unsafe { peripheral.state() } != CBPeripheralState::Connected {
return Err(Error::from(ErrorKind::NotConnected));
}
let data = NSData::with_bytes(value);
unsafe { peripheral.writeValue_forDescriptor(&data, descriptor) };
Ok(unsafe { Dispatched::new(service) })
})?;
loop {
match receiver.recv().await.map_err(Error::from_recv_error)? {
PeripheralEvent::DescriptorValueWrite { descriptor, error } if descriptor == self.inner => {
match error {
Some(err) => return Err(Error::from_nserror(err)),
None => return Ok(()),
}
}
PeripheralEvent::Disconnected { error } => {
return Err(Error::from_kind_and_nserror(ErrorKind::NotConnected, error));
}
PeripheralEvent::ServicesChanged { invalidated_services }
if invalidated_services.contains(&service) =>
{
return Err(ErrorKind::ServiceChanged.into());
}
_ => (),
}
}
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/corebluetooth/device.rs | src/corebluetooth/device.rs | #![allow(clippy::let_unit_value)]
use futures_core::Stream;
use futures_lite::StreamExt;
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2_core_bluetooth::{CBPeripheral, CBPeripheralState, CBService, CBUUID};
use objc2_foundation::{NSArray, NSData};
use super::delegates::{PeripheralDelegate, PeripheralEvent};
use super::dispatch::Dispatched;
#[cfg(feature = "l2cap")]
use super::l2cap_channel::{L2capChannelReader, L2capChannelWriter};
use crate::device::ServicesChanged;
use crate::error::ErrorKind;
use crate::pairing::PairingAgent;
use crate::{BluetoothUuidExt, Device, DeviceId, Error, Result, Service, Uuid};
/// A Bluetooth LE device
#[derive(Clone)]
pub struct DeviceImpl {
pub(super) peripheral: Dispatched<CBPeripheral>,
delegate: Retained<PeripheralDelegate>,
}
impl PartialEq for DeviceImpl {
fn eq(&self, other: &Self) -> bool {
self.peripheral == other.peripheral
}
}
impl Eq for DeviceImpl {}
impl std::hash::Hash for DeviceImpl {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.peripheral.hash(state)
}
}
impl std::fmt::Debug for DeviceImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Device").field(&self.peripheral).finish()
}
}
impl std::fmt::Display for DeviceImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name().as_deref().unwrap_or("(Unknown)"))
}
}
impl Device {
pub(super) fn new(peripheral: Retained<CBPeripheral>) -> Self {
let delegate = unsafe { peripheral.delegate() }.unwrap_or_else(|| {
// Create a new delegate and attach it to the peripheral
let delegate = ProtocolObject::from_retained(PeripheralDelegate::new());
unsafe { peripheral.setDelegate(Some(&delegate)) }
delegate
});
let delegate = delegate.downcast().unwrap();
Device(DeviceImpl {
peripheral: unsafe { Dispatched::new(peripheral) },
delegate,
})
}
}
impl DeviceImpl {
/// This device's unique identifier
pub fn id(&self) -> DeviceId {
let uuid = self
.peripheral
.dispatch(|peripheral| unsafe { Uuid::from_bluetooth_bytes(&peripheral.identifier().as_bytes()[..]) });
super::DeviceId(uuid)
}
/// The local name for this device, if available
///
/// This can either be a name advertised or read from the device, or a name assigned to the device by the OS.
pub fn name(&self) -> Result<String> {
self.peripheral
.dispatch(|peripheral| match unsafe { peripheral.name() } {
Some(name) => Ok(name.to_string()),
None => Err(ErrorKind::NotFound.into()),
})
}
/// The local name for this device, if available
///
/// This can either be a name advertised or read from the device, or a name assigned to the device by the OS.
pub async fn name_async(&self) -> Result<String> {
self.name()
}
/// The connection status for this device
pub async fn is_connected(&self) -> bool {
self.peripheral.dispatch(|peripheral| unsafe { peripheral.state() }) == CBPeripheralState::Connected
}
/// The pairing status for this device
pub async fn is_paired(&self) -> Result<bool> {
Err(ErrorKind::NotSupported.into())
}
/// Attempt to pair this device using the system default pairing UI
///
/// Device pairing is performed automatically by the OS when a characteristic requiring security is accessed. This
/// method is a no-op.
pub async fn pair(&self) -> Result<()> {
Ok(())
}
/// Attempt to pair this device using the system default pairing UI
///
/// Device pairing is performed automatically by the OS when a characteristic requiring security is accessed. This
/// method is a no-op.
pub async fn pair_with_agent<T: PairingAgent>(&self, _agent: &T) -> Result<()> {
Ok(())
}
/// Disconnect and unpair this device from the system
///
/// # Platform specific
///
/// Not supported on MacOS/iOS.
pub async fn unpair(&self) -> Result<()> {
Err(ErrorKind::NotSupported.into())
}
/// Discover the primary services of this device.
pub async fn discover_services(&self) -> Result<Vec<Service>> {
self.discover_services_inner(None).await
}
/// Discover the primary service(s) of this device with the given [`Uuid`].
pub async fn discover_services_with_uuid(&self, uuid: Uuid) -> Result<Vec<Service>> {
let services = self.discover_services_inner(Some(uuid)).await?;
Ok(services.into_iter().filter(|x| x.uuid() == uuid).collect())
}
async fn discover_services_inner(&self, uuid: Option<Uuid>) -> Result<Vec<Service>> {
let mut receiver = self.delegate.sender().new_receiver();
if !self.is_connected().await {
return Err(ErrorKind::NotConnected.into());
}
self.peripheral.dispatch(|peripheral| {
let uuids = uuid.map(|uuid| unsafe {
NSArray::from_retained_slice(&[CBUUID::UUIDWithData(&NSData::with_bytes(uuid.as_bluetooth_bytes()))])
});
unsafe { peripheral.discoverServices(uuids.as_deref()) };
});
loop {
match receiver.recv().await.map_err(Error::from_recv_error)? {
PeripheralEvent::DiscoveredServices { error: None } => break,
PeripheralEvent::DiscoveredServices { error: Some(err) } => {
return Err(Error::from_nserror(err));
}
PeripheralEvent::Disconnected { error } => {
return Err(Error::from_kind_and_nserror(ErrorKind::NotConnected, error));
}
_ => (),
}
}
self.services_inner()
}
/// Get previously discovered services.
///
/// If no services have been discovered yet, this method will perform service discovery.
pub async fn services(&self) -> Result<Vec<Service>> {
match self.services_inner() {
Ok(services) => Ok(services),
Err(_) => self.discover_services().await,
}
}
fn services_inner(&self) -> Result<Vec<Service>> {
self.peripheral.dispatch(|peripheral| {
unsafe { peripheral.services() }
.map(|s| s.iter().map(|x| Service::new(x, self.delegate.clone())).collect())
.ok_or_else(|| Error::new(ErrorKind::NotReady, None, "no services have been discovered"))
})
}
/// Monitors the device for services changed events.
pub async fn service_changed_indications(
&self,
) -> Result<impl Stream<Item = Result<ServicesChanged>> + Send + Unpin + '_> {
let receiver = self.delegate.sender().new_receiver();
if !self.is_connected().await {
return Err(ErrorKind::NotConnected.into());
}
Ok(receiver.filter_map(|ev| match ev {
PeripheralEvent::ServicesChanged { invalidated_services } => {
Some(Ok(ServicesChanged(ServicesChangedImpl(invalidated_services))))
}
PeripheralEvent::Disconnected { error } => {
Some(Err(Error::from_kind_and_nserror(ErrorKind::NotConnected, error)))
}
_ => None,
}))
}
/// Get the current signal strength from the device in dBm.
pub async fn rssi(&self) -> Result<i16> {
let mut receiver = self.delegate.sender().new_receiver();
self.peripheral.dispatch(|peripheral| unsafe { peripheral.readRSSI() });
loop {
match receiver.recv().await {
Ok(PeripheralEvent::ReadRssi { rssi, error: None }) => return Ok(rssi),
Ok(PeripheralEvent::ReadRssi { error: Some(err), .. }) => return Err(Error::from_nserror(err)),
Err(err) => return Err(Error::from_recv_error(err)),
_ => (),
}
}
}
/// Open L2CAP channel given PSM
#[cfg(feature = "l2cap")]
pub async fn open_l2cap_channel(&self, psm: u16, _secure: bool) -> Result<super::l2cap_channel::L2capChannel> {
use tracing::{debug, info};
let mut receiver = self.delegate.sender().new_receiver();
if !self.is_connected().await {
return Err(ErrorKind::NotConnected.into());
}
info!("starting open_l2cap_channel on {}", psm);
self.peripheral
.dispatch(|peripheral| unsafe { peripheral.openL2CAPChannel(psm) });
let l2capchannel;
loop {
match receiver.recv().await.map_err(Error::from_recv_error)? {
PeripheralEvent::L2CAPChannelOpened { channel, error: None } => {
l2capchannel = channel;
break;
}
PeripheralEvent::L2CAPChannelOpened { channel: _, error } => {
return Err(Error::from_nserror(error.unwrap()));
}
PeripheralEvent::Disconnected { error } => {
return Err(Error::from_kind_and_nserror(ErrorKind::NotConnected, error));
}
o => {
info!("Other event: {:?}", o);
}
}
}
debug!("open_l2cap_channel success {:?}", self.peripheral);
let reader = L2capChannelReader::new(l2capchannel.clone());
let writer = L2capChannelWriter::new(l2capchannel);
Ok(super::l2cap_channel::L2capChannel { reader, writer })
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServicesChangedImpl(Vec<Dispatched<CBService>>);
impl ServicesChangedImpl {
pub fn was_invalidated(&self, service: &Service) -> bool {
self.0.contains(&service.0.inner)
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/corebluetooth/characteristic.rs | src/corebluetooth/characteristic.rs | use futures_core::Stream;
use futures_lite::StreamExt;
use objc2::rc::Retained;
use objc2_core_bluetooth::{
CBCharacteristic, CBCharacteristicProperties, CBCharacteristicWriteType, CBPeripheralState,
};
use objc2_foundation::NSData;
use super::delegates::{PeripheralDelegate, PeripheralEvent};
use super::dispatch::Dispatched;
use crate::error::ErrorKind;
use crate::util::defer;
use crate::{BluetoothUuidExt, Characteristic, CharacteristicProperties, Descriptor, Error, Result, Uuid};
/// A Bluetooth GATT characteristic
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CharacteristicImpl {
inner: Dispatched<CBCharacteristic>,
delegate: Retained<PeripheralDelegate>,
}
impl Characteristic {
pub(super) fn new(characteristic: Retained<CBCharacteristic>, delegate: Retained<PeripheralDelegate>) -> Self {
Characteristic(CharacteristicImpl {
inner: unsafe { Dispatched::new(characteristic) },
delegate,
})
}
}
impl CharacteristicImpl {
/// The [`Uuid`] identifying the type of this GATT characteristic
pub fn uuid(&self) -> Uuid {
self.inner.dispatch(|characteristic| unsafe {
Uuid::from_bluetooth_bytes(characteristic.UUID().data().as_bytes_unchecked())
})
}
/// The [`Uuid`] identifying the type of this GATT characteristic
pub async fn uuid_async(&self) -> Result<Uuid> {
Ok(self.uuid())
}
/// The properties of this this GATT characteristic.
///
/// Characteristic properties indicate which operations (e.g. read, write, notify, etc) may be performed on this
/// characteristic.
pub async fn properties(&self) -> Result<CharacteristicProperties> {
let cb_props = self
.inner
.dispatch(|characteristic| unsafe { characteristic.properties() });
let mut props = CharacteristicProperties::default();
if cb_props.contains(CBCharacteristicProperties::Broadcast) {
props.broadcast = true;
}
if cb_props.contains(CBCharacteristicProperties::Read) {
props.read = true;
}
if cb_props.contains(CBCharacteristicProperties::WriteWithoutResponse) {
props.write_without_response = true;
}
if cb_props.contains(CBCharacteristicProperties::Write) {
props.write = true;
}
if cb_props.contains(CBCharacteristicProperties::Notify) {
props.notify = true;
}
if cb_props.contains(CBCharacteristicProperties::Indicate) {
props.indicate = true;
}
if cb_props.contains(CBCharacteristicProperties::AuthenticatedSignedWrites) {
props.authenticated_signed_writes = true;
}
if cb_props.contains(CBCharacteristicProperties::ExtendedProperties) {
props.extended_properties = true;
}
Ok(props)
}
/// The cached value of this characteristic
///
/// If the value has not yet been read, this method may either return an error or perform a read of the value.
pub async fn value(&self) -> Result<Vec<u8>> {
self.inner.dispatch(|characteristic| unsafe {
characteristic
.value()
.map(|val| val.as_bytes_unchecked().to_vec())
.ok_or_else(|| Error::new(ErrorKind::NotReady, None, "the characteristic value has not been read"))
})
}
/// Read the value of this characteristic from the device
pub async fn read(&self) -> Result<Vec<u8>> {
let mut receiver = self.delegate.sender().new_receiver();
let service = self.inner.dispatch(|characteristic| {
let service = unsafe { characteristic.service() }.ok_or(Error::new(
ErrorKind::NotFound,
None,
"service not found",
))?;
let peripheral =
unsafe { service.peripheral() }.ok_or(Error::new(ErrorKind::NotFound, None, "peripheral not found"))?;
if unsafe { peripheral.state() } != CBPeripheralState::Connected {
return Err(Error::from(ErrorKind::NotConnected));
}
unsafe { peripheral.readValueForCharacteristic(characteristic) };
Ok(unsafe { Dispatched::new(service) })
})?;
loop {
match receiver.recv().await.map_err(Error::from_recv_error)? {
PeripheralEvent::CharacteristicValueUpdate {
characteristic,
data,
error,
} if characteristic == self.inner => match error {
Some(err) => return Err(Error::from_nserror(err)),
None => return Ok(data),
},
PeripheralEvent::Disconnected { error } => {
return Err(Error::from_kind_and_nserror(ErrorKind::NotConnected, error));
}
PeripheralEvent::ServicesChanged { invalidated_services }
if invalidated_services.contains(&service) =>
{
return Err(ErrorKind::ServiceChanged.into());
}
_ => (),
}
}
}
/// Write the value of this descriptor on the device to `value` and request the device return a response indicating
/// a successful write.
pub async fn write(&self, value: &[u8]) -> Result<()> {
let mut receiver = self.delegate.sender().new_receiver();
let service = self.inner.dispatch(|characteristic| {
let service = unsafe { characteristic.service() }.ok_or(Error::new(
ErrorKind::NotFound,
None,
"service not found",
))?;
let peripheral =
unsafe { service.peripheral() }.ok_or(Error::new(ErrorKind::NotFound, None, "peripheral not found"))?;
if unsafe { peripheral.state() } != CBPeripheralState::Connected {
return Err(Error::from(ErrorKind::NotConnected));
}
let data = NSData::with_bytes(value);
unsafe {
peripheral.writeValue_forCharacteristic_type(
&data,
characteristic,
CBCharacteristicWriteType::WithResponse,
)
};
Ok(unsafe { Dispatched::new(service) })
})?;
loop {
match receiver.recv().await.map_err(Error::from_recv_error)? {
PeripheralEvent::CharacteristicValueWrite { characteristic, error } if characteristic == self.inner => {
match error {
Some(err) => return Err(Error::from_nserror(err)),
None => return Ok(()),
}
}
PeripheralEvent::Disconnected { error } => {
return Err(Error::from_kind_and_nserror(ErrorKind::NotConnected, error));
}
PeripheralEvent::ServicesChanged { invalidated_services }
if invalidated_services.contains(&service) =>
{
return Err(ErrorKind::ServiceChanged.into());
}
_ => (),
}
}
}
/// Write the value of this descriptor on the device to `value` without requesting a response.
pub async fn write_without_response(&self, value: &[u8]) -> Result<()> {
let mut receiver = self.delegate.sender().new_receiver();
loop {
let service = self.inner.dispatch(|characteristic| {
let service = unsafe { characteristic.service() }.ok_or(Error::new(
ErrorKind::NotFound,
None,
"service not found",
))?;
let peripheral = unsafe { service.peripheral() }.ok_or(Error::new(
ErrorKind::NotFound,
None,
"peripheral not found",
))?;
if unsafe { peripheral.state() } != CBPeripheralState::Connected {
Err(Error::from(ErrorKind::NotConnected))
} else if unsafe { peripheral.canSendWriteWithoutResponse() } {
let data = NSData::with_bytes(value);
unsafe {
peripheral.writeValue_forCharacteristic_type(
&data,
characteristic,
CBCharacteristicWriteType::WithoutResponse,
)
};
Ok(None)
} else {
Ok(Some(unsafe { Dispatched::new(service) }))
}
})?;
if let Some(service) = service {
while let Ok(evt) = receiver.recv().await {
match evt {
PeripheralEvent::ReadyToWrite => break,
PeripheralEvent::Disconnected { error } => {
return Err(Error::from_kind_and_nserror(ErrorKind::NotConnected, error));
}
PeripheralEvent::ServicesChanged { invalidated_services }
if invalidated_services.contains(&service) =>
{
return Err(ErrorKind::ServiceChanged.into());
}
_ => (),
}
}
} else {
return Ok(());
}
}
}
/// Get the maximum amount of data that can be written in a single packet for this characteristic.
pub fn max_write_len(&self) -> Result<usize> {
self.inner.dispatch(|characteristic| {
let peripheral = unsafe { characteristic.service().and_then(|x| x.peripheral()) }.ok_or(Error::new(
ErrorKind::NotFound,
None,
"peripheral not found",
))?;
unsafe { Ok(peripheral.maximumWriteValueLengthForType(CBCharacteristicWriteType::WithoutResponse)) }
})
}
/// Get the maximum amount of data that can be written in a single packet for this characteristic.
pub async fn max_write_len_async(&self) -> Result<usize> {
self.max_write_len()
}
/// Enables notification of value changes for this GATT characteristic.
///
/// Returns a stream of values for the characteristic sent from the device.
pub async fn notify(&self) -> Result<impl Stream<Item = Result<Vec<u8>>> + Send + Unpin + '_> {
let properties = self.properties().await?;
if !(properties.notify || properties.indicate) {
return Err(Error::new(
ErrorKind::NotSupported,
None,
"characteristic does not support indications or notifications",
));
};
let mut receiver = self.delegate.sender().new_receiver();
let service = self.inner.dispatch(|characteristic| {
let service = unsafe { characteristic.service() }.ok_or(Error::new(
ErrorKind::NotFound,
None,
"service not found",
))?;
let peripheral =
unsafe { service.peripheral() }.ok_or(Error::new(ErrorKind::NotFound, None, "peripheral not found"))?;
if unsafe { peripheral.state() } != CBPeripheralState::Connected {
return Err(Error::from(ErrorKind::NotConnected));
}
unsafe { peripheral.setNotifyValue_forCharacteristic(true, characteristic) };
Ok(unsafe { Dispatched::new(service) })
})?;
let guard = defer(move || {
self.inner.dispatch(|characteristic| {
if let Some(peripheral) = unsafe { characteristic.service().and_then(|x| x.peripheral()) } {
unsafe {
if peripheral.state() == CBPeripheralState::Connected {
peripheral.setNotifyValue_forCharacteristic(false, characteristic)
}
};
}
});
});
loop {
match receiver.recv().await.map_err(Error::from_recv_error)? {
PeripheralEvent::NotificationStateUpdate { characteristic, error } if characteristic == self.inner => {
match error {
Some(err) => return Err(Error::from_nserror(err)),
None => break,
}
}
PeripheralEvent::Disconnected { error } => {
return Err(Error::from_kind_and_nserror(ErrorKind::NotConnected, error));
}
PeripheralEvent::ServicesChanged { invalidated_services }
if invalidated_services.contains(&service) =>
{
return Err(ErrorKind::ServiceChanged.into());
}
_ => (),
}
}
let updates = receiver
.filter_map(move |x| {
let _guard = &guard;
match x {
PeripheralEvent::CharacteristicValueUpdate {
characteristic,
data,
error,
} if characteristic == self.inner => match error {
Some(err) => Some(Err(Error::from_nserror(err))),
None => Some(Ok(data)),
},
PeripheralEvent::Disconnected { error } => {
Some(Err(Error::from_kind_and_nserror(ErrorKind::NotConnected, error)))
}
PeripheralEvent::ServicesChanged { invalidated_services }
if invalidated_services.contains(&service) =>
{
Some(Err(ErrorKind::ServiceChanged.into()))
}
_ => None,
}
})
.then(move |x| {
Box::pin(async move {
match x {
Ok(data) => Ok(data),
Err(err) => Err(err),
}
})
});
Ok(updates)
}
/// Is the device currently sending notifications for this characteristic?
pub async fn is_notifying(&self) -> Result<bool> {
Ok(self
.inner
.dispatch(|characteristic| unsafe { characteristic.isNotifying() }))
}
/// Discover the descriptors associated with this characteristic.
pub async fn discover_descriptors(&self) -> Result<Vec<Descriptor>> {
let mut receiver = self.delegate.sender().new_receiver();
let service = self.inner.dispatch(|characteristic| {
let service = unsafe { characteristic.service() }.ok_or(Error::new(
ErrorKind::NotFound,
None,
"service not found",
))?;
let peripheral =
unsafe { service.peripheral() }.ok_or(Error::new(ErrorKind::NotFound, None, "peripheral not found"))?;
if unsafe { peripheral.state() } != CBPeripheralState::Connected {
return Err(Error::from(ErrorKind::NotConnected));
}
unsafe { peripheral.discoverDescriptorsForCharacteristic(characteristic) }
Ok(unsafe { Dispatched::new(service) })
})?;
loop {
match receiver.recv().await.map_err(Error::from_recv_error)? {
PeripheralEvent::DiscoveredDescriptors { characteristic, error } if characteristic == self.inner => {
match error {
Some(err) => return Err(Error::from_nserror(err)),
None => break,
}
}
PeripheralEvent::Disconnected { error } => {
return Err(Error::from_kind_and_nserror(ErrorKind::NotConnected, error));
}
PeripheralEvent::ServicesChanged { invalidated_services }
if invalidated_services.contains(&service) =>
{
return Err(ErrorKind::ServiceChanged.into());
}
_ => (),
}
}
self.descriptors_inner()
}
/// Get previously discovered descriptors.
///
/// If no descriptors have been discovered yet, this method will perform descriptor discovery.
pub async fn descriptors(&self) -> Result<Vec<Descriptor>> {
match self.descriptors_inner() {
Ok(descriptors) => Ok(descriptors),
Err(_) => self.discover_descriptors().await,
}
}
fn descriptors_inner(&self) -> Result<Vec<Descriptor>> {
self.inner.dispatch(|characteristic| {
unsafe { characteristic.descriptors() }
.map(|s| s.iter().map(|x| Descriptor::new(x, self.delegate.clone())).collect())
.ok_or_else(|| Error::new(ErrorKind::NotReady, None, "no descriptors have been discovered"))
})
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/corebluetooth/dispatch.rs | src/corebluetooth/dispatch.rs | use std::cell::UnsafeCell;
use std::hash::{Hash, Hasher};
use std::mem::MaybeUninit;
use std::sync::OnceLock;
use dispatch2::{DispatchQoS, DispatchQueue, DispatchQueueAttr, DispatchRetained};
use objc2::rc::Retained;
use objc2::Message;
/// Get a serial dispatch queue to use for all CoreBluetooth operations
pub(crate) fn queue() -> &'static DispatchQueue {
static CELL: OnceLock<DispatchRetained<DispatchQueue>> = OnceLock::new();
CELL.get_or_init(|| {
let utility =
DispatchQueue::global_queue(dispatch2::GlobalQueueIdentifier::QualityOfService(DispatchQoS::Utility));
DispatchQueue::new_with_target("Bluest", DispatchQueueAttr::SERIAL, Some(&utility))
})
}
/// Synchronizes access to an Objective-C object by restricting all access to occur
/// within the context of a single global serial dispatch queue.
///
/// This allows !Send / !Sync Objective-C types to be used from multiple Rust threads.
#[derive(Debug)]
pub(crate) struct Dispatched<T>(UnsafeCell<Retained<T>>);
unsafe impl<T> Send for Dispatched<T> {}
unsafe impl<T> Sync for Dispatched<T> {}
impl<T: Message> Clone for Dispatched<T> {
fn clone(&self) -> Self {
unsafe { Dispatched::retain(&**self.0.get()) }
}
}
impl<T: PartialEq<T>> PartialEq<Dispatched<T>> for Dispatched<T> {
fn eq(&self, other: &Dispatched<T>) -> bool {
self.dispatch(|val| (*val).eq(unsafe { other.get() }))
}
}
impl<T: Hash> Hash for Dispatched<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
// Hasher may not be Send, so we hash our internal value using `DefaultHasher`
// then add that hash value to `state`
self.dispatch(|val| {
let mut state = std::hash::DefaultHasher::new();
val.hash(&mut state);
state.finish()
})
.hash(state)
}
}
impl<T: Eq> Eq for Dispatched<T> {}
impl<T> Dispatched<T> {
/// # Safety
///
/// - It must be safe to access `value` from the context of [`queue()`].
/// - After calling `new`, `value` must only be accessed from within the context of `queue()`.
pub unsafe fn new(value: Retained<T>) -> Self {
Self(UnsafeCell::new(value))
}
/// # Safety
///
/// - It must be safe to access `value` from the context of [`queue()`].
/// - After calling `retain`, `value` must only be accessed from within the context of `queue()`.
pub unsafe fn retain(value: &T) -> Self
where
T: Message,
{
Self(UnsafeCell::new(value.retain()))
}
pub fn dispatch<F, R>(&self, f: F) -> R
where
F: FnOnce(&T) -> R + Send,
R: Send,
{
let mut ret = MaybeUninit::uninit();
queue().exec_sync(|| {
ret.write((f)(unsafe { self.get() }));
});
unsafe { ret.assume_init() }
}
/// # Safety
///
/// This method must only be called from within the context of `queue()`.
pub unsafe fn get(&self) -> &T {
&*self.0.get()
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/corebluetooth/l2cap_channel.rs | src/corebluetooth/l2cap_channel.rs | use core::ptr::NonNull;
use std::io::{Read, Write};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use std::{fmt, pin};
use futures_lite::io::{AsyncRead, AsyncWrite, BlockOn};
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2::{define_class, msg_send, sel, AnyThread, DefinedClass};
use objc2_core_bluetooth::CBL2CAPChannel;
use objc2_foundation::{
NSDefaultRunLoopMode, NSInputStream, NSNotification, NSNotificationCenter, NSObject, NSObjectProtocol,
NSOutputStream, NSRunLoop, NSStream, NSStreamDelegate, NSStreamEvent, NSString,
};
use tracing::{debug, trace, warn};
use super::dispatch::Dispatched;
use crate::l2cap_channel::{derive_async_read, derive_async_write, PIPE_CAPACITY};
/// Utility struct to close the channel on drop.
pub(super) struct L2capCloser {
channel: Dispatched<CBL2CAPChannel>,
}
impl L2capCloser {
fn close(&self) {
self.channel.dispatch(|channel| unsafe {
if let Some(c) = channel.inputStream() {
c.close()
}
if let Some(c) = channel.outputStream() {
c.close()
}
})
}
}
impl Drop for L2capCloser {
fn drop(&mut self) {
self.close()
}
}
pub struct L2capChannel {
pub(super) reader: L2capChannelReader,
pub(super) writer: L2capChannelWriter,
}
impl L2capChannel {
pub fn split(self) -> (L2capChannelReader, L2capChannelWriter) {
(self.reader, self.writer)
}
}
derive_async_read!(L2capChannel, reader);
derive_async_write!(L2capChannel, writer);
/// The reader side of an L2CAP channel.
pub struct L2capChannelReader {
stream: piper::Reader,
_closer: Arc<L2capCloser>,
_delegate: Retained<InputStreamDelegate>,
}
impl L2capChannelReader {
/// Creates a new L2capChannelReader.
pub(crate) fn new(channel: Dispatched<CBL2CAPChannel>) -> Self {
let (read_rx, read_tx) = piper::pipe(PIPE_CAPACITY);
let closer = Arc::new(L2capCloser {
channel: channel.clone(),
});
let delegate = channel.dispatch(|channel| unsafe {
let input_stream = channel.inputStream().unwrap();
let delegate = InputStreamDelegate::new(read_tx);
input_stream.setDelegate(Some(&ProtocolObject::from_retained(delegate.clone())));
input_stream.scheduleInRunLoop_forMode(&NSRunLoop::mainRunLoop(), NSDefaultRunLoopMode);
input_stream.open();
delegate
});
Self {
stream: read_rx,
_delegate: delegate,
_closer: closer,
}
}
}
derive_async_read!(L2capChannelReader, stream);
impl fmt::Debug for L2capChannelReader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("L2capChannelReader")
}
}
/// The writer side of an L2CAP channel.
pub struct L2capChannelWriter {
stream: piper::Writer,
closer: Arc<L2capCloser>,
_delegate: Retained<OutputStreamDelegate>,
}
impl L2capChannelWriter {
/// Creates a new L2capChannelWriter.
pub(crate) fn new(channel: Dispatched<CBL2CAPChannel>) -> Self {
let (write_rx, write_tx) = piper::pipe(PIPE_CAPACITY);
let closer = Arc::new(L2capCloser {
channel: channel.clone(),
});
let delegate = channel.dispatch(|channel| unsafe {
let output_stream = channel.outputStream().unwrap();
let delegate = OutputStreamDelegate::new(write_rx, Dispatched::retain(&output_stream));
output_stream.setDelegate(Some(&ProtocolObject::from_retained(delegate.clone())));
output_stream.scheduleInRunLoop_forMode(&NSRunLoop::mainRunLoop(), NSDefaultRunLoopMode);
output_stream.open();
let center = NSNotificationCenter::defaultCenter();
let name = NSString::from_str("ChannelWriteNotification");
center.addObserver_selector_name_object(&delegate, sel!(onNotified:), Some(&name), None);
delegate
});
Self {
stream: write_tx,
_delegate: delegate,
closer,
}
}
fn notify(&self) {
unsafe {
let name = NSString::from_str("ChannelWriteNotification");
let center = NSNotificationCenter::defaultCenter();
center.postNotificationName_object(&name, None);
}
}
}
impl AsyncWrite for L2capChannelWriter {
fn poll_write(mut self: pin::Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
let stream = pin::pin!(&mut self.stream);
let ret = stream.poll_write(cx, buf);
if matches!(ret, Poll::Ready(Ok(_))) {
self.notify();
}
ret
}
fn poll_flush(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<std::io::Result<()>> {
let stream = pin::pin!(&mut self.stream);
stream.poll_flush(cx)
}
fn poll_close(mut self: pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
self.closer.close();
let stream = pin::pin!(&mut self.stream);
stream.poll_close(cx)
}
}
impl fmt::Debug for L2capChannelWriter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("L2capChannelWriter")
}
}
struct InputStreamDelegateIvars {
writer: Mutex<BlockOn<piper::Writer>>,
}
define_class!(
#[unsafe(super(NSObject))]
#[ivars = InputStreamDelegateIvars]
#[derive(PartialEq, Eq, Hash)]
struct InputStreamDelegate;
unsafe impl NSObjectProtocol for InputStreamDelegate {}
unsafe impl NSStreamDelegate for InputStreamDelegate {
#[unsafe(method(stream:handleEvent:))]
fn handle_event(&self, stream: &NSStream, event_code: NSStreamEvent) {
let input_stream = stream.downcast_ref::<NSInputStream>().unwrap();
if let NSStreamEvent::HasBytesAvailable = event_code {
// This is the only writer task, so there should never be contention on this lock
let mut writer = self.ivars().writer.try_lock().unwrap();
// This is the the only task that writes to the pipe so at least this many bytes will be available
let to_fill = writer.get_ref().capacity() - writer.get_ref().len();
let mut buf = vec![0u8; to_fill].into_boxed_slice();
let res = unsafe { input_stream.read_maxLength(NonNull::new_unchecked(buf.as_mut_ptr()), buf.len()) };
if res < 0 {
debug!("Read Loop Error: Stream read failed");
return;
}
let filled = res.try_into().unwrap();
if let Err(e) = writer.write_all(&buf[..filled]) {
debug!("Read Loop Error: {:?}", e);
unsafe {
input_stream.setDelegate(None);
input_stream.close();
}
}
}
}
}
);
impl InputStreamDelegate {
pub fn new(writer: piper::Writer) -> Retained<Self> {
let ivars = InputStreamDelegateIvars {
writer: Mutex::new(BlockOn::new(writer)),
};
let this = InputStreamDelegate::alloc().set_ivars(ivars);
unsafe { msg_send![super(this), init] }
}
}
struct OutputStreamDelegateIvars {
receiver: Mutex<BlockOn<piper::Reader>>,
stream: Dispatched<NSOutputStream>,
}
define_class!(
#[unsafe(super(NSObject))]
#[ivars = OutputStreamDelegateIvars]
#[derive(PartialEq, Eq, Hash)]
struct OutputStreamDelegate;
unsafe impl NSObjectProtocol for OutputStreamDelegate {}
unsafe impl NSStreamDelegate for OutputStreamDelegate {
#[unsafe(method(stream:handleEvent:))]
fn handle_event(&self, stream: &NSStream, event_code: NSStreamEvent) {
let output_stream = stream.downcast_ref::<NSOutputStream>().unwrap();
if let NSStreamEvent::HasSpaceAvailable = event_code {
self.send_packet(output_stream)
}
}
#[unsafe(method(onNotified:))]
fn on_notified(&self, _n: &NSNotification) {
let stream = unsafe { self.ivars().stream.get() };
self.send_packet(stream)
}
}
);
impl OutputStreamDelegate {
pub fn new(receiver: piper::Reader, stream: Dispatched<NSOutputStream>) -> Retained<Self> {
let ivars = OutputStreamDelegateIvars {
receiver: Mutex::new(BlockOn::new(receiver)),
stream,
};
let this = OutputStreamDelegate::alloc().set_ivars(ivars);
unsafe { msg_send![super(this), init] }
}
fn send_packet(&self, output_stream: &NSOutputStream) {
let mut receiver = self.ivars().receiver.lock().unwrap();
// This is racy but there will always be at least this many bytesin the channel
let to_write = receiver.get_ref().len();
if to_write == 0 {
trace!("No data to write");
return;
}
let mut buf = vec![0u8; to_write];
let to_write = match receiver.read(&mut buf) {
Err(e) => {
warn!("Error reading from stream {:?}", e);
return;
}
Ok(0) => {
trace!("No more data to write");
self.close(output_stream);
return;
}
Ok(n) => n,
};
buf.truncate(to_write);
let res = unsafe { output_stream.write_maxLength(NonNull::new_unchecked(buf.as_mut_ptr()), buf.len()) };
if res < 0 {
debug!("Write Loop Error: Stream write failed");
self.close(output_stream);
}
}
fn close(&self, output_stream: &NSOutputStream) {
unsafe {
output_stream.setDelegate(None);
output_stream.close();
let center = NSNotificationCenter::defaultCenter();
center.removeObserver(self);
}
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/corebluetooth/adapter.rs | src/corebluetooth/adapter.rs | #![allow(clippy::let_unit_value)]
use std::ops::Deref;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use futures_core::Stream;
use futures_lite::{stream, StreamExt};
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2::{AnyThread, Message};
use objc2_core_bluetooth::{
CBCentralManager, CBCentralManagerOptionShowPowerAlertKey, CBManager, CBManagerAuthorization, CBManagerState,
CBUUID,
};
use objc2_foundation::{NSArray, NSData, NSDictionary, NSNumber, NSString, NSUUID};
use tracing::{debug, error, info, warn};
use super::delegates::{self, CentralDelegate};
use super::dispatch::{self, Dispatched};
use crate::error::ErrorKind;
use crate::util::defer;
use crate::{
AdapterEvent, AdvertisingDevice, BluetoothUuidExt, ConnectionEvent, Device, DeviceId, Error, Result, Uuid,
};
#[derive(Default)]
pub struct AdapterConfig {
/// Enable/disable the power alert dialog when using the adapter.
pub show_power_alert: bool,
}
/// The system's Bluetooth adapter interface.
///
/// The default adapter for the system may be accessed with the [`Adapter::default()`] method.
#[derive(Clone)]
pub struct AdapterImpl {
central: Dispatched<CBCentralManager>,
delegate: Retained<CentralDelegate>,
scanning: Arc<AtomicBool>,
#[cfg(not(target_os = "macos"))]
registered_connection_events: Arc<std::sync::Mutex<std::collections::HashMap<DeviceId, usize>>>,
}
impl PartialEq for AdapterImpl {
fn eq(&self, other: &Self) -> bool {
self.central == other.central
}
}
impl Eq for AdapterImpl {}
impl std::hash::Hash for AdapterImpl {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.central.hash(state);
}
}
impl std::fmt::Debug for AdapterImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Adapter").field(&self.central).finish()
}
}
impl AdapterImpl {
/// Creates an interface to a Bluetooth adapter using the provided config.
pub async fn with_config(config: AdapterConfig) -> Result<Self> {
match unsafe { CBManager::authorization_class() } {
CBManagerAuthorization::AllowedAlways => info!("Bluetooth authorization is allowed"),
CBManagerAuthorization::Denied => error!("Bluetooth authorization is denied"),
CBManagerAuthorization::NotDetermined => {
warn!("Bluetooth authorization is undetermined")
}
CBManagerAuthorization::Restricted => warn!("Bluetooth authorization is restricted"),
val => error!("Bluetooth authorization returned unknown value {:?}", val),
}
let delegate = CentralDelegate::new();
let protocol = ProtocolObject::from_retained(delegate.clone());
let central = unsafe {
let this = CBCentralManager::alloc();
let options: Retained<NSDictionary<NSString>> = NSDictionary::from_retained_objects(
&[CBCentralManagerOptionShowPowerAlertKey],
&[NSNumber::numberWithBool(config.show_power_alert).into()],
);
CBCentralManager::initWithDelegate_queue_options(
this,
Some(&protocol),
Some(dispatch::queue()),
Some(options.deref()),
)
};
let central = unsafe { Dispatched::new(central) };
Ok(AdapterImpl {
central,
delegate,
scanning: Default::default(),
#[cfg(not(target_os = "macos"))]
registered_connection_events: Default::default(),
})
}
/// A stream of [`AdapterEvent`] which allows the application to identify when the adapter is enabled or disabled.
pub async fn events(&self) -> Result<impl Stream<Item = Result<AdapterEvent>> + Send + Unpin + '_> {
let receiver = self.delegate.sender().new_receiver();
Ok(receiver.filter_map(|x| {
match x {
delegates::CentralEvent::StateChanged => {
// TODO: Check CBCentralManager::authorization()?
let state = self.state();
debug!("Central state is now {:?}", state);
match state {
CBManagerState::PoweredOn => Some(Ok(AdapterEvent::Available)),
_ => Some(Ok(AdapterEvent::Unavailable)),
}
}
_ => None,
}
}))
}
fn state(&self) -> CBManagerState {
self.central.dispatch(|central| unsafe { central.state() })
}
/// Asynchronously blocks until the adapter is available
pub async fn wait_available(&self) -> Result<()> {
let events = self.events();
if self.state() != CBManagerState::PoweredOn {
events
.await?
.skip_while(|x| x.is_ok() && !matches!(x, Ok(AdapterEvent::Available)))
.next()
.await
.ok_or_else(|| Error::new(ErrorKind::Internal, None, "adapter event stream closed unexpectedly"))??;
}
Ok(())
}
/// Check if the adapter is available
pub async fn is_available(&self) -> Result<bool> {
let state = self.state();
Ok(state == CBManagerState::PoweredOn)
}
/// Attempts to create the device identified by `id`
pub async fn open_device(&self, id: &DeviceId) -> Result<Device> {
self.central.dispatch(|central| unsafe {
let identifiers = NSArray::from_retained_slice(&[NSUUID::from_bytes(*id.0.as_bytes())]);
let peripherals = central.retrievePeripheralsWithIdentifiers(&identifiers);
peripherals
.iter()
.next()
.map(Device::new)
.ok_or_else(|| Error::new(ErrorKind::NotFound, None, "opening device"))
})
}
/// Finds all connected Bluetooth LE devices
pub async fn connected_devices(&self) -> Result<Vec<Device>> {
self.connected_devices_with_services(&[crate::btuuid::services::GENERIC_ATTRIBUTE])
.await
}
/// Finds all connected devices providing any service in `services`
///
/// # Panics
///
/// Panics if `services` is empty.
pub async fn connected_devices_with_services(&self, services: &[Uuid]) -> Result<Vec<Device>> {
assert!(!services.is_empty());
self.central.dispatch(|central| {
let services = {
let vec = services
.iter()
.copied()
.map(|s| unsafe { CBUUID::UUIDWithData(&NSData::with_bytes(s.as_bluetooth_bytes())) })
.collect::<Vec<_>>();
NSArray::from_retained_slice(&vec[..])
};
unsafe {
let peripherals = central.retrieveConnectedPeripheralsWithServices(&services);
Ok(peripherals.iter().map(Device::new).collect())
}
})
}
/// Starts scanning for Bluetooth advertising packets.
///
/// Returns a stream of [`AdvertisingDevice`] structs which contain the data from the advertising packet and the
/// [`Device`] which sent it. Scanning is automatically stopped when the stream is dropped. Inclusion of duplicate
/// packets is a platform-specific implementation detail.
///
/// If `services` is not empty, returns advertisements including at least one GATT service with a UUID in
/// `services`. Otherwise returns all advertisements.
pub async fn scan<'a>(
&'a self,
services: &'a [Uuid],
) -> Result<impl Stream<Item = AdvertisingDevice> + Send + Unpin + 'a> {
if self.state() != CBManagerState::PoweredOn {
return Err(Error::from(ErrorKind::AdapterUnavailable));
}
if self.scanning.swap(true, Ordering::Acquire) {
return Err(ErrorKind::AlreadyScanning.into());
}
let receiver = self.delegate.sender().new_receiver();
self.central.dispatch(|central| {
let services = (!services.is_empty()).then(|| {
let vec = services
.iter()
.copied()
.map(|s| unsafe { CBUUID::UUIDWithData(&NSData::with_bytes(s.as_bluetooth_bytes())) })
.collect::<Vec<_>>();
NSArray::from_retained_slice(&vec[..])
});
unsafe { central.scanForPeripheralsWithServices_options(services.as_deref(), None) };
});
let guard = defer(|| {
self.central.dispatch(|central| unsafe { central.stopScan() });
self.scanning.store(false, Ordering::Release);
});
let events = receiver
.take_while(|_| self.state() == CBManagerState::PoweredOn)
.filter_map(move |x| {
let _guard = &guard;
match x {
delegates::CentralEvent::Discovered {
peripheral,
adv_data,
rssi,
} => peripheral.dispatch(|peripheral| {
Some(AdvertisingDevice {
device: Device::new(peripheral.retain()),
adv_data,
rssi: Some(rssi),
})
}),
_ => None,
}
});
Ok(events)
}
/// Finds Bluetooth devices providing any service in `services`.
///
/// Returns a stream of [`Device`] structs with matching connected devices returned first. If the stream is not
/// dropped before all matching connected devices are consumed then scanning will begin for devices advertising any
/// of the `services`. Scanning will continue until the stream is dropped. Inclusion of duplicate devices is a
/// platform-specific implementation detail.
pub async fn discover_devices<'a>(
&'a self,
services: &'a [Uuid],
) -> Result<impl Stream<Item = Result<Device>> + Send + Unpin + 'a> {
let connected = stream::iter(self.connected_devices_with_services(services).await?).map(Ok);
// try_unfold is used to ensure we do not start scanning until the connected devices have been consumed
let advertising = Box::pin(stream::try_unfold(None, |state| async {
let mut stream = match state {
Some(stream) => stream,
None => self.scan(services).await?,
};
Ok(stream.next().await.map(|x| (x.device, Some(stream))))
}));
Ok(connected.chain(advertising))
}
/// Connects to the [`Device`]
///
/// This method must be called before any methods on the [`Device`] which require a connection are called. After a
/// successful return from this method, a connection has been established with the device (if one did not already
/// exist) and the application can then interact with the device. This connection will be maintained until either
/// [`disconnect_device`][Self::disconnect_device] is called or the `Adapter` is dropped.
pub async fn connect_device(&self, device: &Device) -> Result<()> {
if self.state() != CBManagerState::PoweredOn {
return Err(ErrorKind::AdapterUnavailable.into());
}
let mut events = self.delegate.sender().new_receiver();
debug!("Connecting to {:?}", device);
self.central
.dispatch(|central| unsafe { central.connectPeripheral_options(device.0.peripheral.get(), None) });
let drop = defer(|| {
self.central.dispatch(|central| unsafe {
central.cancelPeripheralConnection(device.0.peripheral.get());
})
});
while let Some(event) = events.next().await {
if self.state() != CBManagerState::PoweredOn {
drop.defuse();
return Err(ErrorKind::AdapterUnavailable.into());
}
match event {
delegates::CentralEvent::Connect { peripheral } if peripheral == device.0.peripheral => {
drop.defuse();
return Ok(());
}
delegates::CentralEvent::ConnectFailed { peripheral, error } if peripheral == device.0.peripheral => {
drop.defuse();
return Err(error.map_or(ErrorKind::ConnectionFailed.into(), Error::from_nserror));
}
_ => (),
}
}
unreachable!()
}
/// Disconnects from the [`Device`]
///
/// Once this method is called, the application will no longer have access to the [`Device`] and any methods
/// which would require a connection will fail. If no other application has a connection to the same device,
/// the underlying Bluetooth connection will be closed.
pub async fn disconnect_device(&self, device: &Device) -> Result<()> {
if self.state() != CBManagerState::PoweredOn {
return Err(ErrorKind::AdapterUnavailable.into());
}
let mut events = self.delegate.sender().new_receiver();
debug!("Disconnecting from {:?}", device);
self.central
.dispatch(|central| unsafe { central.cancelPeripheralConnection(device.0.peripheral.get()) });
while let Some(event) = events.next().await {
if self.state() != CBManagerState::PoweredOn {
return Err(ErrorKind::AdapterUnavailable.into());
}
match event {
delegates::CentralEvent::Disconnect {
peripheral,
error: None,
} if peripheral == device.0.peripheral => return Ok(()),
delegates::CentralEvent::Disconnect {
peripheral,
error: Some(err),
} if peripheral == device.0.peripheral => return Err(Error::from_nserror(err)),
_ => (),
}
}
unreachable!()
}
#[cfg(not(target_os = "macos"))]
fn register_connection_events(&self, device: DeviceId) -> impl Drop + '_ {
use std::collections::HashMap;
use objc2::rc::Retained;
use objc2_core_bluetooth::CBConnectionEventMatchingOptionPeripheralUUIDs;
use objc2_foundation::{NSDictionary, NSString};
fn options(devices: &HashMap<DeviceId, usize>) -> Retained<NSDictionary<NSString>> {
let ids: Vec<Retained<NSUUID>> = devices.keys().map(|x| NSUUID::from_bytes(*x.0.as_bytes())).collect();
let ids = NSArray::from_retained_slice(&ids[..]);
NSDictionary::from_retained_objects(
&[unsafe { CBConnectionEventMatchingOptionPeripheralUUIDs }],
&[ids.into()],
)
}
self.central.dispatch(|central| {
let mut guard = self.registered_connection_events.lock().unwrap();
match guard.entry(device.clone()) {
std::collections::hash_map::Entry::Occupied(mut e) => {
*e.get_mut() += 1;
}
std::collections::hash_map::Entry::Vacant(e) => {
e.insert(1);
let opts = options(&guard);
unsafe { central.registerForConnectionEventsWithOptions(Some(&opts)) }
}
}
});
defer(move || {
self.central.dispatch(|central| {
let mut guard = self.registered_connection_events.lock().unwrap();
match guard.entry(device) {
std::collections::hash_map::Entry::Occupied(mut e) => {
*e.get_mut() -= 1;
if *e.get() == 0 {
e.remove();
let opts = options(&guard);
unsafe { central.registerForConnectionEventsWithOptions(Some(&opts)) }
}
}
std::collections::hash_map::Entry::Vacant(_) => unreachable!(),
}
})
})
}
/// Monitors a device for connection/disconnection events.
///
/// # Platform specifics
///
/// ## MacOS/iOS
///
/// Available on iOS/iPadOS only. On MacOS no events will be generated.
#[cfg(not(target_os = "macos"))]
pub async fn device_connection_events<'a>(
&'a self,
device: &'a Device,
) -> Result<impl Stream<Item = ConnectionEvent> + Send + Unpin + 'a> {
let events = self.delegate.sender().new_receiver();
let guard = self.register_connection_events(device.id());
let id = device
.0
.peripheral
.dispatch(|peripheral| unsafe { peripheral.identifier() });
Ok(events
.take_while(|_| self.state() == CBManagerState::PoweredOn)
.filter_map(move |x| {
let _guard = &guard;
match x {
delegates::CentralEvent::Connect { peripheral }
if peripheral.dispatch(|peripheral| unsafe { peripheral.identifier() } == id) =>
{
Some(ConnectionEvent::Connected)
}
delegates::CentralEvent::Disconnect { peripheral, .. }
if peripheral.dispatch(|peripheral| unsafe { peripheral.identifier() } == id) =>
{
Some(ConnectionEvent::Disconnected)
}
delegates::CentralEvent::ConnectionEvent { peripheral, event }
if peripheral.dispatch(|peripheral| unsafe { peripheral.identifier() } == id) =>
{
Some(event)
}
_ => None,
}
}))
}
/// Monitors a device for connection/disconnection events.
///
/// # Platform specifics
///
/// ## MacOS/iOS
///
/// Available on iOS/iPadOS only. On MacOS no events will be generated.
#[cfg(target_os = "macos")]
pub async fn device_connection_events<'a>(
&'a self,
device: &'a Device,
) -> Result<impl Stream<Item = ConnectionEvent> + Send + Unpin + 'a> {
let events = self.delegate.sender().new_receiver();
Ok(events
.take_while(|_| self.state() == CBManagerState::PoweredOn)
.filter_map(move |x| match x {
delegates::CentralEvent::Connect { peripheral } if peripheral == device.0.peripheral => {
Some(ConnectionEvent::Connected)
}
delegates::CentralEvent::Disconnect { peripheral, .. } if peripheral == device.0.peripheral => {
Some(ConnectionEvent::Disconnected)
}
_ => None,
}))
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/corebluetooth/error.rs | src/corebluetooth/error.rs | use objc2::rc::Retained;
use objc2_core_bluetooth::CBError;
use objc2_foundation::NSError;
use crate::error::{AttError, ErrorKind};
impl crate::Error {
pub(super) fn from_recv_error(err: async_broadcast::RecvError) -> Self {
crate::Error::new(ErrorKind::Internal, Some(Box::new(err)), "receiving delegate event")
}
pub(super) fn from_nserror(err: Retained<NSError>) -> Self {
crate::Error::new(
kind_from_nserror(&err),
Some(Box::new(NSErrorError(err))),
String::new(),
)
}
pub(super) fn from_kind_and_nserror(kind: ErrorKind, err: Option<Retained<NSError>>) -> Self {
match err {
Some(err) => crate::Error::new(kind, Some(Box::new(NSErrorError(err))), String::new()),
None => kind.into(),
}
}
}
fn kind_from_nserror(value: &NSError) -> ErrorKind {
if value.domain().to_string() == "CBErrorDomain" {
match CBError(value.code()) {
CBError::OperationNotSupported => ErrorKind::NotSupported,
CBError::NotConnected | CBError::PeripheralDisconnected => ErrorKind::NotConnected,
CBError::ConnectionTimeout | CBError::EncryptionTimedOut => ErrorKind::Timeout,
CBError::InvalidParameters | CBError::InvalidHandle | CBError::UUIDNotAllowed | CBError::UnknownDevice => {
ErrorKind::InvalidParameter
}
CBError::ConnectionFailed
| CBError::PeerRemovedPairingInformation
| CBError::ConnectionLimitReached
| CBError::TooManyLEPairedDevices => ErrorKind::ConnectionFailed,
CBError::Unknown | CBError::OutOfSpace | CBError::OperationCancelled | CBError::AlreadyAdvertising => {
ErrorKind::Other
}
_ => ErrorKind::Other,
}
} else if value.domain().to_string() == "CBATTErrorDomain" {
let n = value.code();
if let Ok(n) = u8::try_from(n) {
ErrorKind::Protocol(AttError::from(n))
} else {
ErrorKind::Other
}
} else {
ErrorKind::Other
}
}
struct NSErrorError(Retained<NSError>);
impl std::fmt::Debug for NSErrorError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(&self.0, f)
}
}
impl std::fmt::Display for NSErrorError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.localizedDescription(), f)
}
}
impl std::error::Error for NSErrorError {}
impl std::ops::Deref for NSErrorError {
type Target = NSError;
fn deref(&self) -> &Self::Target {
&self.0
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/corebluetooth/service.rs | src/corebluetooth/service.rs | use objc2::rc::Retained;
use objc2_core_bluetooth::{CBPeripheralState, CBService, CBUUID};
use objc2_foundation::{NSArray, NSData};
use super::delegates::{PeripheralDelegate, PeripheralEvent};
use super::dispatch::Dispatched;
use crate::error::ErrorKind;
use crate::{BluetoothUuidExt, Characteristic, Error, Result, Service, Uuid};
/// A Bluetooth GATT service
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServiceImpl {
pub(super) inner: Dispatched<CBService>,
delegate: Retained<PeripheralDelegate>,
}
impl Service {
pub(super) fn new(service: Retained<CBService>, delegate: Retained<PeripheralDelegate>) -> Self {
Service(ServiceImpl {
inner: unsafe { Dispatched::new(service) },
delegate,
})
}
}
impl ServiceImpl {
/// The [`Uuid`] identifying the type of this GATT service
pub fn uuid(&self) -> Uuid {
self.inner
.dispatch(|service| unsafe { Uuid::from_bluetooth_bytes(service.UUID().data().as_bytes_unchecked()) })
}
/// The [`Uuid`] identifying the type of this GATT service
pub async fn uuid_async(&self) -> Result<Uuid> {
Ok(self.uuid())
}
/// Whether this is a primary service of the device.
pub async fn is_primary(&self) -> Result<bool> {
self.inner.dispatch(|service| unsafe { Ok(service.isPrimary()) })
}
/// Discover all characteristics associated with this service.
pub async fn discover_characteristics(&self) -> Result<Vec<Characteristic>> {
self.discover_characteristics_inner(None).await
}
/// Discover the characteristic(s) with the given [`Uuid`].
pub async fn discover_characteristics_with_uuid(&self, uuid: Uuid) -> Result<Vec<Characteristic>> {
let characteristics = self.discover_characteristics_inner(Some(uuid)).await?;
Ok(characteristics.into_iter().filter(|x| x.uuid() == uuid).collect())
}
async fn discover_characteristics_inner(&self, uuid: Option<Uuid>) -> Result<Vec<Characteristic>> {
let mut receiver = self.delegate.sender().new_receiver();
self.inner.dispatch(|service| {
let uuids = uuid.map(|uuid| unsafe {
NSArray::from_retained_slice(&[CBUUID::UUIDWithData(&NSData::with_bytes(uuid.as_bluetooth_bytes()))])
});
let peripheral = unsafe {
service
.peripheral()
.ok_or(Error::new(ErrorKind::NotFound, None, "peripheral not found"))?
};
if unsafe { peripheral.state() } != CBPeripheralState::Connected {
return Err(Error::from(ErrorKind::NotConnected));
}
unsafe { peripheral.discoverCharacteristics_forService(uuids.as_deref(), service) };
Ok(())
})?;
loop {
match receiver.recv().await.map_err(Error::from_recv_error)? {
PeripheralEvent::DiscoveredCharacteristics { service, error } if service == self.inner => match error {
Some(err) => return Err(Error::from_nserror(err)),
None => break,
},
PeripheralEvent::Disconnected { error } => {
return Err(Error::from_kind_and_nserror(ErrorKind::NotConnected, error));
}
PeripheralEvent::ServicesChanged { invalidated_services }
if invalidated_services.contains(&self.inner) =>
{
return Err(ErrorKind::ServiceChanged.into());
}
_ => (),
}
}
self.characteristics_inner()
}
/// Get previously discovered characteristics.
///
/// If no characteristics have been discovered yet, this method will perform characteristic discovery.
pub async fn characteristics(&self) -> Result<Vec<Characteristic>> {
match self.characteristics_inner() {
Ok(characteristics) => Ok(characteristics),
Err(_) => self.discover_characteristics().await,
}
}
fn characteristics_inner(&self) -> Result<Vec<Characteristic>> {
self.inner.dispatch(|service| {
unsafe { service.characteristics() }
.map(|s| {
s.iter()
.map(|x| Characteristic::new(x, self.delegate.clone()))
.collect()
})
.ok_or_else(|| Error::new(ErrorKind::NotReady, None, "no characteristics have been discovered"))
})
}
/// Discover the included services of this service.
pub async fn discover_included_services(&self) -> Result<Vec<Service>> {
self.discover_included_services_inner(None).await
}
/// Discover the included service(s) with the given [`Uuid`].
pub async fn discover_included_services_with_uuid(&self, uuid: Uuid) -> Result<Vec<Service>> {
let services = self.discover_included_services_inner(Some(uuid)).await?;
Ok(services.into_iter().filter(|x| x.uuid() == uuid).collect())
}
async fn discover_included_services_inner(&self, uuid: Option<Uuid>) -> Result<Vec<Service>> {
let mut receiver = self.delegate.sender().new_receiver();
self.inner.dispatch(|service| {
let uuids = uuid.map(|uuid| unsafe {
NSArray::from_retained_slice(&[CBUUID::UUIDWithData(&NSData::with_bytes(uuid.as_bluetooth_bytes()))])
});
let peripheral = unsafe {
service
.peripheral()
.ok_or(Error::new(ErrorKind::NotFound, None, "peripheral not found"))?
};
if unsafe { peripheral.state() } != CBPeripheralState::Connected {
return Err(Error::from(ErrorKind::NotConnected));
}
unsafe { peripheral.discoverIncludedServices_forService(uuids.as_deref(), service) };
Ok(())
})?;
loop {
match receiver.recv().await.map_err(Error::from_recv_error)? {
PeripheralEvent::DiscoveredIncludedServices { service, error } if service == self.inner => {
match error {
Some(err) => return Err(Error::from_nserror(err)),
None => break,
}
}
PeripheralEvent::Disconnected { error } => {
return Err(Error::from_kind_and_nserror(ErrorKind::NotConnected, error));
}
PeripheralEvent::ServicesChanged { invalidated_services }
if invalidated_services.contains(&self.inner) =>
{
return Err(ErrorKind::ServiceChanged.into());
}
_ => (),
}
}
self.included_services_inner()
}
/// Get previously discovered included services.
///
/// If no included services have been discovered yet, this method will perform included service discovery.
pub async fn included_services(&self) -> Result<Vec<Service>> {
match self.included_services_inner() {
Ok(services) => Ok(services),
Err(_) => self.discover_included_services().await,
}
}
fn included_services_inner(&self) -> Result<Vec<Service>> {
self.inner.dispatch(|service| {
unsafe { service.includedServices() }
.map(|s| s.iter().map(|x| Service::new(x, self.delegate.clone())).collect())
.ok_or_else(|| Error::new(ErrorKind::NotReady, None, "no included services have been discovered"))
})
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/corebluetooth/delegates.rs | src/corebluetooth/delegates.rs | use objc2::rc::Retained;
use objc2::{define_class, msg_send, AnyThread, DefinedClass, Message};
use objc2_core_bluetooth::{
CBCentralManager, CBCentralManagerDelegate, CBCharacteristic, CBConnectionEvent, CBDescriptor, CBL2CAPChannel,
CBPeripheral, CBPeripheralDelegate, CBService,
};
use objc2_foundation::{NSArray, NSDictionary, NSError, NSNumber, NSObject, NSObjectProtocol, NSString};
use tracing::{debug, warn};
use super::dispatch::Dispatched;
use crate::{AdvertisementData, ConnectionEvent};
#[derive(Clone)]
pub enum CentralEvent {
Connect {
peripheral: Dispatched<CBPeripheral>,
},
Disconnect {
peripheral: Dispatched<CBPeripheral>,
error: Option<Retained<NSError>>,
},
ConnectFailed {
peripheral: Dispatched<CBPeripheral>,
error: Option<Retained<NSError>>,
},
ConnectionEvent {
peripheral: Dispatched<CBPeripheral>,
event: ConnectionEvent,
},
Discovered {
peripheral: Dispatched<CBPeripheral>,
adv_data: AdvertisementData,
rssi: i16,
},
StateChanged,
}
impl std::fmt::Debug for CentralEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Connect { peripheral } => f.debug_struct("Connect").field("peripheral", peripheral).finish(),
Self::Disconnect { peripheral, error } => f
.debug_struct("Disconnect")
.field("peripheral", peripheral)
.field("error", error)
.finish(),
Self::ConnectFailed { peripheral, error } => f
.debug_struct("ConnectFailed")
.field("peripheral", peripheral)
.field("error", error)
.finish(),
Self::ConnectionEvent { peripheral, event } => f
.debug_struct("ConnectionEvent")
.field("peripheral", peripheral)
.field("event", event)
.finish(),
Self::Discovered { peripheral, rssi, .. } => f
.debug_struct("Discovered")
.field("peripheral", peripheral)
.field("rssi", rssi)
.finish(),
Self::StateChanged => write!(f, "StateChanged"),
}
}
}
#[derive(Debug, Clone)]
pub enum PeripheralEvent {
Connected,
Disconnected {
error: Option<Retained<NSError>>,
},
DiscoveredServices {
error: Option<Retained<NSError>>,
},
DiscoveredIncludedServices {
service: Dispatched<CBService>,
error: Option<Retained<NSError>>,
},
DiscoveredCharacteristics {
service: Dispatched<CBService>,
error: Option<Retained<NSError>>,
},
DiscoveredDescriptors {
characteristic: Dispatched<CBCharacteristic>,
error: Option<Retained<NSError>>,
},
CharacteristicValueUpdate {
characteristic: Dispatched<CBCharacteristic>,
data: Vec<u8>,
error: Option<Retained<NSError>>,
},
DescriptorValueUpdate {
descriptor: Dispatched<CBDescriptor>,
error: Option<Retained<NSError>>,
},
CharacteristicValueWrite {
characteristic: Dispatched<CBCharacteristic>,
error: Option<Retained<NSError>>,
},
DescriptorValueWrite {
descriptor: Dispatched<CBDescriptor>,
error: Option<Retained<NSError>>,
},
ReadyToWrite,
NotificationStateUpdate {
characteristic: Dispatched<CBCharacteristic>,
error: Option<Retained<NSError>>,
},
ReadRssi {
rssi: i16,
error: Option<Retained<NSError>>,
},
NameUpdate,
ServicesChanged {
invalidated_services: Vec<Dispatched<CBService>>,
},
#[allow(unused)]
L2CAPChannelOpened {
channel: Dispatched<CBL2CAPChannel>,
error: Option<Retained<NSError>>,
},
}
#[derive(Debug)]
pub(crate) struct CentralDelegateIvars {
pub sender: async_broadcast::Sender<CentralEvent>,
_receiver: async_broadcast::InactiveReceiver<CentralEvent>,
}
define_class!(
#[unsafe(super(NSObject))]
#[ivars = CentralDelegateIvars]
#[derive(Debug, PartialEq, Eq, Hash)]
pub(crate) struct CentralDelegate;
unsafe impl NSObjectProtocol for CentralDelegate {}
unsafe impl CBCentralManagerDelegate for CentralDelegate {
#[unsafe(method(centralManagerDidUpdateState:))]
fn did_update_state(&self, _central: &CBCentralManager) {
let _ = self.ivars().sender.try_broadcast(CentralEvent::StateChanged);
}
#[unsafe(method(centralManager:didConnectPeripheral:))]
fn did_connect_peripheral(&self, _central: &CBCentralManager, peripheral: &CBPeripheral) {
let sender = &self.ivars().sender;
unsafe {
if let Some(delegate) = peripheral
.delegate()
.and_then(|d| d.downcast::<PeripheralDelegate>().ok())
{
let _res = delegate.sender().try_broadcast(PeripheralEvent::Connected);
}
let event = CentralEvent::Connect {
peripheral: Dispatched::retain(peripheral),
};
debug!("CentralDelegate received {:?}", event);
let _ = sender.try_broadcast(event);
}
}
#[unsafe(method(centralManager:didDisconnectPeripheral:error:))]
fn did_disconnect_peripheral_error(
&self,
_central: &CBCentralManager,
peripheral: &CBPeripheral,
error: Option<&NSError>,
) {
unsafe {
let sender = &self.ivars().sender;
if let Some(delegate) = peripheral
.delegate()
.and_then(|d| d.downcast::<PeripheralDelegate>().ok())
{
let _res = delegate.sender().try_broadcast(PeripheralEvent::Disconnected {
error: error.map(|e| e.retain()),
});
}
let event = CentralEvent::Disconnect {
peripheral: Dispatched::retain(peripheral),
error: error.map(|e| e.retain()),
};
debug!("CentralDelegate received {:?}", event);
let _res = sender.try_broadcast(event);
}
}
#[unsafe(method(centralManager:didDiscoverPeripheral:advertisementData:RSSI:))]
fn did_discover_peripheral(
&self,
_central: &CBCentralManager,
peripheral: &CBPeripheral,
adv_data: &NSDictionary<NSString>,
rssi: &NSNumber,
) {
let sender = &self.ivars().sender;
let rssi: i16 = rssi.shortValue();
let event = CentralEvent::Discovered {
peripheral: unsafe { Dispatched::retain(peripheral) },
adv_data: AdvertisementData::from_nsdictionary(adv_data),
rssi,
};
debug!("CentralDelegate received {:?}", event);
let _res = sender.try_broadcast(event);
}
#[unsafe(method(centralManager:connectionEventDidOccur:forPeripheral:))]
fn on_connection_event(
&self,
_central: &CBCentralManager,
event: CBConnectionEvent,
peripheral: &CBPeripheral,
) {
debug!("CentralDelegate received {:?}", event);
let sender = &self.ivars().sender;
let event = if event == CBConnectionEvent::PeerConnected {
Some(ConnectionEvent::Connected)
} else if event == CBConnectionEvent::PeerDisconnected {
Some(ConnectionEvent::Disconnected)
} else {
None
};
if let Some(event) = event {
let event = CentralEvent::ConnectionEvent {
peripheral: unsafe { Dispatched::retain(peripheral) },
event,
};
let _res = sender.try_broadcast(event);
} else {
warn!("Unrecognized connection event received");
}
}
#[unsafe(method(centralManager:didFailToConnectPeripheral:error:))]
fn did_fail_to_connect(&self, _central: &CBCentralManager, peripheral: &CBPeripheral, error: Option<&NSError>) {
let _ = self.ivars().sender.try_broadcast(CentralEvent::ConnectFailed {
peripheral: unsafe { Dispatched::retain(peripheral) },
error: error.map(|e| e.retain()),
});
}
}
);
impl CentralDelegate {
pub fn new() -> Retained<Self> {
let (mut sender, receiver) = async_broadcast::broadcast::<CentralEvent>(16);
sender.set_overflow(true);
let receiver = receiver.deactivate();
let ivars = CentralDelegateIvars {
sender,
_receiver: receiver,
};
let this = CentralDelegate::alloc().set_ivars(ivars);
unsafe { msg_send![super(this), init] }
}
pub fn sender(&self) -> async_broadcast::Sender<CentralEvent> {
self.ivars().sender.clone()
}
}
#[derive(Debug)]
pub(crate) struct PeripheralDelegateIvars {
pub sender: async_broadcast::Sender<PeripheralEvent>,
_receiver: async_broadcast::InactiveReceiver<PeripheralEvent>,
}
define_class!(
#[unsafe(super(NSObject))]
#[ivars = PeripheralDelegateIvars]
#[derive(Debug, PartialEq, Eq, Hash)]
pub(crate) struct PeripheralDelegate;
unsafe impl NSObjectProtocol for PeripheralDelegate {}
unsafe impl CBPeripheralDelegate for PeripheralDelegate {
#[unsafe(method(peripheral:didUpdateValueForCharacteristic:error:))]
fn did_update_value_for_characteristic_error(
&self,
_peripheral: &CBPeripheral,
characteristic: &CBCharacteristic,
error: Option<&NSError>,
) {
unsafe {
let sender = &self.ivars().sender;
let data = characteristic
.value()
.map(|x| x.as_bytes_unchecked().to_vec())
.unwrap_or_default();
let event = PeripheralEvent::CharacteristicValueUpdate {
characteristic: Dispatched::retain(characteristic),
data,
error: error.map(|e| e.retain()),
};
debug!("PeripheralDelegate received {:?}", event);
let _res = sender.try_broadcast(event);
}
}
#[unsafe(method(peripheral:didDiscoverServices:))]
fn did_discover_services(&self, _peripheral: &CBPeripheral, error: Option<&NSError>) {
let _ = self.ivars().sender.try_broadcast(PeripheralEvent::DiscoveredServices {
error: error.map(|e| e.retain()),
});
}
#[unsafe(method(peripheral:didDiscoverIncludedServicesForService:error:))]
fn did_discover_included_services(
&self,
_peripheral: &CBPeripheral,
service: &CBService,
error: Option<&NSError>,
) {
let _ = self
.ivars()
.sender
.try_broadcast(PeripheralEvent::DiscoveredIncludedServices {
service: unsafe { Dispatched::retain(service) },
error: error.map(|e| e.retain()),
});
}
#[unsafe(method(peripheralDidUpdateName:))]
fn did_update_name(&self, _peripheral: &CBPeripheral) {
let _ = self.ivars().sender.try_broadcast(PeripheralEvent::NameUpdate);
}
#[unsafe(method(peripheral:didModifyServices:))]
fn did_modify_services(&self, _peripheral: &CBPeripheral, invalidated_services: &NSArray<CBService>) {
let invalidated_services = invalidated_services
.iter()
.map(|x| unsafe { Dispatched::new(x) })
.collect();
let _ = self
.ivars()
.sender
.try_broadcast(PeripheralEvent::ServicesChanged { invalidated_services });
}
#[unsafe(method(peripheralDidUpdateRSSI:error:))]
fn did_update_rssi(&self, _peripheral: &CBPeripheral, _error: Option<&NSError>) {}
#[unsafe(method(peripheral:didReadRSSI:error:))]
fn did_read_rssi(&self, _peripheral: &CBPeripheral, rssi: &NSNumber, error: Option<&NSError>) {
let _ = self.ivars().sender.try_broadcast(PeripheralEvent::ReadRssi {
rssi: rssi.shortValue(),
error: error.map(|e| e.retain()),
});
}
#[unsafe(method(peripheral:didDiscoverCharacteristicsForService:error:))]
fn did_discover_characteristics_for_service(
&self,
_peripheral: &CBPeripheral,
service: &CBService,
error: Option<&NSError>,
) {
let _ = self
.ivars()
.sender
.try_broadcast(PeripheralEvent::DiscoveredCharacteristics {
service: unsafe { Dispatched::retain(service) },
error: error.map(|e| e.retain()),
});
}
#[unsafe(method(peripheral:didWriteValueForCharacteristic:error:))]
fn did_write_value_for_characteristic(
&self,
_peripheral: &CBPeripheral,
characteristic: &CBCharacteristic,
error: Option<&NSError>,
) {
let _ = self
.ivars()
.sender
.try_broadcast(PeripheralEvent::CharacteristicValueWrite {
characteristic: unsafe { Dispatched::retain(characteristic) },
error: error.map(|e| e.retain()),
});
}
#[unsafe(method(peripheral:didUpdateNotificationStateForCharacteristic:error:))]
fn did_update_notification_state_for_characteristic(
&self,
_peripheral: &CBPeripheral,
characteristic: &CBCharacteristic,
error: Option<&NSError>,
) {
let _ = self
.ivars()
.sender
.try_broadcast(PeripheralEvent::NotificationStateUpdate {
characteristic: unsafe { Dispatched::retain(characteristic) },
error: error.map(|e| e.retain()),
});
}
#[unsafe(method(peripheral:didDiscoverDescriptorsForCharacteristic:error:))]
fn did_discover_descriptors_for_characteristic(
&self,
_peripheral: &CBPeripheral,
characteristic: &CBCharacteristic,
error: Option<&NSError>,
) {
let _ = self
.ivars()
.sender
.try_broadcast(PeripheralEvent::DiscoveredDescriptors {
characteristic: unsafe { Dispatched::retain(characteristic) },
error: error.map(|e| e.retain()),
});
}
#[unsafe(method(peripheral:didUpdateValueForDescriptor:error:))]
fn did_update_value_for_descriptor(
&self,
_peripheral: &CBPeripheral,
descriptor: &CBDescriptor,
error: Option<&NSError>,
) {
let _ = self
.ivars()
.sender
.try_broadcast(PeripheralEvent::DescriptorValueUpdate {
descriptor: unsafe { Dispatched::retain(descriptor) },
error: error.map(|e| e.retain()),
});
}
#[unsafe(method(peripheral:didWriteValueForDescriptor:error:))]
fn did_write_value_for_descriptor(
&self,
_peripheral: &CBPeripheral,
descriptor: &CBDescriptor,
error: Option<&NSError>,
) {
let _ = self
.ivars()
.sender
.try_broadcast(PeripheralEvent::DescriptorValueWrite {
descriptor: unsafe { Dispatched::retain(descriptor) },
error: error.map(|e| e.retain()),
});
}
#[unsafe(method(peripheralIsReadyToSendWriteWithoutResponse:))]
fn is_ready_to_write_without_response(&self, _peripheral: &CBPeripheral) {
let _ = self.ivars().sender.try_broadcast(PeripheralEvent::ReadyToWrite);
}
#[unsafe(method(peripheral:didOpenL2CAPChannel:error:))]
fn did_open_l2cap_channel(
&self,
_peripheral: &CBPeripheral,
channel: Option<&CBL2CAPChannel>,
error: Option<&NSError>,
) {
if let Some(channel) = channel {
let _ = self.ivars().sender.try_broadcast(PeripheralEvent::L2CAPChannelOpened {
channel: unsafe { Dispatched::retain(channel) },
error: error.map(|e| e.retain()),
});
}
}
}
);
impl PeripheralDelegate {
pub fn new() -> Retained<Self> {
let (mut sender, receiver) = async_broadcast::broadcast::<PeripheralEvent>(16);
sender.set_overflow(true);
let receiver = receiver.deactivate();
let ivars = PeripheralDelegateIvars {
sender,
_receiver: receiver,
};
let this = PeripheralDelegate::alloc().set_ivars(ivars);
unsafe { msg_send![super(this), init] }
}
pub fn sender(&self) -> async_broadcast::Sender<PeripheralEvent> {
self.ivars().sender.clone()
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/corebluetooth/ad.rs | src/corebluetooth/ad.rs | use std::collections::HashMap;
use objc2_core_bluetooth::{
CBAdvertisementDataIsConnectable, CBAdvertisementDataLocalNameKey, CBAdvertisementDataManufacturerDataKey,
CBAdvertisementDataOverflowServiceUUIDsKey, CBAdvertisementDataServiceDataKey, CBAdvertisementDataServiceUUIDsKey,
CBAdvertisementDataTxPowerLevelKey, CBUUID,
};
use objc2_foundation::{NSArray, NSData, NSDictionary, NSNumber, NSString};
use uuid::Uuid;
use crate::{AdvertisementData, BluetoothUuidExt, ManufacturerData};
impl AdvertisementData {
pub(crate) fn from_nsdictionary(adv_data: &NSDictionary<NSString>) -> Self {
let is_connectable = adv_data
.objectForKey(unsafe { CBAdvertisementDataIsConnectable })
.is_some_and(|val| val.downcast_ref::<NSNumber>().map(|b| b.as_bool()).unwrap_or(false));
let local_name = adv_data
.objectForKey(unsafe { CBAdvertisementDataLocalNameKey })
.and_then(|val| val.downcast_ref::<NSString>().map(|s| s.to_string()));
let manufacturer_data = adv_data
.objectForKey(unsafe { CBAdvertisementDataManufacturerDataKey })
.and_then(|val| val.downcast_ref::<NSData>().map(|v| v.to_vec()))
.and_then(|val| {
(val.len() >= 2).then(|| ManufacturerData {
company_id: u16::from_le_bytes(val[0..2].try_into().unwrap()),
data: val[2..].to_vec(),
})
});
let tx_power_level: Option<i16> = adv_data
.objectForKey(unsafe { CBAdvertisementDataTxPowerLevelKey })
.and_then(|val| val.downcast_ref::<NSNumber>().map(|val| val.shortValue()));
let service_data = if let Some(val) = adv_data.objectForKey(unsafe { CBAdvertisementDataServiceDataKey }) {
unsafe {
if let Some(val) = val.downcast_ref::<NSDictionary>() {
let mut res = HashMap::with_capacity(val.count());
for k in val.allKeys() {
if let Some(key) = k.downcast_ref::<CBUUID>() {
if let Some(val) = val
.objectForKey_unchecked(&k)
.and_then(|val| val.downcast_ref::<NSData>())
{
res.insert(
Uuid::from_bluetooth_bytes(key.data().as_bytes_unchecked()),
val.to_vec(),
);
}
}
}
res
} else {
HashMap::new()
}
}
} else {
HashMap::new()
};
let services = adv_data
.objectForKey(unsafe { CBAdvertisementDataServiceUUIDsKey })
.into_iter()
.chain(adv_data.objectForKey(unsafe { CBAdvertisementDataOverflowServiceUUIDsKey }))
.flat_map(|x| x.downcast::<NSArray>())
.flatten()
.flat_map(|obj| obj.downcast::<CBUUID>())
.map(|uuid| unsafe { uuid.data() })
.map(|data| unsafe { Uuid::from_bluetooth_bytes(data.as_bytes_unchecked()) })
.collect();
AdvertisementData {
local_name,
manufacturer_data,
services,
service_data,
tx_power_level,
is_connectable,
}
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/windows/descriptor.rs | src/windows/descriptor.rs | use windows::Devices::Bluetooth::BluetoothCacheMode;
use windows::Devices::Bluetooth::GenericAttributeProfile::GattDescriptor;
use windows::Storage::Streams::{DataReader, DataWriter};
use super::error::check_communication_status;
use crate::{Descriptor, Result, Uuid};
/// A Bluetooth GATT descriptor
#[derive(Clone, PartialEq, Eq)]
pub struct DescriptorImpl {
inner: GattDescriptor,
}
impl std::fmt::Debug for DescriptorImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Descriptor")
.field("uuid", &self.inner.Uuid().unwrap())
.field("handle", &self.inner.AttributeHandle().unwrap())
.finish()
}
}
impl Descriptor {
pub(super) fn new(descriptor: GattDescriptor) -> Self {
Descriptor(DescriptorImpl { inner: descriptor })
}
}
impl DescriptorImpl {
/// The [`Uuid`] identifying the type of descriptor
pub fn uuid(&self) -> Uuid {
Uuid::from_u128(self.inner.Uuid().expect("UUID missing on GattDescriptor").to_u128())
}
/// The [`Uuid`] identifying the type of this GATT descriptor
pub async fn uuid_async(&self) -> Result<Uuid> {
Ok(Uuid::from_u128(self.inner.Uuid()?.to_u128()))
}
/// The cached value of this descriptor
///
/// If the value has not yet been read, this method may either return an error or perform a read of the value.
pub async fn value(&self) -> Result<Vec<u8>> {
self.read_value(BluetoothCacheMode::Cached).await
}
/// Read the value of this descriptor from the device
pub async fn read(&self) -> Result<Vec<u8>> {
self.read_value(BluetoothCacheMode::Uncached).await
}
async fn read_value(&self, cachemode: BluetoothCacheMode) -> Result<Vec<u8>> {
let res = self.inner.ReadValueWithCacheModeAsync(cachemode)?.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "reading descriptor value")?;
let buf = res.Value()?;
let mut data = vec![0; buf.Length()? as usize];
let reader = DataReader::FromBuffer(&buf)?;
reader.ReadBytes(data.as_mut_slice())?;
Ok(data)
}
/// Write the value of this descriptor on the device to `value`
pub async fn write(&self, value: &[u8]) -> Result<()> {
let op = {
let writer = DataWriter::new()?;
writer.WriteBytes(value)?;
let buf = writer.DetachBuffer()?;
self.inner.WriteValueWithResultAsync(&buf)?
};
let res = op.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "writing descriptor value")
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/windows/device.rs | src/windows/device.rs | use std::pin::pin;
use futures_channel::mpsc;
use futures_core::Stream;
use futures_lite::{future, StreamExt};
use tracing::error;
use windows::core::{GUID, HSTRING};
use windows::Devices::Bluetooth::{
BluetoothAddressType, BluetoothCacheMode, BluetoothConnectionStatus, BluetoothLEDevice,
};
use windows::Devices::Enumeration::{DeviceInformation, DevicePairingKinds, DevicePairingRequestedEventArgs};
use windows::Foundation::TypedEventHandler;
use super::error::{check_communication_status, check_pairing_status, check_unpairing_status};
use crate::device::ServicesChanged;
use crate::error::ErrorKind;
use crate::pairing::{IoCapability, PairingAgent, Passkey};
use crate::util::defer;
use crate::{Device, DeviceId, Error, Result, Service, Uuid};
/// A Bluetooth LE device
#[derive(Clone)]
pub struct DeviceImpl {
pub(super) inner: BluetoothLEDevice,
}
impl PartialEq for DeviceImpl {
fn eq(&self, other: &Self) -> bool {
self.inner.DeviceId() == other.inner.DeviceId()
}
}
impl Eq for DeviceImpl {}
impl std::hash::Hash for DeviceImpl {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.inner.DeviceId().unwrap().to_os_string().hash(state);
}
}
impl std::fmt::Debug for DeviceImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut f = f.debug_struct("Device");
f.field("id", &self.id());
if let Ok(name) = self.name() {
f.field("name", &name);
}
f.finish()
}
}
impl std::fmt::Display for DeviceImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name().as_deref().unwrap_or("(Unknown)"))
}
}
impl Device {
pub(super) async fn from_addr(addr: u64, kind: Option<BluetoothAddressType>) -> windows::core::Result<Self> {
let inner = if let Some(kind) = kind {
BluetoothLEDevice::FromBluetoothAddressWithBluetoothAddressTypeAsync(addr, kind)?.await?
} else {
BluetoothLEDevice::FromBluetoothAddressAsync(addr)?.await?
};
Ok(Device(DeviceImpl { inner }))
}
pub(super) async fn from_id(id: &HSTRING) -> windows::core::Result<Self> {
let inner = BluetoothLEDevice::FromIdAsync(id)?.await?;
Ok(Device(DeviceImpl { inner }))
}
}
impl DeviceImpl {
/// This device's unique identifier
pub fn id(&self) -> DeviceId {
super::DeviceId(
self.inner
.DeviceId()
.expect("error getting DeviceId for BluetoothLEDevice")
.to_os_string(),
)
}
/// The local name for this device, if available
///
/// This can either be a name advertised or read from the device, or a name assigned to the device by the OS.
pub fn name(&self) -> Result<String> {
let name = self.inner.Name()?;
Ok(name.to_string_lossy())
}
/// The local name for this device, if available
///
/// This can either be a name advertised or read from the device, or a name assigned to the device by the OS.
pub async fn name_async(&self) -> Result<String> {
self.name()
}
/// The connection status for this device
pub async fn is_connected(&self) -> bool {
self.inner.ConnectionStatus() == Ok(BluetoothConnectionStatus::Connected)
}
/// The pairing status for this device
pub async fn is_paired(&self) -> Result<bool> {
// Windows does not update the DeviceInformation property on BluetoothLEDevice when the pairing state
// changes, so we need to get a fresh copy.
let id = self.id();
DeviceInformation::CreateFromIdAsync(&id.0.as_os_str().into())?
.await?
.Pairing()?
.IsPaired()
.map_err(Into::into)
}
/// Attempt to pair this device using the system default pairing UI
///
/// This will fail unless it is called from a UWP application.
pub async fn pair(&self) -> Result<()> {
let op = self.inner.DeviceInformation()?.Pairing()?.PairAsync()?;
let res = op.await?;
check_pairing_status(res.Status()?)
}
/// Attempt to pair this device using the system default pairing UI
pub async fn pair_with_agent<T: PairingAgent>(&self, agent: &T) -> Result<()> {
let pairing_kinds_supported = match agent.io_capability() {
IoCapability::DisplayOnly => DevicePairingKinds::DisplayPin,
IoCapability::DisplayYesNo => {
DevicePairingKinds::ConfirmOnly | DevicePairingKinds::DisplayPin | DevicePairingKinds::ConfirmPinMatch
}
IoCapability::KeyboardOnly => DevicePairingKinds::ConfirmOnly | DevicePairingKinds::ProvidePin,
IoCapability::NoInputNoOutput => DevicePairingKinds::ConfirmOnly,
IoCapability::KeyboardDisplay => {
DevicePairingKinds::ConfirmOnly
| DevicePairingKinds::DisplayPin
| DevicePairingKinds::ProvidePin
| DevicePairingKinds::ConfirmPinMatch
}
};
let (mut tx, mut rx) = mpsc::channel(1);
let custom = self.inner.DeviceInformation()?.Pairing()?.Custom()?;
custom.PairingRequested(&TypedEventHandler::new(
move |_custom, event_args: &Option<DevicePairingRequestedEventArgs>| {
if let Some(event_args) = event_args.clone() {
let deferral = event_args.GetDeferral()?;
let _ = tx.try_send((event_args, deferral));
}
Ok(())
},
))?;
let op = custom.PairAsync(pairing_kinds_supported)?;
let device = Device(self.clone());
let pairing_fut = pin!(async move {
while let Some((event_args, deferral)) = rx.next().await {
match event_args.PairingKind()? {
DevicePairingKinds::ConfirmOnly => {
if agent.confirm(&device).await.is_ok() {
event_args.Accept()?;
}
}
DevicePairingKinds::DisplayPin => {
if let Ok(passkey) = event_args.Pin()?.to_string_lossy().parse::<Passkey>() {
agent.display_passkey(&device, passkey);
}
}
DevicePairingKinds::ProvidePin => {
if let Ok(passkey) = agent.request_passkey(&device).await {
event_args.AcceptWithPin(&passkey.to_string().into())?;
}
}
DevicePairingKinds::ConfirmPinMatch => {
if let Ok(passkey) = event_args.Pin()?.to_string_lossy().parse::<Passkey>() {
if let Ok(()) = agent.confirm_passkey(&device, passkey).await {
event_args.Accept()?;
}
}
}
_ => (),
}
deferral.Complete()?;
}
Result::<_, Error>::Ok(())
});
let op = async move {
let res = op.await;
check_pairing_status(res?.Status()?)
};
let pairing_fut = async move {
pairing_fut.await.and_then(|_| {
Err(Error::new(
ErrorKind::Other,
None,
"Pairing agent terminated unexpectedly".to_owned(),
))
})
};
future::or(op, pairing_fut).await
}
/// Disconnect and unpair this device from the system
pub async fn unpair(&self) -> Result<()> {
let op = self.inner.DeviceInformation()?.Pairing()?.UnpairAsync()?;
let res = op.await?;
check_unpairing_status(res.Status()?)
}
/// Discover the primary services of this device.
pub async fn discover_services(&self) -> Result<Vec<Service>> {
let res = self
.inner
.GetGattServicesWithCacheModeAsync(BluetoothCacheMode::Uncached)?
.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "discovering services")?;
let services = res.Services()?;
Ok(services.into_iter().map(Service::new).collect())
}
/// Discover the primary service(s) of this device with the given [`Uuid`].
pub async fn discover_services_with_uuid(&self, uuid: Uuid) -> Result<Vec<Service>> {
let res = self
.inner
.GetGattServicesForUuidWithCacheModeAsync(GUID::from_u128(uuid.as_u128()), BluetoothCacheMode::Uncached)?
.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "discovering services")?;
let services = res.Services()?;
Ok(services.into_iter().map(Service::new).collect())
}
/// Get previously discovered services.
///
/// If no services have been discovered yet, this method will perform service discovery.
pub async fn services(&self) -> Result<Vec<Service>> {
let res = self
.inner
.GetGattServicesWithCacheModeAsync(BluetoothCacheMode::Cached)?
.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "discovering services")?;
let services = res.Services()?;
Ok(services.into_iter().map(Service::new).collect())
}
/// Monitors the device for services changed events.
pub async fn service_changed_indications(
&self,
) -> Result<impl Stream<Item = Result<ServicesChanged>> + Send + Unpin + '_> {
let (mut sender, receiver) = futures_channel::mpsc::channel(16);
let token = self.inner.GattServicesChanged(&TypedEventHandler::new(move |_, _| {
if let Err(err) = sender.try_send(Ok(ServicesChanged(ServicesChangedImpl))) {
error!("Error sending service changed indication: {:?}", err);
}
Ok(())
}))?;
let guard = defer(move || {
if let Err(err) = self.inner.RemoveGattServicesChanged(token) {
error!("Error removing state changed handler: {:?}", err);
}
});
Ok(receiver.map(move |x| {
let _guard = &guard;
x
}))
}
/// Get the current signal strength from the device in dBm.
///
/// Returns [ErrorKind::NotSupported].
pub async fn rssi(&self) -> Result<i16> {
Err(ErrorKind::NotSupported.into())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServicesChangedImpl;
impl ServicesChangedImpl {
pub fn was_invalidated(&self, _service: &Service) -> bool {
true
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/windows/characteristic.rs | src/windows/characteristic.rs | use futures_core::Stream;
use futures_lite::StreamExt;
use tracing::{error, warn};
use windows::Devices::Bluetooth::BluetoothCacheMode;
use windows::Devices::Bluetooth::GenericAttributeProfile::{
GattCharacteristic, GattClientCharacteristicConfigurationDescriptorValue, GattValueChangedEventArgs,
GattWriteOption, GattWriteResult,
};
use windows::Foundation::{AsyncOperationCompletedHandler, TypedEventHandler};
use windows::Storage::Streams::{DataReader, DataWriter};
use super::error::check_communication_status;
use crate::error::ErrorKind;
use crate::util::defer;
use crate::{Characteristic, CharacteristicProperties, Descriptor, Error, Result, Uuid};
/// A Bluetooth GATT characteristic
#[derive(Clone)]
pub struct CharacteristicImpl {
inner: GattCharacteristic,
}
impl PartialEq for CharacteristicImpl {
fn eq(&self, other: &Self) -> bool {
self.inner.Service().unwrap().Session().unwrap() == other.inner.Service().unwrap().Session().unwrap()
&& self.inner.AttributeHandle().unwrap() == other.inner.AttributeHandle().unwrap()
}
}
impl Eq for CharacteristicImpl {}
impl std::hash::Hash for CharacteristicImpl {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.inner
.Service()
.unwrap()
.Session()
.unwrap()
.DeviceId()
.unwrap()
.Id()
.unwrap()
.to_os_string()
.hash(state);
self.inner.AttributeHandle().unwrap().hash(state);
}
}
impl std::fmt::Debug for CharacteristicImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Characteristic")
.field("uuid", &self.inner.Uuid().expect("UUID missing on GattCharacteristic"))
.field(
"handle",
&self
.inner
.AttributeHandle()
.expect("AttributeHandle missing on GattCharacteristic"),
)
.finish()
}
}
impl Characteristic {
pub(super) fn new(characteristic: GattCharacteristic) -> Self {
Characteristic(CharacteristicImpl { inner: characteristic })
}
}
impl CharacteristicImpl {
/// The [`Uuid`] identifying the type of this GATT characteristic
pub fn uuid(&self) -> Uuid {
Uuid::from_u128(self.inner.Uuid().expect("UUID missing on GattCharacteristic").to_u128())
}
/// The [`Uuid`] identifying the type of this GATT characteristic
pub async fn uuid_async(&self) -> Result<Uuid> {
Ok(Uuid::from_u128(self.inner.Uuid()?.to_u128()))
}
/// The properties of this this GATT characteristic.
///
/// Characteristic properties indicate which operations (e.g. read, write, notify, etc) may be performed on this
/// characteristic.
pub async fn properties(&self) -> Result<CharacteristicProperties> {
let props = self.inner.CharacteristicProperties()?;
Ok(CharacteristicProperties::from_bits(props.0))
}
/// The cached value of this characteristic
///
/// If the value has not yet been read, this method may either return an error or perform a read of the value.
pub async fn value(&self) -> Result<Vec<u8>> {
self.read_value(BluetoothCacheMode::Cached).await
}
/// Read the value of this characteristic from the device
pub async fn read(&self) -> Result<Vec<u8>> {
self.read_value(BluetoothCacheMode::Uncached).await
}
async fn read_value(&self, cachemode: BluetoothCacheMode) -> Result<Vec<u8>> {
let res = self.inner.ReadValueWithCacheModeAsync(cachemode)?.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "reading characteristic")?;
let buf = res.Value()?;
let mut data = vec![0; buf.Length()? as usize];
let reader = DataReader::FromBuffer(&buf)?;
reader.ReadBytes(data.as_mut_slice())?;
Ok(data)
}
/// Write the value of this descriptor on the device to `value`
pub async fn write(&self, value: &[u8]) -> Result<()> {
self.write_kind(value, GattWriteOption::WriteWithResponse).await
}
/// Write the value of this descriptor on the device to `value` without requesting a response.
pub async fn write_without_response(&self, value: &[u8]) -> Result<()> {
self.write_kind(value, GattWriteOption::WriteWithoutResponse).await
}
async fn write_kind(&self, value: &[u8], writeoption: GattWriteOption) -> Result<()> {
let op = {
let writer = DataWriter::new()?;
writer.WriteBytes(value)?;
let buf = writer.DetachBuffer()?;
self.inner.WriteValueWithResultAndOptionAsync(&buf, writeoption)?
};
let res = op.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "writing characteristic")
}
/// Get the maximum amount of data that can be written in a single packet for this characteristic.
pub fn max_write_len(&self) -> Result<usize> {
let mtu = self.inner.Service()?.Session()?.MaxPduSize()?;
// GATT characteristic writes have 3 bytes of overhead (opcode + handle id)
Ok(usize::from(mtu) - 3)
}
/// Get the maximum amount of data that can be written in a single packet for this characteristic.
pub async fn max_write_len_async(&self) -> Result<usize> {
self.max_write_len()
}
/// Enables notification of value changes for this GATT characteristic.
///
/// Returns a stream of values for the characteristic sent from the device.
pub async fn notify(&self) -> Result<impl Stream<Item = Result<Vec<u8>>> + Send + Unpin + '_> {
let props = self.properties().await?;
let value = if props.notify {
GattClientCharacteristicConfigurationDescriptorValue::Notify
} else if props.indicate {
GattClientCharacteristicConfigurationDescriptorValue::Indicate
} else {
return Err(Error::new(
ErrorKind::NotSupported,
None,
"characteristic does not support indications or notifications",
));
};
let (mut sender, receiver) = futures_channel::mpsc::channel(16);
let token = self.inner.ValueChanged(&TypedEventHandler::new(
move |_characteristic, event_args: &Option<GattValueChangedEventArgs>| {
let event_args = event_args
.as_ref()
.expect("GattValueChangedEventArgs was null in ValueChanged handler");
fn get_value(event_args: &GattValueChangedEventArgs) -> Result<Vec<u8>> {
let buf = event_args.CharacteristicValue()?;
let len = buf.Length()?;
let mut data: Vec<u8> = vec![0; len as usize];
let reader = DataReader::FromBuffer(&buf)?;
reader.ReadBytes(data.as_mut_slice())?;
Ok(data)
}
if let Err(err) = sender.try_send(get_value(event_args)) {
error!("Error sending characteristic value changed notification: {:?}", err);
}
Ok(())
},
))?;
let guard = defer(move || {
if let Err(err) = self.inner.RemoveValueChanged(token) {
warn!("Error removing value change event handler: {:?}", err);
}
});
let res = self
.inner
.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(value)?
.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "enabling notifications")?;
let guard = defer(move || {
let _guard = guard;
let res = self
.inner
.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(
GattClientCharacteristicConfigurationDescriptorValue::None,
)
.and_then(|op| {
op.SetCompleted(&AsyncOperationCompletedHandler::new(move |op, _status| {
fn check_status(res: windows::core::Result<GattWriteResult>) -> Result<()> {
let res = res?;
check_communication_status(
res.Status()?,
res.ProtocolError(),
"disabling characteristic notifications",
)
}
if let Err(err) = check_status(op.as_ref().unwrap().GetResults()) {
warn!("Error disabling characteristic notifications {:?}", err);
}
Ok(())
}))
});
if let Err(err) = res {
warn!("Error disabling characteristic notifications: {:?}", err);
}
});
Ok(receiver.map(move |x| {
let _guard = &guard;
x
}))
}
/// Is the device currently sending notifications for this characteristic?
pub async fn is_notifying(&self) -> Result<bool> {
let res = self
.inner
.ReadClientCharacteristicConfigurationDescriptorAsync()?
.await?;
check_communication_status(
res.Status()?,
res.ProtocolError(),
"reading client characteristic configuration descriptor",
)?;
const INDICATE: i32 = GattClientCharacteristicConfigurationDescriptorValue::Indicate.0;
const NOTIFY: i32 = GattClientCharacteristicConfigurationDescriptorValue::Notify.0;
let cccd = res.ClientCharacteristicConfigurationDescriptor()?;
Ok((cccd.0 & (INDICATE | NOTIFY)) != 0)
}
/// Discover the descriptors associated with this characteristic.
pub async fn discover_descriptors(&self) -> Result<Vec<Descriptor>> {
self.get_descriptors(BluetoothCacheMode::Uncached).await
}
/// Get previously discovered descriptors.
///
/// If no descriptors have been discovered yet, this method will perform descriptor discovery.
pub async fn descriptors(&self) -> Result<Vec<Descriptor>> {
self.get_descriptors(BluetoothCacheMode::Cached).await
}
async fn get_descriptors(&self, cachemode: BluetoothCacheMode) -> Result<Vec<Descriptor>> {
let res = self.inner.GetDescriptorsWithCacheModeAsync(cachemode)?.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "discovering descriptors")?;
let descriptors = res.Descriptors()?;
Ok(descriptors.into_iter().map(Descriptor::new).collect())
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/windows/winver.rs | src/windows/winver.rs | use std::mem;
use windows::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};
use windows::Win32::System::SystemInformation::OSVERSIONINFOW;
use windows::{s, w};
fn get_windows_version() -> Option<(u32, u32, u32)> {
let handle = unsafe { GetModuleHandleW(w!("ntdll.dll")).ok()? };
let proc = unsafe { GetProcAddress(handle, s!("RtlGetVersion"))? };
type RtlGetVersionFunc = unsafe extern "system" fn(*mut OSVERSIONINFOW) -> i32;
let proc: RtlGetVersionFunc = unsafe { mem::transmute(proc) };
let mut info: OSVERSIONINFOW = unsafe { mem::zeroed() };
info.dwOSVersionInfoSize = mem::size_of::<OSVERSIONINFOW>() as u32;
let status = unsafe { proc(&mut info) };
if status != 0 {
None
} else {
Some((info.dwMajorVersion, info.dwMinorVersion, info.dwBuildNumber))
}
}
pub fn windows_version_above(major: u32, minor: u32, build: u32) -> bool {
let Some((cur_major, cur_minor, cur_build)) = get_windows_version() else {
return false;
};
cur_major
.cmp(&major)
.then_with(|| cur_minor.cmp(&minor))
.then_with(|| cur_build.cmp(&build))
.is_ge()
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/windows/adapter.rs | src/windows/adapter.rs | use std::collections::{HashMap, HashSet};
use std::ffi::OsString;
use std::sync::Arc;
use futures_core::Stream;
use futures_lite::{stream, StreamExt};
use tracing::{debug, error, trace, warn};
use windows::core::HSTRING;
use windows::Devices::Bluetooth::Advertisement::{
BluetoothLEAdvertisement, BluetoothLEAdvertisementDataSection, BluetoothLEAdvertisementFilter,
BluetoothLEAdvertisementReceivedEventArgs, BluetoothLEAdvertisementType, BluetoothLEAdvertisementWatcher,
BluetoothLEAdvertisementWatcherStoppedEventArgs, BluetoothLEManufacturerData, BluetoothLEScanningMode,
};
use windows::Devices::Bluetooth::{BluetoothAdapter, BluetoothConnectionStatus, BluetoothLEDevice};
use windows::Devices::Enumeration::{DeviceInformation, DeviceInformationKind};
use windows::Devices::Radios::{Radio, RadioState};
use windows::Foundation::Collections::{IIterable, IVector};
use windows::Foundation::TypedEventHandler;
use windows::Storage::Streams::DataReader;
use super::types::StringVec;
use super::winver::windows_version_above;
use crate::error::{Error, ErrorKind};
use crate::util::defer;
use crate::{
AdapterEvent, AdvertisementData, AdvertisingDevice, BluetoothUuidExt, ConnectionEvent, Device, DeviceId,
ManufacturerData, Result, Uuid,
};
#[derive(Default)]
pub struct AdapterConfig {
/// Device ID to use.
pub device_id: Option<String>,
}
/// The system's Bluetooth adapter interface.
///
/// The default adapter for the system may be created with the [`Adapter::default()`] method.
#[derive(Clone)]
pub struct AdapterImpl {
inner: BluetoothAdapter,
}
impl PartialEq for AdapterImpl {
fn eq(&self, other: &Self) -> bool {
self.inner.DeviceId() == other.inner.DeviceId()
}
}
impl Eq for AdapterImpl {}
impl std::hash::Hash for AdapterImpl {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.inner.DeviceId().unwrap().to_os_string().hash(state);
}
}
impl std::fmt::Debug for AdapterImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Adapter").field(&self.inner.DeviceId().unwrap()).finish()
}
}
impl AdapterImpl {
/// Creates an interface to a Bluetooth adapter using the provided config.
pub async fn with_config(config: AdapterConfig) -> Result<Self> {
let adapter = if let Some(device_id) = config.device_id {
let device_id = HSTRING::from(&device_id);
BluetoothAdapter::FromIdAsync(&device_id)?.await?
} else {
BluetoothAdapter::GetDefaultAsync()?.await?
};
Ok(AdapterImpl { inner: adapter })
}
/// A stream of [`AdapterEvent`] which allows the application to identify when the adapter is enabled or disabled.
pub async fn events(&self) -> Result<impl Stream<Item = Result<AdapterEvent>> + Send + Unpin + '_> {
let (mut sender, receiver) = futures_channel::mpsc::channel(16);
let radio = self.inner.GetRadioAsync()?.await?;
let token = radio.StateChanged(&TypedEventHandler::new(move |radio: &Option<Radio>, _| {
let radio = radio.as_ref().expect("radio is null in StateChanged event");
let state = radio.State().expect("radio state getter failed in StateChanged event");
let res = sender.try_send(if state == RadioState::On {
Ok(AdapterEvent::Available)
} else {
Ok(AdapterEvent::Unavailable)
});
if let Err(err) = res {
error!("Unable to send AdapterEvent: {:?}", err);
}
Ok(())
}))?;
let guard = defer(move || {
if let Err(err) = radio.RemoveStateChanged(token) {
error!("Error removing state changed handler: {:?}", err);
}
});
Ok(receiver.map(move |x| {
let _guard = &guard;
x
}))
}
/// Asynchronously blocks until the adapter is available
pub async fn wait_available(&self) -> Result<()> {
let radio = self.inner.GetRadioAsync()?.await?;
let events = self.events().await?;
let state = radio.State()?;
if state != RadioState::On {
events
.skip_while(|x| x.is_ok() && !matches!(x, Ok(AdapterEvent::Available)))
.next()
.await
.ok_or_else(|| Error::new(ErrorKind::Internal, None, "adapter event stream closed unexpectedly"))??;
}
Ok(())
}
/// Check if the adapter is available
pub async fn is_available(&self) -> Result<bool> {
let radio = self.inner.GetRadioAsync()?.await?;
let state = radio.State()?;
Ok(state == RadioState::On)
}
/// Attempts to create the device identified by `id`
pub async fn open_device(&self, id: &DeviceId) -> Result<Device> {
Device::from_id(&id.0.as_os_str().into()).await.map_err(Into::into)
}
/// Finds all connected Bluetooth LE devices
pub async fn connected_devices(&self) -> Result<Vec<Device>> {
let aqsfilter = BluetoothLEDevice::GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus::Connected)?;
let op = DeviceInformation::FindAllAsyncWithKindAqsFilterAndAdditionalProperties(
&aqsfilter,
None,
DeviceInformationKind::AssociationEndpoint,
)?;
let devices = op.await?;
let device_ids: Vec<HSTRING> = devices
.into_iter()
.map(|x| x.Id())
.collect::<windows::core::Result<_>>()?;
let mut res = Vec::with_capacity(device_ids.len());
for id in device_ids {
res.push(Device::from_id(&id).await?);
}
Ok(res)
}
/// Finds all connected devices providing any service in `services`
///
/// # Panics
///
/// Panics if `services` is empty.
pub async fn connected_devices_with_services(&self, services: &[Uuid]) -> Result<Vec<Device>> {
assert!(!services.is_empty());
// Find all connected devices
let aqsfilter = BluetoothLEDevice::GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus::Connected)?;
debug!("aqs filter = {:?}", aqsfilter);
let op = DeviceInformation::FindAllAsyncWithKindAqsFilterAndAdditionalProperties(
&aqsfilter,
None,
DeviceInformationKind::AssociationEndpoint,
)?;
let devices = op.await?;
trace!("found {} connected devices", devices.Size()?);
if devices.Size()? == 0 {
return Ok(Vec::new());
}
// Build an AQS filter for services of any of the connected devices
let mut devicefilter = OsString::new();
for device in devices {
if !devicefilter.is_empty() {
devicefilter.push(" OR ");
}
devicefilter.push("System.Devices.AepService.AepId:=\"");
devicefilter.push(device.Id()?.to_os_string());
devicefilter.push("\"");
}
debug!("device filter = {:?}", devicefilter);
// Build an AQS filter for any of the service Uuids
let mut servicefilter = String::new();
for service in services {
if !servicefilter.is_empty() {
servicefilter.push_str(" OR ");
}
servicefilter.push_str("System.Devices.AepService.Bluetooth.ServiceGuid:=\"{");
servicefilter.push_str(&service.to_string());
servicefilter.push_str("}\"");
}
debug!("service filter = {:?}", servicefilter);
// Combine the device and service filters
let mut aqsfilter =
OsString::from("System.Devices.AepService.ProtocolId:=\"{BB7BB05E-5972-42B5-94FC-76EAA7084D49}\" AND (");
aqsfilter.push(devicefilter);
aqsfilter.push(") AND (");
aqsfilter.push(servicefilter);
aqsfilter.push(")");
let aqsfilter: HSTRING = aqsfilter.into();
debug!("aqs filter = {:?}", aqsfilter);
// Find all associated endpoint services matching the filter
let aep_id = HSTRING::from("System.Devices.AepService.AepId");
let additional_properties = StringVec::new(vec![aep_id.clone()]);
let op = DeviceInformation::FindAllAsyncWithKindAqsFilterAndAdditionalProperties(
&aqsfilter,
&IIterable::from(additional_properties),
DeviceInformationKind::AssociationEndpointService,
)?;
let services = op.await?;
trace!("found {} matching services of connected devices", services.Size()?);
// Find the unique set of device ids which matched
let mut device_ids = HashSet::with_capacity(services.Size()? as usize);
for service in services {
let id = service.Properties()?.Lookup(&aep_id)?;
let id: HSTRING = id.try_into()?;
device_ids.insert(id.to_os_string());
}
trace!("found {} devices with at least one matching service", device_ids.len());
// Build the devices
let mut res = Vec::with_capacity(device_ids.len());
for id in device_ids {
res.push(Device::from_id(&id.into()).await?);
}
Ok(res)
}
/// Starts scanning for Bluetooth advertising packets.
///
/// Returns a stream of [`AdvertisingDevice`] structs which contain the data from the advertising packet and the
/// [`Device`] which sent it. Scanning is automatically stopped when the stream is dropped. Inclusion of duplicate
/// packets is a platform-specific implementation detail.
///
/// If `services` is not empty, returns advertisements including at least one GATT service with a UUID in
/// `services`. Otherwise returns all advertisements.
pub async fn scan<'a>(
&'a self,
services: &'a [Uuid],
) -> Result<impl Stream<Item = AdvertisingDevice> + Send + Unpin + 'a> {
let ext_api_available = windows_version_above(10, 0, 19041);
let (sender, receiver) = futures_channel::mpsc::channel(16);
let sender = Arc::new(std::sync::Mutex::new(sender));
let weak_sender = Arc::downgrade(&sender);
let received_handler = TypedEventHandler::new(
move |watcher: &Option<BluetoothLEAdvertisementWatcher>,
event_args: &Option<BluetoothLEAdvertisementReceivedEventArgs>| {
if let Some(sender) = weak_sender.upgrade() {
if let Some(event_args) = event_args {
let res = sender.lock().unwrap().try_send(event_args.clone());
if let Err(err) = res {
error!("Unable to send AdvertisingDevice: {:?}", err);
}
}
} else if let Some(watcher) = watcher {
let res = watcher.Stop();
if let Err(err) = res {
warn!("Failed to stop BluetoothLEAdvertisementWatcher: {:?}", err);
}
}
Ok(())
},
);
let mut sender = Some(sender);
let stopped_handler = TypedEventHandler::new(
move |_watcher, _event_args: &Option<BluetoothLEAdvertisementWatcherStoppedEventArgs>| {
// Drop the sender, ending the stream
let _sender = sender.take();
Ok(())
},
);
let build_watcher = |uuid: Option<Uuid>| {
let watcher = BluetoothLEAdvertisementWatcher::new()?;
watcher.SetScanningMode(BluetoothLEScanningMode::Active)?;
if ext_api_available {
watcher.SetAllowExtendedAdvertisements(true)?;
}
watcher.Received(&received_handler)?;
watcher.Stopped(&stopped_handler)?;
if let Some(uuid) = uuid {
let advertisement = BluetoothLEAdvertisement::new()?;
let service_uuids = advertisement.ServiceUuids()?;
service_uuids.Append(windows::core::GUID::from_u128(uuid.as_u128()))?;
let advertisement_filter = BluetoothLEAdvertisementFilter::new()?;
advertisement_filter.SetAdvertisement(&advertisement)?;
watcher.SetAdvertisementFilter(&advertisement_filter)?;
}
Ok::<_, windows::core::Error>(watcher)
};
let watchers = if services.is_empty() {
vec![build_watcher(None)?]
} else {
services
.iter()
.map(|uuid| build_watcher(Some(*uuid)))
.collect::<Result<_, _>>()?
};
for watcher in &watchers {
watcher.Start()?;
}
let guard = defer(move || {
for watcher in watchers {
if let Err(err) = watcher.Stop() {
error!("Error stopping scan: {:?}", err);
}
}
});
Ok(receiver
.then(move |event_args| {
let _guard = &guard;
Box::pin(async move {
if event_args.AdvertisementType().ok()? == BluetoothLEAdvertisementType::NonConnectableUndirected {
// Device cannot be created from a non-connectable advertisement
return None;
}
let addr = event_args.BluetoothAddress().ok()?;
let kind = ext_api_available
.then(|| event_args.BluetoothAddressType().ok())
.flatten();
let rssi = event_args.RawSignalStrengthInDBm().ok();
let adv_data = AdvertisementData::from(event_args);
match Device::from_addr(addr, kind).await {
Ok(device) => Some(AdvertisingDevice { device, rssi, adv_data }),
Err(err) => {
if err.code().is_err() {
warn!("Error creating device: {:?}", err);
} else {
warn!("Device::from_addr returned null");
}
None
}
}
})
})
.filter_map(|x| x))
}
/// Finds Bluetooth devices providing any service in `services`.
///
/// Returns a stream of [`Device`] structs with matching connected devices returned first. If the stream is not
/// dropped before all matching connected devices are consumed then scanning will begin for devices advertising any
/// of the `services`. Scanning will continue until the stream is dropped. Inclusion of duplicate devices is a
/// platform-specific implementation detail.
pub async fn discover_devices<'a>(
&'a self,
services: &'a [Uuid],
) -> Result<impl Stream<Item = Result<Device>> + Send + Unpin + 'a> {
let connected = stream::iter(self.connected_devices_with_services(services).await?).map(Ok);
// try_unfold is used to ensure we do not start scanning until the connected devices have been consumed
let advertising = Box::pin(stream::try_unfold(None, |state| async {
let mut stream = match state {
Some(stream) => stream,
None => self.scan(services).await?,
};
Ok(stream.next().await.map(|x| (x.device, Some(stream))))
}));
Ok(connected.chain(advertising))
}
/// Connects to the [`Device`]
///
/// Device connections are automatically managed by the OS. This method has no effect. Instead, a connection will
/// automatically be established, if necessary, when methods on the device requiring a connection are called.
pub async fn connect_device(&self, _device: &Device) -> Result<()> {
// Windows manages the device connection automatically
Ok(())
}
/// Disconnects from the [`Device`]
///
/// Device connections are automatically managed by the OS. This method has no effect. Instead, the connection will
/// be closed only when the [`Device`] and all its child objects are dropped.
pub async fn disconnect_device(&self, _device: &Device) -> Result<()> {
// Windows manages the device connection automatically
Ok(())
}
/// Monitors a device for connection/disconnection events.
pub async fn device_connection_events<'a>(
&'a self,
device: &'a Device,
) -> Result<impl Stream<Item = ConnectionEvent> + Send + Unpin + 'a> {
let (mut sender, receiver) = futures_channel::mpsc::channel::<BluetoothConnectionStatus>(16);
let token = {
let handler = TypedEventHandler::new(move |device: &Option<BluetoothLEDevice>, _| {
if let Some(device) = device {
if let Ok(status) = device.ConnectionStatus() {
let res = sender.try_send(status);
if let Err(err) = res {
error!("Unable to send BluetoothConnectionStatus: {:?}", err);
}
}
}
Ok(())
});
device.0.inner.ConnectionStatusChanged(&handler)?
};
let guard = defer(move || {
let _ = device.0.inner.RemoveConnectionStatusChanged(token);
});
Ok(receiver.map(move |x| {
let _guard = &guard;
ConnectionEvent::from(x)
}))
}
}
impl From<BluetoothConnectionStatus> for ConnectionEvent {
fn from(value: BluetoothConnectionStatus) -> Self {
match value {
BluetoothConnectionStatus::Disconnected => ConnectionEvent::Disconnected,
_ => ConnectionEvent::Connected,
}
}
}
impl TryFrom<BluetoothLEManufacturerData> for ManufacturerData {
type Error = windows::core::Error;
fn try_from(val: BluetoothLEManufacturerData) -> Result<Self, Self::Error> {
let company_id = val.CompanyId()?;
let buf = val.Data()?;
let mut data = vec![0; buf.Length()? as usize];
let reader = DataReader::FromBuffer(&buf)?;
reader.ReadBytes(data.as_mut_slice())?;
Ok(ManufacturerData { company_id, data })
}
}
impl From<BluetoothLEAdvertisementReceivedEventArgs> for AdvertisementData {
fn from(event_args: BluetoothLEAdvertisementReceivedEventArgs) -> Self {
let is_connectable = event_args.IsConnectable().unwrap_or(false);
let tx_power_level = event_args.TransmitPowerLevelInDBm().ok().and_then(|x| x.Value().ok());
let (local_name, manufacturer_data, services, service_data) = if let Ok(adv) = event_args.Advertisement() {
let local_name = adv
.LocalName()
.ok()
.and_then(|x| (!x.is_empty()).then(|| x.to_string_lossy()));
let manufacturer_data = adv
.ManufacturerData()
.and_then(|x| x.GetAt(0))
.and_then(|x| x.try_into())
.ok();
let services = adv
.ServiceUuids()
.map(|x| x.into_iter().map(|x| Uuid::from_u128(x.to_u128())).collect())
.unwrap_or_default();
let service_data = if let Ok(data_sections) = adv.DataSections() {
to_service_data(&data_sections).unwrap_or_default()
} else {
Default::default()
};
(local_name, manufacturer_data, services, service_data)
} else {
(None, None, Vec::new(), HashMap::new())
};
AdvertisementData {
local_name,
manufacturer_data,
services,
tx_power_level,
is_connectable,
service_data,
}
}
}
#[derive(Debug, Clone, Copy)]
enum UuidKind {
U16,
U32,
U128,
}
fn read_uuid(reader: &DataReader, kind: UuidKind) -> windows::core::Result<Uuid> {
Ok(match kind {
UuidKind::U16 => Uuid::from_u16(reader.ReadUInt16()?),
UuidKind::U32 => Uuid::from_u32(reader.ReadUInt32()?),
UuidKind::U128 => {
let mut uuid = [0u8; 16];
reader.ReadBytes(&mut uuid)?;
Uuid::from_bytes(uuid)
}
})
}
fn to_service_data(
data_sections: &IVector<BluetoothLEAdvertisementDataSection>,
) -> windows::core::Result<HashMap<Uuid, Vec<u8>>> {
let mut service_data = HashMap::new();
for data in data_sections {
let kind = match data.DataType()? {
0x16 => Some(UuidKind::U16),
0x20 => Some(UuidKind::U32),
0x21 => Some(UuidKind::U128),
_ => None,
};
if let Some(kind) = kind {
let buf = data.Data()?;
let reader = DataReader::FromBuffer(&buf)?;
if let Ok(uuid) = read_uuid(&reader, kind) {
let len = reader.UnconsumedBufferLength()? as usize;
let mut value = vec![0; len];
reader.ReadBytes(value.as_mut_slice())?;
service_data.insert(uuid, value);
}
}
}
Ok(service_data)
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/windows/error.rs | src/windows/error.rs | use windows::Devices::Bluetooth::GenericAttributeProfile::GattCommunicationStatus;
use windows::Devices::Enumeration::{DevicePairingResultStatus, DeviceUnpairingResultStatus};
use windows::Foundation::IReference;
use crate::error::ErrorKind;
use crate::Result;
impl From<windows::core::Error> for crate::Error {
fn from(err: windows::core::Error) -> Self {
crate::Error::new(ErrorKind::Other, Some(Box::new(err)), String::new())
}
}
struct CommunicationError(GattCommunicationStatus);
impl std::fmt::Debug for CommunicationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "CommunicationError({self})")
}
}
impl std::fmt::Display for CommunicationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let str = match self.0 {
GattCommunicationStatus::Success => "success",
GattCommunicationStatus::AccessDenied => "access denied",
GattCommunicationStatus::Unreachable => "unreachable",
GattCommunicationStatus::ProtocolError => "protocol error",
_ => return write!(f, "unknown ({})", self.0 .0),
};
f.write_str(str)
}
}
impl std::error::Error for CommunicationError {}
fn kind_from_communication_status(
status: GattCommunicationStatus,
protocol_error: windows::core::Result<IReference<u8>>,
) -> Result<ErrorKind> {
match status {
GattCommunicationStatus::Success => {
unreachable!("kind_from_communication_status must not be called with GattCommunicationStatus::Success")
}
GattCommunicationStatus::AccessDenied => Ok(ErrorKind::NotAuthorized),
GattCommunicationStatus::Unreachable => Ok(ErrorKind::NotConnected),
GattCommunicationStatus::ProtocolError => Ok(ErrorKind::Protocol(protocol_error?.Value()?.into())),
_ => Ok(ErrorKind::Other),
}
}
pub(super) fn check_communication_status(
status: GattCommunicationStatus,
protocol_error: windows::core::Result<IReference<u8>>,
message: &str,
) -> Result<()> {
use crate::Error;
match status {
GattCommunicationStatus::Success => Ok(()),
_ => Err(Error::new(
kind_from_communication_status(status, protocol_error)?,
Some(Box::new(CommunicationError(status))),
message,
)),
}
}
struct PairingError(DevicePairingResultStatus);
impl std::fmt::Debug for PairingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "PairingError({self})")
}
}
impl std::fmt::Display for PairingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let str = match self.0 {
DevicePairingResultStatus::Paired => "paired",
DevicePairingResultStatus::AlreadyPaired => "already paired",
DevicePairingResultStatus::NotReadyToPair => "not ready to pair",
DevicePairingResultStatus::NotPaired => "not paired",
DevicePairingResultStatus::ConnectionRejected => "connection rejected",
DevicePairingResultStatus::TooManyConnections => "too many connections",
DevicePairingResultStatus::HardwareFailure => "hardware failure",
DevicePairingResultStatus::AuthenticationTimeout => "authentication timeout",
DevicePairingResultStatus::AuthenticationNotAllowed => "authentication not allowed",
DevicePairingResultStatus::AuthenticationFailure => "authentication failure",
DevicePairingResultStatus::NoSupportedProfiles => "no supported profiles",
DevicePairingResultStatus::ProtectionLevelCouldNotBeMet => "protection level could not be met",
DevicePairingResultStatus::AccessDenied => "access denied",
DevicePairingResultStatus::InvalidCeremonyData => "invalid ceremony data",
DevicePairingResultStatus::PairingCanceled => "pairing canceled",
DevicePairingResultStatus::OperationAlreadyInProgress => "operation already in progress",
DevicePairingResultStatus::RequiredHandlerNotRegistered => "required handler not registered",
DevicePairingResultStatus::RejectedByHandler => "rejected by handler",
DevicePairingResultStatus::RemoteDeviceHasAssociation => "remote device has association",
DevicePairingResultStatus::Failed => "failed",
_ => return write!(f, "unknown ({})", self.0 .0),
};
f.write_str(str)
}
}
fn kind_from_pairing_status(status: DevicePairingResultStatus) -> ErrorKind {
match status {
DevicePairingResultStatus::NotReadyToPair => ErrorKind::NotReady,
DevicePairingResultStatus::AuthenticationTimeout => ErrorKind::Timeout,
DevicePairingResultStatus::AuthenticationNotAllowed | DevicePairingResultStatus::AccessDenied => {
ErrorKind::NotAuthorized
}
DevicePairingResultStatus::ConnectionRejected | DevicePairingResultStatus::TooManyConnections => {
ErrorKind::ConnectionFailed
}
DevicePairingResultStatus::NotPaired
| DevicePairingResultStatus::HardwareFailure
| DevicePairingResultStatus::AuthenticationFailure
| DevicePairingResultStatus::NoSupportedProfiles
| DevicePairingResultStatus::ProtectionLevelCouldNotBeMet
| DevicePairingResultStatus::InvalidCeremonyData
| DevicePairingResultStatus::PairingCanceled
| DevicePairingResultStatus::OperationAlreadyInProgress
| DevicePairingResultStatus::RequiredHandlerNotRegistered
| DevicePairingResultStatus::RejectedByHandler
| DevicePairingResultStatus::RemoteDeviceHasAssociation
| DevicePairingResultStatus::Failed => ErrorKind::Other,
_ => ErrorKind::Other,
}
}
impl std::error::Error for PairingError {}
pub(super) fn check_pairing_status(status: DevicePairingResultStatus) -> Result<()> {
match status {
DevicePairingResultStatus::Paired | DevicePairingResultStatus::AlreadyPaired => Ok(()),
_ => Err(crate::Error::new(
kind_from_pairing_status(status),
Some(Box::new(PairingError(status))),
String::new(),
)),
}
}
struct UnpairingError(DeviceUnpairingResultStatus);
impl std::fmt::Debug for UnpairingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "UnpairingError({self})")
}
}
impl std::fmt::Display for UnpairingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let str = match self.0 {
DeviceUnpairingResultStatus::Unpaired => "unpaired",
DeviceUnpairingResultStatus::AlreadyUnpaired => "already unpaired",
DeviceUnpairingResultStatus::OperationAlreadyInProgress => "operation already in progress",
DeviceUnpairingResultStatus::AccessDenied => "access denied",
DeviceUnpairingResultStatus::Failed => "failed",
_ => return write!(f, "unknown ({})", self.0 .0),
};
f.write_str(str)
}
}
fn kind_from_unpairing_status(status: DeviceUnpairingResultStatus) -> ErrorKind {
match status {
DeviceUnpairingResultStatus::AccessDenied => ErrorKind::NotAuthorized,
DeviceUnpairingResultStatus::OperationAlreadyInProgress | DeviceUnpairingResultStatus::Failed => {
ErrorKind::Other
}
_ => ErrorKind::Other,
}
}
impl std::error::Error for UnpairingError {}
pub(super) fn check_unpairing_status(status: DeviceUnpairingResultStatus) -> Result<()> {
match status {
DeviceUnpairingResultStatus::Unpaired | DeviceUnpairingResultStatus::AlreadyUnpaired => Ok(()),
_ => Err(crate::Error::new(
kind_from_unpairing_status(status),
Some(Box::new(UnpairingError(status))),
String::new(),
)),
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/windows/service.rs | src/windows/service.rs | use windows::core::GUID;
use windows::Devices::Bluetooth::BluetoothCacheMode;
use windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService;
use super::error::check_communication_status;
use crate::error::ErrorKind;
use crate::{Characteristic, Result, Service, Uuid};
/// A Bluetooth GATT service
#[derive(Clone)]
pub struct ServiceImpl {
inner: GattDeviceService,
}
impl PartialEq for ServiceImpl {
fn eq(&self, other: &Self) -> bool {
self.inner.Session().unwrap() == other.inner.Session().unwrap()
&& self.inner.AttributeHandle().unwrap() == other.inner.AttributeHandle().unwrap()
}
}
impl Eq for ServiceImpl {}
impl std::hash::Hash for ServiceImpl {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.inner
.Session()
.unwrap()
.DeviceId()
.unwrap()
.Id()
.unwrap()
.to_os_string()
.hash(state);
self.inner.AttributeHandle().unwrap().hash(state);
}
}
impl std::fmt::Debug for ServiceImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Service")
.field(
"device_id",
&self
.inner
.Session()
.expect("Session missing on GattDeviceService")
.DeviceId()
.expect("DeviceId missing on GattSession")
.Id()
.expect("Id missing on BluetoothDeviceId")
.to_os_string(),
)
.field("uuid", &self.inner.Uuid().expect("UUID missing on GattDeviceService"))
.field(
"handle",
&self
.inner
.AttributeHandle()
.expect("AttributeHandle missing on GattDeviceService"),
)
.finish()
}
}
impl Service {
pub(super) fn new(service: GattDeviceService) -> Self {
Service(ServiceImpl { inner: service })
}
}
impl ServiceImpl {
/// The [`Uuid`] identifying the type of service
pub fn uuid(&self) -> Uuid {
Uuid::from_u128(self.inner.Uuid().expect("UUID missing on GattDeviceService").to_u128())
}
/// The [`Uuid`] identifying the type of this GATT service
pub async fn uuid_async(&self) -> Result<Uuid> {
Ok(Uuid::from_u128(self.inner.Uuid()?.to_u128()))
}
/// Whether this is a primary service of the device.
///
/// Returns [ErrorKind::NotSupported].
pub async fn is_primary(&self) -> Result<bool> {
Err(ErrorKind::NotSupported.into())
}
/// Discover all characteristics associated with this service.
pub async fn discover_characteristics(&self) -> Result<Vec<Characteristic>> {
let res = self
.inner
.GetCharacteristicsWithCacheModeAsync(BluetoothCacheMode::Uncached)?
.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "discovering characteristics")?;
let characteristics = res.Characteristics()?;
Ok(characteristics.into_iter().map(Characteristic::new).collect())
}
/// Discover the characteristic(s) with the given [`Uuid`].
pub async fn discover_characteristics_with_uuid(&self, uuid: Uuid) -> Result<Vec<Characteristic>> {
let res = self
.inner
.GetCharacteristicsForUuidWithCacheModeAsync(GUID::from_u128(uuid.as_u128()), BluetoothCacheMode::Uncached)?
.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "discovering characteristics")?;
let characteristics = res.Characteristics()?;
Ok(characteristics.into_iter().map(Characteristic::new).collect())
}
/// Get previously discovered characteristics.
///
/// If no characteristics have been discovered yet, this method will perform characteristic discovery.
pub async fn characteristics(&self) -> Result<Vec<Characteristic>> {
let res = self
.inner
.GetCharacteristicsWithCacheModeAsync(BluetoothCacheMode::Cached)?
.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "discovering characteristics")?;
let characteristics = res.Characteristics()?;
Ok(characteristics.into_iter().map(Characteristic::new).collect())
}
/// Discover the included services of this service.
pub async fn discover_included_services(&self) -> Result<Vec<Service>> {
let res = self
.inner
.GetIncludedServicesWithCacheModeAsync(BluetoothCacheMode::Uncached)?
.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "discovering included services")?;
let services = res.Services()?;
Ok(services.into_iter().map(Service::new).collect())
}
/// Discover the included service(s) with the given [`Uuid`].
pub async fn discover_included_services_with_uuid(&self, uuid: Uuid) -> Result<Vec<Service>> {
let res = self
.inner
.GetIncludedServicesForUuidWithCacheModeAsync(
GUID::from_u128(uuid.as_u128()),
BluetoothCacheMode::Uncached,
)?
.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "discovering included services")?;
let services = res.Services()?;
Ok(services.into_iter().map(Service::new).collect())
}
/// Get previously discovered included services.
///
/// If no included services have been discovered yet, this method will perform included service discovery.
pub async fn included_services(&self) -> Result<Vec<Service>> {
let res = self
.inner
.GetIncludedServicesWithCacheModeAsync(BluetoothCacheMode::Cached)?
.await?;
check_communication_status(res.Status()?, res.ProtocolError(), "discovering included services")?;
let services = res.Services()?;
Ok(services.into_iter().map(Service::new).collect())
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/windows/types.rs | src/windows/types.rs | use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use windows::core::HSTRING;
use windows::Foundation::Collections::{IIterable, IIterable_Impl, IIterator, IIterator_Impl};
#[windows::core::implement(IIterable<HSTRING>)]
pub(super) struct StringVec(Arc<Vec<HSTRING>>);
#[windows::core::implement(IIterator<HSTRING>)]
pub(super) struct StringIterator {
vec: Arc<Vec<HSTRING>>,
pos: AtomicUsize,
}
impl StringVec {
pub fn new(strings: Vec<HSTRING>) -> Self {
Self(Arc::new(strings))
}
}
impl IIterable_Impl<HSTRING> for StringVec {
fn First(&self) -> windows::core::Result<windows::Foundation::Collections::IIterator<HSTRING>> {
Ok(StringIterator {
vec: self.0.clone(),
pos: AtomicUsize::new(0),
}
.into())
}
}
impl IIterator_Impl<HSTRING> for StringIterator {
fn Current(&self) -> windows::core::Result<HSTRING> {
let pos = self.pos.load(Ordering::Relaxed);
if pos < self.vec.len() {
Ok(self.vec[pos].clone())
} else {
Err(windows::core::Error::OK)
}
}
fn HasCurrent(&self) -> windows::core::Result<bool> {
let pos = self.pos.load(Ordering::Relaxed);
Ok(pos < self.vec.len())
}
fn MoveNext(&self) -> windows::core::Result<bool> {
let pos = self.pos.fetch_add(1, Ordering::Relaxed);
Ok(pos + 1 < self.vec.len())
}
fn GetMany(&self, items: &mut [<HSTRING as windows::core::Type<HSTRING>>::Default]) -> windows::core::Result<u32> {
let pos = self.pos.fetch_add(items.len(), Ordering::Relaxed);
if pos < self.vec.len() {
let len = (self.vec.len() - pos).min(items.len());
items[0..len].clone_from_slice(&self.vec[pos..][..len]);
Ok(len as u32)
} else {
Ok(0)
}
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/android/descriptor.rs | src/android/descriptor.rs | use crate::{Result, Uuid};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DescriptorImpl {}
impl DescriptorImpl {
pub fn uuid(&self) -> Uuid {
todo!()
}
pub async fn uuid_async(&self) -> Result<Uuid> {
todo!()
}
pub async fn value(&self) -> Result<Vec<u8>> {
todo!()
}
pub async fn read(&self) -> Result<Vec<u8>> {
todo!()
}
pub async fn write(&self, _value: &[u8]) -> Result<()> {
todo!()
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/android/bindings.rs | src/android/bindings.rs | // WARNING: This file was autogenerated by java-spaghetti. Any changes to this file may be lost!!!
#![allow(unused_imports)]
#![allow(non_camel_case_types)] // We map Java inner classes to Outer_Inner
#![allow(dead_code)] // We generate structs for private Java types too, just in case.
#![allow(deprecated)] // We're generating deprecated types/methods
#![allow(non_upper_case_globals)] // We might be generating Java style fields/methods
#![allow(non_snake_case)] // We might be generating Java style fields/methods
#![allow(clippy::all)] // we don't ensure generated bindings are clippy-compliant at all.
#![allow(unsafe_code)] // play nice if user has `deny(unsafe_code)` in their crate.
mod util {
use std::char::DecodeUtf16Error;
use std::fmt;
use java_spaghetti::sys::jsize;
use java_spaghetti::{Env, Local, StringChars, ThrowableType};
use super::java::lang::{String as JString, Throwable};
impl fmt::Debug for Throwable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "java::lang::Throwable")?;
match self.getMessage() {
Ok(Some(message)) => writeln!(f, " getMessage: {:?}", message)?,
Ok(None) => writeln!(f, " getMessage: N/A (returned null)")?,
Err(_) => writeln!(f, " getMessage: N/A (threw an exception!)")?,
}
match self.getLocalizedMessage() {
Ok(Some(message)) => writeln!(f, " getLocalizedMessage: {:?}", message)?,
Ok(None) => writeln!(f, " getLocalizedMessage: N/A (returned null)")?,
Err(_) => writeln!(f, " getLocalizedMessage: N/A (threw an exception!)")?,
}
match self.getStackTrace() {
Err(_) => writeln!(f, " getStackTrace: N/A (threw an exception!)")?,
Ok(None) => writeln!(f, " getStackTrace: N/A (returned null)")?,
Ok(Some(stack_trace)) => {
writeln!(f, " getStackTrace:")?;
for frame in stack_trace.iter() {
match frame {
None => writeln!(f, " N/A (frame was null)")?,
Some(frame) => {
let file_line = match (frame.getFileName(), frame.getLineNumber()) {
(Ok(Some(file)), Ok(line)) => {
format!("{}({}):", file.to_string_lossy(), line)
}
(Ok(Some(file)), _) => format!("{}:", file.to_string_lossy()),
(_, _) => "N/A (getFileName threw an exception or returned null)".to_owned(),
};
let class_method = match (frame.getClassName(), frame.getMethodName()) {
(Ok(Some(class)), Ok(Some(method))) => {
format!("{}.{}", class.to_string_lossy(), method.to_string_lossy())
}
(Ok(Some(class)), _) => class.to_string_lossy(),
(_, Ok(Some(method))) => method.to_string_lossy(),
(_, _) => "N/A (getClassName + getMethodName threw exceptions or returned null)"
.to_owned(),
};
writeln!(f, " {:120}{}", file_line, class_method)?;
}
}
}
}
}
// Consider also dumping:
// API level 1+:
// getCause()
// API level 19+:
// getSuppressed()
Ok(())
}
}
impl JString {
/// Create new local string from an Env + AsRef<str>
pub fn from_env_str<'env, S: AsRef<str>>(env: Env<'env>, string: S) -> Local<'env, Self> {
let chars = string.as_ref().encode_utf16().collect::<Vec<_>>();
let string = unsafe { env.new_string(chars.as_ptr(), chars.len() as jsize) };
unsafe { Local::from_raw(env, string) }
}
fn string_chars(&self) -> StringChars {
unsafe {
let env = Env::from_raw(self.0.env);
StringChars::from_env_jstring(env, self.0.object)
}
}
/// Returns a new [Ok]\([String]\), or an [Err]\([DecodeUtf16Error]\) if if it contained any invalid UTF16.
///
/// [Ok]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Ok
/// [Err]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
/// [DecodeUtf16Error]: https://doc.rust-lang.org/std/char/struct.DecodeUtf16Error.html
/// [String]: https://doc.rust-lang.org/std/string/struct.String.html
/// [REPLACEMENT_CHARACTER]: https://doc.rust-lang.org/std/char/constant.REPLACEMENT_CHARACTER.html
pub fn to_string(&self) -> Result<String, DecodeUtf16Error> {
self.string_chars().to_string()
}
/// Returns a new [String] with any invalid UTF16 characters replaced with [REPLACEMENT_CHARACTER]s (`'\u{FFFD}'`.)
///
/// [String]: https://doc.rust-lang.org/std/string/struct.String.html
/// [REPLACEMENT_CHARACTER]: https://doc.rust-lang.org/std/char/constant.REPLACEMENT_CHARACTER.html
pub fn to_string_lossy(&self) -> String {
self.string_chars().to_string_lossy()
}
}
// OsString doesn't implement Display, so neither does java::lang::String.
impl fmt::Debug for JString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.to_string_lossy(), f) // XXX: Unneccessary alloc? Shouldn't use lossy here?
}
}
impl ThrowableType for Throwable {}
}
pub mod android {
pub mod bluetooth {
pub mod le {
/// pub class [AdvertiseCallback](https://developer.android.com/reference/android/bluetooth/le/AdvertiseCallback.html)
#[repr(transparent)]
pub struct AdvertiseCallback(pub(crate) ::java_spaghetti::ObjectAndEnv);
unsafe impl ::java_spaghetti::ReferenceType for AdvertiseCallback {}
unsafe impl ::java_spaghetti::JniType for AdvertiseCallback {
fn static_with_jni_type<R>(callback: impl FnOnce(&str) -> R) -> R {
callback("android/bluetooth/le/AdvertiseCallback\0")
}
}
unsafe impl ::java_spaghetti::AssignableTo<super::super::super::java::lang::Object> for AdvertiseCallback {}
impl ::std::ops::Deref for AdvertiseCallback {
type Target = super::super::super::java::lang::Object;
fn deref(&self) -> &Self::Target {
unsafe { &*(self as *const Self as *const Self::Target) }
}
}
impl AdvertiseCallback {
/// [AdvertiseCallback](https://developer.android.com/reference/android/bluetooth/le/AdvertiseCallback.html#AdvertiseCallback())
pub fn new<'env>(
__jni_env: ::java_spaghetti::Env<'env>,
) -> ::std::result::Result<
::java_spaghetti::Local<'env, Self>,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
// class.path == "android/bluetooth/le/AdvertiseCallback", java.flags == PUBLIC, .name == "<init>", .descriptor == "()V"
unsafe {
let __jni_args = [];
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseCallback\0",
"<init>\0",
"()V\0",
);
__jni_env.new_object_a(__jni_class, __jni_method, __jni_args.as_ptr())
}
}
/// [onStartSuccess](https://developer.android.com/reference/android/bluetooth/le/AdvertiseCallback.html#onStartSuccess(android.bluetooth.le.AdvertiseSettings))
pub fn onStartSuccess<'env>(
&'env self,
arg0: impl ::java_spaghetti::AsArg<AdvertiseSettings>,
) -> ::std::result::Result<(), ::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>>
{
// class.path == "android/bluetooth/le/AdvertiseCallback", java.flags == PUBLIC, .name == "onStartSuccess", .descriptor == "(Landroid/bluetooth/le/AdvertiseSettings;)V"
unsafe {
let __jni_args = [arg0.as_arg_jvalue()];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseCallback\0",
"onStartSuccess\0",
"(Landroid/bluetooth/le/AdvertiseSettings;)V\0",
);
__jni_env.call_void_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [onStartFailure](https://developer.android.com/reference/android/bluetooth/le/AdvertiseCallback.html#onStartFailure(int))
pub fn onStartFailure<'env>(
&'env self,
arg0: i32,
) -> ::std::result::Result<(), ::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>>
{
// class.path == "android/bluetooth/le/AdvertiseCallback", java.flags == PUBLIC, .name == "onStartFailure", .descriptor == "(I)V"
unsafe {
let __jni_args = [::java_spaghetti::AsJValue::as_jvalue(&arg0)];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseCallback\0",
"onStartFailure\0",
"(I)V\0",
);
__jni_env.call_void_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// public static final [ADVERTISE_FAILED_ALREADY_STARTED](https://developer.android.com/reference/android/bluetooth/le/AdvertiseCallback.html#ADVERTISE_FAILED_ALREADY_STARTED)
pub const ADVERTISE_FAILED_ALREADY_STARTED: i32 = 3;
/// public static final [ADVERTISE_FAILED_DATA_TOO_LARGE](https://developer.android.com/reference/android/bluetooth/le/AdvertiseCallback.html#ADVERTISE_FAILED_DATA_TOO_LARGE)
pub const ADVERTISE_FAILED_DATA_TOO_LARGE: i32 = 1;
/// public static final [ADVERTISE_FAILED_FEATURE_UNSUPPORTED](https://developer.android.com/reference/android/bluetooth/le/AdvertiseCallback.html#ADVERTISE_FAILED_FEATURE_UNSUPPORTED)
pub const ADVERTISE_FAILED_FEATURE_UNSUPPORTED: i32 = 5;
/// public static final [ADVERTISE_FAILED_INTERNAL_ERROR](https://developer.android.com/reference/android/bluetooth/le/AdvertiseCallback.html#ADVERTISE_FAILED_INTERNAL_ERROR)
pub const ADVERTISE_FAILED_INTERNAL_ERROR: i32 = 4;
/// public static final [ADVERTISE_FAILED_TOO_MANY_ADVERTISERS](https://developer.android.com/reference/android/bluetooth/le/AdvertiseCallback.html#ADVERTISE_FAILED_TOO_MANY_ADVERTISERS)
pub const ADVERTISE_FAILED_TOO_MANY_ADVERTISERS: i32 = 2;
}
/// pub final class [AdvertiseData](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.html)
#[repr(transparent)]
pub struct AdvertiseData(pub(crate) ::java_spaghetti::ObjectAndEnv);
unsafe impl ::java_spaghetti::ReferenceType for AdvertiseData {}
unsafe impl ::java_spaghetti::JniType for AdvertiseData {
fn static_with_jni_type<R>(callback: impl FnOnce(&str) -> R) -> R {
callback("android/bluetooth/le/AdvertiseData\0")
}
}
unsafe impl ::java_spaghetti::AssignableTo<super::super::os::Parcelable> for AdvertiseData {}
unsafe impl ::java_spaghetti::AssignableTo<super::super::super::java::lang::Object> for AdvertiseData {}
impl ::std::ops::Deref for AdvertiseData {
type Target = super::super::super::java::lang::Object;
fn deref(&self) -> &Self::Target {
unsafe { &*(self as *const Self as *const Self::Target) }
}
}
impl ::std::convert::AsRef<super::super::os::Parcelable> for AdvertiseData {
fn as_ref(&self) -> &super::super::os::Parcelable {
unsafe { &*(self as *const Self as *const super::super::os::Parcelable) }
}
}
impl AdvertiseData {
/// [getServiceUuids](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.html#getServiceUuids())
pub fn getServiceUuids<'env>(
&'env self,
) -> ::std::result::Result<
::std::option::Option<::java_spaghetti::Local<'env, super::super::super::java::util::List>>,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
// class.path == "android/bluetooth/le/AdvertiseData", java.flags == PUBLIC, .name == "getServiceUuids", .descriptor == "()Ljava/util/List;"
unsafe {
let __jni_args = [];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData\0",
"getServiceUuids\0",
"()Ljava/util/List;\0",
);
__jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [getServiceSolicitationUuids](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.html#getServiceSolicitationUuids())
pub fn getServiceSolicitationUuids<'env>(
&'env self,
) -> ::std::result::Result<
::std::option::Option<::java_spaghetti::Local<'env, super::super::super::java::util::List>>,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
// class.path == "android/bluetooth/le/AdvertiseData", java.flags == PUBLIC, .name == "getServiceSolicitationUuids", .descriptor == "()Ljava/util/List;"
unsafe {
let __jni_args = [];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData\0",
"getServiceSolicitationUuids\0",
"()Ljava/util/List;\0",
);
__jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [getTransportDiscoveryData](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.html#getTransportDiscoveryData())
pub fn getTransportDiscoveryData<'env>(
&'env self,
) -> ::std::result::Result<
::std::option::Option<::java_spaghetti::Local<'env, super::super::super::java::util::List>>,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
// class.path == "android/bluetooth/le/AdvertiseData", java.flags == PUBLIC, .name == "getTransportDiscoveryData", .descriptor == "()Ljava/util/List;"
unsafe {
let __jni_args = [];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData\0",
"getTransportDiscoveryData\0",
"()Ljava/util/List;\0",
);
__jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [getManufacturerSpecificData](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.html#getManufacturerSpecificData())
pub fn getManufacturerSpecificData<'env>(
&'env self,
) -> ::std::result::Result<
::std::option::Option<::java_spaghetti::Local<'env, super::super::util::SparseArray>>,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
// class.path == "android/bluetooth/le/AdvertiseData", java.flags == PUBLIC, .name == "getManufacturerSpecificData", .descriptor == "()Landroid/util/SparseArray;"
unsafe {
let __jni_args = [];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData\0",
"getManufacturerSpecificData\0",
"()Landroid/util/SparseArray;\0",
);
__jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [getServiceData](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.html#getServiceData())
pub fn getServiceData<'env>(
&'env self,
) -> ::std::result::Result<
::std::option::Option<::java_spaghetti::Local<'env, super::super::super::java::util::Map>>,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
// class.path == "android/bluetooth/le/AdvertiseData", java.flags == PUBLIC, .name == "getServiceData", .descriptor == "()Ljava/util/Map;"
unsafe {
let __jni_args = [];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData\0",
"getServiceData\0",
"()Ljava/util/Map;\0",
);
__jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [getIncludeTxPowerLevel](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.html#getIncludeTxPowerLevel())
pub fn getIncludeTxPowerLevel<'env>(
&'env self,
) -> ::std::result::Result<
bool,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
// class.path == "android/bluetooth/le/AdvertiseData", java.flags == PUBLIC, .name == "getIncludeTxPowerLevel", .descriptor == "()Z"
unsafe {
let __jni_args = [];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData\0",
"getIncludeTxPowerLevel\0",
"()Z\0",
);
__jni_env.call_boolean_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [getIncludeDeviceName](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.html#getIncludeDeviceName())
pub fn getIncludeDeviceName<'env>(
&'env self,
) -> ::std::result::Result<
bool,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
// class.path == "android/bluetooth/le/AdvertiseData", java.flags == PUBLIC, .name == "getIncludeDeviceName", .descriptor == "()Z"
unsafe {
let __jni_args = [];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData\0",
"getIncludeDeviceName\0",
"()Z\0",
);
__jni_env.call_boolean_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [hashCode](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.html#hashCode())
pub fn hashCode<'env>(
&'env self,
) -> ::std::result::Result<i32, ::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>>
{
// class.path == "android/bluetooth/le/AdvertiseData", java.flags == PUBLIC, .name == "hashCode", .descriptor == "()I"
unsafe {
let __jni_args = [];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData\0",
"hashCode\0",
"()I\0",
);
__jni_env.call_int_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [equals](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.html#equals(java.lang.Object))
pub fn equals<'env>(
&'env self,
arg0: impl ::java_spaghetti::AsArg<super::super::super::java::lang::Object>,
) -> ::std::result::Result<
bool,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
// class.path == "android/bluetooth/le/AdvertiseData", java.flags == PUBLIC, .name == "equals", .descriptor == "(Ljava/lang/Object;)Z"
unsafe {
let __jni_args = [arg0.as_arg_jvalue()];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData\0",
"equals\0",
"(Ljava/lang/Object;)Z\0",
);
__jni_env.call_boolean_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [toString](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.html#toString())
pub fn toString<'env>(
&'env self,
) -> ::std::result::Result<
::std::option::Option<::java_spaghetti::Local<'env, super::super::super::java::lang::String>>,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
// class.path == "android/bluetooth/le/AdvertiseData", java.flags == PUBLIC, .name == "toString", .descriptor == "()Ljava/lang/String;"
unsafe {
let __jni_args = [];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData\0",
"toString\0",
"()Ljava/lang/String;\0",
);
__jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [describeContents](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.html#describeContents())
pub fn describeContents<'env>(
&'env self,
) -> ::std::result::Result<i32, ::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>>
{
// class.path == "android/bluetooth/le/AdvertiseData", java.flags == PUBLIC, .name == "describeContents", .descriptor == "()I"
unsafe {
let __jni_args = [];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData\0",
"describeContents\0",
"()I\0",
);
__jni_env.call_int_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
}
/// pub final class [AdvertiseData.Builder](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.Builder.html)
#[repr(transparent)]
pub struct AdvertiseData_Builder(pub(crate) ::java_spaghetti::ObjectAndEnv);
unsafe impl ::java_spaghetti::ReferenceType for AdvertiseData_Builder {}
unsafe impl ::java_spaghetti::JniType for AdvertiseData_Builder {
fn static_with_jni_type<R>(callback: impl FnOnce(&str) -> R) -> R {
callback("android/bluetooth/le/AdvertiseData$Builder\0")
}
}
unsafe impl ::java_spaghetti::AssignableTo<super::super::super::java::lang::Object> for AdvertiseData_Builder {}
impl ::std::ops::Deref for AdvertiseData_Builder {
type Target = super::super::super::java::lang::Object;
fn deref(&self) -> &Self::Target {
unsafe { &*(self as *const Self as *const Self::Target) }
}
}
impl AdvertiseData_Builder {
/// [Builder](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.Builder.html#Builder())
pub fn new<'env>(
__jni_env: ::java_spaghetti::Env<'env>,
) -> ::std::result::Result<
::java_spaghetti::Local<'env, Self>,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
// class.path == "android/bluetooth/le/AdvertiseData$Builder", java.flags == PUBLIC, .name == "<init>", .descriptor == "()V"
unsafe {
let __jni_args = [];
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData$Builder\0",
"<init>\0",
"()V\0",
);
__jni_env.new_object_a(__jni_class, __jni_method, __jni_args.as_ptr())
}
}
/// [addServiceUuid](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.Builder.html#addServiceUuid(android.os.ParcelUuid))
pub fn addServiceUuid<'env>(
&'env self,
arg0: impl ::java_spaghetti::AsArg<super::super::os::ParcelUuid>,
) -> ::std::result::Result<
::std::option::Option<::java_spaghetti::Local<'env, AdvertiseData_Builder>>,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
// class.path == "android/bluetooth/le/AdvertiseData$Builder", java.flags == PUBLIC, .name == "addServiceUuid", .descriptor == "(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/AdvertiseData$Builder;"
unsafe {
let __jni_args = [arg0.as_arg_jvalue()];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData$Builder\0",
"addServiceUuid\0",
"(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/AdvertiseData$Builder;\0",
);
__jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [addServiceSolicitationUuid](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.Builder.html#addServiceSolicitationUuid(android.os.ParcelUuid))
pub fn addServiceSolicitationUuid<'env>(
&'env self,
arg0: impl ::java_spaghetti::AsArg<super::super::os::ParcelUuid>,
) -> ::std::result::Result<
::std::option::Option<::java_spaghetti::Local<'env, AdvertiseData_Builder>>,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
// class.path == "android/bluetooth/le/AdvertiseData$Builder", java.flags == PUBLIC, .name == "addServiceSolicitationUuid", .descriptor == "(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/AdvertiseData$Builder;"
unsafe {
let __jni_args = [arg0.as_arg_jvalue()];
let __jni_env = ::java_spaghetti::Env::from_raw(self.0.env);
let (__jni_class, __jni_method) = __jni_env.require_class_method(
"android/bluetooth/le/AdvertiseData$Builder\0",
"addServiceSolicitationUuid\0",
"(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/AdvertiseData$Builder;\0",
);
__jni_env.call_object_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [addServiceData](https://developer.android.com/reference/android/bluetooth/le/AdvertiseData.Builder.html#addServiceData(android.os.ParcelUuid,%20byte%5B%5D))
pub fn addServiceData<'env>(
&'env self,
arg0: impl ::java_spaghetti::AsArg<super::super::os::ParcelUuid>,
arg1: impl ::java_spaghetti::AsArg<::java_spaghetti::ByteArray>,
) -> ::std::result::Result<
::std::option::Option<::java_spaghetti::Local<'env, AdvertiseData_Builder>>,
::java_spaghetti::Local<'env, super::super::super::java::lang::Throwable>,
> {
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | true |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/android/device.rs | src/android/device.rs | use futures_core::Stream;
use futures_lite::stream;
use java_spaghetti::Global;
use uuid::Uuid;
use super::bindings::android::bluetooth::BluetoothDevice;
use crate::pairing::PairingAgent;
use crate::{DeviceId, Result, Service, ServicesChanged};
#[derive(Clone)]
pub struct DeviceImpl {
pub(super) id: DeviceId,
#[cfg_attr(not(feature = "l2cap"), allow(unused))]
pub(super) device: Global<BluetoothDevice>,
}
impl PartialEq for DeviceImpl {
fn eq(&self, _other: &Self) -> bool {
todo!()
}
}
impl Eq for DeviceImpl {}
impl std::hash::Hash for DeviceImpl {
fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {
todo!()
}
}
impl std::fmt::Debug for DeviceImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut f = f.debug_struct("Device");
f.finish()
}
}
impl std::fmt::Display for DeviceImpl {
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//f.write_str(self.name().as_deref().unwrap_or("(Unknown)"))
todo!()
}
}
impl DeviceImpl {
pub fn id(&self) -> DeviceId {
self.id.clone()
}
pub fn name(&self) -> Result<String> {
todo!()
}
pub async fn name_async(&self) -> Result<String> {
todo!()
}
pub async fn is_connected(&self) -> bool {
todo!()
}
pub async fn is_paired(&self) -> Result<bool> {
todo!()
}
pub async fn pair(&self) -> Result<()> {
todo!()
}
pub async fn pair_with_agent<T: PairingAgent + 'static>(&self, _agent: &T) -> Result<()> {
todo!()
}
pub async fn unpair(&self) -> Result<()> {
todo!()
}
pub async fn discover_services(&self) -> Result<Vec<Service>> {
todo!()
}
pub async fn discover_services_with_uuid(&self, _uuid: Uuid) -> Result<Vec<Service>> {
todo!()
}
pub async fn services(&self) -> Result<Vec<Service>> {
todo!()
}
pub async fn service_changed_indications(
&self,
) -> Result<impl Stream<Item = Result<ServicesChanged>> + Send + Unpin + '_> {
Ok(stream::empty()) // TODO
}
pub async fn rssi(&self) -> Result<i16> {
todo!()
}
#[cfg(feature = "l2cap")]
pub async fn open_l2cap_channel(&self, psm: u16, secure: bool) -> Result<super::l2cap_channel::L2capChannel> {
let (reader, writer) = super::l2cap_channel::open_l2cap_channel(self.device.clone(), psm, secure)?;
Ok(super::l2cap_channel::L2capChannel { reader, writer })
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServicesChangedImpl;
impl ServicesChangedImpl {
pub fn was_invalidated(&self, _service: &Service) -> bool {
true
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/android/characteristic.rs | src/android/characteristic.rs | use futures_core::Stream;
use futures_lite::stream;
use uuid::Uuid;
use crate::{CharacteristicProperties, Descriptor, Result};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CharacteristicImpl {}
impl CharacteristicImpl {
pub fn uuid(&self) -> Uuid {
todo!()
}
pub async fn uuid_async(&self) -> Result<Uuid> {
todo!()
}
pub async fn properties(&self) -> Result<CharacteristicProperties> {
todo!()
}
pub async fn value(&self) -> Result<Vec<u8>> {
todo!()
}
pub async fn read(&self) -> Result<Vec<u8>> {
todo!()
}
pub async fn write(&self, _value: &[u8]) -> Result<()> {
todo!()
}
pub async fn write_without_response(&self, _value: &[u8]) -> Result<()> {
todo!()
}
pub fn max_write_len(&self) -> Result<usize> {
todo!()
}
pub async fn max_write_len_async(&self) -> Result<usize> {
todo!()
}
pub async fn notify(&self) -> Result<impl Stream<Item = Result<Vec<u8>>> + Send + Unpin + '_> {
Ok(stream::empty()) // TODO
}
pub async fn is_notifying(&self) -> Result<bool> {
todo!()
}
pub async fn discover_descriptors(&self) -> Result<Vec<Descriptor>> {
todo!()
}
pub async fn descriptors(&self) -> Result<Vec<Descriptor>> {
todo!()
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/android/l2cap_channel.rs | src/android/l2cap_channel.rs | #![cfg(feature = "l2cap")]
use std::io::{Read, Write};
use std::sync::Arc;
use std::task::{Context, Poll};
use std::{fmt, pin, slice, thread};
use futures_lite::io::{AsyncRead, AsyncWrite, BlockOn};
use java_spaghetti::{ByteArray, Global, Local, PrimitiveArray};
use tracing::{debug, trace, warn};
use super::bindings::android::bluetooth::{BluetoothDevice, BluetoothSocket};
use super::OptionExt;
use crate::l2cap_channel::{derive_async_read, derive_async_write, PIPE_CAPACITY};
pub fn open_l2cap_channel(
device: Global<BluetoothDevice>,
psm: u16,
secure: bool,
) -> std::prelude::v1::Result<(L2capChannelReader, L2capChannelWriter), crate::Error> {
device.vm().with_env(|env| {
let device = device.as_local(env);
let channel = if secure {
device.createL2capChannel(psm as _)?.non_null()?
} else {
device.createInsecureL2capChannel(psm as _)?.non_null()?
};
channel.connect()?;
// The L2capCloser closes the l2cap channel when dropped.
// We put it in an Arc held by both the reader and writer, so it gets dropped
// when
let closer = Arc::new(L2capCloser {
channel: channel.as_global(),
});
let (read_receiver, read_sender) = piper::pipe(PIPE_CAPACITY);
let (write_receiver, write_sender) = piper::pipe(PIPE_CAPACITY);
let input_stream = channel.getInputStream()?.non_null()?.as_global();
let output_stream = channel.getOutputStream()?.non_null()?.as_global();
// Unfortunately, Android's API for L2CAP channels is only blocking. Only way to deal with it
// is to launch two background threads with blocking loops for reading and writing, which communicate
// with the async Rust world via async channels.
//
// The loops stop when either Android returns an error (for example if the channel is closed), or the
// async channel gets closed because the user dropped the reader or writer structs.
thread::spawn(move || {
debug!("l2cap read thread running!");
let mut read_sender = BlockOn::new(read_sender);
input_stream.vm().with_env(|env| {
let stream = input_stream.as_local(env);
let arr: Local<ByteArray> = ByteArray::new(env, 1024);
loop {
match stream.read_byte_array(&arr) {
Ok(n) if n < 0 => {
warn!("failed to read from l2cap channel: {}", n);
break;
}
Err(e) => {
warn!("failed to read from l2cap channel: {:?}", e);
break;
}
Ok(n) => {
let n = n as usize;
let mut buf = vec![0u8; n];
arr.get_region(0, u8toi8_mut(&mut buf));
if let Err(e) = read_sender.write_all(&buf) {
warn!("failed to enqueue received l2cap packet: {:?}", e);
break;
}
}
}
}
});
debug!("l2cap read thread exiting!");
});
thread::spawn(move || {
debug!("l2cap write thread running!");
let mut write_receiver = BlockOn::new(write_receiver);
output_stream.vm().with_env(|env| {
let stream = output_stream.as_local(env);
let mut buf = vec![0; PIPE_CAPACITY];
loop {
match write_receiver.read(&mut buf) {
Err(e) => {
warn!("failed to dequeue l2cap packet to send: {:?}", e);
break;
}
Ok(0) => {
trace!("Stream ended");
break;
}
Ok(packet) => {
let b = ByteArray::new_from(env, u8toi8(&buf[..packet]));
if let Err(e) = stream.write_byte_array(b) {
warn!("failed to write to l2cap channel: {:?}", e);
break;
};
}
}
}
});
debug!("l2cap write thread exiting!");
});
Ok((
L2capChannelReader {
_closer: closer.clone(),
stream: read_receiver,
},
L2capChannelWriter {
_closer: closer,
stream: write_sender,
},
))
})
}
/// Utility struct to close the channel on drop.
pub(super) struct L2capCloser {
channel: Global<BluetoothSocket>,
}
impl L2capCloser {
fn close(&self) {
self.channel.vm().with_env(|env| {
let channel = self.channel.as_local(env);
match channel.close() {
Ok(()) => debug!("l2cap channel closed"),
Err(e) => warn!("failed to close channel: {:?}", e),
};
});
}
}
impl Drop for L2capCloser {
fn drop(&mut self) {
self.close()
}
}
pub struct L2capChannel {
pub(super) reader: L2capChannelReader,
pub(super) writer: L2capChannelWriter,
}
impl L2capChannel {
pub fn split(self) -> (L2capChannelReader, L2capChannelWriter) {
(self.reader, self.writer)
}
}
derive_async_read!(L2capChannel, reader);
derive_async_write!(L2capChannel, writer);
pub struct L2capChannelReader {
stream: piper::Reader,
_closer: Arc<L2capCloser>,
}
derive_async_read!(L2capChannelReader, stream);
impl fmt::Debug for L2capChannelReader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("L2capChannelReader")
}
}
pub struct L2capChannelWriter {
stream: piper::Writer,
_closer: Arc<L2capCloser>,
}
derive_async_write!(L2capChannelWriter, stream);
impl fmt::Debug for L2capChannelWriter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("L2capChannelWriter")
}
}
fn u8toi8(slice: &[u8]) -> &[i8] {
let len = slice.len();
let data = slice.as_ptr() as *const i8;
// safety: any bit pattern is valid for u8 and i8, so transmuting them is fine.
unsafe { slice::from_raw_parts(data, len) }
}
fn u8toi8_mut(slice: &mut [u8]) -> &mut [i8] {
let len = slice.len();
let data = slice.as_mut_ptr() as *mut i8;
// safety: any bit pattern is valid for u8 and i8, so transmuting them is fine.
unsafe { slice::from_raw_parts_mut(data, len) }
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/android/adapter.rs | src/android/adapter.rs | use std::collections::HashMap;
use std::pin::Pin;
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use async_channel::{Receiver, Sender};
use futures_core::Stream;
use futures_lite::{stream, StreamExt};
use java_spaghetti::{Arg, ByteArray, Env, Global, Local, Null, PrimitiveArray, VM};
use tracing::{debug, warn};
use uuid::Uuid;
use super::bindings::android::bluetooth::le::{BluetoothLeScanner, ScanResult, ScanSettings, ScanSettings_Builder};
use super::bindings::android::bluetooth::{BluetoothAdapter, BluetoothManager};
use super::bindings::android::os::ParcelUuid;
use super::bindings::com::github::alexmoon::bluest::android::BluestScanCallback;
use super::device::DeviceImpl;
use super::{JavaIterator, OptionExt};
use crate::android::bindings::java::util::Map_Entry;
use crate::util::defer;
use crate::{
AdapterEvent, AdvertisementData, AdvertisingDevice, ConnectionEvent, Device, DeviceId, ManufacturerData, Result,
};
struct AdapterInner {
manager: Global<BluetoothManager>,
_adapter: Global<BluetoothAdapter>,
le_scanner: Global<BluetoothLeScanner>,
}
#[derive(Clone)]
pub struct AdapterImpl {
inner: Arc<AdapterInner>,
}
/// Creates an interface to the default Bluetooth adapter for the system.
///
/// # Safety
///
/// - The `Adapter` takes ownership of the global reference and will delete it with the `DeleteGlobalRef` JNI call when dropped. You must not do that yourself.
pub struct AdapterConfig {
/// - `vm` must be a valid JNI `JavaVM` pointer to a VM that will stay alive for the entire duration the `Adapter` or any structs obtained from it are live.
vm: *mut java_spaghetti::sys::JavaVM,
/// - `manager` must be a valid global reference to an `android.bluetooth.BluetoothManager` instance, from the `java_vm` VM.
manager: java_spaghetti::sys::jobject,
}
impl AdapterConfig {
/// Creates a config for the default Bluetooth adapter for the system.
///
/// # Safety
///
/// - `java_vm` must be a valid JNI `JavaVM` pointer to a VM that will stay alive for the entire duration the `Adapter` or any structs obtained from it are live.
/// - `bluetooth_manager` must be a valid global reference to an `android.bluetooth.BluetoothManager` instance, from the `java_vm` VM.
/// - The `Adapter` takes ownership of the global reference and will delete it with the `DeleteGlobalRef` JNI call when dropped. You must not do that yourself.
pub unsafe fn new(
java_vm: *mut java_spaghetti::sys::JavaVM,
bluetooth_manager: java_spaghetti::sys::jobject,
) -> Self {
Self {
vm: java_vm,
manager: bluetooth_manager,
}
}
}
impl AdapterImpl {
/// Creates an interface to a Bluetooth adapter.
///
/// # Safety
///
/// In the config object:
///
/// - `vm` must be a valid JNI `JavaVM` pointer to a VM that will stay alive for the entire duration the `Adapter` or any structs obtained from it are live.
/// - `manager` must be a valid global reference to an `android.bluetooth.BluetoothManager` instance, from the `java_vm` VM.
/// - The `Adapter` takes ownership of the global reference and will delete it with the `DeleteGlobalRef` JNI call when dropped. You must not do that yourself.
pub async fn with_config(config: AdapterConfig) -> Result<Self> {
unsafe {
let vm = VM::from_raw(config.vm);
let manager: Global<BluetoothManager> = Global::from_raw(vm, config.manager);
vm.with_env(|env| {
let local_manager = manager.as_ref(env);
let adapter = local_manager.getAdapter()?.non_null()?;
let le_scanner = adapter.getBluetoothLeScanner()?.non_null()?;
Ok(Self {
inner: Arc::new(AdapterInner {
_adapter: adapter.as_global(),
le_scanner: le_scanner.as_global(),
manager: manager.clone(),
}),
})
})
}
}
pub(crate) async fn events(&self) -> Result<impl Stream<Item = Result<AdapterEvent>> + Send + Unpin + '_> {
Ok(stream::empty()) // TODO
}
pub async fn wait_available(&self) -> Result<()> {
Ok(())
}
/// Check if the adapter is available
pub async fn is_available(&self) -> Result<bool> {
Ok(true)
}
pub async fn open_device(&self, _id: &DeviceId) -> Result<Device> {
todo!()
}
pub async fn connected_devices(&self) -> Result<Vec<Device>> {
todo!()
}
pub async fn connected_devices_with_services(&self, _services: &[Uuid]) -> Result<Vec<Device>> {
todo!()
}
pub async fn scan<'a>(
&'a self,
_services: &'a [Uuid],
) -> Result<impl Stream<Item = AdvertisingDevice> + Send + Unpin + 'a> {
self.inner.manager.vm().with_env(|env| {
let receiver = SCAN_CALLBACKS.allocate();
let callback = BluestScanCallback::new(env, receiver.id)?;
let callback_global = callback.as_global();
let scanner = self.inner.le_scanner.as_ref(env);
let settings = ScanSettings_Builder::new(env)?;
settings.setScanMode(ScanSettings::SCAN_MODE_LOW_LATENCY)?;
let settings = settings.build()?.non_null()?;
scanner.startScan_List_ScanSettings_ScanCallback(Null, settings, callback)?;
let guard = defer(move || {
self.inner.manager.vm().with_env(|env| {
let callback = callback_global.as_ref(env);
let scanner = self.inner.le_scanner.as_ref(env);
match scanner.stopScan_ScanCallback(callback) {
Ok(()) => debug!("stopped scan"),
Err(e) => warn!("failed to stop scan: {:?}", e),
};
});
});
Ok(Box::pin(receiver).map(move |x| {
let _guard = &guard;
x
}))
})
}
pub async fn discover_devices<'a>(
&'a self,
services: &'a [Uuid],
) -> Result<impl Stream<Item = Result<Device>> + Send + Unpin + 'a> {
let connected = stream::iter(self.connected_devices_with_services(services).await?).map(Ok);
// try_unfold is used to ensure we do not start scanning until the connected devices have been consumed
let advertising = Box::pin(stream::try_unfold(None, |state| async {
let mut stream = match state {
Some(stream) => stream,
None => self.scan(services).await?,
};
Ok(stream.next().await.map(|x| (x.device, Some(stream))))
}));
Ok(connected.chain(advertising))
}
pub async fn connect_device(&self, _device: &Device) -> Result<()> {
// Windows manages the device connection automatically
Ok(())
}
pub async fn disconnect_device(&self, _device: &Device) -> Result<()> {
// Windows manages the device connection automatically
Ok(())
}
pub async fn device_connection_events<'a>(
&'a self,
_device: &'a Device,
) -> Result<impl Stream<Item = ConnectionEvent> + Send + Unpin + 'a> {
Ok(stream::empty()) // TODO
}
}
impl PartialEq for AdapterImpl {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl Eq for AdapterImpl {}
impl std::hash::Hash for AdapterImpl {
fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
}
impl std::fmt::Debug for AdapterImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Adapter").finish()
}
}
static SCAN_CALLBACKS: CallbackRouter<AdvertisingDevice> = CallbackRouter::new();
struct CallbackRouter<T: Send + 'static> {
map: Mutex<Option<HashMap<i32, Sender<T>>>>,
next_id: AtomicI32,
}
impl<T: Send + 'static> CallbackRouter<T> {
const fn new() -> Self {
Self {
map: Mutex::new(None),
next_id: AtomicI32::new(0),
}
}
fn allocate(&'static self) -> CallbackReceiver<T> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let (sender, receiver) = async_channel::bounded(16);
self.map
.lock()
.unwrap()
.get_or_insert_with(Default::default)
.insert(id, sender);
CallbackReceiver {
router: self,
id,
receiver,
}
}
fn callback(&'static self, id: i32, val: T) {
if let Some(sender) = self.map.lock().unwrap().as_mut().unwrap().get_mut(&id) {
if let Err(e) = sender.send_blocking(val) {
warn!("failed to send scan callback: {:?}", e)
}
}
}
}
struct CallbackReceiver<T: Send + 'static> {
router: &'static CallbackRouter<T>,
id: i32,
receiver: Receiver<T>,
}
impl<T: Send + 'static> Stream for CallbackReceiver<T> {
type Item = T;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
// safety: this is just a manually-written pin projection.
let receiver = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().receiver) };
receiver.poll_next(cx)
}
}
impl<T: Send> Drop for CallbackReceiver<T> {
fn drop(&mut self) {
self.router.map.lock().unwrap().as_mut().unwrap().remove(&self.id);
}
}
#[no_mangle]
pub extern "system" fn Java_com_github_alexmoon_bluest_android_BluestScanCallback_nativeOnScanResult(
env: Env<'_>,
_class: *mut (), // self class, ignore
id: i32,
callback_type: i32,
scan_result: Arg<ScanResult>,
) {
if let Err(e) = on_scan_result(env, id, callback_type, scan_result) {
warn!("on_scan_result failed: {:?}", e);
}
}
fn convert_uuid(uuid: Local<'_, ParcelUuid>) -> Result<Uuid> {
let uuid = uuid.getUuid()?.non_null()?;
let lsb = uuid.getLeastSignificantBits()? as u64;
let msb = uuid.getMostSignificantBits()? as u64;
Ok(Uuid::from_u64_pair(msb, lsb))
}
#[no_mangle]
fn on_scan_result(env: Env<'_>, id: i32, callback_type: i32, scan_result: Arg<ScanResult>) -> Result<()> {
let scan_result = unsafe { scan_result.into_ref(env) }.non_null()?;
tracing::info!("got callback! {} {}", id, callback_type);
let scan_record = scan_result.getScanRecord()?.non_null()?;
let device = scan_result.getDevice()?.non_null()?;
let address = device.getAddress()?.non_null()?.to_string_lossy();
let rssi = scan_result.getRssi()?;
let is_connectable = scan_result.isConnectable()?;
let local_name = scan_record.getDeviceName()?.map(|s| s.to_string_lossy());
let tx_power_level = scan_record.getTxPowerLevel()?;
// Services
let mut services = Vec::new();
if let Some(uuids) = scan_record.getServiceUuids()? {
for uuid in JavaIterator(uuids.iterator()?.non_null()?) {
services.push(convert_uuid(uuid.cast()?)?)
}
}
// Service data
let mut service_data = HashMap::new();
let sd = scan_record.getServiceData()?.non_null()?;
let sd = sd.entrySet()?.non_null()?;
for entry in JavaIterator(sd.iterator()?.non_null()?) {
let entry: Local<Map_Entry> = entry.cast()?;
let key: Local<ParcelUuid> = entry.getKey()?.non_null()?.cast()?;
let val: Local<ByteArray> = entry.getValue()?.non_null()?.cast()?;
service_data.insert(convert_uuid(key)?, val.as_vec().into_iter().map(|i| i as u8).collect());
}
// Manufacturer data
let mut manufacturer_data = None;
let msd = scan_record.getManufacturerSpecificData()?.non_null()?;
// TODO there can be multiple manufacturer data entries, but the bluest API only supports one. So grab just the first.
if msd.size()? != 0 {
let val: Local<'_, ByteArray> = msd.valueAt(0)?.non_null()?.cast()?;
manufacturer_data = Some(ManufacturerData {
company_id: msd.keyAt(0)? as _,
data: val.as_vec().into_iter().map(|i| i as u8).collect(),
});
}
let device_id = DeviceId(address);
let d = AdvertisingDevice {
device: Device(DeviceImpl {
id: device_id,
device: device.as_global(),
}),
adv_data: AdvertisementData {
is_connectable,
local_name,
manufacturer_data, // TODO, SparseArray is cursed.
service_data,
services,
tx_power_level: Some(tx_power_level as _),
},
rssi: Some(rssi as _),
};
SCAN_CALLBACKS.callback(id, d);
Ok(())
}
#[no_mangle]
pub extern "system" fn Java_com_github_alexmoon_bluest_android_BluestScanCallback_nativeOnScanFailed(
_env: Env<'_>,
_class: *mut (), // self class, ignore
id: i32,
error_code: i32,
) {
tracing::error!("got scan fail! {} {}", id, error_code);
todo!()
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/android/service.rs | src/android/service.rs | use crate::{Characteristic, Result, Service, Uuid};
#[derive(Debug, Clone)]
pub struct ServiceImpl {}
impl PartialEq for ServiceImpl {
fn eq(&self, _other: &Self) -> bool {
todo!()
}
}
impl Eq for ServiceImpl {}
impl std::hash::Hash for ServiceImpl {
fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {
todo!()
}
}
impl ServiceImpl {
pub fn uuid(&self) -> Uuid {
todo!()
}
pub async fn uuid_async(&self) -> Result<Uuid> {
todo!()
}
pub async fn is_primary(&self) -> Result<bool> {
todo!()
}
pub async fn discover_characteristics(&self) -> Result<Vec<Characteristic>> {
todo!()
}
pub async fn discover_characteristics_with_uuid(&self, _uuid: Uuid) -> Result<Vec<Characteristic>> {
todo!()
}
pub async fn characteristics(&self) -> Result<Vec<Characteristic>> {
todo!()
}
pub async fn discover_included_services(&self) -> Result<Vec<Service>> {
todo!()
}
pub async fn discover_included_services_with_uuid(&self, _uuid: Uuid) -> Result<Vec<Service>> {
todo!()
}
pub async fn included_services(&self) -> Result<Vec<Service>> {
todo!()
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/bluer/descriptor.rs | src/bluer/descriptor.rs | use crate::{Descriptor, Result, Uuid};
/// A Bluetooth GATT descriptor
#[derive(Debug, Clone)]
pub struct DescriptorImpl {
inner: bluer::gatt::remote::Descriptor,
}
impl PartialEq for DescriptorImpl {
fn eq(&self, other: &Self) -> bool {
self.inner.adapter_name() == other.inner.adapter_name()
&& self.inner.device_address() == other.inner.device_address()
&& self.inner.service_id() == other.inner.service_id()
&& self.inner.characteristic_id() == other.inner.characteristic_id()
&& self.inner.id() == other.inner.id()
}
}
impl Eq for DescriptorImpl {}
impl Descriptor {
pub(super) fn new(inner: bluer::gatt::remote::Descriptor) -> Descriptor {
Descriptor(DescriptorImpl { inner })
}
}
impl DescriptorImpl {
/// The [`Uuid`] identifying the type of this GATT descriptor
///
/// # Panics
///
/// This method will panic if there is a current Tokio runtime and it is single-threaded, if there is no current
/// Tokio runtime and creating one fails, or if the underlying [`DescriptorImpl::uuid_async()`] method fails.
pub fn uuid(&self) -> Uuid {
// Call an async function from a synchronous context
match tokio::runtime::Handle::try_current() {
Ok(handle) => tokio::task::block_in_place(move || handle.block_on(self.uuid_async())),
Err(_) => tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(self.uuid_async()),
}
.unwrap()
}
/// The [`Uuid`] identifying the type of this GATT descriptor
pub async fn uuid_async(&self) -> Result<Uuid> {
self.inner.uuid().await.map_err(Into::into)
}
/// The cached value of this descriptor
///
/// If the value has not yet been read, this method may either return an error or perform a read of the value.
pub async fn value(&self) -> Result<Vec<u8>> {
self.inner.cached_value().await.map_err(Into::into)
}
/// Read the value of this descriptor from the device
pub async fn read(&self) -> Result<Vec<u8>> {
self.inner.read().await.map_err(Into::into)
}
/// Write the value of this descriptor on the device to `value`
pub async fn write(&self, value: &[u8]) -> Result<()> {
self.inner.write(value).await.map_err(Into::into)
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/bluer/device.rs | src/bluer/device.rs | use std::sync::Arc;
use futures_core::Stream;
use futures_lite::StreamExt;
use super::DeviceId;
use crate::device::ServicesChanged;
use crate::error::ErrorKind;
use crate::pairing::PairingAgent;
use crate::{btuuid, AdvertisementData, Device, Error, ManufacturerData, Result, Service, Uuid};
/// A Bluetooth LE device
#[derive(Debug, Clone)]
pub struct DeviceImpl {
pub(super) inner: Arc<bluer::Device>,
session: Arc<bluer::Session>,
}
impl PartialEq for DeviceImpl {
fn eq(&self, other: &Self) -> bool {
self.inner.adapter_name() == other.inner.adapter_name() && self.inner.address() == other.inner.address()
}
}
impl Eq for DeviceImpl {}
impl std::hash::Hash for DeviceImpl {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.inner.adapter_name().hash(state);
self.inner.address().hash(state);
}
}
impl std::fmt::Display for DeviceImpl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name().as_deref().unwrap_or("(Unknown)"))
}
}
impl Device {
pub(super) fn new(session: Arc<bluer::Session>, adapter: &bluer::Adapter, addr: bluer::Address) -> Result<Device> {
Ok(Device(DeviceImpl {
inner: Arc::new(adapter.device(addr)?),
session,
}))
}
}
impl DeviceImpl {
/// This device's unique identifier
pub fn id(&self) -> DeviceId {
DeviceId(self.inner.address())
}
/// The local name for this device, if available
///
/// This can either be a name advertised or read from the device, or a name assigned to the device by the OS.
///
/// # Panics
///
/// This method will panic if there is a current Tokio runtime and it is single-threaded, if there is no current
/// Tokio runtime and creating one fails, or if the underlying [`DeviceImpl::name_async()`] method fails.
pub fn name(&self) -> Result<String> {
// Call an async function from a synchronous context
match tokio::runtime::Handle::try_current() {
Ok(handle) => tokio::task::block_in_place(move || handle.block_on(self.name_async())),
Err(_) => tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(self.name_async()),
}
}
/// The local name for this device, if available
///
/// This can either be a name advertised or read from the device, or a name assigned to the device by the OS.
pub async fn name_async(&self) -> Result<String> {
self.inner.alias().await.map_err(Into::into)
}
/// The connection status for this device
pub async fn is_connected(&self) -> bool {
self.inner.is_connected().await.unwrap_or(false)
}
/// The pairing status for this device
pub async fn is_paired(&self) -> Result<bool> {
self.inner.is_paired().await.map_err(Into::into)
}
/// Attempt to pair this device using the system default pairing UI
pub async fn pair(&self) -> Result<()> {
if self.is_paired().await? {
return Ok(());
}
self.inner.pair().await.map_err(Into::into)
}
/// Attempt to pair this device using the system default pairing UI
pub async fn pair_with_agent<T: PairingAgent + 'static>(&self, agent: &T) -> Result<()> {
if self.is_paired().await? {
return Ok(());
}
let agent = {
// Safety: This `bluer::agent::Agent`, including the encapsulated closures and async blocks will be dropped
// when the `_handle` below is dropped. Therefore, the lifetime of the captures of `agent` will not
// out-live the lifetime of `agent`. Unfortunately, the compiler has no way to prove this, so we must cast
// `agent` to the static lifetime.
let agent: &'static T = unsafe { std::mem::transmute(agent) };
async fn req_device(
session: Arc<bluer::Session>,
adapter: &str,
addr: bluer::Address,
) -> Result<Device, bluer::agent::ReqError> {
let adapter = session.adapter(adapter).map_err(|_| bluer::agent::ReqError::Rejected)?;
let device = adapter.device(addr).map_err(|_| bluer::agent::ReqError::Rejected)?;
Ok(Device(DeviceImpl {
inner: Arc::new(device),
session,
}))
}
bluer::agent::Agent {
request_passkey: Some(Box::new({
let session = self.session.clone();
move |req: bluer::agent::RequestPasskey| {
let session = session.clone();
Box::pin(async move {
let device = req_device(session, &req.adapter, req.device).await?;
match agent.request_passkey(&device).await {
Ok(passkey) => Ok(passkey.into()),
Err(_) => Err(bluer::agent::ReqError::Rejected),
}
})
}
})),
display_passkey: Some(Box::new({
let session = self.session.clone();
move |req: bluer::agent::DisplayPasskey| {
let session = session.clone();
Box::pin(async move {
let device = req_device(session, &req.adapter, req.device).await?;
if let Ok(passkey) = req.passkey.try_into() {
agent.display_passkey(&device, passkey);
Ok(())
} else {
Err(bluer::agent::ReqError::Rejected)
}
})
}
})),
request_confirmation: Some(Box::new({
let session = self.session.clone();
move |req: bluer::agent::RequestConfirmation| {
let session = session.clone();
Box::pin(async move {
let session = session.clone();
let device = req_device(session, &req.adapter, req.device).await?;
if let Ok(passkey) = req.passkey.try_into() {
agent
.confirm_passkey(&device, passkey)
.await
.map_err(|_| bluer::agent::ReqError::Rejected)
} else {
Err(bluer::agent::ReqError::Rejected)
}
})
}
})),
..Default::default()
}
};
let _handle = self.session.register_agent(agent).await?;
self.pair().await
}
/// Disconnect and unpair this device from the system
pub async fn unpair(&self) -> Result<()> {
if self.is_connected().await {
self.inner.disconnect().await?;
}
let adapter = self.session.adapter(self.inner.adapter_name())?;
adapter.remove_device(self.inner.address()).await.map_err(Into::into)
}
/// Discover the primary services of this device.
pub async fn discover_services(&self) -> Result<Vec<Service>> {
self.services().await
}
/// Discover the primary service(s) of this device with the given [`Uuid`].
pub async fn discover_services_with_uuid(&self, uuid: Uuid) -> Result<Vec<Service>> {
Ok(self
.services()
.await?
.into_iter()
.filter(|x| x.uuid() == uuid)
.collect())
}
/// Get previously discovered services.
///
/// If no services have been discovered yet, this method will perform service discovery.
pub async fn services(&self) -> Result<Vec<Service>> {
Ok(self
.inner
.services()
.await?
.into_iter()
.map(|x| Service::new(self.inner.clone(), x))
.collect())
}
/// Monitors the device for services changed events.
pub async fn service_changed_indications(
&self,
) -> Result<impl Stream<Item = Result<ServicesChanged>> + Send + Unpin + '_> {
let mut characteristic = Err(Error::from(ErrorKind::NotFound));
{
let services = self.inner.services().await?;
for service in services {
if service.uuid().await? == btuuid::services::GENERIC_ATTRIBUTE {
for c in service.characteristics().await? {
if c.uuid().await? == btuuid::characteristics::SERVICE_CHANGED {
characteristic = Ok(c);
}
}
}
}
}
let notifications = Box::pin(characteristic?.notify().await?);
Ok(notifications.map(|data| {
if data.len() == 4 {
let start_handle = u16::from_le_bytes(data[..2].try_into().unwrap());
let end_handle = u16::from_le_bytes(data[2..].try_into().unwrap());
Ok(ServicesChanged(ServicesChangedImpl(start_handle..=end_handle)))
} else {
Err(ErrorKind::InvalidParameter.into())
}
}))
}
/// Get the current signal strength from the device in dBm.
///
/// # Platform specific
///
/// Returns [ErrorKind::NotSupported].
pub async fn rssi(&self) -> Result<i16> {
Err(ErrorKind::NotSupported.into())
}
pub(super) async fn adv_data(&self) -> AdvertisementData {
let device = &self.inner;
let is_connectable = true;
let local_name = device.alias().await.unwrap_or_default();
let local_name = (!local_name.is_empty()).then_some(local_name);
let manufacturer_data = device
.manufacturer_data()
.await
.unwrap_or_default()
.and_then(|data| data.into_iter().next())
.map(|(company_id, data)| ManufacturerData { company_id, data });
let tx_power_level = device.tx_power().await.unwrap_or_default();
let service_data = device.service_data().await.unwrap_or_default().unwrap_or_default();
let services = device
.uuids()
.await
.unwrap_or_default()
.map_or(Vec::new(), |x| x.into_iter().collect());
AdvertisementData {
local_name,
manufacturer_data,
service_data,
services,
tx_power_level,
is_connectable,
}
}
#[cfg(feature = "l2cap")]
pub async fn open_l2cap_channel(
&self,
psm: u16,
_secure: bool,
) -> Result<super::l2cap_channel::L2capChannel, crate::Error> {
use async_compat::Compat;
use bluer::l2cap::{SocketAddr, Stream as L2CapStream};
use bluer::AddressType;
let target_sa = SocketAddr::new(self.inner.address(), AddressType::LePublic, psm);
let stream = L2CapStream::connect(target_sa).await?;
Ok(super::l2cap_channel::L2capChannel(Compat::new(stream)))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServicesChangedImpl(std::ops::RangeInclusive<u16>);
impl ServicesChangedImpl {
pub fn was_invalidated(&self, service: &Service) -> bool {
let service_id = service.0.inner.id();
self.0.contains(&service_id)
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/bluer/characteristic.rs | src/bluer/characteristic.rs | use bluer::gatt::remote::CharacteristicWriteRequest;
use bluer::gatt::WriteOp;
use futures_core::Stream;
use futures_lite::StreamExt;
use crate::{Characteristic, CharacteristicProperties, Descriptor, Result, Uuid};
/// A Bluetooth GATT characteristic
#[derive(Debug, Clone)]
pub struct CharacteristicImpl {
inner: bluer::gatt::remote::Characteristic,
}
impl PartialEq for CharacteristicImpl {
fn eq(&self, other: &Self) -> bool {
self.inner.adapter_name() == other.inner.adapter_name()
&& self.inner.device_address() == other.inner.device_address()
&& self.inner.service_id() == other.inner.service_id()
&& self.inner.id() == other.inner.id()
}
}
impl Eq for CharacteristicImpl {}
impl std::hash::Hash for CharacteristicImpl {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.inner.adapter_name().hash(state);
self.inner.device_address().hash(state);
self.inner.service_id().hash(state);
self.inner.id().hash(state);
}
}
impl Characteristic {
pub(super) fn new(inner: bluer::gatt::remote::Characteristic) -> Characteristic {
Characteristic(CharacteristicImpl { inner })
}
}
impl CharacteristicImpl {
/// The [`Uuid`] identifying the type of this GATT characteristic
///
/// # Panics
///
/// This method will panic if there is a current Tokio runtime and it is single-threaded, if there is no current
/// Tokio runtime and creating one fails, or if the underlying [`CharacteristicImpl::uuid_async()`] method fails.
pub fn uuid(&self) -> Uuid {
// Call an async function from a synchronous context
match tokio::runtime::Handle::try_current() {
Ok(handle) => tokio::task::block_in_place(move || handle.block_on(self.uuid_async())),
Err(_) => tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(self.uuid_async()),
}
.unwrap()
}
/// The [`Uuid`] identifying the type of this GATT characteristic
pub async fn uuid_async(&self) -> Result<Uuid> {
self.inner.uuid().await.map_err(Into::into)
}
/// The properties of this this GATT characteristic.
///
/// Characteristic properties indicate which operations (e.g. read, write, notify, etc) may be performed on this
/// characteristic.
pub async fn properties(&self) -> Result<CharacteristicProperties> {
self.inner.flags().await.map(Into::into).map_err(Into::into)
}
/// The cached value of this characteristic
///
/// If the value has not yet been read, this method may either return an error or perform a read of the value.
pub async fn value(&self) -> Result<Vec<u8>> {
self.inner.cached_value().await.map_err(Into::into)
}
/// Read the value of this characteristic from the device
pub async fn read(&self) -> Result<Vec<u8>> {
self.inner.read().await.map_err(Into::into)
}
/// Write the value of this descriptor on the device to `value` and request the device return a response indicating
/// a successful write.
pub async fn write(&self, value: &[u8]) -> Result<()> {
self.inner.write(value).await.map_err(Into::into)
}
/// Write the value of this descriptor on the device to `value` without requesting a response.
pub async fn write_without_response(&self, value: &[u8]) -> Result<()> {
self.inner
.write_ext(
value,
&CharacteristicWriteRequest {
op_type: WriteOp::Command,
..Default::default()
},
)
.await
.map_err(Into::into)
}
/// Get the maximum amount of data that can be written in a single packet for this characteristic.
pub fn max_write_len(&self) -> Result<usize> {
// Call an async function from a synchronous context
match tokio::runtime::Handle::try_current() {
Ok(handle) => tokio::task::block_in_place(move || handle.block_on(self.max_write_len_async())),
Err(_) => tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(self.max_write_len_async()),
}
}
/// Get the maximum amount of data that can be written in a single packet for this characteristic.
pub async fn max_write_len_async(&self) -> Result<usize> {
let mtu = self.inner.mtu().await?;
// GATT characteristic writes have 3 bytes of overhead (opcode + handle id)
Ok(mtu - 3)
}
/// Enables notification of value changes for this GATT characteristic.
///
/// Returns a stream of values for the characteristic sent from the device.
pub async fn notify(&self) -> Result<impl Stream<Item = Result<Vec<u8>>> + Send + Unpin + '_> {
Ok(Box::pin(self.inner.notify().await?.map(Ok)))
}
/// Is the device currently sending notifications for this characteristic?
pub async fn is_notifying(&self) -> Result<bool> {
Ok(self.inner.notifying().await?.unwrap_or(false))
}
/// Discover the descriptors associated with this characteristic.
pub async fn discover_descriptors(&self) -> Result<Vec<Descriptor>> {
self.descriptors().await
}
/// Get previously discovered descriptors.
///
/// If no descriptors have been discovered yet, this method will perform descriptor discovery.
pub async fn descriptors(&self) -> Result<Vec<Descriptor>> {
self.inner
.descriptors()
.await
.map_err(Into::into)
.map(|x| x.into_iter().map(Descriptor::new).collect())
}
}
impl From<bluer::gatt::CharacteristicFlags> for CharacteristicProperties {
fn from(flags: bluer::gatt::CharacteristicFlags) -> Self {
CharacteristicProperties {
broadcast: flags.broadcast,
read: flags.read,
write_without_response: flags.write_without_response,
write: flags.write,
notify: flags.notify,
indicate: flags.indicate,
authenticated_signed_writes: flags.authenticated_signed_writes,
extended_properties: flags.extended_properties,
reliable_write: flags.reliable_write,
writable_auxiliaries: flags.writable_auxiliaries,
}
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/bluer/l2cap_channel.rs | src/bluer/l2cap_channel.rs | #![cfg(feature = "l2cap")]
use std::fmt::Debug;
use std::pin;
use std::task::{Context, Poll};
use async_compat::Compat;
use bluer::l2cap::stream::{OwnedReadHalf, OwnedWriteHalf};
use bluer::l2cap::Stream;
use futures_lite::io::{AsyncRead, AsyncWrite};
use crate::l2cap_channel::{derive_async_read, derive_async_write};
pub struct L2capChannel(pub(super) Compat<Stream>);
impl L2capChannel {
pub fn split(self) -> (L2capChannelReader, L2capChannelWriter) {
let (reader, writer) = self.0.into_inner().into_split();
let (reader, writer) = (Compat::new(reader), Compat::new(writer));
(L2capChannelReader { reader }, L2capChannelWriter { writer })
}
}
derive_async_read!(L2capChannel, 0);
derive_async_write!(L2capChannel, 0);
pub struct L2capChannelReader {
pub(crate) reader: Compat<OwnedReadHalf>,
}
derive_async_read!(L2capChannelReader, reader);
impl Debug for L2capChannelReader {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Debug::fmt(self.reader.get_ref(), f)
}
}
pub struct L2capChannelWriter {
pub(crate) writer: Compat<OwnedWriteHalf>,
}
derive_async_write!(L2capChannelWriter, writer);
impl Debug for L2capChannelWriter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Debug::fmt(self.writer.get_ref(), f)
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/bluer/adapter.rs | src/bluer/adapter.rs | use std::sync::Arc;
use bluer::AdapterProperty;
use futures_core::Stream;
use futures_lite::StreamExt;
use crate::error::ErrorKind;
use crate::{AdapterEvent, AdvertisingDevice, ConnectionEvent, Device, DeviceId, Error, Result, Uuid};
#[derive(Default)]
pub struct AdapterConfig {
/// Name of adapter to use.
pub name: Option<String>,
}
/// The system's Bluetooth adapter interface.
///
/// The default adapter for the system may be accessed with the [`Adapter::default()`] method.
#[derive(Debug, Clone)]
pub struct AdapterImpl {
inner: bluer::Adapter,
session: Arc<bluer::Session>,
}
impl PartialEq for AdapterImpl {
fn eq(&self, other: &Self) -> bool {
self.inner.name() == other.inner.name()
}
}
impl Eq for AdapterImpl {}
impl std::hash::Hash for AdapterImpl {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.inner.name().hash(state);
}
}
impl AdapterImpl {
/// Creates an interface to a Bluetooth adapter using the provided config.
pub async fn with_config(config: AdapterConfig) -> Result<Self> {
let session = Arc::new(bluer::Session::new().await?);
let adapter = if let Some(name) = config.name {
session.adapter(&name)
} else {
session.default_adapter().await
};
let adapter = adapter.map(|inner| AdapterImpl { inner, session })?;
Ok(adapter)
}
/// A stream of [`AdapterEvent`] which allows the application to identify when the adapter is enabled or disabled.
pub async fn events(&self) -> Result<impl Stream<Item = Result<AdapterEvent>> + Send + Unpin + '_> {
let stream = self.inner.events().await?;
Ok(stream.filter_map(|event| match event {
bluer::AdapterEvent::PropertyChanged(AdapterProperty::Powered(true)) => Some(Ok(AdapterEvent::Available)),
bluer::AdapterEvent::PropertyChanged(AdapterProperty::Powered(false)) => {
Some(Ok(AdapterEvent::Unavailable))
}
_ => None,
}))
}
/// Asynchronously blocks until the adapter is available
pub async fn wait_available(&self) -> Result<()> {
let events = self.events();
if !self.inner.is_powered().await? {
events
.await?
.skip_while(|x| x.is_ok() && !matches!(x, Ok(AdapterEvent::Available)))
.next()
.await
.ok_or_else(|| Error::new(ErrorKind::Internal, None, "adapter event stream closed unexpectedly"))??;
}
Ok(())
}
/// Check if the adapter is available
pub async fn is_available(&self) -> Result<bool> {
Ok(self.inner.is_powered().await?)
}
/// Attempts to create the device identified by `id`
pub async fn open_device(&self, id: &DeviceId) -> Result<Device> {
Device::new(self.session.clone(), &self.inner, id.0)
}
/// Finds all connected Bluetooth LE devices
pub async fn connected_devices(&self) -> Result<Vec<Device>> {
let mut devices = Vec::new();
for device in self
.inner
.device_addresses()
.await?
.into_iter()
.filter_map(|addr| Device::new(self.session.clone(), &self.inner, addr).ok())
{
if device.is_connected().await {
devices.push(device);
}
}
Ok(devices)
}
/// Finds all connected devices providing any service in `services`
///
/// # Panics
///
/// Panics if `services` is empty.
pub async fn connected_devices_with_services(&self, services: &[Uuid]) -> Result<Vec<Device>> {
assert!(!services.is_empty());
let devices = self.connected_devices().await?;
let mut res = Vec::new();
for device in devices {
for service in device.0.inner.services().await? {
if services.contains(&service.uuid().await?) {
res.push(device);
break;
}
}
}
Ok(res)
}
/// Starts scanning for Bluetooth advertising packets.
///
/// Returns a stream of [`AdvertisingDevice`] structs which contain the data from the advertising packet and the
/// [`Device`] which sent it. Scanning is automatically stopped when the stream is dropped. Inclusion of duplicate
/// packets is a platform-specific implementation detail.
///
/// If `services` is not empty, returns advertisements including at least one GATT service with a UUID in
/// `services`. Otherwise returns all advertisements.
pub async fn scan<'a>(
&'a self,
services: &'a [Uuid],
) -> Result<impl Stream<Item = AdvertisingDevice> + Send + Unpin + 'a> {
Ok(self
.inner
.discover_devices()
.await?
.then(move |event| {
Box::pin(async move {
match event {
bluer::AdapterEvent::DeviceAdded(addr) => {
let device = Device::new(self.session.clone(), &self.inner, addr).ok()?;
if !device.is_connected().await {
let adv_data = device.0.adv_data().await;
let rssi = device.rssi().await.ok();
Some(AdvertisingDevice { device, adv_data, rssi })
} else {
None
}
}
_ => None,
}
})
})
.filter_map(|x| x)
.filter(|x: &AdvertisingDevice| {
services.is_empty() || x.adv_data.services.iter().any(|y| services.contains(y))
}))
}
/// Finds Bluetooth devices providing any service in `services`.
///
/// Returns a stream of [`Device`] structs with matching connected devices returned first. If the stream is not
/// dropped before all matching connected devices are consumed then scanning will begin for devices advertising any
/// of the `services`. Scanning will continue until the stream is dropped. Inclusion of duplicate devices is a
/// platform-specific implementation detail.
pub async fn discover_devices<'a>(
&'a self,
services: &'a [Uuid],
) -> Result<impl Stream<Item = Result<Device>> + Send + Unpin + 'a> {
Ok(self
.inner
.discover_devices()
.await?
.then(move |event| {
Box::pin(async move {
match event {
bluer::AdapterEvent::DeviceAdded(addr) => {
let device = match Device::new(self.session.clone(), &self.inner, addr) {
Ok(device) => device,
Err(err) => return Some(Err(err)),
};
if services.is_empty() {
Some(Ok(device))
} else {
match device.0.inner.uuids().await {
Ok(uuids) => {
let uuids = uuids.unwrap_or_default();
if services.iter().any(|x| uuids.contains(x)) {
Some(Ok(device))
} else {
None
}
}
Err(err) => Some(Err(err.into())),
}
}
}
_ => None,
}
})
})
.filter_map(|x| x))
}
/// Connects to the [`Device`]
pub async fn connect_device(&self, device: &Device) -> Result<()> {
device.0.inner.connect().await.map_err(Into::into)
}
/// Disconnects from the [`Device`]
pub async fn disconnect_device(&self, device: &Device) -> Result<()> {
device.0.inner.disconnect().await.map_err(Into::into)
}
/// Monitors a device for connection/disconnection events.
#[inline]
pub async fn device_connection_events<'a>(
&'a self,
device: &'a Device,
) -> Result<impl Stream<Item = ConnectionEvent> + Send + Unpin + 'a> {
let events = device.0.inner.events().await?;
Ok(events.filter_map(|ev| match ev {
bluer::DeviceEvent::PropertyChanged(bluer::DeviceProperty::Connected(false)) => {
Some(ConnectionEvent::Disconnected)
}
bluer::DeviceEvent::PropertyChanged(bluer::DeviceProperty::Connected(true)) => {
Some(ConnectionEvent::Connected)
}
_ => None,
}))
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/bluer/error.rs | src/bluer/error.rs | use crate::error::ErrorKind;
impl From<bluer::Error> for crate::Error {
fn from(err: bluer::Error) -> Self {
crate::Error::new(kind_from_bluer(&err), Some(Box::new(err)), String::new())
}
}
fn kind_from_bluer(err: &bluer::Error) -> ErrorKind {
match err.kind {
bluer::ErrorKind::ConnectionAttemptFailed => ErrorKind::ConnectionFailed,
bluer::ErrorKind::Failed => ErrorKind::Other,
bluer::ErrorKind::InvalidArguments => ErrorKind::InvalidParameter,
bluer::ErrorKind::InvalidLength => ErrorKind::InvalidParameter,
bluer::ErrorKind::NotAuthorized => ErrorKind::NotAuthorized,
bluer::ErrorKind::NotReady => ErrorKind::NotReady,
bluer::ErrorKind::NotSupported => ErrorKind::NotSupported,
bluer::ErrorKind::NotPermitted => ErrorKind::NotAuthorized,
bluer::ErrorKind::InvalidOffset => ErrorKind::InvalidParameter,
bluer::ErrorKind::InvalidAddress(_) => ErrorKind::InvalidParameter,
bluer::ErrorKind::InvalidName(_) => ErrorKind::InvalidParameter,
bluer::ErrorKind::ServicesUnresolved => ErrorKind::NotReady,
bluer::ErrorKind::NotFound => ErrorKind::NotFound,
_ => ErrorKind::Other,
}
}
#[cfg(feature = "l2cap")]
impl From<std::io::Error> for crate::Error {
fn from(err: std::io::Error) -> Self {
crate::Error::new(kind_from_io(&err.kind()), Some(Box::new(err)), String::new())
}
}
#[cfg(feature = "l2cap")]
fn kind_from_io(err: &std::io::ErrorKind) -> ErrorKind {
use std::io::ErrorKind as StdErrorKind;
match err {
StdErrorKind::NotFound => ErrorKind::NotFound,
StdErrorKind::PermissionDenied => ErrorKind::NotAuthorized,
StdErrorKind::ConnectionRefused
| StdErrorKind::ConnectionReset
| StdErrorKind::HostUnreachable
| StdErrorKind::NetworkUnreachable
| StdErrorKind::ConnectionAborted => ErrorKind::ConnectionFailed,
StdErrorKind::NotConnected => ErrorKind::NotConnected,
StdErrorKind::AddrNotAvailable | StdErrorKind::NetworkDown | StdErrorKind::ResourceBusy => {
ErrorKind::AdapterUnavailable
}
StdErrorKind::TimedOut => ErrorKind::Timeout,
StdErrorKind::Unsupported => ErrorKind::NotSupported,
StdErrorKind::Other => ErrorKind::Other,
// None of the other errors have semantic meaning for us
_ => ErrorKind::Internal,
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/bluer/service.rs | src/bluer/service.rs | use std::sync::Arc;
use crate::{Characteristic, Result, Service, Uuid};
/// A Bluetooth GATT service
#[derive(Debug, Clone)]
pub struct ServiceImpl {
pub(super) inner: bluer::gatt::remote::Service,
device: Arc<bluer::Device>,
}
impl PartialEq for ServiceImpl {
fn eq(&self, other: &Self) -> bool {
self.inner.adapter_name() == other.inner.adapter_name()
&& self.inner.device_address() == other.inner.device_address()
&& self.inner.id() == other.inner.id()
}
}
impl Eq for ServiceImpl {}
impl std::hash::Hash for ServiceImpl {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.inner.adapter_name().hash(state);
self.inner.device_address().hash(state);
self.inner.id().hash(state);
}
}
impl Service {
pub(super) fn new(device: Arc<bluer::Device>, inner: bluer::gatt::remote::Service) -> Service {
Service(ServiceImpl { inner, device })
}
}
impl ServiceImpl {
/// The [`Uuid`] identifying the type of this GATT service
///
/// # Panics
///
/// This method will panic if there is a current Tokio runtime and it is single-threaded, if there is no current
/// Tokio runtime and creating one fails, or if the underlying [`ServiceImpl::uuid_async()`] method fails.
pub fn uuid(&self) -> Uuid {
// Call an async function from a synchronous context
match tokio::runtime::Handle::try_current() {
Ok(handle) => tokio::task::block_in_place(move || handle.block_on(self.uuid_async())),
Err(_) => tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(self.uuid_async()),
}
.unwrap()
}
/// The [`Uuid`] identifying the type of this GATT service
pub async fn uuid_async(&self) -> Result<Uuid> {
self.inner.uuid().await.map_err(Into::into)
}
/// Whether this is a primary service of the device.
pub async fn is_primary(&self) -> Result<bool> {
self.inner.primary().await.map_err(Into::into)
}
/// Discover all characteristics associated with this service.
pub async fn discover_characteristics(&self) -> Result<Vec<Characteristic>> {
self.characteristics().await
}
/// Discover the characteristic(s) with the given [`Uuid`].
pub async fn discover_characteristics_with_uuid(&self, uuid: Uuid) -> Result<Vec<Characteristic>> {
Ok(self
.characteristics()
.await?
.into_iter()
.filter(|x| x.uuid() == uuid)
.collect())
}
/// Get previously discovered characteristics.
///
/// If no characteristics have been discovered yet, this method will perform characteristic discovery.
pub async fn characteristics(&self) -> Result<Vec<Characteristic>> {
self.inner
.characteristics()
.await
.map_err(Into::into)
.map(|x| x.into_iter().map(Characteristic::new).collect())
}
/// Discover the included services of this service.
pub async fn discover_included_services(&self) -> Result<Vec<Service>> {
self.included_services().await
}
/// Discover the included service(s) with the given [`Uuid`].
pub async fn discover_included_services_with_uuid(&self, uuid: Uuid) -> Result<Vec<Service>> {
Ok(self
.included_services()
.await?
.into_iter()
.filter(|x| x.uuid() == uuid)
.collect())
}
/// Get previously discovered included services.
///
/// If no included services have been discovered yet, this method will perform included service discovery.
pub async fn included_services(&self) -> Result<Vec<Service>> {
let includes = self.inner.includes().await?;
let mut res = Vec::with_capacity(includes.len());
for id in includes {
res.push(Service::new(self.device.clone(), self.device.service(id).await?));
}
Ok(res)
}
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/tests/check_api.rs | tests/check_api.rs | #![allow(clippy::let_unit_value)]
use bluest::*;
use futures_lite::StreamExt;
fn assert_send<T: Send>(t: T) -> T {
t
}
async fn check_adapter_apis(adapter: Adapter) -> Result<Device> {
let events: Result<_> = assert_send(adapter.events()).await;
let _event: Option<Result<AdapterEvent>> = assert_send(events?.next()).await;
let _available: Result<()> = assert_send(adapter.wait_available()).await;
let _devices: Result<Vec<Device>> = assert_send(adapter.connected_devices()).await;
let devices: Result<Vec<Device>> =
assert_send(adapter.connected_devices_with_services(&[btuuid::services::GENERIC_ACCESS])).await;
let scan: Result<_> = assert_send(adapter.scan(&[btuuid::services::GENERIC_ACCESS])).await;
let _adv: Option<AdvertisingDevice> = assert_send(scan?.next()).await;
let discovery: Result<_> = assert_send(adapter.discover_devices(&[btuuid::services::GENERIC_ACCESS])).await;
let _device: Option<Result<Device>> = assert_send(discovery?.next()).await;
let device: Result<Device> = assert_send(adapter.open_device(&devices?[0].id())).await;
let device = device?;
let _res: Result<()> = assert_send(adapter.connect_device(&device)).await;
let _res: Result<()> = assert_send(adapter.disconnect_device(&device)).await;
let events: Result<_> = assert_send(adapter.device_connection_events(&device)).await;
let _event: Option<ConnectionEvent> = assert_send(events?.next()).await;
Ok(device)
}
async fn check_device_apis(device: Device) -> Result<Service> {
let _id: DeviceId = device.id();
let _name: Result<String> = device.name();
let _name: Result<String> = assert_send(device.name_async()).await;
let _is_connected: bool = assert_send(device.is_connected()).await;
let _is_paired: Result<bool> = assert_send(device.is_paired()).await;
let _pair: Result<()> = assert_send(device.pair()).await;
let _pair_with_agent: Result<()> = assert_send(device.pair_with_agent(&pairing::NoInputOutputPairingAgent)).await;
let _unpair: Result<()> = assert_send(device.unpair()).await;
let _discovery: Result<Vec<Service>> = assert_send(device.discover_services()).await;
let _discovery: Result<Vec<Service>> =
assert_send(device.discover_services_with_uuid(btuuid::services::GENERIC_ACCESS)).await;
let services: Result<Vec<Service>> = assert_send(device.services()).await;
let _services_changed: Result<()> = assert_send(device.services_changed()).await;
let _rssi: Result<i16> = assert_send(device.rssi()).await;
Ok(services?.into_iter().next().unwrap())
}
async fn check_service_apis(service: Service) -> Result<Characteristic> {
let _uuid: Uuid = service.uuid();
let _uuid: Result<Uuid> = assert_send(service.uuid_async()).await;
let _is_primary: Result<bool> = assert_send(service.is_primary()).await;
let _discovery: Result<Vec<Characteristic>> = assert_send(service.discover_characteristics()).await;
let _discovery: Result<Vec<Characteristic>> =
assert_send(service.discover_characteristics_with_uuid(btuuid::characteristics::DEVICE_NAME)).await;
let characteristics: Result<Vec<Characteristic>> = assert_send(service.characteristics()).await;
let _discovery: Result<Vec<Service>> = assert_send(service.discover_included_services()).await;
let _discovery: Result<Vec<Service>> =
assert_send(service.discover_included_services_with_uuid(btuuid::services::GENERIC_ACCESS)).await;
let _services: Result<Vec<Service>> = assert_send(service.included_services()).await;
Ok(characteristics?.into_iter().next().unwrap())
}
async fn check_characteristic_apis(characteristic: Characteristic) -> Result<Descriptor> {
let _uuid: Uuid = characteristic.uuid();
let _uuid: Result<Uuid> = assert_send(characteristic.uuid_async()).await;
let _props: Result<CharacteristicProperties> = assert_send(characteristic.properties()).await;
let _value: Result<Vec<u8>> = assert_send(characteristic.value()).await;
let _value: Result<Vec<u8>> = assert_send(characteristic.read()).await;
let _res: Result<()> = assert_send(characteristic.write(&[0u8])).await;
let _res: Result<()> = assert_send(characteristic.write_without_response(&[0u8])).await;
let _len: Result<usize> = assert_send(characteristic.max_write_len_async()).await;
let notifications: Result<_> = assert_send(characteristic.notify()).await;
let _notification: Option<Result<Vec<u8>>> = assert_send(notifications?.next()).await;
let _is_notifying: Result<bool> = assert_send(characteristic.is_notifying()).await;
let _discovery: Result<Vec<Descriptor>> = assert_send(characteristic.discover_descriptors()).await;
let descriptors: Result<Vec<Descriptor>> = assert_send(characteristic.descriptors()).await;
Ok(descriptors?.into_iter().next().unwrap())
}
async fn check_descriptor_apis(descriptor: Descriptor) -> Result<()> {
let _uuid: Uuid = descriptor.uuid();
let _uuid: Result<Uuid> = assert_send(descriptor.uuid_async()).await;
let _value: Result<Vec<u8>> = assert_send(descriptor.value()).await;
let _value: Result<Vec<u8>> = assert_send(descriptor.read()).await;
let _res: Result<()> = assert_send(descriptor.write(&[0u8])).await;
Ok(())
}
#[allow(unused)]
async fn check_apis() -> Result<()> {
#[cfg(target_os = "android")]
let adapter: Result<Adapter> =
Adapter::with_config(unsafe { AdapterConfig::new(core::ptr::null_mut(), core::ptr::null_mut()) }).await;
#[cfg(not(target_os = "android"))]
let adapter: Result<Adapter> = assert_send(Adapter::default()).await;
let device = check_adapter_apis(adapter.unwrap()).await?;
let service = check_device_apis(device).await?;
let characteristic = check_service_apis(service).await?;
let descriptor = check_characteristic_apis(characteristic).await?;
check_descriptor_apis(descriptor).await?;
Ok(())
}
fn main() {}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/examples/reconnect.rs | examples/reconnect.rs | use std::error::Error;
use std::time::Duration;
use bluest::{btuuid, Adapter};
use futures_lite::StreamExt;
use tracing::info;
use tracing::metadata::LevelFilter;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
use tracing_subscriber::prelude::*;
use tracing_subscriber::{fmt, EnvFilter};
tracing_subscriber::registry()
.with(fmt::layer())
.with(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
)
.init();
let device_id = {
let adapter = Adapter::default().await.unwrap();
adapter.wait_available().await?;
info!("looking for device");
let device = adapter
.discover_devices(&[btuuid::services::BATTERY])
.await?
.next()
.await
.ok_or("Failed to discover device")??;
info!(
"found device: {} ({:?})",
device.name().as_deref().unwrap_or("(unknown)"),
device.id()
);
device.id()
};
info!("Time passes...");
tokio::time::sleep(Duration::from_secs(5)).await;
{
let adapter = Adapter::default().await.unwrap();
adapter.wait_available().await?;
info!("re-opening previously found device");
let device = adapter.open_device(&device_id).await?;
info!(
"re-opened device: {} ({:?})",
device.name().as_deref().unwrap_or("(unknown)"),
device.id()
);
}
Ok(())
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/examples/connected.rs | examples/connected.rs | use std::error::Error;
use bluest::Adapter;
use tracing::info;
use tracing::metadata::LevelFilter;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
use tracing_subscriber::prelude::*;
use tracing_subscriber::{fmt, EnvFilter};
tracing_subscriber::registry()
.with(fmt::layer())
.with(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
)
.init();
let adapter = Adapter::default().await?;
adapter.wait_available().await?;
info!("getting connected devices");
let devices = adapter.connected_devices().await?;
for device in devices {
info!("found {:?}", device);
adapter.connect_device(&device).await?;
let services = device.services().await?;
for service in services {
info!(" {:?}", service);
let characteristics = service.characteristics().await?;
for characteristic in characteristics {
info!(" {:?}", characteristic);
let props = characteristic.properties().await?;
info!(" props: {:?}", props);
if props.read {
info!(" value: {:?}", characteristic.read().await);
}
if props.write_without_response {
info!(" max_write_len: {:?}", characteristic.max_write_len());
}
let descriptors = characteristic.descriptors().await?;
for descriptor in descriptors {
info!(" {:?}: {:?}", descriptor, descriptor.read().await);
}
}
}
}
info!("done");
Ok(())
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/examples/pair.rs | examples/pair.rs | use std::error::Error;
use async_trait::async_trait;
use bluest::pairing::{IoCapability, PairingAgent, PairingRejected, Passkey};
use bluest::{btuuid, Adapter, Device};
use futures_lite::StreamExt;
use tracing::info;
use tracing::metadata::LevelFilter;
struct StdioPairingAgent;
#[async_trait]
impl PairingAgent for StdioPairingAgent {
/// The input/output capabilities of this agent
fn io_capability(&self) -> IoCapability {
IoCapability::KeyboardDisplay
}
async fn confirm(&self, device: &Device) -> Result<(), PairingRejected> {
tokio::task::block_in_place(move || {
println!("Do you want to pair with {:?}? (Y/n)", device.name().unwrap());
let mut buf = String::new();
std::io::stdin()
.read_line(&mut buf)
.map_err(|_| PairingRejected::default())?;
let response = buf.trim();
if response.is_empty() || response == "y" || response == "Y" {
Ok(())
} else {
Err(PairingRejected::default())
}
})
}
async fn confirm_passkey(&self, device: &Device, passkey: Passkey) -> Result<(), PairingRejected> {
tokio::task::block_in_place(move || {
println!(
"Is the passkey \"{}\" displayed on {:?}? (Y/n)",
passkey,
device.name().unwrap()
);
let mut buf = String::new();
std::io::stdin()
.read_line(&mut buf)
.map_err(|_| PairingRejected::default())?;
let response = buf.trim();
if response.is_empty() || response == "y" || response == "Y" {
Ok(())
} else {
Err(PairingRejected::default())
}
})
}
async fn request_passkey(&self, device: &Device) -> Result<Passkey, PairingRejected> {
tokio::task::block_in_place(move || {
println!("Please enter the 6-digit passkey for {:?}: ", device.name().unwrap());
let mut buf = String::new();
std::io::stdin()
.read_line(&mut buf)
.map_err(|_| PairingRejected::default())?;
buf.trim().parse().map_err(|_| PairingRejected::default())
})
}
fn display_passkey(&self, device: &Device, passkey: Passkey) {
println!("The passkey is \"{}\" for {:?}.", passkey, device.name().unwrap());
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
use tracing_subscriber::prelude::*;
use tracing_subscriber::{fmt, EnvFilter};
tracing_subscriber::registry()
.with(fmt::layer())
.with(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
)
.init();
let adapter = Adapter::default().await?;
adapter.wait_available().await?;
let discovered_device = {
info!("starting scan");
let mut scan = adapter.scan(&[btuuid::services::HUMAN_INTERFACE_DEVICE]).await?;
info!("scan started");
scan.next().await.ok_or("scan terminated")?
};
info!("{:?} {:?}", discovered_device.rssi, discovered_device.adv_data);
let device = discovered_device.device;
adapter.connect_device(&device).await?;
info!("connected!");
device.pair_with_agent(&StdioPairingAgent).await?;
info!("paired!");
adapter.disconnect_device(&device).await?;
info!("disconnected!");
Ok(())
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/examples/connect.rs | examples/connect.rs | use std::error::Error;
use std::time::Duration;
use bluest::{btuuid, Adapter};
use futures_lite::StreamExt;
use tracing::info;
use tracing::metadata::LevelFilter;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
use tracing_subscriber::prelude::*;
use tracing_subscriber::{fmt, EnvFilter};
tracing_subscriber::registry()
.with(fmt::layer())
.with(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
)
.init();
let adapter = Adapter::default().await?;
adapter.wait_available().await?;
let discovered_device = {
info!("starting scan");
let services = &[btuuid::services::USER_DATA];
let mut scan = adapter.scan(services).await?;
info!("scan started");
scan.next().await.ok_or("scan terminated")?
};
info!("{:?} {:?}", discovered_device.rssi, discovered_device.adv_data);
adapter.connect_device(&discovered_device.device).await?;
info!("connected!");
tokio::time::sleep(Duration::from_secs(30)).await;
adapter.disconnect_device(&discovered_device.device).await?;
info!("disconnected!");
Ok(())
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/examples/scan.rs | examples/scan.rs | use std::error::Error;
use bluest::Adapter;
use futures_lite::StreamExt;
use tracing::info;
use tracing::metadata::LevelFilter;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
use tracing_subscriber::prelude::*;
use tracing_subscriber::{fmt, EnvFilter};
tracing_subscriber::registry()
.with(fmt::layer())
.with(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
)
.init();
let adapter = Adapter::default().await?;
adapter.wait_available().await?;
info!("starting scan");
let mut scan = adapter.scan(&[]).await?;
info!("scan started");
while let Some(discovered_device) = scan.next().await {
info!(
"{}{}: {:?}",
discovered_device.device.name().as_deref().unwrap_or("(unknown)"),
discovered_device
.rssi
.map(|rssi| format!(" ({rssi}dBm)"))
.unwrap_or_default(),
discovered_device.adv_data.services
);
}
Ok(())
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
alexmoon/bluest | https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/examples/blinky.rs | examples/blinky.rs | use std::error::Error;
use std::time::Duration;
use bluest::{Adapter, Uuid};
use futures_lite::{future, StreamExt};
use tracing::metadata::LevelFilter;
use tracing::{error, info};
const NORDIC_LED_AND_BUTTON_SERVICE: Uuid = Uuid::from_u128(0x00001523_1212_efde_1523_785feabcd123);
const BLINKY_BUTTON_STATE_CHARACTERISTIC: Uuid = Uuid::from_u128(0x00001524_1212_efde_1523_785feabcd123);
const BLINKY_LED_STATE_CHARACTERISTIC: Uuid = Uuid::from_u128(0x00001525_1212_efde_1523_785feabcd123);
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
use tracing_subscriber::prelude::*;
use tracing_subscriber::{fmt, EnvFilter};
tracing_subscriber::registry()
.with(fmt::layer())
.with(
EnvFilter::builder()
.with_default_directive(LevelFilter::INFO.into())
.from_env_lossy(),
)
.init();
let adapter = Adapter::default().await?;
adapter.wait_available().await?;
info!("looking for device");
let device = adapter
.discover_devices(&[NORDIC_LED_AND_BUTTON_SERVICE])
.await?
.next()
.await
.ok_or("Failed to discover device")??;
info!(
"found device: {} ({:?})",
device.name().as_deref().unwrap_or("(unknown)"),
device.id()
);
adapter.connect_device(&device).await?;
info!("connected!");
let service = match device
.discover_services_with_uuid(NORDIC_LED_AND_BUTTON_SERVICE)
.await?
.first()
{
Some(service) => service.clone(),
None => return Err("service not found".into()),
};
info!("found LED and button service");
let characteristics = service.characteristics().await?;
info!("discovered characteristics");
let button_characteristic = characteristics
.iter()
.find(|x| x.uuid() == BLINKY_BUTTON_STATE_CHARACTERISTIC)
.ok_or("button characteristic not found")?;
let button_fut = async {
info!("enabling button notifications");
let mut updates = button_characteristic.notify().await?;
info!("waiting for button changes");
while let Some(val) = updates.next().await {
info!("Button state changed: {:?}", val?);
}
Ok(())
};
let led_characteristic = characteristics
.iter()
.find(|x| x.uuid() == BLINKY_LED_STATE_CHARACTERISTIC)
.ok_or("led characteristic not found")?;
let blink_fut = async {
info!("blinking LED");
tokio::time::sleep(Duration::from_secs(1)).await;
loop {
led_characteristic.write(&[0x01]).await?;
info!("LED on");
tokio::time::sleep(Duration::from_secs(1)).await;
led_characteristic.write(&[0x00]).await?;
info!("LED off");
tokio::time::sleep(Duration::from_secs(1)).await;
}
};
type R = Result<(), Box<dyn Error>>;
let button_fut = async move {
let res: R = button_fut.await;
error!("Button task exited: {:?}", res);
};
let blink_fut = async move {
let res: R = blink_fut.await;
error!("Blink task exited: {:?}", res);
};
future::zip(blink_fut, button_fut).await;
Ok(())
}
| rust | Apache-2.0 | 37e353d778b43d4892d2b7315cb5fba6cd5cb969 | 2026-01-04T20:23:19.181316Z | false |
mrmekon/fruitbasket | https://github.com/mrmekon/fruitbasket/blob/3fdebfa159a2248dc55def22edd2aedabd1f294c/src/lib.rs | src/lib.rs | //! fruitbasket - Framework for running Rust programs in a Mac 'app bundle' environment.
//!
//! fruitbasket provides two different (but related) services for helping you run your
//! Rust binaries as native AppKit/Cocoa applications on Mac OS X:
//!
//! * App lifecycle and environment API - fruitbasket provides an API to initialize the
//! AppKit application environment (NSApplication), to pump the main application loop
//! and dispatch Apple events in a non-blocking way, to terminate the application, to
//! access resources in the app bundle, and various other tasks frequently needed by
//! Mac applications.
//!
//! * Self-bundling app 'trampoline' - fruitbasket provides a 'trampoline' to
//! automatically bundle a standalone binary as a Mac application in a `.app` bundle
//! at runtime. This allows access to features that require running from a bundle (
//! such as XPC services), self-installing into the Applications folder, registering
//! your app with the system as a document type or URL handler, and various other
//! features that are only available to bundled apps with unique identifiers.
//! Self-bundling and relaunching itself (the "trampoline" behavior) allows your app
//! to get the features of app bundles, but still be launched in the standard Rust
//! ways (such as `cargo run`).
//!
//! The primary goal of fruitbasket is to make it reasonably easy to develop native
//! Mac GUI applications with the standard Apple AppKit/Cocoa/Foundation frameworks
//! in pure Rust by pushing all of the Apple and Objective-C runtime logic into
//! dedicated libraries, isolating the logic of a Rust binary application from the
//! unsafe platform code. As the ecosystem of Mac libraries for Rust grows, you
//! should be able to mix-and-match the libraries your application needs, pump the
//! event loop with fruitbasket, and never worry about Objective-C in your application.
//!
//! # Getting Started
//!
//! You likely want to create either a [Trampoline](struct.Trampoline.html) or a
//! [FruitApp](struct.FruitApp.html) right after your Rust application starts.
//! If uncertain, use a `Trampoline`. You can hit very strange behavior when running
//! Cocoa apps outside of an app bundle.
#![deny(missing_docs)]
use std::error::Error;
use std::time::Duration;
use std::sync::mpsc::Sender;
#[cfg(any(not(target_os = "macos"), feature="dummy"))]
use std::sync::mpsc::Receiver;
#[cfg(any(not(target_os = "macos"), feature="dummy"))]
use std::thread;
extern crate time;
extern crate dirs;
#[cfg(all(target_os = "macos", not(feature="dummy")))]
#[macro_use]
extern crate objc;
#[cfg(feature = "logging")]
#[allow(unused_imports)]
#[macro_use]
extern crate log;
#[cfg(feature = "logging")]
extern crate log4rs;
#[cfg(not(feature = "logging"))]
#[allow(unused_macros)]
macro_rules! info {
($x:expr) => {println!($x)};
($x:expr, $($arg:tt)+) => {println!($x, $($arg)+)};
}
/// Info.plist entries that have default values, but can be overridden
///
/// These properties are always set in the app bundle's Property List, with the
/// default values provided here, but can be overridden by your application with
/// the Trampoline builder's `plist_key*()` functions.
pub const DEFAULT_PLIST: &'static [(&'static str, &'static str)] = &[
("CFBundleInfoDictionaryVersion","6.0"),
("CFBundlePackageType","APPL"),
("CFBundleSignature","xxxx"),
("LSMinimumSystemVersion","10.10.0"),
];
/// Info.plist entries that are set, and cannot be overridden
///
/// These properties are always set in the app bundle's Property List, based on
/// information provided to the Trampoline builder, and cannot be overridden
/// with the builder's `plist_key*()` functions.
pub const FORBIDDEN_PLIST: &'static [&'static str] = & [
"CFBundleName",
"CFBundleDisplayName",
"CFBundleIdentifier",
"CFBundleExecutable",
"CFBundleIconFile",
"CFBundleVersion",
];
/// Apple kInternetEventClass constant
#[allow(non_upper_case_globals)]
pub const kInternetEventClass: u32 = 0x4755524c;
/// Apple kAEGetURL constant
#[allow(non_upper_case_globals)]
pub const kAEGetURL: u32 = 0x4755524c;
/// Apple keyDirectObject constant
#[allow(non_upper_case_globals)]
pub const keyDirectObject: u32 = 0x2d2d2d2d;
#[cfg(all(target_os = "macos", not(feature="dummy")))]
mod osx;
#[cfg(all(target_os = "macos", not(feature="dummy")))]
pub use osx::FruitApp;
#[cfg(all(target_os = "macos", not(feature="dummy")))]
pub use osx::Trampoline;
#[cfg(all(target_os = "macos", not(feature="dummy")))]
pub use osx::FruitObjcCallback;
#[cfg(all(target_os = "macos", not(feature="dummy")))]
pub use osx::FruitCallbackKey;
#[cfg(all(target_os = "macos", not(feature="dummy")))]
pub use osx::parse_url_event;
#[cfg(all(target_os = "macos", not(feature="dummy")))]
pub use osx::nsstring_to_string;
#[cfg(any(not(target_os = "macos"), feature="dummy"))]
/// Docs in OS X build.
pub enum FruitCallbackKey {
/// Docs in OS X build.
Method(&'static str),
/// Docs in OS X build.
Object(*mut u64),
}
#[cfg(any(not(target_os = "macos"), feature="dummy"))]
/// Docs in OS X build.
pub type FruitObjcCallback = Box<dyn Fn(*mut u64)>;
/// Main interface for controlling and interacting with the AppKit app
///
/// Dummy implementation for non-OSX platforms. See OS X build for proper
/// documentation.
#[cfg(any(not(target_os = "macos"), feature="dummy"))]
pub struct FruitApp {
tx: Sender<()>,
rx: Receiver<()>,
}
#[cfg(any(not(target_os = "macos"), feature="dummy"))]
impl FruitApp {
/// Docs in OS X build.
pub fn new() -> FruitApp {
use std::sync::mpsc::channel;
let (tx,rx) = channel();
FruitApp{ tx: tx, rx: rx}
}
/// Docs in OS X build.
pub fn register_callback(&mut self, _key: FruitCallbackKey, _cb: FruitObjcCallback) {}
/// Docs in OS X build.
pub fn register_apple_event(&mut self, _class: u32, _id: u32) {}
/// Docs in OS X build.
pub fn set_activation_policy(&self, _policy: ActivationPolicy) {}
/// Docs in OS X build.
pub fn terminate(exit_code: i32) {
std::process::exit(exit_code);
}
/// Docs in OS X build.
pub fn stop(stopper: &FruitStopper) {
stopper.stop();
}
/// Docs in OS X build.
pub fn run(&mut self, period: RunPeriod) -> Result<(),()> {
let start = time::now_utc().to_timespec();
loop {
if self.rx.try_recv().is_ok() {
return Err(());
}
if period == RunPeriod::Once {
break;
}
thread::sleep(Duration::from_millis(500));
if let RunPeriod::Time(t) = period {
let now = time::now_utc().to_timespec();
if now >= start + time::Duration::from_std(t).unwrap() {
break;
}
}
}
Ok(())
}
/// Docs in OS X build.
pub fn stopper(&self) -> FruitStopper {
FruitStopper { tx: self.tx.clone() }
}
/// Docs in OS X build.
pub fn bundled_resource_path(_name: &str, _extension: &str) -> Option<String> { None }
}
#[cfg(any(not(target_os = "macos"), feature="dummy"))]
/// Docs in OS X build.
pub fn parse_url_event(_event: *mut u64) -> String { "".into() }
#[cfg(any(not(target_os = "macos"), feature = "dummy"))]
/// Docs in OS X build.
pub fn nsstring_to_string(_nsstring: *mut u64) -> String {
"".into()
}
/// API to move the executable into a Mac app bundle and relaunch (if necessary)
///
/// Dummy implementation for non-OSX platforms. See OS X build for proper
/// documentation.
#[cfg(any(not(target_os = "macos"), feature="dummy"))]
pub struct Trampoline {}
#[cfg(any(not(target_os = "macos"), feature="dummy"))]
impl Trampoline {
/// Docs in OS X build.
pub fn new(_name: &str, _exe: &str, _ident: &str) -> Trampoline { Trampoline {} }
/// Docs in OS X build.
pub fn name(&mut self, _name: &str) -> &mut Self { self }
/// Docs in OS X build.
pub fn exe(&mut self, _exe: &str) -> &mut Self { self }
/// Docs in OS X build.
pub fn ident(&mut self, _ident: &str) -> &mut Self { self }
/// Docs in OS X build.
pub fn icon(&mut self, _icon: &str) -> &mut Self { self }
/// Docs in OS X build.
pub fn version(&mut self, _version: &str) -> &mut Self { self }
/// Docs in OS X build.
pub fn plist_key(&mut self, _key: &str, _value: &str) -> &mut Self { self }
/// Docs in OS X build.
pub fn plist_keys(&mut self, _pairs: &Vec<(&str,&str)>) -> &mut Self { self }
/// Docs in OS X build.
pub fn retina(&mut self, _doit: bool) -> &mut Self { self }
/// Docs in OS X build.
pub fn plist_raw_string(&mut self, _s: String) -> &mut Self { self }
/// Docs in OS X build.
pub fn resource(&mut self, _file: &str) -> &mut Self { self }
/// Docs in OS X build.
pub fn resources(&mut self, _files: &Vec<&str>) -> &mut Self{ self }
/// Docs in OS X build.
pub fn build(&mut self, dir: InstallDir) -> Result<FruitApp, FruitError> {
self.self_bundle(dir)?;
unreachable!()
}
/// Docs in OS X build.
pub fn self_bundle(&mut self, _dir: InstallDir) -> Result<(), FruitError> {
Err(FruitError::UnsupportedPlatform("fruitbasket disabled or not supported on this platform.".to_string()))
}
/// Docs in OS X build.
pub fn is_bundled() -> bool { false }
}
/// Options for how long to run the event loop on each call
#[derive(PartialEq)]
pub enum RunPeriod {
/// Run event loop once and return
Once,
/// Run event loop forever, never returning and blocking the main thread
Forever,
/// Run event loop at least the specified length of time
Time(Duration),
}
/// Policies controlling how a Mac application's UI is interacted with
pub enum ActivationPolicy {
/// Appears in the Dock and menu bar and can have an interactive UI with windows
Regular,
/// Does not appear in Dock or menu bar, but may create windows
Accessory,
/// Does not appear in Dock or menu bar, may not create windows (background-only)
Prohibited,
}
/// Class for errors generated by fruitbasket. Dereferences to a String.
#[derive(Debug)]
pub enum FruitError {
/// fruitbasket doesn't run on this platform (safe to ignore)
UnsupportedPlatform(String),
/// Disk I/O errors: failed to write app bundle to disk
IOError(String),
/// Any other unclassified error
GeneralError(String),
}
impl std::fmt::Display for FruitError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl From<std::io::Error> for FruitError {
fn from(error: std::io::Error) -> Self {
FruitError::IOError(error.to_string())
}
}
impl Error for FruitError {
fn description(&self) -> &str {
"Hmm"
}
fn cause(&self) -> Option<&dyn Error> {
None
}
}
/// An opaque, thread-safe object that can interrupt the run loop.
///
/// An object that is safe to pass across thread boundaries (i.e. it implements
/// Send and Sync), and can be used to interrupt and stop the run loop, even
/// when running in 'Forever' mode. It can be Cloned infinite times and used
/// from any thread.
#[derive(Clone)]
pub struct FruitStopper {
tx: Sender<()>,
}
impl FruitStopper {
/// Stop the run loop on the `FruitApp` instance that created this object
///
/// This is equivalent to passing the object to [FruitApp::stop](FruitApp::stop). See it
/// for more documentation.
pub fn stop(&self) {
let _ = self.tx.send(());
}
}
/// Options for where to save generated app bundle
pub enum InstallDir {
/// Store in a system-defined temporary directory
Temp,
/// Store in the system-wide Application directory (all users)
SystemApplications,
/// Store in the user-specific Application directory (current user)
UserApplications,
/// Store in a custom directory, specified as a String
Custom(String),
}
/// Options for where to save logging output generated by fruitbasket
pub enum LogDir {
/// User's home directory
Home,
/// Temporary directory (as specified by OS)
Temp,
/// Custom location, provided as a String
Custom(String),
}
/// Enable logging to rolling log files with Rust `log` library
///
/// Requires the 'logging' feature to be specified at compile time.
///
/// This is a helper utility for configuring the Rust `log` and `log4rs`
/// libraries to redirect the `log` macros (`info!()`, `warn!()`, `err!()`, etc)
/// to both stdout and a rotating log file on disk.
///
/// If you specify the Home directory with a log named ".fruit.log" and a
/// backup count of 3, eventually you will end up with the files `~/.fruit.log`,
/// `~/.fruit.log.1`, `~/.fruit.log.2`, and `~/.fruit.log.3`
///
/// The maximum disk space used by the log files, in megabytes, will be:
///
/// `(backup_count + 1) * max_size_mb`
///
/// # Arguments
///
/// `filename` - Filename for the log file, *without* path
///
/// `dir` - Directory to save log files in. This is provided as an enum,
/// `LogDir`, which offers some standard logging directories, or allows
/// specification of any custom directory.
///
/// `max_size_mb` - Max size (in megabytes) of the log file before it is rolled
/// into an archive file in the same directory.
///
/// `backup_count` - Number of archived log files to keep before deleting old
/// logs.
///
/// # Returns
///
/// Full path to opened log file on disk
#[cfg(feature = "logging")]
pub fn create_logger(filename: &str,
dir: LogDir,
max_size_mb: u32,
backup_count: u32) -> Result<String, String> {
use log::LevelFilter;
use self::log4rs::append::console::ConsoleAppender;
use self::log4rs::append::rolling_file::RollingFileAppender;
use self::log4rs::append::rolling_file::policy::compound::CompoundPolicy;
use self::log4rs::append::rolling_file::policy::compound::roll::fixed_window::FixedWindowRoller;
use self::log4rs::append::rolling_file::policy::compound::trigger::size::SizeTrigger;
use self::log4rs::encode::pattern::PatternEncoder;
use self::log4rs::config::{Appender, Config, Logger, Root};
let log_path = match dir {
LogDir::Home => format!("{}/{}", dirs::home_dir().unwrap().display(), filename),
LogDir::Temp => format!("{}/{}", std::env::temp_dir().display(), filename),
LogDir::Custom(s) => format!("{}/{}", s, filename),
};
let stdout = ConsoleAppender::builder()
.encoder(Box::new(PatternEncoder::new("{m}{n}")))
.build();
let trigger = Box::new(SizeTrigger::new(1024*1024*max_size_mb as u64));
let roller = Box::new(FixedWindowRoller::builder()
.build(&format!("{}.{{}}", log_path), backup_count).unwrap());
let policy = Box::new(CompoundPolicy::new(trigger, roller));
let rolling = RollingFileAppender::builder()
.build(&log_path, policy)
.unwrap();
let config = Config::builder()
.appender(Appender::builder().build("stdout", Box::new(stdout)))
.appender(Appender::builder().build("requests", Box::new(rolling)))
.logger(Logger::builder().build("app::backend::db", LevelFilter::Info))
.logger(Logger::builder()
.appender("requests")
.additive(false)
.build("app::requests", LevelFilter::Info))
.build(Root::builder().appender("stdout").appender("requests").build(LevelFilter::Info))
.unwrap();
match log4rs::init_config(config) {
Ok(_) => Ok(log_path),
Err(e) => Err(e.to_string()),
}
}
/// Enable logging to rolling log files with Rust `log` library
///
/// Requires the 'logging' feature to be specified at compile time.
///
/// This is a helper utility for configuring the Rust `log` and `log4rs`
/// libraries to redirect the `log` macros (`info!()`, `warn!()`, `error!()`, etc)
/// to both stdout and a rotating log file on disk.
///
/// If you specify the Home directory with a log named ".fruit.log" and a
/// backup count of 3, eventually you will end up with the files `~/.fruit.log`,
/// `~/.fruit.log.1`, `~/.fruit.log.2`, and `~/.fruit.log.3`
///
/// The maximum disk space used by the log files, in megabytes, will be:
///
/// `(backup_count + 1) * max_size_mb`
///
/// # Arguments
///
/// `filename` - Filename for the log file, *without* path
///
/// `dir` - Directory to save log files in. This is provided as an enum,
/// `LogDir`, which offers some standard logging directories, or allows
/// specification of any custom directory.
///
/// `max_size_mb` - Max size (in megabytes) of the log file before it is rolled
/// into an archive file in the same directory.
///
/// `backup_count` - Number of archived log files to keep before deleting old
/// logs.
///
/// # Returns
///
/// Full path to opened log file on disk
#[cfg(not(feature = "logging"))]
pub fn create_logger(_filename: &str,
_dir: LogDir,
_max_size_mb: u32,
_backup_count: u32) -> Result<String, FruitError> {
Err(FruitError::GeneralError("Must recompile with 'logging' feature to use logger.".to_string()))
}
| rust | Apache-2.0 | 3fdebfa159a2248dc55def22edd2aedabd1f294c | 2026-01-04T20:23:17.312436Z | false |
mrmekon/fruitbasket | https://github.com/mrmekon/fruitbasket/blob/3fdebfa159a2248dc55def22edd2aedabd1f294c/src/osx.rs | src/osx.rs | //! fruitbasket - Framework for running Rust programs in a Mac 'app bundle' environment.
//!
//! fruitbasket provides two different (but related) services for helping you run your
//! Rust binaries as native AppKit/Cocoa applications on Mac OS X:
//!
//! * App lifecycle and environment API - fruitbasket provides an API to initialize the
//! AppKit application environment (NSApplication), to pump the main application loop
//! and dispatch Apple events in a non-blocking way, to terminate the application, to
//! access resources in the app bundle, and various other tasks frequently needed by
//! Mac applications.
//!
//! * Self-bundling app 'trampoline' - fruitbasket provides a 'trampoline' to
//! automatically bundle a standalone binary as a Mac application in a `.app` bundle
//! at runtime. This allows access to features that require running from a bundle (
//! such as XPC services), self-installing into the Applications folder, registering
//! your app with the system as a document type or URL handler, and various other
//! features that are only available to bundled apps with unique identifiers.
//! Self-bundling and relaunching itself (the "trampoline" behavior) allows your app
//! to get the features of app bundles, but still be launched in the standard Rust
//! ways (such as `cargo run`).
//!
//! The primary goal of fruitbasket is to make it reasonably easy to develop native
//! Mac GUI applications with the standard Apple AppKit/Cocoa/Foundation frameworks
//! in pure Rust by pushing all of the Apple and Objective-C runtime logic into
//! dedicated libraries, isolating the logic of a Rust binary application from the
//! unsafe platform code. As the ecosystem of Mac libraries for Rust grows, you
//! should be able to mix-and-match the libraries your application needs, pump the
//! event loop with fruitbasket, and never worry about Objective-C in your application.
//!
//! # Getting Started
//!
//! You likely want to create either a [Trampoline](struct.Trampoline.html) or a
//! [FruitApp](struct.FruitApp.html) right after your Rust application starts.
//! If uncertain, use a `Trampoline`. You can hit very strange behavior when running
//! Cocoa apps outside of an app bundle.
#![deny(missing_docs)]
// Temporarily (mmmmhmm...) disable deprecated function warnings, because objc macros
// throw tons of them in rustc 1.34-nightly when initializing atomic uints.
#![allow(deprecated)]
use std;
use std::thread;
use std::time::Duration;
use std::path::Path;
use std::path::PathBuf;
use std::io::Write;
use std::cell::Cell;
use std::sync::mpsc::channel;
use std::sync::mpsc::Receiver;
use std::sync::mpsc::Sender;
use std::collections::HashMap;
use super::FruitError;
use super::ActivationPolicy;
use super::RunPeriod;
use super::InstallDir;
use super::FruitStopper;
use super::DEFAULT_PLIST;
use super::FORBIDDEN_PLIST;
extern crate time;
extern crate dirs;
extern crate objc;
use objc::runtime::Object;
use objc::runtime::Class;
extern crate objc_id;
use self::objc_id::Id;
use self::objc_id::WeakId;
use self::objc_id::Shared;
extern crate objc_foundation;
use std::sync::{Once, ONCE_INIT};
use objc::Message;
use objc::declare::ClassDecl;
use objc::runtime::{Sel};
use self::objc_foundation::{INSObject, NSObject};
#[allow(non_upper_case_globals)]
const nil: *mut Object = 0 as *mut Object;
#[link(name = "Foundation", kind = "framework")]
#[link(name = "CoreFoundation", kind = "framework")]
#[link(name = "ApplicationServices", kind = "framework")]
#[link(name = "AppKit", kind = "framework")]
extern {}
/// Main interface for controlling and interacting with the AppKit app
///
/// `FruitApp` is an instance of an AppKit app, equivalent to (and containing)
/// the NSApplication singleton that is responsible for the app's lifecycle
/// and participation in the Mac app ecosystem.
///
/// You must initialize a single instance of FruitApp before using any Apple
/// frameworks, and after creating it you must regularly pump its event loop.
///
/// You must follow all of the standard requirements for NSApplication. Most
/// notably: FruitApp **must** be created on your app's main thread, and **must**
/// be pumped from the same main thread. Doing otherwise angers the beast.
///
/// An application does *not* need to be in a Mac app bundle to run, so this can
/// be created in any application with [FruitApp::new](FruitApp::new). However, many Apple
/// frameworks *do* require the application to be running from a bundle, so you
/// may want to consider creating your FruitApp instance from the [Trampoline](Trampoline)
/// struct's builder instead.
///
pub struct FruitApp<'a> {
app: *mut Object,
pool: Cell<*mut Object>,
run_count: Cell<u64>,
run_mode: *mut Object,
tx: Sender<()>,
rx: Receiver<()>,
objc: Box<ObjcWrapper<'a>>,
}
/// A boxed Fn type for receiving Rust callbacks from ObjC events
pub type FruitObjcCallback<'a> = Box<dyn Fn(*mut Object) + 'a>;
/// Key into the ObjC callback hash map
///
/// You can register to receive callbacks from ObjectiveC based on these keys.
///
/// Callbacks that are not tied to objects can be registered with static
/// selector strings. For instance, if your app has registered itself as a URL
/// handler, you would use:
/// FruitCallbackKey::Method("handleEvent:withReplyEvent:")
///
/// Other pre-defined selectors are:
/// FruitCallbackKey::Method("applicationWillFinishlaunching:")
/// FruitCallbackKey::Method("applicationDidFinishlaunching:")
///
/// The Object variant is currently unused, and reserved for the future.
/// If the callback will be from a particular object, you use the Object type
/// with the ObjC object included. For example, if you want to register for
/// callbacks from a particular NSButton instance, you would add it to the
/// callback map with:
/// let button1: *mut Object = <create an NSButton>;
/// app.register_callback(FruitCallbackKey::Object(button),
/// Box::new(|button1| {
/// println!("got callback from button1, address: {:x}", button1 as u64);
/// }));
///
#[derive(PartialEq, Eq, Hash)]
pub enum FruitCallbackKey {
/// A callback tied to a generic selector
Method(&'static str),
/// A callback from a specific object instance
Object(*mut Object),
}
/// Rust class for wrapping Objective-C callback class
///
/// There is one Objective-C object, implemented in Rust but registered with and
/// owned by the Objective-C runtime, which handles ObjC callbacks such as those
/// for the NSApplication delegate. This is a native Rust class that wraps the
/// ObjC object.
///
/// There should be exactly one of this object, and it must be stored on the
/// heap (i.e. in a Box). This is because the ObjC object calls into this class
/// via raw function pointers, and its address must not change.
///
struct ObjcWrapper<'a> {
objc: Id<ObjcSubclass, Shared>,
map: HashMap<FruitCallbackKey, FruitObjcCallback<'a>>,
}
impl<'a> ObjcWrapper<'a> {
fn take(&mut self) -> Id<ObjcSubclass, Shared> {
let weak = WeakId::new(&self.objc);
weak.load().unwrap()
}
}
/// API to move the executable into a Mac app bundle and relaunch (if necessary)
///
/// `Trampoline` is a builder pattern for creating a `FruitApp` application
/// instance that is guaranteed to be running inside a Mac app bundle. See the
/// module documentation for why this is often important.
///
/// If the currently running process is already in an app bundle, Trampoline
/// does nothing and is equivalent to calling [FruitApp::new](FruitApp::new).
///
/// The builder takes a variety of information that is required for creating a
/// Mac app (notably: app name, executable name, unique identifier), as well
/// as optional metadata to describe your app and its interactions to the OS,
/// and optional file resources to bundle with it. It creates an app bundle,
/// either in an install path of your choosing or in a temporary directory,
/// launches the bundled app, and terminates the non-bundled binary.
///
/// Care should be taken to call this very early in your application, since any
/// work done prior to this will be discarded when the app is relaunched. Your
/// program should also gracefully support relaunching from a different directory.
/// Take care not to perform any actions that would prevent relaunching, such as
/// claiming locks, until after the trampoline.
///
#[derive(Default)]
pub struct Trampoline {
name: String,
exe: String,
ident: String,
icon: String,
version: String,
keys: Vec<(String,String)>,
plist_raw_strings: Vec<String>,
resources: Vec<String>,
hidpi: bool,
}
impl Trampoline {
/// Creates a new Trampoline builder to build a Mac app bundle
///
/// This creates a new Trampoline builder, which takes the information
/// required to construct a Mac `.app` bundle. If your application
/// is already running in a bundle, the builder does not create a bundle
/// and simply returns a newly constructed `FruitApp` object with the Mac
/// application environment initialized. If your application is not in
/// a bundle, a new bundle is created and launched, and your program's
/// current process is killed.
///
/// # Arguments
///
/// `name` - Name for your Mac application. This is what is displayed
/// in the dock and the menu bar.
///
/// `exe` - Name for the executable file in your application. This is the
/// name of the process that executes, and what appears in `ps` or Activity
/// Monitor.
///
/// `ident` - Unique application identifier for your app. This should be
/// in the reverse DNS format (ex: `com.company.AppName`), and must contain
/// only alpha-numerics, `-`, and `.` characters. It can be used to
/// register your app as a system-wide handler for documents and URIs, and
/// is used when code signing your app for distribution.
///
/// # Returns
///
/// A newly constructed Trampoline builder.
pub fn new(name: &str, exe: &str, ident: &str) -> Trampoline {
Trampoline {
name: name.to_string(),
exe: exe.to_string(),
ident: ident.to_string(),
version: "1.0.0".to_string(),
hidpi: true,
..
Default::default()
}
}
/// Set name of application. Same as provided to `new()`.
pub fn name(&mut self, name: &str) -> &mut Self {
self.name = name.to_string();
self
}
/// Set name of executable. Same as provided to `new()`.
pub fn exe(&mut self, exe: &str) -> &mut Self {
self.exe = exe.to_string();
self
}
/// Set app bundle ID. Same as provided to `new()`.
pub fn ident(&mut self, ident: &str) -> &mut Self {
self.ident = ident.to_string();
self
}
/// Set bundle icon file.
///
/// This is the name of the icon file in the Resources directory. It should
/// be just the file name, without a path. OS X uses this icon file for the
/// icon displayed in the Dock when your application is running, and the
/// icon that appears next to it in Finder and the Application list.
///
/// Icons are typically provided in a multi-icon set file in the `.icns`
/// format.
///
/// It is optional, but strongly recommended for apps that will be
/// distributed to end users.
pub fn icon(&mut self, icon: &str) -> &mut Self {
self.icon = icon.to_string();
self
}
/// Set the bundle version.
///
/// This sets the version number in the app bundle. It is optional, and
/// defaults to "1.0.0" if not provided.
pub fn version(&mut self, version: &str) -> &mut Self {
self.version = version.to_string();
self
}
/// Set an arbitrary key/value pair in the Info.plist
///
/// Bundles support specifying a large variety of configuration options in
/// their Property List files, many of which are only needed for specific
/// use cases. This function lets you specify any arbitrary key/value
/// pair that your application might need.
///
/// Note that some keys are provided with a default value if not specified,
/// and a few keys are always configured by the `Trampoline` builder and
/// cannot be overridden with this function.
///
/// `Trampoline` creates Info.plist files in the "old-style" OpenStep format.
/// Be sure to format your values appropriately for this style. Read up on
/// [Old-Style ASCII Property Lists](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html). You can also verify your
/// formatting by creating a simple `test.plist` with your key/value pairs
/// in it, surround the entire file in braces (`{` and `}`), and then run
/// `plutil test.plist` to validate the formatting.
///
/// See the [Apple documentation](https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Introduction/Introduction.html#//apple_ref/doc/uid/TP40009247)
/// on Info.plist keys for options.
///
/// # Arguments
///
/// `key` - Property List key to set (ex: `CFBundleURLTypes`)
///
/// `value` - Value for the key, in JSON format. You must provide quote
/// characters yourself for any values that require quoted strings. Format
/// in "old-style" OpenStep plist format.
pub fn plist_key(&mut self, key: &str, value: &str) -> &mut Self {
self.keys.push((key.to_string(), value.to_string()));
self
}
/// Set multiple arbitrary key/value pairs in the Info.plist
///
/// See documentation of [plist_key()](Trampoline::plist_key). This function does the same, but
/// allows specifying more than one key/value pair at a time.
pub fn plist_keys(&mut self, pairs: &Vec<(&str,&str)>) -> &mut Self {
for &(ref key, ref value) in pairs {
self.keys.push((key.to_string(), value.to_string()));
}
self
}
/// Sets whether fruitbasket should add properties to the generated plist
/// to tell macOS that this application supports high resolution displays.
///
/// This option is true by default. A bit of backstory follows.
///
/// ---
///
/// macOS, by default, runs apps in a low-resolution mode if they are
/// in a bundle that does not specify that it supports Retina displays. This
/// causes them to look blurry on Retina displays, not crisp like the rest
/// of macOS.
///
/// You may not have noticed this behavior when running GUI applications as
/// bare binaries, where it does not apply (macOS does not run binaries in
/// low-resolution mode). However, the Trampoline is different because it
/// automatically bundles the binary, which opens up the application to this
/// kind of legacy behavior.
///
/// Historically, it was done for backwards compatibility, because when the
/// Retina screen came out in 2012, not all applications supported it.
/// Indeed, some programs even today don't support it either, which is why
/// this behavior remains. However, most GUI facilities like Qt, GTK and
/// libui support Retina just fine, and don't need macOS to sandbox them
/// into this low resolution mode. (libui doesn't even need to do anything
/// special; they use AppKit directly, which has always supported Retina.)
///
/// Applications that wish to indicate that they *do* support Retina
/// displays have to specify two properties in their Info.plist:
/// - Set `NSPrincipalClass` to something. (`"NSApplication"` is a useful
/// default, but it's unknown what the significance of this property is.
/// fruitbasket uses `"NSApplication"`.)
/// - Set `NSHighResolutionCapable` to `True`.
///
/// After this is done, macOS will run the app at full resolution and trust
/// it to scale its UI to match the scale factor of the resolution being
/// used. On most displays, it is 2 by default, but macOS supports both
/// larger and also non-integer scale factors.
///
/// Sometimes you have to do this manually, such as when you are rendering
/// into a framebuffer, and sometimes you don't, like when you are using a
/// GUI toolkit. Usually, programmers can expect their libraries to support
/// this natively and that is why this option is enabled by default.
///
/// Older versions of fruitbasket did not apply these changes by default,
/// which meant in the best case the developer had to look online for a
/// solution, and in the worst case apps built using fruitbasket ran in
/// low resolution (ouch!). It is my hope that this new default will help
/// both new and experienced developers alike, even though it is a somewhat
/// simple change.
pub fn retina(&mut self, doit: bool) -> &mut Self {
self.hidpi = doit;
self
}
/// Add a 'raw', preformatted string to Info.plist
///
/// Pastes a raw, unedited string into the Info.plist file. This is
/// dangerous, and should be used with care. Use this for adding nested
/// structures, such as when registering URI schemes.
///
/// *MUST* be in the JSON plist format. If coming from XML format, you can
/// use `plutil -convert json -r Info.plist` to convert.
///
/// Take care not to override any of the keys in [FORBIDDEN_PLIST](FORBIDDEN_PLIST)
/// unless you really know what you are doing.
pub fn plist_raw_string(&mut self, s: String) -> &mut Self {
self.plist_raw_strings.push(s);
self
}
/// Add file to Resources directory of app bundle
///
/// Specify full path to a file to copy into the Resources directory of the
/// generated app bundle. Resources can be any sort of file, and are copied
/// around with the app when it is moved. The app can easily access any
/// file in its resources at runtime, even when running in sandboxed
/// environments.
///
/// The most common bundled resources are icons.
///
/// # Arguments
///
/// `file` - Full path to file to include
pub fn resource(&mut self, file: &str) -> &mut Self {
self.resources.push(file.to_string());
self
}
/// Add multiple files to Resources directory of app bundle
///
/// See documentation of [resource()](Trampoline::resource). This function does the same, but
/// allows specifying more than one resource at a time.
pub fn resources(&mut self, files: &Vec<&str>) -> &mut Self{
for file in files {
self.resources.push(file.to_string());
}
self
}
/// Finishes building and launching the app bundle
///
/// This builds and executes the "trampoline", meaning it is a highly
/// destructive action. A Mac app bundle will be created on disk if the
/// program is not already executing from one, the new bundle will be
/// launched as a new process, and the currently executing process will
/// be terminated.
///
/// The behavior, when used as intended, is similar to `fork()` (except
/// the child starts over from `main()` instead of continuing from the
/// same instruction, and the parent dies). The parent dies immediately,
/// the child relaunches, re-runs the `Trampoline` builder, but this time
/// it returns an initialized `FruitApp`.
///
/// **WARNING**: the parent process is terminated with `exit(0)`, which
/// does not Drop your Rust allocations. This should always be called as
/// early as possible in your program, before any allocations or locking.
///
/// # Arguments
///
/// `dir` - Directory to create app bundle in (if one is created)
///
/// # Returns
///
/// * Result<_, FruitError> if not running in a bundle and a new bundle
/// could not be created.
/// * Result<_, FruitError> if running in a bundle but the Mac app
/// environment could not be initialized.
/// * Terminates the process if not running in a Mac app bundle and a new
/// bundle was successfully created.
/// * Result<FruitApp, _> if running in a Mac bundle (either when launched
/// from one initially, or successfully re-launched by `Trampoline`)
/// containing the initialized app environment,
pub fn build<'a>(&mut self, dir: InstallDir) -> Result<FruitApp<'a>, FruitError> {
self.self_bundle(dir)?; // terminates this process if not bundled
info!("Process is bundled. Continuing.");
Ok(FruitApp::new())
}
/// Returns whether the current process is running from a Mac app bundle
pub fn is_bundled() -> bool {
unsafe {
let cls = Class::get("NSBundle").unwrap();
let bundle: *mut Object = msg_send![cls, mainBundle];
let ident: *mut Object = msg_send![bundle, bundleIdentifier];
ident != nil
}
}
/// Same as `build`, but does not construct a FruitApp if successful.
///
/// Useful if you'd like to use a GUI library, such as libui, and don't
/// want fruitbasket to try to initialize anything for you. Bundling only.
pub fn self_bundle(&self, dir: InstallDir) -> Result<(), FruitError> {
unsafe {
if Self::is_bundled() {
return Ok(());
}
info!("Process not bundled. Self-bundling and relaunching.");
let install_dir: PathBuf = match dir {
InstallDir::Temp => std::env::temp_dir(),
InstallDir::SystemApplications => PathBuf::from("/Applications/"),
InstallDir::UserApplications => dirs::home_dir().unwrap().join("Applications/"),
InstallDir::Custom(dir) => std::fs::canonicalize(PathBuf::from(dir))?,
};
info!("Install dir: {:?}", install_dir);
let bundle_dir = Path::new(&install_dir).join(&format!("{}.app", self.name));
info!("Bundle dir: {:?}", bundle_dir);
let contents_dir = Path::new(&bundle_dir).join("Contents");
let macos_dir = contents_dir.clone().join("MacOS");
let resources_dir = contents_dir.clone().join("Resources");
let plist = contents_dir.clone().join("Info.plist");
let src_exe = std::env::current_exe()?;
info!("Current exe: {:?}", src_exe);
let dst_exe = macos_dir.clone().join(&self.exe);
let _ = std::fs::remove_dir_all(&bundle_dir); // ignore errors
std::fs::create_dir_all(&macos_dir)?;
std::fs::create_dir_all(&resources_dir)?;
info!("Copy {:?} to {:?}", src_exe, dst_exe);
std::fs::copy(src_exe, dst_exe)?;
for file in &self.resources {
let file = Path::new(file);
if let Some(filename) = file.file_name() {
let dst = resources_dir.clone().join(filename);
info!("Copy {:?} to {:?}", file, dst);
std::fs::copy(file, dst)?;
}
}
// Write Info.plist
let mut f = std::fs::File::create(&plist)?;
// Mandatory fields
write!(&mut f, "{{\n")?;
write!(&mut f, " CFBundleName = \"{}\";\n", self.name)?;
write!(&mut f, " CFBundleDisplayName = \"{}\";\n", self.name)?;
write!(&mut f, " CFBundleIdentifier = \"{}\";\n", self.ident)?;
write!(&mut f, " CFBundleExecutable = \"{}\";\n", self.exe)?;
write!(&mut f, " CFBundleIconFile = \"{}\";\n", self.icon)?;
write!(&mut f, " CFBundleVersion = \"{}\";\n", self.version)?;
// HiDPI fields
if self.hidpi {
write!(&mut f, " NSPrincipalClass = \"NSApplication\";\n")?;
write!(&mut f, " NSHighResolutionCapable = True;\n")?;
}
// User-supplied fields
for &(ref key, ref val) in &self.keys {
if !FORBIDDEN_PLIST.contains(&key.as_str()) {
write!(&mut f, " {} = {};\n", key, val)?;
}
}
// Default fields (if user didn't override)
let keys: Vec<&str> = self.keys.iter().map(|x| {x.0.as_ref()}).collect();
for &(ref key, ref val) in DEFAULT_PLIST {
if !keys.contains(key) {
write!(&mut f, " {} = {};\n", key, val)?;
}
}
// Write raw plist fields
for raw in &self.plist_raw_strings {
write!(&mut f, "{}\n", raw)?;
}
write!(&mut f, "}}\n")?;
// Launch newly created bundle
let cls = Class::get("NSWorkspace").unwrap();
let wspace: *mut Object = msg_send![cls, sharedWorkspace];
let cls = Class::get("NSString").unwrap();
let app = bundle_dir.to_str().unwrap();
info!("Launching: {}", app);
let s: *mut Object = msg_send![cls, alloc];
let s: *mut Object = msg_send![s,
initWithBytes:app.as_ptr()
length:app.len()
encoding: 4]; // UTF8_ENCODING
let _:() = msg_send![wspace, launchApplication: s];
// Note: launchedApplication doesn't return until the child process
// calls [NSApplication sharedApplication].
info!("Parent process exited.");
std::process::exit(0);
}
}
}
impl<'a> FruitApp<'a> {
/// Initialize the Apple app environment
///
/// Initializes the NSApplication singleton that initializes the Mac app
/// environment and creates a memory pool for Objective-C allocations on
/// the main thread.
///
/// # Returns
///
/// A newly allocated FruitApp for managing the app
pub fn new() -> FruitApp<'a> {
let (tx,rx) = channel::<()>();
unsafe {
let cls = Class::get("NSApplication").unwrap();
let app: *mut Object = msg_send![cls, sharedApplication];
let cls = Class::get("NSAutoreleasePool").unwrap();
let pool: *mut Object = msg_send![cls, alloc];
let pool: *mut Object = msg_send![pool, init];
let cls = Class::get("NSString").unwrap();
let rust_runmode = "kCFRunLoopDefaultMode";
let run_mode: *mut Object = msg_send![cls, alloc];
let run_mode: *mut Object = msg_send![run_mode,
initWithBytes:rust_runmode.as_ptr()
length:rust_runmode.len()
encoding: 4]; // UTF8_ENCODING
let objc = ObjcSubclass::new().share();
let rustobjc = Box::new(ObjcWrapper {
objc: objc,
map: HashMap::new(),
});
let ptr: u64 = &*rustobjc as *const ObjcWrapper as u64;
let _:() = msg_send![rustobjc.objc, setRustWrapper: ptr];
FruitApp {
app: app,
pool: Cell::new(pool),
run_count: Cell::new(0),
run_mode: run_mode,
tx: tx,
rx: rx,
objc: rustobjc,
}
}
}
/// Register to receive a callback when the ObjC runtime raises one
///
/// ObjCCallbackKey is used to specify the source of the callback, which
/// must be something registered with the ObjC runtime.
///
pub fn register_callback(&mut self, key: FruitCallbackKey, cb: FruitObjcCallback<'a>) {
let _ = self.objc.map.insert(key, cb);
}
/// Register application to receive Apple events of the given type
///
/// Register with the underlying NSAppleEventManager so this application gets
/// events matching the given Class/ID tuple. This causes the internal ObjC
/// delegate to receive `handleEvent:withReplyEvent:` messages when the
/// specified event is sent to your application.
///
/// This registers the event to be received internally. To receive it in
/// your code, you must use [register_callback](FruitApp::register_callback) to listen for the
/// selector by specifying key:
///
/// `FruitCallbackKey::Method("handleEvent:withReplyEvent:")`
///
pub fn register_apple_event(&mut self, class: u32, id: u32) {
unsafe {
let cls = Class::get("NSAppleEventManager").unwrap();
let manager: *mut Object = msg_send![cls, sharedAppleEventManager];
let objc = (*self.objc).take();
let _:() = msg_send![manager,
setEventHandler: objc
andSelector: sel!(handleEvent:withReplyEvent:)
forEventClass: class
andEventID: id];
}
}
/// Set the app "activation policy" controlling what UI it does/can present.
pub fn set_activation_policy(&self, policy: ActivationPolicy) {
let policy_int = match policy {
ActivationPolicy::Regular => 0,
ActivationPolicy::Accessory => 1,
ActivationPolicy::Prohibited => 2,
};
unsafe {
let _:() = msg_send![self.app, setActivationPolicy: policy_int];
}
}
/// Cleanly terminate the application
///
/// Terminates a running application and its event loop, and terminates the
/// process. This function does not return, so perform any required cleanup
/// of your Rust application before calling it.
///
/// You should call this at the end of your program instead of simply exiting
/// from `main()` to ensure that OS X knows your application has quit cleanly
/// and can immediately inform any subsystems that are monitoring it.
///
/// This can be called from any thread.
///
/// # Arguments
///
/// `exit_code` - Application exit code. '0' is success.
pub fn terminate(exit_code: i32) {
unsafe {
let cls = objc::runtime::Class::get("NSApplication").unwrap();
let app: *mut objc::runtime::Object = msg_send![cls, sharedApplication];
let _:() = msg_send![app, terminate: exit_code];
}
}
/// Stop the running app run loop
///
/// If the run loop is running (`run()`), this stops it after the next event
/// finishes processing. It does not quit or terminate anything, and the
/// run loop can be continued later. This can be used from callbacks to
/// interrupt a run loop running in 'Forever' mode and return control back
/// to Rust's main thread.
///
/// This can be called from any thread.
///
/// # Arguments
///
/// `stopper` - A thread-safe `FruitStopper` object returned by `stopper()`
pub fn stop(stopper: &FruitStopper) {
stopper.stop();
}
/// Runs the main application event loop
///
/// The application's event loop must be run frequently to dispatch all
/// events generated by the Apple frameworks to their destinations and keep
/// the UI updated. Take care to keep this running frequently, as any
/// delays will cause the UI to hang and cause latency on other internal
/// operations.
///
/// # Arguments
///
/// `period` - How long to run the event loop before returning
///
/// # Returns
///
/// Ok on natural end, Err if stopped by a Stopper.
pub fn run(&mut self, period: RunPeriod) -> Result<(),()>{
let start = time::now_utc().to_timespec();
loop {
if self.rx.try_recv().is_ok() {
return Err(());
}
unsafe {
let run_count = self.run_count.get();
if run_count == 0 {
let cls = objc::runtime::Class::get("NSApplication").unwrap();
let app: *mut objc::runtime::Object = msg_send![cls, sharedApplication];
let objc = (*self.objc).take();
let _:() = msg_send![app, setDelegate: objc];
let _:() = msg_send![self.app, finishLaunching];
}
// Create a new release pool every once in a while, draining the old one
if run_count % 100 == 0 {
| rust | Apache-2.0 | 3fdebfa159a2248dc55def22edd2aedabd1f294c | 2026-01-04T20:23:17.312436Z | true |
mrmekon/fruitbasket | https://github.com/mrmekon/fruitbasket/blob/3fdebfa159a2248dc55def22edd2aedabd1f294c/examples/example.rs | examples/example.rs | extern crate fruitbasket;
use fruitbasket::ActivationPolicy;
use fruitbasket::Trampoline;
use fruitbasket::FruitApp;
use fruitbasket::InstallDir;
use fruitbasket::RunPeriod;
use fruitbasket::FruitError;
use std::time::Duration;
use std::path::PathBuf;
#[macro_use]
extern crate log;
fn main() {
let _ = fruitbasket::create_logger(".fruitbasket.log", fruitbasket::LogDir::Home, 5, 2).unwrap();
// Find the icon file from the Cargo project dir
let icon = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("examples").join("icon.png");
// Re-launch self in an app bundle if not already running from one.
info!("Executable must run from App bundle. Let's try:");
let mut app = match Trampoline::new("fruitbasket", "fruitbasket", "com.trevorbentley.fruitbasket")
.version("2.1.3")
.icon("fruitbasket.icns")
.plist_key("CFBundleSpokenName","\"fruit basket\"")
.plist_keys(&vec![
("LSMinimumSystemVersion", "10.12.0"),
("LSBackgroundOnly", "1"),
])
.resource(icon.to_str().unwrap())
.build(InstallDir::Temp) {
Err(FruitError::UnsupportedPlatform(_)) => {
info!("This is not a Mac. App bundling is not supported.");
info!("It is still safe to use FruitApp::new(), though the dummy app will do nothing.");
FruitApp::new()
},
Err(FruitError::IOError(e)) => {
info!("IO error! {}", e);
std::process::exit(1);
},
Err(FruitError::GeneralError(e)) => {
info!("General error! {}", e);
std::process::exit(1);
},
Ok(app) => app,
};
// App is guaranteed to be running in a bundle now!
// Make it a regular app in the dock.
// Note: Because 'LSBackgroundOnly' is set to true in the Info.plist, the
// app will launch backgrounded and will not take focus. If we only did
// that, the app would stay in 'Prohibited' mode and would not create a dock
// icon. By overriding the activation policy now, it will stay background
// but create the Dock and menu bar entries. This basically implements a
// "pop-under" behavior.
app.set_activation_policy(ActivationPolicy::Regular);
// Give it a bit of time for the launching process to quit, to prove that
// the bundled process is not a dependent child of the un-bundled process.
info!("Spawned process started. Sleeping for a bit...");
let _ = app.run(RunPeriod::Time(Duration::from_secs(1)));
// Demonstrate stopping an infinite run loop from another thread.
let stopper = app.stopper();
let _ = std::thread::spawn(move || {
std::thread::sleep(Duration::from_secs(4));
info!("Stopping run loop.");
fruitbasket::FruitApp::stop(&stopper);
});
// Run 'forever', until the other thread interrupts.
info!("Spawned process running!");
let _ = app.run(RunPeriod::Forever);
info!("Run loop stopped from other thread.");
// Find the icon we stored in the bundle
let icon = fruitbasket::FruitApp::bundled_resource_path("icon", "png");
info!("Bundled icon: {}", icon.unwrap_or("MISSING!".to_string()));
// Cleanly terminate
fruitbasket::FruitApp::terminate(0);
info!("This will not print.");
}
| rust | Apache-2.0 | 3fdebfa159a2248dc55def22edd2aedabd1f294c | 2026-01-04T20:23:17.312436Z | false |
mrmekon/fruitbasket | https://github.com/mrmekon/fruitbasket/blob/3fdebfa159a2248dc55def22edd2aedabd1f294c/examples/register_url.rs | examples/register_url.rs | /// Example that launches as Mac App with custom URL scheme handler
///
/// In one terminal, build and run:
///
/// $ cargo build --features=logging --examples
/// $ ./target/debug/examples/register_url && tail -f ~/.fruitbasket_register_url.log
///
/// In a second terminal, open custom URL:
///
/// $ open fruitbasket://test
///
/// Log output will show that the example has received and printed the custom URL.
///
extern crate fruitbasket;
use fruitbasket::ActivationPolicy;
use fruitbasket::Trampoline;
use fruitbasket::FruitApp;
use fruitbasket::InstallDir;
use fruitbasket::RunPeriod;
use fruitbasket::FruitError;
use fruitbasket::FruitCallbackKey;
use std::path::PathBuf;
#[macro_use]
extern crate log;
fn main() {
let _ = fruitbasket::create_logger(".fruitbasket_register_url.log", fruitbasket::LogDir::Home, 5, 2).unwrap();
// Find the icon file from the Cargo project dir
let icon = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("examples").join("icon.png");
// Re-launch self in an app bundle if not already running from one.
info!("Executable must run from App bundle. Let's try:");
let mut app = match Trampoline::new("fruitbasket_register_url", "fruitbasket", "com.trevorbentley.fruitbasket_register_url")
.version("2.1.3")
.icon("fruitbasket.icns")
.plist_key("CFBundleSpokenName","\"fruit basket\"")
.plist_keys(&vec![
("LSMinimumSystemVersion", "10.12.0"),
("LSBackgroundOnly", "1"),
])
// Register "fruitbasket://" and "fbasket://" URL schemes in Info.plist
.plist_raw_string("
CFBundleURLTypes = ( {
CFBundleTypeRole = \"Viewer\";
CFBundleURLName = \"Fruitbasket Example URL\";
CFBundleURLSchemes = (\"fruitbasket\", \"fbasket\");
} );\n".into())
.resource(icon.to_str().unwrap())
.build(InstallDir::Temp) {
Err(FruitError::UnsupportedPlatform(_)) => {
info!("This is not a Mac. App bundling is not supported.");
info!("It is still safe to use FruitApp::new(), though the dummy app will do nothing.");
FruitApp::new()
},
Err(FruitError::IOError(e)) => {
info!("IO error! {}", e);
std::process::exit(1);
},
Err(FruitError::GeneralError(e)) => {
info!("General error! {}", e);
std::process::exit(1);
},
Ok(app) => app,
};
// App is guaranteed to be running in a bundle now!
// Make it a regular app in the dock.
// Note: Because 'LSBackgroundOnly' is set to true in the Info.plist, the
// app will launch backgrounded and will not take focus. If we only did
// that, the app would stay in 'Prohibited' mode and would not create a dock
// icon. By overriding the activation policy now, it will stay background
// but create the Dock and menu bar entries. This basically implements a
// "pop-under" behavior.
app.set_activation_policy(ActivationPolicy::Regular);
// Register a callback for when the ObjC application finishes launching
let stopper = app.stopper();
app.register_callback(FruitCallbackKey::Method("applicationWillFinishLaunching:"),
Box::new(move |_event| {
info!("applicationDidFinishLaunching.");
stopper.stop();
}));
// Run until callback is called
info!("Spawned process started. Run until applicationDidFinishLaunching.");
let _ = app.run(RunPeriod::Forever);
info!("Application launched. Registering URL callbacks.");
// Register a callback to get receive custom URL schemes from any Mac program
app.register_apple_event(fruitbasket::kInternetEventClass, fruitbasket::kAEGetURL);
let stopper = app.stopper();
app.register_callback(FruitCallbackKey::Method("handleEvent:withReplyEvent:"),
Box::new(move |event| {
// Event is a raw NSAppleEventDescriptor.
// Fruitbasket has a parser for URLs. Call that to get the URL:
let url: String = fruitbasket::parse_url_event(event);
info!("Received URL: {}", url);
stopper.stop();
}));
let stopper = app.stopper();
app.register_callback(
FruitCallbackKey::Method("application:openFile:"),
Box::new(move |file| {
// File is a raw NSString.
// Fruitbasket has a converter to Rust String:
let file: String = fruitbasket::nsstring_to_string(file);
info!("Received file: {}", file);
stopper.stop();
}),
);
// Run 'forever', until one of the URL or file callbacks fire
info!("Spawned process running!");
let _ = app.run(RunPeriod::Forever);
info!("Run loop stopped after URL callback.");
// Cleanly terminate
fruitbasket::FruitApp::terminate(0);
info!("This will not print.");
}
| rust | Apache-2.0 | 3fdebfa159a2248dc55def22edd2aedabd1f294c | 2026-01-04T20:23:17.312436Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/udc.rs | src/udc.rs | //! USB device controller (UDC).
use std::{
ffi::{OsStr, OsString},
fmt, fs,
io::{Error, ErrorKind, Result},
os::unix::prelude::OsStringExt,
path::{Path, PathBuf},
};
use crate::{trim_os_str, Speed};
/// USB device controller (UDC).
///
/// Call [`udcs`] to obtain the controllers available on the system.
#[derive(Clone)]
pub struct Udc {
dir: PathBuf,
}
impl fmt::Debug for Udc {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Udc").field("name", &self.name()).finish()
}
}
impl Udc {
/// The name of the USB device controller.
pub fn name(&self) -> &OsStr {
self.dir.file_name().unwrap()
}
/// Indicates if an OTG A-Host supports HNP at an alternate port.
pub fn a_alt_hnp_support(&self) -> Result<bool> {
Ok(fs::read_to_string(self.dir.join("a_alt_hnp_support"))?.trim() != "0")
}
/// Indicates if an OTG A-Host supports HNP at this port.
pub fn a_hnp_support(&self) -> Result<bool> {
Ok(fs::read_to_string(self.dir.join("a_hnp_support"))?.trim() != "0")
}
/// Indicates if an OTG A-Host enabled HNP support.
pub fn b_hnp_enable(&self) -> Result<bool> {
Ok(fs::read_to_string(self.dir.join("b_hnp_enable"))?.trim() != "0")
}
/// Indicates the current negotiated speed at this port.
///
/// `None` if unknown.
pub fn current_speed(&self) -> Result<Speed> {
Ok(fs::read_to_string(self.dir.join("current_speed"))?.trim().parse().unwrap_or_default())
}
/// Indicates the maximum USB speed supported by this port.
pub fn max_speed(&self) -> Result<Speed> {
Ok(fs::read_to_string(self.dir.join("maximum_speed"))?.trim().parse().unwrap_or_default())
}
/// Indicates that this port is the default Host on an OTG session but HNP was used to switch
/// roles.
pub fn is_a_peripheral(&self) -> Result<bool> {
Ok(fs::read_to_string(self.dir.join("is_a_peripheral"))?.trim() != "0")
}
/// Indicates that this port support OTG.
pub fn is_otg(&self) -> Result<bool> {
Ok(fs::read_to_string(self.dir.join("is_otg"))?.trim() != "0")
}
/// Indicates current state of the USB Device Controller.
///
/// However not all USB Device Controllers support reporting all states.
pub fn state(&self) -> Result<UdcState> {
Ok(fs::read_to_string(self.dir.join("state"))?.trim().parse().unwrap_or_default())
}
/// Manually start Session Request Protocol (SRP).
pub fn start_srp(&self) -> Result<()> {
fs::write(self.dir.join("srp"), "1")
}
/// Connect or disconnect data pull-up resistors thus causing a logical connection to or
/// disconnection from the USB host.
pub fn set_soft_connect(&self, connect: bool) -> Result<()> {
fs::write(self.dir.join("soft_connect"), if connect { "connect" } else { "disconnect" })
}
/// Name of currently running USB Gadget Driver.
pub fn function(&self) -> Result<Option<OsString>> {
let data = OsString::from_vec(fs::read(self.dir.join("function"))?);
let data = trim_os_str(&data);
if data.is_empty() {
Ok(None)
} else {
Ok(Some(data.to_os_string()))
}
}
}
/// USB device controller (UDC) connection state.
#[derive(
Default, Debug, strum::Display, strum::EnumString, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
#[non_exhaustive]
pub enum UdcState {
/// Not attached.
#[strum(serialize = "not attached")]
NotAttached,
/// Attached.
#[strum(serialize = "attached")]
Attached,
/// Powered.
#[strum(serialize = "powered")]
Powered,
/// Reconnecting.
#[strum(serialize = "reconnecting")]
Reconnecting,
/// Unauthenticated.
#[strum(serialize = "unauthenticated")]
Unauthenticated,
/// Default.
#[strum(serialize = "default")]
Default,
/// Addressed.
#[strum(serialize = "addressed")]
Addressed,
/// Configured.
#[strum(serialize = "configured")]
Configured,
/// Suspended.
#[strum(serialize = "suspended")]
Suspended,
/// Unknown state.
#[default]
#[strum(serialize = "UNKNOWN")]
Unknown,
}
/// Gets the available USB device controllers (UDCs) in the system.
pub fn udcs() -> Result<Vec<Udc>> {
let class_dir = Path::new("/sys/class");
if !class_dir.is_dir() {
return Err(Error::new(ErrorKind::NotFound, "sysfs is not available"));
}
let udc_dir = class_dir.join("udc");
if !udc_dir.is_dir() {
return Ok(Vec::new());
}
let mut udcs = Vec::new();
for entry in fs::read_dir(&udc_dir)? {
let Ok(entry) = entry else { continue };
udcs.push(Udc { dir: entry.path() });
}
Ok(udcs)
}
/// The default USB device controller (UDC) in the system by alphabetical sorting.
///
/// A not found error is returned if no UDC is present.
pub fn default_udc() -> Result<Udc> {
let mut udcs = udcs()?;
udcs.sort_by_key(|udc| udc.name().to_os_string());
udcs.into_iter()
.next()
.ok_or_else(|| Error::new(ErrorKind::NotFound, "no USB device controller (UDC) available"))
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/lib.rs | src/lib.rs | //! This library allows implementation of USB peripherals, so called **USB gadgets**,
//! on Linux devices that have a USB device controller (UDC).
//! Both, pre-defined USB functions and fully custom implementations of the USB
//! interface are supported.
//!
//! ### Requirements
//!
//! A USB device controller (UDC) supported by Linux is required.
//!
//! The Linux kernel configuration options `CONFIG_USB_GADGET` and `CONFIG_USB_CONFIGFS`
//! need to be enabled.
//!
//! root permissions are required to configure USB gadgets and
//! the `configfs` filesystem needs to be mounted.
//!
//! ### Usage
//!
//! Start defining an USB gadget by calling [`Gadget::new`].
//! When the gadget is fully specified, call [`Gadget::bind`] to register it with
//! a [USB device controller (UDC)](Udc).
#![warn(missing_docs)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#[cfg(not(target_os = "linux"))]
compile_error!("usb_gadget only supports Linux");
use proc_mounts::MountIter;
use std::{
ffi::{CStr, OsStr},
io::{Error, ErrorKind, Result},
os::unix::prelude::OsStrExt,
path::PathBuf,
process::Command,
sync::OnceLock,
};
pub mod function;
mod gadget;
pub use gadget::*;
mod udc;
pub use udc::*;
mod lang;
pub use lang::*;
/// USB speed.
#[derive(
Default, Debug, strum::Display, strum::EnumString, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
#[non_exhaustive]
pub enum Speed {
/// USB 3.1: 10 Gbit/s.
#[strum(serialize = "super-speed-plus")]
SuperSpeedPlus,
/// USB 3.0: 5 Gbit/s.
#[strum(serialize = "super-speed")]
SuperSpeed,
/// USB 2.0: 480 Mbit/s.
#[strum(serialize = "high-speed")]
HighSpeed,
/// USB 1.0: 12 Mbit/s.
#[strum(serialize = "full-speed")]
FullSpeed,
/// USB 1.0: 1.5 Mbit/s.
#[strum(serialize = "low-speed")]
LowSpeed,
/// Unknown speed.
#[default]
#[strum(serialize = "UNKNOWN")]
Unknown,
}
/// 8-bit value to hexadecimal notation.
fn hex_u8(value: u8) -> String {
format!("0x{:02x}", value)
}
/// 16-bit value to hexadecimal notation.
fn hex_u16(value: u16) -> String {
format!("0x{:04x}", value)
}
/// Returns where configfs is mounted.
fn configfs_dir() -> Result<PathBuf> {
for mount in MountIter::new()? {
let Ok(mount) = mount else { continue };
if mount.fstype == "configfs" {
return Ok(mount.dest);
}
}
Err(Error::new(ErrorKind::NotFound, "configfs is not mounted"))
}
/// Trims an OsStr.
fn trim_os_str(value: &OsStr) -> &OsStr {
let mut value = value.as_bytes();
while value.first() == Some(&b'\n') || value.first() == Some(&b' ') || value.first() == Some(&b'\0') {
value = &value[1..];
}
while value.last() == Some(&b'\n') || value.last() == Some(&b' ') || value.last() == Some(&b'\0') {
value = &value[..value.len() - 1];
}
OsStr::from_bytes(value)
}
/// Request a kernel module to be loaded.
fn request_module(name: impl AsRef<OsStr>) -> Result<()> {
let mut res = Command::new("modprobe").arg("-q").arg(name.as_ref()).output();
match res {
Err(err) if err.kind() == ErrorKind::NotFound => {
res = Command::new("/sbin/modprobe").arg("-q").arg(name.as_ref()).output();
}
_ => (),
}
match res {
Ok(out) if out.status.success() => Ok(()),
Ok(_) => Err(Error::new(ErrorKind::Other, "modprobe failed")),
Err(err) => Err(err),
}
}
/// Gets the Linux kernel version.
fn linux_version() -> Option<(u16, u16)> {
static VERSION: OnceLock<Result<(u16, u16)>> = OnceLock::new();
let version = VERSION.get_or_init(|| {
let mut uts = libc::utsname {
sysname: [0; 65],
nodename: [0; 65],
release: [0; 65],
version: [0; 65],
machine: [0; 65],
domainname: [0; 65],
};
if unsafe { libc::uname(&mut uts) } == -1 {
return Err(Error::last_os_error());
}
let release = unsafe { CStr::from_ptr(uts.release.as_ptr() as *const _) }
.to_str()
.map_err(|_| Error::new(ErrorKind::InvalidData, "invalid release string"))?;
let parts: Vec<&str> = release.split('.').collect();
if parts.len() < 2 {
return Err(Error::new(ErrorKind::InvalidData, "invalid kernel version"));
}
let major = parts[0].parse().map_err(|e| Error::new(ErrorKind::InvalidData, e))?;
let minor = parts[1].parse().map_err(|e| Error::new(ErrorKind::InvalidData, e))?;
Ok((major, minor))
});
match version {
Ok(version) => Some(*version),
Err(err) => {
log::warn!("failed to obtain Linux version: {err}");
None
}
}
}
#[cfg(test)]
mod test {
#[test]
fn linux_version() {
let (major, minor) = super::linux_version().expect("failed to get Linux version");
println!("Linux {major}.{minor}");
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/gadget.rs | src/gadget.rs | //! USB gadget.
use nix::errno::Errno;
use std::{
collections::{HashMap, HashSet},
ffi::{OsStr, OsString},
fmt, fs,
io::{Error, ErrorKind, Result},
os::unix::{
fs::symlink,
prelude::{OsStrExt, OsStringExt},
},
path::{Path, PathBuf},
};
use crate::{
configfs_dir, function,
function::{
util::{call_remove_handler, init_remove_handlers},
Handle,
},
hex_u16, hex_u8,
lang::Language,
request_module, trim_os_str,
udc::Udc,
Speed,
};
/// USB gadget ioctl magic byte.
pub const GADGET_IOC_MAGIC: u8 = b'g';
/// USB gadget or interface class.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Class {
/// Class code.
pub class: u8,
/// Subclass code.
pub sub_class: u8,
/// Protocol code.
pub protocol: u8,
}
impl Class {
/// Vendor specific class code.
pub const VENDOR_SPECIFIC: u8 = 0xff;
/// Creates a new USB device or interface class.
pub const fn new(class: u8, sub_class: u8, protocol: u8) -> Self {
Self { class, sub_class, protocol }
}
/// Creates a new USB device or interface class with vendor-specific class code.
pub const fn vendor_specific(sub_class: u8, protocol: u8) -> Self {
Self::new(Self::VENDOR_SPECIFIC, sub_class, protocol)
}
/// Indicates that class information should be determined from the interface descriptors in the
/// device.
///
/// Can only be used as device class.
pub const fn interface_specific() -> Self {
Self::new(0, 0, 0)
}
}
/// USB gadget id.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Id {
/// Vendor id.
pub vendor: u16,
/// Product id.
pub product: u16,
}
impl Id {
/// Creates a new USB device id.
pub const fn new(vendor: u16, product: u16) -> Self {
Self { vendor, product }
}
}
/// USB gadget description strings.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Strings {
/// Manufacturer name.
pub manufacturer: String,
/// Product name.
pub product: String,
/// Serial number.
pub serial_number: String,
}
impl Strings {
/// Creates new USB device strings.
pub fn new(manufacturer: impl AsRef<str>, product: impl AsRef<str>, serial_number: impl AsRef<str>) -> Self {
Self {
manufacturer: manufacturer.as_ref().to_string(),
product: product.as_ref().to_string(),
serial_number: serial_number.as_ref().to_string(),
}
}
}
/// USB gadget operating system descriptor.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OsDescriptor {
/// Vendor code for requests.
pub vendor_code: u8,
/// Signature.
pub qw_sign: String,
/// Index of configuration in [`Gadget::configs`] to be reported at index 0.
///
/// Hosts which expect the "OS Descriptors" ask only for configurations at index 0,
/// but Linux-based USB devices can provide more than one configuration.
pub config: usize,
}
impl OsDescriptor {
/// Creates a new instance.
pub const fn new(vendor_code: u8, qw_sign: String) -> Self {
Self { vendor_code, qw_sign, config: 0 }
}
/// The Microsoft OS descriptor.
///
/// Uses vendor code 0xf0 for requests.
pub fn microsoft() -> Self {
Self { vendor_code: 0xf0, qw_sign: "MSFT100".to_string(), config: 0 }
}
}
/// WebUSB version.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum WebUsbVersion {
/// Version 1.0
#[default]
V10,
/// Other version in BCD format.
Other(u16),
}
impl From<WebUsbVersion> for u16 {
fn from(value: WebUsbVersion) -> Self {
match value {
WebUsbVersion::V10 => 0x0100,
WebUsbVersion::Other(ver) => ver,
}
}
}
/// USB gadget WebUSB descriptor.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WebUsb {
/// WebUSB specification version number.
pub version: WebUsbVersion,
/// bRequest value used for issuing WebUSB requests.
pub vendor_code: u8,
/// URL of the device's landing page.
pub landing_page: String,
}
impl WebUsb {
/// Creates a new instance.
pub fn new(vendor_code: u8, landing_page: impl AsRef<str>) -> Self {
Self { version: WebUsbVersion::default(), vendor_code, landing_page: landing_page.as_ref().to_string() }
}
}
/// USB gadget configuration.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Config {
/// Maximum power in mA.
pub max_power: u16,
/// Self powered?
pub self_powered: bool,
/// Remote wakeup?
pub remote_wakeup: bool,
/// Configuration description string.
pub description: HashMap<Language, String>,
/// Functions, i.e. USB interfaces, present in this configuration.
pub functions: Vec<function::Handle>,
}
impl Config {
/// Creates a new USB gadget configuration.
pub fn new(description: impl AsRef<str>) -> Self {
Self {
max_power: 500,
self_powered: false,
remote_wakeup: false,
description: [(Language::default(), description.as_ref().to_string())].into(),
functions: Default::default(),
}
}
/// Sets the maximum power in mA.
#[deprecated(since = "0.7.1", note = "use the field Config::max_power instead")]
pub fn set_max_power_ma(&mut self, ma: u16) -> Result<()> {
self.max_power = ma;
Ok(())
}
/// Adds a USB function (interface) to this configuration.
pub fn add_function(&mut self, function_handle: function::Handle) {
self.functions.push(function_handle);
}
/// Adds a USB function (interface) to this configuration.
#[must_use]
pub fn with_function(mut self, function_handle: function::Handle) -> Self {
self.add_function(function_handle);
self
}
fn register(
&self, gadget_dir: &Path, idx: usize, func_dirs: &HashMap<function::Handle, PathBuf>,
) -> Result<PathBuf> {
let dir = gadget_dir.join("configs").join(format!("c.{idx}"));
log::debug!("creating config at {}", dir.display());
fs::create_dir(&dir)?;
let mut attributes = 1 << 7;
if self.self_powered {
attributes |= 1 << 6;
}
if self.remote_wakeup {
attributes |= 1 << 5;
}
fs::write(dir.join("bmAttributes"), hex_u8(attributes))?;
fs::write(dir.join("MaxPower"), self.max_power.to_string())?;
for (&lang, desc) in &self.description {
let lang_dir = dir.join("strings").join(hex_u16(lang.into()));
fs::create_dir(&lang_dir)?;
fs::write(lang_dir.join("configuration"), desc)?;
}
for func in &self.functions {
let func_dir = &func_dirs[func];
log::debug!("adding function {}", func_dir.display());
symlink(func_dir, dir.join(func_dir.file_name().unwrap()))?;
}
Ok(dir)
}
}
/// USB version.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum UsbVersion {
/// USB 1.1
V11,
/// USB 2.0
#[default]
V20,
/// USB 3.0
V30,
/// USB 3.1
V31,
/// Other version in BCD format.
Other(u16),
}
impl From<UsbVersion> for u16 {
fn from(value: UsbVersion) -> Self {
match value {
UsbVersion::V11 => 0x0110,
UsbVersion::V20 => 0x0200,
UsbVersion::V30 => 0x0300,
UsbVersion::V31 => 0x0310,
UsbVersion::Other(ver) => ver,
}
}
}
/// USB gadget definition.
///
/// Fields set to `None` are left at their kernel-provided default values.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Gadget {
/// USB device class.
pub device_class: Class,
/// USB device id.
pub id: Id,
/// USB device strings.
pub strings: HashMap<Language, Strings>,
/// Maximum endpoint 0 packet size.
pub max_packet_size0: u8,
/// Device release number in BCD format.
///
/// No hexadecimal digit must exceed 9.
pub device_release: u16,
/// USB specification version.
pub usb_version: UsbVersion,
/// Maximum speed supported by driver.
pub max_speed: Option<Speed>,
/// OS descriptor extension.
pub os_descriptor: Option<OsDescriptor>,
/// WebUSB extension.
pub web_usb: Option<WebUsb>,
/// USB device configurations.
pub configs: Vec<Config>,
}
impl Gadget {
/// Creates a new USB gadget definition.
pub fn new(device_class: Class, id: Id, strings: Strings) -> Self {
Self {
device_class,
id,
strings: [(Language::default(), strings)].into(),
max_packet_size0: 64,
device_release: 0x0000,
usb_version: UsbVersion::default(),
max_speed: None,
os_descriptor: None,
web_usb: None,
configs: Vec::new(),
}
}
/// Adds a USB device configuration.
pub fn add_config(&mut self, config: Config) {
self.configs.push(config);
}
/// Adds a USB device configuration.
#[must_use]
pub fn with_config(mut self, config: Config) -> Self {
self.add_config(config);
self
}
/// Sets the OS descriptor.
#[must_use]
pub fn with_os_descriptor(mut self, os_descriptor: OsDescriptor) -> Self {
self.os_descriptor = Some(os_descriptor);
self
}
/// Sets the WebUSB extension.
#[must_use]
pub fn with_web_usb(mut self, web_usb: WebUsb) -> Self {
self.web_usb = Some(web_usb);
self
}
/// Register the USB gadget.
///
/// At least one [configuration](Config) must be added before the gadget
/// can be registered.
pub fn register(self) -> Result<RegGadget> {
if self.configs.is_empty() {
return Err(Error::new(ErrorKind::InvalidInput, "USB gadget must have at least one configuration"));
}
let usb_gadget_dir = usb_gadget_dir()?;
let mut gadget_idx: u16 = 0;
let dir = loop {
let dir = usb_gadget_dir.join(format!("usb-gadget{gadget_idx}"));
match fs::create_dir(&dir) {
Ok(()) => break dir,
Err(err) if err.kind() == ErrorKind::AlreadyExists => (),
Err(err) => return Err(err),
}
gadget_idx = gadget_idx
.checked_add(1)
.ok_or_else(|| Error::new(ErrorKind::OutOfMemory, "USB gadgets exhausted"))?;
};
log::debug!("registering gadget at {}", dir.display());
fs::write(dir.join("bDeviceClass"), hex_u8(self.device_class.class))?;
fs::write(dir.join("bDeviceSubClass"), hex_u8(self.device_class.sub_class))?;
fs::write(dir.join("bDeviceProtocol"), hex_u8(self.device_class.protocol))?;
fs::write(dir.join("idVendor"), hex_u16(self.id.vendor))?;
fs::write(dir.join("idProduct"), hex_u16(self.id.product))?;
fs::write(dir.join("bMaxPacketSize0"), hex_u8(self.max_packet_size0))?;
fs::write(dir.join("bcdDevice"), hex_u16(self.device_release))?;
fs::write(dir.join("bcdUSB"), hex_u16(self.usb_version.into()))?;
if let Some(v) = self.max_speed {
fs::write(dir.join("max_speed"), v.to_string())?;
}
if let Some(webusb) = &self.web_usb {
let webusb_dir = dir.join("webusb");
if webusb_dir.is_dir() {
fs::write(webusb_dir.join("bVendorCode"), hex_u8(webusb.vendor_code))?;
fs::write(webusb_dir.join("bcdVersion"), hex_u16(webusb.version.into()))?;
fs::write(webusb_dir.join("landingPage"), &webusb.landing_page)?;
fs::write(webusb_dir.join("use"), "1")?;
} else {
log::warn!("WebUSB descriptor is unsupported by kernel");
}
}
for (&lang, strs) in &self.strings {
let lang_dir = dir.join("strings").join(hex_u16(lang.into()));
fs::create_dir(&lang_dir)?;
fs::write(lang_dir.join("manufacturer"), &strs.manufacturer)?;
fs::write(lang_dir.join("product"), &strs.product)?;
fs::write(lang_dir.join("serialnumber"), &strs.serial_number)?;
}
let functions: HashSet<_> = self.configs.iter().flat_map(|c| &c.functions).collect();
let mut func_dirs = HashMap::new();
for (func_idx, &func) in functions.iter().enumerate() {
let func_dir = dir.join(
dir.join("functions")
.join(format!("{}.usb-gadget{gadget_idx}-{func_idx}", func.get().driver().to_str().unwrap())),
);
log::debug!("creating function at {}", func_dir.display());
fs::create_dir(&func_dir)?;
func.get().dir().set_dir(&func_dir);
func.get().register()?;
func_dirs.insert(func.clone(), func_dir);
}
let mut config_dirs = Vec::new();
for (idx, config) in self.configs.iter().enumerate() {
let dir = config.register(&dir, idx + 1, &func_dirs)?;
config_dirs.push(dir);
}
if let Some(os_desc) = &self.os_descriptor {
let os_desc_dir = dir.join("os_desc");
if os_desc_dir.is_dir() {
fs::write(os_desc_dir.join("b_vendor_code"), hex_u8(os_desc.vendor_code))?;
fs::write(os_desc_dir.join("qw_sign"), &os_desc.qw_sign)?;
fs::write(os_desc_dir.join("use"), "1")?;
let config_dir = config_dirs.get(os_desc.config).ok_or_else(|| {
Error::new(ErrorKind::InvalidInput, "invalid configuration index in OS descriptor")
})?;
symlink(config_dir, os_desc_dir.join(config_dir.file_name().unwrap()))?;
} else {
log::warn!("USB OS descriptor is unsupported by kernel");
}
}
log::debug!("gadget at {} registered", dir.display());
Ok(RegGadget { dir, attached: true, func_dirs })
}
/// Register and bind USB gadget to a USB device controller (UDC).
///
/// At least one [configuration](Config) must be added before the gadget
/// can be bound.
pub fn bind(self, udc: &Udc) -> Result<RegGadget> {
let reg = self.register()?;
reg.bind(Some(udc))?;
Ok(reg)
}
}
/// USB gadget registered with the system.
///
/// If this was obtained by calling [`Gadget::bind`], the USB gadget will be
/// unbound and removed when this is dropped.
///
/// Call [`registered`] to obtain all gadgets registered on the system.
#[must_use = "The USB gadget is removed when RegGadget is dropped."]
pub struct RegGadget {
dir: PathBuf,
attached: bool,
func_dirs: HashMap<Handle, PathBuf>,
}
impl fmt::Debug for RegGadget {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("RegGadget").field("name", &self.name()).field("is_attached", &self.is_attached()).finish()
}
}
impl RegGadget {
/// Name of this USB gadget in configfs.
pub fn name(&self) -> &OsStr {
self.dir.file_name().unwrap()
}
/// Path of this USB gadget in configfs.
pub fn path(&self) -> &Path {
&self.dir
}
/// If true, the USB gadget will be removed when this is dropped.
pub fn is_attached(&self) -> bool {
self.attached
}
/// The name of the USB device controller (UDC) this gadget is bound to.
pub fn udc(&self) -> Result<Option<OsString>> {
let data = OsString::from_vec(fs::read(self.dir.join("UDC"))?);
let data = trim_os_str(&data);
if data.is_empty() {
Ok(None)
} else {
Ok(Some(data.to_os_string()))
}
}
/// Binds the gadget to the specified USB device controller (UDC).
///
/// If `udc` is `None`, the gadget is unbound from any UDC.
pub fn bind(&self, udc: Option<&Udc>) -> Result<()> {
log::debug!("binding gadget {:?} to {:?}", self, &udc);
let name = match udc {
Some(udc) => udc.name().to_os_string(),
None => "\n".into(),
};
match fs::write(self.dir.join("UDC"), name.as_bytes()) {
Ok(()) => (),
Err(err) if udc.is_none() && err.raw_os_error() == Some(Errno::ENODEV as i32) => (),
Err(err) => return Err(err),
}
for func in self.func_dirs.keys() {
func.get().dir().set_bound(udc.is_some());
}
Ok(())
}
/// Detach the handle from the USB gadget while keeping the USB gadget active.
pub fn detach(&mut self) {
self.attached = false;
}
fn do_remove(&mut self) -> Result<()> {
for func in self.func_dirs.keys() {
func.get().pre_removal()?;
}
for func in self.func_dirs.keys() {
func.get().dir().set_bound(false);
}
remove_at(&self.dir)?;
for func in self.func_dirs.keys() {
func.get().dir().reset_dir();
}
for (func, dir) in &self.func_dirs {
func.get().post_removal(dir)?;
}
self.detach();
Ok(())
}
/// Unbind from the UDC and remove the USB gadget.
pub fn remove(mut self) -> Result<()> {
self.do_remove()
}
}
impl Drop for RegGadget {
fn drop(&mut self) {
if self.attached {
if let Err(err) = self.do_remove() {
log::warn!("removing gadget at {} failed: {err}", self.dir.display());
}
}
}
}
/// Remove USB gadget at specified configfs gadget directory.
fn remove_at(dir: &Path) -> Result<()> {
log::debug!("removing gadget at {}", dir.display());
init_remove_handlers();
let _ = fs::write(dir.join("UDC"), "\n");
if let Ok(entries) = fs::read_dir(dir.join("os_desc")) {
for file in entries {
let Ok(file) = file else { continue };
let Ok(file_type) = file.file_type() else { continue };
if file_type.is_symlink() {
fs::remove_file(file.path())?;
}
}
}
for config_dir in fs::read_dir(dir.join("configs"))? {
let Ok(config_dir) = config_dir else { continue };
if !config_dir.metadata()?.is_dir() {
continue;
}
for func in fs::read_dir(config_dir.path())? {
let Ok(func) = func else { continue };
if func.metadata()?.is_symlink() {
fs::remove_file(func.path())?;
}
}
for lang in fs::read_dir(config_dir.path().join("strings"))? {
let Ok(lang) = lang else { continue };
if lang.metadata()?.is_dir() {
fs::remove_dir(lang.path())?;
}
}
fs::remove_dir(config_dir.path())?;
}
for func_dir in fs::read_dir(dir.join("functions"))? {
let Ok(func_dir) = func_dir else { continue };
if !func_dir.metadata()?.is_dir() {
continue;
}
call_remove_handler(&func_dir.path())?;
fs::remove_dir(func_dir.path())?;
}
for lang in fs::read_dir(dir.join("strings"))? {
let Ok(lang) = lang else { continue };
if lang.metadata()?.is_dir() {
fs::remove_dir(lang.path())?;
}
}
fs::remove_dir(dir)?;
log::debug!("removed gadget at {}", dir.display());
Ok(())
}
/// The path to the USB gadget configuration directory within configfs.
fn usb_gadget_dir() -> Result<PathBuf> {
let _ = request_module("libcomposite");
let usb_gadget_dir = configfs_dir()?.join("usb_gadget");
if usb_gadget_dir.is_dir() {
Ok(usb_gadget_dir)
} else {
Err(Error::new(ErrorKind::NotFound, "usb_gadget not found in configfs"))
}
}
/// Get all USB gadgets registered on the system.
///
/// This returns all USB gadgets, including gadgets not created by the running program or
/// registered by other means than using this library.
pub fn registered() -> Result<Vec<RegGadget>> {
let usb_gadget_dir = usb_gadget_dir()?;
let mut gadgets = Vec::new();
for gadget_dir in fs::read_dir(usb_gadget_dir)? {
let Ok(gadget_dir) = gadget_dir else { continue };
if gadget_dir.metadata()?.is_dir() {
gadgets.push(RegGadget { dir: gadget_dir.path(), attached: false, func_dirs: HashMap::new() });
}
}
Ok(gadgets)
}
/// Remove all USB gadgets defined on the system.
///
/// This removes all USB gadgets, including gadgets not created by the running program or
/// registered by other means than using this library.
pub fn remove_all() -> Result<()> {
let mut res = Ok(());
for gadget in registered()? {
if let Err(err) = gadget.remove() {
res = Err(err);
}
}
res
}
/// Unbind all USB gadgets defined on the system.
///
/// This unbinds all USB gadgets, including gadgets not created by the running program or
/// registered by other means than using this library.
pub fn unbind_all() -> Result<()> {
let mut res = Ok(());
for gadget in registered()? {
if let Err(err) = gadget.bind(None) {
res = Err(err);
}
}
res
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/lang.rs | src/lang.rs | /// USB language id.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Language {
/// Afrikaans
Afrikaans,
/// Albanian
Albanian,
/// Arabic (Saudi Arabia)
ArabicSaudiArabia,
/// Arabic (Iraq)
ArabicIraq,
/// Arabic (Egypt)
ArabicEgypt,
/// Arabic (Libya)
ArabicLibya,
/// Arabic (Algeria)
ArabicAlgeria,
/// Arabic (Morocco)
ArabicMorocco,
/// Arabic (Tunisia)
ArabicTunisia,
/// Arabic (Oman)
ArabicOman,
/// Arabic (Yemen)
ArabicYemen,
/// Arabic (Syria)
ArabicSyria,
/// Arabic (Jordan)
ArabicJordan,
/// Arabic (Lebanon)
ArabicLebanon,
/// Arabic (Kuwait)
ArabicKuwait,
/// Arabic (UAE)
ArabicUAE,
/// Arabic (Bahrain)
ArabicBahrain,
/// Arabic (Qatar)
ArabicQatar,
/// Armenian
Armenian,
/// Assamese
Assamese,
/// Azeri (Latin)
AzeriLatin,
/// Azeri (Cyrillic)
AzeriCyrillic,
/// Basque
Basque,
/// Belarussian
Belarussian,
/// Bengali
Bengali,
/// Bulgarian
Bulgarian,
/// Burmese
Burmese,
/// Catalan
Catalan,
/// Chinese (Taiwan)
ChineseTaiwan,
/// Chinese (PRC)
ChinesePRC,
/// Chinese (Hong Kong SAR PRC)
ChineseHongKongSARPRC,
/// Chinese (Singapore)
ChineseSingapore,
/// Chinese (Macau SAR)
ChineseMacauSAR,
/// Croatian
Croatian,
/// Czech
Czech,
/// Danish
Danish,
/// Dutch (Netherlands)
DutchNetherlands,
/// Dutch (Belgium)
DutchBelgium,
/// English (United States)
#[default]
EnglishUnitedStates,
/// English (United Kingdom)
EnglishUnitedKingdom,
/// English (Australian)
EnglishAustralian,
/// English (Canadian)
EnglishCanadian,
/// English (New Zealand)
EnglishNewZealand,
/// English (Ireland)
EnglishIreland,
/// English (South Africa)
EnglishSouthAfrica,
/// English (Jamaica)
EnglishJamaica,
/// English (Caribbean)
EnglishCaribbean,
/// English (Belize)
EnglishBelize,
/// English (Trinidad)
EnglishTrinidad,
/// English (Zimbabwe)
EnglishZimbabwe,
/// English (Philippines)
EnglishPhilippines,
/// Estonian
Estonian,
/// Faeroese
Faeroese,
/// Farsi
Farsi,
/// Finnish
Finnish,
/// French (Standard)
FrenchStandard,
/// French (Belgian)
FrenchBelgian,
/// French (Canadian)
FrenchCanadian,
/// French (Switzerland)
FrenchSwitzerland,
/// French (Luxembourg)
FrenchLuxembourg,
/// French (Monaco)
FrenchMonaco,
/// Georgian
Georgian,
/// German (Standard)
GermanStandard,
/// German (Switzerland)
GermanSwitzerland,
/// German (Austria)
GermanAustria,
/// German (Luxembourg)
GermanLuxembourg,
/// German (Liechtenstein)
GermanLiechtenstein,
/// Greek
Greek,
/// Gujarati
Gujarati,
/// Hebrew
Hebrew,
/// Hindi
Hindi,
/// Hungarian
Hungarian,
/// Icelandic
Icelandic,
/// Indonesian
Indonesian,
/// Italian (Standard)
ItalianStandard,
/// Italian (Switzerland)
ItalianSwitzerland,
/// Japanese
Japanese,
/// Kannada
Kannada,
/// KashmiriIndia
KashmiriIndia,
/// Kazakh
Kazakh,
/// Konkani
Konkani,
/// Korean
Korean,
/// Korean (Johab)
KoreanJohab,
/// Latvian
Latvian,
/// Lithuanian
Lithuanian,
/// Lithuanian (Classic)
LithuanianClassic,
/// Macedonian
Macedonian,
/// Malay (Malaysian)
MalayMalaysian,
/// Malay (Brunei Darussalam)
MalayBruneiDarussalam,
/// Malayalam
Malayalam,
/// Manipuri
Manipuri,
/// Marathi
Marathi,
/// Nepali (India)
NepaliIndia,
/// Norwegian (Bokmal)
NorwegianBokmal,
/// Norwegian (Nynorsk)
NorwegianNynorsk,
/// Oriya
Oriya,
/// Polish
Polish,
/// Portuguese (Brazil)
PortugueseBrazil,
/// Portuguese (Standard)
PortugueseStandard,
/// Punjabi
Punjabi,
/// Romanian
Romanian,
/// Russian
Russian,
/// Sanskrit
Sanskrit,
/// Serbian (Cyrillic)
SerbianCyrillic,
/// Serbian (Latin)
SerbianLatin,
/// Sindhi
Sindhi,
/// Slovak
Slovak,
/// Slovenian
Slovenian,
/// Spanish (Traditional Sort)
SpanishTraditionalSort,
/// Spanish (Mexican)
SpanishMexican,
/// Spanish (ModernSort)
SpanishModernSort,
/// Spanish (Guatemala)
SpanishGuatemala,
/// Spanish (Costa Rica)
SpanishCostaRica,
/// Spanish (Panama)
SpanishPanama,
/// Spanish (Dominican Republic)
SpanishDominicanRepublic,
/// Spanish (Venezuela)
SpanishVenezuela,
/// Spanish (Colombia)
SpanishColombia,
/// Spanish (Peru)
SpanishPeru,
/// Spanish (Argentina)
SpanishArgentina,
/// Spanish (Ecuador)
SpanishEcuador,
/// Spanish (Chile)
SpanishChile,
/// Spanish (Uruguay)
SpanishUruguay,
/// Spanish (Paraguay)
SpanishParaguay,
/// Spanish (Bolivia)
SpanishBolivia,
/// Spanish (El Salvador)
SpanishElSalvador,
/// Spanish (Honduras)
SpanishHonduras,
/// Spanish (Nicaragua)
SpanishNicaragua,
/// Spanish (Puerto Rico)
SpanishPuertoRico,
/// Sutu
Sutu,
/// Swahili (Kenya)
SwahiliKenya,
/// Swedish
Swedish,
/// Swedish (Finland)
SwedishFinland,
/// Tamil
Tamil,
/// Tatar (Tatarstan)
TatarTatarstan,
/// Telugu
Telugu,
/// Thai
Thai,
/// Turkish
Turkish,
/// Ukrainian
Ukrainian,
/// Urdu (Pakistan)
UrduPakistan,
/// Urdu (India)
UrduIndia,
/// Uzbek (Latin)
UzbekLatin,
/// Uzbek (Cyrillic)
UzbekCyrillic,
/// Vietnamese
Vietnamese,
/// HID usage data descriptor
HidUsageDataDescriptor,
/// HID vendor defined 1
HidVendorDefined1,
/// HID vendor defined 2
HidVendorDefined2,
/// HID vendor defined 3
HidVendorDefined3,
/// HID vendor defined 4
HidVendorDefined4,
/// Custom language code
Other(u16),
}
impl From<Language> for u16 {
fn from(lang: Language) -> u16 {
match lang {
Language::Afrikaans => 0x0436,
Language::Albanian => 0x041c,
Language::ArabicSaudiArabia => 0x0401,
Language::ArabicIraq => 0x0801,
Language::ArabicEgypt => 0x0c01,
Language::ArabicLibya => 0x1001,
Language::ArabicAlgeria => 0x1401,
Language::ArabicMorocco => 0x1801,
Language::ArabicTunisia => 0x1c01,
Language::ArabicOman => 0x2001,
Language::ArabicYemen => 0x2401,
Language::ArabicSyria => 0x2801,
Language::ArabicJordan => 0x2c01,
Language::ArabicLebanon => 0x3001,
Language::ArabicKuwait => 0x3401,
Language::ArabicUAE => 0x3801,
Language::ArabicBahrain => 0x3c01,
Language::ArabicQatar => 0x4001,
Language::Armenian => 0x042b,
Language::Assamese => 0x044d,
Language::AzeriLatin => 0x042c,
Language::AzeriCyrillic => 0x082c,
Language::Basque => 0x042d,
Language::Belarussian => 0x0423,
Language::Bengali => 0x0445,
Language::Bulgarian => 0x0402,
Language::Burmese => 0x0455,
Language::Catalan => 0x0403,
Language::ChineseTaiwan => 0x0404,
Language::ChinesePRC => 0x0804,
Language::ChineseHongKongSARPRC => 0x0c04,
Language::ChineseSingapore => 0x1004,
Language::ChineseMacauSAR => 0x1404,
Language::Croatian => 0x041a,
Language::Czech => 0x0405,
Language::Danish => 0x0406,
Language::DutchNetherlands => 0x0413,
Language::DutchBelgium => 0x0813,
Language::EnglishUnitedStates => 0x0409,
Language::EnglishUnitedKingdom => 0x0809,
Language::EnglishAustralian => 0x0c09,
Language::EnglishCanadian => 0x1009,
Language::EnglishNewZealand => 0x1409,
Language::EnglishIreland => 0x1809,
Language::EnglishSouthAfrica => 0x1c09,
Language::EnglishJamaica => 0x2009,
Language::EnglishCaribbean => 0x2409,
Language::EnglishBelize => 0x2809,
Language::EnglishTrinidad => 0x2c09,
Language::EnglishZimbabwe => 0x3009,
Language::EnglishPhilippines => 0x3409,
Language::Estonian => 0x0425,
Language::Faeroese => 0x0438,
Language::Farsi => 0x0429,
Language::Finnish => 0x040b,
Language::FrenchStandard => 0x040c,
Language::FrenchBelgian => 0x080c,
Language::FrenchCanadian => 0x0c0c,
Language::FrenchSwitzerland => 0x100c,
Language::FrenchLuxembourg => 0x140c,
Language::FrenchMonaco => 0x180c,
Language::Georgian => 0x0437,
Language::GermanStandard => 0x0407,
Language::GermanSwitzerland => 0x0807,
Language::GermanAustria => 0x0c07,
Language::GermanLuxembourg => 0x1007,
Language::GermanLiechtenstein => 0x1407,
Language::Greek => 0x0408,
Language::Gujarati => 0x0447,
Language::Hebrew => 0x040d,
Language::Hindi => 0x0439,
Language::Hungarian => 0x040e,
Language::Icelandic => 0x040f,
Language::Indonesian => 0x0421,
Language::ItalianStandard => 0x0410,
Language::ItalianSwitzerland => 0x0810,
Language::Japanese => 0x0411,
Language::Kannada => 0x044b,
Language::KashmiriIndia => 0x0860,
Language::Kazakh => 0x043f,
Language::Konkani => 0x0457,
Language::Korean => 0x0412,
Language::KoreanJohab => 0x0812,
Language::Latvian => 0x0426,
Language::Lithuanian => 0x0427,
Language::LithuanianClassic => 0x0827,
Language::Macedonian => 0x042f,
Language::MalayMalaysian => 0x043e,
Language::MalayBruneiDarussalam => 0x083e,
Language::Malayalam => 0x044c,
Language::Manipuri => 0x0458,
Language::Marathi => 0x044e,
Language::NepaliIndia => 0x0861,
Language::NorwegianBokmal => 0x0414,
Language::NorwegianNynorsk => 0x0814,
Language::Oriya => 0x0448,
Language::Polish => 0x0415,
Language::PortugueseBrazil => 0x0416,
Language::PortugueseStandard => 0x0816,
Language::Punjabi => 0x0446,
Language::Romanian => 0x0418,
Language::Russian => 0x0419,
Language::Sanskrit => 0x044f,
Language::SerbianCyrillic => 0x0c1a,
Language::SerbianLatin => 0x081a,
Language::Sindhi => 0x0459,
Language::Slovak => 0x041b,
Language::Slovenian => 0x0424,
Language::SpanishTraditionalSort => 0x040a,
Language::SpanishMexican => 0x080a,
Language::SpanishModernSort => 0x0c0a,
Language::SpanishGuatemala => 0x100a,
Language::SpanishCostaRica => 0x140a,
Language::SpanishPanama => 0x180a,
Language::SpanishDominicanRepublic => 0x1c0a,
Language::SpanishVenezuela => 0x200a,
Language::SpanishColombia => 0x240a,
Language::SpanishPeru => 0x280a,
Language::SpanishArgentina => 0x2c0a,
Language::SpanishEcuador => 0x300a,
Language::SpanishChile => 0x340a,
Language::SpanishUruguay => 0x380a,
Language::SpanishParaguay => 0x3c0a,
Language::SpanishBolivia => 0x400a,
Language::SpanishElSalvador => 0x440a,
Language::SpanishHonduras => 0x480a,
Language::SpanishNicaragua => 0x4c0a,
Language::SpanishPuertoRico => 0x500a,
Language::Sutu => 0x0430,
Language::SwahiliKenya => 0x0441,
Language::Swedish => 0x041d,
Language::SwedishFinland => 0x081d,
Language::Tamil => 0x0449,
Language::TatarTatarstan => 0x0444,
Language::Telugu => 0x044a,
Language::Thai => 0x041e,
Language::Turkish => 0x041f,
Language::Ukrainian => 0x0422,
Language::UrduPakistan => 0x0420,
Language::UrduIndia => 0x0820,
Language::UzbekLatin => 0x0443,
Language::UzbekCyrillic => 0x0843,
Language::Vietnamese => 0x042a,
Language::HidUsageDataDescriptor => 0x04ff,
Language::HidVendorDefined1 => 0xf0ff,
Language::HidVendorDefined2 => 0xf4ff,
Language::HidVendorDefined3 => 0xf8ff,
Language::HidVendorDefined4 => 0xfcff,
Language::Other(other) => other,
}
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/video.rs | src/function/video.rs | //! USB Video Class (UVC) function.
//!
//! The Linux kernel configuration option `CONFIG_USB_CONFIGFS_F_UVC` must be enabled.
//! It must be paired with a userspace program that responds to UVC control requests
//! and fills buffers to be queued to the V4L2 device that the driver creates.
//! See [example](https://gitlab.freedesktop.org/camera/uvc-gadget).
//!
//! # Example
//!
//! ```no_run
//! use usb_gadget::function::video::{Uvc, Frame, Format};
//! use usb_gadget::{default_udc, Class, Config, Gadget, Id, Strings};
//!
//! // Create a new UVC function with the specified frames:
//! // - 640x360 YUYV format at 15, 30, 60, 120 fps
//! // - 640x360 MJPEG format at 15, 30, 60, 120 fps
//! // - 1280x720 MJPEG format at 30, 60 fps
//! // - 1920x1080 MJPEG format at 30 fps
//! let (video, func) = Uvc::new(vec![
//! Frame::new(640, 360, vec![15, 30, 60, 120], Format::Yuyv),
//! Frame::new(640, 360, vec![15, 30, 60, 120], Format::Mjpeg),
//! Frame::new(1280, 720, vec![30, 60], Format::Mjpeg),
//! Frame::new(1920, 1080, vec![30], Format::Mjpeg),
//! ]);
//!
//! let udc = default_udc().expect("cannot get UDC");
//! let reg =
//! // USB device descriptor base class 0xEF, 0x02, 0x01: Misc, Interface Association Descriptor
//! // Linux Foundation VID Gadget PID
//! Gadget::new(Class::new(0xEF, 0x02, 0x01), Id::new(0x1d6b, 0x0104), Strings::new("Clippy Manufacturer", "Rust Video Device", "RUST0123456"))
//! .with_config(Config::new("UVC Config 1").with_function(func))
//! .bind(&udc)
//! .expect("cannot bind to UDC");
//!
//! println!(
//! "UAC2 video {} at {} to {} status {:?}",
//! reg.name().to_string_lossy(),
//! reg.path().display(),
//! udc.name().to_string_lossy(),
//! video.status()
//! );
//! ```
//! The gadget will bind won't enumaterate with host unless a userspace program (such as uvc-gadget)
//! is running and responding to UVC control requests.
use std::{
collections::HashSet,
ffi::{OsStr, OsString},
fs,
io::{Error, ErrorKind, Result},
path::{Path, PathBuf},
};
use super::{
util::{FunctionDir, Status},
Function, Handle,
};
pub(crate) fn driver() -> &'static OsStr {
OsStr::new("uvc")
}
/// USB Video Class (UVC) frame format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Format {
/// YUYV format [Packed YUV formats](https://docs.kernel.org/6.12/userspace-api/media/v4l/pixfmt-packed-yuv.html).
/// Currently only uncompressed format supported.
Yuyv,
/// MJPEG compressed format.
Mjpeg,
}
impl Format {
fn all() -> &'static [Format] {
&[Format::Yuyv, Format::Mjpeg]
}
fn dir_name(&self) -> &'static OsStr {
match self {
Format::Yuyv => OsStr::new("yuyv"),
Format::Mjpeg => OsStr::new("mjpeg"),
}
}
fn group_dir_name(&self) -> &'static OsStr {
match self {
Format::Yuyv => OsStr::new("uncompressed"),
_ => self.dir_name(),
}
}
fn group_path(&self) -> PathBuf {
format!("streaming/{}/{}", self.group_dir_name().to_string_lossy(), self.dir_name().to_string_lossy())
.into()
}
fn header_link_path(&self) -> PathBuf {
format!("streaming/header/h/{}", self.dir_name().to_string_lossy()).into()
}
fn color_matching_path(&self) -> PathBuf {
format!("streaming/color_matching/{}", self.dir_name().to_string_lossy()).into()
}
fn color_matching_link_path(&self) -> PathBuf {
self.group_path().join("color_matching")
}
}
/// Frame color matching information properties.
///
/// It’s possible to specify some colometry information for each format you
/// create. This step is optional, and default information will be included if
/// this step is skipped; those default values follow those defined in the
/// Color Matching Descriptor section of the UVC specification.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct ColorMatching {
/// Color primaries
pub color_primaries: u8,
/// Transfer characteristics
pub transfer_characteristics: u8,
/// Matrix coefficients
pub matrix_coefficients: u8,
}
impl ColorMatching {
/// Create a new color matching information with the specified properties.
pub fn new(color_primaries: u8, transfer_characteristics: u8, matrix_coefficients: u8) -> Self {
Self { color_primaries, transfer_characteristics, matrix_coefficients }
}
}
/// Helper to create a new [`UvcFrame`].
#[derive(Debug, Clone)]
pub struct Frame {
/// Frame width in pixels
pub width: u32,
/// Frame height in pixels
pub height: u32,
/// Frame [`Format`]
pub format: Format,
/// Frames per second available
pub fps: Vec<u16>,
}
impl Frame {
/// Create a new [`UvcFrame`] with the specified properties.
pub fn new(width: u32, height: u32, fps: Vec<u16>, format: Format) -> Self {
Self { width, height, format, fps }
}
}
impl From<Frame> for UvcFrame {
fn from(frame: Frame) -> Self {
UvcFrame {
width: frame.width,
height: frame.height,
intervals: frame.fps.iter().filter(|i| **i != 0).map(|i| 1_000_000_000 / *i as u32).collect(),
color_matching: None,
format: frame.format,
}
}
}
/// USB Video Class (UVC) frame configuration.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct UvcFrame {
/// Frame width in pixels
pub width: u32,
/// Frame height in pixels
pub height: u32,
/// Frame intervals available each in 100 ns units
pub intervals: Vec<u32>,
/// Color matching information. If not provided, the default values are used.
pub color_matching: Option<ColorMatching>,
/// Frame format
pub format: Format,
}
impl UvcFrame {
fn dir_name(&self) -> String {
format!("{}p", self.height)
}
fn path(&self) -> PathBuf {
self.format.group_path().join(self.dir_name())
}
/// Create a new UVC frame with the specified properties.
pub fn new(width: u32, height: u32, format: Format, intervals: impl IntoIterator<Item = u32>) -> Self {
Self { width, height, intervals: intervals.into_iter().collect(), color_matching: None, format }
}
}
/// Builder for USB Video Class (UVC) function. None value uses the f_uvc default/generated value.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct UvcBuilder {
/// Interval for polling endpoint for data transfers
pub streaming_interval: Option<u8>,
/// bMaxBurst for super speed companion descriptor. Valid values are 1-15.
pub streaming_max_burst: Option<u8>,
/// Maximum packet size this endpoint is capable of sending or receiving when this configuration
/// is selected. Valid values are 1024/2048/3072.
pub streaming_max_packet: Option<u32>,
/// Video device interface name
pub function_name: Option<String>,
/// Video frames available
pub frames: Vec<UvcFrame>,
/// Processing Unit's bmControls field
pub processing_controls: Option<u8>,
/// Camera Terminal's bmControls field
pub camera_controls: Option<u8>,
}
impl UvcBuilder {
/// Build the USB function.
///
/// The returned handle must be added to a USB gadget configuration.
pub fn build(self) -> (Uvc, Handle) {
let dir = FunctionDir::new();
(Uvc { dir: dir.clone() }, Handle::new(UvcFunction { builder: self, dir }))
}
/// Add a frame to builder
pub fn add_frame<F>(&mut self, frame: F)
where
UvcFrame: From<F>,
{
self.frames.push(frame.into());
}
/// UVC builder with frames
#[must_use]
pub fn with_frames<F>(mut self, frames: impl IntoIterator<Item = F>) -> Self
where
UvcFrame: From<F>,
{
self.frames = frames.into_iter().map(UvcFrame::from).collect();
self
}
}
#[derive(Debug)]
struct UvcFunction {
builder: UvcBuilder,
dir: FunctionDir,
}
impl Function for UvcFunction {
fn driver(&self) -> OsString {
driver().into()
}
fn dir(&self) -> FunctionDir {
self.dir.clone()
}
fn register(&self) -> Result<()> {
if self.builder.frames.is_empty() {
return Err(Error::new(ErrorKind::InvalidInput, "at least one frame must exist"));
}
if self.builder.frames.iter().any(|f| f.intervals.is_empty()) {
return Err(Error::new(ErrorKind::InvalidInput, "at least one interval must exist for every frame"));
}
// format groups to link to header
let mut formats_to_link: HashSet<Format> = HashSet::new();
// create frame descriptors
for frame in &self.builder.frames {
self.dir.create_dir_all(frame.path())?;
self.dir.write(frame.path().join("wWidth"), frame.width.to_string())?;
self.dir.write(frame.path().join("wHeight"), frame.height.to_string())?;
self.dir.write(
frame.path().join("dwMaxVideoFrameBufferSize"),
(frame.width * frame.height * 2).to_string(),
)?;
self.dir.write(
frame.path().join("dwFrameInterval"),
frame.intervals.iter().map(|i| i.to_string()).collect::<Vec<String>>().join("\n"),
)?;
formats_to_link.insert(frame.format);
if let Some(color_matching) = frame.color_matching.as_ref() {
let color_matching_path = frame.format.color_matching_path();
// can only have one color matching information per format
if !color_matching_path.is_dir() {
self.dir.create_dir_all(&color_matching_path)?;
self.dir.write(
frame.format.color_matching_path().join("bColorPrimaries"),
color_matching.color_primaries.to_string(),
)?;
self.dir.write(
frame.format.color_matching_path().join("bTransferCharacteristics"),
color_matching.transfer_characteristics.to_string(),
)?;
self.dir.write(
frame.format.color_matching_path().join("bMatrixCoefficients"),
color_matching.matrix_coefficients.to_string(),
)?;
self.dir.symlink(&color_matching_path, frame.format.color_matching_link_path())?;
} else {
log::warn!("Color matching information already exists for format {:?}", frame.format);
}
}
}
// header linking format descriptors and associated frames to header after creating
// otherwise cannot add new frames
self.dir.create_dir_all("streaming/header/h")?;
self.dir.create_dir_all("control/header/h")?;
for format in formats_to_link {
self.dir.symlink(format.group_path(), format.header_link_path())?;
}
// supported speeds: all linked but selected based on gadget speed: https://github.com/torvalds/linux/blob/master/drivers/usb/gadget/function/f_uvc.c#L732
self.dir.symlink("streaming/header/h", "streaming/class/fs/h")?;
self.dir.symlink("streaming/header/h", "streaming/class/hs/h")?;
self.dir.symlink("streaming/header/h", "streaming/class/ss/h")?;
self.dir.symlink("control/header/h", "control/class/fs/h")?;
self.dir.symlink("control/header/h", "control/class/ss/h")?;
// controls
if let Some(processing_controls) = self.builder.processing_controls {
self.dir.write("control/processing/default/bmControls", processing_controls.to_string())?;
}
// terminal
if let Some(camera_controls) = self.builder.camera_controls {
self.dir.write("control/terminal/camera/default/bmControls", camera_controls.to_string())?;
}
// bandwidth configuration
if let Some(interval) = self.builder.streaming_interval {
self.dir.write("streaming_interval", interval.to_string())?;
}
if let Some(max_burst) = self.builder.streaming_max_burst {
self.dir.write("streaming_maxburst", max_burst.to_string())?;
}
if let Some(max_packet) = self.builder.streaming_max_packet {
self.dir.write("streaming_maxpacket", max_packet.to_string())?;
}
Ok(())
}
}
/// USB Video Class (UVC) function.
#[derive(Debug)]
pub struct Uvc {
dir: FunctionDir,
}
impl Uvc {
/// Creates a new USB Video Class (UVC) builder with f_uvc video defaults.
pub fn builder() -> UvcBuilder {
UvcBuilder::default()
}
/// Creates a new USB Video Class (UVC) with the specified frames.
pub fn new<F>(frames: impl IntoIterator<Item = F>) -> (Uvc, Handle)
where
UvcFrame: From<F>,
{
let frames = frames.into_iter().map(UvcFrame::from).collect();
let builder = UvcBuilder { frames, ..Default::default() };
builder.build()
}
/// Access to registration status.
pub fn status(&self) -> Status {
self.dir.status()
}
}
fn remove_class_headers<P: AsRef<Path>>(path: P) -> Result<()> {
for entry in fs::read_dir(path)? {
let Ok(entry) = entry else { continue };
let path = entry.path();
let header_path = path.join("h");
if header_path.is_symlink() {
log::trace!("removing UVC header {:?}", path);
fs::remove_file(header_path)?;
}
}
Ok(())
}
pub(crate) fn remove_handler(dir: PathBuf) -> Result<()> {
// remove header links for control and streaming
let ctrl_class = dir.join("control/class");
if ctrl_class.is_dir() {
remove_class_headers(ctrl_class)?;
}
let stream_class = dir.join("streaming/class");
if stream_class.is_dir() {
remove_class_headers(stream_class)?;
}
// remove all UVC frames, color matching information and header links
if dir.join("streaming").is_dir() {
for format in Format::all() {
// remove header link first to allow removing frames
let header_link_path = dir.join(format.header_link_path());
if header_link_path.is_symlink() {
log::trace!("removing UVC header link {:?}", header_link_path);
fs::remove_file(header_link_path)?;
}
let color_matching_dir = dir.join(format.color_matching_path());
if color_matching_dir.is_dir() {
log::trace!("removing UVC color matching information {:?}", color_matching_dir);
fs::remove_file(dir.join(format.color_matching_link_path()))?;
fs::remove_dir(color_matching_dir)?;
}
let group_dir = dir.join(format.group_path());
if group_dir.is_dir() {
for entry in fs::read_dir(&group_dir)? {
let Ok(entry) = entry else { continue };
let path = entry.path();
if path.is_dir() && !path.is_symlink() {
log::trace!("removing UVC frame {:?}", path);
fs::remove_dir(path)?;
}
}
log::trace!("removing UVC group {:?}", group_dir);
fs::remove_dir(group_dir)?;
}
}
}
// finally remove header folders
let stream_header = dir.join("streaming/header/h");
if stream_header.is_dir() {
fs::remove_dir(stream_header)?;
}
let control_header = dir.join("control/header/h");
if control_header.is_dir() {
fs::remove_dir(control_header)?;
}
Ok(())
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/serial.rs | src/function/serial.rs | //! Serial functions.
use std::{
ffi::{OsStr, OsString},
io::{Error, ErrorKind, Result},
path::PathBuf,
};
use super::{
util::{FunctionDir, Status},
Function, Handle,
};
/// Class of USB serial function.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SerialClass {
/// Abstract Control Model (CDC ACM).
///
/// The Linux kernel configuration option `CONFIG_USB_CONFIGFS_ACM` must be enabled.
Acm,
/// Generic serial.
///
/// The Linux kernel configuration option `CONFIG_USB_CONFIGFS_SERIAL` must be enabled.
Generic,
}
impl SerialClass {
fn driver(&self) -> &OsStr {
OsStr::new(match self {
SerialClass::Acm => "acm",
SerialClass::Generic => "gser",
})
}
}
/// Builder for USB serial function.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SerialBuilder {
serial_class: SerialClass,
/// Console?
pub console: Option<bool>,
}
impl SerialBuilder {
/// Build the USB function.
///
/// The returned handle must be added to a USB gadget configuration.
pub fn build(self) -> (Serial, Handle) {
let dir = FunctionDir::new();
(Serial { dir: dir.clone() }, Handle::new(SerialFunction { builder: self, dir }))
}
}
#[derive(Debug)]
struct SerialFunction {
builder: SerialBuilder,
dir: FunctionDir,
}
impl Function for SerialFunction {
fn driver(&self) -> OsString {
self.builder.serial_class.driver().to_os_string()
}
fn dir(&self) -> FunctionDir {
self.dir.clone()
}
fn register(&self) -> Result<()> {
if let Some(console) = self.builder.console {
// Console support is optional.
let _ = self.dir.write("console", if console { "1" } else { "0" });
}
Ok(())
}
}
/// USB serial function.
#[derive(Debug)]
pub struct Serial {
dir: FunctionDir,
}
impl Serial {
/// Creates a new USB serial function.
pub fn new(serial_class: SerialClass) -> (Serial, Handle) {
Self::builder(serial_class).build()
}
/// Creates a new USB serial function builder.
pub fn builder(serial_class: SerialClass) -> SerialBuilder {
SerialBuilder { serial_class, console: None }
}
/// Access to registration status.
pub fn status(&self) -> Status {
self.dir.status()
}
/// Path to TTY device.
pub fn tty(&self) -> Result<PathBuf> {
let port_num: u32 =
self.dir.read_string("port_num")?.parse().map_err(|err| Error::new(ErrorKind::InvalidData, err))?;
Ok(format!("/dev/ttyGS{port_num}").into())
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/hid.rs | src/function/hid.rs | //! Human interface device (HID) function.
//!
//! The Linux kernel configuration option `CONFIG_USB_CONFIGFS_F_HID` must be enabled.
use std::{
ffi::OsString,
io::{Error, ErrorKind, Result},
};
use super::{
util::{FunctionDir, Status},
Function, Handle,
};
/// Builder for USB human interface device (HID) function.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct HidBuilder {
/// HID subclass to use.
pub sub_class: u8,
/// HID protocol to use.
pub protocol: u8,
/// Data to be used in HID reports.
pub report_desc: Vec<u8>,
/// HID report length.
pub report_len: u8,
/// No out endpoint?
pub no_out_endpoint: bool,
}
impl HidBuilder {
/// Build the USB function.
///
/// The returned handle must be added to a USB gadget configuration.
pub fn build(self) -> (Hid, Handle) {
let dir = FunctionDir::new();
(Hid { dir: dir.clone() }, Handle::new(HidFunction { builder: self, dir }))
}
}
#[derive(Debug)]
struct HidFunction {
builder: HidBuilder,
dir: FunctionDir,
}
impl Function for HidFunction {
fn driver(&self) -> OsString {
"hid".into()
}
fn dir(&self) -> FunctionDir {
self.dir.clone()
}
fn register(&self) -> Result<()> {
self.dir.write("subclass", self.builder.sub_class.to_string())?;
self.dir.write("protocol", self.builder.protocol.to_string())?;
self.dir.write("report_desc", &self.builder.report_desc)?;
self.dir.write("report_length", self.builder.report_len.to_string())?;
self.dir.write("no_out_endpoint", if self.builder.no_out_endpoint { "1" } else { "0" })?;
Ok(())
}
}
/// USB human interface device (HID) function.
#[derive(Debug)]
pub struct Hid {
dir: FunctionDir,
}
impl Hid {
/// Creates a new USB human interface device (HID) builder.
pub fn builder() -> HidBuilder {
HidBuilder { sub_class: 0, protocol: 0, report_desc: Vec::new(), report_len: 0, no_out_endpoint: false }
}
/// Access to registration status.
pub fn status(&self) -> Status {
self.dir.status()
}
/// Device major and minor numbers.
pub fn device(&self) -> Result<(u32, u32)> {
let dev = self.dir.read_string("dev")?;
let Some((major, minor)) = dev.split_once(':') else {
return Err(Error::new(ErrorKind::InvalidData, "invalid device number format"));
};
let major = major.parse().map_err(|err| Error::new(ErrorKind::InvalidData, err))?;
let minor = minor.parse().map_err(|err| Error::new(ErrorKind::InvalidData, err))?;
Ok((major, minor))
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/printer.rs | src/function/printer.rs | //! Printer function.
//!
//! The Linux kernel configuration option `CONFIG_USB_CONFIGFS_F_PRINTER` must be enabled.
//!
//! A device file at `/dev/g_printerN` will be created for each instance of the function, where N
//! instance number. See `examples/printer.rs` for an example.
use bitflags::bitflags;
use std::{ffi::OsString, io::Result};
use super::{
util::{FunctionDir, Status},
Function, Handle,
};
/// Get printer status ioctrl ID
pub const GADGET_GET_PRINTER_STATUS: u8 = 0x21;
/// Set printer status ioctrl ID
pub const GADGET_SET_PRINTER_STATUS: u8 = 0x22;
bitflags! {
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
/// [Printer status flags](https://www.usb.org/sites/default/files/usbprint11a021811.pdf)
pub struct StatusFlags: u8 {
/// Printer not in error state
const NOT_ERROR = (1 << 3);
/// Printer selected
const SELECTED = (1 << 4);
/// Printer out of paper
const PAPER_EMPTY = (1 << 5);
}
}
/// Builder for USB printer function.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PrinterBuilder {
/// The PNP ID string used for this printer.
pub pnp_string: Option<String>,
/// The number of 8k buffers to use per endpoint. The default is 10.
pub qlen: Option<u8>,
}
impl PrinterBuilder {
/// Build the USB function.
///
/// The returned handle must be added to a USB gadget configuration.
pub fn build(self) -> (Printer, Handle) {
let dir = FunctionDir::new();
(Printer { dir: dir.clone() }, Handle::new(PrinterFunction { builder: self, dir }))
}
}
#[derive(Debug)]
struct PrinterFunction {
builder: PrinterBuilder,
dir: FunctionDir,
}
impl Function for PrinterFunction {
fn driver(&self) -> OsString {
"printer".into()
}
fn dir(&self) -> FunctionDir {
self.dir.clone()
}
fn register(&self) -> Result<()> {
if let Some(pnp_string) = &self.builder.pnp_string {
self.dir.write("pnp_string", pnp_string)?;
}
if let Some(qlen) = self.builder.qlen {
self.dir.write("q_len", qlen.to_string())?;
}
Ok(())
}
}
/// USB printer function.
#[derive(Debug)]
pub struct Printer {
dir: FunctionDir,
}
impl Printer {
/// Creates a new USB printer builder.
pub fn builder() -> PrinterBuilder {
PrinterBuilder { pnp_string: None, qlen: None }
}
/// Creates a new USB printer function and handle with f_printer defaults
pub fn new(self) -> (Printer, Handle) {
Self::builder().build()
}
/// Access to registration status.
pub fn status(&self) -> Status {
self.dir.status()
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/util.rs | src/function/util.rs | //! Utils for implementing USB gadget functions.
use std::{
collections::HashMap,
ffi::{OsStr, OsString},
fmt, fs,
io::{Error, ErrorKind, Result},
os::unix::prelude::{OsStrExt, OsStringExt},
path::{Component, Path, PathBuf},
sync::{Arc, Mutex, MutexGuard, Once, OnceLock},
};
use crate::{function::register_remove_handlers, trim_os_str};
/// USB gadget function.
pub trait Function: fmt::Debug + Send + Sync + 'static {
/// Name of the function driver.
fn driver(&self) -> OsString;
/// Function directory.
fn dir(&self) -> FunctionDir;
/// Register the function in configfs at the specified path.
fn register(&self) -> Result<()>;
/// Notifies the function that the USB gadget is about to be removed.
fn pre_removal(&self) -> Result<()> {
Ok(())
}
/// Notifies the function that the USB gadget has been removed.
fn post_removal(&self, _dir: &Path) -> Result<()> {
Ok(())
}
}
/// USB function registration state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum State {
/// Function is not registered.
Unregistered,
/// Function is registered but not bound to UDC.
Registered,
/// Function is registered and bound to UDC.
Bound,
/// Function was removed and will stay in this state.
Removed,
}
/// Provides access to the status of a USB function.
#[derive(Clone, Debug)]
pub struct Status(FunctionDir);
impl Status {
/// Registration state.
pub fn state(&self) -> State {
let inner = self.0.inner.lock().unwrap();
match (&inner.dir, inner.dir_was_set, inner.bound) {
(None, false, _) => State::Unregistered,
(None, true, _) => State::Removed,
(Some(_), _, false) => State::Registered,
(Some(_), _, true) => State::Bound,
}
}
/// Waits for the function to be bound to a UDC.
///
/// Returns with a broken pipe error if gadget is removed.
#[cfg(feature = "tokio")]
pub async fn bound(&self) -> Result<()> {
loop {
let notifier = self.0.notify.notified();
match self.state() {
State::Bound => return Ok(()),
State::Removed => return Err(Error::new(ErrorKind::BrokenPipe, "gadget was removed")),
_ => (),
}
notifier.await;
}
}
/// Waits for the function to be unbound from a UDC.
#[cfg(feature = "tokio")]
pub async fn unbound(&self) {
loop {
let notifier = self.0.notify.notified();
if self.state() != State::Bound {
return;
}
notifier.await;
}
}
/// The USB gadget function directory in configfs, if registered.
pub fn path(&self) -> Option<PathBuf> {
self.0.inner.lock().unwrap().dir.clone()
}
}
/// USB gadget function directory container.
///
/// Stores the directory in configfs of a USB function and provides access methods.
#[derive(Clone)]
pub struct FunctionDir {
inner: Arc<Mutex<FunctionDirInner>>,
#[cfg(feature = "tokio")]
notify: Arc<tokio::sync::Notify>,
}
#[derive(Debug, Default)]
struct FunctionDirInner {
dir: Option<PathBuf>,
dir_was_set: bool,
bound: bool,
}
impl fmt::Debug for FunctionDir {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("FunctionDir").field(&*self.inner.lock().unwrap()).finish()
}
}
impl Default for FunctionDir {
fn default() -> Self {
Self::new()
}
}
impl FunctionDir {
/// Creates an empty function directory container.
pub fn new() -> Self {
Self {
inner: Arc::new(Mutex::new(FunctionDirInner::default())),
#[cfg(feature = "tokio")]
notify: Arc::new(tokio::sync::Notify::new()),
}
}
pub(crate) fn set_dir(&self, function_dir: &Path) {
let mut inner = self.inner.lock().unwrap();
inner.dir = Some(function_dir.to_path_buf());
inner.dir_was_set = true;
#[cfg(feature = "tokio")]
self.notify.notify_waiters();
}
pub(crate) fn reset_dir(&self) {
self.inner.lock().unwrap().dir = None;
#[cfg(feature = "tokio")]
self.notify.notify_waiters();
}
pub(crate) fn set_bound(&self, bound: bool) {
self.inner.lock().unwrap().bound = bound;
#[cfg(feature = "tokio")]
self.notify.notify_waiters();
}
/// Create status accessor.
pub fn status(&self) -> Status {
Status(self.clone())
}
/// The USB gadget function directory in configfs.
pub fn dir(&self) -> Result<PathBuf> {
self.inner
.lock()
.unwrap()
.dir
.clone()
.ok_or_else(|| Error::new(ErrorKind::NotFound, "USB function not registered"))
}
/// Driver name.
pub fn driver(&self) -> Result<OsString> {
let dir = self.dir()?;
let (driver, _instance) = split_function_dir(&dir).unwrap();
Ok(driver.to_os_string())
}
/// Instance name.
pub fn instance(&self) -> Result<OsString> {
let dir = self.dir()?;
let (_driver, instance) = split_function_dir(&dir).unwrap();
Ok(instance.to_os_string())
}
/// Path to the specified property.
pub fn property_path(&self, name: impl AsRef<Path>) -> Result<PathBuf> {
let path = name.as_ref();
if path.components().all(|c| matches!(c, Component::Normal(_))) {
Ok(self.dir()?.join(path))
} else {
Err(Error::new(ErrorKind::InvalidInput, "property path must be relative"))
}
}
/// Create a subdirectory.
pub fn create_dir(&self, name: impl AsRef<Path>) -> Result<()> {
let path = self.property_path(name)?;
log::debug!("creating directory {}", path.display());
fs::create_dir(path)
}
/// Create a subdirectory and its parent directories.
pub fn create_dir_all(&self, name: impl AsRef<Path>) -> Result<()> {
let path = self.property_path(name)?;
log::debug!("creating directories {}", path.display());
fs::create_dir_all(path)
}
/// Remove a subdirectory.
pub fn remove_dir(&self, name: impl AsRef<Path>) -> Result<()> {
let path = self.property_path(name)?;
log::debug!("removing directory {}", path.display());
fs::remove_dir(path)
}
/// Read a binary property.
pub fn read(&self, name: impl AsRef<Path>) -> Result<Vec<u8>> {
let path = self.property_path(name)?;
let res = fs::read(&path);
match &res {
Ok(value) => {
log::debug!("read property {} with value {}", path.display(), String::from_utf8_lossy(value))
}
Err(err) => log::debug!("reading property {} failed: {}", path.display(), err),
}
res
}
/// Read and trim a string property.
pub fn read_string(&self, name: impl AsRef<Path>) -> Result<String> {
let mut data = self.read(name)?;
while data.last() == Some(&b'\0') || data.last() == Some(&b' ') || data.last() == Some(&b'\n') {
data.truncate(data.len() - 1);
}
Ok(String::from_utf8(data).map_err(|err| Error::new(ErrorKind::InvalidData, err))?.trim().to_string())
}
/// Read an trim an OS string property.
pub fn read_os_string(&self, name: impl AsRef<Path>) -> Result<OsString> {
Ok(trim_os_str(&OsString::from_vec(self.read(name)?)).to_os_string())
}
/// Write a property.
pub fn write(&self, name: impl AsRef<Path>, value: impl AsRef<[u8]>) -> Result<()> {
let path = self.property_path(name)?;
let value = value.as_ref();
log::debug!("setting property {} to {}", path.display(), String::from_utf8_lossy(value));
fs::write(path, value)
}
/// Create a symbolic link.
pub fn symlink(&self, target: impl AsRef<Path>, link: impl AsRef<Path>) -> Result<()> {
let target = self.property_path(target)?;
let link = self.property_path(link)?;
log::debug!("creating symlink {} -> {}", link.display(), target.display());
std::os::unix::fs::symlink(target, link)
}
}
/// Split configfs function directory path into driver name and instance name.
pub fn split_function_dir(function_dir: &Path) -> Option<(&OsStr, &OsStr)> {
let name = function_dir.file_name()?;
let name = name.as_bytes();
let dot = name.iter().enumerate().find_map(|(i, c)| if *c == b'.' { Some(i) } else { None })?;
let driver = &name[..dot];
let instance = &name[dot + 1..];
Some((OsStr::from_bytes(driver), OsStr::from_bytes(instance)))
}
/// Handler function for removing function instance.
type RemoveHandler = Arc<dyn Fn(PathBuf) -> Result<()> + Send + Sync>;
/// Registered handlers for removing function instances.
static REMOVE_HANDLERS: OnceLock<Mutex<HashMap<OsString, RemoveHandler>>> = OnceLock::new();
/// Registered handlers for removing function instances.
fn remove_handlers() -> MutexGuard<'static, HashMap<OsString, RemoveHandler>> {
let handlers = REMOVE_HANDLERS.get_or_init(|| Mutex::new(HashMap::new()));
handlers.lock().unwrap()
}
/// Initializes handlers for removing function instances.
pub(crate) fn init_remove_handlers() {
static ONCE: Once = Once::new();
ONCE.call_once(|| {
register_remove_handlers();
});
}
/// Register a function remove handler for the specified function driver.
pub fn register_remove_handler(
driver: impl AsRef<OsStr>, handler: impl Fn(PathBuf) -> Result<()> + Send + Sync + 'static,
) {
remove_handlers().insert(driver.as_ref().to_os_string(), Arc::new(handler));
}
/// Calls the remove handler for the function directory, if any is registered.
pub(crate) fn call_remove_handler(function_dir: &Path) -> Result<()> {
let Some((driver, _)) = split_function_dir(function_dir) else {
return Err(Error::new(ErrorKind::InvalidInput, "invalid function directory"));
};
let handler_opt = remove_handlers().get(driver).cloned();
match handler_opt {
Some(handler) => handler(function_dir.to_path_buf()),
None => Ok(()),
}
}
/// Value channel.
pub(crate) mod value {
use std::{
error::Error,
fmt,
fmt::Display,
io, mem,
sync::{mpsc, Mutex},
};
/// Value was already sent.
#[derive(Debug, Clone)]
pub struct AlreadySentError;
impl Display for AlreadySentError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "value already sent")
}
}
impl Error for AlreadySentError {}
/// Sender of value channel.
#[derive(Debug)]
pub struct Sender<T>(Mutex<Option<mpsc::Sender<T>>>);
impl<T> Sender<T> {
/// Sends a value.
///
/// This can only be called once.
pub fn send(&self, value: T) -> Result<(), AlreadySentError> {
match self.0.lock().unwrap().take() {
Some(tx) => {
let _ = tx.send(value);
Ok(())
}
None => Err(AlreadySentError),
}
}
}
/// Value channel receive error.
#[derive(Debug, Clone)]
pub enum RecvError {
/// Value was not yet sent.
Empty,
/// Sender was dropped without sending a value.
Disconnected,
/// Value was taken.
Taken,
}
impl Display for RecvError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
RecvError::Empty => write!(f, "value was not yet sent"),
RecvError::Disconnected => write!(f, "no value was sent"),
RecvError::Taken => write!(f, "value was taken"),
}
}
}
impl Error for RecvError {}
impl From<mpsc::RecvError> for RecvError {
fn from(_err: mpsc::RecvError) -> Self {
Self::Disconnected
}
}
impl From<mpsc::TryRecvError> for RecvError {
fn from(err: mpsc::TryRecvError) -> Self {
match err {
mpsc::TryRecvError::Empty => Self::Empty,
mpsc::TryRecvError::Disconnected => Self::Disconnected,
}
}
}
impl From<RecvError> for io::Error {
fn from(err: RecvError) -> Self {
match err {
RecvError::Empty => io::Error::new(io::ErrorKind::WouldBlock, err),
RecvError::Disconnected => io::Error::new(io::ErrorKind::BrokenPipe, err),
RecvError::Taken => io::Error::new(io::ErrorKind::Other, err),
}
}
}
/// Receiver state.
#[derive(Default)]
enum State<T> {
Receiving(Mutex<mpsc::Receiver<T>>),
Received(T),
#[default]
Taken,
}
/// Receiver of value channel.
#[derive(Default)]
pub struct Receiver<T>(State<T>);
impl<T: fmt::Debug> fmt::Debug for Receiver<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.0 {
State::Receiving(_) => write!(f, "<uninit>"),
State::Received(v) => v.fmt(f),
State::Taken => write!(f, "<taken>"),
}
}
}
impl<T> Receiver<T> {
/// Get the value, if it has been sent.
pub fn get(&mut self) -> Result<&mut T, RecvError> {
match &mut self.0 {
State::Receiving(rx) => {
let value = rx.get_mut().unwrap().try_recv()?;
self.0 = State::Received(value);
}
State::Taken => return Err(RecvError::Taken),
_ => (),
}
let State::Received(value) = &mut self.0 else { unreachable!() };
Ok(value)
}
/// Wait for the value.
#[allow(dead_code)]
pub fn wait(&mut self) -> Result<&mut T, RecvError> {
if let State::Receiving(rx) = &mut self.0 {
let value = rx.get_mut().unwrap().recv()?;
self.0 = State::Received(value);
}
self.get()
}
/// Take the value, if it has been sent.
#[allow(dead_code)]
pub fn take(&mut self) -> Result<T, RecvError> {
self.get()?;
let State::Received(value) = mem::take(&mut self.0) else { unreachable!() };
Ok(value)
}
}
/// Creates a new value channel.
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
let (tx, rx) = mpsc::channel();
(Sender(Mutex::new(Some(tx))), Receiver(State::Receiving(Mutex::new(rx))))
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/mod.rs | src/function/mod.rs | //! USB gadget functions.
pub mod audio;
pub mod custom;
pub mod hid;
pub mod midi;
pub mod msd;
pub mod net;
pub mod other;
pub mod printer;
pub mod serial;
pub mod util;
pub mod video;
use std::{cmp, hash, hash::Hash, sync::Arc};
use self::util::{register_remove_handler, Function};
/// USB gadget function handle.
///
/// Use a member of the [function module](crate::function) to obtain a
/// gadget function handle.
#[derive(Debug, Clone)]
pub struct Handle(Arc<dyn Function>);
impl Handle {
pub(crate) fn new<F: Function>(f: F) -> Self {
Self(Arc::new(f))
}
}
impl Handle {
pub(crate) fn get(&self) -> &dyn Function {
&*self.0
}
}
impl PartialEq for Handle {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for Handle {}
impl PartialOrd for Handle {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Handle {
fn cmp(&self, other: &Self) -> cmp::Ordering {
Arc::as_ptr(&self.0).cast::<()>().cmp(&Arc::as_ptr(&other.0).cast::<()>())
}
}
impl Hash for Handle {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
Arc::as_ptr(&self.0).hash(state);
}
}
/// Register included remove handlers.
fn register_remove_handlers() {
register_remove_handler(custom::driver(), custom::remove_handler);
register_remove_handler(msd::driver(), msd::remove_handler);
register_remove_handler(video::driver(), video::remove_handler);
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/other.rs | src/function/other.rs | //! Other USB function.
use std::{
collections::HashMap,
ffi::{OsStr, OsString},
io::{Error, ErrorKind, Result},
os::unix::prelude::OsStrExt,
path::{Component, Path, PathBuf},
};
use super::{
util::{FunctionDir, Status},
Function, Handle,
};
/// Builder for other USB function implemented by a kernel function driver.
#[derive(Debug, Clone)]
pub struct OtherBuilder {
/// Function driver name.
driver: OsString,
/// Properties to set.
properties: HashMap<PathBuf, Vec<u8>>,
}
impl OtherBuilder {
/// Build the USB function.
///
/// The returned handle must be added to a USB gadget configuration.
pub fn build(self) -> (Other, Handle) {
let dir = FunctionDir::new();
(Other { dir: dir.clone() }, Handle::new(OtherFunction { builder: self, dir }))
}
/// Set a property value.
pub fn set(&mut self, name: impl AsRef<Path>, value: impl AsRef<[u8]>) -> Result<()> {
let path = name.as_ref().to_path_buf();
if !path.components().all(|c| matches!(c, Component::Normal(_))) {
return Err(Error::new(ErrorKind::InvalidInput, "property path must be relative"));
}
self.properties.insert(path, value.as_ref().to_vec());
Ok(())
}
}
#[derive(Debug)]
struct OtherFunction {
builder: OtherBuilder,
dir: FunctionDir,
}
impl Function for OtherFunction {
fn driver(&self) -> OsString {
self.builder.driver.clone()
}
fn dir(&self) -> FunctionDir {
self.dir.clone()
}
fn register(&self) -> Result<()> {
for (prop, val) in &self.builder.properties {
self.dir.write(prop, val)?;
}
Ok(())
}
}
/// Other USB function implemented by a kernel function driver.
///
/// Driver name `xxx` corresponds to kernel module `usb_f_xxx.ko`.
#[derive(Debug)]
pub struct Other {
dir: FunctionDir,
}
impl Other {
/// Create a new other function implemented by the specified kernel function driver.
pub fn new(driver: impl AsRef<OsStr>) -> Result<(Other, Handle)> {
Ok(Self::builder(driver)?.build())
}
/// Build a new other function implemented by the specified kernel function driver.
pub fn builder(driver: impl AsRef<OsStr>) -> Result<OtherBuilder> {
let driver = driver.as_ref();
if driver.as_bytes().contains(&b'.') || driver.as_bytes().contains(&b'/') || !driver.is_ascii() {
return Err(Error::new(ErrorKind::InvalidInput, "invalid driver name"));
}
Ok(OtherBuilder { driver: driver.to_os_string(), properties: HashMap::new() })
}
/// Access to registration status.
pub fn status(&self) -> Status {
self.dir.status()
}
/// Get a property value.
pub fn get(&self, name: impl AsRef<Path>) -> Result<Vec<u8>> {
self.dir.read(name)
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/msd.rs | src/function/msd.rs | //! Mass Storage Device (MSD) function.
//!
//! The Linux kernel configuration option `CONFIG_USB_CONFIGFS_MASS_STORAGE` must be enabled.
use std::{
ffi::{OsStr, OsString},
fs,
io::{Error, ErrorKind, Result},
os::unix::prelude::OsStrExt,
path::{Path, PathBuf},
};
use super::{
util::{FunctionDir, Status},
Function, Handle,
};
pub(crate) fn driver() -> &'static OsStr {
OsStr::new("mass_storage")
}
/// Logical unit (LUN) of mass storage device (MSD).
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Lun {
/// Flag specifying access to the LUN shall be read-only.
///
/// This is implied if CD-ROM emulation is enabled as well as
/// when it was impossible to open the backing file in R/W mode.
pub read_only: bool,
/// Flag specifying that LUN shall be reported as being a CD-ROM.
pub cdrom: bool,
/// Flag specifying that FUA flag in SCSI WRITE(10,12).
pub no_fua: bool,
/// Flag specifying that LUN shall be indicated as being removable.
pub removable: bool,
/// The path to the backing file for the LUN.
///
/// Required if LUN is not marked as removable.
file: Option<PathBuf>,
/// Inquiry string.
pub inquiry_string: String,
}
impl Lun {
/// Create a new LUN backed by the specified file.
pub fn new(file: impl AsRef<Path>) -> Result<Self> {
let mut this = Self::default();
this.set_file(Some(file))?;
Ok(this)
}
/// Creates a new LUN without a medium.
pub fn empty() -> Self {
Self::default()
}
/// Set the path to the backing file for the LUN.
pub fn set_file<F: AsRef<Path>>(&mut self, file: Option<F>) -> Result<()> {
match file {
Some(file) => {
let file = file.as_ref();
if !file.is_absolute() {
return Err(Error::new(ErrorKind::InvalidInput, "the LUN file path must be absolute"));
}
self.file = Some(file.to_path_buf());
}
None => self.file = None,
}
Ok(())
}
fn dir_name(idx: usize) -> String {
format!("lun.{idx}")
}
}
impl Default for Lun {
fn default() -> Self {
Self {
read_only: false,
cdrom: false,
no_fua: false,
removable: true,
file: None,
inquiry_string: String::new(),
}
}
}
/// Builder for USB Mass Storage Device (MSD) function.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct MsdBuilder {
/// Set to permit function to halt bulk endpoints.
///
/// Disabled on some USB devices known not to work correctly.
pub stall: Option<bool>,
/// Logical units.
pub luns: Vec<Lun>,
}
impl MsdBuilder {
/// Build the USB function.
///
/// The returned handle must be added to a USB gadget configuration.
pub fn build(self) -> (Msd, Handle) {
let dir = FunctionDir::new();
(Msd { dir: dir.clone() }, Handle::new(MsdFunction { builder: self, dir }))
}
/// Adds a LUN.
pub fn add_lun(&mut self, lun: Lun) {
self.luns.push(lun);
}
/// Adds a LUN.
#[must_use]
pub fn with_lun(mut self, lun: Lun) -> Self {
self.add_lun(lun);
self
}
}
#[derive(Debug)]
struct MsdFunction {
builder: MsdBuilder,
dir: FunctionDir,
}
impl Function for MsdFunction {
fn driver(&self) -> OsString {
driver().into()
}
fn dir(&self) -> FunctionDir {
self.dir.clone()
}
fn register(&self) -> Result<()> {
if self.builder.luns.is_empty() {
return Err(Error::new(ErrorKind::InvalidInput, "at least one LUN must exist"));
}
if let Some(stall) = self.builder.stall {
self.dir.write("stall", if stall { "1" } else { "0" })?;
}
for (idx, lun) in self.builder.luns.iter().enumerate() {
let lun_dir_name = Lun::dir_name(idx);
if idx != 0 {
self.dir.create_dir(&lun_dir_name)?;
}
self.dir.write(format!("{lun_dir_name}/ro"), if lun.read_only { "1" } else { "0" })?;
self.dir.write(format!("{lun_dir_name}/cdrom"), if lun.cdrom { "1" } else { "0" })?;
self.dir.write(format!("{lun_dir_name}/nofua"), if lun.no_fua { "1" } else { "0" })?;
self.dir.write(format!("{lun_dir_name}/removable"), if lun.removable { "1" } else { "0" })?;
self.dir.write(format!("{lun_dir_name}/inquiry_string"), &lun.inquiry_string)?;
if let Some(file) = &lun.file {
self.dir.write(format!("{lun_dir_name}/file"), file.as_os_str().as_bytes())?;
}
}
Ok(())
}
}
/// USB Mass Storage Device (MSD) function.
#[derive(Debug)]
pub struct Msd {
dir: FunctionDir,
}
impl Msd {
/// Creates a new USB Mass Storage Device (MSD) with the specified backing file.
pub fn new(file: impl AsRef<Path>) -> Result<(Msd, Handle)> {
let mut builder = Self::builder();
builder.luns.push(Lun::new(file)?);
Ok(builder.build())
}
/// Creates a new USB Mass Storage Device (MSD) builder.
pub fn builder() -> MsdBuilder {
MsdBuilder { stall: None, luns: Vec::new() }
}
/// Access to registration status.
pub fn status(&self) -> Status {
self.dir.status()
}
/// Forcibly detach the backing file from the LUN, regardless of whether the host has allowed
/// it.
pub fn force_eject(&self, lun: usize) -> Result<()> {
let lun_dir_name = Lun::dir_name(lun);
self.dir.write(format!("{lun_dir_name}/forced_eject"), "1")
}
/// Set the path to the backing file for the LUN.
pub fn set_file<P: AsRef<Path>>(&self, lun: usize, file: Option<P>) -> Result<()> {
let lun_dir_name = Lun::dir_name(lun);
let file = match file {
Some(file) => {
let file = file.as_ref();
if !file.is_absolute() {
return Err(Error::new(ErrorKind::InvalidInput, "the LUN file path must be absolute"));
}
file.as_os_str().as_bytes().to_vec()
}
None => Vec::new(),
};
self.dir.write(format!("{lun_dir_name}/file"), file)
}
}
pub(crate) fn remove_handler(dir: PathBuf) -> Result<()> {
for entry in fs::read_dir(dir)? {
let Ok(entry) = entry else { continue };
if entry.file_type()?.is_dir()
&& entry.file_name().as_bytes().contains(&b'.')
&& entry.file_name() != "lun.0"
{
fs::remove_dir(entry.path())?;
}
}
Ok(())
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/midi.rs | src/function/midi.rs | //! Musical Instrument Digital Interface (MIDI) function.
//!
//! The Linux kernel configuration option `CONFIG_USB_CONFIGFS_F_MIDI` must be enabled.
//! Can use `amidi -l` once the gadget is configured to list the MIDI devices.
//!
//! # Example
//!
//! ```no_run
//! use usb_gadget::function::midi::Midi;
//! use usb_gadget::{default_udc, Class, Config, Gadget, Id, Strings};
//!
//! let mut builder = Midi::builder();
//! builder.id = Some("midi".to_string());
//! builder.in_ports = Some(1);
//! builder.out_ports = Some(1);
//! let (midi, func) = builder.build();
//!
//! let udc = default_udc().expect("cannot get UDC");
//! let reg =
//! // USB device descriptor base class 0, 0, 0: use Interface Descriptors
//! // Linux Foundation VID Gadget PID
//! Gadget::new(Class::new(0, 0, 0), Id::new(0x1d6b, 0x0104), Strings::new("Clippy Manufacturer", "Rust MIDI", "RUST0123456"))
//! .with_config(Config::new("MIDI Config 1").with_function(func))
//! .bind(&udc)
//! .expect("cannot bind to UDC");
//!
//! println!(
//! "USB MIDI {} at {} to {} status {:?}",
//! reg.name().to_string_lossy(),
//! reg.path().display(),
//! udc.name().to_string_lossy(),
//! midi.status()
//! );
//! ```
use std::{ffi::OsString, io::Result};
use super::{
util::{FunctionDir, Status},
Function, Handle,
};
/// Builder for USB musical instrument digital interface (MIDI) function.
///
/// None value will use the f_midi module default.
/// See `drivers/usb/gadget/function/f_midi.c#L1274`.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct MidiBuilder {
/// MIDI buffer length
pub buflen: Option<u16>,
/// ID string for the USB MIDI adapter
pub id: Option<String>,
/// Number of MIDI input ports
pub in_ports: Option<u8>,
/// Number of MIDI output ports
pub out_ports: Option<u8>,
/// Sound device index for the MIDI adapter.
/// `None` for automatic selection.
///
/// There must be a sound device available with this index.
/// If the device fails to register and in dmesg one sees
/// `cannot find the slot for index $index (range 0-1), error: -16`,
/// then the index is not available.
/// Most likely the index is already in use by the physical sound card. T
/// ry another index within range or unload the physical sound card driver.
/// See [USB Gadget MIDI](https://linux-sunxi.org/USB_Gadget/MIDI).
pub index: Option<u8>,
/// USB read request queue length
pub qlen: Option<u8>,
}
impl MidiBuilder {
/// Build the USB function.
///
/// The returned handle must be added to a USB gadget configuration.
pub fn build(self) -> (Midi, Handle) {
let dir = FunctionDir::new();
(Midi { dir: dir.clone() }, Handle::new(MidiFunction { builder: self, dir }))
}
}
#[derive(Debug)]
struct MidiFunction {
builder: MidiBuilder,
dir: FunctionDir,
}
impl Function for MidiFunction {
fn driver(&self) -> OsString {
"midi".into()
}
fn dir(&self) -> FunctionDir {
self.dir.clone()
}
fn register(&self) -> Result<()> {
if let Some(buflen) = self.builder.buflen {
self.dir.write("buflen", buflen.to_string())?;
}
if let Some(id) = &self.builder.id {
self.dir.write("id", id)?;
}
if let Some(in_ports) = self.builder.in_ports {
self.dir.write("in_ports", in_ports.to_string())?;
}
if let Some(out_ports) = self.builder.out_ports {
self.dir.write("out_ports", out_ports.to_string())?;
}
if let Some(index) = self.builder.index {
self.dir.write("index", index.to_string())?;
}
if let Some(qlen) = self.builder.qlen {
self.dir.write("qlen", qlen.to_string())?;
}
Ok(())
}
}
/// USB musical instrument digital interface (MIDI) function.
#[derive(Debug)]
pub struct Midi {
dir: FunctionDir,
}
impl Midi {
/// Creates a new USB musical instrument digital interface (MIDI) builder.
pub fn builder() -> MidiBuilder {
MidiBuilder::default()
}
/// Access to registration status.
pub fn status(&self) -> Status {
self.dir.status()
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/audio.rs | src/function/audio.rs | //! USB Audio Class 2 (UAC2) function.
//!
//! The Linux kernel configuration option `CONFIG_USB_CONFIGFS_F_UAC2` must be enabled.
//!
//! # Example
//!
//! ```no_run
//! use usb_gadget::function::audio::{Uac2, Channel};
//! use usb_gadget::{default_udc, Class, Config, Gadget, Id, Strings};
//!
//! // capture: 8 ch, 48000 Hz, 24 bit, playback: 2 ch, 48000 Hz, 16 bit
//! let (audio, func) = Uac2::new(Channel::new(0b1111_1111, 48000, 24 / 8), Channel::new(0b11, 48000, 16 / 8));
//!
//! let udc = default_udc().expect("cannot get UDC");
//! let reg =
//! // USB device descriptor base class 0, 0, 0: use Interface Descriptors
//! // Linux Foundation VID Gadget PID
//! Gadget::new(Class::new(0, 0, 0), Id::new(0x1d6b, 0x0104), Strings::new("Clippy Manufacturer", "Rust UAC2", "RUST0123456"))
//! .with_config(Config::new("Audio Config 1").with_function(func))
//! .bind(&udc)
//! .expect("cannot bind to UDC");
//!
//! println!(
//! "UAC2 audio {} at {} to {} status {:?}",
//! reg.name().to_string_lossy(),
//! reg.path().display(),
//! udc.name().to_string_lossy(),
//! audio.status()
//! );
//! ```
use std::{ffi::OsString, io::Result};
use super::{
util::{FunctionDir, Status},
Function, Handle,
};
/// Audio channel configuration.
#[derive(Debug, Clone, Default)]
pub struct Channel {
/// Audio channel mask. Set to 0 to disable the audio endpoint.
///
/// The audio channel mask is a bit mask of the audio channels. The mask is a 32-bit integer
/// with each bit representing a channel. The least significant bit is channel 1. The mask is
/// used to specify the audio channels that are present in the audio stream. For example, a
/// stereo stream would have a mask of 0x3 (channel 1 and channel 2).
pub channel_mask: Option<u32>,
/// Audio sample rate (Hz)
pub sample_rate: Option<u32>,
/// Audio sample size (bytes) so 2 bytes per sample (16 bit) would be 2.
pub sample_size: Option<u32>,
}
impl Channel {
/// Creates a new audio channel with the specified channel mask, sample rate (Hz), and sample
/// size (bytes).
pub fn new(channel_mask: u32, sample_rate: u32, sample_size: u32) -> Self {
Self { channel_mask: Some(channel_mask), sample_rate: Some(sample_rate), sample_size: Some(sample_size) }
}
}
/// Audio device configuration.
///
/// Fields are optional and will be set to f_uac2 default values if not specified, see
/// drivers/usb/gadget/function/u_uac2.h. Not all fields are supported by all kernels; permission
/// denied errors may occur if unsupported fields are set.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct Uac2Config {
/// Audio channel configuration.
pub channel: Channel,
/// Audio sync type (capture only)
pub sync_type: Option<u32>,
/// Capture bInterval for HS/SS (1-4: fixed, 0: auto)
pub hs_interval: Option<u8>,
/// If channel has mute
pub mute_present: Option<bool>,
/// Terminal type
pub terminal_type: Option<u8>,
/// If channel has volume
pub volume_present: Option<bool>,
/// Minimum volume (in 1/256 dB)
pub volume_min: Option<i16>,
/// Maximum volume (in 1/256 dB)
pub volume_max: Option<i16>,
/// Resolution of volume control (in 1/256 dB)
pub volume_resolution: Option<i16>,
/// Name of the volume control function
pub volume_name: Option<String>,
/// Name of the input terminal
pub input_terminal_name: Option<String>,
/// Name of the input terminal channel
pub input_terminal_channel_name: Option<String>,
/// Name of the output terminal
pub output_terminal_name: Option<String>,
}
/// Builder for USB audio class 2 (UAC2) function.
///
/// Set capture or playback channel_mask to 0 to disable the audio endpoint.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct Uac2Builder {
/// Audio capture configuration.
pub capture: Uac2Config,
/// Audio playback configuration.
pub playback: Uac2Config,
/// Maximum extra bandwidth in async mode
pub fb_max: Option<u32>,
/// The number of pre-allocated request for both capture and playback
pub request_number: Option<u32>,
/// The name of the interface
pub function_name: Option<String>,
/// Topology control name
pub control_name: Option<String>,
/// The name of the input clock source
pub clock_source_in_name: Option<String>,
/// The name of the output clock source
pub clock_source_out_name: Option<String>,
}
impl Uac2Builder {
/// Build the USB function.
///
/// The returned handle must be added to a USB gadget configuration.
pub fn build(self) -> (Uac2, Handle) {
let dir = FunctionDir::new();
(Uac2 { dir: dir.clone() }, Handle::new(Uac2Function { builder: self, dir }))
}
/// Set audio capture configuration.
#[must_use]
pub fn with_capture_config(mut self, capture: Uac2Config) -> Self {
self.capture = capture;
self
}
/// Set audio playback configuration.
#[must_use]
pub fn with_playback_config(mut self, playback: Uac2Config) -> Self {
self.playback = playback;
self
}
}
#[derive(Debug)]
struct Uac2Function {
builder: Uac2Builder,
dir: FunctionDir,
}
impl Function for Uac2Function {
fn driver(&self) -> OsString {
"uac2".into()
}
fn dir(&self) -> FunctionDir {
self.dir.clone()
}
fn register(&self) -> Result<()> {
// capture
if let Some(channel_mask) = self.builder.capture.channel.channel_mask {
self.dir.write("c_chmask", channel_mask.to_string())?;
}
if let Some(sample_rate) = self.builder.capture.channel.sample_rate {
self.dir.write("c_srate", sample_rate.to_string())?;
}
if let Some(sample_size) = self.builder.capture.channel.sample_size {
self.dir.write("c_ssize", sample_size.to_string())?;
}
if let Some(sync_type) = self.builder.capture.sync_type {
self.dir.write("c_sync", sync_type.to_string())?;
}
if let Some(hs_interval) = self.builder.capture.hs_interval {
self.dir.write("c_hs_bint", hs_interval.to_string())?;
}
if let Some(mute_present) = self.builder.capture.mute_present {
self.dir.write("c_mute_present", (mute_present as u8).to_string())?;
}
if let Some(volume_present) = self.builder.capture.volume_present {
self.dir.write("c_volume_present", (volume_present as u8).to_string())?;
}
if let Some(volume_min) = self.builder.capture.volume_min {
self.dir.write("c_volume_min", volume_min.to_string())?;
}
if let Some(volume_max) = self.builder.capture.volume_max {
self.dir.write("c_volume_max", volume_max.to_string())?;
}
if let Some(volume_resolution) = self.builder.capture.volume_resolution {
self.dir.write("c_volume_res", volume_resolution.to_string())?;
}
if let Some(volume_name) = &self.builder.capture.volume_name {
self.dir.write("c_fu_vol_name", volume_name)?;
}
if let Some(terminal_type) = self.builder.capture.terminal_type {
self.dir.write("c_terminal_type", terminal_type.to_string())?;
}
if let Some(input_terminal_name) = &self.builder.capture.input_terminal_name {
self.dir.write("c_it_name", input_terminal_name)?;
}
if let Some(input_terminal_channel_name) = &self.builder.capture.input_terminal_channel_name {
self.dir.write("c_it_ch_name", input_terminal_channel_name)?;
}
if let Some(output_terminal_name) = &self.builder.capture.output_terminal_name {
self.dir.write("c_ot_name", output_terminal_name)?;
}
// playback
if let Some(channel_mask) = self.builder.playback.channel.channel_mask {
self.dir.write("p_chmask", channel_mask.to_string())?;
}
if let Some(sample_rate) = self.builder.playback.channel.sample_rate {
self.dir.write("p_srate", sample_rate.to_string())?;
}
if let Some(sample_size) = self.builder.playback.channel.sample_size {
self.dir.write("p_ssize", sample_size.to_string())?;
}
if let Some(hs_interval) = self.builder.playback.hs_interval {
self.dir.write("p_hs_bint", hs_interval.to_string())?;
}
if let Some(mute_present) = self.builder.playback.mute_present {
self.dir.write("p_mute_present", (mute_present as u8).to_string())?;
}
if let Some(volume_present) = self.builder.playback.volume_present {
self.dir.write("p_volume_present", (volume_present as u8).to_string())?;
}
if let Some(volume_min) = self.builder.playback.volume_min {
self.dir.write("p_volume_min", volume_min.to_string())?;
}
if let Some(volume_max) = self.builder.playback.volume_max {
self.dir.write("p_volume_max", volume_max.to_string())?;
}
if let Some(volume_resolution) = self.builder.playback.volume_resolution {
self.dir.write("p_volume_res", volume_resolution.to_string())?;
}
if let Some(volume_name) = &self.builder.playback.volume_name {
self.dir.write("p_fu_vol_name", volume_name)?;
}
if let Some(terminal_type) = self.builder.playback.terminal_type {
self.dir.write("p_terminal_type", terminal_type.to_string())?;
}
if let Some(input_terminal_name) = &self.builder.playback.input_terminal_name {
self.dir.write("p_it_name", input_terminal_name)?;
}
if let Some(input_terminal_channel_name) = &self.builder.playback.input_terminal_channel_name {
self.dir.write("p_it_ch_name", input_terminal_channel_name)?;
}
if let Some(output_terminal_name) = &self.builder.playback.output_terminal_name {
self.dir.write("p_ot_name", output_terminal_name)?;
}
// general
if let Some(fb_max) = self.builder.fb_max {
self.dir.write("fb_max", fb_max.to_string())?;
}
if let Some(request_number) = self.builder.request_number {
self.dir.write("req_number", request_number.to_string())?;
}
if let Some(function_name) = &self.builder.function_name {
self.dir.write("function_name", function_name)?;
}
if let Some(control_name) = &self.builder.control_name {
self.dir.write("if_ctrl_name", control_name)?;
}
if let Some(clock_source_in_name) = &self.builder.clock_source_in_name {
self.dir.write("clksrc_in_name", clock_source_in_name)?;
}
if let Some(clock_source_out_name) = &self.builder.clock_source_out_name {
self.dir.write("clksrc_out_name", clock_source_out_name)?;
}
Ok(())
}
}
/// USB Audio Class 2 (UAC2) function.
#[derive(Debug)]
pub struct Uac2 {
dir: FunctionDir,
}
impl Uac2 {
/// Creates a new USB Audio Class 2 (UAC2) builder with g_uac2 audio defaults.
pub fn builder() -> Uac2Builder {
Uac2Builder::default()
}
/// Creates a new USB Audio Class 2 (UAC2) function with the specified capture and playback
/// channels.
pub fn new(capture: Channel, playback: Channel) -> (Uac2, Handle) {
let mut builder = Uac2Builder::default();
builder.capture.channel = capture;
builder.playback.channel = playback;
builder.build()
}
/// Access to registration status.
pub fn status(&self) -> Status {
self.dir.status()
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/net.rs | src/function/net.rs | //! Net functions.
use macaddr::MacAddr6;
use std::{
ffi::{OsStr, OsString},
io::{Error, ErrorKind, Result},
};
use super::{
util::{FunctionDir, Status},
Function, Handle,
};
use crate::{gadget::Class, hex_u8};
/// Class of USB network device.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum NetClass {
/// Ethernet Control Model (CDC ECM).
///
/// The Linux kernel configuration option `CONFIG_USB_CONFIGFS_ECM` must be enabled.
Ecm,
/// Subset of Ethernet Control Model (CDC ECM subset).
///
/// The Linux kernel configuration option `CONFIG_USB_CONFIGFS_ECM_SUBSET` must be enabled.
EcmSubset,
/// Ethernet Emulation Model (CDC EEM).
///
/// The Linux kernel configuration option `CONFIG_USB_CONFIGFS_EEM` must be enabled.
Eem,
/// Network Control Model (CDC NCM).
///
/// The Linux kernel configuration option `CONFIG_USB_CONFIGFS_NCM` must be enabled.
Ncm,
/// Remote Network Driver Interface Specification (RNDIS).
///
/// The Linux kernel configuration option `CONFIG_USB_CONFIGFS_RNDIS` must be enabled.
Rndis,
}
impl NetClass {
fn driver(&self) -> &OsStr {
OsStr::new(match self {
NetClass::Ecm => "ecm",
NetClass::EcmSubset => "geth",
NetClass::Eem => "eem",
NetClass::Ncm => "ncm",
NetClass::Rndis => "rndis",
})
}
}
/// Builder for Communication Device Class (CDC) network functions.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct NetBuilder {
net_class: NetClass,
/// MAC address of device's end of this Ethernet over USB link.
pub dev_addr: Option<MacAddr6>,
/// MAC address of host's end of this Ethernet over USB link.
pub host_addr: Option<MacAddr6>,
/// Queue length multiplier for high and super speed.
pub qmult: Option<u32>,
/// For RNDIS only: interface class.
pub interface_class: Option<Class>,
}
impl NetBuilder {
/// Build the USB function.
///
/// The returned handle must be added to a USB gadget configuration.
pub fn build(self) -> (Net, Handle) {
let dir = FunctionDir::new();
(Net { dir: dir.clone() }, Handle::new(NetFunction { builder: self, dir }))
}
}
#[derive(Debug)]
struct NetFunction {
builder: NetBuilder,
dir: FunctionDir,
}
impl Function for NetFunction {
fn driver(&self) -> OsString {
self.builder.net_class.driver().to_os_string()
}
fn dir(&self) -> FunctionDir {
self.dir.clone()
}
fn register(&self) -> Result<()> {
if let Some(dev_addr) = self.builder.dev_addr {
self.dir.write("dev_addr", dev_addr.to_string())?;
}
if let Some(host_addr) = self.builder.host_addr {
self.dir.write("host_addr", host_addr.to_string())?;
}
if let Some(qmult) = self.builder.qmult {
self.dir.write("qmult", qmult.to_string())?;
}
if let (NetClass::Rndis, Some(class)) = (self.builder.net_class, self.builder.interface_class) {
self.dir.write("class", hex_u8(class.class))?;
self.dir.write("subclass", hex_u8(class.sub_class))?;
self.dir.write("protocol", hex_u8(class.protocol))?;
}
Ok(())
}
}
/// Communication Device Class (CDC) network function.
#[derive(Debug)]
pub struct Net {
dir: FunctionDir,
}
impl Net {
/// Creates a new USB network function.
pub fn new(net_class: NetClass) -> (Net, Handle) {
Self::builder(net_class).build()
}
/// Creates a new USB network function builder.
pub fn builder(net_class: NetClass) -> NetBuilder {
NetBuilder { net_class, dev_addr: None, host_addr: None, qmult: None, interface_class: None }
}
/// Access to registration status.
pub fn status(&self) -> Status {
self.dir.status()
}
/// MAC address of device's end of this Ethernet over USB link.
pub fn dev_addr(&self) -> Result<MacAddr6> {
self.dir.read_string("dev_addr")?.parse().map_err(|err| Error::new(ErrorKind::InvalidData, err))
}
/// MAC address of host's end of this Ethernet over USB link.
pub fn host_addr(&self) -> Result<MacAddr6> {
self.dir.read_string("host_addr")?.parse().map_err(|err| Error::new(ErrorKind::InvalidData, err))
}
/// Network device interface name associated with this function instance.
pub fn ifname(&self) -> Result<OsString> {
self.dir.read_os_string("ifname")
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/custom/ffs.rs | src/function/custom/ffs.rs | //! FunctionFS bindings.
use bitflags::bitflags;
use byteorder::{ReadBytesExt, WriteBytesExt, LE};
use nix::{
ioctl_none, ioctl_read, ioctl_write_int_bad,
mount::{MntFlags, MsFlags},
request_code_none,
};
use std::{
collections::HashMap,
ffi::OsStr,
fmt,
io::{ErrorKind, Read, Write},
num::TryFromIntError,
os::fd::RawFd,
path::Path,
};
use crate::{linux_version, Language};
#[derive(Debug, Clone)]
pub enum Error {
StringsDifferAcrossLanguages,
Overflow,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::StringsDifferAcrossLanguages => write!(f, "string count differs across languages"),
Error::Overflow => write!(f, "too many descriptor entries"),
}
}
}
impl std::error::Error for Error {}
impl From<std::io::Error> for Error {
fn from(_: std::io::Error) -> Self {
unreachable!()
}
}
impl From<TryFromIntError> for Error {
fn from(_: TryFromIntError) -> Self {
Self::Overflow
}
}
impl From<Error> for std::io::Error {
fn from(err: Error) -> Self {
std::io::Error::new(ErrorKind::InvalidInput, err)
}
}
type Result<T> = std::result::Result<T, Error>;
/// USB direction to device.
pub const DIR_OUT: u8 = 0x00;
/// USB direction to host.
pub const DIR_IN: u8 = 0x80;
bitflags! {
#[derive(Clone, Copy, Debug)]
pub struct Flags: u32 {
const HAS_FS_DESC = 1;
const HAS_HS_DESC = 2;
const HAS_SS_DESC = 4;
const HAS_MS_OS_DESC = 8;
const VIRTUAL_ADDR = 16;
const EVENTFD = 32;
const ALL_CTRL_RECIP = 64;
const CONFIG0_SETUP = 128;
}
}
#[derive(Clone, Debug)]
pub struct Descs {
pub flags: Flags,
pub eventfd: Option<RawFd>,
pub fs_descrs: Vec<Desc>,
pub hs_descrs: Vec<Desc>,
pub ss_descrs: Vec<Desc>,
pub os_descrs: Vec<OsDesc>,
}
impl Descs {
const MAGIC_V2: u32 = 3;
pub fn to_bytes(&self) -> Result<Vec<u8>> {
let mut data = Vec::new();
data.write_u32::<LE>(Self::MAGIC_V2)?;
data.write_u32::<LE>(0)?; // length
let mut flags = self.flags;
flags.insert(Flags::HAS_FS_DESC | Flags::HAS_HS_DESC | Flags::HAS_SS_DESC | Flags::HAS_MS_OS_DESC);
flags.set(Flags::EVENTFD, self.eventfd.is_some());
data.write_u32::<LE>(flags.bits())?;
if let Some(fd) = self.eventfd {
data.write_i32::<LE>(fd)?;
}
data.write_u32::<LE>(self.fs_descrs.len().try_into()?)?;
data.write_u32::<LE>(self.hs_descrs.len().try_into()?)?;
data.write_u32::<LE>(self.ss_descrs.len().try_into()?)?;
data.write_u32::<LE>(self.os_descrs.len().try_into()?)?;
for fs_descr in &self.fs_descrs {
data.extend(fs_descr.to_bytes()?);
}
for hs_descr in &self.hs_descrs {
data.extend(hs_descr.to_bytes()?);
}
for ss_descr in &self.ss_descrs {
data.extend(ss_descr.to_bytes()?);
}
for os_descr in &self.os_descrs {
data.extend(os_descr.to_bytes()?);
}
let len: u32 = data.len().try_into()?;
data[4..8].copy_from_slice(&len.to_le_bytes());
Ok(data)
}
}
#[derive(Clone, Debug)]
pub enum Desc {
Interface(InterfaceDesc),
Endpoint(EndpointDesc),
SsEndpointComp(SsEndpointComp),
InterfaceAssoc(InterfaceAssocDesc),
Custom(CustomDesc),
}
impl From<InterfaceDesc> for Desc {
fn from(value: InterfaceDesc) -> Self {
Self::Interface(value)
}
}
impl From<EndpointDesc> for Desc {
fn from(value: EndpointDesc) -> Self {
Self::Endpoint(value)
}
}
impl From<SsEndpointComp> for Desc {
fn from(value: SsEndpointComp) -> Self {
Self::SsEndpointComp(value)
}
}
impl From<InterfaceAssocDesc> for Desc {
fn from(value: InterfaceAssocDesc) -> Self {
Self::InterfaceAssoc(value)
}
}
impl From<CustomDesc> for Desc {
fn from(value: CustomDesc) -> Self {
Self::Custom(value)
}
}
impl Desc {
fn to_bytes(&self) -> Result<Vec<u8>> {
let mut data = Vec::new();
data.write_u8(0)?;
match self {
Self::Interface(d) => d.write(&mut data)?,
Self::Endpoint(d) => d.write(&mut data)?,
Self::SsEndpointComp(d) => d.write(&mut data)?,
Self::InterfaceAssoc(d) => d.write(&mut data)?,
Self::Custom(d) => d.write(&mut data)?,
}
data[0] = data.len().try_into()?;
Ok(data)
}
}
#[derive(Clone, Debug)]
pub struct InterfaceDesc {
pub interface_number: u8,
pub alternate_setting: u8,
pub num_endpoints: u8,
pub interface_class: u8,
pub interface_sub_class: u8,
pub interface_protocol: u8,
pub name_idx: u8,
}
impl InterfaceDesc {
pub const TYPE: u8 = 0x04;
fn write(&self, data: &mut Vec<u8>) -> Result<()> {
data.write_u8(Self::TYPE)?;
data.write_u8(self.interface_number)?;
data.write_u8(self.alternate_setting)?;
data.write_u8(self.num_endpoints)?;
data.write_u8(self.interface_class)?;
data.write_u8(self.interface_sub_class)?;
data.write_u8(self.interface_protocol)?;
data.write_u8(self.name_idx)?;
Ok(())
}
}
/// USB endpoint descriptor.
#[derive(Clone, Debug)]
pub struct EndpointDesc {
/// Endpoint address.
pub endpoint_address: u8,
/// Attributes.
pub attributes: u8,
/// Maximum packet size.
pub max_packet_size: u16,
/// Interval.
pub interval: u8,
/// Audio-endpoint specific data.
pub audio: Option<AudioEndpointDesc>,
}
/// Audio-part of USB endpoint descriptor.
#[derive(Clone, Debug)]
pub struct AudioEndpointDesc {
/// Refresh.
pub refresh: u8,
/// Sync address.
pub synch_address: u8,
}
impl EndpointDesc {
/// Endpoint descriptor type.
pub const TYPE: u8 = 0x05;
/// Size without audio.
pub const SIZE: usize = 7;
/// Size with audio.
pub const AUDIO_SIZE: usize = 9;
fn write(&self, data: &mut Vec<u8>) -> Result<()> {
data.write_u8(Self::TYPE)?;
data.write_u8(self.endpoint_address)?;
data.write_u8(self.attributes)?;
data.write_u16::<LE>(self.max_packet_size)?;
data.write_u8(self.interval)?;
if let Some(audio) = &self.audio {
data.write_u8(audio.refresh)?;
data.write_u8(audio.synch_address)?;
}
Ok(())
}
/// Parse from raw descriptor data.
pub fn parse(mut data: &[u8]) -> std::io::Result<Self> {
let size = data.read_u8()?;
if usize::from(size) != Self::SIZE && usize::from(size) != Self::AUDIO_SIZE {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"endpoint descriptor size mismatch",
));
}
if data.read_u8()? != Self::TYPE {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"endpoint descriptor type mismatch",
));
}
let endpoint_address = data.read_u8()?;
let attributes = data.read_u8()?;
let max_packet_size = data.read_u16::<LE>()?;
let interval = data.read_u8()?;
let audio = if usize::from(size) == Self::AUDIO_SIZE {
let refresh = data.read_u8()?;
let synch_address = data.read_u8()?;
Some(AudioEndpointDesc { refresh, synch_address })
} else {
None
};
Ok(Self { endpoint_address, attributes, max_packet_size, interval, audio })
}
}
#[derive(Clone, Debug)]
pub struct SsEndpointComp {
pub max_burst: u8,
pub attributes: u8,
pub bytes_per_interval: u16,
}
impl SsEndpointComp {
pub const TYPE: u8 = 0x30;
fn write(&self, data: &mut Vec<u8>) -> Result<()> {
data.write_u8(Self::TYPE)?;
data.write_u8(self.max_burst)?;
data.write_u8(self.attributes)?;
data.write_u16::<LE>(self.bytes_per_interval)?;
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct InterfaceAssocDesc {
pub first_interface: u8,
pub interface_count: u8,
pub function_class: u8,
pub function_sub_class: u8,
pub function_protocol: u8,
pub name_idx: u8,
}
impl InterfaceAssocDesc {
pub const TYPE: u8 = 0x0b;
fn write(&self, data: &mut Vec<u8>) -> Result<()> {
data.write_u8(Self::TYPE)?;
data.write_u8(self.first_interface)?;
data.write_u8(self.interface_count)?;
data.write_u8(self.function_class)?;
data.write_u8(self.function_sub_class)?;
data.write_u8(self.function_protocol)?;
data.write_u8(self.name_idx)?;
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct OsDesc {
pub interface: u8,
pub ext: OsDescExt,
}
impl OsDesc {
fn to_bytes(&self) -> Result<Vec<u8>> {
let mut data = Vec::new();
data.write_u8(self.interface)?;
data.write_u32::<LE>(0)?; // length
self.ext.write(&mut data)?;
let len: u32 = data.len().try_into()?;
data[1..5].copy_from_slice(&len.to_le_bytes());
Ok(data)
}
}
#[derive(Clone, Debug)]
pub enum OsDescExt {
ExtCompat(Vec<OsExtCompat>),
ExtProp(Vec<OsExtProp>),
}
impl OsDescExt {
fn write(&self, data: &mut Vec<u8>) -> Result<()> {
let os_desc_bcd_version = if linux_version().unwrap_or_default() >= (6, 4) { 0x0100 } else { 0x0001 };
match self {
Self::ExtCompat(compats) => {
data.write_u16::<LE>(os_desc_bcd_version)?; // bcdVersion
data.write_u16::<LE>(4)?; // wIndex
data.write_u8(compats.len().try_into()?)?;
data.write_u8(0)?;
for compat in compats {
compat.write(data)?;
}
}
Self::ExtProp(props) => {
data.write_u16::<LE>(os_desc_bcd_version)?; // bcdVersion
data.write_u16::<LE>(5)?; // wIndex
data.write_u16::<LE>(props.len().try_into()?)?;
for prop in props {
data.extend(prop.to_bytes()?);
}
}
}
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct OsExtCompat {
pub first_interface_number: u8,
pub compatible_id: [u8; 8],
pub sub_compatible_id: [u8; 8],
}
impl OsExtCompat {
fn write(&self, data: &mut Vec<u8>) -> Result<()> {
data.write_u8(self.first_interface_number)?;
data.write_u8(1)?;
data.extend_from_slice(&self.compatible_id);
data.extend_from_slice(&self.sub_compatible_id);
data.extend_from_slice(&[0; 6]);
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct OsExtProp {
pub data_type: u32,
pub name: String,
pub data: Vec<u8>,
}
impl OsExtProp {
fn to_bytes(&self) -> Result<Vec<u8>> {
let mut data = Vec::new();
data.write_u32::<LE>(0)?; // length
data.write_u32::<LE>(self.data_type)?;
data.write_u16::<LE>(self.name.len().try_into()?)?;
data.write_all(self.name.as_bytes())?;
data.write_u32::<LE>(self.data.len().try_into()?)?;
data.write_all(&self.data)?;
let len: u32 = data.len().try_into()?;
assert_eq!(len as usize, 14 + self.name.len() + self.data.len(), "invalid OS descriptor length");
data[0..4].copy_from_slice(&len.to_le_bytes());
Ok(data)
}
}
/// Custom descriptor.
///
/// The raw descriptor published will be of the form:
/// `[length, descriptor_type, data...]`
#[derive(Clone, Debug)]
pub struct CustomDesc {
/// Descriptor type.
pub descriptor_type: u8,
/// Custom data.
pub data: Vec<u8>,
}
impl CustomDesc {
/// Creates a new custom descriptor.
///
/// The data must not include the length and descriptor type.
pub fn new(descriptor_type: u8, data: Vec<u8>) -> Self {
Self { descriptor_type, data }
}
fn write(&self, data: &mut Vec<u8>) -> Result<()> {
data.write_u8(self.descriptor_type)?;
data.write_all(&self.data)?;
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct Strings(pub HashMap<Language, Vec<String>>);
impl Strings {
const MAGIC: u32 = 2;
pub fn to_bytes(&self) -> Result<Vec<u8>> {
let str_count = self.0.values().next().map(|v| v.len()).unwrap_or_default();
if !self.0.values().all(|v| v.len() == str_count) {
return Err(Error::StringsDifferAcrossLanguages);
}
let mut data = Vec::new();
data.write_u32::<LE>(Self::MAGIC)?;
data.write_u32::<LE>(0)?; // length
data.write_u32::<LE>(str_count.try_into()?)?;
data.write_u32::<LE>(self.0.len().try_into()?)?;
for (lang, strings) in &self.0 {
data.write_u16::<LE>((*lang).into())?;
for str in strings {
data.write_all(str.as_bytes())?;
data.write_u8(0)?;
}
}
let len: u32 = data.len().try_into()?;
data[4..8].copy_from_slice(&len.to_le_bytes());
Ok(data)
}
}
/// USB control request.
#[derive(Clone, Debug)]
pub struct CtrlReq {
/// Request type.
pub request_type: u8,
/// Request.
pub request: u8,
/// Value.
pub value: u16,
/// Index.
pub index: u16,
/// Length.
pub length: u16,
}
impl CtrlReq {
/// Parse from buffer.
pub fn parse(mut buf: &[u8]) -> Result<Self> {
let request_type = buf.read_u8()?;
let request = buf.read_u8()?;
let value = buf.read_u16::<LE>()?;
let index = buf.read_u16::<LE>()?;
let length = buf.read_u16::<LE>()?;
Ok(Self { request_type, request, value, index, length })
}
}
/// FunctionFS event type.
pub mod event {
pub const BIND: u8 = 0;
pub const UNBIND: u8 = 1;
pub const ENABLE: u8 = 2;
pub const DISABLE: u8 = 3;
pub const SETUP: u8 = 4;
pub const SUSPEND: u8 = 5;
pub const RESUME: u8 = 6;
}
/// FunctionFS event.
pub struct Event {
pub data: [u8; 8],
pub event_type: u8,
}
impl Event {
/// Size of raw event data.
pub const SIZE: usize = 12;
/// Parse FunctionFS event data.
pub fn parse(mut buf: &[u8]) -> Result<Self> {
let mut data = [0; 8];
buf.read_exact(&mut data)?;
let event_type = buf.read_u8()?;
let mut pad = [0; 3];
buf.read_exact(&mut pad)?;
Ok(Self { data, event_type })
}
}
pub const FS_TYPE: &str = "functionfs";
/// FunctionFS mount options.
#[derive(Debug, Clone, Default)]
pub struct MountOptions {
pub no_disconnect: bool,
pub rmode: Option<u32>,
pub fmode: Option<u32>,
pub mode: Option<u32>,
pub uid: Option<u32>,
pub gid: Option<u32>,
}
impl MountOptions {
fn to_mount_data(&self) -> String {
let mut opts = Vec::new();
if self.no_disconnect {
opts.push("no_disconnect=1".to_string());
}
if let Some(v) = self.rmode {
opts.push(format!("rmode={v}"));
}
if let Some(v) = self.fmode {
opts.push(format!("fmode={v}"));
}
if let Some(v) = self.mode {
opts.push(format!("mode={v}"));
}
if let Some(v) = self.uid {
opts.push(format!("uid={v}"));
}
if let Some(v) = self.gid {
opts.push(format!("gid={v}"));
}
opts.join(",")
}
}
pub fn mount(instance: &OsStr, target: &Path, opts: &MountOptions) -> std::io::Result<()> {
let instance = instance.to_os_string();
let target = target.to_path_buf();
nix::mount::mount(
Some(instance.as_os_str()),
&target,
Some(FS_TYPE),
MsFlags::empty(),
Some(opts.to_mount_data().as_str()),
)?;
Ok(())
}
pub fn umount(target: &Path, lazy: bool) -> std::io::Result<()> {
let target = target.to_path_buf();
nix::mount::umount2(&target, if lazy { MntFlags::MNT_DETACH } else { MntFlags::empty() })?;
Ok(())
}
ioctl_none!(fifo_status, 'g', 1);
ioctl_none!(fifo_flush, 'g', 2);
ioctl_none!(clear_halt, 'g', 3);
ioctl_write_int_bad!(interface_revmap, request_code_none!('g', 128));
ioctl_none!(endpoint_revmap, 'g', 129);
ioctl_read!(endpoint_desc, 'g', 130, [u8; EndpointDesc::AUDIO_SIZE]);
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/custom/mod.rs | src/function/custom/mod.rs | //! Custom USB interface, implemented in user code.
//!
//! The Linux kernel configuration option `CONFIG_USB_CONFIGFS_F_FS` must be enabled.
use bytes::{Bytes, BytesMut};
use nix::poll::{poll, PollFd, PollFlags, PollTimeout};
use proc_mounts::MountIter;
use std::{
collections::{hash_map::Entry, HashMap, HashSet},
ffi::{OsStr, OsString},
fmt, fs,
fs::File,
hash::Hash,
io::{Error, ErrorKind, Read, Result, Write},
os::fd::{AsFd, AsRawFd, RawFd},
path::{Path, PathBuf},
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex, Weak,
},
time::Duration,
};
use uuid::Uuid;
use super::{
util::{split_function_dir, value, FunctionDir, Status},
Function, Handle,
};
use crate::{Class, Language};
mod aio;
mod ffs;
pub(crate) fn driver() -> &'static OsStr {
OsStr::new("ffs")
}
pub use ffs::CustomDesc;
/// An USB interface.
#[derive(Debug)]
#[non_exhaustive]
pub struct Interface {
/// Interface class.
pub interface_class: Class,
/// Interface name.
pub name: HashMap<Language, String>,
/// USB endpoints.
pub endpoints: Vec<Endpoint>,
/// Interface association.
pub association: Option<Association>,
/// Microsoft extended compatibility descriptors.
pub os_ext_compat: Vec<OsExtCompat>,
/// Microsoft extended properties.
pub os_ext_props: Vec<OsExtProp>,
/// Custom descriptors.
///
/// These are inserted directly after the interface descriptor.
pub custom_descs: Vec<CustomDesc>,
}
impl Interface {
/// Creates a new interface.
pub fn new(interface_class: Class, name: impl AsRef<str>) -> Self {
Self {
interface_class,
name: [(Language::default(), name.as_ref().to_string())].into(),
endpoints: Vec::new(),
association: None,
os_ext_compat: Vec::new(),
os_ext_props: Vec::new(),
custom_descs: Vec::new(),
}
}
/// Add an USB endpoint.
#[must_use]
pub fn with_endpoint(mut self, endpoint: Endpoint) -> Self {
self.endpoints.push(endpoint);
self
}
/// Set the USB interface association.
#[must_use]
pub fn with_association(mut self, association: &Association) -> Self {
self.association = Some(association.clone());
self
}
/// Adds a Microsoft extended compatibility descriptor.
#[must_use]
pub fn with_os_ext_compat(mut self, os_ext_compat: OsExtCompat) -> Self {
self.os_ext_compat.push(os_ext_compat);
self
}
/// Adds a Microsoft extended property.
#[must_use]
pub fn with_os_ext_prop(mut self, os_ext_prop: OsExtProp) -> Self {
self.os_ext_props.push(os_ext_prop);
self
}
/// Adds a custom descriptor after the interface descriptor.
#[must_use]
pub fn with_custom_desc(mut self, custom_desc: CustomDesc) -> Self {
self.custom_descs.push(custom_desc);
self
}
}
/// Interface association.
#[derive(Debug, Clone)]
pub struct Association {
addr: Arc<()>,
/// Function class.
pub function_class: Class,
/// Function name.
pub name: HashMap<Language, String>,
}
impl PartialEq for Association {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.addr, &other.addr)
&& self.function_class == other.function_class
&& self.name == other.name
}
}
impl Eq for Association {}
impl Hash for Association {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
Arc::as_ptr(&self.addr).hash(state);
}
}
impl Association {
/// Creates a new interface association.
pub fn new(function_class: Class, name: impl AsRef<str>) -> Self {
Self {
addr: Arc::new(()),
function_class,
name: [(Language::default(), name.as_ref().to_string())].into(),
}
}
}
/// Transfer direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Direction {
/// From device to host.
DeviceToHost,
/// From host to device.
HostToDevice,
}
/// Endpoint transfer direction.
pub struct EndpointDirection {
direction: Direction,
/// Queue length.
pub queue_len: u32,
tx: value::Sender<EndpointIo>,
}
impl fmt::Debug for EndpointDirection {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("EndpointDirection")
.field("direction", &self.direction)
.field("queue_len", &self.queue_len)
.finish()
}
}
impl EndpointDirection {
const DEFAULT_QUEUE_LEN: u32 = 16;
/// From device to host.
pub fn device_to_host() -> (EndpointSender, EndpointDirection) {
let (tx, rx) = value::channel();
let writer = EndpointSender(rx);
let this = Self { direction: Direction::DeviceToHost, tx, queue_len: Self::DEFAULT_QUEUE_LEN };
(writer, this)
}
/// From host to device.
pub fn host_to_device() -> (EndpointReceiver, EndpointDirection) {
let (tx, rx) = value::channel();
let reader = EndpointReceiver(rx);
let this = Self { direction: Direction::HostToDevice, tx, queue_len: Self::DEFAULT_QUEUE_LEN };
(reader, this)
}
/// Sets the queue length.
#[must_use]
pub fn with_queue_len(mut self, queue_len: u32) -> Self {
self.queue_len = queue_len;
self
}
}
/// Endpoint synchronization type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SyncType {
/// No synchronization.
NoSync,
/// Asynchronous.
Async,
/// Adaptive.
Adaptive,
/// Synchronous.
Sync,
}
impl SyncType {
fn to_attributes(self) -> u8 {
(match self {
Self::NoSync => 0b00,
Self::Async => 0b01,
Self::Adaptive => 0b10,
Self::Sync => 0b11,
} << 2)
}
}
/// Endpoint usage type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum UsageType {
/// Data endpoint.
Data,
/// Feedback endpoint.
Feedback,
/// Implicit feedback data endpoint.
ImplicitFeedback,
}
impl UsageType {
fn to_attributes(self) -> u8 {
(match self {
Self::Data => 0b00,
Self::Feedback => 0b01,
Self::ImplicitFeedback => 0b10,
} << 4)
}
}
/// Endpoint transfer type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TransferType {
/// Control.
Control,
/// Isochronous.
Isochronous {
/// Synchronization type.
sync: SyncType,
/// Usage type.
usage: UsageType,
},
/// Bulk.
Bulk,
/// Interrupt.
Interrupt,
}
impl TransferType {
fn to_attributes(self) -> u8 {
match self {
Self::Control => 0b00,
Self::Isochronous { sync, usage } => 0b01 | sync.to_attributes() | usage.to_attributes(),
Self::Bulk => 0b10,
Self::Interrupt => 0b11,
}
}
}
/// An USB endpoint.
#[derive(Debug)]
#[non_exhaustive]
pub struct Endpoint {
/// Endpoint transfer direction.
pub direction: EndpointDirection,
/// Transfer type.
pub transfer: TransferType,
/// Maximum packet size for high speed.
pub max_packet_size_hs: u16,
/// Maximum packet size for super speed.
pub max_packet_size_ss: u16,
/// Maximum number of packets that the endpoint can send or receive as a part of a burst
/// for super speed.
pub max_burst_ss: u8,
/// Number of bytes per interval for super speed.
pub bytes_per_interval_ss: u16,
/// Interval for polling endpoint for data transfers.
pub interval: u8,
/// Data for audio endpoints.
pub audio: Option<EndpointAudio>,
}
/// Extension of USB endpoint for audio.
#[derive(Debug)]
pub struct EndpointAudio {
/// Refresh.
pub refresh: u8,
/// Sync address.
pub synch_address: u8,
}
impl Endpoint {
/// Creates a new bulk endpoint.
pub fn bulk(direction: EndpointDirection) -> Self {
Self::custom(direction, TransferType::Bulk)
}
/// Creates a new custom endpoint.
pub fn custom(direction: EndpointDirection, transfer: TransferType) -> Self {
let transfer_direction = direction.direction;
Self {
direction,
transfer,
max_packet_size_hs: 512,
max_packet_size_ss: 1024,
max_burst_ss: 0,
bytes_per_interval_ss: 0,
interval: match transfer_direction {
Direction::DeviceToHost => 0,
Direction::HostToDevice => 1,
},
audio: None,
}
}
}
/// Microsoft extended compatibility descriptor.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OsExtCompat {
/// Compatible ID string.
pub compatible_id: [u8; 8],
/// Sub-compatible ID string.
pub sub_compatible_id: [u8; 8],
}
/// Creates a new extended compatibility descriptor.
impl OsExtCompat {
/// Creates a new extended compatibility descriptor.
pub const fn new(compatible_id: [u8; 8], sub_compatible_id: [u8; 8]) -> Self {
Self { compatible_id, sub_compatible_id }
}
/// Use Microsoft WinUSB driver.
pub const fn winusb() -> Self {
Self::new(*b"WINUSB\0\0", [0; 8])
}
}
/// Microsoft extended property descriptor.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OsExtProp {
/// Property name.
pub name: String,
/// Property value.
pub value: OsRegValue,
}
impl OsExtProp {
/// Creates a new extended property descriptor.
pub fn new(name: impl AsRef<str>, value: impl Into<OsRegValue>) -> Self {
Self { name: name.as_ref().to_string(), value: value.into() }
}
/// Sets the device interface GUID.
pub fn device_interface_guid(guid: Uuid) -> Self {
Self::new("DeviceInterfaceGUID", guid.to_string())
}
// Unsupported by Linux 6.5
//
// /// Indicate whether the device can power down when idle (selective suspend).
// pub fn device_idle_enabled(enabled: bool) -> Self {
// Self::new("DeviceIdleEnabled", u32::from(enabled))
// }
//
// /// Indicate whether the device can be suspended when idle by default.
// pub fn default_idle_state(state: bool) -> Self {
// Self::new("DefaultIdleState", u32::from(state))
// }
//
// /// Indicate the amount of time in milliseconds to wait before determining that a device is
// /// idle.
// pub fn default_idle_timeout(timeout_ms: u32) -> Self {
// Self::new("DefaultIdleTimeout", timeout_ms)
// }
//
// /// Indicate whether to allow the user to control the ability of the device to enable
// /// or disable USB selective suspend.
// pub fn user_set_device_idle_enabled(enabled: bool) -> Self {
// Self::new("UserSetDeviceIdleEnabled", u32::from(enabled))
// }
//
// /// Indicate whether to allow the user to control the ability of the device to wake the
// /// system from a low-power state.
// pub fn system_wake_enabled(enabled: bool) -> Self {
// Self::new("SystemWakeEnabled", u32::from(enabled))
// }
fn as_os_ext_prop(&self) -> ffs::OsExtProp {
let mut name = self.name.clone();
name.push('\0');
ffs::OsExtProp { name, data_type: self.value.as_type(), data: self.value.as_bytes() }
}
}
/// Microsoft registry value.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum OsRegValue {
/// Unicode string.
Sz(String),
/// Unicode string that includes environment variables.
ExpandSz(String),
/// Free-form binary.
Binary(Vec<u8>),
/// Little-endian 32-bit integer.
DwordLe(u32),
/// Big-endian 32-bit integer.
DwordBe(u32),
/// Unicode string that contains a symbolic link.
Link(String),
/// Multiple Unicode strings.
MultiSz(Vec<String>),
}
impl OsRegValue {
fn as_type(&self) -> u32 {
match self {
Self::Sz(_) => 1,
Self::ExpandSz(_) => 2,
Self::Binary(_) => 3,
Self::DwordLe(_) => 4,
Self::DwordBe(_) => 5,
Self::Link(_) => 6,
Self::MultiSz(_) => 7,
}
}
fn as_bytes(&self) -> Vec<u8> {
match self {
Self::Sz(s) => [s.as_bytes(), &[0]].concat().to_vec(),
Self::ExpandSz(s) => [s.as_bytes(), &[0]].concat().to_vec(),
Self::Binary(s) => s.clone(),
Self::DwordLe(v) => v.to_le_bytes().to_vec(),
Self::DwordBe(v) => v.to_be_bytes().to_vec(),
Self::Link(s) => [s.as_bytes(), &[0]].concat().to_vec(),
Self::MultiSz(ss) => ss.iter().flat_map(|s| [s.as_bytes(), &[0]].concat()).collect(),
}
}
}
impl From<String> for OsRegValue {
fn from(value: String) -> Self {
Self::Sz(value)
}
}
impl From<&str> for OsRegValue {
fn from(value: &str) -> Self {
Self::Sz(value.to_string())
}
}
impl From<Vec<u8>> for OsRegValue {
fn from(value: Vec<u8>) -> Self {
Self::Binary(value)
}
}
impl From<&[u8]> for OsRegValue {
fn from(value: &[u8]) -> Self {
Self::Binary(value.to_vec())
}
}
impl From<u32> for OsRegValue {
fn from(value: u32) -> Self {
Self::DwordLe(value)
}
}
impl From<Vec<String>> for OsRegValue {
fn from(value: Vec<String>) -> Self {
Self::MultiSz(value)
}
}
/// Builder for custom USB interface, implemented in user code.
#[derive(Debug)]
#[non_exhaustive]
pub struct CustomBuilder {
/// USB interfaces.
pub interfaces: Vec<Interface>,
/// Receive control requests that are not explicitly directed to
/// an interface or endpoint.
pub all_ctrl_recipient: bool,
/// Receive control requests in configuration 0.
pub config0_setup: bool,
/// FunctionFS mount directory.
///
/// The parent directory must exist.
/// If unspecified, a directory starting with `/dev/ffs-*` is created and used.
pub ffs_dir: Option<PathBuf>,
/// FunctionFS root permissions.
pub ffs_root_mode: Option<u32>,
/// FunctionFS file permissions.
pub ffs_file_mode: Option<u32>,
/// FunctionFS user id.
pub ffs_uid: Option<u32>,
/// FunctionFS group id.
pub ffs_gid: Option<u32>,
/// Do not disconnect USB gadget when interface files are closed.
pub ffs_no_disconnect: bool,
/// Do not initialize FunctionFS.
///
/// No FunctionFS files are opened. This must then be done externally.
pub ffs_no_init: bool,
/// Do not mount FunctionFS.
///
/// Implies [`ffs_no_init`](Self::ffs_no_init).
pub ffs_no_mount: bool,
}
impl CustomBuilder {
/// Build the USB function.
///
/// The returned handle must be added to a USB gadget configuration.
pub fn build(self) -> (Custom, Handle) {
let dir = FunctionDir::new();
let (ep0_tx, ep0_rx) = value::channel();
let (ffs_dir_tx, ffs_dir_rx) = value::channel();
let ep_files = Arc::new(Mutex::new(Vec::new()));
(
Custom {
dir: dir.clone(),
ep0: ep0_rx,
setup_event: None,
ep_files: ep_files.clone(),
existing_ffs: false,
ffs_dir: ffs_dir_rx,
},
Handle::new(CustomFunction {
builder: self,
dir,
ep0_tx,
ep_files,
ffs_dir_created: AtomicBool::new(false),
ffs_dir_tx,
}),
)
}
/// Use the specified pre-mounted FunctionFS directory.
///
/// Descriptors and strings are written into the `ep0` device file.
///
/// This allows usage of the custom interface functionality when the USB gadget has
/// been registered externally.
pub fn existing(mut self, ffs_dir: impl AsRef<Path>) -> Result<Custom> {
self.ffs_dir = Some(ffs_dir.as_ref().to_path_buf());
let dir = FunctionDir::new();
let (ep0_tx, ep0_rx) = value::channel();
let (ffs_dir_tx, ffs_dir_rx) = value::channel();
let ep_files = Arc::new(Mutex::new(Vec::new()));
let func = CustomFunction {
builder: self,
dir: dir.clone(),
ep0_tx,
ep_files: ep_files.clone(),
ffs_dir_created: AtomicBool::new(false),
ffs_dir_tx,
};
func.init()?;
Ok(Custom { dir, ep0: ep0_rx, setup_event: None, ep_files, existing_ffs: true, ffs_dir: ffs_dir_rx })
}
/// Add an USB interface.
#[must_use]
pub fn with_interface(mut self, interface: Interface) -> Self {
self.interfaces.push(interface);
self
}
/// Build functionfs descriptors and strings.
fn ffs_descs(&self) -> Result<(ffs::Descs, ffs::Strings)> {
let mut strings = ffs::Strings(HashMap::new());
let mut add_strings = |strs: &HashMap<Language, String>| {
let all_langs: HashSet<_> = strings.0.keys().chain(strs.keys()).cloned().collect();
let str_cnt = strings.0.values().next().map(|s| s.len()).unwrap_or_default();
for lang in all_langs.into_iter() {
let lang_strs = strings.0.entry(lang).or_insert_with(|| vec![String::new(); str_cnt]);
lang_strs.push(strs.get(&lang).cloned().unwrap_or_default());
}
u8::try_from(str_cnt + 1).map_err(|_| Error::new(ErrorKind::InvalidInput, "too many strings"))
};
let mut fs_descrs = Vec::new();
let mut hs_descrs = Vec::new();
let mut ss_descrs = Vec::new();
let mut os_descrs = Vec::new();
let mut endpoint_num: u8 = 0;
let mut assocs: HashMap<Association, ffs::InterfaceAssocDesc> = HashMap::new();
for (interface_number, intf) in self.interfaces.iter().enumerate() {
let interface_number: u8 = interface_number
.try_into()
.map_err(|_| Error::new(ErrorKind::InvalidInput, "too many interfaces"))?;
let num_endpoints: u8 = intf
.endpoints
.len()
.try_into()
.map_err(|_| Error::new(ErrorKind::InvalidInput, "too many endpoints"))?;
let if_desc = ffs::InterfaceDesc {
interface_number,
alternate_setting: 0,
num_endpoints,
interface_class: intf.interface_class.class,
interface_sub_class: intf.interface_class.sub_class,
interface_protocol: intf.interface_class.protocol,
name_idx: add_strings(&intf.name)?,
};
fs_descrs.push(if_desc.clone().into());
hs_descrs.push(if_desc.clone().into());
ss_descrs.push(if_desc.clone().into());
for custom in &intf.custom_descs {
fs_descrs.push(custom.clone().into());
hs_descrs.push(custom.clone().into());
ss_descrs.push(custom.clone().into());
}
for ep in &intf.endpoints {
endpoint_num += 1;
if endpoint_num >= ffs::DIR_IN {
return Err(Error::new(ErrorKind::InvalidInput, "too many endpoints"));
}
let ep_desc = ffs::EndpointDesc {
endpoint_address: match ep.direction.direction {
Direction::DeviceToHost => endpoint_num | ffs::DIR_IN,
Direction::HostToDevice => endpoint_num | ffs::DIR_OUT,
},
attributes: ep.transfer.to_attributes(),
max_packet_size: 0,
interval: ep.interval,
audio: ep
.audio
.as_ref()
.map(|a| ffs::AudioEndpointDesc { refresh: a.refresh, synch_address: a.synch_address }),
};
let ss_comp_desc = ffs::SsEndpointComp {
max_burst: ep.max_burst_ss,
attributes: 0,
bytes_per_interval: ep.bytes_per_interval_ss,
};
fs_descrs.push(ep_desc.clone().into());
hs_descrs
.push(ffs::EndpointDesc { max_packet_size: ep.max_packet_size_hs, ..ep_desc.clone() }.into());
ss_descrs
.push(ffs::EndpointDesc { max_packet_size: ep.max_packet_size_ss, ..ep_desc.clone() }.into());
ss_descrs.push(ss_comp_desc.into());
}
if let Some(assoc) = &intf.association {
let iad = match assocs.entry(assoc.clone()) {
Entry::Occupied(ocu) => ocu.into_mut(),
Entry::Vacant(vac) => vac.insert(ffs::InterfaceAssocDesc {
first_interface: interface_number,
interface_count: 0,
function_class: assoc.function_class.class,
function_sub_class: assoc.function_class.sub_class,
function_protocol: assoc.function_class.protocol,
name_idx: add_strings(&assoc.name)?,
}),
};
if iad.first_interface + interface_number != interface_number {
return Err(Error::new(ErrorKind::InvalidInput, "associated interfaces must be adjacent"));
}
iad.interface_count += 1;
}
if !intf.os_ext_compat.is_empty() {
let os_desc = ffs::OsDesc {
interface: interface_number,
ext: ffs::OsDescExt::ExtCompat(
intf.os_ext_compat
.iter()
.map(|oe| ffs::OsExtCompat {
first_interface_number: interface_number,
compatible_id: oe.compatible_id,
sub_compatible_id: oe.sub_compatible_id,
})
.collect(),
),
};
os_descrs.push(os_desc);
}
if !intf.os_ext_props.is_empty() {
let os_desc = ffs::OsDesc {
interface: interface_number,
ext: ffs::OsDescExt::ExtProp(
intf.os_ext_props.iter().map(|oep| oep.as_os_ext_prop()).collect(),
),
};
os_descrs.push(os_desc);
}
}
for iad in assocs.into_values() {
fs_descrs.push(iad.clone().into());
hs_descrs.push(iad.clone().into());
ss_descrs.push(iad.clone().into());
}
let mut flags = ffs::Flags::empty();
flags.set(ffs::Flags::ALL_CTRL_RECIP, self.all_ctrl_recipient);
flags.set(ffs::Flags::CONFIG0_SETUP, self.config0_setup);
let descs = ffs::Descs { flags, eventfd: None, fs_descrs, hs_descrs, ss_descrs, os_descrs };
Ok((descs, strings))
}
/// Gets the descriptor and string data for writing into `ep0` of FunctionFS.
///
/// Normally, this is done automatically when the custom function is registered.
/// This function is only useful when descriptors and strings should be written
/// to `ep0` by other means.
pub fn ffs_descriptors_and_strings(&self) -> Result<(Vec<u8>, Vec<u8>)> {
let (descs, strs) = self.ffs_descs()?;
Ok((descs.to_bytes()?, strs.to_bytes()?))
}
}
fn default_ffs_dir(instance: &OsStr) -> PathBuf {
let mut name: OsString = "ffs-".into();
name.push(instance);
Path::new("/dev").join(name)
}
#[derive(Debug)]
struct CustomFunction {
builder: CustomBuilder,
dir: FunctionDir,
ep0_tx: value::Sender<Weak<File>>,
ep_files: Arc<Mutex<Vec<Arc<File>>>>,
ffs_dir_created: AtomicBool,
ffs_dir_tx: value::Sender<PathBuf>,
}
impl CustomFunction {
/// FunctionFS directory.
fn ffs_dir(&self) -> Result<PathBuf> {
match &self.builder.ffs_dir {
Some(ffs_dir) => Ok(ffs_dir.clone()),
None => Ok(default_ffs_dir(&self.dir.instance()?)),
}
}
/// Initialize FunctionFS.
///
/// It must already be mounted.
fn init(&self) -> Result<()> {
let ffs_dir = self.ffs_dir()?;
if !self.builder.ffs_no_init {
let (descs, strs) = self.builder.ffs_descs()?;
log::trace!("functionfs descriptors: {descs:x?}");
log::trace!("functionfs strings: {strs:?}");
let ep0_path = ffs_dir.join("ep0");
let mut ep0 = File::options().read(true).write(true).open(&ep0_path)?;
log::debug!("writing functionfs descriptors to {}", ep0_path.display());
let descs_data = descs.to_bytes()?;
log::trace!("functionfs descriptor data: {descs_data:x?}");
if ep0.write(&descs_data)? != descs_data.len() {
return Err(Error::new(ErrorKind::UnexpectedEof, "short descriptor write"));
}
log::debug!("writing functionfs strings to {}", ep0_path.display());
let strs_data = strs.to_bytes()?;
log::trace!("functionfs strings data: {strs_data:x?}");
if ep0.write(&strs_data)? != strs_data.len() {
return Err(Error::new(ErrorKind::UnexpectedEof, "short strings write"));
}
log::debug!("functionfs initialized");
// Open endpoint files.
let mut endpoint_num = 0;
let mut ep_files = Vec::new();
for intf in &self.builder.interfaces {
for ep in &intf.endpoints {
endpoint_num += 1;
let ep_path = ffs_dir.join(format!("ep{endpoint_num}"));
let (ep_io, ep_file) = EndpointIo::new(ep_path, ep.direction.queue_len)?;
ep.direction.tx.send(ep_io).unwrap();
ep_files.push(ep_file);
}
}
// Provide endpoint 0 file.
let ep0 = Arc::new(ep0);
self.ep0_tx.send(Arc::downgrade(&ep0)).unwrap();
ep_files.push(ep0);
*self.ep_files.lock().unwrap() = ep_files;
}
self.ffs_dir_tx.send(ffs_dir).unwrap();
Ok(())
}
/// Close all device files.
fn close(&self) {
self.ep_files.lock().unwrap().clear();
}
}
impl Function for CustomFunction {
fn driver(&self) -> OsString {
driver().to_os_string()
}
fn dir(&self) -> FunctionDir {
self.dir.clone()
}
fn register(&self) -> Result<()> {
if self.builder.ffs_no_mount {
return Ok(());
}
let ffs_dir = self.ffs_dir()?;
log::debug!("creating functionfs directory {}", ffs_dir.display());
match fs::create_dir(&ffs_dir) {
Ok(()) => self.ffs_dir_created.store(true, Ordering::SeqCst),
Err(err) if err.kind() == ErrorKind::AlreadyExists => (),
Err(err) => return Err(err),
}
let mount_opts = ffs::MountOptions {
no_disconnect: self.builder.ffs_no_disconnect,
rmode: self.builder.ffs_root_mode,
fmode: self.builder.ffs_file_mode,
mode: None,
uid: self.builder.ffs_uid,
gid: self.builder.ffs_gid,
};
log::debug!("mounting functionfs into {} using options {mount_opts:?}", ffs_dir.display());
ffs::mount(&self.dir.instance()?, &ffs_dir, &mount_opts)?;
self.init()
}
fn pre_removal(&self) -> Result<()> {
self.close();
Ok(())
}
fn post_removal(&self, _dir: &Path) -> Result<()> {
if self.ffs_dir_created.load(Ordering::SeqCst) {
if let Ok(ffs_dir) = self.ffs_dir() {
let _ = fs::remove_dir(ffs_dir);
}
}
Ok(())
}
}
pub(crate) fn remove_handler(dir: PathBuf) -> Result<()> {
let (_driver, instance) =
split_function_dir(&dir).ok_or_else(|| Error::new(ErrorKind::InvalidInput, "invalid configfs dir"))?;
for mount in MountIter::new()? {
let Ok(mount) = mount else { continue };
if mount.fstype == ffs::FS_TYPE && mount.source == instance {
log::debug!("unmounting functionfs {} from {}", instance.to_string_lossy(), mount.dest.display());
if let Err(err) = ffs::umount(&mount.dest, false) {
log::debug!("unmount failed, trying lazy unmount: {err}");
ffs::umount(&mount.dest, true)?;
}
if mount.dest == default_ffs_dir(instance) {
let _ = fs::remove_dir(&mount.dest);
}
}
}
Ok(())
}
/// Custom USB interface, implemented in user code.
///
/// Dropping this causes all endpoint files to be closed.
/// However, the FunctionFS instance stays mounted until the USB gadget is unregistered.
#[derive(Debug)]
pub struct Custom {
dir: FunctionDir,
ep0: value::Receiver<Weak<File>>,
setup_event: Option<Direction>,
ep_files: Arc<Mutex<Vec<Arc<File>>>>,
existing_ffs: bool,
ffs_dir: value::Receiver<PathBuf>,
}
impl Custom {
/// Creates a new USB custom function builder.
pub fn builder() -> CustomBuilder {
CustomBuilder {
interfaces: Vec::new(),
all_ctrl_recipient: false,
config0_setup: false,
ffs_dir: None,
ffs_root_mode: None,
ffs_file_mode: None,
ffs_uid: None,
ffs_gid: None,
ffs_no_disconnect: false,
ffs_no_init: false,
ffs_no_mount: false,
}
}
/// Access to registration status.
///
/// The registration status is not available when [`CustomBuilder::existing`] has been
/// used to create this object.
pub fn status(&self) -> Option<Status> {
if !self.existing_ffs {
Some(self.dir.status())
} else {
None
}
}
fn ep0(&mut self) -> Result<Arc<File>> {
let ep0 = self.ep0.get()?;
ep0.upgrade().ok_or_else(|| Error::new(ErrorKind::BrokenPipe, "USB gadget was removed"))
}
/// Returns real address of an interface.
pub fn real_address(&mut self, intf: u8) -> Result<u8> {
let ep0 = self.ep0()?;
let address = unsafe { ffs::interface_revmap(ep0.as_raw_fd(), intf.into()) }?;
Ok(address as u8)
}
/// Clear previous event if it was forgotten.
fn clear_prev_event(&mut self) -> Result<()> {
let mut ep0 = self.ep0()?;
let mut buf = [0; 1];
match self.setup_event.take() {
Some(Direction::DeviceToHost) => {
let _ = ep0.read(&mut buf)?;
}
Some(Direction::HostToDevice) => {
let _ = ep0.write(&buf)?;
}
None => (),
}
Ok(())
}
/// Blocking read event.
fn read_event(&'_ mut self) -> Result<Event<'_>> {
let mut ep0 = self.ep0()?;
let mut buf = [0; ffs::Event::SIZE];
let n = ep0.read(&mut buf)?;
if n != ffs::Event::SIZE {
return Err(Error::new(ErrorKind::InvalidData, "invalid event size"));
}
let raw_event = ffs::Event::parse(&buf)?;
Ok(Event::from_ffs(raw_event, self))
}
/// Wait for an event for the specified duration.
fn wait_event_sync(&mut self, timeout: Option<Duration>) -> Result<bool> {
let ep0 = self.ep0()?;
let mut fds = [PollFd::new(ep0.as_fd(), PollFlags::POLLIN)];
poll(&mut fds, timeout.map(|d| d.as_millis().try_into().unwrap()).unwrap_or(PollTimeout::NONE))?;
Ok(fds[0].revents().map(|e| e.contains(PollFlags::POLLIN)).unwrap_or_default())
}
/// Asynchronously wait for an event to be available.
#[cfg(feature = "tokio")]
pub async fn wait_event(&mut self) -> Result<()> {
use tokio::io::{unix::AsyncFd, Interest};
let ep0 = self.ep0()?;
let async_fd = AsyncFd::with_interest(ep0.as_fd(), Interest::READABLE)?;
let mut guard = async_fd.readable().await?;
guard.clear_ready();
Ok(())
}
/// Returns whether events are available for processing.
pub fn has_event(&mut self) -> bool {
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | true |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/custom/aio/mod.rs | src/function/custom/aio/mod.rs | //! Linux AIO driver.
use bytes::{Bytes, BytesMut};
use nix::sys::eventfd::{self, EfdFlags};
use std::{
collections::{hash_map::Entry, HashMap, VecDeque},
fmt,
io::{Error, ErrorKind, Result},
mem::{self, MaybeUninit},
ops::Deref,
os::fd::{AsRawFd, RawFd},
pin::Pin,
ptr,
sync::{mpsc, mpsc::TryRecvError, Arc},
thread,
time::Duration,
};
mod sys;
pub use sys::opcode;
/// eventfd provided by kernel.
#[derive(Debug, Clone)]
struct EventFd(Arc<eventfd::EventFd>);
impl EventFd {
/// Create new eventfd with initial value and semaphore characteristics, if requested.
pub fn new(initval: u32, semaphore: bool) -> Result<Self> {
let flags = if semaphore { EfdFlags::EFD_SEMAPHORE } else { EfdFlags::empty() };
let fd = eventfd::EventFd::from_value_and_flags(initval, flags)?;
Ok(Self(Arc::new(fd)))
}
/// Decrease value by one or set to zero if using semaphore characteristics.
///
/// Blocks while value is zero.
pub fn read(&self) -> Result<u64> {
let mut buf = [0; 8];
let ret = unsafe { libc::read(self.0.as_raw_fd(), buf.as_mut_ptr() as *mut _, buf.len()) };
if ret != buf.len() as _ {
return Err(Error::last_os_error());
}
Ok(u64::from_ne_bytes(buf))
}
/// Increase value by `n`.
pub fn write(&self, n: u64) -> Result<()> {
let buf = n.to_ne_bytes();
let ret = unsafe { libc::write(self.0.as_raw_fd(), buf.as_ptr() as *mut _, buf.len()) };
if ret != buf.len() as _ {
return Err(Error::last_os_error());
}
Ok(())
}
}
impl AsRawFd for EventFd {
fn as_raw_fd(&self) -> RawFd {
self.0.as_raw_fd()
}
}
/// AIO context wrapper.
#[derive(Debug)]
struct Context(sys::ContextId);
impl Context {
/// create an asynchronous I/O context
pub fn new(nr_events: u32) -> Result<Self> {
let mut id = 0;
unsafe { sys::setup(nr_events, &mut id) }?;
Ok(Self(id))
}
}
impl Drop for Context {
fn drop(&mut self) {
unsafe { sys::destroy(self.0) }.expect("cannot destory AIO context");
}
}
impl Deref for Context {
type Target = sys::ContextId;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Data buffer for AIO operation.
#[derive(Debug)]
pub enum Buffer {
/// Initialized buffer for writing data.
Write(Bytes),
/// Possibly uninitialized buffer for reading data.
Read(BytesMut),
}
impl Buffer {
/// Length or capacity of buffer.
pub fn size(&self) -> usize {
match self {
Self::Write(buf) => buf.len(),
Self::Read(buf) => buf.capacity(),
}
}
/// Get pointer to buffer.
///
/// ## Safety
/// If this is a write buffer the pointer must only be read from.
unsafe fn as_mut_ptr(&mut self) -> *mut u8 {
match self {
Self::Write(buf) => buf.as_ptr() as *mut _,
Self::Read(buf) => buf.as_mut_ptr(),
}
}
/// Assume buffer is initialized to given length.
unsafe fn assume_init(&mut self, len: usize) {
match self {
Self::Write(_) => (),
Self::Read(buf) => buf.set_len(len),
}
}
}
impl From<Bytes> for Buffer {
fn from(buf: Bytes) -> Self {
Self::Write(buf)
}
}
impl From<BytesMut> for Buffer {
fn from(buf: BytesMut) -> Self {
Self::Read(buf)
}
}
impl From<Buffer> for Bytes {
fn from(buf: Buffer) -> Self {
match buf {
Buffer::Write(buf) => buf,
Buffer::Read(buf) => buf.freeze(),
}
}
}
/// Buffer is not a read buffer.
#[derive(Debug, Clone)]
pub struct NotAReadBuffer;
impl TryFrom<Buffer> for BytesMut {
type Error = NotAReadBuffer;
fn try_from(buf: Buffer) -> std::result::Result<Self, NotAReadBuffer> {
match buf {
Buffer::Write(_) => Err(NotAReadBuffer),
Buffer::Read(buf) => Ok(buf),
}
}
}
impl Default for Buffer {
fn default() -> Self {
Self::Write(Bytes::new())
}
}
/// AIO operation.
struct Op {
/// IO control block.
pub iocb: Pin<Box<sys::IoCb>>,
/// Buffer referenced by [`Self::iocb`].
pub buf: Buffer,
}
impl Default for Op {
fn default() -> Self {
Self { iocb: Box::pin(Default::default()), buf: Default::default() }
}
}
impl Op {
/// Get pointer to IO control block.
fn iocb_ptr(&mut self) -> *mut sys::IoCb {
Pin::into_inner(self.iocb.as_mut()) as *mut _
}
/// Given received AIO event convert operation to result.
fn complete(mut self, event: sys::IoEvent) -> CompletedOp {
assert_eq!(event.data, self.iocb.data);
let result = if event.res >= 0 {
unsafe { self.buf.assume_init(event.res.try_into().unwrap()) };
Ok(self.buf)
} else {
Err(Error::from_raw_os_error(-i32::try_from(event.res).unwrap()))
};
CompletedOp { id: event.data, res: event.res, res2: event.res2, result }
}
}
/// AIO operation handle.
pub struct OpHandle(u64);
impl OpHandle {
/// Operation id.
#[allow(dead_code)]
pub const fn id(&self) -> u64 {
self.0
}
}
/// Completed AIO operation.
#[derive(Debug)]
pub struct CompletedOp {
id: u64,
res: i64,
res2: i64,
result: Result<Buffer>,
}
impl CompletedOp {
/// Operation id.
#[allow(dead_code)]
pub const fn id(&self) -> u64 {
self.id
}
/// Retrieve result.
pub fn result(self) -> Result<Buffer> {
self.result
}
/// Result code.
#[allow(dead_code)]
pub const fn res(&self) -> i64 {
self.res
}
/// Result code 2.
#[allow(dead_code)]
pub const fn res2(&self) -> i64 {
self.res2
}
}
enum Cmd {
Insert(Op),
Remove(u64),
#[allow(dead_code)]
Cancel(u64),
CancelAll,
}
#[cfg(feature = "tokio")]
type TNotify = Arc<tokio::sync::Notify>;
#[cfg(not(feature = "tokio"))]
type TNotify = Arc<()>;
/// AIO driver.
///
/// All outstanding operations are cancelled when this is dropped.
pub struct Driver {
aio: Arc<Context>,
cmd_tx: mpsc::Sender<Cmd>,
done_rx: mpsc::Receiver<CompletedOp>,
next_id: u64,
eventfd: EventFd,
space: u32,
queue_length: u32,
#[cfg(feature = "tokio")]
notify: Arc<tokio::sync::Notify>,
}
impl fmt::Debug for Driver {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Driver")
.field("aio", &*self.aio)
.field("next_id", &self.next_id)
.field("space", &self.space)
.field("queue_length", &self.queue_length)
.finish()
}
}
impl Driver {
/// Create new AIO driver.
pub fn new(queue_length: u32, thread_name: Option<String>) -> Result<Self> {
let (cmd_tx, cmd_rx) = mpsc::channel();
let (done_tx, done_rx) = mpsc::channel();
let aio = Arc::new(Context::new(queue_length)?);
let eventfd = EventFd::new(0, true)?;
#[cfg(feature = "tokio")]
let notify = Arc::new(tokio::sync::Notify::new());
#[cfg(not(feature = "tokio"))]
let notify = Arc::new(());
let aio_thread = aio.clone();
let eventfd_thread = eventfd.clone();
let notify_thread = notify.clone();
let mut builder = thread::Builder::new();
if let Some(thread_name) = thread_name {
builder = builder.name(thread_name);
}
builder.spawn(|| Self::thread(aio_thread, eventfd_thread, cmd_rx, done_tx, notify_thread))?;
Ok(Self {
aio,
cmd_tx,
done_rx,
next_id: 0,
eventfd,
space: queue_length,
queue_length,
#[cfg(feature = "tokio")]
notify,
})
}
/// Returns whether the queue of AIO operations is full.
pub fn is_full(&self) -> bool {
self.space == 0
}
/// Returns whether the queue of AIO operations is empty.
pub fn is_empty(&self) -> bool {
self.space == self.queue_length
}
/// Submits an AIO operation.
pub fn submit(&mut self, opcode: u16, file: impl AsRawFd, buf: impl Into<Buffer>) -> Result<OpHandle> {
if self.is_full() {
return Err(Error::new(ErrorKind::WouldBlock, "no AIO queue space available"));
}
let id = self.next_id;
self.next_id = self.next_id.wrapping_add(1);
let mut buf = buf.into();
let iocb =
sys::IoCb::new(opcode, file.as_raw_fd(), unsafe { buf.as_mut_ptr() }, buf.size().try_into().unwrap())
.with_resfd(self.eventfd.as_raw_fd())
.with_data(id);
let mut op = Op { iocb: Box::pin(iocb), buf };
let iocb_ptr = op.iocb_ptr();
self.cmd_tx.send(Cmd::Insert(op)).unwrap();
let mut iocbs = [iocb_ptr];
match unsafe { sys::submit(**self.aio, 1, iocbs.as_mut_ptr()) } {
Ok(1) => {
self.space -= 1;
self.eventfd.write(1).unwrap();
Ok(OpHandle(id))
}
res => {
self.cmd_tx.send(Cmd::Remove(id)).unwrap();
self.eventfd.write(1).unwrap();
match res {
Ok(_) => Err(Error::new(ErrorKind::WouldBlock, "AIO request not accepted")),
Err(err) => Err(err),
}
}
}
}
/// Retrieves the next operation from the completion queue.
///
/// Blocks until a completed operation becomes available.
pub fn completed(&mut self) -> Option<CompletedOp> {
if self.is_empty() {
return None;
}
let res = self.done_rx.recv().unwrap();
self.space += 1;
Some(res)
}
/// Asynchronously retrieves the next operation from the completion queue.
///
/// Waits until a completed operation becomes available.
#[cfg(feature = "tokio")]
pub async fn wait_completed(&mut self) -> Option<CompletedOp> {
if self.is_empty() {
return None;
}
loop {
if let Some(op) = self.try_completed() {
return Some(op);
}
self.notify.notified().await;
}
}
/// Retrieves the next operation from the completion queue with a timeout.
///
/// Blocks until a completed operation becomes available or the timeout is reached.
pub fn completed_timeout(&mut self, timeout: Duration) -> Option<CompletedOp> {
if self.is_empty() {
return None;
}
let res = self.done_rx.recv_timeout(timeout).ok();
if res.is_some() {
self.space += 1;
}
res
}
/// Retrieves the next operation from the completion queue without blocking.
///
/// Returns immediately if no completed operation is available.
pub fn try_completed(&mut self) -> Option<CompletedOp> {
let res = self.done_rx.try_recv().ok();
if res.is_some() {
self.space += 1;
}
res
}
/// Requests cancellation of the specified operation.
#[allow(dead_code)]
pub fn cancel(&mut self, handle: OpHandle) {
self.cmd_tx.send(Cmd::Cancel(handle.0)).unwrap();
self.eventfd.write(1).unwrap();
}
/// Requests cancellation of all operations.
pub fn cancel_all(&mut self) {
self.cmd_tx.send(Cmd::CancelAll).unwrap();
self.eventfd.write(1).unwrap();
}
/// Thread managing submitted AIO operations.
fn thread(
aio: Arc<Context>, eventfd: EventFd, cmd_rx: mpsc::Receiver<Cmd>, done_tx: mpsc::Sender<CompletedOp>,
notify: TNotify,
) {
#[cfg(not(feature = "tokio"))]
let _ = notify;
let mut active: HashMap<u64, Op> = HashMap::new();
let mut event_queue = VecDeque::new();
'outer: loop {
// Wait for event.
eventfd.read().unwrap();
// Process commands.
loop {
match cmd_rx.try_recv() {
Ok(Cmd::Insert(op)) => {
if active.insert(op.iocb.data, op).is_some() {
panic!("submitted aio request with duplicate id");
}
}
Ok(Cmd::Remove(id)) => {
active.remove(&id).expect("received remove request for unknown id");
}
Ok(Cmd::Cancel(id)) => {
if let Entry::Occupied(mut op) = active.entry(id) {
let mut event = MaybeUninit::<sys::IoEvent>::uninit();
if unsafe {
sys::cancel(**aio, op.get_mut().iocb_ptr(), &mut event as *mut _ as *mut _)
}
.is_ok()
{
let _ = done_tx.send(op.remove().complete(unsafe { event.assume_init() }));
#[cfg(feature = "tokio")]
notify.notify_one();
}
}
}
Ok(Cmd::CancelAll) => {
active.retain(|_id, op| {
let mut event = MaybeUninit::<sys::IoEvent>::uninit();
if unsafe { sys::cancel(**aio, op.iocb_ptr(), &mut event as *mut _ as *mut _) }
.is_ok()
{
let _ = done_tx.send(mem::take(op).complete(unsafe { event.assume_init() }));
#[cfg(feature = "tokio")]
notify.notify_one();
false
} else {
true
}
});
}
Err(TryRecvError::Disconnected) if active.is_empty() => break 'outer,
Err(_) => break,
}
}
// Fetch AIO events.
loop {
let mut events = [MaybeUninit::<sys::IoEvent>::uninit(); 16];
let n = unsafe {
sys::getevents(**aio, 0, events.len() as _, events.as_mut_ptr() as *mut _, ptr::null())
}
.expect("io_getevents failed");
if n == 0 {
break;
}
for event in events.into_iter().take(n.try_into().unwrap()) {
let event = unsafe { event.assume_init() };
event_queue.push_back(event);
}
}
// Process AIO events.
while let Some(event) = event_queue.front() {
match active.remove(&event.data) {
Some(op) => {
let _ = done_tx.send(op.complete(event_queue.pop_front().unwrap()));
#[cfg(feature = "tokio")]
notify.notify_one();
}
None => break,
}
}
}
}
}
impl Drop for Driver {
fn drop(&mut self) {
self.cancel_all();
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/src/function/custom/aio/sys.rs | src/function/custom/aio/sys.rs | //! Linux-native AIO interface.
use libc::{
c_int, c_long, c_uint, c_ulong, syscall, timespec, SYS_io_cancel, SYS_io_destroy, SYS_io_getevents,
SYS_io_setup, SYS_io_submit,
};
use std::{
io::{Error, Result},
os::fd::RawFd,
};
/// AIO context.
pub type ContextId = c_ulong;
/// Opcodes for [`IoCb::opcode`].
#[allow(dead_code)]
pub mod opcode {
pub const PREAD: u16 = 0;
pub const PWRITE: u16 = 1;
pub const FSYNC: u16 = 2;
pub const FDSYNC: u16 = 3;
pub const POLL: u16 = 5;
pub const NOOP: u16 = 6;
pub const PREADV: u16 = 7;
pub const PWRITEV: u16 = 8;
}
/// Validity flags for [`IoCb`].
#[allow(dead_code)]
pub mod flags {
/// Set if [`IoCb::resfd`](super::IoCb::resfd) is valid.
pub const RESFD: u32 = 1 << 0;
/// Set if [`IoCb::reqprio`](super::IoCb::reqprio) is valid.
pub const IOPRIO: u32 = 1 << 1;
}
/// AIO event.
#[derive(Debug, Clone, Copy, Default)]
#[repr(C)]
pub struct IoEvent {
/// data from [`IoCb::data`]
pub data: u64,
/// what iocb this event came from
pub obj: u64,
/// result code for this event
pub res: i64,
/// secondary result
pub res2: i64,
}
/// AIO control block.
#[derive(Debug, Clone, Copy, Default)]
#[repr(C)]
pub struct IoCb {
/// data to be returned in [`IoEvent::data`].
pub data: u64,
/// the kernel sets key to the req #
#[cfg(target_endian = "little")]
pub key: u32,
/// RWF_* flags
#[cfg(target_endian = "little")]
pub rw_flags: c_int,
/// RWF_* flags
#[cfg(target_endian = "big")]
pub rw_flags: c_int,
/// the kernel sets key to the req #
#[cfg(target_endian = "big")]
pub key: u32,
/// Opcode from [`opcode`].
pub opcode: u16,
/// This defines the requests priority.
pub reqprio: i16,
/// The file descriptor on which the I/O operation is to be performed.
pub fildes: RawFd,
/// This is the buffer used to transfer data for a read or write operation.
pub buf: u64,
/// This is the size of the buffer pointed to by [`buf`].
pub nbytes: u64,
/// This is the file offset at which the I/O operation is to be performed.
pub offset: i64,
pub _reserved2: u64,
/// Flags specified by [`flags`].
pub flags: u32,
/// if the IOCB_FLAG_RESFD flag of "aio_flags" is set, this is an
/// eventfd to signal AIO readiness to
pub resfd: RawFd,
}
impl IoCb {
pub fn new(opcode: u16, fildes: RawFd, buf: *mut u8, nbytes: u64) -> Self {
Self { opcode, fildes, buf: buf as usize as u64, nbytes, ..Default::default() }
}
pub fn with_resfd(mut self, resfd: RawFd) -> Self {
self.resfd = resfd;
self.flags |= flags::RESFD;
self
}
pub fn with_data(mut self, data: u64) -> Self {
self.data = data;
self
}
}
/// create an asynchronous I/O context
pub unsafe fn setup(nr_events: c_uint, ctx_idp: &mut ContextId) -> Result<()> {
match syscall(SYS_io_setup, nr_events, ctx_idp as *mut _) {
0 => Ok(()),
_ => Err(Error::last_os_error()),
}
}
/// destroy an asynchronous I/O context
pub unsafe fn destroy(ctx_id: ContextId) -> Result<()> {
match syscall(SYS_io_destroy, ctx_id) as c_int {
0 => Ok(()),
_ => Err(Error::last_os_error()),
}
}
/// submit asynchronous I/O blocks for processing
pub unsafe fn submit(ctx_id: ContextId, nr: c_ulong, iocbpp: *mut *mut IoCb) -> Result<c_int> {
match syscall(SYS_io_submit, ctx_id, nr, iocbpp) as c_int {
-1 => Err(Error::last_os_error()),
n => Ok(n),
}
}
/// cancel an outstanding asynchronous I/O operation
pub unsafe fn cancel(ctx_id: ContextId, iocb: *mut IoCb, result: *mut IoEvent) -> Result<()> {
match syscall(SYS_io_cancel, ctx_id, iocb, result) as c_int {
0 => Ok(()),
_ => Err(Error::last_os_error()),
}
}
/// read asynchronous I/O events from the completion queue
pub unsafe fn getevents(
ctx_id: ContextId, min_nr: c_long, nr: c_long, events: *mut IoEvent, timeout: *const timespec,
) -> Result<c_int> {
match syscall(SYS_io_getevents, ctx_id, min_nr, nr, events, timeout) as c_int {
-1 => Err(Error::last_os_error()),
n => Ok(n),
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/tests/video.rs | tests/video.rs | mod common;
use common::*;
use usb_gadget::function::video::{ColorMatching, Format, Frame, Uvc};
#[test]
fn video() {
init();
let mut builder = Uvc::builder().with_frames(vec![
Frame::new(640, 360, vec![15, 30, 60, 120], Format::Yuyv),
Frame::new(640, 360, vec![15, 30, 60, 120], Format::Mjpeg),
Frame::new(1280, 720, vec![30, 60], Format::Mjpeg),
Frame::new(1920, 1080, vec![30], Format::Mjpeg),
]);
builder.frames[0].color_matching = Some(ColorMatching::new(0x4, 0x1, 0x2));
builder.processing_controls = Some(0x05);
builder.camera_controls = Some(0x60);
let (video, func) = builder.build();
let reg = reg(func);
println!("UVC video device at {}", video.status().path().unwrap().display());
unreg(reg).unwrap();
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/tests/udc.rs | tests/udc.rs | mod common;
use common::*;
#[test]
fn query_udcs() {
init();
let udcs = usb_gadget::udcs().unwrap();
println!("USB device controllers:\n{:#?}", &udcs);
for udc in udcs {
println!("Name: {}", udc.name().to_string_lossy());
println!("OTG: {:?}", udc.is_otg().unwrap());
println!("Peripheral: {:?}", udc.is_a_peripheral().unwrap());
println!("Current speed: {:?}", udc.current_speed().unwrap());
println!("Max speed: {:?}", udc.max_speed().unwrap());
println!("State: {:?}", udc.state().unwrap());
println!("Function: {:?}", udc.function().unwrap());
println!();
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/tests/serial.rs | tests/serial.rs | use std::os::unix::prelude::FileTypeExt;
use usb_gadget::function::serial::{Serial, SerialClass};
mod common;
use common::*;
fn serial(serial_class: SerialClass) {
init();
let _mutex = exclusive();
let mut builder = Serial::builder(serial_class);
builder.console = Some(false);
let (serial, func) = builder.build();
let reg = reg(func);
let tty = serial.tty().unwrap();
println!("Serial device {} function at {}", tty.display(), serial.status().path().unwrap().display());
assert!(tty.metadata().unwrap().file_type().is_char_device());
if unreg(reg).unwrap() {
assert!(serial.status().path().is_none());
assert!(serial.tty().is_err());
}
}
#[test]
fn acm() {
serial(SerialClass::Acm)
}
#[test]
fn generic_serial() {
serial(SerialClass::Generic)
}
#[cfg(feature = "tokio")]
#[tokio::test]
#[allow(clippy::await_holding_lock)]
async fn serial_status() {
use std::time::Duration;
use tokio::time::sleep;
use usb_gadget::function::util::State;
init();
let _mutex = exclusive();
let mut builder = Serial::builder(SerialClass::Acm);
builder.console = Some(false);
let (serial, func) = builder.build();
let status = serial.status();
assert_eq!(status.state(), State::Unregistered);
let task = tokio::spawn(async move { status.bound().await });
sleep(Duration::from_secs(1)).await;
let reg = reg(func);
println!("waiting for bound");
task.await.unwrap().unwrap();
let status = serial.status();
assert_eq!(status.state(), State::Bound);
let status = serial.status();
let task = tokio::spawn(async move { status.unbound().await });
sleep(Duration::from_secs(1)).await;
if unreg(reg).unwrap() {
let status = serial.status();
assert_eq!(status.state(), State::Removed);
println!("waiting for unbound");
task.await.unwrap();
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/tests/hid.rs | tests/hid.rs | mod common;
use common::*;
use usb_gadget::function::hid::Hid;
#[test]
fn hid() {
init();
// Keyboard HID description
let mut builder = Hid::builder();
builder.protocol = 1;
builder.sub_class = 1;
builder.report_len = 8;
builder.report_desc = vec![
0x05, 0x01, 0x09, 0x06, 0xa1, 0x01, 0x05, 0x07, 0x19, 0xe0, 0x29, 0xe7, 0x15, 0x00, 0x25, 0x01, 0x75,
0x01, 0x95, 0x08, 0x81, 0x02, 0x95, 0x01, 0x75, 0x08, 0x81, 0x03, 0x95, 0x05, 0x75, 0x01, 0x05, 0x08,
0x19, 0x01, 0x29, 0x05, 0x91, 0x02, 0x95, 0x01, 0x75, 0x03, 0x91, 0x03, 0x95, 0x06, 0x75, 0x08, 0x15,
0x00, 0x25, 0x65, 0x05, 0x07, 0x19, 0x00, 0x29, 0x65, 0x81, 0x00, 0xc0,
];
let (hid, func) = builder.build();
let reg = reg(func);
println!("HID device {:?} at {}", hid.device().unwrap(), hid.status().path().unwrap().display());
unreg(reg).unwrap();
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/tests/printer.rs | tests/printer.rs | mod common;
use common::*;
use usb_gadget::function::printer::Printer;
#[test]
fn printer() {
init();
// Keyboard printer description
let mut builder = Printer::builder();
builder.pnp_string = Some("Rust Printer".to_string());
builder.qlen = Some(20);
let (printer, func) = builder.build();
let reg = reg(func);
println!("printer device at {}", printer.status().path().unwrap().display());
unreg(reg).unwrap();
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/tests/other.rs | tests/other.rs | mod common;
use common::*;
use usb_gadget::function::other::Other;
#[test]
fn other_ecm() {
init();
let dev_addr = "66:f9:7d:f2:3e:2a";
let mut builder = Other::builder("ecm").unwrap();
builder.set("dev_addr", dev_addr).unwrap();
let (other, func) = builder.build();
let reg = reg(func);
println!("Other device at {}", other.status().path().unwrap().display());
let mut dev_addr2 = other.get("dev_addr").unwrap();
dev_addr2.retain(|&c| c != 0);
let dev_addr2 = String::from_utf8_lossy(&dev_addr2).trim().to_string();
assert_eq!(dev_addr, dev_addr2);
unreg(reg).unwrap();
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/tests/msd.rs | tests/msd.rs | mod common;
use common::*;
use std::{io::Write, thread::sleep, time::Duration};
use tempfile::NamedTempFile;
use usb_gadget::function::msd::{Lun, Msd};
#[test]
fn msd() {
init();
let mut file1 = NamedTempFile::new().unwrap();
file1.write_all(&vec![1; 1_048_576]).unwrap();
let path1 = file1.into_temp_path();
let mut file2 = NamedTempFile::new().unwrap();
file2.write_all(&vec![2; 1_048_576]).unwrap();
let path2 = file2.into_temp_path();
let mut builder = Msd::builder();
builder.add_lun(Lun::new(&path1).unwrap());
let mut lun2 = Lun::new(&path2).unwrap();
lun2.cdrom = true;
builder.add_lun(lun2);
let (msd, func) = builder.build();
let reg = reg(func);
println!("MSD device at {}", msd.status().path().unwrap().display());
sleep(Duration::from_secs(1));
msd.force_eject(0).unwrap();
sleep(Duration::from_secs(1));
msd.force_eject(1).unwrap();
sleep(Duration::from_secs(1));
msd.set_file(1, Some(&path1)).unwrap();
sleep(Duration::from_secs(1));
if unreg(reg).unwrap() {
path1.close().expect("cannot delete temp file");
path2.close().expect("cannot delete temp file");
}
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/tests/midi.rs | tests/midi.rs | mod common;
use common::*;
use usb_gadget::function::midi::Midi;
#[test]
fn midi() {
init();
let mut builder = Midi::builder();
builder.id = Some("midi".to_string());
builder.in_ports = Some(1);
builder.out_ports = Some(1);
let (midi, func) = builder.build();
let reg = reg(func);
println!("midi device at {}", midi.status().path().unwrap().display());
unreg(reg).unwrap();
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/tests/audio.rs | tests/audio.rs | mod common;
use common::*;
use usb_gadget::function::audio::{Channel, Uac2};
#[test]
fn audio() {
init();
let (audio, func) = Uac2::new(Channel::new(0b1111_1111, 48000, 24 / 8), Channel::new(0b11, 48000, 16 / 8));
let reg = reg(func);
println!("UAC2 audio device at {}", audio.status().path().unwrap().display());
unreg(reg).unwrap();
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/tests/net.rs | tests/net.rs | mod common;
use common::*;
use macaddr::MacAddr6;
use usb_gadget::function::net::{Net, NetClass};
fn net(net_class: NetClass) {
init();
let _mutex = exclusive();
let dev_addr = MacAddr6::new(0x66, 0xf9, 0x7d, 0xf2, 0x3e, 0x2a);
let host_addr = MacAddr6::new(0x7e, 0x21, 0xb2, 0xcb, 0xd4, 0x51);
let mut builder = Net::builder(net_class);
builder.dev_addr = Some(dev_addr);
builder.host_addr = Some(host_addr);
builder.qmult = Some(10);
let (net, func) = builder.build();
let reg = reg(func);
println!(
"Net device {} function at {}",
net.ifname().unwrap().to_string_lossy(),
net.status().path().unwrap().display()
);
assert_eq!(net.dev_addr().unwrap(), dev_addr);
assert_eq!(net.host_addr().unwrap(), host_addr);
if unreg(reg).unwrap() {
assert!(net.status().path().is_none());
assert!(net.dev_addr().is_err());
}
}
#[test]
fn ecm() {
net(NetClass::Ecm)
}
#[test]
fn ecm_subset() {
net(NetClass::EcmSubset)
}
#[test]
fn eem() {
net(NetClass::Eem)
}
#[test]
fn ncm() {
net(NetClass::Ncm)
}
#[test]
fn rndis() {
net(NetClass::Rndis)
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/tests/gadget.rs | tests/gadget.rs | mod common;
use common::*;
#[test]
fn registered_gadgets() {
init();
let _mutex = exclusive();
let reg = usb_gadget::registered().unwrap();
for gadget in reg {
println!("Gadget {gadget:?} at {}", gadget.path().display());
println!("UDC: {:?}", gadget.udc().unwrap());
println!();
}
}
#[test]
fn remove_all_gadgets() {
init();
let _mutex = exclusive();
usb_gadget::remove_all().unwrap();
}
#[test]
fn unbind_all_gadgets() {
init();
let _mutex = exclusive();
usb_gadget::unbind_all().unwrap();
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/tests/custom.rs | tests/custom.rs | use std::{thread, time::Duration};
use uuid::uuid;
use usb_gadget::{
default_udc,
function::custom::{Custom, Endpoint, EndpointDirection, Interface, OsExtCompat, OsExtProp},
Class,
};
mod common;
use common::*;
#[test]
fn custom() {
init();
let _mutex = exclusive();
let (mut ep1_rx, ep1_dir) = EndpointDirection::host_to_device();
let (mut ep2_tx, ep2_dir) = EndpointDirection::device_to_host();
let (custom, handle) = Custom::builder()
.with_interface(
Interface::new(Class::vendor_specific(1, 1), "custom interface")
.with_endpoint(Endpoint::bulk(ep1_dir))
.with_endpoint(Endpoint::bulk(ep2_dir)),
)
.build();
let reg = reg(handle);
println!("Custom function at {}", custom.status().unwrap().path().unwrap().display());
println!();
println!("Getting ep1_rx control");
let _ep1_control = ep1_rx.control().unwrap();
println!("Getting ep2_tx control");
let _ep2_control = ep2_tx.control().unwrap();
thread::sleep(Duration::from_secs(1));
println!("Unregistering");
if unreg(reg).unwrap() {
assert!(custom.status().unwrap().path().is_none());
}
}
#[test]
#[ignore = "test requires a USB connection to a USB host"]
fn custom_with_os_desc() {
init();
let _mutex = exclusive();
let (mut ep1_rx, ep1_dir) = EndpointDirection::host_to_device();
let (mut ep2_tx, ep2_dir) = EndpointDirection::device_to_host();
let (mut custom, handle) = Custom::builder()
.with_interface(
Interface::new(Class::vendor_specific(1, 1), "custom interface")
.with_endpoint(Endpoint::bulk(ep1_dir))
.with_endpoint(Endpoint::bulk(ep2_dir))
.with_os_ext_compat(OsExtCompat::winusb())
.with_os_ext_prop(OsExtProp::device_interface_guid(uuid!(
"8FE6D4D7-49DD-41E7-9486-49AFC6BFE475"
))),
)
.build();
let reg = reg_with_os_desc(handle);
println!("Custom function at {}", custom.status().unwrap().path().unwrap().display());
println!("real interface address 0: {}", custom.real_address(0).unwrap());
println!();
let ep1_control = ep1_rx.control().unwrap();
println!("ep1 unclaimed: {:?}", ep1_control.unclaimed_fifo());
println!("ep1 real address: {}", ep1_control.real_address().unwrap());
println!("ep1 descriptor: {:?}", ep1_control.descriptor().unwrap());
println!();
let ep2_control = ep2_tx.control().unwrap();
println!("ep2 unclaimed: {:?}", ep2_control.unclaimed_fifo());
println!("ep2 real address: {}", ep2_control.real_address().unwrap());
println!("ep2 descriptor: {:?}", ep2_control.descriptor().unwrap());
println!();
thread::sleep(Duration::from_secs(10));
println!("Unregistering");
if unreg(reg).unwrap() {
assert!(custom.status().unwrap().path().is_none());
}
}
#[test]
fn custom_no_disconnect() {
init();
let _mutex = exclusive();
let (reg, ffs_dir) = {
let (mut ep1_rx, ep1_dir) = EndpointDirection::host_to_device();
let (mut ep2_tx, ep2_dir) = EndpointDirection::device_to_host();
let mut builder = Custom::builder().with_interface(
Interface::new(Class::vendor_specific(1, 1), "custom interface")
.with_endpoint(Endpoint::bulk(ep1_dir))
.with_endpoint(Endpoint::bulk(ep2_dir)),
);
builder.ffs_no_disconnect = true;
builder.ffs_file_mode = Some(0o770);
builder.ffs_root_mode = Some(0o777);
let (mut custom, handle) = builder.build();
let reg = reg(handle);
println!("Custom function at {}", custom.status().unwrap().path().unwrap().display());
println!();
let ffs_dir = custom.ffs_dir().unwrap();
println!("FunctionFS is at {}", ffs_dir.display());
println!("Getting ep1_rx control");
let _ep1_control = ep1_rx.control().unwrap();
println!("Getting ep2_tx control");
let _ep2_control = ep2_tx.control().unwrap();
thread::sleep(Duration::from_secs(3));
println!("Dropping custom interface");
(reg, ffs_dir)
};
println!("Dropped custom interface");
thread::sleep(Duration::from_secs(3));
{
println!("Recreating custom interface using existing FunctionFS mount");
let (mut ep1_rx, ep1_dir) = EndpointDirection::host_to_device();
let (mut ep2_tx, ep2_dir) = EndpointDirection::device_to_host();
let mut custom = Custom::builder()
.with_interface(
Interface::new(Class::vendor_specific(1, 1), "custom interface")
.with_endpoint(Endpoint::bulk(ep1_dir))
.with_endpoint(Endpoint::bulk(ep2_dir)),
)
.existing(&ffs_dir)
.unwrap();
assert_eq!(ffs_dir, custom.ffs_dir().unwrap());
println!("Getting ep1_rx control");
let _ep1_control = ep1_rx.control().unwrap();
println!("Getting ep2_tx control");
let _ep2_control = ep2_tx.control().unwrap();
println!("Reactivating USB gadget");
reg.bind(Some(&default_udc().unwrap())).unwrap();
thread::sleep(Duration::from_secs(3));
println!("Dropping custom interface");
}
println!("Unregistering");
unreg(reg).unwrap();
}
#[test]
fn custom_ext_init() {
init();
let _mutex = exclusive();
let (reg, ffs_dir) = {
let mut builder = Custom::builder();
builder.ffs_no_init = true;
let (mut custom, handle) = builder.build();
let reg = reg_no_bind(handle);
println!("Custom function at {}", custom.status().unwrap().path().unwrap().display());
println!();
let ffs_dir = custom.ffs_dir().unwrap();
println!("FunctionFS is at {}", ffs_dir.display());
custom.fd().expect_err("fd must not be available");
thread::sleep(Duration::from_secs(3));
println!("Dropping custom interface");
(reg, ffs_dir)
};
println!("Dropped custom interface");
thread::sleep(Duration::from_secs(3));
{
println!("Creating custom interface using existing FunctionFS mount");
let (mut ep1_rx, ep1_dir) = EndpointDirection::host_to_device();
let (mut ep2_tx, ep2_dir) = EndpointDirection::device_to_host();
let mut custom = Custom::builder()
.with_interface(
Interface::new(Class::vendor_specific(1, 1), "custom interface")
.with_endpoint(Endpoint::bulk(ep1_dir))
.with_endpoint(Endpoint::bulk(ep2_dir)),
)
.existing(&ffs_dir)
.unwrap();
assert_eq!(ffs_dir, custom.ffs_dir().unwrap());
assert!(custom.status().is_none());
println!("Getting ep1_rx control");
let _ep1_control = ep1_rx.control().unwrap();
println!("Getting ep2_tx control");
let _ep2_control = ep2_tx.control().unwrap();
println!("Activating USB gadget");
reg.bind(Some(&default_udc().unwrap())).unwrap();
thread::sleep(Duration::from_secs(3));
println!("Dropping custom interface");
}
println!("Unregistering");
unreg(reg).unwrap();
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/tests/common/mod.rs | tests/common/mod.rs | //! Common test functions.
#![allow(dead_code)]
use std::{
env,
io::Result,
sync::{Mutex, MutexGuard, Once},
thread::sleep,
time::Duration,
};
use usb_gadget::{
default_udc, function::Handle, registered, Class, Config, Gadget, Id, OsDescriptor, RegGadget, Strings,
WebUsb,
};
pub fn init() {
static INIT: Once = Once::new();
INIT.call_once(|| {
env_logger::init();
for gadget in registered().expect("cannot query registered gadgets") {
if let Some(udc) = gadget.udc().unwrap() {
println!(
"Unbinding gadget {} from UDC {}",
gadget.name().to_string_lossy(),
udc.to_string_lossy()
);
gadget.bind(None).expect("cannot unbind existing gadget");
sleep(Duration::from_secs(1));
}
}
});
}
pub fn reg(func: Handle) -> RegGadget {
let udc = default_udc().expect("cannot get UDC");
let reg =
Gadget::new(Class::new(1, 2, 3), Id::new(4, 5), Strings::new("manufacturer", "product", "serial_number"))
.with_config(Config::new("config").with_function(func))
.bind(&udc)
.expect("cannot bind to UDC");
assert!(reg.is_attached());
assert_eq!(reg.udc().unwrap().unwrap(), udc.name());
println!(
"bound USB gadget {} at {} to {}",
reg.name().to_string_lossy(),
reg.path().display(),
udc.name().to_string_lossy()
);
sleep(Duration::from_secs(3));
reg
}
pub fn reg_no_bind(func: Handle) -> RegGadget {
let reg =
Gadget::new(Class::new(1, 2, 3), Id::new(4, 5), Strings::new("manufacturer", "product", "serial_number"))
.with_config(Config::new("config").with_function(func))
.register()
.expect("cannot register gadget");
assert!(reg.is_attached());
assert_eq!(reg.udc().unwrap(), None);
println!("registered USB gadget {} at {}", reg.name().to_string_lossy(), reg.path().display());
sleep(Duration::from_secs(3));
reg
}
pub fn reg_with_os_desc(func: Handle) -> RegGadget {
let udc = default_udc().expect("cannot get UDC");
let reg = Gadget::new(
Class::new(255, 255, 3),
Id::new(6, 0x11),
Strings::new("manufacturer", "product with OS descriptor", "serial_number"),
)
.with_config(Config::new("config").with_function(func))
.with_os_descriptor(OsDescriptor::microsoft())
.with_web_usb(WebUsb::new(0xf1, "http://webusb.org"))
.bind(&udc)
.expect("cannot bind to UDC");
assert!(reg.is_attached());
assert_eq!(reg.udc().unwrap().unwrap(), udc.name());
println!("bound USB gadget {} at {}", reg.name().to_string_lossy(), reg.path().display());
sleep(Duration::from_secs(3));
reg
}
pub fn unreg(mut reg: RegGadget) -> Result<bool> {
if env::var_os("KEEP_GADGET").is_some() {
reg.detach();
Ok(false)
} else {
reg.remove()?;
sleep(Duration::from_secs(1));
Ok(true)
}
}
pub fn exclusive() -> MutexGuard<'static, ()> {
static LOCK: Mutex<()> = Mutex::new(());
LOCK.lock().unwrap()
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/examples/custom_interface_device_split.rs | examples/custom_interface_device_split.rs | //! Device-side example for USB gadget with custom interface.
//! This example follows the custom_interface_device.rs, but also
//! demonstrates how it is possible to run the privileged parts of
//! gadget setup (interacting with ConfigFS) in a different process to
//! the custom function parts (FunctionFS). This example runs
//! the main gadget logic in an unprivileged process.
use bytes::BytesMut;
use std::{
io::ErrorKind,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
thread,
time::Duration,
};
use usb_gadget::{
default_udc,
function::custom::{Custom, Endpoint, EndpointDirection, EndpointReceiver, EndpointSender, Event, Interface},
Class, Config, Gadget, Id, OsDescriptor, Strings, WebUsb,
};
fn main() {
env_logger::init();
let existing = std::env::var("EXISTING_FFS").ok();
let register_only = std::env::var("REGISTER_ONLY").ok().is_some();
let (ep1_rx, ep1_dir) = EndpointDirection::host_to_device();
let (ep2_tx, ep2_dir) = EndpointDirection::device_to_host();
let mut builder = Custom::builder();
if register_only {
// We are only registering and binding the gadget, and leaving the FunctionFS interactions
// to another process.
builder.ffs_no_init = true;
builder.ffs_uid = Some(std::env::var("SUDO_UID").unwrap().parse().unwrap());
builder.ffs_gid = Some(std::env::var("SUDO_GID").unwrap().parse().unwrap());
} else {
builder = builder.with_interface(
Interface::new(Class::vendor_specific(1, 2), "custom interface")
.with_endpoint(Endpoint::bulk(ep1_dir))
.with_endpoint(Endpoint::bulk(ep2_dir)),
);
}
let (reg, custom) = if let Some(ref path) = existing {
(None, builder.existing(path).unwrap())
} else {
let (mut custom, handle) = builder.build();
usb_gadget::remove_all().expect("cannot remove all gadgets");
let udc = default_udc().expect("cannot get UDC");
let gadget = Gadget::new(
Class::new(255, 255, 3),
Id::new(6, 0x11),
Strings::new("manufacturer", "custom USB interface", "serial_number"),
)
.with_config(Config::new("config").with_function(handle))
.with_os_descriptor(OsDescriptor::microsoft())
.with_web_usb(WebUsb::new(0xf1, "http://webusb.org"));
let reg = gadget.register().expect("cannot register gadget");
if register_only {
let ffs_dir = custom.ffs_dir().unwrap();
println!("FunctionFS dir mounted at {}", ffs_dir.display());
println!("You can now run this program again as unprivileged user:");
println!("EXISTING_FFS={} {}", ffs_dir.display(), std::env::args().next().unwrap());
let mut ep1_path = ffs_dir.clone();
ep1_path.push("ep1");
while std::fs::metadata(&ep1_path).is_err() {
thread::sleep(Duration::from_secs(1));
}
println!("Detected ep1 in FunctionFS dir, this means descriptors have been written to ep0.");
println!("Now binding gadget to UDC (making it active)...");
}
reg.bind(Some(&udc)).expect("cannot bind to UDC");
println!("Custom function at {}", custom.status().unwrap().path().unwrap().display());
println!();
(Some(reg), custom)
};
if register_only {
println!("Waiting for the gadget to become unbound. If you stop the other process, this will happen automatically.");
while reg.as_ref().unwrap().udc().unwrap().is_some() {
thread::sleep(Duration::from_secs(1));
}
} else {
if existing.is_some() {
println!("The FunctionFS setup is done, you can type 'yes' in the other process and hit <ENTER>");
}
run(ep1_rx, ep2_tx, custom);
}
if let Some(reg) = reg {
println!("Unregistering");
reg.remove().unwrap();
}
}
fn run(mut ep1_rx: EndpointReceiver, mut ep2_tx: EndpointSender, mut custom: Custom) {
let ep1_control = ep1_rx.control().unwrap();
println!("ep1 unclaimed: {:?}", ep1_control.unclaimed_fifo());
println!("ep1 real address: {}", ep1_control.real_address().unwrap());
println!("ep1 descriptor: {:?}", ep1_control.descriptor().unwrap());
println!();
let ep2_control = ep2_tx.control().unwrap();
println!("ep2 unclaimed: {:?}", ep2_control.unclaimed_fifo());
println!("ep2 real address: {}", ep2_control.real_address().unwrap());
println!("ep2 descriptor: {:?}", ep2_control.descriptor().unwrap());
println!();
let stop = Arc::new(AtomicBool::new(false));
thread::scope(|s| {
s.spawn(|| {
let size = ep1_rx.max_packet_size().unwrap();
let mut b = 0;
while !stop.load(Ordering::Relaxed) {
let data = ep1_rx
.recv_timeout(BytesMut::with_capacity(size), Duration::from_secs(1))
.expect("recv failed");
match data {
Some(data) => {
println!("received {} bytes: {data:x?}", data.len());
if !data.iter().all(|x| *x == b) {
panic!("wrong data received");
}
b = b.wrapping_add(1);
}
None => {
println!("receive empty");
}
}
}
});
s.spawn(|| {
let size = ep2_tx.max_packet_size().unwrap();
let mut b = 0u8;
while !stop.load(Ordering::Relaxed) {
let data = vec![b; size];
match ep2_tx.send_timeout(data.into(), Duration::from_secs(1)) {
Ok(()) => {
println!("sent data {b} of size {size} bytes");
b = b.wrapping_add(1);
}
Err(err) if err.kind() == ErrorKind::TimedOut => println!("send timeout"),
Err(err) => panic!("send failed: {err}"),
}
}
});
s.spawn(|| {
let mut ctrl_data = Vec::new();
while !stop.load(Ordering::Relaxed) {
if let Some(event) = custom.event_timeout(Duration::from_secs(1)).expect("event failed") {
println!("Event: {event:?}");
match event {
Event::SetupHostToDevice(req) => {
if req.ctrl_req().request == 255 {
println!("Stopping");
stop.store(true, Ordering::Relaxed);
}
ctrl_data = req.recv_all().unwrap();
println!("Control data: {ctrl_data:x?}");
}
Event::SetupDeviceToHost(req) => {
println!("Replying with data");
req.send(&ctrl_data).unwrap();
}
_ => (),
}
} else {
println!("no event");
}
}
});
});
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/examples/printer.rs | examples/printer.rs | //! Printer example userspace application based on [prn_example](https://docs.kernel.org/6.6/usb/gadget_printer.html#example-code)
//!
//! Creates and binds a printer gadget function, then reads data from the device file created by the
//! gadget to stdout. Will exit after printing a set number of pages.
use nix::{ioctl_read, ioctl_readwrite};
use std::{
fs::{File, OpenOptions},
io::{self, Read, Write},
os::unix::io::AsRawFd,
};
use usb_gadget::{
default_udc,
function::printer::{Printer, StatusFlags, GADGET_GET_PRINTER_STATUS, GADGET_SET_PRINTER_STATUS},
Class, Config, Gadget, Id, RegGadget, Strings, GADGET_IOC_MAGIC,
};
// Printer read buffer size, best equal to EP wMaxPacketSize
const BUF_SIZE: usize = 512;
// Printer device path - 0 assumes we are the only printer gadget!
const DEV_PATH: &str = "/dev/g_printer0";
// Pages to 'print' before exiting
const PRINT_EXIT_COUNT: u8 = 1;
// Default printer status
const DEFAULT_STATUS: StatusFlags =
StatusFlags::from_bits_truncate(StatusFlags::NOT_ERROR.bits() | StatusFlags::SELECTED.bits());
// ioctl read/write for printer status
ioctl_read!(ioctl_read_printer_status, GADGET_IOC_MAGIC, GADGET_GET_PRINTER_STATUS, u8);
ioctl_readwrite!(ioctl_write_printer_status, GADGET_IOC_MAGIC, GADGET_SET_PRINTER_STATUS, u8);
fn create_printer_gadget() -> io::Result<RegGadget> {
usb_gadget::remove_all().expect("cannot remove all gadgets");
let udc = default_udc().expect("cannot get UDC");
let mut builder = Printer::builder();
builder.pnp_string = Some("Rust PNP".to_string());
let (_, func) = builder.build();
let reg =
// Linux Foundation VID Gadget PID
Gadget::new(Class::interface_specific(), Id::new(0x1d6b, 0x0104), Strings::new("Clippy Manufacturer", "Rusty Printer", "RUST0123456"))
.with_config(Config::new("Config 1")
.with_function(func))
.bind(&udc)?;
Ok(reg)
}
fn read_printer_data(file: &mut File) -> io::Result<()> {
let mut buf = [0u8; BUF_SIZE];
let mut printed = 0;
println!("Will exit after printing {} pages...", PRINT_EXIT_COUNT);
loop {
let bytes_read = match file.read(&mut buf) {
Ok(bytes_read) if bytes_read > 0 => bytes_read,
_ => break,
};
io::stdout().write_all(&buf[..bytes_read])?;
io::stdout().flush()?;
// check if %%EOF is in the buffer
if buf.windows(5).any(|w| w == b"%%EOF") {
printed += 1;
if printed == PRINT_EXIT_COUNT {
println!("Printed {} pages, exiting.", PRINT_EXIT_COUNT);
break;
}
}
}
Ok(())
}
fn set_printer_status(file: &File, flags: StatusFlags, clear: bool) -> io::Result<StatusFlags> {
let mut status = get_printer_status(file)?;
if clear {
status.remove(flags);
} else {
status.insert(flags);
}
let mut bits = status.bits();
log::debug!("Setting printer status: {:08b}", bits);
unsafe { ioctl_write_printer_status(file.as_raw_fd(), &mut bits) }?;
Ok(StatusFlags::from_bits_truncate(bits))
}
fn get_printer_status(file: &File) -> io::Result<StatusFlags> {
let mut status = 0;
unsafe { ioctl_read_printer_status(file.as_raw_fd(), &mut status) }?;
log::debug!("Got printer status: {:08b}", status);
let status = StatusFlags::from_bits_truncate(status);
Ok(status)
}
fn print_status(status: StatusFlags) {
println!("Printer status is:");
if status.contains(StatusFlags::SELECTED) {
println!(" Printer is Selected");
} else {
println!(" Printer is NOT Selected");
}
if status.contains(StatusFlags::PAPER_EMPTY) {
println!(" Paper is Out");
} else {
println!(" Paper is Loaded");
}
if status.contains(StatusFlags::NOT_ERROR) {
println!(" Printer OK");
} else {
println!(" Printer ERROR");
}
}
fn main() -> io::Result<()> {
env_logger::init();
// create printer gadget, will unbind on drop
let g_printer = create_printer_gadget().map_err(|e| {
eprintln!("Failed to create printer gadget: {e}");
e
})?;
println!("Printer gadget created: {}", g_printer.path().display());
// wait for device file creation
println!("Attempt open device path: {}", DEV_PATH);
let mut count = 0;
let mut file = loop {
std::thread::sleep(std::time::Duration::from_secs(1));
match OpenOptions::new().read(true).write(true).open(DEV_PATH) {
Ok(file) => break file,
Err(_) if count < 5 => count += 1,
Err(err) => {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("Printer {DEV_PATH} not found or cannot open: {err}",),
))
}
}
};
print_status(set_printer_status(&file, DEFAULT_STATUS, false)?);
if let Err(e) = read_printer_data(&mut file) {
return Err(io::Error::new(io::ErrorKind::Other, format!("Failed to read data from {DEV_PATH}: {e}")));
}
Ok(())
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/examples/custom_interface_device_async.rs | examples/custom_interface_device_async.rs | //! Device-side example for USB gadget with custom interface using async IO.
use bytes::BytesMut;
use std::{
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
use usb_gadget::{
default_udc,
function::custom::{Custom, Endpoint, EndpointDirection, Event, Interface},
Class, Config, Gadget, Id, OsDescriptor, Strings, WebUsb,
};
#[tokio::main(flavor = "current_thread")]
async fn main() {
env_logger::init();
usb_gadget::remove_all().expect("cannot remove all gadgets");
let (mut ep1_rx, ep1_dir) = EndpointDirection::host_to_device();
let (mut ep2_tx, ep2_dir) = EndpointDirection::device_to_host();
let (mut custom, handle) = Custom::builder()
.with_interface(
Interface::new(Class::vendor_specific(1, 2), "custom interface")
.with_endpoint(Endpoint::bulk(ep1_dir))
.with_endpoint(Endpoint::bulk(ep2_dir)),
)
.build();
let udc = default_udc().expect("cannot get UDC");
let reg = Gadget::new(
Class::new(255, 255, 3),
Id::new(6, 0x11),
Strings::new("manufacturer", "custom USB interface", "serial_number"),
)
.with_config(Config::new("config").with_function(handle))
.with_os_descriptor(OsDescriptor::microsoft())
.with_web_usb(WebUsb::new(0xf1, "http://webusb.org"))
.bind(&udc)
.expect("cannot bind to UDC");
println!("Custom function at {}", custom.status().unwrap().path().unwrap().display());
println!();
let ep1_control = ep1_rx.control().unwrap();
println!("ep1 unclaimed: {:?}", ep1_control.unclaimed_fifo());
println!("ep1 real address: {}", ep1_control.real_address().unwrap());
println!("ep1 descriptor: {:?}", ep1_control.descriptor().unwrap());
println!();
let ep2_control = ep2_tx.control().unwrap();
println!("ep2 unclaimed: {:?}", ep2_control.unclaimed_fifo());
println!("ep2 real address: {}", ep2_control.real_address().unwrap());
println!("ep2 descriptor: {:?}", ep2_control.descriptor().unwrap());
println!();
let stop = Arc::new(AtomicBool::new(false));
let stop1 = stop.clone();
tokio::spawn(async move {
let size = ep1_rx.max_packet_size().unwrap();
let mut b = 0;
while !stop1.load(Ordering::Relaxed) {
let data = ep1_rx.recv_async(BytesMut::with_capacity(size)).await.expect("recv_async failed");
match data {
Some(data) => {
println!("received {} bytes: {data:x?}", data.len());
if !data.iter().all(|x| *x == b) {
panic!("wrong data received");
}
b = b.wrapping_add(1);
}
None => {
println!("receive empty");
}
}
}
});
let stop2 = stop.clone();
tokio::spawn(async move {
let size = ep2_tx.max_packet_size().unwrap();
let mut b = 0u8;
while !stop2.load(Ordering::Relaxed) {
let data = vec![b; size];
match ep2_tx.send_async(data.into()).await {
Ok(()) => {
println!("sent data {b} of size {size} bytes");
b = b.wrapping_add(1);
}
Err(err) => panic!("send failed: {err}"),
}
}
});
let mut ctrl_data = Vec::new();
while !stop.load(Ordering::Relaxed) {
custom.wait_event().await.expect("wait for event failed");
println!("event ready");
let event = custom.event().expect("event failed");
println!("Event: {event:?}");
match event {
Event::SetupHostToDevice(req) => {
if req.ctrl_req().request == 255 {
println!("Stopping");
stop.store(true, Ordering::Relaxed);
}
ctrl_data = req.recv_all().unwrap();
println!("Control data: {ctrl_data:x?}");
}
Event::SetupDeviceToHost(req) => {
println!("Replying with data");
req.send(&ctrl_data).unwrap();
}
_ => (),
}
}
tokio::time::sleep(Duration::from_secs(1)).await;
println!("Unregistering");
reg.remove().unwrap();
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/examples/custom_interface_host.rs | examples/custom_interface_host.rs | //! Host-side example for USB gadget with custom interface.
use std::{thread, time::Duration};
use rusb::{open_device_with_vid_pid, request_type, Direction, RequestType};
fn main() {
let hnd = open_device_with_vid_pid(6, 0x11).expect("USB device not found");
let dev = hnd.device();
println!("device opened: {hnd:?}");
let cfg = dev.active_config_descriptor().unwrap();
let mut my_if = None;
let mut ep_in = None;
let mut ep_out = None;
for intf in cfg.interfaces() {
println!("Interface {}:", intf.number());
for desc in intf.descriptors() {
println!(" Descriptor {:?}", desc);
for ep in desc.endpoint_descriptors() {
println!(" Endpoint {ep:?}");
println!(" Direction: {:?}", ep.direction());
println!(" Transfer type: {:?}", ep.transfer_type());
match ep.direction() {
Direction::In => ep_in = Some(ep.address()),
Direction::Out => ep_out = Some(ep.address()),
}
my_if = Some(intf.number());
}
}
println!();
}
let my_if = my_if.unwrap();
let ep_in = ep_in.unwrap();
let ep_out = ep_out.unwrap();
println!("claiming interface {my_if}");
hnd.claim_interface(my_if).expect("cannot claim interface");
//hnd.reset().expect("reset failed");
hnd.write_control(
request_type(Direction::Out, RequestType::Vendor, rusb::Recipient::Interface),
100,
200,
my_if.into(),
&[],
Duration::from_secs(1),
)
.expect("control error");
let buf = [1, 2, 3, 4, 5, 6];
hnd.write_control(
request_type(Direction::Out, RequestType::Vendor, rusb::Recipient::Interface),
123,
222,
my_if.into(),
&buf,
Duration::from_secs(1),
)
.expect("control error");
let mut rbuf = vec![0; buf.len()];
hnd.read_control(
request_type(Direction::In, RequestType::Vendor, rusb::Recipient::Interface),
123,
222,
my_if.into(),
&mut rbuf,
Duration::from_secs(1),
)
.expect("control error");
assert_eq!(&buf, rbuf.as_slice());
thread::scope(|t| {
t.spawn(|| {
println!("reading from endpoint {ep_in}");
let mut b = 0;
for _ in 0..1024 {
let mut buf = vec![0; 512];
let n = hnd.read_bulk(ep_in, &mut buf, Duration::from_secs(1)).expect("cannot read");
buf.truncate(n);
println!("Read {n} bytes: {:x?}", &buf);
if !buf.iter().all(|x| *x == b) {
panic!("wrong data received");
}
b = b.wrapping_add(1);
}
});
t.spawn(|| {
println!("writing to endpoint {ep_out}");
let mut b = 0u8;
for _ in 0..1024 {
hnd.write_bulk(ep_out, &vec![b; 512], Duration::from_secs(1)).expect("cannot write");
b = b.wrapping_add(1);
}
});
});
hnd.write_control(
request_type(Direction::Out, RequestType::Vendor, rusb::Recipient::Interface),
255,
255,
my_if.into(),
&[],
Duration::from_secs(1),
)
.expect("control error");
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
surban/usb-gadget | https://github.com/surban/usb-gadget/blob/d5823aade2c4d1718b9b229435dceac44e812dce/examples/custom_interface_device.rs | examples/custom_interface_device.rs | //! Device-side example for USB gadget with custom interface.
use bytes::BytesMut;
use std::{
io::ErrorKind,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
thread,
time::Duration,
};
use usb_gadget::{
default_udc,
function::custom::{Custom, Endpoint, EndpointDirection, Event, Interface},
Class, Config, Gadget, Id, OsDescriptor, Strings, WebUsb,
};
fn main() {
env_logger::init();
usb_gadget::remove_all().expect("cannot remove all gadgets");
let (mut ep1_rx, ep1_dir) = EndpointDirection::host_to_device();
let (mut ep2_tx, ep2_dir) = EndpointDirection::device_to_host();
let (mut custom, handle) = Custom::builder()
.with_interface(
Interface::new(Class::vendor_specific(1, 2), "custom interface")
.with_endpoint(Endpoint::bulk(ep1_dir))
.with_endpoint(Endpoint::bulk(ep2_dir)),
)
.build();
let udc = default_udc().expect("cannot get UDC");
let reg = Gadget::new(
Class::new(255, 255, 3),
Id::new(6, 0x11),
Strings::new("manufacturer", "custom USB interface", "serial_number"),
)
.with_config(Config::new("config").with_function(handle))
.with_os_descriptor(OsDescriptor::microsoft())
.with_web_usb(WebUsb::new(0xf1, "http://webusb.org"))
.bind(&udc)
.expect("cannot bind to UDC");
println!("Custom function at {}", custom.status().unwrap().path().unwrap().display());
println!();
let ep1_control = ep1_rx.control().unwrap();
println!("ep1 unclaimed: {:?}", ep1_control.unclaimed_fifo());
println!("ep1 real address: {}", ep1_control.real_address().unwrap());
println!("ep1 descriptor: {:?}", ep1_control.descriptor().unwrap());
println!();
let ep2_control = ep2_tx.control().unwrap();
println!("ep2 unclaimed: {:?}", ep2_control.unclaimed_fifo());
println!("ep2 real address: {}", ep2_control.real_address().unwrap());
println!("ep2 descriptor: {:?}", ep2_control.descriptor().unwrap());
println!();
let stop = Arc::new(AtomicBool::new(false));
thread::scope(|s| {
s.spawn(|| {
let size = ep1_rx.max_packet_size().unwrap();
let mut b = 0;
while !stop.load(Ordering::Relaxed) {
let data = ep1_rx
.recv_timeout(BytesMut::with_capacity(size), Duration::from_secs(1))
.expect("recv failed");
match data {
Some(data) => {
println!("received {} bytes: {data:x?}", data.len());
if !data.iter().all(|x| *x == b) {
panic!("wrong data received");
}
b = b.wrapping_add(1);
}
None => {
println!("receive empty");
}
}
}
});
s.spawn(|| {
let size = ep2_tx.max_packet_size().unwrap();
let mut b = 0u8;
while !stop.load(Ordering::Relaxed) {
let data = vec![b; size];
match ep2_tx.send_timeout(data.into(), Duration::from_secs(1)) {
Ok(()) => {
println!("sent data {b} of size {size} bytes");
b = b.wrapping_add(1);
}
Err(err) if err.kind() == ErrorKind::TimedOut => println!("send timeout"),
Err(err) => panic!("send failed: {err}"),
}
}
});
s.spawn(|| {
let mut ctrl_data = Vec::new();
while !stop.load(Ordering::Relaxed) {
if let Some(event) = custom.event_timeout(Duration::from_secs(1)).expect("event failed") {
println!("Event: {event:?}");
match event {
Event::SetupHostToDevice(req) => {
if req.ctrl_req().request == 255 {
println!("Stopping");
stop.store(true, Ordering::Relaxed);
}
ctrl_data = req.recv_all().unwrap();
println!("Control data: {ctrl_data:x?}");
}
Event::SetupDeviceToHost(req) => {
println!("Replying with data");
req.send(&ctrl_data).unwrap();
}
_ => (),
}
} else {
println!("no event");
}
}
});
});
thread::sleep(Duration::from_secs(1));
println!("Unregistering");
reg.remove().unwrap();
}
| rust | Apache-2.0 | d5823aade2c4d1718b9b229435dceac44e812dce | 2026-01-04T20:23:22.416925Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/random.rs | src/random.rs | use std::cell::RefCell;
use itertools::izip;
use num_traits::{FromPrimitive, PrimInt, Zero};
use rand::{distributions::Uniform, Rng, RngCore, SeedableRng};
use rand_chacha::ChaCha8Rng;
use rand_distr::{uniform::SampleUniform, Distribution};
use crate::{backend::Modulus, utils::WithLocal};
thread_local! {
pub(crate) static DEFAULT_RNG: RefCell<DefaultSecureRng> = RefCell::new(DefaultSecureRng::new());
}
pub trait NewWithSeed {
type Seed;
fn new_with_seed(seed: Self::Seed) -> Self;
}
pub trait RandomElementInModulus<T, M> {
/// Sample Random element of type T in range [0, modulus)
fn random(&mut self, modulus: &M) -> T;
}
pub trait RandomGaussianElementInModulus<T, M> {
/// Sample Random gaussian element from \mu = 0.0 and \sigma = 3.19. Sampled
/// element is converted to signed representation in modulus.
fn random(&mut self, modulus: &M) -> T;
}
pub trait RandomFill<M>
where
M: ?Sized,
{
/// Fill container with random elements of type of its elements
fn random_fill(&mut self, container: &mut M);
}
pub trait RandomFillGaussian<M>
where
M: ?Sized,
{
/// Fill container with random elements sampled from normal distribtuion
/// with \mu = 0.0 and \sigma = 3.19.
fn random_fill(&mut self, container: &mut M);
}
pub trait RandomFillUniformInModulus<M, P>
where
M: ?Sized,
{
/// Fill container with random elements in range [0, modulus)
fn random_fill(&mut self, modulus: &P, container: &mut M);
}
pub trait RandomFillGaussianInModulus<M, P>
where
M: ?Sized,
{
/// Fill container with gaussian elements sampled from normal distribution
/// with \mu = 0.0 and \sigma = 3.19. Elements are converted to signed
/// represented in the modulus.
fn random_fill(&mut self, modulus: &P, container: &mut M);
}
pub struct DefaultSecureRng {
rng: ChaCha8Rng,
}
impl DefaultSecureRng {
pub fn new_seeded(seed: <ChaCha8Rng as SeedableRng>::Seed) -> DefaultSecureRng {
let rng = ChaCha8Rng::from_seed(seed);
DefaultSecureRng { rng }
}
pub fn new() -> DefaultSecureRng {
let rng = ChaCha8Rng::from_entropy();
DefaultSecureRng { rng }
}
pub fn fill_bytes(&mut self, a: &mut [u8; 32]) {
self.rng.fill_bytes(a);
}
}
impl NewWithSeed for DefaultSecureRng {
type Seed = <ChaCha8Rng as SeedableRng>::Seed;
fn new_with_seed(seed: Self::Seed) -> Self {
DefaultSecureRng::new_seeded(seed)
}
}
impl<T, C> RandomFillUniformInModulus<[T], C> for DefaultSecureRng
where
T: PrimInt + SampleUniform,
C: Modulus<Element = T>,
{
fn random_fill(&mut self, modulus: &C, container: &mut [T]) {
izip!(
(&mut self.rng).sample_iter(Uniform::new_inclusive(
T::zero(),
modulus.largest_unsigned_value()
)),
container.iter_mut()
)
.for_each(|(from, to)| {
*to = from;
});
}
}
impl<T, C> RandomFillGaussianInModulus<[T], C> for DefaultSecureRng
where
T: PrimInt,
C: Modulus<Element = T>,
{
fn random_fill(&mut self, modulus: &C, container: &mut [T]) {
izip!(
rand_distr::Normal::new(0.0, 3.19f64)
.unwrap()
.sample_iter(&mut self.rng),
container.iter_mut()
)
.for_each(|(from, to)| {
*to = modulus.map_element_from_f64(from);
});
}
}
impl<T> RandomFill<[T]> for DefaultSecureRng
where
T: PrimInt + SampleUniform,
{
fn random_fill(&mut self, container: &mut [T]) {
izip!(
(&mut self.rng).sample_iter(Uniform::new_inclusive(T::zero(), T::max_value())),
container.iter_mut()
)
.for_each(|(from, to)| {
*to = from;
});
}
}
impl<T> RandomFillGaussian<[T]> for DefaultSecureRng
where
T: FromPrimitive,
{
fn random_fill(&mut self, container: &mut [T]) {
izip!(
rand_distr::Normal::new(0.0, 3.19f64)
.unwrap()
.sample_iter(&mut self.rng),
container.iter_mut()
)
.for_each(|(from, to)| {
*to = T::from_f64(from).unwrap();
});
}
}
impl<T> RandomFill<[T; 32]> for DefaultSecureRng
where
T: PrimInt + SampleUniform,
{
fn random_fill(&mut self, container: &mut [T; 32]) {
izip!(
(&mut self.rng).sample_iter(Uniform::new_inclusive(T::zero(), T::max_value())),
container.iter_mut()
)
.for_each(|(from, to)| {
*to = from;
});
}
}
impl<T> RandomElementInModulus<T, T> for DefaultSecureRng
where
T: Zero + SampleUniform,
{
fn random(&mut self, modulus: &T) -> T {
Uniform::new(T::zero(), modulus).sample(&mut self.rng)
}
}
impl<T, M: Modulus<Element = T>> RandomGaussianElementInModulus<T, M> for DefaultSecureRng {
fn random(&mut self, modulus: &M) -> T {
modulus.map_element_from_f64(
rand_distr::Normal::new(0.0, 3.19f64)
.unwrap()
.sample(&mut self.rng),
)
}
}
impl WithLocal for DefaultSecureRng {
fn with_local<F, R>(func: F) -> R
where
F: Fn(&Self) -> R,
{
DEFAULT_RNG.with_borrow(|r| func(r))
}
fn with_local_mut<F, R>(func: F) -> R
where
F: Fn(&mut Self) -> R,
{
DEFAULT_RNG.with_borrow_mut(|r| func(r))
}
fn with_local_mut_mut<F, R>(func: &mut F) -> R
where
F: FnMut(&mut Self) -> R,
{
DEFAULT_RNG.with_borrow_mut(|r| func(r))
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/lib.rs | src/lib.rs | use num_traits::Zero;
mod backend;
mod bool;
mod decomposer;
mod lwe;
mod multi_party;
mod ntt;
mod pbs;
mod random;
mod rgsw;
#[cfg(any(feature = "interactive_mp", feature = "non_interactive_mp"))]
mod shortint;
mod utils;
pub use backend::{
ArithmeticLazyOps, ArithmeticOps, ModInit, ModularOpsU64, ShoupMatrixFMA, VectorOps,
};
pub use bool::*;
pub use ntt::{Ntt, NttBackendU64, NttInit};
#[cfg(any(feature = "interactive_mp", feature = "non_interactive_mp"))]
pub use shortint::{div_zero_error_flag, reset_error_flags, FheUint8};
pub use decomposer::{Decomposer, DecomposerIter, DefaultDecomposer};
pub trait Matrix: AsRef<[Self::R]> {
type MatElement;
type R: Row<Element = Self::MatElement>;
fn dimension(&self) -> (usize, usize);
fn get_row(&self, row_idx: usize) -> impl Iterator<Item = &Self::MatElement> {
self.as_ref()[row_idx].as_ref().iter().map(move |r| r)
}
fn get_row_slice(&self, row_idx: usize) -> &[Self::MatElement] {
self.as_ref()[row_idx].as_ref()
}
fn iter_rows(&self) -> impl Iterator<Item = &Self::R> {
self.as_ref().iter().map(move |r| r)
}
fn get(&self, row_idx: usize, column_idx: usize) -> &Self::MatElement {
&self.as_ref()[row_idx].as_ref()[column_idx]
}
fn split_at_row(&self, idx: usize) -> (&[<Self as Matrix>::R], &[<Self as Matrix>::R]) {
self.as_ref().split_at(idx)
}
/// Does the matrix fit sub-matrix of dimension row x col
fn fits(&self, row: usize, col: usize) -> bool;
}
pub trait MatrixMut: Matrix + AsMut<[<Self as Matrix>::R]>
where
<Self as Matrix>::R: RowMut,
{
fn get_row_mut(&mut self, row_index: usize) -> &mut [Self::MatElement] {
self.as_mut()[row_index].as_mut()
}
fn iter_rows_mut(&mut self) -> impl Iterator<Item = &mut Self::R> {
self.as_mut().iter_mut().map(move |r| r)
}
fn set(&mut self, row_idx: usize, column_idx: usize, val: <Self as Matrix>::MatElement) {
self.as_mut()[row_idx].as_mut()[column_idx] = val;
}
fn split_at_row_mut(
&mut self,
idx: usize,
) -> (&mut [<Self as Matrix>::R], &mut [<Self as Matrix>::R]) {
self.as_mut().split_at_mut(idx)
}
}
pub trait MatrixEntity: Matrix // where
// <Self as Matrix>::MatElement: Zero,
{
fn zeros(row: usize, col: usize) -> Self;
}
pub trait Row: AsRef<[Self::Element]> {
type Element;
}
pub trait RowMut: Row + AsMut<[<Self as Row>::Element]> {}
pub trait RowEntity: Row {
fn zeros(col: usize) -> Self;
}
impl<T> Matrix for Vec<Vec<T>> {
type MatElement = T;
type R = Vec<T>;
fn dimension(&self) -> (usize, usize) {
(self.len(), self[0].len())
}
fn fits(&self, row: usize, col: usize) -> bool {
self.len() >= row && self[0].len() >= col
}
}
impl<T> Matrix for &[Vec<T>] {
type MatElement = T;
type R = Vec<T>;
fn dimension(&self) -> (usize, usize) {
(self.len(), self[0].len())
}
fn fits(&self, row: usize, col: usize) -> bool {
self.len() >= row && self[0].len() >= col
}
}
impl<T> Matrix for &mut [Vec<T>] {
type MatElement = T;
type R = Vec<T>;
fn dimension(&self) -> (usize, usize) {
(self.len(), self[0].len())
}
fn fits(&self, row: usize, col: usize) -> bool {
self.len() >= row && self[0].len() >= col
}
}
impl<T> MatrixMut for Vec<Vec<T>> {}
impl<T> MatrixMut for &mut [Vec<T>] {}
impl<T: Zero + Clone> MatrixEntity for Vec<Vec<T>> {
fn zeros(row: usize, col: usize) -> Self {
vec![vec![T::zero(); col]; row]
}
}
impl<T> Row for Vec<T> {
type Element = T;
}
impl<T> Row for [T] {
type Element = T;
}
impl<T> RowMut for Vec<T> {}
impl<T: Zero + Clone> RowEntity for Vec<T> {
fn zeros(col: usize) -> Self {
vec![T::zero(); col]
}
}
pub trait Encryptor<M: ?Sized, C> {
fn encrypt(&self, m: &M) -> C;
}
pub trait Decryptor<M, C> {
fn decrypt(&self, c: &C) -> M;
}
pub trait MultiPartyDecryptor<M, C> {
type DecryptionShare;
fn gen_decryption_share(&self, c: &C) -> Self::DecryptionShare;
fn aggregate_decryption_shares(&self, c: &C, shares: &[Self::DecryptionShare]) -> M;
}
pub trait KeySwitchWithId<C> {
fn key_switch(&self, user_id: usize) -> C;
}
pub trait SampleExtractor<R> {
/// Extract ciphertext at `index`
fn extract_at(&self, index: usize) -> R;
/// Extract all ciphertexts
fn extract_all(&self) -> Vec<R>;
/// Extract first `how_many` ciphertexts
fn extract_many(&self, how_many: usize) -> Vec<R>;
}
trait Encoder<F, T> {
fn encode(&self, v: F) -> T;
}
trait SizeInBitsWithLogModulus {
/// Returns size of `Self` containing several elements mod Q where
/// 2^{log_modulus-1} < Q <= `2^log_modulus`
fn size(&self, log_modulus: usize) -> usize;
}
impl SizeInBitsWithLogModulus for Vec<Vec<u64>> {
fn size(&self, log_modulus: usize) -> usize {
let mut total = 0;
self.iter().for_each(|r| total += log_modulus * r.len());
total
}
}
impl SizeInBitsWithLogModulus for Vec<u64> {
fn size(&self, log_modulus: usize) -> usize {
self.len() * log_modulus
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/decomposer.rs | src/decomposer.rs | use itertools::{izip, Itertools};
use num_traits::{FromPrimitive, PrimInt, ToPrimitive, WrappingAdd, WrappingSub};
use std::fmt::{Debug, Display};
use crate::{
backend::ArithmeticOps,
parameters::{
DecompositionCount, DecompostionLogBase, DoubleDecomposerParams, SingleDecomposerParams,
},
utils::log2,
};
fn gadget_vector<T: PrimInt>(logq: usize, logb: usize, d: usize) -> Vec<T> {
assert!(logq >= (logb * d));
let ignored_bits = logq - (logb * d);
(0..d)
.into_iter()
.map(|i| T::one() << (logb * i + ignored_bits))
.collect_vec()
}
pub trait RlweDecomposer {
type Element;
type D: Decomposer<Element = Self::Element>;
/// Decomposer for RLWE Part A
fn a(&self) -> &Self::D;
/// Decomposer for RLWE Part B
fn b(&self) -> &Self::D;
}
impl<D> RlweDecomposer for (D, D)
where
D: Decomposer,
{
type D = D;
type Element = D::Element;
fn a(&self) -> &Self::D {
&self.0
}
fn b(&self) -> &Self::D {
&self.1
}
}
impl<D> DoubleDecomposerParams for D
where
D: RlweDecomposer,
{
type Base = DecompostionLogBase;
type Count = DecompositionCount;
fn decomposition_base(&self) -> Self::Base {
assert!(
Decomposer::decomposition_base(self.a()) == Decomposer::decomposition_base(self.b())
);
Decomposer::decomposition_base(self.a())
}
fn decomposition_count_a(&self) -> Self::Count {
Decomposer::decomposition_count(self.a())
}
fn decomposition_count_b(&self) -> Self::Count {
Decomposer::decomposition_count(self.b())
}
}
impl<D> SingleDecomposerParams for D
where
D: Decomposer,
{
type Base = DecompostionLogBase;
type Count = DecompositionCount;
fn decomposition_base(&self) -> Self::Base {
Decomposer::decomposition_base(self)
}
fn decomposition_count(&self) -> Self::Count {
Decomposer::decomposition_count(self)
}
}
pub trait Decomposer {
type Element;
type Iter: Iterator<Item = Self::Element>;
fn new(q: Self::Element, logb: usize, d: usize) -> Self;
fn decompose_to_vec(&self, v: &Self::Element) -> Vec<Self::Element>;
fn decompose_iter(&self, v: &Self::Element) -> Self::Iter;
fn decomposition_count(&self) -> DecompositionCount;
fn decomposition_base(&self) -> DecompostionLogBase;
fn gadget_vector(&self) -> Vec<Self::Element>;
}
pub struct DefaultDecomposer<T> {
/// Ciphertext modulus
q: T,
/// Log of ciphertext modulus
logq: usize,
/// Log of base B
logb: usize,
/// base B
b: T,
/// (B - 1). To simulate (% B) as &(B-1), that is extract least significant
/// logb bits
b_mask: T,
/// B/2
bby2: T,
/// Decomposition count
d: usize,
/// No. of bits to ignore in rounding
ignore_bits: usize,
}
pub trait NumInfo {
const BITS: u32;
}
impl NumInfo for u64 {
const BITS: u32 = u64::BITS;
}
impl NumInfo for u32 {
const BITS: u32 = u32::BITS;
}
impl NumInfo for u128 {
const BITS: u32 = u128::BITS;
}
impl<T: PrimInt + NumInfo + Debug> DefaultDecomposer<T> {
fn recompose<Op>(&self, limbs: &[T], modq_op: &Op) -> T
where
Op: ArithmeticOps<Element = T>,
{
let mut value = T::zero();
let gadget_vector = gadget_vector(self.logq, self.logb, self.d);
assert!(limbs.len() == gadget_vector.len());
izip!(limbs.iter(), gadget_vector.iter())
.for_each(|(d_el, beta)| value = modq_op.add(&value, &modq_op.mul(d_el, beta)));
value
}
}
impl<
T: PrimInt
+ ToPrimitive
+ FromPrimitive
+ WrappingSub
+ WrappingAdd
+ NumInfo
+ From<bool>
+ Display
+ Debug,
> Decomposer for DefaultDecomposer<T>
{
type Element = T;
type Iter = DecomposerIter<T>;
fn new(q: T, logb: usize, d: usize) -> DefaultDecomposer<T> {
// if q is power of 2, then `BITS - leading_zeros` outputs logq + 1.
let logq = log2(&q);
assert!(
logq >= (logb * d),
"Decomposer wants logq >= logb*d but got logq={logq}, logb={logb}, d={d}"
);
let ignore_bits = logq - (logb * d);
DefaultDecomposer {
q,
logq,
logb,
b: T::one() << logb,
b_mask: (T::one() << logb) - T::one(),
bby2: T::one() << (logb - 1),
d,
ignore_bits,
}
}
fn decompose_to_vec(&self, value: &T) -> Vec<T> {
let q = self.q;
let logb = self.logb;
let b = T::one() << logb;
let full_mask = b - T::one();
let bby2 = b >> 1;
let mut value = *value;
if value >= (q >> 1) {
value = !(q - value) + T::one()
}
value = round_value(value, self.ignore_bits);
let mut out = Vec::with_capacity(self.d);
for _ in 0..(self.d) {
let k_i = value & full_mask;
value = (value - k_i) >> logb;
if k_i > bby2 || (k_i == bby2 && ((value & T::one()) == T::one())) {
out.push(q - (b - k_i));
value = value + T::one();
} else {
out.push(k_i);
}
}
return out;
}
fn decomposition_count(&self) -> DecompositionCount {
DecompositionCount(self.d)
}
fn decomposition_base(&self) -> DecompostionLogBase {
DecompostionLogBase(self.logb)
}
fn decompose_iter(&self, value: &T) -> DecomposerIter<T> {
let mut value = *value;
if value >= (self.q >> 1) {
value = !(self.q - value) + T::one()
}
value = round_value(value, self.ignore_bits);
DecomposerIter {
value,
q: self.q,
logq: self.logq,
logb: self.logb,
b: self.b,
bby2: self.bby2,
b_mask: self.b_mask,
steps_left: self.d,
}
}
fn gadget_vector(&self) -> Vec<T> {
return gadget_vector(self.logq, self.logb, self.d);
}
}
impl<T: PrimInt> DefaultDecomposer<T> {}
pub struct DecomposerIter<T> {
/// Value to decompose
value: T,
steps_left: usize,
/// (1 << logb) - 1 (for % (1<<logb); i.e. to extract least signiciant logb
/// bits)
b_mask: T,
logb: usize,
// b/2 = 1 << (logb-1)
bby2: T,
/// Ciphertext modulus
q: T,
/// Log of ciphertext modulus
logq: usize,
/// b = 1 << logb
b: T,
}
impl<T: PrimInt + From<bool> + WrappingSub + Display> Iterator for DecomposerIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.steps_left != 0 {
self.steps_left -= 1;
let k_i = self.value & self.b_mask;
self.value = (self.value - k_i) >> self.logb;
// if k_i > self.bby2 || (k_i == self.bby2 && ((self.value &
// T::one()) == T::one())) { self.value = self.value
// + T::one(); Some(self.q + k_i - self.b)
// } else {
// Some(k_i)
// }
// Following is without branching impl of the commented version above. It
// happens to speed up bootstrapping for `SMALL_MP_BOOL_PARAMS` (& other
// parameters as well but I haven't tested) by roughly 15ms.
// Suprisingly the improvement does not show up when I benchmark
// `decomposer_iter` in isolation. Putting this remark here as a
// future task to investiage (TODO).
let carry_bool =
k_i > self.bby2 || (k_i == self.bby2 && ((self.value & T::one()) == T::one()));
let carry = <T as From<bool>>::from(carry_bool);
let neg_carry = (T::zero().wrapping_sub(&carry));
self.value = self.value + carry;
Some((neg_carry & self.q) + k_i - (carry << self.logb))
// Some(
// (self.q & ((carry << self.logq) - (T::one() & carry))) + k_i
// - (carry << self.logb), )
// Some(k_i)
} else {
None
}
}
}
fn round_value<T: PrimInt + WrappingAdd>(value: T, ignore_bits: usize) -> T {
if ignore_bits == 0 {
return value;
}
let ignored_msb = (value & ((T::one() << ignore_bits) - T::one())) >> (ignore_bits - 1);
(value >> ignore_bits).wrapping_add(&ignored_msb)
}
#[cfg(test)]
mod tests {
use itertools::Itertools;
use rand::{thread_rng, Rng};
use crate::{
backend::{ModInit, ModularOpsU64},
decomposer::round_value,
utils::generate_prime,
};
use super::{Decomposer, DefaultDecomposer};
#[test]
fn decomposition_works() {
let ring_size = 1 << 11;
let mut rng = thread_rng();
for logq in [37, 55] {
let logb = 11;
let d = 3;
// let mut stats = vec![Stats::new(); d];
for i in [true, false] {
let q = if i {
generate_prime(logq, 2 * ring_size, 1u64 << logq).unwrap()
} else {
1u64 << logq
};
let decomposer = DefaultDecomposer::new(q, logb, d);
let modq_op = ModularOpsU64::new(q);
for _ in 0..1000000 {
let value = rng.gen_range(0..q);
let limbs = decomposer.decompose_to_vec(&value);
let limbs_from_iter = decomposer.decompose_iter(&value).collect_vec();
assert_eq!(limbs, limbs_from_iter);
let value_back = round_value(
decomposer.recompose(&limbs, &modq_op),
decomposer.ignore_bits,
);
let rounded_value = round_value(value, decomposer.ignore_bits);
assert!((rounded_value as i64 - value_back as i64).abs() <= 1,);
// izip!(stats.iter_mut(), limbs.iter()).for_each(|(s, l)| {
// s.add_more(&vec![q.map_element_to_i64(l)]);
// });
}
}
// stats.iter().enumerate().for_each(|(index, s)| {
// println!(
// "Limb {index} - Mean: {}, Std: {}",
// s.mean(),
// s.std_dev().abs().log2()
// );
// });
}
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/lwe.rs | src/lwe.rs | use std::fmt::Debug;
use itertools::izip;
use num_traits::Zero;
use crate::{
backend::{ArithmeticOps, GetModulus, VectorOps},
decomposer::Decomposer,
random::{RandomFillUniformInModulus, RandomGaussianElementInModulus},
utils::TryConvertFrom1,
Matrix, Row, RowEntity, RowMut,
};
pub(crate) fn lwe_key_switch<
M: Matrix,
Ro: AsMut<[M::MatElement]> + AsRef<[M::MatElement]>,
Op: VectorOps<Element = M::MatElement> + ArithmeticOps<Element = M::MatElement>,
D: Decomposer<Element = M::MatElement>,
>(
lwe_out: &mut Ro,
lwe_in: &Ro,
lwe_ksk: &M,
operator: &Op,
decomposer: &D,
) {
assert!(
lwe_ksk.dimension().0 == ((lwe_in.as_ref().len() - 1) * decomposer.decomposition_count().0)
);
assert!(lwe_out.as_ref().len() == lwe_ksk.dimension().1);
let lwe_in_a_decomposed = lwe_in
.as_ref()
.iter()
.skip(1)
.flat_map(|ai| decomposer.decompose_iter(ai));
izip!(lwe_in_a_decomposed, lwe_ksk.iter_rows()).for_each(|(ai_j, beta_ij_lwe)| {
// let now = std::time::Instant::now();
operator.elwise_fma_scalar_mut(lwe_out.as_mut(), beta_ij_lwe.as_ref(), &ai_j);
// println!("Time elwise_fma_scalar_mut: {:?}", now.elapsed());
});
let out_b = operator.add(&lwe_out.as_ref()[0], &lwe_in.as_ref()[0]);
lwe_out.as_mut()[0] = out_b;
}
pub(crate) fn seeded_lwe_ksk_keygen<
Ro: RowMut + RowEntity,
S,
Op: VectorOps<Element = Ro::Element>
+ ArithmeticOps<Element = Ro::Element>
+ GetModulus<Element = Ro::Element>,
R: RandomGaussianElementInModulus<Ro::Element, Op::M>,
PR: RandomFillUniformInModulus<[Ro::Element], Op::M>,
>(
from_lwe_sk: &[S],
to_lwe_sk: &[S],
gadget: &[Ro::Element],
operator: &Op,
p_rng: &mut PR,
rng: &mut R,
) -> Ro
where
Ro: TryConvertFrom1<[S], Op::M>,
Ro::Element: Zero + Debug,
{
let mut ksk_out = Ro::zeros(from_lwe_sk.len() * gadget.len());
let d = gadget.len();
let modulus = operator.modulus();
let mut neg_sk_in_m = Ro::try_convert_from(from_lwe_sk, modulus);
operator.elwise_neg_mut(neg_sk_in_m.as_mut());
let sk_out_m = Ro::try_convert_from(to_lwe_sk, modulus);
let mut scratch = Ro::zeros(to_lwe_sk.len());
izip!(neg_sk_in_m.as_ref(), ksk_out.as_mut().chunks_mut(d)).for_each(
|(neg_sk_in_si, d_lwes_partb)| {
izip!(gadget.iter(), d_lwes_partb.into_iter()).for_each(|(beta, lwe_b)| {
// sample `a`
RandomFillUniformInModulus::random_fill(p_rng, &modulus, scratch.as_mut());
// a * z
let mut az = Ro::Element::zero();
izip!(scratch.as_ref().iter(), sk_out_m.as_ref()).for_each(|(ai, si)| {
let ai_si = operator.mul(ai, si);
az = operator.add(&az, &ai_si);
});
// a*z + (-s_i)*\beta^j + e
let mut b = operator.add(&az, &operator.mul(beta, neg_sk_in_si));
let e = RandomGaussianElementInModulus::random(rng, &modulus);
b = operator.add(&b, &e);
*lwe_b = b;
})
},
);
ksk_out
}
/// Encrypts encoded message m as LWE ciphertext
pub(crate) fn encrypt_lwe<
Ro: RowMut + RowEntity,
Op: ArithmeticOps<Element = Ro::Element> + GetModulus<Element = Ro::Element>,
R: RandomGaussianElementInModulus<Ro::Element, Op::M>
+ RandomFillUniformInModulus<[Ro::Element], Op::M>,
S,
>(
m: &Ro::Element,
s: &[S],
operator: &Op,
rng: &mut R,
) -> Ro
where
Ro: TryConvertFrom1<[S], Op::M>,
Ro::Element: Zero,
{
let s = Ro::try_convert_from(s, operator.modulus());
let mut lwe_out = Ro::zeros(s.as_ref().len() + 1);
// a*s
RandomFillUniformInModulus::random_fill(rng, operator.modulus(), &mut lwe_out.as_mut()[1..]);
let mut sa = Ro::Element::zero();
izip!(lwe_out.as_mut().iter().skip(1), s.as_ref()).for_each(|(ai, si)| {
let tmp = operator.mul(ai, si);
sa = operator.add(&tmp, &sa);
});
// b = a*s + e + m
let e = RandomGaussianElementInModulus::random(rng, operator.modulus());
let b = operator.add(&operator.add(&sa, &e), m);
lwe_out.as_mut()[0] = b;
lwe_out
}
pub(crate) fn decrypt_lwe<
Ro: Row,
Op: ArithmeticOps<Element = Ro::Element> + GetModulus<Element = Ro::Element>,
S,
>(
lwe_ct: &Ro,
s: &[S],
operator: &Op,
) -> Ro::Element
where
Ro: TryConvertFrom1<[S], Op::M>,
Ro::Element: Zero,
{
let s = Ro::try_convert_from(s, operator.modulus());
let mut sa = Ro::Element::zero();
izip!(lwe_ct.as_ref().iter().skip(1), s.as_ref()).for_each(|(ai, si)| {
let tmp = operator.mul(ai, si);
sa = operator.add(&tmp, &sa);
});
let b = &lwe_ct.as_ref()[0];
operator.sub(b, &sa)
}
#[cfg(test)]
mod tests {
use std::marker::PhantomData;
use itertools::izip;
use crate::{
backend::{ModInit, ModulusPowerOf2},
decomposer::DefaultDecomposer,
random::{DefaultSecureRng, NewWithSeed},
utils::{fill_random_ternary_secret_with_hamming_weight, WithLocal},
MatrixEntity, MatrixMut,
};
use super::*;
const K: usize = 50;
#[derive(Clone)]
struct LweSecret {
pub(crate) values: Vec<i32>,
}
impl LweSecret {
fn random(hw: usize, n: usize) -> LweSecret {
DefaultSecureRng::with_local_mut(|rng| {
let mut out = vec![0i32; n];
fill_random_ternary_secret_with_hamming_weight(&mut out, hw, rng);
LweSecret { values: out }
})
}
fn values(&self) -> &[i32] {
&self.values
}
}
struct LweKeySwitchingKey<M, R> {
data: M,
_phantom: PhantomData<R>,
}
impl<
M: MatrixMut + MatrixEntity,
R: NewWithSeed + RandomFillUniformInModulus<[M::MatElement], M::MatElement>,
> From<&(M::R, R::Seed, usize, M::MatElement)> for LweKeySwitchingKey<M, R>
where
M::R: RowMut,
R::Seed: Clone,
M::MatElement: Copy,
{
fn from(value: &(M::R, R::Seed, usize, M::MatElement)) -> Self {
let data_in = &value.0;
let seed = &value.1;
let to_lwe_n = value.2;
let modulus = value.3;
let mut p_rng = R::new_with_seed(seed.clone());
let mut data = M::zeros(data_in.as_ref().len(), to_lwe_n + 1);
izip!(data_in.as_ref().iter(), data.iter_rows_mut()).for_each(|(bi, lwe_i)| {
RandomFillUniformInModulus::random_fill(
&mut p_rng,
&modulus,
&mut lwe_i.as_mut()[1..],
);
lwe_i.as_mut()[0] = *bi;
});
LweKeySwitchingKey {
data,
_phantom: PhantomData,
}
}
}
#[test]
fn encrypt_decrypt_works() {
let logq = 16;
let q = 1u64 << logq;
let lwe_n = 1024;
let logp = 3;
let modq_op = ModulusPowerOf2::new(q);
let lwe_sk = LweSecret::random(lwe_n >> 1, lwe_n);
let mut rng = DefaultSecureRng::new();
// encrypt
for m in 0..1u64 << logp {
let encoded_m = m << (logq - logp);
let lwe_ct =
encrypt_lwe::<Vec<u64>, _, _, _>(&encoded_m, &lwe_sk.values(), &modq_op, &mut rng);
let encoded_m_back = decrypt_lwe(&lwe_ct, &lwe_sk.values(), &modq_op);
let m_back = ((((encoded_m_back as f64) * ((1 << logp) as f64)) / q as f64).round()
as u64)
% (1u64 << logp);
assert_eq!(m, m_back, "Expected {m} but got {m_back}");
}
}
#[test]
fn key_switch_works() {
let logq = 20;
let logp = 2;
let q = 1u64 << logq;
let lwe_in_n = 2048;
let lwe_out_n = 600;
let d_ks = 5;
let logb = 4;
let lwe_sk_in = LweSecret::random(lwe_in_n >> 1, lwe_in_n);
let lwe_sk_out = LweSecret::random(lwe_out_n >> 1, lwe_out_n);
let mut rng = DefaultSecureRng::new();
let modq_op = ModulusPowerOf2::new(q);
// genrate ksk
for _ in 0..1 {
let mut ksk_seed = [0u8; 32];
rng.fill_bytes(&mut ksk_seed);
let mut p_rng = DefaultSecureRng::new_seeded(ksk_seed);
let decomposer = DefaultDecomposer::new(q, logb, d_ks);
let gadget = decomposer.gadget_vector();
let seeded_ksk = seeded_lwe_ksk_keygen(
&lwe_sk_in.values(),
&lwe_sk_out.values(),
&gadget,
&modq_op,
&mut p_rng,
&mut rng,
);
// println!("{:?}", ksk);
let ksk = LweKeySwitchingKey::<Vec<Vec<u64>>, DefaultSecureRng>::from(&(
seeded_ksk, ksk_seed, lwe_out_n, q,
));
for m in 0..(1 << logp) {
// encrypt using lwe_sk_in
let encoded_m = m << (logq - logp);
let lwe_in_ct = encrypt_lwe(&encoded_m, lwe_sk_in.values(), &modq_op, &mut rng);
// key switch from lwe_sk_in to lwe_sk_out
let mut lwe_out_ct = vec![0u64; lwe_out_n + 1];
let now = std::time::Instant::now();
lwe_key_switch(
&mut lwe_out_ct,
&lwe_in_ct,
&ksk.data,
&modq_op,
&decomposer,
);
println!("Time: {:?}", now.elapsed());
// decrypt lwe_out_ct using lwe_sk_out
// TODO(Jay): Fix me
// let encoded_m_back = decrypt_lwe(&lwe_out_ct,
// &lwe_sk_out.values(), &modq_op); let m_back =
// ((((encoded_m_back as f64) * ((1 << logp) as f64)) / q as
// f64).round() as u64)
// % (1u64 << logp);
// let noise =
// measure_noise_lwe(&lwe_out_ct, lwe_sk_out.values(),
// &modq_op, &encoded_m); println!("Noise:
// {noise}"); assert_eq!(m, m_back, "Expected
// {m} but got {m_back}"); dbg!(m, m_back);
// dbg!(encoded_m, encoded_m_back);
}
}
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/utils.rs | src/utils.rs | use std::{usize, vec};
use itertools::{izip, Itertools};
use num_traits::{One, PrimInt, Signed};
use crate::{
backend::Modulus,
decomposer::NumInfo,
random::{RandomElementInModulus, RandomFill},
Matrix, RowEntity, RowMut,
};
pub trait WithLocal {
fn with_local<F, R>(func: F) -> R
where
F: Fn(&Self) -> R;
fn with_local_mut<F, R>(func: F) -> R
where
F: Fn(&mut Self) -> R;
fn with_local_mut_mut<F, R>(func: &mut F) -> R
where
F: FnMut(&mut Self) -> R;
}
pub trait Global {
fn global() -> &'static Self;
}
pub(crate) trait ShoupMul {
fn representation(value: Self, q: Self) -> Self;
fn mul(a: Self, b: Self, b_shoup: Self, q: Self) -> Self;
}
impl ShoupMul for u64 {
#[inline]
fn representation(value: Self, q: Self) -> Self {
((value as u128 * (1u128 << 64)) / q as u128) as u64
}
#[inline]
/// Returns a * b % q
fn mul(a: Self, b: Self, b_shoup: Self, q: Self) -> Self {
(b.wrapping_mul(a))
.wrapping_sub(q.wrapping_mul(((b_shoup as u128 * a as u128) >> 64) as u64))
}
}
pub(crate) trait ToShoup {
type Modulus;
fn to_shoup(value: &Self, modulus: Self::Modulus) -> Self;
}
impl ToShoup for u64 {
type Modulus = u64;
fn to_shoup(value: &Self, modulus: Self) -> Self {
((*value as u128 * (1u128 << 64)) / modulus as u128) as u64
}
}
impl ToShoup for Vec<Vec<u64>> {
type Modulus = u64;
fn to_shoup(value: &Self, modulus: Self::Modulus) -> Self {
let (row, col) = value.dimension();
let mut shoup_value = vec![vec![0u64; col]; row];
izip!(shoup_value.iter_mut(), value.iter()).for_each(|(shoup_r, r)| {
izip!(shoup_r.iter_mut(), r.iter()).for_each(|(s, e)| {
*s = u64::to_shoup(e, modulus);
})
});
shoup_value
}
}
pub fn fill_random_ternary_secret_with_hamming_weight<
T: Signed,
R: RandomFill<[u8]> + RandomElementInModulus<usize, usize>,
>(
out: &mut [T],
hamming_weight: usize,
rng: &mut R,
) {
let mut bytes = vec![0u8; hamming_weight.div_ceil(8)];
RandomFill::<[u8]>::random_fill(rng, &mut bytes);
let size = out.len();
let mut secret_indices = (0..size).into_iter().map(|i| i).collect_vec();
let mut bit_index = 0;
let mut byte_index = 0;
for i in 0..hamming_weight {
let s_index = RandomElementInModulus::<usize, usize>::random(rng, &secret_indices.len());
let curr_bit = (bytes[byte_index] >> bit_index) & 1;
if curr_bit == 1 {
out[secret_indices[s_index]] = T::one();
} else {
out[secret_indices[s_index]] = -T::one();
}
secret_indices[s_index] = *secret_indices.last().unwrap();
secret_indices.truncate(secret_indices.len() - 1);
if bit_index == 7 {
bit_index = 0;
byte_index += 1;
} else {
bit_index += 1;
}
}
}
// TODO (Jay): this is only a workaround. Add a propoer way to perform primality
// tests.
fn is_probably_prime(candidate: u64) -> bool {
num_bigint_dig::prime::probably_prime(&num_bigint_dig::BigUint::from(candidate), 0)
}
/// Finds prime that satisfy
/// - $prime \lt upper_bound$
/// - $\log{prime} = num_bits$
/// - `prime % modulo == 1`
pub(crate) fn generate_prime(num_bits: usize, modulo: u64, upper_bound: u64) -> Option<u64> {
let leading_zeros = (64 - num_bits) as u32;
let mut tentative_prime = upper_bound - 1;
while tentative_prime % modulo != 1 && tentative_prime.leading_zeros() == leading_zeros {
tentative_prime -= 1;
}
while !is_probably_prime(tentative_prime)
&& tentative_prime.leading_zeros() == leading_zeros
&& tentative_prime >= modulo
{
tentative_prime -= modulo;
}
if is_probably_prime(tentative_prime) && tentative_prime.leading_zeros() == leading_zeros {
Some(tentative_prime)
} else {
None
}
}
/// Returns a^b mod q
pub fn mod_exponent(a: u64, mut b: u64, q: u64) -> u64 {
let mod_mul = |v1: &u64, v2: &u64| {
let tmp = *v1 as u128 * *v2 as u128;
(tmp % q as u128) as u64
};
let mut acc = a;
let mut out = 1;
while b != 0 {
let flag = b & 1;
if flag == 1 {
out = mod_mul(&acc, &out);
}
acc = mod_mul(&acc, &acc);
b >>= 1;
}
out
}
pub(crate) fn mod_inverse(a: u64, q: u64) -> u64 {
mod_exponent(a, q - 2, q)
}
pub(crate) fn negacyclic_mul<T: PrimInt, F: Fn(&T, &T) -> T>(
a: &[T],
b: &[T],
mul: F,
modulus: T,
) -> Vec<T> {
let mut r = vec![T::zero(); a.len()];
for i in 0..a.len() {
for j in 0..i + 1 {
// println!("i: {j} {}", i - j);
r[i] = (r[i] + mul(&a[j], &b[i - j])) % modulus;
}
for j in i + 1..a.len() {
// println!("i: {j} {}", a.len() - j + i);
r[i] = (r[i] + modulus - mul(&a[j], &b[a.len() - j + i])) % modulus;
}
// println!("")
}
return r;
}
/// Returns a polynomial X^{emebedding_factor * si} \mod {Z_Q / X^{N}+1}
pub(crate) fn encode_x_pow_si_with_emebedding_factor<
R: RowEntity + RowMut,
M: Modulus<Element = R::Element>,
>(
si: i32,
embedding_factor: usize,
ring_size: usize,
modulus: &M,
) -> R
where
R::Element: One,
{
assert!((si.abs() as usize) < ring_size);
let mut m = R::zeros(ring_size);
let si = si * (embedding_factor as i32);
if si < 0 {
// X^{-si} = X^{2N-si} = -X^{N-si}, assuming abs(si) < N
m.as_mut()[ring_size - (si.abs() as usize)] = modulus.neg_one();
} else {
m.as_mut()[si as usize] = R::Element::one();
}
m
}
pub(crate) fn puncture_p_rng<S: Default + Copy, R: RandomFill<S>>(
p_rng: &mut R,
times: usize,
) -> S {
let mut out = S::default();
for _ in 0..times {
RandomFill::<S>::random_fill(p_rng, &mut out);
}
return out;
}
pub(crate) fn log2<T: PrimInt + NumInfo>(v: &T) -> usize {
if (*v & (*v - T::one())) == T::zero() {
// value is power of 2
(T::BITS - v.leading_zeros() - 1) as usize
} else {
(T::BITS - v.leading_zeros()) as usize
}
}
pub trait TryConvertFrom1<T: ?Sized, P> {
fn try_convert_from(value: &T, parameters: &P) -> Self;
}
impl<P: Modulus<Element = u64>> TryConvertFrom1<[i64], P> for Vec<u64> {
fn try_convert_from(value: &[i64], parameters: &P) -> Self {
value
.iter()
.map(|v| parameters.map_element_from_i64(*v))
.collect_vec()
}
}
impl<P: Modulus<Element = u64>> TryConvertFrom1<[i32], P> for Vec<u64> {
fn try_convert_from(value: &[i32], parameters: &P) -> Self {
value
.iter()
.map(|v| parameters.map_element_from_i64(*v as i64))
.collect_vec()
}
}
impl<P: Modulus> TryConvertFrom1<[P::Element], P> for Vec<i64> {
fn try_convert_from(value: &[P::Element], parameters: &P) -> Self {
value
.iter()
.map(|v| parameters.map_element_to_i64(v))
.collect_vec()
}
}
#[cfg(test)]
pub(crate) mod tests {
use std::fmt::Debug;
use num_traits::ToPrimitive;
use crate::random::DefaultSecureRng;
use super::fill_random_ternary_secret_with_hamming_weight;
#[derive(Clone)]
pub(crate) struct Stats<T> {
pub(crate) samples: Vec<T>,
}
impl<T> Default for Stats<T> {
fn default() -> Self {
Stats { samples: vec![] }
}
}
impl<T: Copy + ToPrimitive + Debug> Stats<T>
where
// T: for<'a> Sum<&'a T>,
T: for<'a> std::iter::Sum<&'a T> + std::iter::Sum<T>,
{
pub(crate) fn new() -> Self {
Self { samples: vec![] }
}
pub(crate) fn mean(&self) -> f64 {
self.samples.iter().sum::<T>().to_f64().unwrap() / (self.samples.len() as f64)
}
pub(crate) fn variance(&self) -> f64 {
let mean = self.mean();
// diff
let diff_sq = self
.samples
.iter()
.map(|v| {
let t = v.to_f64().unwrap() - mean;
t * t
})
.into_iter()
.sum::<f64>();
diff_sq / (self.samples.len() as f64 - 1.0)
}
pub(crate) fn std_dev(&self) -> f64 {
self.variance().sqrt()
}
pub(crate) fn add_many_samples(&mut self, values: &[T]) {
self.samples.extend(values.iter());
}
pub(crate) fn add_sample(&mut self, value: T) {
self.samples.push(value)
}
pub(crate) fn merge_in(&mut self, other: &Self) {
self.samples.extend(other.samples.iter());
}
}
#[test]
fn ternary_secret_has_correct_hw() {
let mut rng = DefaultSecureRng::new();
for n in 4..15 {
let ring_size = 1 << n;
let mut out = vec![0i32; ring_size];
fill_random_ternary_secret_with_hamming_weight(&mut out, ring_size >> 1, &mut rng);
// check hamming weight of out equals ring_size/2
let mut non_zeros = 0;
out.iter().for_each(|i| {
if *i != 0 {
non_zeros += 1;
}
});
assert_eq!(ring_size >> 1, non_zeros);
}
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/ntt.rs | src/ntt.rs | use itertools::{izip, Itertools};
use rand::{Rng, RngCore, SeedableRng};
use rand_chacha::ChaCha8Rng;
use crate::{
backend::{ArithmeticOps, ModInit, ModularOpsU64, Modulus},
utils::{mod_exponent, mod_inverse, ShoupMul},
};
pub trait NttInit<M> {
/// Ntt istance must be compatible across different instances with same `q`
/// and `n`
fn new(q: &M, n: usize) -> Self;
}
pub trait Ntt {
type Element;
fn forward_lazy(&self, v: &mut [Self::Element]);
fn forward(&self, v: &mut [Self::Element]);
fn backward_lazy(&self, v: &mut [Self::Element]);
fn backward(&self, v: &mut [Self::Element]);
}
/// Forward butterfly routine for Number theoretic transform. Given inputs `x <
/// 4q` and `y < 4q` mutates x and y in place to equal x' and y' where
/// x' = x + wy
/// y' = x - wy
/// and both x' and y' are \in [0, 4q)
///
/// Implements Algorithm 4 of [FASTER ARITHMETIC FOR NUMBER-THEORETIC TRANSFORMS](https://arxiv.org/pdf/1205.2926.pdf)
pub fn forward_butterly_0_to_4q(
mut x: u64,
y: u64,
w: u64,
w_shoup: u64,
q: u64,
q_twice: u64,
) -> (u64, u64) {
debug_assert!(x < q * 4, "{} >= (4q){}", x, 4 * q);
debug_assert!(y < q * 4, "{} >= (4q){}", y, 4 * q);
if x >= q_twice {
x = x - q_twice;
}
let t = ShoupMul::mul(y, w, w_shoup, q);
(x + t, x + q_twice - t)
}
pub fn forward_butterly_0_to_2q(
mut x: u64,
y: u64,
w: u64,
w_shoup: u64,
q: u64,
q_twice: u64,
) -> (u64, u64) {
debug_assert!(x < q * 4, "{} >= (4q){}", x, 4 * q);
debug_assert!(y < q * 4, "{} >= (4q){}", y, 4 * q);
if x >= q_twice {
x = x - q_twice;
}
let t = ShoupMul::mul(y, w, w_shoup, q);
let ox = x.wrapping_add(t);
let oy = x.wrapping_sub(t);
(
(ox).min(ox.wrapping_sub(q_twice)),
oy.min(oy.wrapping_add(q_twice)),
)
}
/// Inverse butterfly routine of Inverse Number theoretic transform. Given
/// inputs `x < 2q` and `y < 2q` mutates x and y to equal x' and y' where
/// x'= x + y
/// y' = w(x - y)
/// and both x' and y' are \in [0, 2q)
///
/// Implements Algorithm 3 of [FASTER ARITHMETIC FOR NUMBER-THEORETIC TRANSFORMS](https://arxiv.org/pdf/1205.2926.pdf)
pub fn inverse_butterfly_0_to_2q(
x: u64,
y: u64,
w_inv: u64,
w_inv_shoup: u64,
q: u64,
q_twice: u64,
) -> (u64, u64) {
debug_assert!(x < q_twice, "{} >= (2q){q_twice}", x);
debug_assert!(y < q_twice, "{} >= (2q){q_twice}", y);
let mut x_dash = x + y;
if x_dash >= q_twice {
x_dash -= q_twice
}
let t = x + q_twice - y;
let y = ShoupMul::mul(t, w_inv, w_inv_shoup, q);
(x_dash, y)
}
/// Number theoretic transform of vector `a` where each element can be in range
/// [0, 2q). Outputs NTT(a) where each element is in range [0,2q)
///
/// Implements Cooley-tukey based forward NTT as given in Algorithm 1 of https://eprint.iacr.org/2016/504.pdf.
pub fn ntt_lazy(a: &mut [u64], psi: &[u64], psi_shoup: &[u64], q: u64, q_twice: u64) {
assert!(a.len() == psi.len());
let n = a.len();
let mut t = n;
let mut m = 1;
while m < n {
t >>= 1;
let w = &psi[m..];
let w_shoup = &psi_shoup[m..];
if t == 1 {
for (a, w, w_shoup) in izip!(a.chunks_mut(2), w.iter(), w_shoup.iter()) {
let (ox, oy) = forward_butterly_0_to_2q(a[0], a[1], *w, *w_shoup, q, q_twice);
a[0] = ox;
a[1] = oy;
}
} else {
for i in 0..m {
let a = &mut a[2 * i * t..(2 * (i + 1) * t)];
let (left, right) = a.split_at_mut(t);
for (x, y) in izip!(left.iter_mut(), right.iter_mut()) {
let (ox, oy) = forward_butterly_0_to_4q(*x, *y, w[i], w_shoup[i], q, q_twice);
*x = ox;
*y = oy;
}
}
}
m <<= 1;
}
}
/// Same as `ntt_lazy` with output in range [0, q)
pub fn ntt(a: &mut [u64], psi: &[u64], psi_shoup: &[u64], q: u64, q_twice: u64) {
assert!(a.len() == psi.len());
let n = a.len();
let mut t = n;
let mut m = 1;
while m < n {
t >>= 1;
let w = &psi[m..];
let w_shoup = &psi_shoup[m..];
if t == 1 {
for (a, w, w_shoup) in izip!(a.chunks_mut(2), w.iter(), w_shoup.iter()) {
let (ox, oy) = forward_butterly_0_to_2q(a[0], a[1], *w, *w_shoup, q, q_twice);
// reduce from range [0, 2q) to [0, q)
a[0] = ox.min(ox.wrapping_sub(q));
a[1] = oy.min(oy.wrapping_sub(q));
}
} else {
for i in 0..m {
let a = &mut a[2 * i * t..(2 * (i + 1) * t)];
let (left, right) = a.split_at_mut(t);
for (x, y) in izip!(left.iter_mut(), right.iter_mut()) {
let (ox, oy) = forward_butterly_0_to_4q(*x, *y, w[i], w_shoup[i], q, q_twice);
*x = ox;
*y = oy;
}
}
}
m <<= 1;
}
}
/// Inverse number theoretic transform of input vector `a` with each element can
/// be in range [0, 2q). Outputs vector INTT(a) with each element in range [0,
/// 2q)
///
/// Implements backward number theorectic transform using GS algorithm as given in Algorithm 2 of https://eprint.iacr.org/2016/504.pdf
pub fn ntt_inv_lazy(
a: &mut [u64],
psi_inv: &[u64],
psi_inv_shoup: &[u64],
n_inv: u64,
n_inv_shoup: u64,
q: u64,
q_twice: u64,
) {
assert!(a.len() == psi_inv.len());
let mut m = a.len() >> 1;
let mut t = 1;
while m > 0 {
if m == 1 {
let (left, right) = a.split_at_mut(t);
for (x, y) in izip!(left.iter_mut(), right.iter_mut()) {
let (ox, oy) =
inverse_butterfly_0_to_2q(*x, *y, psi_inv[1], psi_inv_shoup[1], q, q_twice);
*x = ShoupMul::mul(ox, n_inv, n_inv_shoup, q);
*y = ShoupMul::mul(oy, n_inv, n_inv_shoup, q);
}
} else {
let w_inv = &psi_inv[m..];
let w_inv_shoup = &psi_inv_shoup[m..];
for i in 0..m {
let a = &mut a[2 * i * t..2 * (i + 1) * t];
let (left, right) = a.split_at_mut(t);
for (x, y) in izip!(left.iter_mut(), right.iter_mut()) {
let (ox, oy) =
inverse_butterfly_0_to_2q(*x, *y, w_inv[i], w_inv_shoup[i], q, q_twice);
*x = ox;
*y = oy;
}
}
}
t *= 2;
m >>= 1;
}
}
/// Same as `ntt_inv_lazy` with output in range [0, q)
pub fn ntt_inv(
a: &mut [u64],
psi_inv: &[u64],
psi_inv_shoup: &[u64],
n_inv: u64,
n_inv_shoup: u64,
q: u64,
q_twice: u64,
) {
assert!(a.len() == psi_inv.len());
let mut m = a.len() >> 1;
let mut t = 1;
while m > 0 {
if m == 1 {
let (left, right) = a.split_at_mut(t);
for (x, y) in izip!(left.iter_mut(), right.iter_mut()) {
let (ox, oy) =
inverse_butterfly_0_to_2q(*x, *y, psi_inv[1], psi_inv_shoup[1], q, q_twice);
let ox = ShoupMul::mul(ox, n_inv, n_inv_shoup, q);
let oy = ShoupMul::mul(oy, n_inv, n_inv_shoup, q);
*x = ox.min(ox.wrapping_sub(q));
*y = oy.min(oy.wrapping_sub(q));
}
} else {
let w_inv = &psi_inv[m..];
let w_inv_shoup = &psi_inv_shoup[m..];
for i in 0..m {
let a = &mut a[2 * i * t..2 * (i + 1) * t];
let (left, right) = a.split_at_mut(t);
for (x, y) in izip!(left.iter_mut(), right.iter_mut()) {
let (ox, oy) =
inverse_butterfly_0_to_2q(*x, *y, w_inv[i], w_inv_shoup[i], q, q_twice);
*x = ox;
*y = oy;
}
}
}
t *= 2;
m >>= 1;
}
}
/// Find n^{th} root of unity in field F_q, if one exists
///
/// Note: n^{th} root of unity exists if and only if $q = 1 \mod{n}$
pub(crate) fn find_primitive_root<R: RngCore>(q: u64, n: u64, rng: &mut R) -> Option<u64> {
assert!(n.is_power_of_two(), "{n} is not power of two");
// n^th root of unity only exists if n|(q-1)
assert!(q % n == 1, "{n}^th root of unity in F_{q} does not exists");
let t = (q - 1) / n;
for _ in 0..100 {
let mut omega = rng.gen::<u64>() % q;
// \omega = \omega^t. \omega is now n^th root of unity
omega = mod_exponent(omega, t, q);
// We restrict n to be power of 2. Thus checking whether \omega is primitive
// n^th root of unity is as simple as checking: \omega^{n/2} != 1
if mod_exponent(omega, n >> 1, q) == 1 {
continue;
} else {
return Some(omega);
}
}
None
}
#[derive(Debug)]
pub struct NttBackendU64 {
q: u64,
q_twice: u64,
_n: u64,
n_inv: u64,
n_inv_shoup: u64,
psi_powers_bo: Box<[u64]>,
psi_inv_powers_bo: Box<[u64]>,
psi_powers_bo_shoup: Box<[u64]>,
psi_inv_powers_bo_shoup: Box<[u64]>,
}
impl NttBackendU64 {
fn _new(q: u64, n: usize) -> Self {
// \psi = 2n^{th} primitive root of unity in F_q
let mut rng = ChaCha8Rng::from_seed([0u8; 32]);
let psi = find_primitive_root(q, (n * 2) as u64, &mut rng)
.expect("Unable to find 2n^th root of unity");
let psi_inv = mod_inverse(psi, q);
// assert!(
// ((psi_inv as u128 * psi as u128) % q as u128) == 1,
// "psi:{psi}, psi_inv:{psi_inv}"
// );
let modulus = ModularOpsU64::new(q);
let mut psi_powers = Vec::with_capacity(n as usize);
let mut psi_inv_powers = Vec::with_capacity(n as usize);
let mut running_psi = 1;
let mut running_psi_inv = 1;
for _ in 0..n {
psi_powers.push(running_psi);
psi_inv_powers.push(running_psi_inv);
running_psi = modulus.mul(&running_psi, &psi);
running_psi_inv = modulus.mul(&running_psi_inv, &psi_inv);
}
// powers stored in bit reversed order
let mut psi_powers_bo = vec![0u64; n as usize];
let mut psi_inv_powers_bo = vec![0u64; n as usize];
let shift_by = n.leading_zeros() + 1;
for i in 0..n as usize {
// i in bit reversed order
let bo_index = i.reverse_bits() >> shift_by;
psi_powers_bo[bo_index] = psi_powers[i];
psi_inv_powers_bo[bo_index] = psi_inv_powers[i];
}
// shoup representation
let psi_powers_bo_shoup = psi_powers_bo
.iter()
.map(|v| ShoupMul::representation(*v, q))
.collect_vec();
let psi_inv_powers_bo_shoup = psi_inv_powers_bo
.iter()
.map(|v| ShoupMul::representation(*v, q))
.collect_vec();
// n^{-1} \mod{q}
let n_inv = mod_inverse(n as u64, q);
NttBackendU64 {
q,
q_twice: 2 * q,
_n: n as u64,
n_inv,
n_inv_shoup: ShoupMul::representation(n_inv, q),
psi_powers_bo: psi_powers_bo.into_boxed_slice(),
psi_inv_powers_bo: psi_inv_powers_bo.into_boxed_slice(),
psi_powers_bo_shoup: psi_powers_bo_shoup.into_boxed_slice(),
psi_inv_powers_bo_shoup: psi_inv_powers_bo_shoup.into_boxed_slice(),
}
}
}
impl<M: Modulus<Element = u64>> NttInit<M> for NttBackendU64 {
fn new(q: &M, n: usize) -> Self {
// This NTT does not support native modulus
assert!(!q.is_native());
NttBackendU64::_new(q.q().unwrap(), n)
}
}
impl Ntt for NttBackendU64 {
type Element = u64;
fn forward_lazy(&self, v: &mut [Self::Element]) {
ntt_lazy(
v,
&self.psi_powers_bo,
&self.psi_powers_bo_shoup,
self.q,
self.q_twice,
)
}
fn forward(&self, v: &mut [Self::Element]) {
ntt(
v,
&self.psi_powers_bo,
&self.psi_powers_bo_shoup,
self.q,
self.q_twice,
);
}
fn backward_lazy(&self, v: &mut [Self::Element]) {
ntt_inv_lazy(
v,
&self.psi_inv_powers_bo,
&self.psi_inv_powers_bo_shoup,
self.n_inv,
self.n_inv_shoup,
self.q,
self.q_twice,
)
}
fn backward(&self, v: &mut [Self::Element]) {
ntt_inv(
v,
&self.psi_inv_powers_bo,
&self.psi_inv_powers_bo_shoup,
self.n_inv,
self.n_inv_shoup,
self.q,
self.q_twice,
);
}
}
#[cfg(test)]
mod tests {
use itertools::Itertools;
use rand::{thread_rng, Rng};
use rand_distr::Uniform;
use super::NttBackendU64;
use crate::{
backend::{ModInit, ModularOpsU64, VectorOps},
ntt::Ntt,
utils::{generate_prime, negacyclic_mul},
};
const Q_60_BITS: u64 = 1152921504606748673;
const N: usize = 1 << 4;
const K: usize = 128;
fn random_vec_in_fq(size: usize, q: u64) -> Vec<u64> {
thread_rng()
.sample_iter(Uniform::new(0, q))
.take(size)
.collect_vec()
}
fn assert_output_range(a: &[u64], max_val: u64) {
a.iter()
.for_each(|v| assert!(v <= &max_val, "{v} > {max_val}"));
}
#[test]
fn native_ntt_backend_works() {
// TODO(Jay): Improve tests. Add tests for different primes and ring size.
let ntt_backend = NttBackendU64::_new(Q_60_BITS, N);
for _ in 0..K {
let mut a = random_vec_in_fq(N, Q_60_BITS);
let a_clone = a.clone();
ntt_backend.forward(&mut a);
assert_output_range(a.as_ref(), Q_60_BITS - 1);
assert_ne!(a, a_clone);
ntt_backend.backward(&mut a);
assert_output_range(a.as_ref(), Q_60_BITS - 1);
assert_eq!(a, a_clone);
ntt_backend.forward_lazy(&mut a);
assert_output_range(a.as_ref(), (2 * Q_60_BITS) - 1);
assert_ne!(a, a_clone);
ntt_backend.backward(&mut a);
assert_output_range(a.as_ref(), Q_60_BITS - 1);
assert_eq!(a, a_clone);
ntt_backend.forward(&mut a);
assert_output_range(a.as_ref(), Q_60_BITS - 1);
ntt_backend.backward_lazy(&mut a);
assert_output_range(a.as_ref(), (2 * Q_60_BITS) - 1);
// reduce
a.iter_mut().for_each(|a0| {
if *a0 >= Q_60_BITS {
*a0 -= *a0 - Q_60_BITS;
}
});
assert_eq!(a, a_clone);
}
}
#[test]
fn native_ntt_negacylic_mul() {
let primes = [25, 40, 50, 60]
.iter()
.map(|bits| generate_prime(*bits, (2 * N) as u64, 1u64 << bits).unwrap())
.collect_vec();
for p in primes.into_iter() {
let ntt_backend = NttBackendU64::_new(p, N);
let modulus_backend = ModularOpsU64::new(p);
for _ in 0..K {
let a = random_vec_in_fq(N, p);
let b = random_vec_in_fq(N, p);
let mut a_clone = a.clone();
let mut b_clone = b.clone();
ntt_backend.forward_lazy(&mut a_clone);
ntt_backend.forward_lazy(&mut b_clone);
modulus_backend.elwise_mul_mut(&mut a_clone, &b_clone);
ntt_backend.backward(&mut a_clone);
let mul = |a: &u64, b: &u64| {
let tmp = *a as u128 * *b as u128;
(tmp % p as u128) as u64
};
let expected_out = negacyclic_mul(&a, &b, mul, p);
assert_eq!(a_clone, expected_out);
}
}
}
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/multi_party.rs | src/multi_party.rs | use std::fmt::Debug;
use itertools::izip;
use num_traits::Zero;
use crate::{
backend::{GetModulus, Modulus, VectorOps},
ntt::Ntt,
random::{
RandomFillGaussianInModulus, RandomFillUniformInModulus, RandomGaussianElementInModulus,
},
utils::TryConvertFrom1,
ArithmeticOps, Matrix, MatrixEntity, MatrixMut, Row, RowEntity, RowMut,
};
pub(crate) fn public_key_share<
R: Row + RowMut + RowEntity,
S,
ModOp: VectorOps<Element = R::Element> + GetModulus<Element = R::Element>,
NttOp: Ntt<Element = R::Element>,
Rng: RandomFillGaussianInModulus<[R::Element], ModOp::M>,
PRng: RandomFillUniformInModulus<[R::Element], ModOp::M>,
>(
share_out: &mut R,
s_i: &[S],
modop: &ModOp,
nttop: &NttOp,
p_rng: &mut PRng,
rng: &mut Rng,
) where
R: TryConvertFrom1<[S], ModOp::M>,
{
let ring_size = share_out.as_ref().len();
assert!(s_i.len() == ring_size);
let q = modop.modulus();
// sample a
let mut a = {
let mut a = R::zeros(ring_size);
RandomFillUniformInModulus::random_fill(p_rng, &q, a.as_mut());
a
};
// s*a
nttop.forward(a.as_mut());
let mut s = R::try_convert_from(s_i, &q);
nttop.forward(s.as_mut());
modop.elwise_mul_mut(s.as_mut(), a.as_ref());
nttop.backward(s.as_mut());
RandomFillGaussianInModulus::random_fill(rng, &q, share_out.as_mut());
modop.elwise_add_mut(share_out.as_mut(), s.as_ref()); // s*e + e
}
/// Generate decryption share for LWE ciphertext `lwe_ct` with user's secret `s`
pub(crate) fn multi_party_decryption_share<
R: RowMut + RowEntity,
Mod: Modulus<Element = R::Element>,
ModOp: ArithmeticOps<Element = R::Element> + VectorOps<Element = R::Element> + GetModulus<M = Mod>,
Rng: RandomGaussianElementInModulus<R::Element, Mod>,
S,
>(
lwe_ct: &R,
s: &[S],
mod_op: &ModOp,
rng: &mut Rng,
) -> R::Element
where
R: TryConvertFrom1<[S], Mod>,
R::Element: Zero,
{
assert!(lwe_ct.as_ref().len() == s.len() + 1);
let mut neg_s = R::try_convert_from(s, mod_op.modulus());
mod_op.elwise_neg_mut(neg_s.as_mut());
// share = (\sum -s_i * a_i) + e
let mut share = R::Element::zero();
izip!(neg_s.as_ref().iter(), lwe_ct.as_ref().iter().skip(1)).for_each(|(si, ai)| {
share = mod_op.add(&share, &mod_op.mul(si, ai));
});
let e = rng.random(mod_op.modulus());
share = mod_op.add(&share, &e);
share
}
/// Aggregate decryption shares for `lwe_ct` and return noisy decryption output
/// `m + e`
pub(crate) fn multi_party_aggregate_decryption_shares_and_decrypt<
R: RowMut + RowEntity,
ModOp: ArithmeticOps<Element = R::Element>,
>(
lwe_ct: &R,
shares: &[R::Element],
mod_op: &ModOp,
) -> R::Element
where
R::Element: Zero,
{
let mut sum_shares = R::Element::zero();
shares
.iter()
.for_each(|v| sum_shares = mod_op.add(&sum_shares, v));
mod_op.add(&lwe_ct.as_ref()[0], &sum_shares)
}
pub(crate) fn non_interactive_rgsw_ct<
M: MatrixMut + MatrixEntity,
S,
PRng: RandomFillUniformInModulus<[M::MatElement], ModOp::M>,
Rng: RandomFillGaussianInModulus<[M::MatElement], ModOp::M>,
NttOp: Ntt<Element = M::MatElement>,
ModOp: VectorOps<Element = M::MatElement> + GetModulus<Element = M::MatElement>,
>(
s: &[S],
u: &[S],
m: &[M::MatElement],
gadget_vec: &[M::MatElement],
p_rng: &mut PRng,
rng: &mut Rng,
nttop: &NttOp,
modop: &ModOp,
) -> (M, M)
where
<M as Matrix>::R: RowMut + TryConvertFrom1<[S], ModOp::M> + RowEntity,
M::MatElement: Copy,
{
assert_eq!(s.len(), u.len());
assert_eq!(s.len(), m.len());
let q = modop.modulus();
let d = gadget_vec.len();
let ring_size = s.len();
let mut s_poly_eval = M::R::try_convert_from(s, q);
let mut u_poly_eval = M::R::try_convert_from(u, q);
nttop.forward(s_poly_eval.as_mut());
nttop.forward(u_poly_eval.as_mut());
// encryptions of a_i*u + e + \beta m
let mut enc_beta_m = M::zeros(d, ring_size);
// zero encrypition: a_i*s + e'
let mut zero_encryptions = M::zeros(d, ring_size);
let mut scratch_space = M::R::zeros(ring_size);
izip!(
enc_beta_m.iter_rows_mut(),
zero_encryptions.iter_rows_mut(),
gadget_vec.iter()
)
.for_each(|(e_beta_m, e_zero, beta)| {
// sample a_i
RandomFillUniformInModulus::random_fill(p_rng, q, e_beta_m.as_mut());
e_zero.as_mut().copy_from_slice(e_beta_m.as_ref());
// a_i * u + \beta m + e //
// a_i * u
nttop.forward(e_beta_m.as_mut());
modop.elwise_mul_mut(e_beta_m.as_mut(), u_poly_eval.as_ref());
nttop.backward(e_beta_m.as_mut());
// sample error e
RandomFillGaussianInModulus::random_fill(rng, q, scratch_space.as_mut());
// a_i * u + e
modop.elwise_add_mut(e_beta_m.as_mut(), scratch_space.as_ref());
// beta * m
modop.elwise_scalar_mul(scratch_space.as_mut(), m.as_ref(), beta);
// a_i * u + e + \beta m
modop.elwise_add_mut(e_beta_m.as_mut(), scratch_space.as_ref());
// a_i * s + e //
// a_i * s
nttop.forward(e_zero.as_mut());
modop.elwise_mul_mut(e_zero.as_mut(), s_poly_eval.as_ref());
nttop.backward(e_zero.as_mut());
// sample error e
RandomFillGaussianInModulus::random_fill(rng, q, scratch_space.as_mut());
// a_i * s + e
modop.elwise_add_mut(e_zero.as_mut(), scratch_space.as_ref());
});
(enc_beta_m, zero_encryptions)
}
pub(crate) fn non_interactive_ksk_gen<
M: MatrixMut + MatrixEntity,
S,
PRng: RandomFillUniformInModulus<[M::MatElement], ModOp::M>,
Rng: RandomFillGaussianInModulus<[M::MatElement], ModOp::M>,
NttOp: Ntt<Element = M::MatElement>,
ModOp: VectorOps<Element = M::MatElement> + GetModulus<Element = M::MatElement>,
>(
s: &[S],
u: &[S],
gadget_vec: &[M::MatElement],
p_rng: &mut PRng,
rng: &mut Rng,
nttop: &NttOp,
modop: &ModOp,
) -> M
where
<M as Matrix>::R: RowMut + TryConvertFrom1<[S], ModOp::M> + RowEntity,
M::MatElement: Copy + Debug,
{
assert_eq!(s.len(), u.len());
let q = modop.modulus();
let d = gadget_vec.len();
let ring_size = s.len();
let mut s_poly_eval = M::R::try_convert_from(s, q);
nttop.forward(s_poly_eval.as_mut());
let u_poly = M::R::try_convert_from(u, q);
// a_i * s + \beta u + e
let mut ksk = M::zeros(d, ring_size);
let mut scratch_space = M::R::zeros(ring_size);
izip!(ksk.iter_rows_mut(), gadget_vec.iter()).for_each(|(e_ksk, beta)| {
// sample a_i
RandomFillUniformInModulus::random_fill(p_rng, q, e_ksk.as_mut());
// a_i * s + e + beta u
nttop.forward(e_ksk.as_mut());
modop.elwise_mul_mut(e_ksk.as_mut(), s_poly_eval.as_ref());
nttop.backward(e_ksk.as_mut());
// sample error e
RandomFillGaussianInModulus::random_fill(rng, q, scratch_space.as_mut());
// a_i * s + e
modop.elwise_add_mut(e_ksk.as_mut(), scratch_space.as_ref());
// \beta * u
modop.elwise_scalar_mul(scratch_space.as_mut(), u_poly.as_ref(), beta);
// a_i * s + e + \beta * u
modop.elwise_add_mut(e_ksk.as_mut(), scratch_space.as_ref());
});
ksk
}
pub(crate) fn non_interactive_ksk_zero_encryptions_for_other_party_i<
M: MatrixMut + MatrixEntity,
S,
PRng: RandomFillUniformInModulus<[M::MatElement], ModOp::M>,
Rng: RandomFillGaussianInModulus<[M::MatElement], ModOp::M>,
NttOp: Ntt<Element = M::MatElement>,
ModOp: VectorOps<Element = M::MatElement> + GetModulus<Element = M::MatElement>,
>(
s: &[S],
gadget_vec: &[M::MatElement],
p_rng: &mut PRng,
rng: &mut Rng,
nttop: &NttOp,
modop: &ModOp,
) -> M
where
<M as Matrix>::R: RowMut + TryConvertFrom1<[S], ModOp::M> + RowEntity,
M::MatElement: Copy + Debug,
{
let q = modop.modulus();
let d = gadget_vec.len();
let ring_size = s.len();
let mut s_poly_eval = M::R::try_convert_from(s, q);
nttop.forward(s_poly_eval.as_mut());
// a_i * s + e
let mut zero_encs = M::zeros(d, ring_size);
let mut scratch_space = M::R::zeros(ring_size);
izip!(zero_encs.iter_rows_mut()).for_each(|e_zero| {
// sample a_i
RandomFillUniformInModulus::random_fill(p_rng, q, e_zero.as_mut());
// a_i * s + e
nttop.forward(e_zero.as_mut());
modop.elwise_mul_mut(e_zero.as_mut(), s_poly_eval.as_ref());
nttop.backward(e_zero.as_mut());
// sample error e
RandomFillGaussianInModulus::random_fill(rng, q, scratch_space.as_mut());
modop.elwise_add_mut(e_zero.as_mut(), scratch_space.as_ref());
});
zero_encs
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/main.rs | src/main.rs | fn main() {}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/pbs.rs | src/pbs.rs | use std::fmt::Display;
use num_traits::{FromPrimitive, One, PrimInt, ToPrimitive, Zero};
use crate::{
backend::{ArithmeticOps, Modulus, ShoupMatrixFMA, VectorOps},
decomposer::{Decomposer, RlweDecomposer},
lwe::lwe_key_switch,
ntt::Ntt,
rgsw::{
rlwe_auto_shoup, rlwe_by_rgsw_shoup, RgswCiphertextRef, RlweCiphertextMutRef, RlweKskRef,
RuntimeScratchMutRef,
},
Matrix, MatrixEntity, MatrixMut, RowMut,
};
pub(crate) trait PbsKey {
type RgswCt;
type AutoKey;
type LweKskKey;
/// RGSW ciphertext of LWE secret elements
fn rgsw_ct_lwe_si(&self, si: usize) -> &Self::RgswCt;
/// Key for automorphism with g^k. For -g use k = 0
fn galois_key_for_auto(&self, k: usize) -> &Self::AutoKey;
/// LWE ksk to key switch from RLWE secret to LWE secret
fn lwe_ksk(&self) -> &Self::LweKskKey;
}
pub(crate) trait WithShoupRepr: AsRef<Self::M> {
type M;
fn shoup_repr(&self) -> &Self::M;
}
pub(crate) trait PbsInfo {
/// Type of Matrix
type M: Matrix;
/// Type of Ciphertext modulus
type Modulus: Modulus<Element = <Self::M as Matrix>::MatElement>;
/// Type of Ntt Operator for Ring polynomials
type NttOp: Ntt<Element = <Self::M as Matrix>::MatElement>;
/// Type of Signed Decomposer
type D: Decomposer<Element = <Self::M as Matrix>::MatElement>;
// Although both `RlweModOp` and `LweModOp` types have same bounds, they can be
// different types. For ex, type RlweModOp may only support native modulus,
// where LweModOp may only support prime modulus, etc.
/// Type of RLWE Modulus Operator
type RlweModOp: ArithmeticOps<Element = <Self::M as Matrix>::MatElement>
+ ShoupMatrixFMA<<Self::M as Matrix>::R>;
/// Type of LWE Modulus Operator
type LweModOp: VectorOps<Element = <Self::M as Matrix>::MatElement>
+ ArithmeticOps<Element = <Self::M as Matrix>::MatElement>;
/// RLWE ciphertext modulus
fn rlwe_q(&self) -> &Self::Modulus;
/// LWE ciphertext modulus
fn lwe_q(&self) -> &Self::Modulus;
/// Blind rotation modulus. It is the modulus to which we switch for blind
/// rotation. Since blind rotation decrypts LWE ciphetext in the exponent of
/// ring polynmial (which is a ring mod 2N), `br_q <= 2N`
fn br_q(&self) -> usize;
/// Ring polynomial size `N`
fn rlwe_n(&self) -> usize;
/// LWE dimension `n`
fn lwe_n(&self) -> usize;
/// Embedding fator for ring X^{q}+1 inside
fn embedding_factor(&self) -> usize;
/// Window size parameter LKMC++ blind rotaiton
fn w(&self) -> usize;
/// generator `g` for group Z^*_{br_q}
fn g(&self) -> isize;
/// LWE key switching decomposer
fn lwe_decomposer(&self) -> &Self::D;
/// RLWE x RGSW decoposer
fn rlwe_rgsw_decomposer(&self) -> &(Self::D, Self::D);
/// RLWE auto decomposer
fn auto_decomposer(&self) -> &Self::D;
/// LWE modulus operator
fn modop_lweq(&self) -> &Self::LweModOp;
/// RLWE modulus operator
fn modop_rlweq(&self) -> &Self::RlweModOp;
/// Ntt operators
fn nttop_rlweq(&self) -> &Self::NttOp;
/// Maps a \in Z^*_{br_q} to discrete log k, with generator g (i.e. g^k =
/// a). Returned vector is of size q that stores dlog of `a` at `vec[a]`.
///
/// For any `a`, if k is s.t. `a = g^{k} % br_q`, then `k` is expressed as
/// k. If `k` is s.t `a = -g^{k} % br_q`, then `k` is expressed as
/// k=k+q/4
fn g_k_dlog_map(&self) -> &[usize];
/// Returns auto map and index vector for auto element g^k. For auto element
/// -g set k = 0.
fn rlwe_auto_map(&self, k: usize) -> &(Vec<usize>, Vec<bool>);
}
/// - Mod down
/// - key switching
/// - mod down
/// - blind rotate
pub(crate) fn pbs<
M: MatrixMut + MatrixEntity,
MShoup: WithShoupRepr<M = M>,
P: PbsInfo<M = M>,
K: PbsKey<RgswCt = MShoup, AutoKey = MShoup, LweKskKey = M>,
>(
pbs_info: &P,
test_vec: &M::R,
lwe_in: &mut M::R,
pbs_key: &K,
scratch_lwe_vec: &mut M::R,
scratch_blind_rotate_matrix: &mut M,
) where
<M as Matrix>::R: RowMut,
M::MatElement: PrimInt + FromPrimitive + One + Copy + Zero + Display,
{
let rlwe_q = pbs_info.rlwe_q();
let lwe_q = pbs_info.lwe_q();
let br_q = pbs_info.br_q();
let rlwe_qf64 = rlwe_q.q_as_f64().unwrap();
let lwe_qf64 = lwe_q.q_as_f64().unwrap();
let br_qf64 = br_q.to_f64().unwrap();
let rlwe_n = pbs_info.rlwe_n();
// moddown Q -> Q_ks
lwe_in.as_mut().iter_mut().for_each(|v| {
*v =
M::MatElement::from_f64(((v.to_f64().unwrap() * lwe_qf64) / rlwe_qf64).round()).unwrap()
});
// key switch RLWE secret to LWE secret
// let now = std::time::Instant::now();
scratch_lwe_vec.as_mut().fill(M::MatElement::zero());
lwe_key_switch(
scratch_lwe_vec,
lwe_in,
pbs_key.lwe_ksk(),
pbs_info.modop_lweq(),
pbs_info.lwe_decomposer(),
);
// println!("Time: {:?}", now.elapsed());
// odd moddown Q_ks -> q
let g_k_dlog_map = pbs_info.g_k_dlog_map();
let mut g_k_si = vec![vec![]; br_q >> 1];
scratch_lwe_vec
.as_ref()
.iter()
.skip(1)
.enumerate()
.for_each(|(index, v)| {
let odd_v = mod_switch_odd(v.to_f64().unwrap(), lwe_qf64, br_qf64);
// dlog `k` for `odd_v` is stored as `k` if odd_v = +g^{k}. If odd_v = -g^{k},
// then `k` is stored as `q/4 + k`.
let k = g_k_dlog_map[odd_v];
// assert!(k != 0);
g_k_si[k].push(index);
});
// handle b and set trivial test RLWE
let g = pbs_info.g() as usize;
let g_times_b = (g * mod_switch_odd(
scratch_lwe_vec.as_ref()[0].to_f64().unwrap(),
lwe_qf64,
br_qf64,
)) % (br_q);
// v = (v(X) * X^{g*b}) mod X^{q/2}+1
let br_qby2 = br_q >> 1;
let mut gb_monomial_sign = true;
let mut gb_monomial_exp = g_times_b;
// X^{g*b} mod X^{q/2}+1
if gb_monomial_exp > br_qby2 {
gb_monomial_exp -= br_qby2;
gb_monomial_sign = false
}
// monomial mul
let mut trivial_rlwe_test_poly = M::zeros(2, rlwe_n);
if pbs_info.embedding_factor() == 1 {
monomial_mul(
test_vec.as_ref(),
trivial_rlwe_test_poly.get_row_mut(1).as_mut(),
gb_monomial_exp,
gb_monomial_sign,
br_qby2,
pbs_info.modop_rlweq(),
);
} else {
// use lwe_in to store the `t = v(X) * X^{g*2} mod X^{q/2}+1` temporarily. This
// works because q/2 <= N (where N is lwe_in LWE dimension) always.
monomial_mul(
test_vec.as_ref(),
&mut lwe_in.as_mut()[..br_qby2],
gb_monomial_exp,
gb_monomial_sign,
br_qby2,
pbs_info.modop_rlweq(),
);
// emebed poly `t` in ring X^{q/2}+1 inside the bigger ring X^{N}+1
let embed_factor = pbs_info.embedding_factor();
let partb_trivial_rlwe = trivial_rlwe_test_poly.get_row_mut(1);
lwe_in.as_ref()[..br_qby2]
.iter()
.enumerate()
.for_each(|(index, v)| {
partb_trivial_rlwe[embed_factor * index] = *v;
});
}
// let now = std::time::Instant::now();
// blind rotate
blind_rotation(
&mut trivial_rlwe_test_poly,
scratch_blind_rotate_matrix,
pbs_info.g(),
pbs_info.w(),
br_q,
&g_k_si,
pbs_info.rlwe_rgsw_decomposer(),
pbs_info.auto_decomposer(),
pbs_info.nttop_rlweq(),
pbs_info.modop_rlweq(),
pbs_info,
pbs_key,
);
// println!("Blind rotation time: {:?}", now.elapsed());
// sample extract
sample_extract(lwe_in, &trivial_rlwe_test_poly, pbs_info.modop_rlweq(), 0);
}
/// LMKCY+ Blind rotation
///
/// - gk_to_si: Contains LWE secret index `i` in array of secret indices at k^th
/// index if a_i = g^k if k < q/4 or a_i = -g^k if k > q/4. [g^0, ...,
/// g^{q/2-1}, -g^0, -g^1, .., -g^{q/2-1}]
fn blind_rotation<
Mmut: MatrixMut,
RlweD: RlweDecomposer<Element = Mmut::MatElement>,
AutoD: Decomposer<Element = Mmut::MatElement>,
NttOp: Ntt<Element = Mmut::MatElement>,
ModOp: ArithmeticOps<Element = Mmut::MatElement> + ShoupMatrixFMA<Mmut::R>,
MShoup: WithShoupRepr<M = Mmut>,
K: PbsKey<RgswCt = MShoup, AutoKey = MShoup>,
P: PbsInfo<M = Mmut>,
>(
trivial_rlwe_test_poly: &mut Mmut,
scratch_matrix: &mut Mmut,
_g: isize,
w: usize,
q: usize,
gk_to_si: &[Vec<usize>],
rlwe_rgsw_decomposer: &RlweD,
auto_decomposer: &AutoD,
ntt_op: &NttOp,
mod_op: &ModOp,
parameters: &P,
pbs_key: &K,
) where
<Mmut as Matrix>::R: RowMut,
Mmut::MatElement: Copy + Zero,
{
let mut is_trivial = true;
let mut scratch_matrix = RuntimeScratchMutRef::new(scratch_matrix.as_mut());
let mut rlwe = RlweCiphertextMutRef::new(trivial_rlwe_test_poly.as_mut());
let d_a = rlwe_rgsw_decomposer.a().decomposition_count().0;
let d_b = rlwe_rgsw_decomposer.b().decomposition_count().0;
let d_auto = auto_decomposer.decomposition_count().0;
let q_by_4 = q >> 2;
// let mut count = 0;
// -(g^k)
let mut v = 0;
for i in (1..q_by_4).rev() {
// dbg!(q_by_4 + i);
let s_indices = &gk_to_si[q_by_4 + i];
s_indices.iter().for_each(|s_index| {
// let new = std::time::Instant::now();
let ct = pbs_key.rgsw_ct_lwe_si(*s_index);
rlwe_by_rgsw_shoup(
&mut rlwe,
&RgswCiphertextRef::new(ct.as_ref().as_ref(), d_a, d_b),
&RgswCiphertextRef::new(ct.shoup_repr().as_ref(), d_a, d_b),
&mut scratch_matrix,
rlwe_rgsw_decomposer,
ntt_op,
mod_op,
is_trivial,
);
is_trivial = false;
// println!("Rlwe x Rgsw time: {:?}", new.elapsed());
});
v += 1;
if gk_to_si[q_by_4 + i - 1].len() != 0 || v == w || i == 1 {
let (auto_map_index, auto_map_sign) = parameters.rlwe_auto_map(v);
// let now = std::time::Instant::now();
let auto_key = pbs_key.galois_key_for_auto(v);
rlwe_auto_shoup(
&mut rlwe,
&RlweKskRef::new(auto_key.as_ref().as_ref(), d_auto),
&RlweKskRef::new(auto_key.shoup_repr().as_ref(), d_auto),
&mut scratch_matrix,
&auto_map_index,
&auto_map_sign,
mod_op,
ntt_op,
auto_decomposer,
is_trivial,
);
// println!("Auto time: {:?}", now.elapsed());
// count += 1;
v = 0;
}
}
// -(g^0)
{
gk_to_si[q_by_4].iter().for_each(|s_index| {
let ct = pbs_key.rgsw_ct_lwe_si(*s_index);
rlwe_by_rgsw_shoup(
&mut rlwe,
&RgswCiphertextRef::new(ct.as_ref().as_ref(), d_a, d_b),
&RgswCiphertextRef::new(ct.shoup_repr().as_ref(), d_a, d_b),
&mut scratch_matrix,
rlwe_rgsw_decomposer,
ntt_op,
mod_op,
is_trivial,
);
is_trivial = false;
});
let (auto_map_index, auto_map_sign) = parameters.rlwe_auto_map(0);
let auto_key = pbs_key.galois_key_for_auto(0);
rlwe_auto_shoup(
&mut rlwe,
&RlweKskRef::new(auto_key.as_ref().as_ref(), d_auto),
&RlweKskRef::new(auto_key.shoup_repr().as_ref(), d_auto),
&mut scratch_matrix,
&auto_map_index,
&auto_map_sign,
mod_op,
ntt_op,
auto_decomposer,
is_trivial,
);
// count += 1;
}
// +(g^k)
let mut v = 0;
for i in (1..q_by_4).rev() {
let s_indices = &gk_to_si[i];
s_indices.iter().for_each(|s_index| {
let ct = pbs_key.rgsw_ct_lwe_si(*s_index);
rlwe_by_rgsw_shoup(
&mut rlwe,
&RgswCiphertextRef::new(ct.as_ref().as_ref(), d_a, d_b),
&RgswCiphertextRef::new(ct.shoup_repr().as_ref(), d_a, d_b),
&mut scratch_matrix,
rlwe_rgsw_decomposer,
ntt_op,
mod_op,
is_trivial,
);
is_trivial = false;
});
v += 1;
if gk_to_si[i - 1].len() != 0 || v == w || i == 1 {
let (auto_map_index, auto_map_sign) = parameters.rlwe_auto_map(v);
let auto_key = pbs_key.galois_key_for_auto(v);
rlwe_auto_shoup(
&mut rlwe,
&RlweKskRef::new(auto_key.as_ref().as_ref(), d_auto),
&RlweKskRef::new(auto_key.shoup_repr().as_ref(), d_auto),
&mut scratch_matrix,
&auto_map_index,
&auto_map_sign,
mod_op,
ntt_op,
auto_decomposer,
is_trivial,
);
v = 0;
// count += 1;
}
}
// +(g^0)
gk_to_si[0].iter().for_each(|s_index| {
let ct = pbs_key.rgsw_ct_lwe_si(*s_index);
rlwe_by_rgsw_shoup(
&mut rlwe,
&RgswCiphertextRef::new(ct.as_ref().as_ref(), d_a, d_b),
&RgswCiphertextRef::new(ct.shoup_repr().as_ref(), d_a, d_b),
&mut scratch_matrix,
rlwe_rgsw_decomposer,
ntt_op,
mod_op,
is_trivial,
);
is_trivial = false;
});
// println!("Auto count: {count}");
}
fn mod_switch_odd(v: f64, from_q: f64, to_q: f64) -> usize {
let odd_v = (((v * to_q) / (from_q)).floor()).to_usize().unwrap();
//TODO(Jay): check correctness of this
odd_v + ((odd_v & 1) ^ 1)
}
// TODO(Jay): Add tests for sample extract
pub(crate) fn sample_extract<M: Matrix + MatrixMut, ModOp: ArithmeticOps<Element = M::MatElement>>(
lwe_out: &mut M::R,
rlwe_in: &M,
mod_op: &ModOp,
index: usize,
) where
<M as Matrix>::R: RowMut,
M::MatElement: Copy,
{
let ring_size = rlwe_in.dimension().1;
assert!(ring_size + 1 == lwe_out.as_ref().len());
// index..=0
let to = &mut lwe_out.as_mut()[1..];
let from = rlwe_in.get_row_slice(0);
for i in 0..index + 1 {
to[i] = from[index - i];
}
// -(N..index)
for i in index + 1..ring_size {
to[i] = mod_op.neg(&from[ring_size + index - i]);
}
// set b
lwe_out.as_mut()[0] = *rlwe_in.get(1, index);
}
/// Monomial multiplication (p(X)*X^{mon_exp})
///
/// - p_out: Output is written to p_out and independent of values in p_out
fn monomial_mul<El, ModOp: ArithmeticOps<Element = El>>(
p_in: &[El],
p_out: &mut [El],
mon_exp: usize,
mon_sign: bool,
ring_size: usize,
mod_op: &ModOp,
) where
El: Copy,
{
debug_assert!(p_in.as_ref().len() == ring_size);
debug_assert!(p_in.as_ref().len() == p_out.as_ref().len());
debug_assert!(mon_exp < ring_size);
p_in.as_ref().iter().enumerate().for_each(|(index, v)| {
let mut to_index = index + mon_exp;
let mut to_sign = mon_sign;
if to_index >= ring_size {
to_index = to_index - ring_size;
to_sign = !to_sign;
}
if !to_sign {
p_out.as_mut()[to_index] = mod_op.neg(v);
} else {
p_out.as_mut()[to_index] = *v;
}
});
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/rgsw/keygen.rs | src/rgsw/keygen.rs | use std::{fmt::Debug, ops::Sub};
use itertools::izip;
use num_traits::{PrimInt, Signed, ToPrimitive, Zero};
use crate::{
backend::{ArithmeticOps, GetModulus, Modulus, VectorOps},
ntt::Ntt,
random::{
RandomElementInModulus, RandomFill, RandomFillGaussianInModulus, RandomFillUniformInModulus,
},
utils::{fill_random_ternary_secret_with_hamming_weight, TryConvertFrom1},
Matrix, MatrixEntity, MatrixMut, Row, RowEntity, RowMut,
};
pub(crate) fn generate_auto_map(ring_size: usize, k: isize) -> (Vec<usize>, Vec<bool>) {
assert!(k & 1 == 1, "Auto {k} must be odd");
let k = if k < 0 {
// k is -ve, return k%(2*N)
(2 * ring_size) - (k.abs() as usize % (2 * ring_size))
} else {
k as usize
};
let (auto_map_index, auto_sign_index): (Vec<usize>, Vec<bool>) = (0..ring_size)
.into_iter()
.map(|i| {
let mut to_index = (i * k) % (2 * ring_size);
let mut sign = true;
// wrap around. false implies negative
if to_index >= ring_size {
to_index = to_index - ring_size;
sign = false;
}
(to_index, sign)
})
.unzip();
(auto_map_index, auto_sign_index)
}
/// Returns RGSW(m)
///
/// RGSW = [RLWE'(-sm) || RLWE(m)] = [RLWE'_A(-sm), RLWE'_B(-sm), RLWE'_A(m),
/// RLWE'_B(m)]
///
/// RGSW(m1) ciphertext is used for RLWE(m0) x RGSW(m1) multiplication.
/// Let RLWE(m) = [a, b] where b = as + e + m0.
/// For RLWExRGSW we calculate:
/// (\sum signed_decompose(a)[i] x RLWE(-s \beta^i' m1))
/// + (\sum signed_decompose(b)[i'] x RLWE(\beta^i' m1))
/// = RLWE(m0m1)
/// We denote decomposer count for signed_decompose(a)[i] with d_a and
/// corresponding gadget vector with `gadget_a`. We denote decomposer count for
/// signed_decompose(b)[i] with d_b and corresponding gadget vector with
/// `gadget_b`
///
/// In secret key RGSW encrypton RLWE'_A(m) can be seeded. Hence, we seed it
/// using the `p_rng` passed and the retured RGSW ciphertext has d_a * 2 + d_b
/// rows
///
/// - s: is the secret key
/// - m: message to encrypt
/// - gadget_a: Gadget vector for RLWE'(-sm)
/// - gadget_b: Gadget vector for RLWE'(m)
/// - p_rng: Seeded psuedo random generator used to sample RLWE'_A(m).
pub(crate) fn secret_key_encrypt_rgsw<
Mmut: MatrixMut + MatrixEntity,
S,
R: RandomFillGaussianInModulus<[Mmut::MatElement], ModOp::M>
+ RandomFillUniformInModulus<[Mmut::MatElement], ModOp::M>,
PR: RandomFillUniformInModulus<[Mmut::MatElement], ModOp::M>,
ModOp: VectorOps<Element = Mmut::MatElement> + GetModulus<Element = Mmut::MatElement>,
NttOp: Ntt<Element = Mmut::MatElement>,
>(
out_rgsw: &mut Mmut,
m: &[Mmut::MatElement],
gadget_a: &[Mmut::MatElement],
gadget_b: &[Mmut::MatElement],
s: &[S],
mod_op: &ModOp,
ntt_op: &NttOp,
p_rng: &mut PR,
rng: &mut R,
) where
<Mmut as Matrix>::R: RowMut + RowEntity + TryConvertFrom1<[S], ModOp::M> + Debug,
Mmut::MatElement: Copy + Debug,
{
let d_a = gadget_a.len();
let d_b = gadget_b.len();
let q = mod_op.modulus();
let ring_size = s.len();
assert!(out_rgsw.dimension() == (d_a * 2 + d_b, ring_size));
assert!(m.as_ref().len() == ring_size);
// RLWE(-sm), RLWE(m)
let (rlwe_dash_nsm, b_rlwe_dash_m) = out_rgsw.split_at_row_mut(d_a * 2);
let mut s_eval = Mmut::R::try_convert_from(s, &q);
ntt_op.forward(s_eval.as_mut());
let mut scratch_space = Mmut::R::zeros(ring_size);
// RLWE'(-sm)
let (a_rlwe_dash_nsm, b_rlwe_dash_nsm) = rlwe_dash_nsm.split_at_mut(d_a);
izip!(
a_rlwe_dash_nsm.iter_mut(),
b_rlwe_dash_nsm.iter_mut(),
gadget_a.iter()
)
.for_each(|(ai, bi, beta_i)| {
// Sample a_i
RandomFillUniformInModulus::random_fill(rng, &q, ai.as_mut());
// a_i * s
scratch_space.as_mut().copy_from_slice(ai.as_ref());
ntt_op.forward(scratch_space.as_mut());
mod_op.elwise_mul_mut(scratch_space.as_mut(), s_eval.as_ref());
ntt_op.backward(scratch_space.as_mut());
// b_i = e_i + a_i * s
RandomFillGaussianInModulus::random_fill(rng, &q, bi.as_mut());
mod_op.elwise_add_mut(bi.as_mut(), scratch_space.as_ref());
// a_i + \beta_i * m
mod_op.elwise_scalar_mul(scratch_space.as_mut(), m.as_ref(), beta_i);
mod_op.elwise_add_mut(ai.as_mut(), scratch_space.as_ref());
});
// RLWE(m)
let mut a_rlwe_dash_m = {
// polynomials of part A of RLWE'(m) are sampled from seed
let mut a = Mmut::zeros(d_b, ring_size);
a.iter_rows_mut()
.for_each(|ai| RandomFillUniformInModulus::random_fill(p_rng, &q, ai.as_mut()));
a
};
izip!(
a_rlwe_dash_m.iter_rows_mut(),
b_rlwe_dash_m.iter_mut(),
gadget_b.iter()
)
.for_each(|(ai, bi, beta_i)| {
// ai * s
ntt_op.forward(ai.as_mut());
mod_op.elwise_mul_mut(ai.as_mut(), s_eval.as_ref());
ntt_op.backward(ai.as_mut());
// beta_i * m
mod_op.elwise_scalar_mul(scratch_space.as_mut(), m.as_ref(), beta_i);
// Sample e_i
RandomFillGaussianInModulus::random_fill(rng, &q, bi.as_mut());
// e_i + beta_i * m + ai*s
mod_op.elwise_add_mut(bi.as_mut(), scratch_space.as_ref());
mod_op.elwise_add_mut(bi.as_mut(), ai.as_ref());
});
}
/// Returns RGSW(m) encrypted with public key
///
/// Follows the same routine as `secret_key_encrypt_rgsw` but with the
/// difference that each RLWE encryption uses public key instead of secret key.
///
/// Since public key encryption cannot be seeded `RLWE'_A(m)` is included in the
/// ciphertext. Hence the returned RGSW ciphertext has d_a * 2 + d_b * 2 rows
pub(crate) fn public_key_encrypt_rgsw<
Mmut: MatrixMut + MatrixEntity,
M: Matrix<MatElement = Mmut::MatElement>,
R: RandomFillGaussianInModulus<[Mmut::MatElement], ModOp::M>
+ RandomFill<[u8]>
+ RandomElementInModulus<usize, usize>,
ModOp: VectorOps<Element = Mmut::MatElement> + GetModulus<Element = Mmut::MatElement>,
NttOp: Ntt<Element = Mmut::MatElement>,
>(
out_rgsw: &mut Mmut,
m: &[M::MatElement],
public_key: &M,
gadget_a: &[Mmut::MatElement],
gadget_b: &[Mmut::MatElement],
mod_op: &ModOp,
ntt_op: &NttOp,
rng: &mut R,
) where
<Mmut as Matrix>::R: RowMut + RowEntity + TryConvertFrom1<[i32], ModOp::M>,
Mmut::MatElement: Copy,
{
let ring_size = public_key.dimension().1;
let d_a = gadget_a.len();
let d_b = gadget_b.len();
assert!(public_key.dimension().0 == 2);
assert!(out_rgsw.dimension() == (d_a * 2 + d_b * 2, ring_size));
let mut pk_eval = Mmut::zeros(2, ring_size);
izip!(pk_eval.iter_rows_mut(), public_key.iter_rows()).for_each(|(to_i, from_i)| {
to_i.as_mut().copy_from_slice(from_i.as_ref());
ntt_op.forward(to_i.as_mut());
});
let p0 = pk_eval.get_row_slice(0);
let p1 = pk_eval.get_row_slice(1);
let q = mod_op.modulus();
// RGSW(m) = RLWE'(-sm), RLWE(m)
let (rlwe_dash_nsm, rlwe_dash_m) = out_rgsw.split_at_row_mut(d_a * 2);
// RLWE(-sm)
let (rlwe_dash_nsm_parta, rlwe_dash_nsm_partb) = rlwe_dash_nsm.split_at_mut(d_a);
izip!(
rlwe_dash_nsm_parta.iter_mut(),
rlwe_dash_nsm_partb.iter_mut(),
gadget_a.iter()
)
.for_each(|(ai, bi, beta_i)| {
// sample ephemeral secret u_i
let mut u = vec![0i32; ring_size];
fill_random_ternary_secret_with_hamming_weight(u.as_mut(), ring_size >> 1, rng);
let mut u_eval = Mmut::R::try_convert_from(u.as_ref(), &q);
ntt_op.forward(u_eval.as_mut());
let mut u_eval_copy = Mmut::R::zeros(ring_size);
u_eval_copy.as_mut().copy_from_slice(u_eval.as_ref());
// p0 * u
mod_op.elwise_mul_mut(u_eval.as_mut(), p0.as_ref());
// p1 * u
mod_op.elwise_mul_mut(u_eval_copy.as_mut(), p1.as_ref());
ntt_op.backward(u_eval.as_mut());
ntt_op.backward(u_eval_copy.as_mut());
// sample error
RandomFillGaussianInModulus::random_fill(rng, &q, ai.as_mut());
RandomFillGaussianInModulus::random_fill(rng, &q, bi.as_mut());
// a = p0*u+e0
mod_op.elwise_add_mut(ai.as_mut(), u_eval.as_ref());
// b = p1*u+e1
mod_op.elwise_add_mut(bi.as_mut(), u_eval_copy.as_ref());
// a = p0*u + e0 + \beta*m
// use u_eval as scratch
mod_op.elwise_scalar_mul(u_eval.as_mut(), m.as_ref(), beta_i);
mod_op.elwise_add_mut(ai.as_mut(), u_eval.as_ref());
});
// RLWE(m)
let (rlwe_dash_m_parta, rlwe_dash_m_partb) = rlwe_dash_m.split_at_mut(d_b);
izip!(
rlwe_dash_m_parta.iter_mut(),
rlwe_dash_m_partb.iter_mut(),
gadget_b.iter()
)
.for_each(|(ai, bi, beta_i)| {
// sample ephemeral secret u_i
let mut u = vec![0i32; ring_size];
fill_random_ternary_secret_with_hamming_weight(u.as_mut(), ring_size >> 1, rng);
let mut u_eval = Mmut::R::try_convert_from(u.as_ref(), &q);
ntt_op.forward(u_eval.as_mut());
let mut u_eval_copy = Mmut::R::zeros(ring_size);
u_eval_copy.as_mut().copy_from_slice(u_eval.as_ref());
// p0 * u
mod_op.elwise_mul_mut(u_eval.as_mut(), p0.as_ref());
// p1 * u
mod_op.elwise_mul_mut(u_eval_copy.as_mut(), p1.as_ref());
ntt_op.backward(u_eval.as_mut());
ntt_op.backward(u_eval_copy.as_mut());
// sample error
RandomFillGaussianInModulus::random_fill(rng, &q, ai.as_mut());
RandomFillGaussianInModulus::random_fill(rng, &q, bi.as_mut());
// a = p0*u+e0
mod_op.elwise_add_mut(ai.as_mut(), u_eval.as_ref());
// b = p1*u+e1
mod_op.elwise_add_mut(bi.as_mut(), u_eval_copy.as_ref());
// b = p1*u + e0 + \beta*m
// use u_eval as scratch
mod_op.elwise_scalar_mul(u_eval.as_mut(), m.as_ref(), beta_i);
mod_op.elwise_add_mut(bi.as_mut(), u_eval.as_ref());
});
}
/// Returns key switching key to key switch ciphertext RLWE_{from_s}(m)
/// to RLWE_{to_s}(m).
///
/// Let key switching decomposer have `d` decompostion count with gadget vector:
/// [1, \beta, ..., \beta^d-1]
///
/// Key switching key consists of `d` RLWE ciphertexts:
/// RLWE'_{to_s}(-from_s) = [RLWE_{to_s}(\beta^i -from_s)]
///
/// In RLWE(m) s.t. b = as + e + m where s is the secret key, `a` can be seeded.
/// And we seed all RLWE ciphertexts in key switchin key.
///
/// - neg_from_s: Negative of secret polynomial to key switch from (i.e.
/// -from_s)
/// - to_s: secret polynomial to key switch to.
/// - gadget_vector: Gadget vector of decomposer used in key switch
/// - p_rng: Seeded pseudo random generate used to generate `a` polynomials of
/// key switching key RLWE ciphertexts
fn seeded_rlwe_ksk_gen<
Mmut: MatrixMut + MatrixEntity,
ModOp: ArithmeticOps<Element = Mmut::MatElement>
+ VectorOps<Element = Mmut::MatElement>
+ GetModulus<Element = Mmut::MatElement>,
NttOp: Ntt<Element = Mmut::MatElement>,
R: RandomFillGaussianInModulus<[Mmut::MatElement], ModOp::M>,
PR: RandomFillUniformInModulus<[Mmut::MatElement], ModOp::M>,
>(
ksk_out: &mut Mmut,
neg_from_s: Mmut::R,
mut to_s: Mmut::R,
gadget_vector: &[Mmut::MatElement],
mod_op: &ModOp,
ntt_op: &NttOp,
p_rng: &mut PR,
rng: &mut R,
) where
<Mmut as Matrix>::R: RowMut,
{
let ring_size = neg_from_s.as_ref().len();
let d = gadget_vector.len();
assert!(ksk_out.dimension() == (d, ring_size));
let q = mod_op.modulus();
ntt_op.forward(to_s.as_mut());
// RLWE'_{to_s}(-from_s)
let mut part_a = {
let mut a = Mmut::zeros(d, ring_size);
a.iter_rows_mut()
.for_each(|ai| RandomFillUniformInModulus::random_fill(p_rng, q, ai.as_mut()));
a
};
izip!(
part_a.iter_rows_mut(),
ksk_out.iter_rows_mut(),
gadget_vector.iter(),
)
.for_each(|(ai, bi, beta_i)| {
// si * ai
ntt_op.forward(ai.as_mut());
mod_op.elwise_mul_mut(ai.as_mut(), to_s.as_ref());
ntt_op.backward(ai.as_mut());
// ei + to_s*ai
RandomFillGaussianInModulus::random_fill(rng, &q, bi.as_mut());
mod_op.elwise_add_mut(bi.as_mut(), ai.as_ref());
// beta_i * -from_s
// use ai as scratch space
mod_op.elwise_scalar_mul(ai.as_mut(), neg_from_s.as_ref(), beta_i);
// bi = ei + to_s*ai + beta_i*-from_s
mod_op.elwise_add_mut(bi.as_mut(), ai.as_ref());
});
}
/// Returns auto key to send RLWE(m(X)) -> RLWE(m(X^k))
///
/// Auto key is key switchin key that key-switches RLWE_{s(X^k)}(m(X^k)) to
/// RLWE_{s(X)}(m(X^k)).
///
/// - s: secret polynomial s(X)
/// - auto_k: k used in for autmorphism X -> X^k
/// - gadget_vector: Gadget vector corresponding to decomposer used in key
/// switch
/// - p_rng: pseudo random generator used to generate `a` polynomials of key
/// switching key RLWE ciphertexts
pub(crate) fn seeded_auto_key_gen<
Mmut: MatrixMut + MatrixEntity,
ModOp: ArithmeticOps<Element = Mmut::MatElement>
+ VectorOps<Element = Mmut::MatElement>
+ GetModulus<Element = Mmut::MatElement>,
NttOp: Ntt<Element = Mmut::MatElement>,
S,
R: RandomFillGaussianInModulus<[Mmut::MatElement], ModOp::M>,
PR: RandomFillUniformInModulus<[Mmut::MatElement], ModOp::M>,
>(
ksk_out: &mut Mmut,
s: &[S],
auto_k: isize,
gadget_vector: &[Mmut::MatElement],
mod_op: &ModOp,
ntt_op: &NttOp,
p_rng: &mut PR,
rng: &mut R,
) where
<Mmut as Matrix>::R: RowMut,
Mmut::R: TryConvertFrom1<[S], ModOp::M> + RowEntity,
Mmut::MatElement: Copy + Sub<Output = Mmut::MatElement>,
{
let ring_size = s.len();
let (auto_map_index, auto_map_sign) = generate_auto_map(ring_size, auto_k);
let q = mod_op.modulus();
// s(X) -> -s(X^k)
let s = Mmut::R::try_convert_from(s, q);
let mut neg_s_auto = Mmut::R::zeros(s.as_ref().len());
izip!(s.as_ref(), auto_map_index.iter(), auto_map_sign.iter()).for_each(
|(el, to_index, sign)| {
// if sign is +ve (true), then negate because we need -s(X) (i.e. do the
// opposite than the usual case)
if *sign {
neg_s_auto.as_mut()[*to_index] = mod_op.neg(el);
} else {
neg_s_auto.as_mut()[*to_index] = *el;
}
},
);
// Ksk from -s(X^k) to s(X)
seeded_rlwe_ksk_gen(
ksk_out,
neg_s_auto,
s,
gadget_vector,
mod_op,
ntt_op,
p_rng,
rng,
);
}
/// Returns seeded RLWE(m(X))
///
/// RLWE(m(X)) = [a(X), b(X) = a(X)s(X) + e(X) + m(X)]
///
/// a(X) of RLWE encyrptions using secret key s(X) can be seeded. We use seeded
/// pseudo random generator `p_rng` to sample a(X) and return seeded RLWE
/// ciphertext (i.e. only b(X))
pub(crate) fn seeded_secret_key_encrypt_rlwe<
Ro: Row + RowMut + RowEntity,
ModOp: VectorOps<Element = Ro::Element> + GetModulus<Element = Ro::Element>,
NttOp: Ntt<Element = Ro::Element>,
S,
R: RandomFillGaussianInModulus<[Ro::Element], ModOp::M>,
PR: RandomFillUniformInModulus<[Ro::Element], ModOp::M>,
>(
m: &[Ro::Element],
b_rlwe_out: &mut Ro,
s: &[S],
mod_op: &ModOp,
ntt_op: &NttOp,
p_rng: &mut PR,
rng: &mut R,
) where
Ro: TryConvertFrom1<[S], ModOp::M> + Debug,
{
let ring_size = s.len();
assert!(m.as_ref().len() == ring_size);
assert!(b_rlwe_out.as_ref().len() == ring_size);
let q = mod_op.modulus();
// sample a
let mut a = {
let mut a = Ro::zeros(ring_size);
RandomFillUniformInModulus::random_fill(p_rng, q, a.as_mut());
a
};
// s * a
let mut sa = Ro::try_convert_from(s, q);
ntt_op.forward(sa.as_mut());
ntt_op.forward(a.as_mut());
mod_op.elwise_mul_mut(sa.as_mut(), a.as_ref());
ntt_op.backward(sa.as_mut());
// sample e
RandomFillGaussianInModulus::random_fill(rng, q, b_rlwe_out.as_mut());
mod_op.elwise_add_mut(b_rlwe_out.as_mut(), m.as_ref());
mod_op.elwise_add_mut(b_rlwe_out.as_mut(), sa.as_ref());
}
/// Returns RLWE(m(X)) encrypted using public key.
///
/// Unlike secret key encryption, public key encryption cannot be seeded
pub(crate) fn public_key_encrypt_rlwe<
M: Matrix,
Mmut: MatrixMut<MatElement = M::MatElement>,
ModOp: VectorOps<Element = M::MatElement> + GetModulus<Element = M::MatElement>,
NttOp: Ntt<Element = M::MatElement>,
S,
R: RandomFillGaussianInModulus<[M::MatElement], ModOp::M>
+ RandomFillUniformInModulus<[M::MatElement], ModOp::M>
+ RandomFill<[u8]>
+ RandomElementInModulus<usize, usize>,
>(
rlwe_out: &mut Mmut,
pk: &M,
m: &[M::MatElement],
mod_op: &ModOp,
ntt_op: &NttOp,
rng: &mut R,
) where
<Mmut as Matrix>::R: RowMut + TryConvertFrom1<[S], ModOp::M> + RowEntity,
M::MatElement: Copy,
S: Zero + Signed + Copy,
{
let ring_size = m.len();
assert!(rlwe_out.dimension() == (2, ring_size));
let q = mod_op.modulus();
let mut u = vec![S::zero(); ring_size];
fill_random_ternary_secret_with_hamming_weight(u.as_mut(), ring_size >> 1, rng);
let mut u = Mmut::R::try_convert_from(&u, q);
ntt_op.forward(u.as_mut());
let mut ua = Mmut::R::zeros(ring_size);
ua.as_mut().copy_from_slice(pk.get_row_slice(0));
let mut ub = Mmut::R::zeros(ring_size);
ub.as_mut().copy_from_slice(pk.get_row_slice(1));
// a*u
ntt_op.forward(ua.as_mut());
mod_op.elwise_mul_mut(ua.as_mut(), u.as_ref());
ntt_op.backward(ua.as_mut());
// b*u
ntt_op.forward(ub.as_mut());
mod_op.elwise_mul_mut(ub.as_mut(), u.as_ref());
ntt_op.backward(ub.as_mut());
// sample error
rlwe_out.iter_rows_mut().for_each(|ri| {
RandomFillGaussianInModulus::random_fill(rng, &q, ri.as_mut());
});
// a*u + e0
mod_op.elwise_add_mut(rlwe_out.get_row_mut(0), ua.as_ref());
// b*u + e1
mod_op.elwise_add_mut(rlwe_out.get_row_mut(1), ub.as_ref());
// b*u + e1 + m
mod_op.elwise_add_mut(rlwe_out.get_row_mut(1), m);
}
/// Returns RLWE public key generated using RLWE secret key
pub(crate) fn rlwe_public_key<
Ro: RowMut + RowEntity,
S,
ModOp: VectorOps<Element = Ro::Element> + GetModulus<Element = Ro::Element>,
NttOp: Ntt<Element = Ro::Element>,
PRng: RandomFillUniformInModulus<[Ro::Element], ModOp::M>,
Rng: RandomFillGaussianInModulus<[Ro::Element], ModOp::M>,
>(
part_b_out: &mut Ro,
s: &[S],
ntt_op: &NttOp,
mod_op: &ModOp,
p_rng: &mut PRng,
rng: &mut Rng,
) where
Ro: TryConvertFrom1<[S], ModOp::M>,
{
let ring_size = s.len();
assert!(part_b_out.as_ref().len() == ring_size);
let q = mod_op.modulus();
// sample a
let mut a = {
let mut tmp = Ro::zeros(ring_size);
RandomFillUniformInModulus::random_fill(p_rng, &q, tmp.as_mut());
tmp
};
ntt_op.forward(a.as_mut());
// s*a
let mut sa = Ro::try_convert_from(s, &q);
ntt_op.forward(sa.as_mut());
mod_op.elwise_mul_mut(sa.as_mut(), a.as_ref());
ntt_op.backward(sa.as_mut());
// s*a + e
RandomFillGaussianInModulus::random_fill(rng, &q, part_b_out.as_mut());
mod_op.elwise_add_mut(part_b_out.as_mut(), sa.as_ref());
}
/// Decrypts ciphertext RLWE(m) and returns noisy m
///
/// We assume RLWE(m) = [a, b] is a degree 1 ciphertext s.t. b - sa = e + m
pub(crate) fn decrypt_rlwe<
R: RowMut,
M: Matrix<MatElement = R::Element>,
ModOp: VectorOps<Element = R::Element> + GetModulus<Element = R::Element>,
NttOp: Ntt<Element = R::Element>,
S,
>(
rlwe_ct: &M,
s: &[S],
m_out: &mut R,
ntt_op: &NttOp,
mod_op: &ModOp,
) where
R: TryConvertFrom1<[S], ModOp::M>,
R::Element: Copy,
{
let ring_size = s.len();
assert!(rlwe_ct.dimension() == (2, ring_size));
assert!(m_out.as_ref().len() == ring_size);
// transform a to evluation form
m_out.as_mut().copy_from_slice(rlwe_ct.get_row_slice(0));
ntt_op.forward(m_out.as_mut());
// -s*a
let mut s = R::try_convert_from(&s, mod_op.modulus());
ntt_op.forward(s.as_mut());
mod_op.elwise_mul_mut(m_out.as_mut(), s.as_ref());
mod_op.elwise_neg_mut(m_out.as_mut());
ntt_op.backward(m_out.as_mut());
// m+e = b - s*a
mod_op.elwise_add_mut(m_out.as_mut(), rlwe_ct.get_row_slice(1));
}
// Measures maximum noise in degree 1 RLWE ciphertext against message `want_m`
fn measure_max_noise<
Mmut: MatrixMut + Matrix,
ModOp: VectorOps<Element = Mmut::MatElement> + GetModulus<Element = Mmut::MatElement>,
NttOp: Ntt<Element = Mmut::MatElement>,
S,
>(
rlwe_ct: &Mmut,
want_m: &Mmut::R,
ntt_op: &NttOp,
mod_op: &ModOp,
s: &[S],
) -> f64
where
<Mmut as Matrix>::R: RowMut,
Mmut::R: RowEntity + TryConvertFrom1<[S], ModOp::M>,
Mmut::MatElement: PrimInt + ToPrimitive + Debug,
{
let ring_size = s.len();
assert!(rlwe_ct.dimension() == (2, ring_size));
assert!(want_m.as_ref().len() == ring_size);
// -(s * a)
let q = mod_op.modulus();
let mut s = Mmut::R::try_convert_from(s, &q);
ntt_op.forward(s.as_mut());
let mut a = Mmut::R::zeros(ring_size);
a.as_mut().copy_from_slice(rlwe_ct.get_row_slice(0));
ntt_op.forward(a.as_mut());
mod_op.elwise_mul_mut(s.as_mut(), a.as_ref());
mod_op.elwise_neg_mut(s.as_mut());
ntt_op.backward(s.as_mut());
// m+e = b - s*a
let mut m_plus_e = s;
mod_op.elwise_add_mut(m_plus_e.as_mut(), rlwe_ct.get_row_slice(1));
// difference
mod_op.elwise_sub_mut(m_plus_e.as_mut(), want_m.as_ref());
let mut max_diff_bits = f64::MIN;
m_plus_e.as_ref().iter().for_each(|v| {
let bits = (q.map_element_to_i64(v).to_f64().unwrap().abs()).log2();
if max_diff_bits < bits {
max_diff_bits = bits;
}
});
return max_diff_bits;
}
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | false |
phantomzone-org/phantom-zone | https://github.com/phantomzone-org/phantom-zone/blob/a8e6c276273bbe2cb7f2508ba07d1d192a467c13/src/rgsw/runtime.rs | src/rgsw/runtime.rs | use itertools::izip;
use num_traits::Zero;
use crate::{
backend::{ArithmeticOps, GetModulus, ShoupMatrixFMA, VectorOps},
decomposer::{Decomposer, RlweDecomposer},
ntt::Ntt,
parameters::{DecompositionCount, DoubleDecomposerParams, SingleDecomposerParams},
Matrix, MatrixEntity, MatrixMut, Row, RowEntity, RowMut,
};
/// Degree 1 RLWE ciphertext.
///
/// RLWE(m) = [a, b] s.t. m+e = b - as
pub(crate) trait RlweCiphertext {
type R: RowMut;
/// Returns polynomial `a` of RLWE ciphertext as slice of elements
fn part_a(&self) -> &[<Self::R as Row>::Element];
/// Returns polynomial `a` of RLWE ciphertext as mutable slice of elements
fn part_a_mut(&mut self) -> &mut [<Self::R as Row>::Element];
/// Returns polynomial `b` of RLWE ciphertext as slice of elements
fn part_b(&self) -> &[<Self::R as Row>::Element];
/// Returns polynomial `b` of RLWE ciphertext as mut slice of elements
fn part_b_mut(&mut self) -> &mut [<Self::R as Row>::Element];
/// Returns ring size of polynomials
fn ring_size(&self) -> usize;
}
/// RGSW ciphertext
///
/// RGSW is a collection of RLWE' ciphertext which are collection degree 1 of
/// RLWE ciphertexts
///
/// RGSW = [RLWE'(-sm) || RLWE'(m)]
///
/// As usual we refer to decomposition count for RLWE_A in RLWE x RGSW
/// multiplicaiton as `d_a` and decomposition count for RLWE_B in RLWE x RGDW
/// multiplication as `d_b`.
pub(crate) trait RgswCiphertext {
type R: Row;
/// Splits RGSW ciphertext and returns references:
/// (RLWE'_A(-sm), RLWE'_B(-sm)), (RLWE'_A(m), RLWE'_B(m))
fn split(&self) -> ((&[Self::R], &[Self::R]), (&[Self::R], &[Self::R]));
}
pub(crate) trait RgswCiphertextMut: RgswCiphertext {
/// Splits RGSW ciphertext and returns mutable references:
/// (RLWE'_A(-sm), RLWE'_B(-sm)), (RLWE'_A(m), RLWE'_B(m))
fn split_mut(
&mut self,
) -> (
(&mut [Self::R], &mut [Self::R]),
(&mut [Self::R], &mut [Self::R]),
);
}
/// RLWE Key switching Key
///
/// Key switching key from s' -> s consists of multiple RLWE cipheretxts.
/// For gadget vector: [1, beta, ..., beta^{d-1}]
/// RLWE'_{s}(-s'm) = [RWLE_{s}(-s'm), ..., RLWE_{s}(beta^{d-1} -s'm)]
pub(crate) trait RlweKsk {
type R: Row;
/// Returns reference to RLWE'_A(-s'm) polynomials
fn ksk_part_a(&self) -> &[Self::R];
/// Returns reference to RLWE'_B(-s'm) polynomials
fn ksk_part_b(&self) -> &[Self::R];
}
/// Scratch matrix used in several rlwe/rgsw runtime operations
pub(crate) trait RuntimeScratchMatrix {
type R: RowMut;
type Rgsw: RgswCiphertext;
/// Returns scratch matrix for RLWE automorphism (not trivial case)
///
/// RLWE auto requires scratch matric to store decomposed polynomials + 1
/// rlwe ciphertext temporarily.
///
/// For example, if Auto decomposer has decompostion count `d` then the
/// scratch matrix must have dimension (d + 2, N) where N is the ring size.
fn scratch_for_rlwe_auto_and_zero_rlwe_space(
&mut self,
decompostion_count: usize,
) -> (&mut [Self::R], &mut [Self::R]);
/// Returns scratch matrix for RLWE automorphism (trivial case)
///
/// We refer to cases where RLWE(m) = [0, b] s.t. m = b as trivial cases. In
/// such a case a single row of length N, N being the ring dimension, is
/// required as scratch buffer to store automorphism of polynomial `b`
/// temporarily.
fn scratch_for_rlwe_auto_trivial_case(&mut self) -> &mut Self::R;
/// Returns scratch matrix + zeroed RLWE ciphertext space for
/// RLWE x RGSW
///
/// RLWE x RGSW product requires scratch space to store decomposed
/// polynomials for both cases: (1) SignedDecompose(RLWE_A) x RLWE'(-sm) and
/// (2) SignedDecompose(RLWE_B) x RLWE'(m). Hence, scratch space returned to
/// store decomposed polynomials must have MAX(d_a, d_b) rows.
///
/// Additional scratch space is required to store 1 RLWE ciphertext
/// temporarily. The space must be zeroed.
fn scratch_for_rlwe_x_rgsw_and_zero_rlwe_space<D: RlweDecomposer>(
&mut self,
decomposer: &D,
) -> (&mut [Self::R], &mut [Self::R]);
/// Returns scracth matrix + zeroed RGSW ciphertext space for RGSW0 x RGSW1
///
/// RGSW0 x RGSW1 requires `d_{0,a} + d_{0,b}` RLWE x RGSW1 products where
/// d_{0, a/b} are decomposition counts corresponding to decmposer used for
/// RGSW0. Hence, scratch space required to store decomposed polynomial for
/// RLWE x RGSW1 product should have MAX(d_{1, a}, d_{1, b}) rows.
///
/// Additional scravth space is required to store RGSW0 ciphertext
/// temporarily. The space must be zeroed.
fn scratch_for_rgsw_x_rgsw_and_zero_rgsw0_space<D: RlweDecomposer>(
&mut self,
d0: &D,
d1: &D,
) -> (&mut [Self::R], &mut [Self::R]);
}
pub(crate) struct RlweCiphertextMutRef<'a, R> {
data: &'a mut [R],
}
impl<'a, R> RlweCiphertextMutRef<'a, R> {
pub(crate) fn new(data: &'a mut [R]) -> Self {
Self { data }
}
}
impl<'a, R: RowMut> RlweCiphertext for RlweCiphertextMutRef<'a, R> {
type R = R;
fn part_a(&self) -> &[<Self::R as Row>::Element] {
self.data[0].as_ref()
}
fn part_a_mut(&mut self) -> &mut [<Self::R as Row>::Element] {
self.data[0].as_mut()
}
fn part_b(&self) -> &[<Self::R as Row>::Element] {
self.data[1].as_ref()
}
fn part_b_mut(&mut self) -> &mut [<Self::R as Row>::Element] {
self.data[1].as_mut()
}
fn ring_size(&self) -> usize {
self.data[0].as_ref().len()
}
}
pub(crate) struct RgswCiphertextRef<'a, R> {
data: &'a [R],
d_a: usize,
d_b: usize,
}
impl<'a, R> RgswCiphertextRef<'a, R> {
pub(crate) fn new(data: &'a [R], d_a: usize, d_b: usize) -> Self {
RgswCiphertextRef { data, d_a, d_b }
}
}
impl<'a, R> RgswCiphertext for RgswCiphertextRef<'a, R>
where
R: Row,
{
type R = R;
fn split(&self) -> ((&[Self::R], &[Self::R]), (&[Self::R], &[Self::R])) {
let (rlwe_dash_nsm, rlwe_dash_m) = self.data.split_at(self.d_a * 2);
(
rlwe_dash_nsm.split_at(self.d_a),
rlwe_dash_m.split_at(self.d_b),
)
}
}
pub(crate) struct RgswCiphertextMutRef<'a, R> {
data: &'a mut [R],
d_a: usize,
d_b: usize,
}
impl<'a, R> RgswCiphertextMutRef<'a, R> {
pub(crate) fn new(data: &'a mut [R], d_a: usize, d_b: usize) -> Self {
RgswCiphertextMutRef { data, d_a, d_b }
}
}
impl<'a, R: RowMut> AsMut<[R]> for RgswCiphertextMutRef<'a, R> {
fn as_mut(&mut self) -> &mut [R] {
&mut self.data
}
}
impl<'a, R> RgswCiphertext for RgswCiphertextMutRef<'a, R>
where
R: Row,
{
type R = R;
fn split(&self) -> ((&[Self::R], &[Self::R]), (&[Self::R], &[Self::R])) {
let (rlwe_dash_nsm, rlwe_dash_m) = self.data.split_at(self.d_a * 2);
(
rlwe_dash_nsm.split_at(self.d_a),
rlwe_dash_m.split_at(self.d_b),
)
}
}
impl<'a, R> RgswCiphertextMut for RgswCiphertextMutRef<'a, R>
where
R: RowMut,
{
fn split_mut(
&mut self,
) -> (
(&mut [Self::R], &mut [Self::R]),
(&mut [Self::R], &mut [Self::R]),
) {
let (rlwe_dash_nsm, rlwe_dash_m) = self.data.split_at_mut(self.d_a * 2);
(
rlwe_dash_nsm.split_at_mut(self.d_a),
rlwe_dash_m.split_at_mut(self.d_b),
)
}
}
pub(crate) struct RlweKskRef<'a, R> {
data: &'a [R],
decomposition_count: usize,
}
impl<'a, R: Row> RlweKskRef<'a, R> {
pub(crate) fn new(ksk: &'a [R], decomposition_count: usize) -> Self {
Self {
data: ksk,
decomposition_count,
}
}
}
impl<'a, R: Row> RlweKsk for RlweKskRef<'a, R> {
type R = R;
fn ksk_part_a(&self) -> &[Self::R] {
&self.data[..self.decomposition_count]
}
fn ksk_part_b(&self) -> &[Self::R] {
&self.data[self.decomposition_count..]
}
}
pub(crate) struct RuntimeScratchMutRef<'a, R> {
data: &'a mut [R],
}
impl<'a, R> RuntimeScratchMutRef<'a, R> {
pub(crate) fn new(data: &'a mut [R]) -> Self {
Self { data }
}
}
impl<'a, R: RowMut> RuntimeScratchMatrix for RuntimeScratchMutRef<'a, R>
where
R::Element: Zero + Clone,
{
type R = R;
type Rgsw = RgswCiphertextRef<'a, R>;
fn scratch_for_rlwe_auto_and_zero_rlwe_space(
&mut self,
decompostion_count: usize,
) -> (&mut [Self::R], &mut [Self::R]) {
let (decomp_poly, other) = self.data.split_at_mut(decompostion_count);
let (rlwe, _) = other.split_at_mut(2);
// zero fill rlwe
rlwe.iter_mut()
.for_each(|r| r.as_mut().fill(R::Element::zero()));
(decomp_poly, rlwe)
}
fn scratch_for_rlwe_auto_trivial_case(&mut self) -> &mut Self::R {
&mut self.data[0]
}
fn scratch_for_rgsw_x_rgsw_and_zero_rgsw0_space<D: RlweDecomposer>(
&mut self,
rgsw0_decoposer: &D,
rgsw1_decoposer: &D,
) -> (&mut [Self::R], &mut [Self::R]) {
let (decomp_poly, other) = self.data.split_at_mut(std::cmp::max(
rgsw1_decoposer.decomposition_count_a().0,
rgsw1_decoposer.decomposition_count_b().0,
));
let (rgsw, _) = other.split_at_mut(
rgsw0_decoposer.decomposition_count_a().0 * 2
+ rgsw0_decoposer.decomposition_count_b().0 * 2,
);
// zero fill rgsw0
rgsw.iter_mut()
.for_each(|r| r.as_mut().fill(R::Element::zero()));
(decomp_poly, rgsw)
}
fn scratch_for_rlwe_x_rgsw_and_zero_rlwe_space<D: RlweDecomposer>(
&mut self,
decomposer: &D,
) -> (&mut [Self::R], &mut [Self::R]) {
let (decomp_poly, other) = self.data.split_at_mut(std::cmp::max(
decomposer.decomposition_count_a().0,
decomposer.decomposition_count_b().0,
));
let (rlwe, _) = other.split_at_mut(2);
// zero fill rlwe
rlwe.iter_mut()
.for_each(|r| r.as_mut().fill(R::Element::zero()));
(decomp_poly, rlwe)
}
}
/// Returns no. of rows in scratch space for RGSW0 x RGSW1 product
pub(crate) fn rgsw_x_rgsw_scratch_rows<D: DoubleDecomposerParams<Count = DecompositionCount>>(
rgsw0_decomposer_param: &D,
rgsw1_decomposer_param: &D,
) -> usize {
std::cmp::max(
rgsw1_decomposer_param.decomposition_count_a().0,
rgsw1_decomposer_param.decomposition_count_b().0,
) + rgsw0_decomposer_param.decomposition_count_a().0 * 2
+ rgsw0_decomposer_param.decomposition_count_b().0 * 2
}
/// Returns no. of rows in scratch space for RLWE x RGSW product
pub(crate) fn rlwe_x_rgsw_scratch_rows<D: DoubleDecomposerParams<Count = DecompositionCount>>(
rgsw_decomposer_param: &D,
) -> usize {
std::cmp::max(
rgsw_decomposer_param.decomposition_count_a().0,
rgsw_decomposer_param.decomposition_count_b().0,
) + 2
}
/// Returns no. of rows in scratch space for RLWE auto
pub(crate) fn rlwe_auto_scratch_rows<D: SingleDecomposerParams<Count = DecompositionCount>>(
param: &D,
) -> usize {
param.decomposition_count().0 + 2
}
pub(crate) fn poly_fma_routine<R: RowMut, ModOp: VectorOps<Element = R::Element>>(
write_to_row: &mut [R::Element],
matrix_a: &[R],
matrix_b: &[R],
mod_op: &ModOp,
) {
izip!(matrix_a.iter(), matrix_b.iter()).for_each(|(a, b)| {
mod_op.elwise_fma_mut(write_to_row, a.as_ref(), b.as_ref());
});
}
/// Decomposes ring polynomial r(X) into d polynomials using decomposer into
/// output matrix decomp_r
///
/// Note that decomposition of r(X) requires decomposition of each of
/// coefficients.
///
/// - decomp_r: must have dimensions d x ring_size. i^th decomposed polynomial
/// will be stored at i^th row.
pub(crate) fn decompose_r<R: RowMut, D: Decomposer<Element = R::Element>>(
r: &[R::Element],
decomp_r: &mut [R],
decomposer: &D,
) where
R::Element: Copy,
{
let ring_size = r.len();
for ri in 0..ring_size {
decomposer
.decompose_iter(&r[ri])
.enumerate()
.for_each(|(index, el)| {
decomp_r[index].as_mut()[ri] = el;
});
}
}
/// Sends RLWE_{s(X)}(m(X)) -> RLWE_{s(X)}(m{X^k}) where k is some galois
/// element
///
/// - rlwe_in: Input ciphertext RLWE_{s(X)}(m(X)).
/// - ksk: Auto key switching key with polynomials in evaluation domain
/// - auto_map_index: If automorphism sends i^th coefficient of m(X) to j^th
/// coefficient of m(X^k) then auto_map_index[i] = j
/// - auto_sign_index: With a = m(X)[i], if m(X^k)[auto_map_index[i]] = -a, then
/// auto_sign_index[i] = false, else auto_sign_index[i] = true
/// - scratch_matrix: must have dimension at-least d+2 x ring_size. `d` rows to
/// store decomposed polynomials nad 2 rows to store out RLWE temporarily.
pub(crate) fn rlwe_auto<
Rlwe: RlweCiphertext,
Ksk: RlweKsk<R = Rlwe::R>,
Sc: RuntimeScratchMatrix<R = Rlwe::R>,
ModOp: ArithmeticOps<Element = <Rlwe::R as Row>::Element>
+ VectorOps<Element = <Rlwe::R as Row>::Element>,
NttOp: Ntt<Element = <Rlwe::R as Row>::Element>,
D: Decomposer<Element = <Rlwe::R as Row>::Element>,
>(
rlwe_in: &mut Rlwe,
ksk: &Ksk,
scratch_matrix: &mut Sc,
auto_map_index: &[usize],
auto_map_sign: &[bool],
mod_op: &ModOp,
ntt_op: &NttOp,
decomposer: &D,
is_trivial: bool,
) where
<Rlwe::R as Row>::Element: Copy + Zero,
{
// let ring_size = rlwe_in.dimension().1;
// assert!(rlwe_in.dimension().0 == 2);
// assert!(scratch_matrix.fits(d + 2, ring_size));
if !is_trivial {
let (decomp_poly_scratch, tmp_rlwe) = scratch_matrix
.scratch_for_rlwe_auto_and_zero_rlwe_space(decomposer.decomposition_count().0);
let mut tmp_rlwe = RlweCiphertextMutRef::new(tmp_rlwe);
// send a(X) -> a(X^k) and decompose a(X^k)
izip!(
rlwe_in.part_a(),
auto_map_index.iter(),
auto_map_sign.iter()
)
.for_each(|(el_in, to_index, sign)| {
let el_out = if !*sign { mod_op.neg(el_in) } else { *el_in };
decomposer
.decompose_iter(&el_out)
.enumerate()
.for_each(|(index, el)| {
decomp_poly_scratch[index].as_mut()[*to_index] = el;
});
});
// transform decomposed a(X^k) to evaluation domain
decomp_poly_scratch.iter_mut().for_each(|r| {
ntt_op.forward(r.as_mut());
});
// RLWE(m^k) = a', b'; RLWE(m) = a, b
// key switch: (a * RLWE'(s(X^k)))
// a' = decomp<a> * RLWE'_A(s(X^k))
poly_fma_routine(
tmp_rlwe.part_a_mut(),
decomp_poly_scratch,
ksk.ksk_part_a(),
mod_op,
);
// b' += decomp<a(X^k)> * RLWE'_B(s(X^k))
poly_fma_routine(
tmp_rlwe.part_b_mut(),
decomp_poly_scratch,
ksk.ksk_part_b(),
mod_op,
);
// transform RLWE(m^k) to coefficient domain
ntt_op.backward(tmp_rlwe.part_a_mut());
ntt_op.backward(tmp_rlwe.part_b_mut());
// send b(X) -> b(X^k) and then b'(X) += b(X^k)
izip!(
rlwe_in.part_b(),
auto_map_index.iter(),
auto_map_sign.iter()
)
.for_each(|(el_in, to_index, sign)| {
let row = tmp_rlwe.part_b_mut();
if !*sign {
row[*to_index] = mod_op.sub(&row[*to_index], el_in);
} else {
row[*to_index] = mod_op.add(&row[*to_index], el_in);
}
});
// copy over A; Leave B for later
rlwe_in.part_a_mut().copy_from_slice(tmp_rlwe.part_a());
rlwe_in.part_b_mut().copy_from_slice(tmp_rlwe.part_b());
} else {
// RLWE is trivial, a(X) is 0.
// send b(X) -> b(X^k)
let tmp_row = scratch_matrix.scratch_for_rlwe_auto_trivial_case();
izip!(
rlwe_in.part_b(),
auto_map_index.iter(),
auto_map_sign.iter()
)
.for_each(|(el_in, to_index, sign)| {
if !*sign {
tmp_row.as_mut()[*to_index] = mod_op.neg(el_in);
} else {
tmp_row.as_mut()[*to_index] = *el_in;
}
});
rlwe_in.part_b_mut().copy_from_slice(tmp_row.as_ref());
}
}
/// Sends RLWE_{s(X)}(m(X)) -> RLWE_{s(X)}(m{X^k}) where k is some galois
/// element
///
/// This is same as `galois_auto` with the difference that alongside `ksk` with
/// key switching polynomials in evaluation domain, shoup representation,
/// `ksk_shoup`, of the polynomials in evaluation domain is also supplied.
pub(crate) fn rlwe_auto_shoup<
Rlwe: RlweCiphertext,
Ksk: RlweKsk<R = Rlwe::R>,
Sc: RuntimeScratchMatrix<R = Rlwe::R>,
ModOp: ArithmeticOps<Element = <Rlwe::R as Row>::Element>
// + VectorOps<Element = MT::MatElement>
+ ShoupMatrixFMA<Rlwe::R>,
NttOp: Ntt<Element = <Rlwe::R as Row>::Element>,
D: Decomposer<Element = <Rlwe::R as Row>::Element>,
>(
rlwe_in: &mut Rlwe,
ksk: &Ksk,
ksk_shoup: &Ksk,
scratch_matrix: &mut Sc,
auto_map_index: &[usize],
auto_map_sign: &[bool],
mod_op: &ModOp,
ntt_op: &NttOp,
decomposer: &D,
is_trivial: bool,
) where
<Rlwe::R as Row>::Element: Copy + Zero,
{
// let d = decomposer.decomposition_count();
// let ring_size = rlwe_in.dimension().1;
// assert!(rlwe_in.dimension().0 == 2);
// assert!(scratch_matrix.fits(d + 2, ring_size));
if !is_trivial {
let (decomp_poly_scratch, tmp_rlwe) = scratch_matrix
.scratch_for_rlwe_auto_and_zero_rlwe_space(decomposer.decomposition_count().0);
let mut tmp_rlwe = RlweCiphertextMutRef::new(tmp_rlwe);
// send a(X) -> a(X^k) and decompose a(X^k)
izip!(
rlwe_in.part_a(),
auto_map_index.iter(),
auto_map_sign.iter()
)
.for_each(|(el_in, to_index, sign)| {
let el_out = if !*sign { mod_op.neg(el_in) } else { *el_in };
decomposer
.decompose_iter(&el_out)
.enumerate()
.for_each(|(index, el)| {
decomp_poly_scratch[index].as_mut()[*to_index] = el;
});
});
// transform decomposed a(X^k) to evaluation domain
decomp_poly_scratch.iter_mut().for_each(|r| {
ntt_op.forward_lazy(r.as_mut());
});
// RLWE(m^k) = a', b'; RLWE(m) = a, b
// key switch: (a * RLWE'(s(X^k)))
// a' = decomp<a> * RLWE'_A(s(X^k))
mod_op.shoup_matrix_fma(
tmp_rlwe.part_a_mut(),
ksk.ksk_part_a(),
ksk_shoup.ksk_part_a(),
decomp_poly_scratch,
);
// b'= decomp<a(X^k)> * RLWE'_B(s(X^k))
mod_op.shoup_matrix_fma(
tmp_rlwe.part_b_mut(),
ksk.ksk_part_b(),
ksk_shoup.ksk_part_b(),
decomp_poly_scratch,
);
// transform RLWE(m^k) to coefficient domain
ntt_op.backward(tmp_rlwe.part_a_mut());
ntt_op.backward(tmp_rlwe.part_b_mut());
// send b(X) -> b(X^k) and then b'(X) += b(X^k)
let row = tmp_rlwe.part_b_mut();
izip!(
rlwe_in.part_b(),
auto_map_index.iter(),
auto_map_sign.iter()
)
.for_each(|(el_in, to_index, sign)| {
if !*sign {
row[*to_index] = mod_op.sub(&row[*to_index], el_in);
} else {
row[*to_index] = mod_op.add(&row[*to_index], el_in);
}
});
// copy over A, B
rlwe_in.part_a_mut().copy_from_slice(tmp_rlwe.part_a());
rlwe_in.part_b_mut().copy_from_slice(tmp_rlwe.part_b());
} else {
// RLWE is trivial, a(X) is 0.
// send b(X) -> b(X^k)
let row = scratch_matrix.scratch_for_rlwe_auto_trivial_case();
izip!(
rlwe_in.part_b(),
auto_map_index.iter(),
auto_map_sign.iter()
)
.for_each(|(el_in, to_index, sign)| {
if !*sign {
row.as_mut()[*to_index] = mod_op.neg(el_in);
} else {
row.as_mut()[*to_index] = *el_in;
}
});
rlwe_in.part_b_mut().copy_from_slice(row.as_ref());
}
}
/// Inplace mutates RLWE(m0) to equal RLWE(m0m1) = RLWE(m0) x RGSW(m1).
///
/// - rlwe_in: is RLWE(m0) with polynomials in coefficient domain
/// - rgsw_in: is RGSW(m1) with polynomials in evaluation domain
/// - scratch_matrix: with dimension (max(d_a, d_b) + 2) x ring_size columns.
/// It's used to store decomposed polynomials and out RLWE temporarily
pub(crate) fn rlwe_by_rgsw<
Rlwe: RlweCiphertext,
Rgsw: RgswCiphertext<R = Rlwe::R>,
Sc: RuntimeScratchMatrix<R = Rlwe::R>,
D: RlweDecomposer<Element = <Rlwe::R as Row>::Element>,
ModOp: VectorOps<Element = <Rlwe::R as Row>::Element>,
NttOp: Ntt<Element = <Rlwe::R as Row>::Element>,
>(
rlwe_in: &mut Rlwe,
rgsw_in: &Rgsw,
scratch_matrix: &mut Sc,
decomposer: &D,
ntt_op: &NttOp,
mod_op: &ModOp,
is_trivial: bool,
) where
<Rlwe::R as Row>::Element: Copy + Zero,
{
let decomposer_a = decomposer.a();
let decomposer_b = decomposer.b();
let d_a = decomposer.decomposition_count_a().0;
let d_b = decomposer.decomposition_count_b().0;
let ((rlwe_dash_nsm_parta, rlwe_dash_nsm_partb), (rlwe_dash_m_parta, rlwe_dash_m_partb)) =
rgsw_in.split();
let (decomposed_poly_scratch, tmp_rlwe) =
scratch_matrix.scratch_for_rlwe_x_rgsw_and_zero_rlwe_space(decomposer);
// RLWE_in = a_in, b_in; RLWE_out = a_out, b_out
if !is_trivial {
// a_in = 0 when RLWE_in is trivial RLWE ciphertext
// decomp<a_in>
let mut decomposed_polys_of_rlwea = &mut decomposed_poly_scratch[..d_a];
decompose_r(
rlwe_in.part_a(),
&mut decomposed_polys_of_rlwea,
decomposer_a,
);
decomposed_polys_of_rlwea
.iter_mut()
.for_each(|r| ntt_op.forward(r.as_mut()));
// a_out += decomp<a_in> \cdot RLWE_A'(-sm)
poly_fma_routine(
tmp_rlwe[0].as_mut(),
&decomposed_polys_of_rlwea,
rlwe_dash_nsm_parta,
mod_op,
);
// b_out += decomp<a_in> \cdot RLWE_B'(-sm)
poly_fma_routine(
tmp_rlwe[1].as_mut(),
&decomposed_polys_of_rlwea,
&rlwe_dash_nsm_partb,
mod_op,
);
}
{
// decomp<b_in>
let mut decomposed_polys_of_rlweb = &mut decomposed_poly_scratch[..d_b];
decompose_r(
rlwe_in.part_b(),
&mut decomposed_polys_of_rlweb,
decomposer_b,
);
decomposed_polys_of_rlweb
.iter_mut()
.for_each(|r| ntt_op.forward(r.as_mut()));
// a_out += decomp<b_in> \cdot RLWE_A'(m)
poly_fma_routine(
tmp_rlwe[0].as_mut(),
&decomposed_polys_of_rlweb,
&rlwe_dash_m_parta,
mod_op,
);
// b_out += decomp<b_in> \cdot RLWE_B'(m)
poly_fma_routine(
tmp_rlwe[1].as_mut(),
&decomposed_polys_of_rlweb,
&rlwe_dash_m_partb,
mod_op,
);
}
// transform rlwe_out to coefficient domain
tmp_rlwe
.iter_mut()
.for_each(|r| ntt_op.backward(r.as_mut()));
rlwe_in.part_a_mut().copy_from_slice(tmp_rlwe[0].as_mut());
rlwe_in.part_b_mut().copy_from_slice(tmp_rlwe[1].as_mut());
}
/// Inplace mutates RLWE(m0) to equal RLWE(m0m1) = RLWE(m0) x RGSW(m1).
///
/// Same as `rlwe_by_rgsw` with the difference that alongside `rgsw_in` with
/// polynomials in evaluation domain, shoup representation of polynomials in
/// evaluation domain, `rgsw_in_shoup`, is also supplied.
pub(crate) fn rlwe_by_rgsw_shoup<
Rlwe: RlweCiphertext,
Rgsw: RgswCiphertext<R = Rlwe::R>,
Sc: RuntimeScratchMatrix<R = Rlwe::R>,
D: RlweDecomposer<Element = <Rlwe::R as Row>::Element>,
ModOp: ShoupMatrixFMA<Rlwe::R>,
NttOp: Ntt<Element = <Rlwe::R as Row>::Element>,
>(
rlwe_in: &mut Rlwe,
rgsw_in: &Rgsw,
rgsw_in_shoup: &Rgsw,
scratch_matrix: &mut Sc,
decomposer: &D,
ntt_op: &NttOp,
mod_op: &ModOp,
is_trivial: bool,
) where
<Rlwe::R as Row>::Element: Copy + Zero,
{
let decomposer_a = decomposer.a();
let decomposer_b = decomposer.b();
let d_a = decomposer.decomposition_count_a().0;
let d_b = decomposer.decomposition_count_b().0;
let ((rlwe_dash_nsm_parta, rlwe_dash_nsm_partb), (rlwe_dash_m_parta, rlwe_dash_m_partb)) =
rgsw_in.split();
let (
(rlwe_dash_nsm_parta_shoup, rlwe_dash_nsm_partb_shoup),
(rlwe_dash_m_parta_shoup, rlwe_dash_m_partb_shoup),
) = rgsw_in_shoup.split();
let (decomposed_poly_scratch, tmp_rlwe) =
scratch_matrix.scratch_for_rlwe_x_rgsw_and_zero_rlwe_space(decomposer);
// RLWE_in = a_in, b_in; RLWE_out = a_out, b_out
if !is_trivial {
// a_in = 0 when RLWE_in is trivial RLWE ciphertext
// decomp<a_in>
let mut decomposed_polys_of_rlwea = &mut decomposed_poly_scratch[..d_a];
decompose_r(
rlwe_in.part_a(),
&mut decomposed_polys_of_rlwea,
decomposer_a,
);
decomposed_polys_of_rlwea
.iter_mut()
.for_each(|r| ntt_op.forward_lazy(r.as_mut()));
// a_out += decomp<a_in> \cdot RLWE_A'(-sm)
mod_op.shoup_matrix_fma(
tmp_rlwe[0].as_mut(),
&rlwe_dash_nsm_parta,
&rlwe_dash_nsm_parta_shoup,
&decomposed_polys_of_rlwea,
);
// b_out += decomp<a_in> \cdot RLWE_B'(-sm)
mod_op.shoup_matrix_fma(
tmp_rlwe[1].as_mut(),
&rlwe_dash_nsm_partb,
&rlwe_dash_nsm_partb_shoup,
&decomposed_polys_of_rlwea,
);
}
{
// decomp<b_in>
let mut decomposed_polys_of_rlweb = &mut decomposed_poly_scratch[..d_b];
decompose_r(
rlwe_in.part_b(),
&mut decomposed_polys_of_rlweb,
decomposer_b,
);
decomposed_polys_of_rlweb
.iter_mut()
.for_each(|r| ntt_op.forward_lazy(r.as_mut()));
// a_out += decomp<b_in> \cdot RLWE_A'(m)
mod_op.shoup_matrix_fma(
tmp_rlwe[0].as_mut(),
&rlwe_dash_m_parta,
&rlwe_dash_m_parta_shoup,
&decomposed_polys_of_rlweb,
);
// b_out += decomp<b_in> \cdot RLWE_B'(m)
mod_op.shoup_matrix_fma(
tmp_rlwe[1].as_mut(),
&rlwe_dash_m_partb,
&rlwe_dash_m_partb_shoup,
&decomposed_polys_of_rlweb,
);
}
// transform rlwe_out to coefficient domain
tmp_rlwe
.iter_mut()
.for_each(|r| ntt_op.backward(r.as_mut()));
rlwe_in.part_a_mut().copy_from_slice(tmp_rlwe[0].as_mut());
rlwe_in.part_b_mut().copy_from_slice(tmp_rlwe[1].as_mut());
}
/// Inplace mutates RGSW(m0) to equal RGSW(m0m1) = RGSW(m0)xRGSW(m1)
///
/// RGSW x RGSW product requires multiple RLWE x RGSW products. For example,
/// Define
///
/// RGSW(m0) = [RLWE(-sm), RLWE(\beta -sm), ..., RLWE(\beta^{d-1} -sm)
/// RLWE(m), RLWE(\beta m), ..., RLWE(\beta^{d-1} m)]
/// And RGSW(m1)
///
/// Then RGSW(m0) x RGSW(m1) equals:
/// RGSW(m0m1) = [
/// rlwe_x_rgsw(RLWE(-sm), RGSW(m1)),
/// ...,
/// rlwe_x_rgsw(RLWE(\beta^{d-1} -sm), RGSW(m1)),
/// rlwe_x_rgsw(RLWE(m), RGSW(m1)),
/// ...,
/// rlwe_x_rgsw(RLWE(\beta^{d-1} m), RGSW(m1)),
/// ]
///
/// Since noise growth in RLWE x RGSW depends on noise in RGSW ciphertext, it is
/// clear to observe from above that noise in resulting RGSW(m0m1) equals noise
/// accumulated in a single RLWE x RGSW and depends on noise in RGSW(m1) (i.e.
/// rgsw_1_eval)
///
/// - rgsw_0: RGSW(m0) in coefficient domain
/// - rgsw_1_eval: RGSW(m1) in evaluation domain
pub(crate) fn rgsw_by_rgsw_inplace<
Rgsw: RgswCiphertext,
RgswMut: RgswCiphertextMut<R = Rgsw::R>,
Sc: RuntimeScratchMatrix<R = Rgsw::R, Rgsw = Rgsw>,
D: RlweDecomposer<Element = <Rgsw::R as Row>::Element>,
ModOp: VectorOps<Element = <Rgsw::R as Row>::Element>,
NttOp: Ntt<Element = <Rgsw::R as Row>::Element>,
>(
rgsw0: &mut RgswMut,
rgsw1_eval: &Rgsw,
rgsw0_decomposer: &D,
rgsw1_decomposer: &D,
scratch_matrix: &mut Sc,
ntt_op: &NttOp,
mod_op: &ModOp,
) where
<Rgsw::R as Row>::Element: Copy + Zero,
RgswMut: AsMut<[Rgsw::R]>,
RgswMut::R: RowMut,
// Rgsw: AsRef<[Rgsw::R]>,
{
let (decomp_r_space, rgsw_space) = scratch_matrix
.scratch_for_rgsw_x_rgsw_and_zero_rgsw0_space(rgsw0_decomposer, rgsw1_decomposer);
let mut rgsw_space = RgswCiphertextMutRef::new(
rgsw_space,
rgsw0_decomposer.decomposition_count_a().0,
rgsw0_decomposer.decomposition_count_b().0,
);
let (
(rlwe_dash_space_nsm_parta, rlwe_dash_space_nsm_partb),
(rlwe_dash_space_m_parta, rlwe_dash_space_m_partb),
) = rgsw_space.split_mut();
let ((rgsw0_nsm_parta, rgsw0_nsm_partb), (rgsw0_m_parta, rgsw0_m_partb)) = rgsw0.split();
let ((rgsw1_nsm_parta, rgsw1_nsm_partb), (rgsw1_m_parta, rgsw1_m_partb)) = rgsw1_eval.split();
// RGSW x RGSW
izip!(
rgsw0_nsm_parta.iter().chain(rgsw0_m_parta),
rgsw0_nsm_partb.iter().chain(rgsw0_m_partb),
rlwe_dash_space_nsm_parta
.iter_mut()
.chain(rlwe_dash_space_m_parta.iter_mut()),
rlwe_dash_space_nsm_partb
.iter_mut()
.chain(rlwe_dash_space_m_partb.iter_mut()),
)
.for_each(|(rlwe_a, rlwe_b, rlwe_out_a, rlwe_out_b)| {
// RLWE(m0) x RGSW(m1)
// Part A: Decomp<RLWE(m0)[A]> \cdot RLWE'(-sm1)
{
let decomp_r_parta = &mut decomp_r_space[..rgsw1_decomposer.decomposition_count_a().0];
decompose_r(
rlwe_a.as_ref(),
decomp_r_parta.as_mut(),
rgsw1_decomposer.a(),
);
decomp_r_parta
.iter_mut()
.for_each(|ri| ntt_op.forward(ri.as_mut()));
poly_fma_routine(
rlwe_out_a.as_mut(),
&decomp_r_parta,
&rgsw1_nsm_parta,
mod_op,
);
poly_fma_routine(
rlwe_out_b.as_mut(),
&decomp_r_parta,
&rgsw1_nsm_partb,
mod_op,
);
}
// Part B: Decompose<RLWE(m0)[B]> \cdot RLWE'(m1)
{
let decomp_r_partb = &mut decomp_r_space[..rgsw1_decomposer.decomposition_count_b().0];
decompose_r(
rlwe_b.as_ref(),
decomp_r_partb.as_mut(),
rgsw1_decomposer.b(),
);
decomp_r_partb
.iter_mut()
.for_each(|ri| ntt_op.forward(ri.as_mut()));
poly_fma_routine(rlwe_out_a.as_mut(), &decomp_r_partb, &rgsw1_m_parta, mod_op);
poly_fma_routine(rlwe_out_b.as_mut(), &decomp_r_partb, &rgsw1_m_partb, mod_op);
}
});
// copy over RGSW(m0m1) to RGSW(m0)
// let d = rgsw0.as_mut();
izip!(rgsw0.as_mut().iter_mut(), rgsw_space.data.iter())
.for_each(|(to_ri, from_ri)| to_ri.as_mut().copy_from_slice(from_ri.as_ref()));
// send back to coefficient domain
rgsw0
.as_mut()
.iter_mut()
.for_each(|ri| ntt_op.backward(ri.as_mut()));
}
/// Key switches input RLWE_{s'}(m) -> RLWE_{s}(m)
///
/// Let RLWE_{s'}(m) = [a, b] s.t. m+e = b - as'
///
/// Given key switchin key Ksk(s' -> s) = RLWE'_{s}(s') = [RLWE_{s}(beta^i s')]
/// = [a, a*s + e + beta^i s'] for i \in [0,d), key switching computes:
/// 1. RLWE_{s}(-s'a) = \sum signed_decompose(-a)[i] RLWE_{s}(beta^i s')
/// 2. RLWE_{s}(m) = (b, 0) + RLWE_{s}(-s'a)
///
/// - rlwe_in: Input rlwe ciphertext
/// - ksk: Key switching key Ksk(s' -> s) with polynomials in evaluation domain
/// - ksk_shoup: Key switching key Ksk(s' -> s) with polynomials in evaluation
/// domain in shoup representation
| rust | MIT | a8e6c276273bbe2cb7f2508ba07d1d192a467c13 | 2026-01-04T20:23:25.934339Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.