Class: XBee::XBee

Inherits:
Object
  • Object
show all
Includes:
SemanticLogger::Loggable
Defined in:
lib/xbee/xbee.rb

Overview

Either specify the port and serial parameters

xbee = XBee::Xbee.new device_path: '/dev/ttyUSB0', rate: 9600

or pass in a SerialPort like object

xbee = XBee::XBee.new io: some_serial_mockup_for_testing

Instance Method Summary collapse

Constructor Details

#initialize(device_path: '/dev/ttyUSB0', rate: 115200, io: nil) ⇒ XBee

Returns a new instance of XBee.



37
38
39
40
41
42
43
# File 'lib/xbee/xbee.rb', line 37

def initialize(device_path: '/dev/ttyUSB0', rate: 115200, io: nil)
	@device_path = device_path
	@rate = rate
	@io = io
	@connected = false
	@logger = nil
end

Instance Method Details

#closeObject



57
58
59
60
# File 'lib/xbee/xbee.rb', line 57

def close
	@io.close if @io
	@connected = false
end

#connected?Boolean Also known as: open?

Returns:

  • (Boolean)


63
64
65
# File 'lib/xbee/xbee.rb', line 63

def connected?
	@connected
end

#io=(io) ⇒ Object



105
106
107
# File 'lib/xbee/xbee.rb', line 105

def io=(io)
	@io = io
end

#openObject



46
47
48
49
50
51
52
53
54
# File 'lib/xbee/xbee.rb', line 46

def open
	@io ||= SerialPort.new @device_path, @rate
	@io_input = Enumerator.new do |y|
		loop do
			y.yield @io.readbyte
		end
	end
	@connected = true
end

#read_frameObject



100
101
102
# File 'lib/xbee/xbee.rb', line 100

def read_frame
	Frames::Frame.from_packet read_packet
end

#read_packetObject



93
94
95
96
97
# File 'lib/xbee/xbee.rb', line 93

def read_packet
	Packet.from_byte_enum(@io_input).tap do |packet|
		logger.trace 'Packet received.', bytes: packet.bytes
	end
end

#write_frame(frame) ⇒ Object



75
76
77
78
79
80
81
82
83
# File 'lib/xbee/xbee.rb', line 75

def write_frame(frame)
	if frame.packet
		# TODO: Is it right to assume the packet is in sync with the frame?
		write_packet frame.packet
	else
		packet = frame.to_packet
		write_packet packet
	end
end

#write_packet(packet) ⇒ Object



69
70
71
72
# File 'lib/xbee/xbee.rb', line 69

def write_packet(packet)
	@io.write packet.bytes_escaped.pack('C*').force_encoding('ascii')
	@io.flush
end

#write_request(request) ⇒ Object



86
87
88
89
90
# File 'lib/xbee/xbee.rb', line 86

def write_request(request)
	logger.measure_trace('Packet sent.', payload: { bytes: request.packet.bytes }) do
		write_packet request.packet
	end
end