#!/usr/bin/ruby
# This file is part of ScopePort (Client Ruby).
#
# Copyright 2009 Lennart Koopmann
#
# ScopePort (Client Ruby) is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ScopePort (Client Ruby) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ScopePort (Client Ruby). If not, see <http://www.gnu.org/licenses/>.
hostname = "localhost"
port = 12200
host_id = 1
password = "secret"
require "socket"
class Conversation
private
def socket
@socket
end
public
def initialize hostname, port
raise "Invalid port" if port < 0 or port > 65535
@hostname = hostname
@port = port
# Try to open a socket.
begin
@socket = TCPSocket.open(@hostname, @port)
# Check the answer.
msg = @socket.recvfrom 100
raise "Empty or no reply" if msg[0].length == 0
raise msg[0] if msg[0] != "Okay"
rescue => e
raise e
end
end
def close
begin
@socket.close
rescue => e
raise e
end
end
def login host_id, password
begin
login_message = "#{host_id},login,#{password}"
@socket.send login_message, login_message.length
msg = @socket.recvfrom 100
raise "Empty or no reply" if msg[0].length == 0
raise msg[0] if msg[0] != "Okay"
rescue => e
raise e
end
end
def send_sensor_data(host_id, sensor, value)
raise "Missing host_id" if !host_id.integer?
raise "Missing sensor name" if sensor.length <= 0
raise "Missing sensor value" if value.length <= 0
raise "Illegal characters" if sensor.include? "," or value.include? ","
begin
sensor_message = "#{host_id},#{sensor},#{value}"
@socket.send sensor_message, sensor_message.length
msg = @socket.recvfrom 100
raise "Empty or no reply" if msg[0].length == 0
raise msg[0] if msg[0] != "Okay"
rescue => e
raise e
end
end
end
while 1 do
# Connect to the ScopePort server.
begin
con = Conversation.new hostname, port
rescue => e
puts "Could not connect to ScopePort server: #{e}"
con.close
sleep(60)
next
end
# Log in
begin
con.login host_id, password
rescue => e
puts "Could not log in: #{e}"
con.close
sleep(60)
next
end
# Send sensor data
begin
con.send_sensor_data host_id, "sensor_,cpu5", "5.2"
rescue => e
puts "Could not send sensor data: #{e}"
con.close
sleep(60)
next
end
# All done. Close socket.
con.close
sleep 60
end