/
leap.go
338 lines (306 loc) · 9.03 KB
/
leap.go
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
//https://github.com/leapmotion/leapjs/blob/master/PROTOCOL.md
package leap
import (
"encoding/json"
"fmt"
"log"
"time"
glm "github.com/folago/googlmath"
"github.com/gorilla/websocket"
)
func init() {
//runtime.GOMAXPROCS(runtime.NumCPU())
log.SetFlags(log.LstdFlags | log.Lshortfile)
}
const (
Hovering string = "hovering"
None string = "none"
Touching string = "touching"
)
var (
WSPort string = "6437"
WSHost string = "127.0.0.1"
WSURL string = "ws://127.0.0.1:6437/v1.json"
)
type Pointable struct {
//Valid bool `json: "valid"`
Tool bool `json:"tool"`
ID int `json:"id"`
HandId int `json:"handId"`
Length float32 `json:"length"`
Width float32 `json:"width"`
Direction Vector `json:"direction"`
TipPosition Vector `json:"tipPosition"`
StabilizedTipPosition Vector `json:"stabilizedTipPosition"`
TipVelocity Vector `json:"tipVelocity"`
TouchZone string `json:"touchZone"`
TouchDistance float32 `json:"touchDistance"`
TimeVisible float32 `json:"timeVisible"`
}
type Finger struct {
ID int `json: "id"`
*Pointable
}
type Tool struct {
ID int `json: "id"`
*Pointable
}
type Hand struct {
Direction Vector `json:"direction"` //: array of floats (vector)
Fingers []Pointable `json:"fingers"`
Tools []Pointable `json:"tools"`
Pointables []Pointable `json:"pointables"`
ID int `json:"id"` //: integer
PalmNormal Vector `json:"palmNormal"` //: array of floats (vector)
PalmPosition Vector `json:"palmPosition"` //: array of floats (vector)
PalmVelocity Vector `json:"palmVelocity"` //: array of floats (vector)
SphereCenter Vector `json:"sphereCenter"` //: array of floats (vector)
SphereRadius float32 `json:"sphereRadius"` //: float
StabilizedPalmPosition Vector `json:"stabilizedPalmPosition"`
R Matrix `json:"r"` //: nested arrays of floats (matrix)
S float32 `json:"s"` //: float
T Vector `json:"t"` //: array of floats (vector)
PinchStrength float32 `json:"pinchStrength"`
GrabStrength float32 `json:"grabStrength"`
Confidence float32 `json:"confidence"`
Type string `json:"type"`
//Valid bool `json: "valid"`
}
type Gesture struct {
ID int `json:"id"`
State string `json:"state"`
Type string `json:"type"`
Duration time.Duration `json:"duration"` //in microseconds
HandIds []int `json:"handIds"`
PointableIds []int `json:"pointableIds"`
Speed float32 `json:"speed"`
Radius float32 `json:"radius"`
Progress float32 `json:"progress"`
Center Vector `json:"center"`
Normal Vector `json:"normal"`
StartPosition Vector `json:"startPosition"`
Position Vector `json:"position"`
Direction Vector `json:"direction"`
}
type InteractionBox struct {
//Valid bool `json: "valid"`
//The center of the InteractionBox in device coordinates (millimeters). This point is equidistant from all sides of the box
Center Vector `json:"center"`
Size Vector `json:"size"`
}
//homebrew
func (ib *InteractionBox) Norm(p Vector) Vector {
vec := Vector{}
vec.X = (p.X + ib.Center.X) / (ib.Size.X * 2)
vec.Y = (p.Y + ib.Center.Y) / (ib.Size.Y * 2)
vec.Z = (p.Z + ib.Center.Z) / (ib.Size.Z * 2)
//vec := p.Add(ib.Center.Vector3)
//vec := p.Add(ib.Center.Vector3)
//vec.X /= 2 * ib.Size.X
//vec.Y /= 2 * ib.Size.Y
//vec.Z /= 2 * ib.Size.Z
//return Vector{vec}
return vec
}
//from the JS API
func (ib *InteractionBox) NormalizePoint(p Vector, clamp bool) Vector {
vec := Vector{}
vec.X = (p.X-ib.Center.X)/ib.Size.X + 0.5
vec.Y = (p.Y-ib.Center.Y)/ib.Size.Y + 0.5
vec.Z = (p.Z-ib.Center.Z)/ib.Size.Z + 0.5
if clamp {
vec.X = glm.Clampf(vec.X, 0, 1)
vec.Y = glm.Clampf(vec.Y, 0, 1)
vec.Z = glm.Clampf(vec.Z, 0, 1)
}
return vec
}
func (ib *InteractionBox) DenormalizePoint(p Vector) Vector {
v := Vector{}
v.X = (p.X-0.5)*ib.Size.X + ib.Center.X
v.Y = (p.Y-0.5)*ib.Size.Y + ib.Center.Y
v.Z = (p.Z-0.5)*ib.Size.Z + ib.Center.Z
return v
}
type Frame struct {
CurrentFrameRate float32 `json:"currentFrameRate"`
Gestures []Gesture `json:"gestures"`
Hands []Hand `json:"hands"`
Pointables []Pointable `json:"pintables"`
Fingers []Pointable `json:"fingers"`
Tools []Pointable `json:"tools"`
ID int `json:"id"`
InteractionBox InteractionBox `json:"interactionBox"`
R Matrix `json:"r"`
S float32 `json:"s"`
T Vector `json:"t"`
// microseconds elapsed since the Leap started
Timestamp time.Duration `json:"timestamp"`
//Valid bool `json: "valid"`
}
/*
func (f *Frame) UnmarshalJSON(data []byte) error {
err := json.Unmarshal(data, f)
if err != nil {
switch t := err.(type) {
case *json.UnmarshalFieldError:
log.Println(t)
case *json.UnmarshalTypeError:
log.Println(t)
case *json.UnsupportedTypeError:
log.Println(t)
case *json.UnsupportedValueError:
log.Println(t)
case *json.SyntaxError:
log.Println(t)
case *json.InvalidUnmarshalError:
log.Println(t)
}
return err
}
f.Timestamp *= time.Microsecond
return nil
}
*/
type Vector struct {
glm.Vector3
}
func (v *Vector) UnmarshalJSON(data []byte) error {
vp := [3]float32{}
err := json.Unmarshal(data, &vp)
if err != nil {
switch t := err.(type) {
case *json.UnmarshalFieldError:
log.Println(t)
case *json.UnmarshalTypeError:
log.Println(t)
case *json.UnsupportedTypeError:
log.Println(t)
case *json.UnsupportedValueError:
log.Println(t)
case *json.SyntaxError:
log.Println(t)
case *json.InvalidUnmarshalError:
log.Println(t)
}
return err
}
v.X, v.Y, v.Z = vp[0], vp[1], vp[2]
return nil
}
type Matrix struct {
glm.Matrix3
}
func (m *Matrix) UnmarshalJSON(data []byte) error {
mp := [3][3]float32{}
err := json.Unmarshal(data, &mp)
if err != nil {
switch t := err.(type) {
case *json.UnmarshalFieldError:
log.Println(t)
case *json.UnmarshalTypeError:
log.Println(t)
case *json.UnsupportedTypeError:
log.Println(t)
case *json.UnsupportedValueError:
log.Println(t)
case *json.SyntaxError:
log.Println(t)
case *json.InvalidUnmarshalError:
log.Println(t)
}
return err
}
m.M11, m.M12, m.M13 = mp[0][0], mp[0][1], mp[0][2]
m.M21, m.M22, m.M23 = mp[1][0], mp[1][1], mp[1][2]
m.M31, m.M32, m.M33 = mp[2][0], mp[2][1], mp[2][2]
return nil
}
type Device struct {
Conn *websocket.Conn
Frames, Bin chan *Frame
quit chan struct{}
}
func (dev *Device) Close() {
close(dev.quit)
}
//enables or disables the gestures form the leapmotion
func (dev *Device) GestEnable(enable bool) error {
msg := struct {
EnableGestures bool `json:"enableGestures"`
}{enable}
err := dev.Conn.WriteJSON(msg)
//err := dev.Conn.WriteMessage(websocket.TextMessage, []byte("{enableGestures: true}"))
if err != nil {
return err
}
return nil
}
//Dial try to connects to the websocket and if successful will start a goroutine
//to decode frames from the websocket and send them on the Device channel
func Dial(url string) (*Device, error) {
//origin default to localhost
//if origin == "" {
// origin = "http://localhost/"
//}
//ws, err := websocket.Dial(url, "", origin)
//if err != nil {
// return nil, err
//}
conn, resp, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
if err == websocket.ErrBadHandshake {
return nil, fmt.Errorf("%v\n Response: %+v\n", err, resp)
}
}
dev := &Device{
Conn: conn,
Frames: make(chan *Frame, 2),
Bin: make(chan *Frame, 100),
quit: make(chan struct{})}
go listener(dev)
return dev, nil
}
//this is the decoder of the frames, here are also fixed some quirks
//as the timestamps being in microseconds
func listener(dev *Device) {
//dec := json.NewDecoder(dev.Conn)
var f *Frame
for {
select {
case <-dev.quit:
close(dev.Frames)
dev.Conn.Close()
return
case f = <-dev.Bin:
default: //new frame
f = &Frame{}
}
//if err := dec.Decode(f); err == io.EOF { //shutdown
// dev.Close()
//} else if err != nil {
// log.Panic("Error decoding from websocket ", err)
//}
err := dev.Conn.ReadJSON(f)
//_, p, err := dev.Conn.ReadMessage()
if err != nil {
log.Printf("Error receiving %+v\n", err)
}
//log.Println(string(p))
//fix the timestamps
f.Timestamp *= time.Microsecond
for _, g := range f.Gestures {
g.Duration *= time.Microsecond
}
//try to giva a frame to the clinet
select {
case dev.Frames <- f:
default: //if not ready skip this frame
log.Println("client not ready, skip frame")
select {
case dev.Bin <- f:
default:
}
}
}
}