Skip to main content

PtpSession

Struct PtpSession 

Source
pub struct PtpSession { /* private fields */ }
Expand description

A PTP session with a device.

PtpSession manages the lifecycle of a PTP/MTP session, including:

  • Opening and closing sessions
  • Transaction ID management
  • Serializing concurrent operations (MTP only allows one operation at a time)
  • Executing operations and receiving responses

§Example

use mtp_rs::ptp::PtpSession;

// Open a session with session ID 1
let session = PtpSession::open(transport, 1).await?;

// Get device info
let device_info = session.get_device_info().await?;

// Get storage IDs
let storage_ids = session.get_storage_ids().await?;

// Close the session when done
session.close().await?;

Implementations§

Source§

impl PtpSession

Source

pub async fn get_device_info(&self) -> Result<DeviceInfo, Error>

Returns information about the device including its capabilities, manufacturer, model, and supported operations.

Source

pub async fn get_storage_ids(&self) -> Result<Vec<StorageId>, Error>

Returns a list of storage IDs available on the device.

Source

pub async fn get_storage_info( &self, storage_id: StorageId, ) -> Result<StorageInfo, Error>

Returns information about a specific storage, including capacity, free space, and filesystem type.

Source

pub async fn get_object_handles( &self, storage_id: StorageId, format: Option<ObjectFormatCode>, parent: Option<ObjectHandle>, ) -> Result<Vec<ObjectHandle>, Error>

Get object handles.

Returns a list of object handles matching the specified criteria.

§Arguments
  • storage_id - Storage to search, or StorageId::ALL for all storages
  • format - Filter by format, or None for all formats
  • parent - Parent folder handle, or None for root level only, or Some(ObjectHandle::ALL) for recursive listing
Source

pub async fn get_object_info( &self, handle: ObjectHandle, ) -> Result<ObjectInfo, Error>

Returns metadata about an object, including filename, size, and timestamps.

Source

pub async fn get_object(&self, handle: ObjectHandle) -> Result<Vec<u8>, Error>

Downloads the complete data of an object.

Source

pub async fn get_partial_object( &self, handle: ObjectHandle, offset: u64, max_bytes: u32, ) -> Result<Vec<u8>, Error>

Get partial object.

Downloads a portion of an object’s data.

§Arguments
  • handle - The object handle
  • offset - Byte offset to start from (truncated to u32 in standard MTP)
  • max_bytes - Maximum number of bytes to retrieve
Source

pub async fn get_thumb(&self, handle: ObjectHandle) -> Result<Vec<u8>, Error>

Downloads the thumbnail image for an object.

Source

pub async fn send_object_info( &self, storage_id: StorageId, parent: ObjectHandle, info: &ObjectInfo, ) -> Result<(StorageId, ObjectHandle, ObjectHandle), Error>

Send object info (prepare for upload).

This must be called before send_object() to prepare the device for receiving a new object.

§Returns

Returns a tuple of (storage_id, parent_handle, new_object_handle) where:

  • storage_id - The storage where the object will be created
  • parent_handle - The parent folder handle
  • new_object_handle - The handle assigned to the new object
Source

pub async fn send_object(&self, data: &[u8]) -> Result<(), Error>

Send object data (must follow send_object_info).

Uploads the actual data for an object. This must be called immediately after send_object_info().

Source

pub async fn delete_object(&self, handle: ObjectHandle) -> Result<(), Error>

Deletes an object from the device.

Source

pub async fn move_object( &self, handle: ObjectHandle, storage_id: StorageId, parent: ObjectHandle, ) -> Result<(), Error>

Moves an object to a different location.

Source

pub async fn copy_object( &self, handle: ObjectHandle, storage_id: StorageId, parent: ObjectHandle, ) -> Result<ObjectHandle, Error>

Copies an object to a new location. Returns the handle of the newly created copy.

Source

pub async fn get_object_prop_value( &self, handle: ObjectHandle, property: ObjectPropertyCode, ) -> Result<Vec<u8>, Error>

Get object property value.

Retrieves the value of a specific property for an object. This is an MTP extension operation (0x9803).

§Arguments
  • handle - The object handle
  • property - The property code to retrieve
§Returns

Returns the raw property value as bytes.

Source

pub async fn set_object_prop_value( &self, handle: ObjectHandle, property: ObjectPropertyCode, value: &[u8], ) -> Result<(), Error>

Set object property value.

Sets the value of a specific property for an object. This is an MTP extension operation (0x9804).

§Arguments
  • handle - The object handle
  • property - The property code to set
  • value - The raw property value as bytes
Source

pub async fn rename_object( &self, handle: ObjectHandle, new_name: &str, ) -> Result<(), Error>

Rename an object (file or folder).

This is a convenience method that uses SetObjectPropValue to change the ObjectFileName property (0xDC07).

§Arguments
  • handle - The object handle to rename
  • new_name - The new filename
§Note

Not all devices support renaming. Check supports_rename() on DeviceInfo first.

Source

pub async fn initiate_capture( &self, storage_id: StorageId, format: ObjectFormatCode, ) -> Result<(), Error>

Initiate a capture operation.

This triggers the camera to capture an image. The operation is asynchronous; use poll_event() to wait for CaptureComplete and ObjectAdded events.

§Arguments
  • storage_id - Target storage (use StorageId(0) for camera default)
  • format - Object format for the capture (use ObjectFormatCode::Undefined for camera default)
§Events

After calling this method, monitor for these events:

  • EventCode::CaptureComplete - Capture operation finished
  • EventCode::ObjectAdded - New object (image) was created on device
§Example
// Trigger capture
session.initiate_capture(StorageId(0), ObjectFormatCode::Undefined).await?;

// Wait for events
loop {
    match session.poll_event().await? {
        Some(event) if event.code == EventCode::CaptureComplete => {
            println!("Capture complete!");
            break;
        }
        Some(event) if event.code == EventCode::ObjectAdded => {
            println!("New object: {}", event.params[0]);
        }
        _ => continue,
    }
}
Source

pub async fn poll_event(&self) -> Result<Option<EventContainer>, Error>

Poll for a single event from the interrupt endpoint.

This method waits until an event is received from the USB interrupt endpoint. Events are asynchronous notifications from the device about changes such as objects being added/removed, storage changes, etc.

Note: This method does not require the operation lock since events are received on the interrupt endpoint, which is independent of bulk transfers.

§Returns
  • Ok(Some(container)) - An event was received
  • Ok(None) - Timeout (only if caller wraps with their own timeout)
  • Err(_) - Communication error
Source§

impl PtpSession

Source

pub async fn get_device_prop_desc( &self, property: DevicePropertyCode, ) -> Result<DevicePropDesc, Error>

Get the descriptor for a device property.

Returns detailed information about the property including its type, current value, default value, and allowed values/range.

This is primarily used for digital cameras to query settings like ISO, aperture, shutter speed, etc. Most Android MTP devices do not support device properties.

§Arguments
  • property - The device property code to query
§Example
let desc = session.get_device_prop_desc(DevicePropertyCode::BatteryLevel).await?;
println!("Battery level: {:?}", desc.current_value);
Source

pub async fn get_device_prop_value( &self, property: DevicePropertyCode, ) -> Result<Vec<u8>, Error>

Get the current value of a device property.

Returns the raw bytes of the property value. To interpret the value, you need to know the property’s data type. Use get_device_prop_desc() to get the full descriptor including the data type.

§Arguments
  • property - The device property code to query
Source

pub async fn get_device_prop_value_typed( &self, property: DevicePropertyCode, data_type: PropertyDataType, ) -> Result<PropertyValue, Error>

Get a device property value as a typed PropertyValue.

This is a convenience method that parses the raw bytes according to the specified data type.

§Arguments
  • property - The device property code to query
  • data_type - The expected data type of the property
Source

pub async fn set_device_prop_value( &self, property: DevicePropertyCode, value: &[u8], ) -> Result<(), Error>

Set a device property value.

The value should be the raw bytes of the new value. The value type must match the property’s data type.

§Arguments
  • property - The device property code to set
  • value - The raw bytes of the new value
Source

pub async fn set_device_prop_value_typed( &self, property: DevicePropertyCode, value: &PropertyValue, ) -> Result<(), Error>

Set a device property value from a PropertyValue.

This is a convenience method that serializes the PropertyValue to bytes.

§Arguments
  • property - The device property code to set
  • value - The new value
Source

pub async fn reset_device_prop_value( &self, property: DevicePropertyCode, ) -> Result<(), Error>

Reset a device property to its default value.

§Arguments
  • property - The device property code to reset
Source§

impl PtpSession

Source

pub async fn execute_with_receive_stream( self: &Arc<Self>, operation: OperationCode, params: &[u32], ) -> Result<ReceiveStream, Error>

Execute operation with streaming data receive.

Returns a Stream that yields data chunks as they arrive from USB. The stream yields Bytes chunks (typically up to 64KB each).

§Important

The caller must consume the entire stream before calling any other session methods. The MTP session is locked while the stream is active.

§Arguments
  • operation - The operation code to execute
  • params - Operation parameters
§Returns

A ReceiveStream that yields Result<Bytes, Error> chunks.

Source

pub async fn execute_with_send_stream<S>( &self, operation: OperationCode, params: &[u32], total_size: u64, data: S, ) -> Result<ResponseContainer, Error>
where S: Stream<Item = Result<Bytes, Error>> + Unpin,

Execute operation with streaming data send.

Accepts a Stream of data chunks to send. The total_size must be known upfront (MTP protocol requirement).

§Arguments
  • operation - The operation code
  • params - Operation parameters
  • total_size - Total bytes that will be sent (REQUIRED by MTP protocol)
  • data - Stream of data chunks to send
§Important

The total_size must match the actual total bytes in the stream. MTP requires knowing the size before transfer begins.

Source

pub async fn get_object_stream( self: &Arc<Self>, handle: ObjectHandle, ) -> Result<ReceiveStream, Error>

Download an object as a stream of chunks.

This is a convenience method that calls execute_with_receive_stream with GetObject operation.

§Important

The caller must consume the entire stream before calling any other session methods. The MTP session is locked while the stream is active.

Source

pub async fn send_object_stream<S>( &self, total_size: u64, data: S, ) -> Result<(), Error>
where S: Stream<Item = Result<Bytes, Error>> + Unpin,

Upload an object from a stream.

This is a convenience method that streams object data directly to USB.

§Arguments
  • total_size - Total bytes that will be sent
  • data - Stream of data chunks to send
Source§

impl PtpSession

Source

pub async fn open( transport: Arc<dyn Transport>, session_id: u32, ) -> Result<Self, Error>

Open a new session with the device.

This sends an OpenSession command to the device and establishes a session with the given session ID.

§Arguments
  • transport - The transport layer for USB communication
  • session_id - The session ID to use (typically 1)
§Errors

Returns an error if the device rejects the session or communication fails.

Source

pub fn session_id(&self) -> SessionId

Get the session ID.

Source

pub async fn close(self) -> Result<(), Error>

Close the session.

This sends a CloseSession command to the device. Errors during close are ignored since the session is being terminated anyway.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.