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 11 total  RSS 

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]

#!/usr/bin/ruby
#file: whereib.rb

deviceid = '00:0E:6D:29:38:EB'
devicename = 'Nokia 6600'

count = 0
while count < 1
  if `hcitool name #{deviceid}`.chomp == devicename 
    puts devicename + ' IN RANGE'
    puts Time.now
  else
    puts devicename + ' OUT OF RANGE'
    puts Time.now
  end
  sleep 7
end  

PyS60: Bluetooth GPS polling class

Threaded approach for reading NMEA data from a bluetooth GPS.

import thread, socket

class BTGPSPoller(object):
	def __init__(self, address):
		address, services = socket.bt_discover(address)
		self.target = (address, services.values()[0])
		self.active = True
		self.connected = False
		self.lock = thread.allocate_lock()
		self.sentances = list()
		
	def connect(self):
		if not self.connected:
			thread.start_new_thread(self.run, ())

	def run(self):
		print "BTGPSPoller thread activated"
		try:
			conn = socket.socket(socket.AF_BT, socket.SOCK_STREAM)
			conn.connect(self.target)
			self.connected = True
		except:
			print "Unable to connect"
		
		if self.connected:
			try:
				to_gps = conn.makefile("r", 0)
			except:
				print "Failure calling conn.makefile()"
			while self.active:
				#e32.ao_sleep(1)
				msg = None
				try:
					msg = to_gps.readline()
					if not msg == None and msg.startswith("$GPGGA"):
						gps_data = msg.split(",")
						if not gps_data[2] == "":
							self.lock.acquire()
							self.sentances.append(msg)
							if len(self.sentances) > 10:
								self.sentances.pop(0)
							self.lock.release()
				except:
					self.active = False

			try:
				to_gps.close()
				conn.close()
				self.connected = False
				print "Closed and disconnected"
			except:
				self.connected = False
				print "Unable to close"

	def disconnect(self):
		self.active = False
		print "Disconnecting from GPS"

	def getSentances(self):
		self.lock.acquire()
		l = self.sentances[:]
		self.lock.release()
		return l

help!.. please

// description of your code here

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

J2ME - Create Service Bluetooth

// Create Service Bluetooth

import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class ServerChat
{
	private static final String CHATTANDO_UUID = "A1A2A3A4A5A6A7A8A9A0B1B2B3B4B5B6";
	private static final String CHATTANDO_SERVICE = "Chattando";
	
	private boolean isReady = false;
	
	private StreamConnection stream_connection;
	private StreamConnectionNotifier stream_connection_notifier;
	
	public ServerChat()
	{
		startServerChatBluetooth();
	}
	
	// Apre il servizio per la Chat
	public void startServerChatBluetooth()
	{
		new Thread()
		{
			public void run()
			{
				try
				{
					LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);
				}
				catch(Exception error)
				{
					error.printStackTrace();
				}
				
				try
				{
					stream_connection_notifier = (StreamConnectionNotifier) Connector.open("btspp://localhost:" + CHATTANDO_UUID + ";name=" + CHATTANDO_SERVICE);
				}
				catch(Exception error)
				{
					error.printStackTrace();
				}
				
				stopServerChatBluetooth();
				
				// Mette in ascolto il Server della Chat
				isReady = true;
				
				try
				{
					while(isReady)
					{
						System.out.println("Sono in ascolto...");
						
						stream_connection = stream_connection_notifier.acceptAndOpen();
						
						System.out.println("Client Connected");
					}
				}
				catch(Exception error)
				{
					error.printStackTrace();
				}
			}
			
		}.start();
	}

	// Chiude il servizio per la Chat
	public void stopServerChatBluetooth()
	{
		if(isReady)
		{
			isReady = false;
			
			try
			{
				stream_connection_notifier.close();
			}
			catch(Exception error)
			{
				error.printStackTrace();
			}
		}
	}
}

J2ME - Search Service Bluetooth

// Example Search Service Bluetooth

import java.util.Vector;

import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;

public class ClientChat implements DiscoveryListener
{
	private static final String CHATTANDO_UUID = "A1A2A3A4A5A6A7A8A9A0B1B2B3B4B5B6";
	private static final String CHATTANDO_SERVICE = "Chattando";

	protected Chattando midlet;
	
	private boolean searchDone = false;
	
	private DiscoveryAgent discovery_agent;
	
	private Vector remote_device;
	private Vector device_found;
	
	public ClientChat(Chattando midlet)
	{
		this.midlet = midlet;
		
		startScanBluetoothDevices();
	}
	
	// Avvia la ricerca dei dispositivi Bluetooth
	public void startScanBluetoothDevices()
	{
		try
		{
			remote_device = new Vector();
			device_found = new Vector();
			
			discovery_agent = LocalDevice.getLocalDevice().getDiscoveryAgent();
			discovery_agent.startInquiry(DiscoveryAgent.GIAC, this);
		}
		catch(Exception error)
		{
			error.printStackTrace();
		}
	}
	
	// Stoppa la ricerca dei dispositivi Bluetooth
	public void stopScanBluetoothDevices()
	{
		discovery_agent.cancelInquiry(this);
	}

	public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) 
	{
		// Aggiungo il dispositivo solo se e' un computer (0x0100) o un cellulare (0x0200)
		if(cod.getMajorDeviceClass() == 0x0100 || cod.getMajorDeviceClass() == 0x0200)
			remote_device.addElement(btDevice);
	}

	public void inquiryCompleted(int discType)
	{
		switch(discType)
		{
			case DiscoveryListener.INQUIRY_COMPLETED:
														System.out.println("Device Search Completed");
														
														break;
				
			case DiscoveryListener.INQUIRY_ERROR:
														System.out.println("Device Search Error");
														
														break;
				
			case DiscoveryListener.INQUIRY_TERMINATED:
														System.out.println("Device Search Terminated");
														
														break;
		}
		
		try
		{
			for(int i=0, cnt=remote_device.size(); i<cnt; i++)
			{
				discovery_agent.searchServices(new int[]{ 0x0100, 0x0200 }, new UUID[]{ new UUID(0x0003), new UUID(CHATTANDO_UUID, false) }, (RemoteDevice) remote_device.elementAt(i), this);
				waitForSearchDone();
			}
		}
		catch(Exception error)
		{
			error.printStackTrace();
		}
	}

	// Aspetta che la ricerca dei servizi per il dispositivo sia terminata
	private void waitForSearchDone()
	{
		searchDone = false;
		
		try
		{
			while(!searchDone)
			{
				synchronized(this)
				{
					this.wait();
				}
			}
		}
		catch(Exception error)
		{
			
		}
	}
	
	public void serviceSearchCompleted(int transID, int respCode)
	{
		switch(respCode)
		{
			case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
																		System.out.println("Service Search Completed");
																		
																		break;
				
			case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
																		System.out.println("Service Search Device not Reachable");
																		
																		break;
				
			case DiscoveryListener.SERVICE_SEARCH_ERROR:
																		System.out.println("Service Search Error");
																		
																		break;
				
			case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
																		System.out.println("Service Search No Records");
																		
																		break;
				
			case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
																		System.out.println("Service Search Terminated");
																		
																		break;
		}
		
		searchDone = true;
		
		// Risveglia il processo in attesa del completamento della ricerca dei servizi per un dispositivo
		synchronized(this)
		{
			this.notifyAll();
		}
	}

	public void servicesDiscovered(int transID, ServiceRecord[] servRecord)
	{
		for(int i=0, cnt=servRecord.length; i<cnt; i++)
		{
			if(((String) servRecord[i].getAttributeValue(0x0100).getValue()).equalsIgnoreCase(CHATTANDO_SERVICE))
			{
				device_found.addElement(servRecord[i].getHostDevice());
			}
		}
	}
}

Python - SendSMS over BT and AT

// Send SMS over Bluetooth (AT Command)

import bluetooth

sockfd = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sockfd.connect(('00:00:00:00:00:00', 1)) # BT Address
sockfd.send('ATZ\r')
sockfd.send('AT+CMGF=1\r')
sockfd.send('AT+CSCA="+393359609600"\r') # Client TIM ITA
sockfd.send('AT+CMGS="+39xxxxxxxxxx"\r') # TO PhoneNumber
sockfd.send('Messaggio da mandare...\n')
sockfd.send(chr(26)) # CTRL+Z
sockfd.close()

PyS60 - SendFile

// Send File over Bluetooth

from appuifw import *
from e32socket import *

try:
    phone = bt_obex_discover()
    file = query(u'File Selection', 'text')
    bt_obex_send_file(phone[0], phone[1].values()[0], file)
    note(u'File Sent')
except Exception, error:
    note(unicode(error), 'error')

bluetooth port in linux

To find out the bluetooth port
hcitool inq

Finding a bluetooth device with pybluez

Last time, I show how to use pys60 to discover
bluetooth devices. Here's another bluetooth
snippet, but this time it use pybluez (BT on Linux).
import bluetooth

target_name = "My Phone"
target_address = None

nearby_devices = bluetooth.discover_devices()

for bdaddr in nearby_devices:
    if target_name == bluetooth.lookup_name( bdaddr ):
        target_address = bdaddr
        break

if target_address is not None:
    print "found target bluetooth device with address ", target_address
else:
    print "could not find target bluetooth device nearby"

Taken from Albert Huang's exellent pybluez tutorial.

Discover bluetooth devices around you

Pys60 has good bluetooth support from the beginning.
However, to discover another device, it require you to
interact with the app, choosing a device from the list.
PDIS has a library that help you list all devices silently.
# need to install these 2 modules from PDIS first
import aosocketnativenew
from aosocket.symbian.bt_device_discoverer import *

def callback(error, devices, cb_param=None):
    for address, name in devices:      
        print "Found: ", name, address
# You can get more data by importing socket and try 
# bt_discover(address) or bt_obex_discover(address)
# see details in official pys60 doc on socket module

lister = BtDeviceLister()
lister.discover_all(callback, None)

I summarize the code above from thejamo's example here.
His code is more complete with error checking.
« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS