Skip to content

Commit

Permalink
Map mode to relay state and pin value
Browse files Browse the repository at this point in the history
  • Loading branch information
pawiecz committed Jan 2, 2018
1 parent 69e4b6b commit 7c5e0e3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
16 changes: 8 additions & 8 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"net/http"

"github.com/julienschmidt/httprouter"
"github.com/nathan-osman/go-rpigpio"
)

// Index handles the default route (GET /).
Expand Down Expand Up @@ -37,13 +36,13 @@ func RelayShow(w http.ResponseWriter, r *http.Request, params httprouter.Params)
// RelayOn handles the relays on action (GET /relays/:id/on).
func RelayOn(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
id := params.ByName("id")
switchRelay(w, id, true, rpi.LOW)
switchRelay(w, id, PIN_ON)
}

// RelayOff handles the relays off action (GET /relays/:id/off).
func RelayOff(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
id := params.ByName("id")
switchRelay(w, id, false, rpi.HIGH)
switchRelay(w, id, PIN_OFF)
}

// findRelay locates Relay with the given ID on the module.
Expand All @@ -57,26 +56,27 @@ func findRelay(id string) (*Relay, error) {
}

// switchRelay provides unified wrapper for Relay On/Off actions.
func switchRelay(w http.ResponseWriter, id string, state bool, pinState rpi.Value) {
func switchRelay(w http.ResponseWriter, id string, mode int) {
relay, err := findRelay(id)
if err != nil {
writeError(w, err)
return
}
if err := setState(id, state, pinState); err != nil {
if err := setState(id, mode); err != nil {
writeError(w, err)
return
}
writeResponse(w, http.StatusOK, &JsonResponse{Data: relay})
}

// setState switches given pin to requested state.
func setState(id string, state bool, pinState rpi.Value) error {
if err := pins[id].Write(pinState); err != nil {
func setState(id string, mode int) error {
ps := modePinState[mode]
if err := pins[id].Write(ps.value); err != nil {
// Writing requested state to the given pin failed
return ErrStateChangeFailed
}
module[id].State = state
module[id].State = ps.state
return nil
}

Expand Down
15 changes: 15 additions & 0 deletions pins.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ import "github.com/nathan-osman/go-rpigpio"

type PinMap map[string]int

type PinState struct {
state bool
value rpi.Value
}

const (
PIN_ON = iota
PIN_OFF
)

var modePinState = map[int]PinState{
PIN_ON: PinState{true, rpi.LOW},
PIN_OFF: PinState{false, rpi.HIGH},
}

func AllPins() PinMap {
pinmap := PinMap{
"I1": 27,
Expand Down

0 comments on commit 7c5e0e3

Please sign in to comment.