Bluetooth ScreenLock

Published 19 August 07 10:58 PM | Coding4Fun 
Bluetooth ScreenLock is a sample application built on top of the Bluetooth managed wrappers that are included in the Coding4Fun Developer Toolkit.
Clarity Consulting, Inc.

Difficulty: Easy
Time Required: 1-3 hours
Cost: Free
Software: Visual Studio 2008 Express Editions Beta 2, Coding4Fun Developer Toolkit (Bluetooth assemblies)
Hardware: Bluetooth-enabled laptop and phone.
Download: Download

    The Coding4Fun Developer Kit that was released to CodePlex last month contains a bunch of neat libraries and components for jumpstarting development against some of the new features of Vista. Included in the kit is a managed wrapper around Bluetooth communication that is designed to run in non-mobile environments – something that has not previously been widely available. With most newer laptops shipping with Bluetooth radios, and the proliferation of Bluetooth devices and receivers, I looked forward to trying this out. To get familiar with the managed wrappers, I built a simple screen locking application that I call Bluetooth Screenlock. The Bluetooth ScreenLock application runs on your PC, connects to your phone, and when it detects that you’ve walked out of range, locks your workstation. Using the Bluetooth wrappers included in the Coding4Fun Developer Toolkit makes this pretty simple.

    Bluetooth Profiles

    The managed Bluetooth wrapper classes that are part of the Coding4Fun Developer Kit (C4F Kit) contain libraries for connecting to three different Bluetooth profiles: Serial Port, File Transfer and Object Push. A profile is a standardized interface specification that devices comply to in order to communicate with each other. For the Bluetooth ScreenLock application I used the Serial Port profile to establish a connection and then send heartbeat messages across the Bluetooth channel periodically. If any heartbeat were to fail, the program will lock the user’s workstation.

    Discovery and Pairing

    Discovery is the process of detecting nearby Bluetooth devices and potentially asking them to enumerate their supported services. In order to discover a device and enumerate its services, one of two things must happen: The phone must be set to discovery mode, which enables any other Bluetooth device to see it, or the two devices must be paired. Note for security reasons you generally don’t want to leave your phone set up as discoverable.

    Pairing is the process of establishing a trust relationship between two devices. Pairing usually involves the exchange of a key pair – a pin-like series of digits that must be entered on both devices before the trust relationship is established. In order to use the Bluetooth ScreenLock application you must pair your phone to your PC. You can start this from the PC, or from your phone. In Vista you can start the pairing process by opening the Bluetooth Devices utility and clicking the Add button on the Devices tab (see Figure 1).  Note that I built and tested the application with a Motorola Q smartphone.

    Figure 1 - The Bluetooth Devices utility in Vista

    Once you’ve paired your phone to your PC, you can use the application. I decided to build the application as a Windows Forms application, but it just as easily could have been a Windows Service set to start automatically. The form is simple – just a combo box listing nearby devices and a button to enable the ScreenLock feature. It would be a pretty easy exercise to configure the application to automatically enable itself at Windows startup.

    Figure 2 - The ScreenLock window

    Connecting to a device

    The code for the ScreenLock application uses just two of the functions in the C4F toolkit – DiscoverDeviceByName and DiscoverServicesByType. DiscoverDeviceByName is used to get an instance of a Device, which is a managed class exposed through the C4F.DevKit.Bluetooth.DeviceAndServiceDiscovery assembly.

    C#

    public bool DiscoverDevice(string deviceName)
    {
        bool returnValue = false;
        try
        {
            DeviceServicesManager _manager = new DeviceServicesManager();
            SelectedDevice = _manager.DiscoverDeviceByName(deviceName);
            if (SelectedDevice != null)
            {
                returnValue = true;
            }
        }
        catch (Exception ex)
        {
            throw new Exception("An unexpected error was raised during device discovery." + Environment.NewLine + ex.Message);
        }
        return returnValue;
    }
    

    VB.Net

    Public Function DiscoverDevice(ByVal deviceName As String) As Boolean
        Dim returnValue As Boolean = False
        Try
            Dim _manager As DeviceServicesManager = New DeviceServicesManager()
            SelectedDevice = _manager.DiscoverDeviceByName(deviceName)
            If Not SelectedDevice Is Nothing Then
                returnValue = True
            End If
        Catch ex As Exception
            Throw New Exception("An unexpected error was raised during device discovery." & Environment.NewLine & ex.Message)
        End Try
        Return returnValue
    End Function
     

    Once you have an instance of a Device, you can get a handle to the serial port service by calling DiscoverServicesByType.  After that you could connect directly to the service on the device:

    C#

    public bool Connect()
    {
        bool returnValue = false;
    
        List<RemoteService> serviceList = _manager.DiscoverServicesByType(SelectedDevice, ServiceType.SerialPortProfile);
        RemoteService remoteService = null;
    
        try
        {
            remoteService = serviceList[0];
            _stream = remoteService.Connect();
            _connectedService = remoteService;
            returnValue = true;
        }
        catch (ServiceConnectionException servEx)
        {
            throw new Exception("An error occurred while trying to connect to " + remoteService.Name + Environment.NewLine + "Error Details: " + servEx.Message);
        }
        catch
        {
            throw;
        }
        return returnValue;
    }
    VB.Net
    Public Function Connect() As Boolean
        Dim returnValue As Boolean = False
    
        Dim serviceList As List(Of RemoteService) = _manager.DiscoverServicesByType(SelectedDevice, ServiceType.SerialPortProfile)
        Dim remoteService As RemoteService = Nothing
    
        Try
            remoteService = serviceList(0)
            _stream = remoteService.Connect()
            _connectedService = remoteService
            returnValue = True
        Catch servEx As ServiceConnectionException
            Throw New Exception("An error occurred while trying to connect to " & remoteService.Name & Environment.NewLine & "Error Details: " & servEx.Message)
        Catch
            Throw
        End Try
        Return returnValue
    End Function

    Bluetooth devices are recognized by their 48-bit address, but most devices use a friendly name to identify themselves. The friendly name can usually be changed by the owner of the device. The ScreenLock application allows the user to specify the friendly name to use to connect, or to search for paired devices (in the case where they don’t know the device name). To search for nearby devices the app uses the DiscoverAllDevices function with returns a list of Device objects. Since we only need the device names to populate our combo box, we use a simple LINQ query to extract the names and project them into a List of type string:

    C#

    public List<string> DiscoverDevices()
    {
        var q =
            from device in _manager.DiscoverAllDevices()
            select device.Name;
        return q.ToList<string>();
    }

    VB.Net

    Public Function DiscoverDevices() as List(Of String)
       Dim result As List(Of String) = New List(Of String)
       For Each d As Device in _manager.DiscoverAllDevices()
          result.Add(d.Name)
       Next
    
       Return result
    End Function

    Once a device is connected to the serial port profile, the application simply uses a timer to periodically write a byte of text to the port. If the transmission fails for any reason, the application will lock the workstation by calling the LockWorkstation API call from user32.dll.

    C#

    public bool Ping()
    {
        bool returnValue = true;
    
        if (!object.Equals(_stream,null)) {
            try
            {
                _stream.WriteByte(1);
            }
            catch (Exception ex)
            {
                returnValue = false;
            }
        }
        return returnValue;
    }

    VB.Net

    Public Function Ping() As Boolean
        Dim returnValue As Boolean = True
    
        If (Not Object.Equals(_stream,Nothing)) Then
            Try
                _stream.WriteByte(1)
            Catch ex As Exception
                returnValue = False
            End Try
        End If
        Return returnValue
    End Function
    
    

    The excellent Coding4Fun Developer Toolkit hides all of the complexity of setting up socket connections using the Bluetooth protocol and exposes a few simple but useful functions for interacting with Bluetooth devices from managed code. If you’re interested in writing Bluetooth apps in managed code, I suggest you take a look at it – it includes several detailed samples. In addition to the Bluetooth wrapper, there several other cool samples, such as those showing you how to write your own Preview Handlers and interact with Windows Vista Contacts.

    Filed under: ,

    Comment Notification

    If you would like to receive an email when updates are made to this post, please register here

    Subscribe to this post's comments using RSS

    Comments

    # MSDN Blog Postings » Bluetooth ScreenLock said on August 20, 2007 4:28 AM:

    PingBack from http://msdnrss.thecoderblogs.com/2007/08/20/bluetooth-screenlock/

    # Monkey see, monkey build - The mumblings of Clint Rutkas » Finally a good use for bluetooth other than wireless communication said on August 20, 2007 6:51 PM:

    PingBack from http://betterthaneveryone.com/?p=602

    # blue tooth device - Bluetooth ScreenLock said on August 22, 2007 2:47 PM:

    PingBack from http://blue-tooth-device.maildevice.com/post/83834/

    # device to phone - Bluetooth ScreenLock said on August 22, 2007 3:50 PM:

    PingBack from http://device-to-phone.maildevice.com/post/84293/

    # PC World - Master Bluetooth Device Pairing Hassles | News | said on August 26, 2007 9:12 PM:

    PingBack from http://bluetooth.portal-resources.com/news/pc-world-master-bluetooth-device-pairing-hassles

    # Geoff @ UVM - Coding projects said on August 29, 2007 10:26 AM:

    PingBack from http://www.uvm.edu/~gcd/?p=32

    # T.H. said on September 24, 2007 8:13 AM:

    Nice piece of code!

    I am not able to install the VS 2008 (since I'm using a corporate laptop) but instead I removed the Linq stuff so I can compile this with VS 2005. I don't really know anything about Linq but I just assumed it comes with VS 2008. Here's my DiscoverDevices function:

    List<string> devices = new List<string>();

    foreach (Device device in _manager.DiscoverAllDevices())

    {

       devices.Add(device.Name);

    }

    return devices;

    Also, my brand new Nokia E65 does not support the serial port profile on Bluetooth so I added a few lines of code to check for dial-up networking profile (ServiceType.DialupNetworking).

    # joao rico » Blog Archive » Bluetooth ScreenLock said on September 28, 2007 1:40 PM:

    PingBack from http://pessoa.fct.unl.pt/jfr17488/weblog/2007/09/28/bluetooth-screenlock/

    # Monkey See, Monkey Build said on November 4, 2007 12:33 AM:

    Finally a good use for bluetooth other than wireless communication

    # Mitch Green said on December 4, 2007 12:15 AM:

    I cant get this working in the RTM edition of MS VB.NET 2008 Express Edition. DeviceServicesManager is not defined.

    # Fernando Lopez Jr. said on December 9, 2007 6:08 AM:

    Mitch:

    change it to BluetoothDeviceServicesManager... it compiles ok... but i still get no reponse or anything. i'm using a kensington bluetooth adapter.

    # Jason said on December 13, 2007 5:46 AM:

    This program compiles and runs fine, however it discovers no devices. I use windows discover and find devices no problem.

    Anyone else have this problem? How did you resolve?

    # Gusti said on January 23, 2008 2:16 AM:

    @Jason: the same here :(

    I have an HP laptop and default HP .... Bluetooth Driver installed. Maybe we must use the Microsoft Bluetooth Drivers that are installed by XP SP2? But I have no ideea how to do it.

    # Gusti said on January 23, 2008 4:30 AM:

    If anyone has the some probleme, here is a link that can help you: http://h20000.www2.hp.com/bizsupport/TechSupport/Document.jsp?lang=en&cc=us&objectID=c00711848&jumpid=reg_R1002_USEN

    # Bill K said on February 7, 2008 9:36 PM:

    I have an HP notebook and the above made my device work with the Microsoft Bluetooth stack so now this app can discover the device.

    But I can not find any services available where before I switched to the MS stack I hade several services.

    After this I switched to an MSI StarKey usb bluetooth device and I get the same results.

    My OS is XP. Any ideas on how to get a service to show up. THe OS bluetooth icon says I have a dial up modem service but I can not find it with the app.

    # Fer said on April 7, 2008 5:05 PM:

    does this works with the toshiba bluetooth stack? how can i get it to work?

    thank you.

    # Coding4Fun said on April 7, 2008 5:35 PM:

    @Fer:  It should, did you try?

    # Ion said on April 11, 2008 6:13 AM:

    I've heard about Rohos Logon Key program. Its not just a primitive desktop locker but complette authentication solution by using Bluetooth enabled phone. Works with MS bt stack and also bluesoleil.

    # DR said on April 24, 2008 1:38 PM:

    What about using the Moto Q?  Can it still connect using vb.net...2005?

    Thanks in advance for any help/suggestions...

    # DR said on April 24, 2008 1:43 PM:

    Nevermind my last question....I was re-reading and saw that it 'was' tested/written specifically for the Moto Q.

    # Coding4Fun said on April 24, 2008 2:59 PM:

    @DR:  Shouldn't matter, this would work on a Blackjack also.  The UI may need to shift depending on the screen res but code would stay the same.

    # Blue said on May 10, 2008 5:08 AM:

    Where would I go to find out how to add code to do the following...

    1. Have it start when windows starts and auto configure

    2. Have it reenter the password when I return

    I have no idea how this thing works, but I love it so far!

    Thank you

    # Blue said on May 10, 2008 5:32 AM:

    Also I just upgraded from the beta and now the source wont compile.

    Warning 1 Namespace or type specified in the Imports 'C4F.DevKit.Bluetooth.DeviceAndServiceDiscovery' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.

    # elango said on June 17, 2008 2:01 AM:

    i need a sample vb.net windows desktop application for the basic operation through Bluetooth(pc 2 pc  or pc to mobile)....its urgent,pls help me , mail me to elan78in@yahoo.com

    # Coding4Fun said on June 20, 2008 7:58 PM:

    @elango:  Try the Coding4Fun Dev kit on CodePlex

    # RobV said on July 3, 2008 4:48 PM:

    Sadly experiencing the same problem as Blue; any thoughts?

    # Coding4Fun said on July 8, 2008 4:58 PM:

    @RobV and @Blue, this is one of the problems when using other people's APIs.  If an API gets updated or removed, an existing application could break.

    Should be a pretty easy fix.  Andy Konkol has an article that should outline how to update this with his BlueBoss detector.

    http://blogs.msdn.com/coding4fun/archive/2008/06/26/8658548.aspx

    # rbelknap said on August 8, 2008 6:17 PM:

    Has anyone had success using the IOGEAR GBU421 usb/bluetooth adapter. I can get the program to compile, but it does not see any devices.

    # Jack said on September 10, 2008 4:56 PM:

    No problems after installing the C4F framework and changing "DeviceServicesManager" to "BluetoothDeviceServicesManager". Although, if you're using the toshiba stack, you may have issues; I solved the problem by removing the "Bluetooth Stack by Toshiba for Windows" (or whatever it's called) from add/remove programs, and then letting windows find and install the drivers. Using an LG Dare on a Toshiba 350 bluetooth card inside of a dell laptop.

    # charles justice said on May 6, 2009 7:29 PM:

    i love all your works and article,but looka this problem i have,am in final year and my project supervisor gave me topic to work on "design and implementation of a bluetooth communication software" and i have tried to design d interface and the source code but to no avail could you please help me out cos i have just 2weeks please save.thanks.you can send through this e-mail charlesjustice65@yahoo.com. am counting on u.

    # charles justice said on May 6, 2009 7:50 PM:

    i love all your works and article,but looka this problem i have,am in final year and my project supervisor gave me topic to work on "design and implementation of a bluetooth communication software" and i have tried to design d interface and the source code but to no avail could you please help me out cos i have just 2weeks please save.thanks.you can send through this e-mail charlesjustice65@yahoo.com. am counting on u.

    # Coding4Fun said on May 11, 2009 11:58 AM:

    @Charles Justice: Not sure what your issue is?  Did you try http://www.codeplex.com/C4FDevKit for the bluetooth part by itself?

    Leave a Comment

    (required) 
    (optional)
    (required) 
    Page view tracker