我创建了一个获取串行数据的 Ruby 脚本,如果它以某些字符开头,则打印字符串(SMS),将字符串插入文件,解析字符串,然后将解析的数据插入 MySql 数据库。如果我用一个示例测试字符串代替串行数据,那么包括循环在内的一切都可以正常工作(包括在测试中插入数据库后的十秒延迟)当我使用串行数据时,打印和文件附加工作正常,但是没有插入任何内容进入数据库。数据库表创建成功。我的生产代码如下:
require "rubygems"
require "serialport"
require "data_mapper"
#params for serial port
port_str = "/dev/ttyACM0"
baud_rate = 19200
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
#Connect to mysql database
DataMapper.setup(:default, {
:adapter => 'mysql',
:host => 'localhost',
:database => 'Kourarau',
:username => 'root',
:password => 'xxxxxxx'
})
class StnA
include DataMapper::Resource
property :id, Serial, :key => true
property :datetime, DateTime
property :stna_kW, Integer
property :total_kW, Integer
property :stna_kVAr, Integer
property :total_kVAr, Integer
property :tailrace, Integer
property :lo_pond, Integer
property :up_pond, Integer
property :mode, String
property :pen_a_press, Integer
property :pen_b_press, Integer
property :volt_A, Integer
property :stat_A, String
property :surge, Integer
property :needle_a1, Integer
property :needle_b1, Integer
property :needle_a2, Integer
property :needle_b2, Integer
end
DataMapper.finalize
DataMapper.auto_upgrade!
sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
loop do
sp_char = sp.gets
if sp_char.start_with?("Time")
printf("%s", sp_char)
open('statusA.current', 'a') { |f|
f.puts(sp_char)
}
status_ar = sp_char.split (',')
time_split = status_ar[0].split(' ') #required to split time and Station A information
stna_kW = time_split[1].tr('^0-9', '')
stna_kVAr = status_ar[1].tr('^0-9-', '')
total_kW = status_ar[2].tr('^0-9', '')
total_kVAr = status_ar[3].tr('^0-9-', '')
tailrace = status_ar[4].tr('^0-9-', '')
lo_pond = status_ar[5].tr('^0-9-', '')
up_pond = status_ar[6].tr('^0-9-', '')
mode = status_ar[7][4,1]
pen_a_press = status_ar[8].tr('^0-9', '')
pen_b_press = status_ar[9].tr('^0-9', '')
volt_A = status_ar[10].tr('^0-9', '')
stat_A = status_ar[11][6,2]
surge = status_ar[11].tr('^0-9-', '')
needle_split = status_ar[12].split('%')
needle_a1 = needle_split[0].slice!(2..4)
needle_b1 = needle_split[1].slice!(2..4)
needle_a2 = needle_split[2].slice!(2..4)
needle_b2 = needle_split[3].slice!(2..4)
StnA.create(
:datetime => DateTime.now,
:total_kW => total_kW,
:stna_kW => stna_kW,
:stna_kVAr => stna_kVAr,
:total_kVAr => total_kVAr,
:tailrace => tailrace,
:lo_pond => lo_pond,
:up_pond => up_pond,
:mode => mode,
:pen_a_press => pen_a_press,
:pen_b_press => pen_b_press,
:volt_A => volt_A,
:stat_A => stat_A,
:surge => surge,
:needle_a1 => needle_a1,
:needle_b1 => needle_b1,
:needle_a2 => needle_a2,
:needle_b2 => needle_b2
)
end
# may require a break in the loop later
end