gobot.io/x/gobot/v2@v2.1.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  			<-ticker.C
    21  			f()
    22  		}
    23  	}()
    24  
    25  	return ticker
    26  }
    27  
    28  // After triggers f after t duration.
    29  func After(t time.Duration, f func()) {
    30  	time.AfterFunc(t, f)
    31  }
    32  
    33  // Rand returns a positive random int up to max
    34  func Rand(max int) int {
    35  	i, _ := rand.Int(rand.Reader, big.NewInt(int64(max)))
    36  	return int(i.Int64())
    37  }
    38  
    39  // FromScale returns a converted input from min, max to 0.0...1.0.
    40  func FromScale(input, min, max float64) float64 {
    41  	return (input - math.Min(min, max)) / (math.Max(min, max) - math.Min(min, max))
    42  }
    43  
    44  // ToScale returns a converted input from 0...1 to min...max scale.
    45  // If input is less than min then ToScale returns min.
    46  // If input is greater than max then ToScale returns max
    47  func ToScale(input, min, max float64) float64 {
    48  	i := input*(math.Max(min, max)-math.Min(min, max)) + math.Min(min, max)
    49  	if i < math.Min(min, max) {
    50  		return math.Min(min, max)
    51  	} else if i > math.Max(min, max) {
    52  		return math.Max(min, max)
    53  	} else {
    54  		return i
    55  	}
    56  }
    57  
    58  // Rescale performs a direct linear rescaling of a number from one scale to another.
    59  func Rescale(input, fromMin, fromMax, toMin, toMax float64) float64 {
    60  	return (input-fromMin)*(toMax-toMin)/(fromMax-fromMin) + toMin
    61  }
    62  
    63  // DefaultName returns a sensible random default name
    64  // for a robot, adaptor or driver
    65  func DefaultName(name string) string {
    66  	return fmt.Sprintf("%s-%X", name, Rand(int(^uint(0)>>1)))
    67  }