USBSerialからSMSを送信します(ruby2.4.0)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'serialport' | |
class AtCommand | |
def self.fin_proc | |
proc { @sp.close } | |
end | |
def initialize | |
@sp = SerialPort.new('/dev/sms') | |
@sp.set_modem_params(115_200, 8, 1, 0) | |
ObjectSpace.define_finalizer(self, self.class.fin_proc) | |
end | |
def ok? | |
sleep(0.5) | |
line = @sp.readpartial(1024).delete("\r").split("\n") | |
puts "<< #{line}" | |
line[-1] == 'OK' | |
end | |
def prompt? | |
sleep(0.5) | |
line = @sp.readpartial(1024).delete("\r").split("\n") | |
line[-1] == '> ' | |
end | |
def sent? | |
sleep(5) | |
line = @sp.readpartial(1024).delete("\r").split("\n") | |
puts "<< #{line}" | |
line[1] != 'ERROR' | |
end | |
def send(msg) | |
@sp.write(msg) | |
puts ">> #{msg}" | |
end | |
def pack(msg) | |
cpmsg = '' | |
msg.each_codepoint { |cp| cpmsg << format('%04x', cp) } | |
cpmsg | |
end | |
end | |
def main | |
phone_number = '' | |
ac = AtCommand.new | |
ac.send("AT+CFUN=1\n") | |
return unless ac.ok? | |
ac.send("AT+CMGF=1\n") | |
return unless ac.ok? | |
ac.send("AT+CSMP=1,167,0,8\n") | |
return unless ac.ok? | |
ac.send("AT+CSCS=\"UCS2\"\n") | |
return unless ac.ok? | |
ac.send("AT+CMGS=\"#{phone_number}\"\n") | |
return unless ac.prompt? | |
msg = ac.pack('あ' * 63) | |
ac.send(msg + 26.chr) | |
return unless ac.sent? | |
end | |
main if $PROGRAM_NAME == __FILE__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment