gobot.io/x/gobot@v1.16.0/utils.go (about) 1 package gobot 2 3 import ( 4 "crypto/rand" 5 "fmt" 6 "math" 7 "math/big" 8 "time" 9 ) 10 11 // Every triggers f every t time.Duration until the end of days, or when a Stop() 12 // is called on the Ticker that is returned by the Every function. 13 // It does not wait for the previous execution of f to finish before 14 // it fires the next f. 15 func Every(t time.Duration, f func()) *time.Ticker { 16 ticker := time.NewTicker(t) 17 18 go func() { 19 for { 20 select { 21 case <-ticker.C: 22 f() 23 } 24 } 25 }() 26 27 return ticker 28 } 29 30 // After triggers f after t duration. 31 func After(t time.Duration, f func()) { 32 time.AfterFunc(t, f) 33 } 34 35 // Rand returns a positive random int up to max 36 func Rand(max int) int { 37 i, _ := rand.Int(rand.Reader, big.NewInt(int64(max))) 38 return int(i.Int64()) 39 } 40 41 // FromScale returns a converted input from min, max to 0.0...1.0. 42 func FromScale(input, min, max float64) float64 { 43 return (input - math.Min(min, max)) / (math.Max(min, max) - math.Min(min, max)) 44 } 45 46 // ToScale returns a converted input from 0...1 to min...max scale. 47 // If input is less than min then ToScale returns min. 48 // If input is greater than max then ToScale returns max 49 func ToScale(input, min, max float64) float64 { 50 i := input*(math.Max(min, max)-math.Min(min, max)) + math.Min(min, max) 51 if i < math.Min(min, max) { 52 return math.Min(min, max) 53 } else if i > math.Max(min, max) { 54 return math.Max(min, max) 55 } else { 56 return i 57 } 58 } 59 60 // Rescale performs a direct linear rescaling of a number from one scale to another. 61 func Rescale(input, fromMin, fromMax, toMin, toMax float64) float64 { 62 return (input-fromMin)*(toMax-toMin)/(fromMax-fromMin) + toMin 63 } 64 65 // DefaultName returns a sensible random default name 66 // for a robot, adaptor or driver 67 func DefaultName(name string) string { 68 return fmt.Sprintf("%s-%X", name, Rand(int(^uint(0)>>1))) 69 }