#!/usr/bin/env python # # A Ctypes wrapper to LibMTP # Developed by: Nick Devito (nick@nick125.com) # (c) 2007 Nick Devito # import ctypes ## # ## _libmtp = ctypes.CDLL("libmtp.so") # ---------- # Error Definitions # ---------- class NoDeviceConnected: pass class UnsupportedCommand: pass class CommandFailed: pass # ---------- # End Error Definitions # ---------- # ---------- # Data Model Definitions # ---------- class LIBMTP_File(ctypes.Structure): pass LIBMTP_File._fields_ = [("item_id", ctypes.c_uint32), ("parent_id", ctypes.c_uint32), ("filename", ctypes.c_char_p), ("filesize", ctypes.c_uint64), ("filetype", ctypes.c_int), ("next", ctypes.POINTER(LIBMTP_File))] # ---------- # End Data Model Definitions # ---------- # ---------- # Type Definitions # ---------- _libmtp.LIBMTP_Get_Friendlyname.restype = ctypes.c_char_p _libmtp.LIBMTP_Get_Serialnumber.restype = ctypes.c_char_p _libmtp.LIBMTP_Get_Modelname.restype = ctypes.c_char_p _libmtp.LIBMTP_Get_Deviceversion.restype = ctypes.c_char_p _libmtp.LIBMTP_Get_Filelisting_With_Callback.restype = ctypes.POINTER(LIBMTP_File) # ---------- # End Type Definitions # ---------- class MTP: def __init__(self): """ __init__() -> None """ self.mtp = _libmtp self.mtp.LIBMTP_Init() def connect(self, device=""): """ connect(device) -> None or raise NoDeviceConnected device - MTP Device pointer connects the mtp device """ ## TODO: This does not actually care if device is passed on! self.device = self.mtp.LIBMTP_Get_First_Device() if not self.device: raise NoDeviceConnected def disconnect(self): """ disconnect() -> None disconnects the mtp device """ self.mtp.LIBMTP_Release_Device(self.device) del self.device def get_devicename(self): """ get_devicename() -> name name - the name returns the name of the device """ return self.mtp.LIBMTP_Get_Friendlyname(self.device) def get_serialnumber(self): return self.mtp.LIBMTP_Get_Serialnumber(self.device) def get_batterylevel(self): maximum_level = ctypes.c_uint8() current_level = ctypes.c_uint8() self.mtp.LIBMTP_Get_Batterylevel(self.device, ctypes.byref(maximum_level), ctypes.byref(current_level)) if maximum_level and current_level: return (maximum_level.value, current_level.value) else: raise UnsupportedCommand def get_modelname(self): return self.mtp.LIBMTP_Get_Modelname(self.device) def get_deviceversion(self): return self.mtp.LIBMTP_Get_Deviceversion(self.device) def get_filelisting(self): files = self.mtp.LIBMTP_Get_Filelisting_With_Callback(self.device, None, None) to_return = [] next = files while next: to_return.append(next.contents) if not next.contents.next: break next = next.contents.next return to_return