github.com/martinohmann/rfoutlet@v1.2.1-0.20220707195255-8a66aa411105/internal/outlet/outlet.go (about)

     1  // Package outlet provides types for the outlet and outlet group as well as
     2  // tools to interact with them and to manage their state.
     3  package outlet
     4  
     5  import (
     6  	"sync"
     7  
     8  	"github.com/martinohmann/rfoutlet/internal/schedule"
     9  )
    10  
    11  // State describes the state of an outlet (on or off).
    12  type State uint
    13  
    14  const (
    15  	// StateOff describes an outlet that is switched off.
    16  	StateOff State = iota
    17  	// StateOn describes an outlet that is switched on.
    18  	StateOn
    19  )
    20  
    21  // Group is a group of outlets that can be switched as one.
    22  type Group struct {
    23  	ID          string    `json:"id"`
    24  	DisplayName string    `json:"displayName"`
    25  	Outlets     []*Outlet `json:"outlets"`
    26  }
    27  
    28  // Outlet is an rf controlled outlet that can be switched on or off.
    29  type Outlet struct {
    30  	sync.Mutex
    31  	ID          string             `json:"id"`
    32  	DisplayName string             `json:"displayName"`
    33  	CodeOn      uint64             `json:"-"`
    34  	CodeOff     uint64             `json:"-"`
    35  	Protocol    int                `json:"-"`
    36  	PulseLength uint               `json:"-"`
    37  	Schedule    *schedule.Schedule `json:"schedule"`
    38  	State       State              `json:"state"`
    39  }
    40  
    41  // SetState sets the state of the outlet
    42  func (o *Outlet) SetState(state State) {
    43  	o.Lock()
    44  	o.State = state
    45  	o.Unlock()
    46  }
    47  
    48  // GetState returns the state of the outlet
    49  func (o *Outlet) GetState() State {
    50  	o.Lock()
    51  	defer o.Unlock()
    52  	return o.State
    53  }
    54  
    55  // getCodeForState returns the code to transmit to bring the outlet into state.
    56  func (o *Outlet) getCodeForState(state State) uint64 {
    57  	switch state {
    58  	case StateOn:
    59  		return o.CodeOn
    60  	default:
    61  		return o.CodeOff
    62  	}
    63  }