blob: c28d508a0b778d45ebbfb63453fa5beb6a0022c3 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
#!/usr/bin/env ruby
class Rdr
def initialize(f)
@f = f
reset
end
def valid?
@len == 10# && @csok
end
def read!
v = @f.read(1)
@len += 1
case @len
when 1
reset if v != 0xAA
when 2
reset if v != 0xC0
when 3
@pm25 = v
when 4
@pm25 += v * 256
when 5
@pm10 = v
when 6
@pm10 += v * 256
when 7
@id = v
when 8
@id += v * 256
when 9
if checksum == v
@csok = true
else
reset
end
when 10
reset if v != 0xAB
else
reset
end
end
def checksum
((@pm25 / 256) + (@pm25 % 256) +
(@pm10 / 256) + (@pm10 % 256) +
(@id / 256) + (@id % 256)) % 256
end
def reset
@len = 0
@pm25 = 0
@pm10 = 0
@id = 0
@csok = false
end
end
File.open("/dev/ttyUSB0", "rb") do |f|
r = Rdr.new(f)
r.read! until r.valid?
puts "Hooray"
end
|