More protocols
This commit is contained in:
84
protocol/meshcore/util.go
Normal file
84
protocol/meshcore/util.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package meshcore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.maze.io/go/ham/protocol/meshcore/crypto"
|
||||
)
|
||||
|
||||
type Position struct {
|
||||
Latitude float64
|
||||
Longitude float64
|
||||
}
|
||||
|
||||
func (pos *Position) String() string {
|
||||
if pos == nil {
|
||||
return "<unknown>"
|
||||
}
|
||||
return fmt.Sprintf("%f,%f", pos.Latitude, pos.Longitude)
|
||||
}
|
||||
|
||||
func (pos *Position) Marshal() []byte {
|
||||
var buf [8]byte
|
||||
binary.LittleEndian.PutUint32(buf[0:], uint32(pos.Latitude*1e6))
|
||||
binary.LittleEndian.PutUint32(buf[4:], uint32(pos.Longitude*1e6))
|
||||
return buf[:]
|
||||
}
|
||||
|
||||
func (pos *Position) Unmarshal(b []byte) error {
|
||||
if len(b) < 8 {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
pos.Latitude = float64(binary.LittleEndian.Uint32(b[0:])) / 1e6
|
||||
pos.Longitude = float64(binary.LittleEndian.Uint32(b[4:])) / 1e6
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeTime(b []byte, t time.Time) {
|
||||
binary.LittleEndian.PutUint32(b, uint32(t.Unix()))
|
||||
}
|
||||
|
||||
func decodeTime(b []byte) time.Time {
|
||||
return time.Unix(int64(binary.LittleEndian.Uint32(b)), 0).UTC()
|
||||
}
|
||||
|
||||
func encodeFrequency(b []byte, f float64) {
|
||||
binary.LittleEndian.PutUint32(b, uint32(f*1e3))
|
||||
}
|
||||
|
||||
func decodeFrequency(b []byte) float64 {
|
||||
return float64(int64(binary.LittleEndian.Uint32(b))) / 1e3
|
||||
}
|
||||
|
||||
func decodeCString(b []byte) string {
|
||||
if i := bytes.IndexByte(b, 0x00); i > -1 {
|
||||
return string(b[:i])
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func formatPath(path []byte) string {
|
||||
p := make([]string, len(path))
|
||||
for i, node := range path {
|
||||
p[i] = fmt.Sprintf("%02X", node)
|
||||
}
|
||||
return strings.Join(p, ">")
|
||||
}
|
||||
|
||||
func formatPublicKey(b []byte) string {
|
||||
switch len(b) {
|
||||
case 8:
|
||||
return fmt.Sprintf("<%016x>", b)
|
||||
case crypto.PublicKeySize:
|
||||
return fmt.Sprintf("<%06x…%06x>", b[:3], b[29:])
|
||||
case crypto.PrivateKeySize:
|
||||
return formatPublicKey(b[32:])
|
||||
default:
|
||||
return "<unknown>"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user