summaryrefslogtreecommitdiff
path: root/m4p/message.go
blob: 34a9383ca643deea2de57eaa01333a0d147dbcf9 (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
89
90
91
package m4p

import (
	"bytes"
	"encoding/json"
)

type MessageType string

// MessageType enums.
const (
	Magic4PCAdMessage   MessageType = "magic4pc_ad"
	SubSensorMessage    MessageType = "sub_sensor"
	RemoteUpdateMessage MessageType = "remote_update"
	InputMessage        MessageType = "input"
	KeepAliveMessage    MessageType = "keepalive"
)

// Message format sent over the wire.
type Message struct {
	Type    MessageType `json:"t"`
	Version int         `json:"version"`
	*DeviceInfo
	*Register
	*RemoteUpdate
	*Input
}

// NewMessage initializes a message with the type and protocol version.
func NewMessage(typ MessageType) Message {
	return Message{
		Type:    typ,
		Version: protocolVersion,
	}
}

// DeviceInfo represents a magic4pc server.
type DeviceInfo struct {
	Model  string `json:"model"`
	IPAddr string `json:"-"`
	Port   int    `json:"port"`
	MAC    string `json:"mac"`
}

// Register payload for registering a new client on the server.
type Register struct {
	UpdateFrequency int      `json:"updateFreq"`
	Filter          []string `json:"filter"`
}

// Input event (key pressed).
type Input struct {
	Parameters struct {
		KeyCode int  `json:"keyCode"`
		IsDown  bool `json:"isDown"`
	} `json:"parameters"`
}

// RemoteUpdate event, sensor data from the magic remote.
type RemoteUpdate struct {
	// filters []string
	Payload []byte `json:"payload"`
}

// type (
// 	ReturnValue  uint8
// 	DeviceID     uint8
// 	Coordinates  struct{ X, Y int32 }
// 	Gyroscope    struct{ X, Y, Z float32 }
// 	Acceleration struct{ X, Y, Z float32 }
// 	Quaternion   struct{ Q0, Q1, Q2, Q3 float32 }
// )

// func (ru RemoteUpdate) Coordinates() Coordinates {
// 	return Coordinates{}
// }

// func (ru RemoteUpdate) Acceleration() Acceleration {
// 	return Acceleration{}
// }

func decode(b []byte) (Message, error) {
	var m Message
	dec := json.NewDecoder(bytes.NewReader(b))
	dec.DisallowUnknownFields()
	if err := dec.Decode(&m); err != nil {
		return Message{}, err
	}

	return m, nil
}