untested unix socket lua sample sensor
[svn42.git] / sensor_graph / sample_sensor.lua
1 #!/usr/bin/lua
2 require('os')
3 require('string')
4 require('socket')
5
6 last_movement = 0
7
8 function save_values()
9   os.execute(string.format("rrdtool update /home/sensordata.rrd -t temp:light:movement N:%f:%d:%d", last_temp, last_light, last_movement))
10   last_movement=0
11 end
12
13
14 function parse_value(str)
15   last_temp = 0.0
16   last_light = 0
17   if string.find(str,"Sensor T: Temp C:") then
18     last_temp = tonumber(string.sub(str,18))
19     os.execute(string.format("rrdtool update /home/sensordata.rrd -t temp N:%f", last_temp))
20     print(string.format("t: %f Grad Celsius",last_temp))
21   end
22   if string.find(str,"Sensor P: Photo:") then
23     last_light = tonumber(string.sub(str,17))
24     os.execute(string.format("rrdtool update /home/sensordata.rrd -t light N:%d", last_light))
25     print(string.format("p: %d",last_light))
26   end
27   if string.find(str,"movement") then
28     --last_movement=1
29     os.execute(string.format("rrdtool update /home/sensordata.rrd -t movement N:%d", 1))
30   end
31 end
32
33
34 local socket_factory = require("socket.unix");
35 local socket = socket_factory()
36
37
38 while 1 do
39   local client = socket.connect("/var/run/powersensordaemon/cmd.sock")
40   if client then
41     client:send("listen sensor\n")
42     --client:settimeout(30)
43     while 1 do
44       local line, err = client:receive()
45       if not err then 
46         parse_value(line) 
47       elseif err ~= "timeout" then
48         break
49       end
50     end
51     client:shutdown("both")
52   end
53   --wait 10 seconds
54   socket.select(nil, nil, 10)
55 end