Monthly Archive for February, 2010

Broadcom Bluetooth SDK Programming with Perl and Inline C++

I bought a Syba USB Bluetooth 2.0 dongle adapter from Amazon recently in an attempt to bluetooth enable my aging home PC. This adapter has a Broadcom 2045 wireless chip. If you have one of those new bluetooth enabled smartphones, you can do a lot of cool things with a bluetooth connection to your PC like synchronizing messages, tasks and contacts with Outlook, transfer files with the help of an OBEX file transfer client on your phone, play music from your phone on the PC speakers among other things.

Broadcom has published their bluetooth SDK which can be downloaded at:

http://www.broadcom.com/support/bluetooth/sdk.php

using which you can do quite a bit of bluetooth programming to control Broadcom bluetooth adapters. Since the SDK has source header files for C++ it is most natural to use C++ to call the APIs – but you don’t have to. Perl is my choice scripting language for this kind of explorations. I found that Perl has an inline CPP module that will allow you to embed C++ code snippets in your Perl program. Of course you need a C++ compiler installed on your PC to make use of this module. On Windows platform your inline  C++ code gets compiled into a DLL which will get called at run time by your Perl code.

I thought it is a cool way to do my bluetooth programming. I can write the core functionality in C++ classes and then instantiate those classes from Perl and call their methods. I use Microsoft Visual C++ 6.0 compiler. Below is the sample code for listing all bluetooth enabled devices in your PC’s neighborhood. To compile and run it you will need:

  • Microsoft Visual C++ compiler (or any other suitable C++ compiler. Modify the include and library paths accordiningly.)
  • Perl with Inline CPP Module
  • Broadcom Bluetooth SDK and (of course)
  • Bluetooth Adapter with Broadcom chip connected to your PC

Don’t forget to change the include and library paths to point to the appropriate locations in your environment. Download Perl source code here: http://infinilogix.com/downloads/btoothcpp.zip

#!/usr/bin/perl
use strict;
use warnings;
use Win32::OLE;

use Inline CPP => Config =>

LIBS => '-l"T:\Widcomm\BTW DK\SDK\Release\WidcommSdklib.lib" \
 -L"C:\Program Files\Microsoft Visual Studio\VC98\Lib"',

INC => '-I"T:\Widcomm\BTW DK\SDK\Inc"',

CCFLAGS => '-TP -LD -I"T:\Widcomm\BTW DK\SDK\Inc" \
 -nologo -GF -W3 -D_M_M68K -O1 -DWIN32 -D_CONSOLE \
 -D_AFXDLL -D_BTWLIB -DNO_STRICT -DHAVE_DES_FCRYPT \
 -DNO_HASH_SEED  -DUSE_SITECUSTOMIZE -DPERL_IMPLICIT_CONTEXT \
 -DPERL_IMPLICIT_SYS -DUSE_PERLIO -DPERL_MSVCRT_READFIX',

LDDLFLAGS => '/DLL /libpath:"C:\Perl\lib\CORE" \
 /libpath:"T:\Widcomm\BTW DK\SDK\Release" \
 /libpath:"C:\Program Files\Microsoft Visual Studio\VC98\Lib" \
 /nodefaultlib:"msvcrt.lib"',

BUILD_NOISY =>1;

use Inline CPP => <<'EOC';

//Some of the functionality below has been adapted from
//Broadcom Bluetooth SDK.
//Copyright (c) 2000-2006, Broadcom Corporation.

#include "BtIfDefinitions.h"
#include "BtIfClasses.h"
#define CHAR_0 '0'
#define CHAR_CAP_A 'A'
#define CHAR_CAP_F 'F'
#define CHAR_A 'a'
#define CHAR_F 'f'
class CDeviceInfo
{
public:
    CDeviceInfo(BD_ADDR bda, DEV_CLASS dc, BD_NAME bdn)
 {
  memcpy (bd_addr, bda, BD_ADDR_LEN);
  memcpy (dev_class, dc, DEV_CLASS_LEN);
  memcpy (bd_name, bdn, BD_NAME_LEN);

  pNext       = NULL;
  m_nServices = 0;
  m_hFtp      = 0;
  m_sSPPPort  = 0;
  m_sLAPPort  = 0;
  m_sDUNPort  = 0;
  m_sFAXPort  = 0;
 }

    CDeviceInfo *pNext;

    BD_ADDR   bd_addr;
    DEV_CLASS dev_class;
    BD_NAME   bd_name;

    int       m_nServices;
    long      m_hFtp;
 short     m_sSPPPort;
 short     m_sLAPPort;
 short     m_sDUNPort;
 short     m_sFAXPort;
};

class Test : public CBtIf
{

public:
 Test():CBtIf() { }
 ~Test() { }

 /* init() will start the device enquiry */

 char* init()
 {
  ok = 0;
  pFirstDeviceInfo = NULL;
  StartInquiry();
  return "Success";
 }

 /* Are we done with all devices in the neighborhood? */
 int Done()
 {
   return ok;
 }

 /* Get the first device in the list of devices we found */
 char* GetFirstDevice()
 {
   return pFirstDeviceInfo?(LPSTR)pFirstDeviceInfo->bd_name:NULL;
 }

 /* Get the next device in the list of devices we found */
 char* GetNextDevice()
 {
   pCurrDeviceInfo = pCurrDeviceInfo->pNext?
                         pCurrDeviceInfo->pNext:NULL;
   return pCurrDeviceInfo?
               (LPSTR)pCurrDeviceInfo->bd_name:NULL;
 }

private:
 int ok;
 CDeviceInfo *pFirstDeviceInfo;
 CDeviceInfo *pCurrDeviceInfo;

 /* Callback method that gets called when
  a device responds to our query */

  void OnDeviceResponded(BD_ADDR p_bda,
 DEV_CLASS dev_class,
 BD_NAME bd_name,
 BOOL bConnected)
  {
    CDeviceInfo *pDeviceInfo;

// Check if this is an update for an already known device
    for (pDeviceInfo = pFirstDeviceInfo;
          pDeviceInfo;
          pDeviceInfo = pDeviceInfo->pNext)
    {
      if (!memcmp (pDeviceInfo->bd_addr, p_bda, BD_ADDR_LEN))
      break;
    }

    BOOL new_item = FALSE;

//We have found a new device. Add it to our linked list.
    if (!pDeviceInfo)
    {
      new_item = TRUE;

      pDeviceInfo = new CDeviceInfo (p_bda, dev_class, bd_name);
      if (!pFirstDeviceInfo)
        pFirstDeviceInfo = pCurrDeviceInfo = pDeviceInfo;
      else
      { CDeviceInfo *p;
        for (p = pFirstDeviceInfo; p->pNext; p = p->pNext)
        ;
        p->pNext = pDeviceInfo;
      }
    }
  }

  /* Callback method that gets called when
     the query has completed */
  void OnInquiryComplete (BOOL success,
        short num_responses)
  {
    ok = 1;
  }

  /* Utility method to convert from a hex string to int */
  WORD axtoi(char *pch)
  {
    register char ch;
    register WORD n = 0;

    while((ch = *pch++) != 0)
    {
      if (isdigit(ch))
       ch -= CHAR_0;
      else if (ch >= CHAR_CAP_A && ch <= CHAR_CAP_F)
       ch += (char)(10 - CHAR_CAP_A);
      else if (ch >= CHAR_A && ch <= CHAR_F)
       ch += (char)(10 - CHAR_A);
      else
       break; //ch = (char)0;
      n = 16 * n + ch;
    }
    return n;
  }

  BOOL string2BDAddr(BD_ADDR bdAddr, char *lpbdAddrString)
  {
    if ( strlen(lpbdAddrString) != (BD_ADDR_LEN * 3 - 1))
      return FALSE;

    for (int i = 0; i<BD_ADDR_LEN; i++)
      bdAddr[i] = (char)axtoi(&lpbdAddrString[i *3]);
    return TRUE;
  }

};
EOC

my $t = new Test;

my $result = $t->init();

while (!$t->Done())
{
 Win32::OLE->SpinMessageLoop();
}

my $dev = $t->GetFirstDevice();
while($dev)
{
 print "$dev\n";
 $dev = $t->GetNextDevice();
}

Automated Dialing with Google Voice

I was able to get my Google Voice number last week. It is wonderful to be able to make free US and Canada calls with GV. The only downside being you have to first login to your GV account to use their dialer or select a contact from your Google Contacts address book. I thought it would be nice if I could dial a contact right from a spreadsheet on my PC desktop without first logging into my GV account.

To do that I created a Microsoft Excel spreadsheet which can store all my contacts. I wrote Excel VB macros to do the login and dialing using my GV account. Double clicking on any cell that contains a phone number would dial that number using my GV account.

You may download the spreadsheet from the link below. You have to have macros enabled in Excel to make use of this spreadsheet. First time you open the spreadsheet you will be prompted to enter your GV user id and password which will be stored in hidden cells for future use. So be careful not to share this spreadsheet with others. In case you don’t want to store your credentials in the spreadsheet, before you save the spreadsheet you can click the ‘Clear Credentials’ button which will clear your user id and password.

http://infinilogix.com/downloads/Contacts.xls

Disclaimer: The spreadsheet is provided as is without any warranty about its usability or performance. It has only been tested using MS Excel 2003 though it should work with other versions too. But I cannot guarantee that.

How to Control Access Restriction Rules in Tomato by a Shell Script

This week I got some time to delve deeper into the Access Restriction rules on my ASUS WL-520GU router running Tomato firmware version 1.27. I wanted to write a Bourne Shell script to turn any given Access Restriction rule on or off. Access Restriction rules are coded as pipe (|) separated strings and stored in nvram variables named rrule0, rrule1, rrule2 etc. To see what is in the first rule we can issue the following command at the shell prompt in Tomato:

nvram get rrule0

The returned string might look something like:

1|540|1140|62|||block-site.com$|0|New Rule 1

Let us take a closer look at what each of these nine fields separated by pipe (|) means.

The first field shows whether the rule is currently enabled or disabled – 1 means enabled, 0 means disabled.

The second field gives the start time, i.e. the time to start applying this rule, in minutes elapsed since midnight. In the above example start time is 540 meaning the router should enforce this rule starting at 9am.  The third field is the end time, i.e. the time to stop applying this rule, again coded the same way as the start time. Both the second and third fields will be -1 if you select the option ‘All Day’ in the control panel.

The fourth field is the days of week on which the rule should be applied and is coded in binary – 1 for Sunday, 2 for Monday, 4 for Tuesday and so on. For multiple days, add the corresponding numbers for each day. In the above example the fourth field is 62 which is equal to 2+4+8+16+32 – meaning the rule should be active on Mon, Tue, Wed, Thu, and Fri i.e. only on week days. If you had checked the option Everyday this value would be 127.

The fifth field shows the ip or mac address range in your network for which the rule should be applied – in case you don’t want all the computers on the network to be affected by this rule. The sixth field has the Port/Application information coded in it i.e. which ports numbers, protocols, layer 7 and p2p applications should be blocked by this rule.

The seventh field contains the domains or URLs you want to block and it partially supports regular expressions. In the above example, domain names ending in block-site.com are blocked. The eighth field stores as a binary coded value if ActiveX, Flash or Java need to  be blocked – 1 for ActiveX, 2 for Flash and 4 for Java. And finally the ninth field stores the name that you gave to this rule.

Now with this basic understanding about how the Access Restriction rules in Tomato work, we can write shell scripts to control the rules. Below is the script I wrote to enable or disable a rule. Two values are passed on the command line – the rule number and either a 0 or a 1 to disable or enable the service respectively. If you have jffs enabled in control panel you can copy the script under jffs directory and schedule it to run, if you want, as a cron job.

#!/bin/sh

#Wait if any service is currently being restarted

nvstat=`nvram get action_service`
while [ "$nvstat" != "" ]; do
echo
done

#Assume we are going to enable the rule
enable=1

#Was a 1 or 0 passed on the command line?
[ "$2" != "" ] && enable=$2

#Get the current setting of the rule.
#Rule number is passed as the first parameter on the command line.
rr=`nvram get rrule$1`

#Set the first field to the value in variable $enable
rr=$(echo $rr|sed "s/^./$enable/")
echo $rr

#Replace the old rule with the new value
nvram set rrule$1="$rr"

#Prepare to restart the service by killing the init process
nvram set action_service=restrict-restart

#kill the init process
kill -USR1 1

#Wait for the service to restart
while [ "`nvram get action_service`" == "restrict-restart" ]; do
echo
done