Skip to content

Commit

Permalink
make code more modular and work for multiple devices
Browse files Browse the repository at this point in the history
  • Loading branch information
bsamm committed Oct 11, 2020
1 parent ecdb6f5 commit 5b8926c
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 27 deletions.
5 changes: 2 additions & 3 deletions app/controllers/pages_controller.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
class PagesController < ApplicationController
def home
@devices = Device.all
@led_status = WebConnectedLed.status
@devices = Device.all_connected
end

def toggle_led
WebConnectedLed.toggle
WebConnectedLed.new(params['device_name'])&.toggle
redirect_to root_path
end
end
13 changes: 12 additions & 1 deletion app/models/device.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
class Device
class << self
def all
def all_connected
Particle.devices
.select { |d| d.connected? }
.each { |d| d
.attributes
.merge!(extra_attributes(d.name))
}
end

def first
all.first
end

def extra_attributes(name)
{
:led_status => WebConnectedLed.new(name)&.status
}
end
end
end
8 changes: 4 additions & 4 deletions app/views/pages/home.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,18 @@
</tr>
<% @devices.each do |d| %>
<tr>
<td><%= d.name %></td>
<td><%= d.last_heard %></td>
<td><%= d.attributes[:name] %></td>
<td><%= d.attributes[:last_heard] %></td>
<td>
<% if @led_status == 1 %>
<% if d.attributes[:led_status] == 1 %>
<span class="tag is-success">On</span>
<% else %>
<span class="tag is-danger">Off</span>
<% end %>
</td>
<td>
<div class="buttons">
<%= button_to 'Toggle Led', pages_toggle_led_path, method: :post, class: "button is-warning" %>
<%= button_to 'Toggle Led', pages_toggle_led_path, method: :post, params: { device_name: d.attributes[:name] }, class: "button is-warning" %>
</div>
</td>
</tr>
Expand Down
36 changes: 17 additions & 19 deletions lib/web_connected_led.rb
Original file line number Diff line number Diff line change
@@ -1,27 +1,25 @@
class WebConnectedLed
class << self
def toggle
if status == 0
switch('on')
else
switch('off')
end
end
def initialize(name)
@name = name
end

def device
Particle.device(name)
def toggle
if status == 0
switch('on')
else
switch('off')
end
end

def name
'photon-0002'
end
def device
Particle.device(@name)
end

def status
device.variable('led')
end
def status
device.variable('led')
end

def switch(state)
device.function('led', state)
end
def switch(state)
device.function('led', state)
end
end

0 comments on commit 5b8926c

Please sign in to comment.