-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpiweb.rb
60 lines (51 loc) · 1.53 KB
/
piweb.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
# encoding: utf-8
require 'rubygems'
require 'bundler'
Bundler.setup
require 'sinatra/base'
require 'wiringpi2'
require 'tilt/erb'
require 'yaml'
require 'socket'
class Main < Sinatra::Base
configure do
set :environment, :production
enable :sessions, :logging
file = File.new("#{settings.root}/log/#{settings.environment}.log", 'a+')
file.sync = true
use Rack::CommonLogger, file
config = YAML.load_file("#{settings.root}/config/config.yml")
set :hostname, Socket.gethostname.capitalize
set :place, config['place']
set :devices, config['devices']
set :io, WiringPi::GPIO.new
settings.devices.keys.each { |pin| settings.io.pin_mode pin, WiringPi::OUTPUT }
end
get '/' do
devices = {}
settings.devices.each do |pin, name|
state = settings.io.digital_read pin
devices[pin] = { :name => name, :state => state }
end
erb :devices_states, :locals => { :hostname => settings.hostname, :place => settings.place, :devices => devices }
end
get '/toggle/:pin' do
pin = params['pin'].to_i
if settings.devices.has_key? pin
current_state = settings.io.digital_read pin
settings.io.digital_write pin, (current_state + 1) % 2
end
redirect('/')
end
get '/switch/:state/:pin' do
pin = params['pin'].to_i
state = params['state'].downcase
if settings.devices.has_key? pin && state =~ /(on|off)/
settings.io.digital_write pin, state == 'on' ? 0 : 1
end
redirect('/')
end
not_found do
redirect to('http://www.google.com')
end
end