Posts Tagged ‘OBEX’

Managed wrapper for the BTObex library

More open-source goodness. A managed wrapper for the BTObex library. The source includes the BTObexWrapper.h header file which contains the wrapper code (shown below) and a compiled managed DLL, for those who just want to include it into their projects and use it ASAP.

// Managed C++/CLI wrapper for the BTObex Library
// Include the BTObex library files into the project (BTOBEX sub-directory) and compile as a managed DLL

/*
    Copyright (c) 2010, Avishkar Autar
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
        * Redistributions of source code must retain the above copyright
         notice, this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright
         notice, this list of conditions and the following disclaimer in the
         documentation and/or other materials provided with the distribution.
        * Neither the name of the <organization> nor the
         names of its contributors may be used to endorse or promote products
         derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/



#pragma once

#pragma
unmanaged
    #ifndef WIN32_LEAN_AND_MEAN
    
#define WIN32_LEAN_AND_MEAN
    
#endif

    #include <winsock2.h>
    #include <Ws2bth.h>
    #include <BluetoothAPIs.h>

    #pragma comment(lib, "ws2_32.lib")

    
#include <windows.h>
    #include <cguid.h>

    #include "BTOBEX/BTSock.h"
    #include "BTOBEX/OBEX.h"
    #include "BTOBEX/BTOBEX.h"

#pragma managed

using
namespace System;
using namespace System::Runtime::InteropServices;

namespace BTObex
{
    
public ref class BluetoothDeviceProfile
    {
        
public:
            System::String^        name;
            System::String^        address;
// (address):port, typically repeat of device address
            int                    port;
    };

    
public ref class BluetoothDevice
    {
        
public:
            System::String^                            name;
            System::String^                            localAddress;
            System::String^                            deviceAddress;
            System::Collections::ArrayList^         supportedProfiles;

            
virtual System::String^ ToString() override
            {
                
return name;
            }
    };

    
public ref class Progress
    {
        
public:
            System::IntPtr^        current;
            System::IntPtr^        total;
    };

    
public ref class BTObexFileIO
    {
        
protected:
            BTOBEX::Session* btSession;
            BTOBEX::Progress* opProgress;

            
wchar_t* MarshalStringToCStr(System::String^ str)
            {
                
wchar_t* ret = new wchar_t[str->Length+1];

                
for(int i=0; i<str->Length; i++)
                    ret[i] = str[i];

                ret[str->Length] = 0;

                
return ret;
            }

            
void DeleteMarshaledCStr(wchar_t* str)
            {
                
delete [] str;
                str = 0;
            }

        
public:
            BTObexFileIO() : btSession(0)
            {
                opProgress =
new BTOBEX::Progress();
            }

            ~BTObexFileIO()
            {
                
delete opProgress;
            }

            
void QueryDevices(System::Collections::ArrayList^ devices, bool queryOnlyOBEXFileTransferProfiles)
            {
                BTSock::Session* btSession =
new BTSock::Session();

                std::vector<BTSock::Device*> btDevices;
                
if(queryOnlyOBEXFileTransferProfiles)
                {
                    btSession->DeviceQueryObject()->PerformQuery(btDevices, OBEXFileTransferServiceClass_UUID);
                }
                
else
                {
                    btSession->DeviceQueryObject()->PerformQuery(btDevices);
                }

                
for(int i=0; i<(int)btDevices.size(); i++)
                {
                    BluetoothDevice^ dev =
gcnew BluetoothDevice();
                    dev->name =
gcnew System::String( btDevices[i]->name.c_str() );
                    dev->localAddress =
gcnew System::String( btDevices[i]->localAddress.c_str() );
                    dev->deviceAddress =
gcnew System::String( btDevices[i]->deviceAddress.c_str() );
                    dev->supportedProfiles =
gcnew System::Collections::ArrayList();

                    
for(int j=0; j<(int)btDevices[i]->supportedProfiles.size(); j++)
                    {
                        BluetoothDeviceProfile^ profile =
gcnew BluetoothDeviceProfile();
                        profile->name =
gcnew System::String( btDevices[i]->supportedProfiles[j]->name.c_str() );
                        profile->address =
gcnew System::String( btDevices[i]->supportedProfiles[j]->address.c_str() );
                        profile->port = btDevices[i]->supportedProfiles[j]->port;

                        dev->supportedProfiles->Add(profile);
                    }

                    devices->Add(dev);
                }

                
delete btSession;
            }
                

            
bool Connect(System::String^ address, int port, int packetSize)
            {
                
wchar_t* addr = MarshalStringToCStr(address);

                btSession =
new BTOBEX::Session();
                
bool connOk = btSession->Connect(addr, port, packetSize);

                DeleteMarshaledCStr(addr);

                
return connOk;
            }

            
void Disconnect()
            {
                btSession->Disconnect();
                
delete btSession;
            }

            
bool SetPathBackward()
            {
                
return btSession->SetPathBackward();
            }

            
bool SetPathForward(System::String^ folderName)
            {
                
wchar_t* folderNameCStr = MarshalStringToCStr(folderName);

                
bool setOk = btSession->SetPathForward(folderNameCStr);

                DeleteMarshaledCStr(folderNameCStr);

                
return setOk;
            }

            
bool GetFolderListing(System::Collections::ArrayList^ result)
            {
                OBEX::NakedVector<OBEX::byte> utf8Bytes;
                
bool getOk = btSession->GetFolderListing(utf8Bytes);

                
if(getOk)
                {
                    
for(int i=0; i<utf8Bytes.Count(); i++)
                    {
                        result->Add(
gcnew System::Byte(utf8Bytes[i]) );
                    }
                }

                
return getOk;
            }

            
bool DeleteObject(System::String^ objName)
            {
                
wchar_t* objNameCStr = MarshalStringToCStr(objName);

                
bool delOk = btSession->DeleteObject(objNameCStr);

                DeleteMarshaledCStr(objNameCStr);

                
return delOk;
            }

            
bool PutFile(System::String^ remoteFileName, System::String^ localFilePath, Progress^ progress)
            {
                progress->current =
gcnew System::IntPtr( &opProgress->current );
                progress->total =
gcnew System::IntPtr( &opProgress->total );

                
wchar_t* remoteFileNameCStr = MarshalStringToCStr(remoteFileName);
                
wchar_t* localFilePathCStr = MarshalStringToCStr(localFilePath);

                
bool putOk = btSession->PutFile(remoteFileNameCStr, localFilePathCStr, opProgress);

                DeleteMarshaledCStr(remoteFileNameCStr);
                DeleteMarshaledCStr(localFilePathCStr);

                
return putOk;
            }

            
bool GetFile(System::String^ remoteFileName, System::String^ localFilePath, Progress^ progress)
            {
                progress->current =
gcnew System::IntPtr( &opProgress->current );
                progress->total =
gcnew System::IntPtr( &opProgress->total );
                
                
wchar_t* remoteFileNameCStr = MarshalStringToCStr(remoteFileName);
                
wchar_t* localFilePathCStr = MarshalStringToCStr(localFilePath);

                
bool getOk = btSession->GetFile(remoteFileNameCStr, localFilePathCStr, opProgress);

                DeleteMarshaledCStr(remoteFileNameCStr);
                DeleteMarshaledCStr(localFilePathCStr);

                
return getOk;
            }
    };
}

BTObex Library

I’ve released the BTObex library (I’m playing around with using bitbucket for hosting the code) I wrote a few months ago which is a Win32 bluetooth library that allows for file transfers with devices that support the Bluetooth File Transfer Profile. This library uses the MS Bluetooth stack (included w/ Win XP SP2 and later).

For those wondering what OBEX is and what Bluetooth has to do with it: Bluetooth devices support a set of profiles, one of which is the File Transfer Profile. However, the FTP itself doesn’t really take care of anything much, once the connection is established, actual file transfers are handled by the OBEX protocol.

Bluetooth FTP stack

OBEX was originally designed for transfers across infrared devices and is not handled by the Bluetooth SIG, its specs are controlled by the IrDA. Now, aside from being a useless bit of trivia, this is important because while the Bluetooth SIG publishes a ton of documentation, the IrDA does not. The documentation on the specs for OBEX requires signing up for IrDA membership and paying some hefty membership fees. That said I was able to get my hands on a copy of the OBEX documentation here. How long that remains up and the legality of me reading it is up in the air. Charging for documentation is a shitty practice by the IrDA and I can only hope that the Bluetooth SIG ditches OBEX for something better in the future.

There’s little-to-no documentation for the library, so I’m going to use this blog post to provide some examples.

Link with necessary libraries

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "irprops.lib")

Include header file

#include "BTOBEX.h"

The entire library simply consists of a bunch of header files. BTOBEX.h will include everything else.

Query all Bluetooth devices

std::vector<BTSock::Device*> btDevices;
BTSock::Session* btSession =
new BTSock::Session();
btSession->DeviceQueryObject()->PerformQuery(btDevices);
delete btSession;

The vector btDevices will contain an entry for each device paired with the system. Look at BTSockDevice.h to see the structure of the BTSock::Device class.

Make a connection

BTOBEX::Session* btObexSession = new BTOBEX::Session();
bool connOk = btObexSession->Connect(devAddress, port, 8192);

devAddress is the deviceAddress member of a BTSock::Device object.
port is the port number for a given profile, for the file transfer profile it’s 5. If you can’t connect on the port, it likely means that the profile is not support by the device.

Set the current directory on the device

bool setPathOk = btObexSession->SetPathForward(L"my_picture");

OBEX only allows you to move forward into a subdirectory (SetPathForward) or jump back to a parent directory (SetPathForward).

Get a directory listing

OBEX::NakedVector<OBEX::byte> xmlBytes;
btObexSession->GetFolderListing(xmlBytes);

The bytes are UTF-8 bytes that form a XML document (an XML parser is not part of the library). The XML doc will have folder and/or file elements, each with a required name attribute. Directory listings are one of the dumbest aspects of the OBEX protocol; whereas everything else is binary and well-defined, directory listings are verbose and text-based (remember, this is a low bandwidth connection) and have no required attribute aside from name. Other attributes (e.g. size) may be present, but they’re optional, meaning, in general, you’ll likely avoid them in order to develop for the lowest common denominator.

Get a file from the device

bool getOk = btObexSession->GetFile(L"remote.jpg", L"local.jpg", new BTOBEX::Progress());

The last parameter is optional, you can pass a BTOBEX::Progress object if you wish to poll the progress of the transfer from another thread.

Put a file on the device

bool putOk = btObexSession->PutFile(L"remote.jpg", L"local.jpg", new BTOBEX::Progress());

The last parameter is optional, you can pass a BTOBEX::Progress object if you wish to poll the progress of the transfer from another thread.

Disconnect and clean up

btObexSession->Disconnect();
delete btObexSession;

Have fun! The code is released under the BSD license. Any comments or bug reports are greatly appreciated.

Edit (11/22/2020): Update link to point to GitHub repo.