bin/ligo-sample
#!/usr/bin/env ruby
# -*- coding: utf-8; fill-column: 80 -*-
require 'ligo'
id = {
manufacturer: 'Ligo',
model: 'VirtualAccessory',
description: 'PC acts as an accessory!',
version: '0.1',
uri: 'http://blog.renaud.io',
serial: '3678000012345678'
}
log_file = 'ligo-sample.log'
log_file_path = case Ligo.os
when :windows
ENV['TEMP']
else # :unix, :linux and :macosx
'/tmp'
end
Ligo::Logging.configure_logger_output("#{log_file_path}/#{log_file}")
ctx = Ligo::Context.new
acc = Ligo::Accessory.new(id)
dev = ctx.devices.first
unless dev
puts 'No device found ⇒ Exit'
exit
end
if dev.attach_accessory(acc)
begin
dev.process do |handle|
puts <<-eof
The selected android device should now ask to switch to Accessory Mode.
The log file is /tmp/ligo-sample.log.
Once you have accepted: type some strings and send them to the selected device by hitting Enter
(use Ctrl-C to quit):
eof
reader_t = nil
writer_t = nil
mutex = Mutex.new
reader_t = Thread.new do
loop do
res = nil
mutex.synchronize do
begin
output_string = dev.read(1024, 200)
unless output_string.nil?
puts "IN -- String received: #{output_string}"
end
rescue LIBUSB::ERROR_TIMEOUT
# do nothing and proceed
end
end
# get some time to write data if any
sleep 0.2
end
end
writer_t = Thread.new do
loop do
if s = gets
mutex.synchronize do
bytes_sent = dev.send(s)
if bytes_sent == s.bytesize
puts "OUT -- String '#{s.chomp}' of size #{bytes_sent} bytes successfully sent"
else
puts "OUT -- Error / String '#{s.chomp}' of size #{bytes_sent} bytes not successfully sent"
end
end
end
end
end
reader_t.abort_on_exception = true
writer_t.abort_on_exception = true
reader_t.join
writer_t.join
end
rescue SystemExit, Interrupt => e
puts "#{e.message} ⇒ Exit"
Thread.list.each { |t| t.exit }
end
end