lib/arduino_firmata/arduino.rb in arduino_firmata-0.1.5 vs lib/arduino_firmata/arduino.rb in arduino_firmata-0.1.6
- old
+ new
@@ -1,12 +1,13 @@
module ArduinoFirmata
class Arduino
- attr_reader :version
+ attr_reader :version, :status
def initialize(serial_name, params)
+ @status = Status::CLOSE
@wait_for_data = 0
@execute_multi_byte_command = 0
@multi_byte_channel = 0
@stored_input_data = []
@parsing_sysex = false
@@ -21,29 +22,37 @@
@on_analog_changed = []
@serial = SerialPort.new(serial_name, params[:bps], params[:bit], params[:stopbit], params[:parity])
@serial.read_timeout = 3
sleep 3
+ @status = Status::OPEN
trap 'SIGHUP' do
close
+ exit
end
trap 'SIGINT' do
close
+ exit
end
trap 'SIGKILL' do
close
+ exit
end
trap 'SIGTERM' do
close
+ exit
end
+ @thread_status = false
Thread.new{
- loop do
+ @thread_status = true
+ while status == Status::OPEN do
process_input
- sleep 0.1
+ sleep 0.01
end
+ @thread_status = false
}.run
(0...6).each do |i|
write(REPORT_ANALOG | i)
write 1
@@ -51,20 +60,28 @@
(0...2).each do |i|
write(REPORT_DIGITAL | i)
write 1
end
+ write REPORT_VERSION
loop do
break if @version
sleep 0.3
end
sleep 0.5
-
end
def close
+ return if status == Status::CLOSE
+ @status = Status::CLOSE
@serial.close
+ loop do
+ if @serial.closed? and @thread_status != true
+ break
+ end
+ sleep 0.01
+ end
end
def digital_read(pin)
(@digital_input_data[pin >> 3] >> (pin & 0x07)) & 0x01 > 0
end
@@ -106,13 +123,15 @@
write(angle >> 7)
end
private
def write(cmd)
+ return if status == Status::CLOSE
@serial.write_nonblock cmd.chr
end
def read
+ return if status == Status::CLOSE
@serial.read_nonblock 9600 rescue EOFError
end
def process_input
StringIO.new(String read).bytes.each do |input_data|