Commits

Jason R. Coombs committed bf43cc1

Fixed read_input example. Fixes #1.

Comments (0)

Files changed (3)

examples/read_input.py

 """
 This example demonstrates how one might read sensor values from the brick.
-
-Caution: this module has not been tested. Please report your experience
-with it.
 """
 
+import sys
+
 from jaraco.nxt import Connection
-from jaraco.nxt.messages import GetInputValues
+from jaraco.nxt import messages
 from jaraco.nxt import locator
 
 dev = locator.find_brick()
 port = 1
 # send the GetInputValues message, which returns a
 #  jaraco.nxt.messages.InputValues reply
-input_values = dev.send(GetInputValues(port))
-# print each of the fields
-for field in input_value.fields:
-	value = getattr(input_values, field)
-	print("%(field)s:\t%(value)s" % vars())
+dev.send(messages.SetInputMode(
+	1,
+	messages.SensorType.switch,
+	messages.SensorMode.boolean,
+))
+
+# print out the field names once
+print ', '.join(field[:4] for field in messages.InputValues.fields)
+
+def query_status():
+	# query for the input values and re-write the line
+	dev.send(messages.GetInputValues(port))
+	input_res = dev.receive()
+	# print each of the fields
+	values = ', '.join('%4d' % getattr(input_res, field) for field in input_res.fields)
+	# carriage return but no line feed so we write over the previous line
+	sys.stdout.write('\r')
+	sys.stdout.write(values)
+
+try:
+	while True: query_status()
+except KeyboardInterrupt:
+	sys.stdout.write('\n')

jaraco/nxt/_enum.py

 	@classmethod
 	def keys(cls):
 		return cls.dictionary().keys()
-		
+
 	@classmethod
 	def values(cls):
 		return cls.dictionary().values()
 	angle_steps = 0xE0
 	slope_mask = 0x1F
 	mode_mask = 0xE0
-	
+
+class InputPort(int):
+	"""
+	Input ports are numbered from 0 internally and from 1 externally, so
+	model this disparity.
+
+	>>> x = InputPort(1)
+	>>> x
+	InputPort(1)
+	>>> x + 10
+	10
+	>>> InputPort(x)
+	InputPort(1)
+	"""
+	def __new__(cls, val):
+		adjusted_val = val if isinstance(val, InputPort) else val-1
+		return int.__new__(cls, adjusted_val)
+
+	def __init__(self, val):
+		assert 0 <= val <= 3, "InputPort must be between 1 and 4"
+
+	def __repr__(self):
+		class_name = self.__class__.__name__
+		val_1 = self + 1
+		return '%(class_name)s(%(val_1)s)' % vars()

jaraco/nxt/messages.py

 	structure = 'BBB'
 
 	def validate_settings(self):
-		assert self.port in range(4)
+		self.port = InputPort(self.port)
 		assert self.type in SensorType.values()
 		assert self.mode in SensorMode.values()
 
 	structure = 'B'
 
 	def validate_settings(self):
-		assert self.port in InputPort.values()
+		self.port = InputPort(self.port)
 
 class GetInputValues(Command):
 	command = 0x7
 	structure = 'B'
 
 	def validate_settings(self):
-		assert self.port in InputPort.values()
+		self.port = InputPort(self.port)
 
 class GetVersion(Command):
 	expected_reply = Message