-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathampel.rb
69 lines (56 loc) · 1.43 KB
/
ampel.rb
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
67
68
69
require 'singleton'
begin
require 'simpleport'
rescue LoadError
require 'spec/simpleport_mock'
end
class Ampel
include Singleton
SIGNAL = 2
RED = 7
YELLOW = 3
GREEN = 4
OFF = 0
ON = 1
def initialize
@handle = Simpleport.simpleport_open
reset_lights
end
%w(red yellow green).each do |color|
define_method(color) do |state|
color_const = Ampel.const_get(color.upcase)
if state == "Off"
Simpleport.simpleport_set_pin(@handle, color_const, OFF)
elsif state == "On"
Simpleport.simpleport_set_pin(@handle, color_const, ON)
end
sleep(0.5)
end
end
def state_for(color)
Simpleport.simpleport_get_pin(@handle, Ampel.const_get(color.upcase)) == 0 ? "Off" : "On"
end
def state
states = %w(red yellow green signal).inject([]) do |state, color|
state << "#{color}=#{state_for(color)}"
end
return states
end
def signal(duration=10)
if duration.to_i > 0
Simpleport.simpleport_set_pin(@handle, SIGNAL, ON)
sleep(duration.to_i)
Simpleport.simpleport_set_pin(@handle, SIGNAL, OFF)
elsif duration == "Off"
Simpleport.simpleport_set_pin(@handle, SIGNAL, OFF)
elsif duration == "On"
Simpleport.simpleport_set_pin(@handle, SIGNAL, ON)
end
end
private
def reset_lights
for i in 1..11 do
Simpleport.simpleport_set_pin(@handle, i, OFF)
end
end
end