hybridgroup.gobot/utils.go

119 lines
2.2 KiB
Go
Raw Normal View History

2013-11-24 01:12:57 +08:00
package gobot
import (
2013-11-24 02:36:08 +08:00
"encoding/json"
2013-12-04 02:43:22 +08:00
"github.com/tarm/goserial"
"io"
2014-03-27 13:24:45 +08:00
"math"
2013-11-24 01:12:57 +08:00
"math/rand"
"net"
"reflect"
2013-12-04 02:43:22 +08:00
"regexp"
2013-11-24 01:12:57 +08:00
"time"
)
2013-12-04 02:43:22 +08:00
type Port io.ReadWriteCloser
2013-11-24 01:12:57 +08:00
func Every(t string, f func()) {
dur := parseDuration(t)
go func() {
for {
time.Sleep(dur)
go f()
}
}()
}
func After(t string, f func()) {
dur := parseDuration(t)
go func() {
time.Sleep(dur)
f()
}()
}
2013-12-31 11:06:13 +08:00
func Publish(c chan interface{}, val interface{}) {
select {
case c <- val:
default:
}
}
func On(c chan interface{}, f func(s interface{})) {
go func() {
for s := range c {
f(s)
}
}()
}
2013-11-24 01:12:57 +08:00
func parseDuration(t string) time.Duration {
dur, err := time.ParseDuration(t)
if err != nil {
panic(err)
}
return dur
}
func Rand(max int) int {
rand.Seed(time.Now().UTC().UnixNano())
return rand.Intn(max)
}
2013-12-04 02:43:22 +08:00
func ConnectToTcp(port string) io.ReadWriteCloser {
2013-11-24 01:12:57 +08:00
tcpPort, err := net.Dial("tcp", port)
if err != nil {
panic(err)
}
return tcpPort
}
2013-12-04 02:43:22 +08:00
func ConnectToSerial(port string, baud int) io.ReadWriteCloser {
c := &serial.Config{Name: port, Baud: baud}
s, err := serial.OpenPort(c)
if err != nil {
panic(err)
}
return s
}
func IsUrl(url string) bool {
rp := regexp.MustCompile("([^A-Za-z0-9]+).([^A-Za-z0-9]+).([^A-Za-z0-9]+)")
return rp.MatchString(url)
}
2013-11-25 06:41:36 +08:00
func Call(thing interface{}, method string, params ...interface{}) []reflect.Value {
2013-11-24 01:12:57 +08:00
in := make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
2013-11-25 06:41:36 +08:00
return reflect.ValueOf(thing).MethodByName(method).Call(in)
2013-11-24 01:12:57 +08:00
}
2013-11-24 02:36:08 +08:00
func FieldByName(thing interface{}, field string) reflect.Value {
return reflect.ValueOf(thing).FieldByName(field)
}
func FieldByNamePtr(thing interface{}, field string) reflect.Value {
return reflect.ValueOf(thing).Elem().FieldByName(field)
}
2013-11-24 02:36:08 +08:00
func toJson(obj interface{}) string {
b, _ := json.Marshal(obj)
return string(b)
}
2014-03-27 13:24:45 +08:00
func FromScale(input, min, max float64) float64 {
return (input - math.Min(min, max)) / (math.Max(min, max) - math.Min(min, max))
}
func ToScale(input, min, max float64) float64 {
i := input*(math.Max(min, max)-math.Min(min, max)) + math.Min(min, max)
if i < math.Min(min, max) {
return math.Min(min, max)
} else if i > math.Max(min, max) {
return math.Max(min, max)
} else {
return i
}
}