Class: IprogSms::SMS

Inherits:
Object
  • Object
show all
Defined in:
lib/iprog_sms/sms.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(port_str = "/dev/ttyUSB0") ⇒ SMS

Returns a new instance of SMS.



10
11
12
13
14
# File 'lib/iprog_sms/sms.rb', line 10

def initialize(port_str = "/dev/ttyUSB0")
  @baud_rate = 9600
  @port_str = port_str  # Use the passed port, or default to "/dev/ttyUSB0"
  @error_message = nil   # Initialize error message
end

Instance Attribute Details

#error_messageObject (readonly)

Returns the value of attribute error_message.



8
9
10
# File 'lib/iprog_sms/sms.rb', line 8

def error_message
  @error_message
end

Instance Method Details

#connected?Boolean

Returns:

  • (Boolean)


62
63
64
65
66
67
68
69
70
71
72
# File 'lib/iprog_sms/sms.rb', line 62

def connected?
  begin
    serial = Serial.new(@port_str, @baud_rate)
    response = send_at_command(serial, "AT")
    serial.close
    response.include?("OK") # Check if the response contains "OK"
  rescue StandardError => e
    @error_message = "Error checking connection: #{e.message}"
    false
  end
end

#send_sms(phone_number, message) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/iprog_sms/sms.rb', line 16

def send_sms(phone_number, message)
  @error_message = nil   # Reset error message before sending

  if connected?
    begin
      # Open the serial connection
      serial = Serial.new(@port_str, @baud_rate)
      result_status = false

      # Set SMS to text mode with a shorter delay
      send_at_command(serial, "AT+CMGF=1", 3)

      # Specify the recipient phone number
      response = send_at_command(serial, "AT+CMGS=\"#{phone_number}\"", 3)
      unless response.include?(">")
        @error_message = "Failed to specify recipient. Response: #{response}"
        result_status  = false
      end

      # Send the actual SMS message, followed by Ctrl+Z (ASCII 26)
      response = send_at_command(serial, "#{message}\x1A", 5)
      if response.include?("+CMGS")
        puts "SMS successfully sent to #{phone_number}."
        result_status = true
      elsif response.include?("+CMS ERROR")
        error_code = response.match(/\+CMS ERROR: (\d+)/)[1]
        @error_message = "Failed to send SMS. Error code: #{error_code}"
        result_status  = false
      else
        @error_message = "Unexpected response while sending SMS: #{response}"
        result_status  = false
      end

      serial.close

      result_status
    rescue StandardError => e
      @error_message = "Error while sending SMS: #{e.message}"
      false
    end
  else
    @error_message = "SIM800C is not connected!"
    false
  end
end