Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How to check for available space using MTP (Media Transfer Protocol) with Delphi?

Posted on 2017-10-16
6
Low Priority
?
65 Views
Last Modified: 2017-11-20
How to check for available space?
For example, unable to copy file to Mobile Device. There is an Mobile Device Copy Error. It is necessary to find out the reason, whether it happened because of a lack of available space.
0
Comment
Question by:Michael Vlasenko
  • 3
  • 3
6 Comments
 
LVL 28

Accepted Solution

by:
Sinisa Vuk earned 1000 total points
ID: 42334603
With help of using PortableDeviceApi tlb (MS) unit ... you can get storage size and free space too.
I examine MS blog example...

uses ... PortableDeviceApiLib_TLB;
....

const
  //storage
  WPD_STORAGE_ACCESS_CAPABILITY_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_ACCESS_CAPABILITY_PID = 11;

  WPD_STORAGE_CAPACITY_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_CAPACITY_PID = 4;         

  WPD_STORAGE_CAPACITY_IN_OBJECTS_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_CAPACITY_IN_OBJECTS_PID = 10;

  WPD_STORAGE_DESCRIPTION_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_DESCRIPTION_PID = 7;

  WPD_STORAGE_FILE_SYSTEM_TYPE_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_FILE_SYSTEM_TYPE_PID = 3;

  WPD_STORAGE_FREE_SPACE_IN_BYTES_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_FREE_SPACE_IN_BYTES_PID = 5;

  WWPD_STORAGE_FREE_SPACE_IN_OBJECTS_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_FREE_SPACE_IN_OBJECTS_PID = 6;

  WPD_STORAGE_MAX_OBJECT_SIZE_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_MAX_OBJECT_SIZE_PID = 9;

  WPD_STORAGE_SERIAL_NUMBER_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_SERIAL_NUMBER_PID = 8;

  WPD_STORAGE_TYPE_FMTID : TGuid = '{01a3057a-74d6-4e80-bea7-dc4c212ce50a}';
  WPD_STORAGE_TYPE_PID = 2;

  //*****
  WPD_DEVICE_OBJECT_ID = 'DEVICE';
....

type
  PStorageInfo = ^TStorageInfo;
  TStorageInfo = record
    StorageId: String[255];
    lStorageFreeSpace: Int64;
    lStorageTotalSpace: Int64;
  end;

  TStorageInfoArray = array of TStorageInfo;

...

function ConnectToDevice(sDev: WideString; var PortableDev: IPortableDevice; DbgLst: TStringList): Boolean;
var
  PortableDeviceValues: IPortableDeviceValues;
  hr: HResult;
  dev_val: PortableDeviceApiLib_TLB._tagpropertykey;
  //bReadonly: Boolean;
begin
  Result := False;

  if Assigned(DbgLst) then
    DbgLst.Add('Start Connecting: '+sDev);

  PortableDev := CoPortableDevice.Create;
  try
    //create device values:
    PortableDeviceValues := CreateComObject(CLASS_PortableDeviceValues) as IPortableDeviceValues;
    if VarIsClear(PortableDeviceValues) then Exit;

    if Assigned(DbgLst) then
      DbgLst.Add('Dev. val. ok! ');

    //bReadonly := False;
    //set some info
    dev_val.fmtid := WPD_CLIENT_NAME_FMTID;
    dev_val.pid := WPD_CLIENT_NAME_PID;
    PortableDeviceValues.SetStringValue(dev_val, PWideChar(CLIENT_NAME));

    dev_val.fmtid := WPD_CLIENT_MAJOR_VERSION_FMTID;
    dev_val.pid := WPD_CLIENT_MAJOR_VERSION_PID;
    PortableDeviceValues.SetUnsignedIntegerValue(dev_val, CLIENT_MAJOR_VER);

    dev_val.fmtid := WPD_CLIENT_MINOR_VERSION_FMTID;
    dev_val.pid := WPD_CLIENT_MINOR_VERSION_PID;
    PortableDeviceValues.SetUnsignedIntegerValue(dev_val, CLIENT_MINOR_VER);

    dev_val.fmtid := WPD_CLIENT_REVISION_FMTID;
    dev_val.pid := WPD_CLIENT_REVISION_PID;
    PortableDeviceValues.SetUnsignedIntegerValue(dev_val, CLIENT_REVISION);

    //open device
    hr := PortableDev.Open(PWideChar(sDev), PortableDeviceValues);
    if hr = E_ACCESSDENIED then
    begin
      // Attempt to open for read-only access
      dev_val.fmtid := WPD_CLIENT_DESIRED_ACCESS_FMTID;
      dev_val.pid := WPD_CLIENT_DESIRED_ACCESS_PID;
      PortableDeviceValues.SetUnsignedIntegerValue(dev_val, GENERIC_READ);
      hr := PortableDev.Open(PWideChar(sDev), PortableDeviceValues);
      //bReadonly := (hr = S_OK);
    end;

    //opened ok
    if hr = S_OK then
    begin
      if Assigned(DbgLst) then
        DbgLst.Add('Connected: '+sDev);
      Result := True;
    end
    else
    begin
      if Assigned(DbgLst) then
        DbgLst.Add('Not connected: '+IntToStr(hr));
    end;
  finally
    PortableDeviceValues := nil;
  end;
end;

function GetFirstStorageID(PortableDev: IPortableDevice; DbgLst: TStringList): WideString;
var
  content: IPortableDeviceContent;
  objectIds: IEnumPortableDeviceObjectIDs;
  objectId: PWideChar;
  fetched: Cardinal;
begin
  Result := WPD_DEVICE_OBJECT_ID;
  if PortableDev.Content(content) = S_OK then
  begin
    if content.EnumObjects(0, '', nil, objectIds) = S_OK then
    begin
      objectIds.Reset;
      objectIds.Next(1, objectId, fetched);
      if (fetched > 0) then
        Result := objectId;
    end;
  end;
  
  if Assigned(DbgLst) then
    DbgLst.Add('Device root: '+ Result);
end;

function GetDevDescription(PMan: TPortableDeviceManager; sDeviceId: WideString; DbgLst: TStringList): WideString;
var
  iDevNameLen: LongWord;
  iRes: Integer;
begin
  //get length of friendly name:
  iDevNameLen := 0;
  Result := '';

  iRes := PMan.GetDeviceDescription(PWideChar(sDeviceId), Word(nil^), iDevNameLen);
  if iRes = S_OK then
  begin
    if Assigned(DbgLst) then
      DbgLst.Add('DeviceDescription len='+IntToStr(iDevNameLen));

    //Get Description
    if iDevNameLen>0 then
    begin
      SetLength(Result, iDevNameLen);
      ZeroMemory(PWideChar(Result), iDevNameLen);
      PMan.GetDeviceDescription(PWideChar(sDeviceId), PWord(PWideChar(Result))^, iDevNameLen);
      Result := Trim(Result);
      if Assigned(DbgLst) then
        DbgLst.Add('DeviceDescription='+Result);
    end;
  end
  else
  begin
    if Assigned(DbgLst) then
      DbgLst.Add('Cannot GetDeviceDescription! ('+IntToStr(iRes)+')');
  end;
end;

function GetDeviceFriendlyName(PMan: TPortableDeviceManager; sDeviceId: WideString; DbgLst: TStringList): WideString;
var
  iDevNameLen{, iType}: LongWord;
  iRes: Integer;
begin
  //get length of friendly name:
  iDevNameLen := 0;
  Result := '';

  iRes := PMan.GetDeviceFriendlyName(PWideChar(sDeviceId), Word(nil^), iDevNameLen);
  if iRes = S_OK then
  begin
    if Assigned(DbgLst) then
      DbgLst.Add('FriendlyName len='+IntToStr(iDevNameLen));

    //Get Friendly Name
    if iDevNameLen>0 then
    begin
      SetLength(Result, iDevNameLen);
      ZeroMemory(PWideChar(Result), iDevNameLen);
      PMan.GetDeviceFriendlyName(PWideChar(sDeviceId), PWord(PWideChar(Result))^, iDevNameLen);
      Result := Trim(Result);
      if Assigned(DbgLst) then
        DbgLst.Add('FriendlyName='+Result);
    end;
  end
  else
  begin
    if Assigned(DbgLst) then
      DbgLst.Add('Cannot GetDeviceFriendlyName! ('+IntToStr(iRes)+')');

    Result := GetDevDescription(PMan, sDeviceId, DbgLst);
  end;
end;

procedure GetDeviceStorageInfo(sDeviceId, parentID: WideString; var StorageInfo: TStorageInfoArray;
  DbgLst: TStringList);
var
  PortableDev: IPortableDevice;
  content: IPortableDeviceContent;
  prop: IPortableDeviceProperties;
  prop_val: IPortableDeviceValues;
  propKeys_val: PortableDeviceApiLib_TLB._tagpropertykey;
  objectIds: IEnumPortableDeviceObjectIDs;
  objectId: PWideChar;
  fetched: Cardinal;
  propKeys: IPortableDeviceKeyCollection;
  info: TStorageInfo;
begin
  //clear...
  SetLength(StorageInfo, 0);
  try
    if ConnectToDevice(sDeviceId, PortableDev, DbgLst) then
    begin
      //read content of device
      try
        if PortableDev.Content(content) = S_OK then
        begin
          if parentID='' then
            parentID := GetFirstStorageID(PortableDev, DbgLst);

          //get content properties
          content.Properties(prop);
                                        //DEVICE
          if content.EnumObjects(0, PWideChar(parentID), nil, objectIds) = S_OK then
          begin
            objectIds.Reset;
            while objectIds.Next(1, objectId, fetched) = S_OK do    //list all storages under DEVICE
            begin
              if (fetched > 0) then
              begin
                propKeys := CreateComObject(CLSID_PortableDeviceKeyCollection) as IPortableDeviceKeyCollection;
                if VarIsClear(propKeys) then Exit;

                try
                  //add props we want to get
                  propKeys_val.fmtid := WPD_STORAGE_CAPACITY_FMTID; //CAPACITY
                  propKeys_val.pid := WPD_STORAGE_CAPACITY_PID;
                  propKeys.Add(propKeys_val);

                  propKeys_val.fmtid := WPD_STORAGE_FREE_SPACE_IN_BYTES_FMTID; //FREE
                  propKeys_val.pid := WPD_STORAGE_FREE_SPACE_IN_BYTES_PID;
                  propKeys.Add(propKeys_val);

                  //get values
                  prop.GetValues(PWideChar(objectId), propKeys, prop_val);
                  //check....
                  if not VarIsClear(prop_val) then
                  begin
                    //init info record
                    ZeroMemory(@info, SizeOf(TStorageInfo));
                    info.StorageId := String(objectId);  //keep storage id

                    propKeys_val.fmtid := WPD_STORAGE_CAPACITY_FMTID; //CAPACITY
                    propKeys_val.pid := WPD_STORAGE_CAPACITY_PID;

                    //prop_val.GetStringValue(propKeys_val, ObjVal);
                    prop_val.GetUnsignedLargeIntegerValue(propKeys_val, info.lStorageTotalSpace);
                    if Assigned(DbgLst) then
                      DbgLst.Add('WPD_STORAGE_CAPACITY ('+objectId+'): '+ IntToStr(info.lStorageTotalSpace));

                    propKeys_val.fmtid := WPD_STORAGE_FREE_SPACE_IN_BYTES_FMTID;
                    propKeys_val.pid := WPD_STORAGE_FREE_SPACE_IN_BYTES_PID;

                    prop_val.GetUnsignedLargeIntegerValue(propKeys_val, info.lStorageFreeSpace);
                    if Assigned(DbgLst) then
                      DbgLst.Add('WPD_STORAGE_FREE_SPACE_IN_BYTES ('+objectId+'): '+ IntToStr(info.lStorageFreeSpace));
                      
                    //keep 4 later
                    SetLength(StorageInfo, Length(StorageInfo)+1);
                    StorageInfo[High(StorageInfo)] := info;
                  end;
                finally

                end;
              end
              else
                Break;
            end; //while
          end;
        end;
      finally
        PortableDev.Close;
      end;
    end;
  finally
    PortableDev := nil;
  end;
end;

Open in new window


usage:
sDevId := GetDeviceId;
  if Length(sDevId) > 0 then
  begin
    GetDeviceStorageInfo(sDevId, '', StorageInfo, TStringList(Memo1.Lines));
  end;

Open in new window


Main part of code relies on older code made as result of this question...

As I test with my phone - which have two partition (internal, external) - made example which support this - so get free space for both.
0
 

Author Closing Comment

by:Michael Vlasenko
Thank you for leaving line 272. Thanks, that you did not delete it, but just commented out. I did not succeed with the GetUnsignedLargeIntegerValue, but it turned out using the GetStringValue method.
0
 
LVL 28

Expert Comment

by:Sinisa Vuk
Do you get any error with GetUnsignedLargeIntegerValue? or just return 0?
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:Michael Vlasenko
I'm can not running compilation and the error message pops up:
Types of actual and formal var parameters must be identical.
0
 
LVL 28

Expert Comment

by:Sinisa Vuk
Maybe wrong PortableDeviceApi lib. Can you drop your PortableDeviceApiLib_TLB.pas here?
0
 

Author Comment

by:Michael Vlasenko
You're right. The reason is this. I looked in PortableDeviceApiLib_TLB.pas and saw:
    function GetUnsignedLargeIntegerValue(var key: _tagpropertykey; out pValue: Largeuint): HResult; stdcall;

Open in new window

I made changes to the lines 44, 45:
      lStorageFreeSpace: Largeuint;
      lStorageTotalSpace: Largeuint;

Open in new window

After that, the compilation was successful...
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Join & Write a Comment

In this post we will learn different types of Android Layout and some basics of an Android App.
Creating a Cordova application which allow user to save to/load from his Dropbox account the application database.
This video is in connection to the article "The case of a missing mobile phone (https://www.experts-exchange.com/articles/28474/The-Case-of-a-Missing-Mobile-Phone.html)". It will help one to understand clearly the steps to track a lost android phone.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
Suggested Courses

824 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question