Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 14 total  RSS 

Using Bluetooth to control Asterisk calls.

Redirect an Asterisk call

   1  
   2      de61.old_status = get_status(de61.file) # found is either true or false
   3      de61.old_location = get_location(de61.file) # location is either 'at home', 'gone to bed' or 'asleep'
   4      
   5      while count < 1
   6  
   7        puts 'old status : ' + de61.old_status.to_s
   8        de61.new_status = check_device(de61.id, de61.name)
   9        puts 'new_status: ' + de61.new_status.to_s
  10  
  11  
  12        if de61.new_status and de61.old_status
  13          if de61.old_status == false
  14            puts 'connecting to the bluetooth device ...'
  15            Thread.new{`rfcomm connect 0 #{de61.id}`}
  16            sleep 12
  17          end
  18          de61.new_location = check_location(de61.id) 
  19        end
  20        
  21        puts 'old_location: ' + de61.old_location.to_s
  22        puts 'new_location: ' + de61.new_location.to_s
  23        update_status(de61.project, de61.new_status, de61.new_location) if ((de61.old_status != de61.new_status.to_s) or (de61.old_location != de61.new_location)) 
  24          
  25        mystatus = ''
  26        
  27        if  (not de61.old_status == de61.new_status) then
  28          if (de61.new_status.to_s == 'true') then
  29              mystatus = ' has entered the building'
  30              callto('SIP/line1')
  31          elsif  (de61.new_status == false) then
  32            mystatus = ' has left the building'
  33            callto('SIP/07736668666@sipgate')
  34          end
  35          puts 'updating in or out the building'
  36          ms = MyStatus.new(mystatus)
  37        elsif (de61.old_location.to_s != de61.new_location.to_s)
  38          if de61.old_location.match(/sleep/) and de61.new_location.match(/home|bed/) and not old_mystatus.match(/awoken/) then
  39            mystatus = ' has awoken'
  40          elsif (de61.old_location.match(/home|bed/)) and de61.new_location.match(/sleep/) 
  41            mystatus = ' has gone to sleep'           
  42          elsif (de61.old_location.match(/home/)) and de61.new_location.match(/bed/) 
  43            mystatus = ' has gone to bed'
  44          elsif de61.old_location.match(/bed/) and de61.new_location.match(/home/) 
  45            mystatus = ' has got out of bed'
  46          end
  47          puts 'updating home location'
  48          ms = MyStatus.new(mystatus) if mystatus != ''
  49        end
  50  
  51  
  52        de61.old_location = de61.new_location
  53        de61.new_location = 'at home'
  54        de61.old_status = de61.new_status
  55        old_mystatus = mystatus
  56        sleep 7
  57      end
  58    end
  59      
  60    def callto(dialstring)
  61      file = File.new('/etc/asterisk/ruby/call-to.txt','w')
  62      file.puts 'Dial(' + dialstring + ')'
  63      file.close
  64    end


file: extensions.conf
   1  
   2  exten => 5168666,n,ReadFile(dialplan1=/etc/asterisk/ruby/call-to.txt,130)
   3  exten => 5168666,n,Exec(${dialplan1})

Using Ruby to detect Bluetooth proximity

This Ruby script uses the hcitool and rfcomm to detect the proximity of a bluetooth enabled mobile phone. The signal strength in this script will return a value from 0 to 10, 0 is near and 10 is far, otherwise if there is no connection it will keep on trying.

   1  
   2  deviceid = '00:12:D1:E6:57:BE' 
   3  range = ''
   4  count = 0
   5  while count < 1
   6    # assuming the bt device is already connected get the signal strength value.
   7    range = `hcitool rssi #{deviceid}`.chomp
   8    if  range.length > 0
   9      puts range[/\w+$/]
  10    else
  11      puts 'connecting to the bluetooth device ...'
  12      Thread.new{`rfcomm connect 0 #{deviceid}`}
  13    end
  14  	
  15    sleep 7
  16  end
  17  


warning (11-Jul-2008): I've found Thread.new to be causing a problem, it appears not to remove itself from the process queue when it is no longer required.

Simple Bluetooth Proximity

Following on from my earlier investigation into bluetooth proximity, I wanted something which returned a value which could be used to determine distance. The output from hcitool rssi ranges from 0 for close object down to -10 for far away objects.

   1  
   2  rfcomm connect 0 00:12:D1:E6:57:BE

   1  
   2  hcitool rssi 00:12:D1:E6:57:BE


Proximity Results:
-4 .. 0 : Bedroom - nearest to my bed
-4 .. -6 : Hallway
-8 .. -9 : Livingroom - on the computer desk
-9 .. -10 : Livingroom - nearest to the window

Detect the presence of a Bluetooth device

This example shows how to check for the presence of a mobile phone. The code was based on the article 'Implementing Bluetooth Proximity Detection with Asterisk, Part II' http://snipr.com/1vvi5 [nerdvittles.com]

   1  
   2  #!/usr/bin/ruby
   3  #file: whereib.rb
   4  
   5  deviceid = '00:0E:6D:29:38:EB'
   6  devicename = 'Nokia 6600'
   7  
   8  count = 0
   9  while count < 1
  10    if `hcitool name #{deviceid}`.chomp == devicename 
  11      puts devicename + ' IN RANGE'
  12      puts Time.now
  13    else
  14      puts devicename + ' OUT OF RANGE'
  15      puts Time.now
  16    end
  17    sleep 7
  18  end  

PyS60: Bluetooth GPS polling class

Threaded approach for reading NMEA data from a bluetooth GPS.

   1  
   2  import thread, socket
   3  
   4  class BTGPSPoller(object):
   5  	def __init__(self, address):
   6  		address, services = socket.bt_discover(address)
   7  		self.target = (address, services.values()[0])
   8  		self.active = True
   9  		self.connected = False
  10  		self.lock = thread.allocate_lock()
  11  		self.sentances = list()
  12  		
  13  	def connect(self):
  14  		if not self.connected:
  15  			thread.start_new_thread(self.run, ())
  16  
  17  	def run(self):
  18  		print "BTGPSPoller thread activated"
  19  		try:
  20  			conn = socket.socket(socket.AF_BT, socket.SOCK_STREAM)
  21  			conn.connect(self.target)
  22  			self.connected = True
  23  		except:
  24  			print "Unable to connect"
  25  		
  26  		if self.connected:
  27  			try:
  28  				to_gps = conn.makefile("r", 0)
  29  			except:
  30  				print "Failure calling conn.makefile()"
  31  			while self.active:
  32  				#e32.ao_sleep(1)
  33  				msg = None
  34  				try:
  35  					msg = to_gps.readline()
  36  					if not msg == None and msg.startswith("$GPGGA"):
  37  						gps_data = msg.split(",")
  38  						if not gps_data[2] == "":
  39  							self.lock.acquire()
  40  							self.sentances.append(msg)
  41  							if len(self.sentances) > 10:
  42  								self.sentances.pop(0)
  43  							self.lock.release()
  44  				except:
  45  					self.active = False
  46  
  47  			try:
  48  				to_gps.close()
  49  				conn.close()
  50  				self.connected = False
  51  				print "Closed and disconnected"
  52  			except:
  53  				self.connected = False
  54  				print "Unable to close"
  55  
  56  	def disconnect(self):
  57  		self.active = False
  58  		print "Disconnecting from GPS"
  59  
  60  	def getSentances(self):
  61  		self.lock.acquire()
  62  		l = self.sentances[:]
  63  		self.lock.release()
  64  		return l

help!.. please

// description of your code here

   1  
   2  sorry! what does it mean "Chattando" midlet ? [J2ME - Search Service Bluetooth: protected Chattando midlet;]

J2ME - Create Service Bluetooth

// Create Service Bluetooth

   1  
   2  import javax.bluetooth.DiscoveryAgent;
   3  import javax.bluetooth.LocalDevice;
   4  import javax.microedition.io.Connector;
   5  import javax.microedition.io.StreamConnection;
   6  import javax.microedition.io.StreamConnectionNotifier;
   7  
   8  public class ServerChat
   9  {
  10  	private static final String CHATTANDO_UUID = "A1A2A3A4A5A6A7A8A9A0B1B2B3B4B5B6";
  11  	private static final String CHATTANDO_SERVICE = "Chattando";
  12  	
  13  	private boolean isReady = false;
  14  	
  15  	private StreamConnection stream_connection;
  16  	private StreamConnectionNotifier stream_connection_notifier;
  17  	
  18  	public ServerChat()
  19  	{
  20  		startServerChatBluetooth();
  21  	}
  22  	
  23  	// Apre il servizio per la Chat
  24  	public void startServerChatBluetooth()
  25  	{
  26  		new Thread()
  27  		{
  28  			public void run()
  29  			{
  30  				try
  31  				{
  32  					LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);
  33  				}
  34  				catch(Exception error)
  35  				{
  36  					error.printStackTrace();
  37  				}
  38  				
  39  				try
  40  				{
  41  					stream_connection_notifier = (StreamConnectionNotifier) Connector.open("btspp://localhost:" + CHATTANDO_UUID + ";name=" + CHATTANDO_SERVICE);
  42  				}
  43  				catch(Exception error)
  44  				{
  45  					error.printStackTrace();
  46  				}
  47  				
  48  				stopServerChatBluetooth();
  49  				
  50  				// Mette in ascolto il Server della Chat
  51  				isReady = true;
  52  				
  53  				try
  54  				{
  55  					while(isReady)
  56  					{
  57  						System.out.println("Sono in ascolto...");
  58  						
  59  						stream_connection = stream_connection_notifier.acceptAndOpen();
  60  						
  61  						System.out.println("Client Connected");
  62  					}
  63  				}
  64  				catch(Exception error)
  65  				{
  66  					error.printStackTrace();
  67  				}
  68  			}
  69  			
  70  		}.start();
  71  	}
  72  
  73  	// Chiude il servizio per la Chat
  74  	public void stopServerChatBluetooth()
  75  	{
  76  		if(isReady)
  77  		{
  78  			isReady = false;
  79  			
  80  			try
  81  			{
  82  				stream_connection_notifier.close();
  83  			}
  84  			catch(Exception error)
  85  			{
  86  				error.printStackTrace();
  87  			}
  88  		}
  89  	}
  90  }

J2ME - Search Service Bluetooth

// Example Search Service Bluetooth

   1  
   2  import java.util.Vector;
   3  
   4  import javax.bluetooth.DeviceClass;
   5  import javax.bluetooth.DiscoveryAgent;
   6  import javax.bluetooth.DiscoveryListener;
   7  import javax.bluetooth.LocalDevice;
   8  import javax.bluetooth.RemoteDevice;
   9  import javax.bluetooth.ServiceRecord;
  10  import javax.bluetooth.UUID;
  11  
  12  public class ClientChat implements DiscoveryListener
  13  {
  14  	private static final String CHATTANDO_UUID = "A1A2A3A4A5A6A7A8A9A0B1B2B3B4B5B6";
  15  	private static final String CHATTANDO_SERVICE = "Chattando";
  16  
  17  	protected Chattando midlet;
  18  	
  19  	private boolean searchDone = false;
  20  	
  21  	private DiscoveryAgent discovery_agent;
  22  	
  23  	private Vector remote_device;
  24  	private Vector device_found;
  25  	
  26  	public ClientChat(Chattando midlet)
  27  	{
  28  		this.midlet = midlet;
  29  		
  30  		startScanBluetoothDevices();
  31  	}
  32  	
  33  	// Avvia la ricerca dei dispositivi Bluetooth
  34  	public void startScanBluetoothDevices()
  35  	{
  36  		try
  37  		{
  38  			remote_device = new Vector();
  39  			device_found = new Vector();
  40  			
  41  			discovery_agent = LocalDevice.getLocalDevice().getDiscoveryAgent();
  42  			discovery_agent.startInquiry(DiscoveryAgent.GIAC, this);
  43  		}
  44  		catch(Exception error)
  45  		{
  46  			error.printStackTrace();
  47  		}
  48  	}
  49  	
  50  	// Stoppa la ricerca dei dispositivi Bluetooth
  51  	public void stopScanBluetoothDevices()
  52  	{
  53  		discovery_agent.cancelInquiry(this);
  54  	}
  55  
  56  	public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) 
  57  	{
  58  		// Aggiungo il dispositivo solo se e' un computer (0x0100) o un cellulare (0x0200)
  59  		if(cod.getMajorDeviceClass() == 0x0100 || cod.getMajorDeviceClass() == 0x0200)
  60  			remote_device.addElement(btDevice);
  61  	}
  62  
  63  	public void inquiryCompleted(int discType)
  64  	{
  65  		switch(discType)
  66  		{
  67  			case DiscoveryListener.INQUIRY_COMPLETED:
  68  														System.out.println("Device Search Completed");
  69  														
  70  														break;
  71  				
  72  			case DiscoveryListener.INQUIRY_ERROR:
  73  														System.out.println("Device Search Error");
  74  														
  75  														break;
  76  				
  77  			case DiscoveryListener.INQUIRY_TERMINATED:
  78  														System.out.println("Device Search Terminated");
  79  														
  80  														break;
  81  		}
  82  		
  83  		try
  84  		{
  85  			for(int i=0, cnt=remote_device.size(); i<cnt; i++)
  86  			{
  87  				discovery_agent.searchServices(new int[]{ 0x0100, 0x0200 }, new UUID[]{ new UUID(0x0003), new UUID(CHATTANDO_UUID, false) }, (RemoteDevice) remote_device.elementAt(i), this);
  88  				waitForSearchDone();
  89  			}
  90  		}
  91  		catch(Exception error)
  92  		{
  93  			error.printStackTrace();
  94  		}
  95  	}
  96  
  97  	// Aspetta che la ricerca dei servizi per il dispositivo sia terminata
  98  	private void waitForSearchDone()
  99  	{
 100  		searchDone = false;
 101  		
 102  		try
 103  		{
 104  			while(!searchDone)
 105  			{
 106  				synchronized(this)
 107  				{
 108  					this.wait();
 109  				}
 110  			}
 111  		}
 112  		catch(Exception error)
 113  		{
 114  			
 115  		}
 116  	}
 117  	
 118  	public void serviceSearchCompleted(int transID, int respCode)
 119  	{
 120  		switch(respCode)
 121  		{
 122  			case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
 123  																		System.out.println("Service Search Completed");
 124  																		
 125  																		break;
 126  				
 127  			case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
 128  																		System.out.println("Service Search Device not Reachable");
 129  																		
 130  																		break;
 131  				
 132  			case DiscoveryListener.SERVICE_SEARCH_ERROR:
 133  																		System.out.println("Service Search Error");
 134  																		
 135  																		break;
 136  				
 137  			case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
 138  																		System.out.println("Service Search No Records");
 139  																		
 140  																		break;
 141  				
 142  			case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
 143  																		System.out.println("Service Search Terminated");
 144  																		
 145  																		break;
 146  		}
 147  		
 148  		searchDone = true;
 149  		
 150  		// Risveglia il processo in attesa del completamento della ricerca dei servizi per un dispositivo
 151  		synchronized(this)
 152  		{
 153  			this.notifyAll();
 154  		}
 155  	}
 156  
 157  	public void servicesDiscovered(int transID, ServiceRecord[] servRecord)
 158  	{
 159  		for(int i=0, cnt=servRecord.length; i<cnt; i++)
 160  		{
 161  			if(((String) servRecord[i].getAttributeValue(0x0100).getValue()).equalsIgnoreCase(CHATTANDO_SERVICE))
 162  			{
 163  				device_found.addElement(servRecord[i].getHostDevice());
 164  			}
 165  		}
 166  	}
 167  }

Python - SendSMS over BT and AT

// Send SMS over Bluetooth (AT Command)

   1  
   2  import bluetooth
   3  
   4  sockfd = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
   5  sockfd.connect(('00:00:00:00:00:00', 1)) # BT Address
   6  sockfd.send('ATZ\r')
   7  sockfd.send('AT+CMGF=1\r')
   8  sockfd.send('AT+CSCA="+393359609600"\r') # Client TIM ITA
   9  sockfd.send('AT+CMGS="+39xxxxxxxxxx"\r') # TO PhoneNumber
  10  sockfd.send('Messaggio da mandare...\n')
  11  sockfd.send(chr(26)) # CTRL+Z
  12  sockfd.close()

PyS60 - SendFile

// Send File over Bluetooth

   1  
   2  from appuifw import *
   3  from e32socket import *
   4  
   5  try:
   6      phone = bt_obex_discover()
   7      file = query(u'File Selection', 'text')
   8      bt_obex_send_file(phone[0], phone[1].values()[0], file)
   9      note(u'File Sent')
  10  except Exception, error:
  11      note(unicode(error), 'error')
« Newer Snippets
Older Snippets »
Showing 1-10 of 14 total  RSS