Skip to content

Commit

Permalink
Add more functionality for integration and logging (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
bb4L authored Jul 9, 2021
1 parent e609ec8 commit 10ae19b
Show file tree
Hide file tree
Showing 14 changed files with 354 additions and 75 deletions.
28 changes: 22 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,29 @@

Wrapper library to communicate with the [rpi-radio-alarm-go](https://github.com/bb4L/rpi-radio-alarm-go)

It uses `dotenv` this means a `.env` file is required.
## Installation
- get the package with `go get`
- ensure `./rpi_data.yaml` is available (if using the helper interacting with storage)
```yaml
settings:
port: 8000
run_api: true
run_telegram_bot: true
run_discord_bot: false
alarms:
- name: Test
hour: 7
minute: 0
days:
- 0
- 1
active: false
...
radio:
running: false
pid: -1

```
ALARMURL=URL-TO-ALARM # https://example.com
EXTRAHEADER=EXTRA-HEADER # eg. ApiKey
EXTRAHEADERVALUE=VALUE-FOR-THE-HEADER # eg. password1234
```
```

# License
[GPLv3](LICENSE)
32 changes: 15 additions & 17 deletions api/alarm.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// Package api contains the data / helper functions to interact with the api
package api

import (
Expand All @@ -11,37 +10,39 @@ import (
"os"
"strconv"

"github.com/bb4L/rpi-radio-alarm-go-library/constants"
"github.com/bb4L/rpi-radio-alarm-go-library/logging"
"github.com/bb4L/rpi-radio-alarm-go-library/types"
)

var logger = logging.GetLogger("alarm", os.Stdout)
var logger = logging.GetLogger(os.Stdout, constants.DefaultPrefix, "alarm")

// GetAlarms gets all alarms
func (helper *Helper) GetAlarms() ([]types.Alarm, error) {
func (helper *Helper) GetAlarms(withWritePermission bool) ([]types.Alarm, error) {
url := helper.AlarmURL + "/alarm"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("could not create request for GetAlarms")
}

res, err := helper.prepareAndDoRequest(req)
logger.Println(res)

if err != nil {
logger.Println(err)
logger.Println("ERR:", err)
return nil, err
}

jsonData, _ := ioutil.ReadAll(res.Body)
jsonData, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
logger.Println("read ERR:", readErr)
return nil, readErr
}

if res.StatusCode != 200 {
return nil, fmt.Errorf(string(jsonData[:]))
}

var data []types.Alarm
err = json.Unmarshal(jsonData, &data)

if err != nil {
logger.Println(err)
return nil, err
Expand All @@ -51,16 +52,14 @@ func (helper *Helper) GetAlarms() ([]types.Alarm, error) {
}

// GetAlarm gets a specific alarm by index
func (helper *Helper) GetAlarm(idx int) (types.Alarm, error) {
func (helper *Helper) GetAlarm(idx int, withWritePermission bool) (types.Alarm, error) {
url := helper.AlarmURL + "/alarm/" + strconv.Itoa(idx)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return types.Alarm{}, fmt.Errorf("could not create request for GetAlarm")
}

res, err := helper.prepareAndDoRequest(req)
logger.Println(res)

if err != nil {
logger.Println(err)
return types.Alarm{}, err
Expand All @@ -74,7 +73,6 @@ func (helper *Helper) GetAlarm(idx int) (types.Alarm, error) {

var data types.Alarm
err = json.Unmarshal(jsonData, &data)

if err != nil {
logger.Println(err)
return types.Alarm{}, err
Expand All @@ -83,6 +81,11 @@ func (helper *Helper) GetAlarm(idx int) (types.Alarm, error) {
return data, nil
}

// SaveAlarm saves the given alarm on the given index
func (helper *Helper) SaveAlarm(idx int, alarm types.Alarm) (types.Alarm, error) {
return helper.ChangeAlarm(alarm, idx)
}

// ChangeAlarm changes the alarm on the given index with the data of the passed instance
func (helper *Helper) ChangeAlarm(alarm types.Alarm, idx int) (types.Alarm, error) {
url := helper.AlarmURL + "/alarm/" + strconv.Itoa(idx)
Expand All @@ -98,8 +101,6 @@ func (helper *Helper) ChangeAlarm(alarm types.Alarm, idx int) (types.Alarm, erro
}

res, err := helper.prepareAndDoRequest(req)
logger.Println(res)

if err != nil {
logger.Println(err)
return types.Alarm{}, err
Expand All @@ -113,7 +114,6 @@ func (helper *Helper) ChangeAlarm(alarm types.Alarm, idx int) (types.Alarm, erro

var data types.Alarm
err = json.Unmarshal(jsonData, &data)

if err != nil {
logger.Println(err)
return types.Alarm{}, fmt.Errorf("could not unmarshal result")
Expand All @@ -138,7 +138,6 @@ func (helper *Helper) AddAlarm(alarm types.Alarm) ([]types.Alarm, error) {
}

res, err := helper.prepareAndDoRequest(req)
logger.Println(res)
if err != nil {
logger.Println(err)
return nil, err
Expand Down Expand Up @@ -170,7 +169,6 @@ func (helper *Helper) DeleteAlarm(idx int) ([]types.Alarm, error) {
}

res, err := helper.prepareAndDoRequest(req)
logger.Println(res)
if err != nil {
logger.Println(err)
return nil, err
Expand Down
30 changes: 29 additions & 1 deletion api/helper.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
// Package api implements a wrapper around the rest api
package api

import (
"fmt"
"net/http"
"os"

"github.com/joho/godotenv"
)

// Helper struct to define the api settings being used
Expand Down Expand Up @@ -47,6 +51,30 @@ func (helper *Helper) addHeadersToRequest(req *http.Request) *http.Request {
if helper.ExtraHeader != "" && helper.ExtreaHeaderValue != "" {
req.Header.Set(helper.ExtraHeader, helper.ExtreaHeaderValue)
}

return req
}

// GetHelperFromEnv Returns the working helper object with the config loaded from a .env file
// It uses dotenv this means a .env file is required.
// ALARMURL=URL-TO-ALARM # https://example.com
// EXTRAHEADER=EXTRA-HEADER # eg. ApiKey
// EXTRAHEADERVALUE=VALUE-FOR-THE-HEADER # eg. password1234
func GetHelperFromEnv() Helper {
err := godotenv.Load()
if err != nil {
logger.Fatal("error loading .env file")
}

if os.Getenv("ALARMURL") == "" {
logger.Fatal("you have to specify ALARMURL in the .env")
}

helper := Helper{AlarmURL: os.Getenv("ALARMURL"), ExtraHeader: os.Getenv("EXTRAHEADER"), ExtreaHeaderValue: os.Getenv("EXTRAHEADERVALUE")}

err = helper.CheckHealth()
if err != nil {
logger.Fatalf("health check failed with: %s", err)
}

return helper
}
26 changes: 20 additions & 6 deletions api/radio.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,14 @@ import (
)

// GetRadio returns the radio status
func (helper *Helper) GetRadio() (types.Radio, error) {
func (helper *Helper) GetRadio(withWritePermission bool) (types.Radio, error) {
url := helper.AlarmURL + "/radio"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return types.Radio{}, fmt.Errorf("could not create request for GetRadio")
}

res, err := helper.prepareAndDoRequest(req)

if err != nil {
logger.Println(err)
return types.Radio{}, err
Expand All @@ -33,7 +32,6 @@ func (helper *Helper) GetRadio() (types.Radio, error) {

var data types.Radio
err = json.Unmarshal(jsonData, &data)

if err != nil {
logger.Println(err)
return types.Radio{}, err
Expand All @@ -42,6 +40,25 @@ func (helper *Helper) GetRadio() (types.Radio, error) {
return data, nil
}

// SaveRadio saves the radio and returns it
func (helper *Helper) SaveRadio(radio types.Radio) (types.Radio, error) {
if radio.Running {
return helper.StartRadio()
} else {
return helper.StopRadio()
}
}

// SwitchRadio changes the radio to the state running passed as argument
func (helper *Helper) SwitchRadio(running bool) (types.Radio, error) {
if running {
return helper.StartRadio()

} else {
return helper.StopRadio()
}
}

// StartRadio starts the radio
func (helper *Helper) StartRadio() (types.Radio, error) {
values := map[string]string{"switch": "on"}
Expand All @@ -54,8 +71,6 @@ func (helper *Helper) StartRadio() (types.Radio, error) {
}

res, err := helper.prepareAndDoRequest(req)
logger.Println(res)

if err != nil {
logger.Println(err)
return types.Radio{}, err
Expand All @@ -69,7 +84,6 @@ func (helper *Helper) StartRadio() (types.Radio, error) {

var data types.Radio
err = json.Unmarshal(jsonData, &data)

if err != nil {
logger.Println(err)
return types.Radio{}, err
Expand Down
5 changes: 5 additions & 0 deletions constants/constant.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Package constants contains some constant values
package constants

// DefaultPrefix the default prefix for the loggers
const DefaultPrefix = "rpi-radio-alarm-go-library"
5 changes: 4 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ module github.com/bb4L/rpi-radio-alarm-go-library

go 1.16

require github.com/joho/godotenv v1.3.0
require (
github.com/joho/godotenv v1.3.0
gopkg.in/yaml.v2 v2.4.0
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc=
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
11 changes: 5 additions & 6 deletions logging/loggers.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
// Package logging contains some logging utils
// Package logging contains utils to get a logger with e standardized formatting
package logging

import (
"io"
"log"
"strings"
)

const commonPrefix = "[rpi-radio-alarm-library] "

var prefixes = log.Ldate | log.Ltime | log.Lmsgprefix
const prefixes = log.Ldate | log.Ltime | log.Lmsgprefix

// GetLogger returns a logger with given additional prefix
func GetLogger(place string, output io.Writer) *log.Logger {
return log.New(output, commonPrefix+"["+place+"] ", prefixes)
func GetLogger(output io.Writer, places ...string) *log.Logger {
return log.New(output, "["+strings.Join(places, ".")+"] ", prefixes)
}
34 changes: 0 additions & 34 deletions rpi-radio-alarm-go-library.go

This file was deleted.

Loading

0 comments on commit 10ae19b

Please sign in to comment.