summaryrefslogtreecommitdiff
path: root/servo/servo.go
blob: e3f608ce3bf1cdb1d1f259ebcee75fe7b174af1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/* SPDX-License-Identifier: MIT
 *
 * Copyright (C) 2020 jet tsang zeon-git. All Rights Reserved.
 */

package servo

import (
	"fmt"

	"git.jettsang.com/drivers/lobot/iface"
	"git.jettsang.com/drivers/lobot/utils"
)

const (

	// Unit conversions
	maxPos          uint16  = 1000
	maxAngle        float64 = 240
	positionToAngle float64 = maxAngle / float64(maxPos) // 0.24
	angleToPosition float64 = 1 / positionToAngle        // 4.16
)

type Servo struct {
	Protocol     iface.Protocol
	ID           int
	instructions InstructionMap
}

// New returns a new Servo.
func New(proto iface.Protocol, instructions InstructionMap, ID int) *Servo {
	return &Servo{
		Protocol:     proto,
		ID:           ID,
		instructions: instructions,
	}
}

func (s *Servo) sendInstruction(i InstName, values []uint16) error {
	r, ok := s.instructions[i]
	if !ok {
		return fmt.Errorf("can't send a unsupported instruction: %v", i)
	}

	if r.Access == RO {
		return fmt.Errorf("can't sned a read-only instruction.")
	}

	var params []byte
	switch r.Length {
	case 1:
		if len(values) != 1 {
			return fmt.Errorf("invalid values length inputs.")
		}
		params = []byte{utils.Low(values[0])}
	case 4:
		if len(values) != 2 {
			return fmt.Errorf("invalid values length inputs.")
		}
		params = []byte{
			utils.Low(values[0]),
			utils.High(values[0]),
			utils.Low(values[1]),
			utils.High(values[1]),
		}
	default:
		return fmt.Errorf("invalid instruction length: %d", r.Length)
	}

	return s.Protocol.WriteData(s.ID, r.InstByte, params)
}

func (s *Servo) SendInstruction(i InstName, values []uint16) error {
	return s.sendInstruction(i, values)
}

func (s *Servo) getData(i InstName) ([]byte, error) {
	r, ok := s.instructions[i]
	if !ok {
		return nil, fmt.Errorf("can't send a unsupported instruction: %v", i)
	}

	if r.Access != RO {
		return nil, fmt.Errorf("can't sned a read-only instruction.")
	}

	return s.Protocol.ReadData(s.ID, r.InstByte)
}