mirror of
https://github.com/hybridgroup/gobot.git
synced 2025-04-27 13:48:56 +08:00
sphero: calculate checksum of response packets
a little more robust.
This commit is contained in:
parent
1b61814ee1
commit
44d34d1ce7
@ -106,11 +106,16 @@ func (s *SpheroDriver) Start() bool {
|
|||||||
header := s.readHeader()
|
header := s.readHeader()
|
||||||
if header != nil && len(header) != 0 {
|
if header != nil && len(header) != 0 {
|
||||||
body := s.readBody(header[4])
|
body := s.readBody(header[4])
|
||||||
if header[1] == 0xFE {
|
data := append(header, body...)
|
||||||
async := append(header, body...)
|
checksum := data[len(data)-1]
|
||||||
s.asyncResponse = append(s.asyncResponse, async)
|
if checksum != calculateChecksum(data[2:len(data)-1]) {
|
||||||
} else {
|
continue
|
||||||
s.responseChannel <- append(header, body...)
|
}
|
||||||
|
switch header[1] {
|
||||||
|
case 0xFE:
|
||||||
|
s.asyncResponse = append(s.asyncResponse, data)
|
||||||
|
case 0xFF:
|
||||||
|
s.responseChannel <- data
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -230,7 +235,10 @@ func (s *SpheroDriver) write(packet *packet) {
|
|||||||
|
|
||||||
func (s *SpheroDriver) calculateChecksum(packet *packet) uint8 {
|
func (s *SpheroDriver) calculateChecksum(packet *packet) uint8 {
|
||||||
buf := append(packet.header, packet.body...)
|
buf := append(packet.header, packet.body...)
|
||||||
buf = buf[2:]
|
return calculateChecksum(buf[2:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func calculateChecksum(buf []byte) byte {
|
||||||
var calculatedChecksum uint16
|
var calculatedChecksum uint16
|
||||||
for i := range buf {
|
for i := range buf {
|
||||||
calculatedChecksum += uint16(buf[i])
|
calculatedChecksum += uint16(buf[i])
|
||||||
|
@ -1,8 +1,9 @@
|
|||||||
package sphero
|
package sphero
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/hybridgroup/gobot"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/hybridgroup/gobot"
|
||||||
)
|
)
|
||||||
|
|
||||||
func initTestSpheroDriver() *SpheroDriver {
|
func initTestSpheroDriver() *SpheroDriver {
|
||||||
@ -20,3 +21,20 @@ func TestSpheroDriverHalt(t *testing.T) {
|
|||||||
d := initTestSpheroDriver()
|
d := initTestSpheroDriver()
|
||||||
gobot.Assert(t, d.Halt(), true)
|
gobot.Assert(t, d.Halt(), true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCalculateChecksum(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
data []byte
|
||||||
|
checksum byte
|
||||||
|
}{
|
||||||
|
{[]byte{0x00}, 0xff},
|
||||||
|
{[]byte{0xf0, 0x0f}, 0x00},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
actual := calculateChecksum(tt.data)
|
||||||
|
if actual != tt.checksum {
|
||||||
|
t.Errorf("Expected %x, got %x for data %x.", tt.checksum, actual, tt.data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user