diff --git a/lib/biju.rb b/lib/biju.rb index 89ad972..a7a08b6 100644 --- a/lib/biju.rb +++ b/lib/biju.rb @@ -1,2 +1,3 @@ require 'biju/version' +require "biju/modem" require "biju/sms" diff --git a/lib/biju/modem.rb b/lib/biju/modem.rb new file mode 100644 index 0000000..f72ccbe --- /dev/null +++ b/lib/biju/modem.rb @@ -0,0 +1,48 @@ +require 'serialport' +require_relative 'sms' + +module Biju + class Modem + def initialize(options={}) + raise Exception.new("Port is required") unless options[:port] + @connection = connection(options) + cmd("AT") + cmd("AT+CMGF=1") + end + + def connection(options) + port = options.delete(:port) + SerialPort.new(port, default_options.merge!(options)) + end + + def close + @connection.close + end + + def messages + sms = cmd("AT+CMGL=\"ALL\"") + msgs = sms.scan(/\+CMGL\:\s*?(\d+)\,.*?\,\"(.+?)\"\,.*?\,\"(.+?)\".*?\n(.*)/) + return nil unless msgs + msgs.collect!{ |msg| Biju::Sms.new(:id => msg[0], :phone_number => msg[1], :datetime => msg[2], :message => msg[3].chomp) } + end + + private + def default_options + { :baud => 9600, :data_bits => 8, :stop_bits => 1, :parity => SerialPort::NONE } + end + + def cmd(cmd) + @connection.write(cmd + "\r") + wait + end + + def wait + buffer = '' + while IO.select([@connection], [], [], 0.25) + chr = @connection.getc.chr; + buffer += chr + end + buffer + end + end +end diff --git a/spec/biju/modem_spec.rb b/spec/biju/modem_spec.rb new file mode 100644 index 0000000..6da75ce --- /dev/null +++ b/spec/biju/modem_spec.rb @@ -0,0 +1,10 @@ +require_relative '../spec_helper' + +# TODO: Fix missing tests SOON +describe Biju::Modem do + describe ".new" do + it "should raise an Exception without port option" do + lambda { Biju::Modem.new }.must_raise Exception + end + end +end \ No newline at end of file