Skip to content

Instantly share code, notes, and snippets.

@izumogeiger
Created August 27, 2016 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save izumogeiger/c000a91a77161acb3365d22f48d6c83c to your computer and use it in GitHub Desktop.
Save izumogeiger/c000a91a77161acb3365d22f48d6c83c to your computer and use it in GitHub Desktop.
require 'pp'
require 'fileutils'
require 'net/https'
class Locked < StandardError
end
def lock(lock_file_path='/tmp/mix1.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 Mix1Logger
def initialize
end
def get_line
uri = URI.parse('http://192.168.1.203')
http = Net::HTTP.new(uri.host,uri.port)
res = http.send_request('GET',uri.request_uri)
unless res.code == "200"
return nil
end
line = res.body
r = %r|^[\d]+\s*,\s*[\d]+\s*,\s*[\d\.]+\s*,\s*[\d-]+\s*,\s*[\d-]+\s*,\s*[\d-]+|
return nil unless r =~ line
k = [:h,:t,:d,:x,:y,:z,:line]
v = line.split(",")
v << line
v.each do |vv| vv.strip! end
a = k.zip(v)
ret = Hash[a]
pp ret
ret
end
def xively(l,d)
uri = URI.parse('https://api.xively.com/v2/feeds/xxxxxxxxxxxxxx.xml')
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
headers = {
'X-ApiKey' => 'xxxsecretkeyxxx',
'Content-Type' => 'application/xml'
}
data =<<-"EOS"
<?xml version="1.0" encoding="UTF-8"?>
<eeml>
<environment>
<data id="dht11_t">
<current_value>#{l[:t]}</current_value>
</data>
<data id="dht11_h">
<current_value>#{l[:h]}</current_value>
</data>
<data id="pm2_5">
<current_value>#{d}</current_value>
</data>
<data id="hmc5883_x">
<current_value>#{l[:x]}</current_value>
</data>
<data id="hmc5883_y">
<current_value>#{l[:y]}</current_value>
</data>
<data id="hmc5883_z">
<current_value>#{l[:z]}</current_value>
</data>
</environment>
</eeml>
EOS
puts data
res = https.send_request('PUT',uri.request_uri,data,headers)
pp res
end
WARM_UP_COUNT = 3
REPORT_CYCLE = 60
def run
count = 0
ds = []
loop do
sleep 3
count += 1
l = get_line
next unless l
next if count < WARM_UP_COUNT
now = Time.now
if count % REPORT_CYCLE == 0
pp l
dir = File.join(ENV["HOME"],"mix1log",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
ds << l[:d].to_i
if ds.size > 11
ds.shift
end
d = 0.0
ds.each do |i| d += i end
d /= ds.size
d = "%.2f"%d
xively(l,d)
end
end
end
end
begin
lock do
pkg = Mix1Logger.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