You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
weather/internal/mqtt/event.go

71 lines
1.5 KiB

package mqtt
import (
"fmt"
"reflect"
"strconv"
"time"
"github.com/dustinpianalto/weather"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
type eventService struct {
client *mqtt.Client
}
func (e eventService) Event(i uint64) (*weather.AmbientEntry, error) {
return nil, nil
}
func (e eventService) AddEvent(event *weather.AmbientEntry) (*weather.AmbientEntry, error) {
m := eventToMap(event)
for k, v := range m {
(*e.client).Publish(fmt.Sprintf("weather/WS-2902C/%s", k), 0, false, v)
}
return event, nil
}
func (e eventService) UpdateEvent(event *weather.AmbientEntry) error {
return nil
}
func (e eventService) DeleteEvent(event *weather.AmbientEntry) error {
return nil
}
func eventToMap(event *weather.AmbientEntry) map[string]string {
m := make(map[string]string)
iVal := reflect.ValueOf(event).Elem()
typ := iVal.Type()
for i := 0; i < iVal.NumField(); i++ {
f := iVal.Field(i)
var v string
switch f.Interface().(type) {
case int, int8, int16, int32, int64:
v = strconv.FormatInt(f.Int(), 10)
case uint, uint8, uint16, uint32, uint64:
v = strconv.FormatUint(f.Uint(), 10)
case float32:
v = strconv.FormatFloat(f.Float(), 'f', 1, 32)
case float64:
v = strconv.FormatFloat(f.Float(), 'f', 1, 64)
case []byte:
v = string(f.Bytes())
case string:
v = f.String()
case bool:
if f.Bool() {
v = "true"
} else {
v = "false"
}
case time.Time:
v = strconv.FormatInt(f.Interface().(time.Time).Unix(), 10)
}
m[typ.Field(i).Name] = v
}
return m
}