Created
June 28, 2016 02:51
-
-
Save izumogeiger/ad07fa739314dd76c504619b2af29cea to your computer and use it in GitHub Desktop.
pkgt5logger.rb
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
require 'pp' | |
require 'fileutils' | |
require 'serialport' | |
require 'net/https' | |
class Locked < StandardError | |
end | |
def lock(lock_file_path='/tmp/pkgt5logger.lock') | |
File.open(lock_file_path, 'w') do |lock_file| | |
if lock_file.flock(File::LOCK_EX|File::LOCK_NB) | |
yield | |
else | |
raise Locked | |
end | |
end | |
end | |
class PKGt5Logger | |
def initialize | |
i = 0 | |
dev = %w|/dev/ttyUSB0 /dev/ttyUSB1 /dev/ttyUSB2| | |
begin | |
@sp = SerialPort.new(dev[i],9600,8,1,0) | |
puts @sp | |
rescue Exception => ex | |
if i < dev.size | |
puts "#{dev[i]} failure" | |
i += 1 | |
retry | |
else | |
puts "PKGt5Logger device failure" | |
exit 1 | |
end | |
end | |
end | |
def get_line | |
line = @sp.gets | |
line.chomp! | |
k = %i|h s count cpm usvh usvhe line| | |
v = line.split(",") | |
v << line | |
a = k.zip(v) | |
Hash[a] | |
end | |
def xively(cpm) | |
uri = URI.parse('https://api.xively.com/v2/feeds/xxxxxxxxx.xml') | |
https = Net::HTTP.new(uri.host,uri.port) | |
https.use_ssl = true | |
headers = { | |
'X-ApiKey' => 'xxxxxxxxxxxxxxxxxxx', | |
'Content-Type' => 'application/xml' | |
} | |
data =<<-EOS | |
<?xml version="1.0" encoding="UTF-8"?> | |
<eeml> | |
<environment> | |
<data id="pkgt5cpm"> | |
<current_value>#{cpm}</current_value> | |
</data> | |
</environment> | |
</eeml> | |
EOS | |
res = https.send_request('PUT',uri.request_uri,data,headers) | |
pp res | |
end | |
WARM_UP_COUNT = 10000 | |
REPORT_CYCLE = 1000 | |
def run | |
count = 0 | |
loop do | |
count += 1 | |
l = get_line | |
now = Time.now | |
next unless l | |
next if count < WARM_UP_COUNT | |
if count % REPORT_CYCLE == 0 | |
pp l | |
dir = File.join(ENV["HOME"],"pkgt5",now.strftime("%Y"),now.strftime("%m")) | |
file = File.join(dir,now.strftime("%d")+".txt") | |
FileUtils.mkdir_p(dir) | |
mode = File.exists?(file) ? "a" : "w" | |
File.open(file,mode) do |io| | |
out = "#{now.strftime("%Y%m%d%H%M%S")},#{l[:line]}" | |
io.puts out | |
end | |
xively(l[:cpm]) | |
end | |
end | |
end | |
end | |
begin | |
lock do | |
pkg = PKGt5Logger.new | |
pkg.run | |
end | |
rescue Locked | |
exit 0 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment