Commits

Anonymous committed 30adce4

Began adding support for device discovery

  • Participants
  • Parent commits 5f01c44

Comments (0)

Files changed (2)

examples/locate-device.py

+from jaraco.nxt import locator
+import logging
+logging.basicConfig(level=logging.DEBUG)
+locator.find_brick()

jaraco/nxt/__init__.py

 __author__='Jason R. Coombs <jaraco@jaraco.com>'
 __svnauthor__='$Author$'[9:-2]
 
+import logging
+
 import serial
-import struct
-import time
 
-import messages
+from jaraco.nxt import messages
+
+try:
+	import bluetooth
+except ImportError:
+	class bluetooth:
+		class BluetoothSocket: pass
+	bluetooth.discover_devices = lambda *args, **kwargs: []
+
+log = logging.getLogger(__name__)
 
 def add_options(parser):
 	parser.add_option("-p", "--port")
 
-class Connection(serial.Serial):
+class Device:
+	def receive(self):
+		'Receive a message from the NXT'
+		return messages.Message.read(self)
+
+	def send(self, message):
+		"Send a message to the NXT"
+		self.write(str(message))
+
+class Connection(serial.Serial, Device):
 	"""
 	A low-level connection to an NXT brick
 	
 	Example usage:
 	conn = Connection('COM3')
 	"""
-	def receive(self):
-		'Receive a message from the NXT'
-		return messages.Message.read(self)
 
-	def send(self, message):
-		"Send a message to the NXT"
-		self.write(str(message))
+class BluetoothDevice(Device, bluetooth.BluetoothSocket):
+	port = 1
+
+	def __init__(self, host):
+		bluetooth.BluetoothSocket.__init__(self, bluetooth.RFCOMM)
+		hp = (host, self.port)
+		self.connect(hp)
+
+	def read(self, nbytes):
+		return self.recv(nbytes)
+
+	def write(self, bytes):
+		self.send(bytes)
+
+class DeviceNotFoundException(Exception): pass
+
+class Locator:
+	def find_brick(self):
+		try:
+			return next(self.find_bricks())
+		except StopIteration:
+			raise DeviceNotFoundException()
+
+	def find_bricks(self):
+		for candidate in self.find_candidates():
+			try:
+				candidate.send(messages.GetBatteryLevel())
+				resp = candidate.receive()
+				yield candidate
+			except BaseException:
+				pass
+
+	def find_candidates(self):
+		for host, name in bluetooth.discover_devices(lookup_names=True):
+			log.debug('Attempting to connect to bluetooth host %s (%s)', host, name)
+			try:
+				yield BluetoothDevice(host)
+			except IOError:
+				pass
+		for serial_port in range(10):
+			log.debug('Attempting to connect to serial port %d', serial_port)
+			try:
+				yield Connection(serial_port)
+			except serial.serialutil.SerialException:
+				pass
+
+locator = Locator()