This repository has been archived by the owner on Jan 10, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpacket.lua
339 lines (288 loc) · 8.31 KB
/
packet.lua
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
339
--[[
Copyright 2019 [Valeri Ochinski]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local crc32 = require 'crc32'.crc32
local maxPver = 1001
local socket = ...
-- Incoming messages
local IMessage = {
Version = 0x100000;
Ports = 0x100001;
Data = 0x100002;
}
-- Outcoming messages (constants have happened to be the same)
local OMessage = IMessage
local function crcTable(tab)
local crc = ''
for k,v in ipairs(tab) do
crc = crc32(crc, v)
end
return crc
end
local function getBatteryEnum(percent)
if percent >= 70 then
return 0x05 -- Full
elseif percent >= 50 then
return 0x04 -- High
elseif percent >= 30 then
return 0x03 -- Medium
elseif percent >= 15 then
return 0x02 -- Low
else
return 0x01 -- Dying
end
end
-- TODO: use string.(un)pack instead where possible (full bytes)
local function num2bytestring(num, len)
if len == 1 then
return string.char(num)
end
local arr = {}
for i=1,len do
arr[i] = (num >> ((i-1) * 8)) & 0xFF
end
return string.char(table.unpack(arr))
end
local function bytestring2num(str)
local arr = {str:byte(1, -1)}
local num = arr[1]
for i=2,#str do
num = (arr[i] << ((i-1) * 8)) | num
end
return num
end
--[[
Package structure (both sides):
bytes 1-4 DSUC/DSUS — magic number
bytes 5-6 protocol version number
bytes 7-8 length of package without header
bytes 9-12 CRC32 of package (while this was 0's)
bytes 13-16 client/server ID
bytes 17-20 message type
bytes 21-∞ other data
]]--
local getServerId
do
local sId
getServerId = function()
if sId then return sId end
math.randomseed(os.time())
sId = num2bytestring(math.random(1, 0xffffff), 4)
return sId
end
end
local function addHeader(data, msgtype, pVer)
local packet = {
'DSUS', -- DSU Server, I suppose?
num2bytestring(pVer, 2), -- Protocol version
num2bytestring(#data+4, 2), -- Size without header (add four for message type as it isn't part of header)
'\0\0\0\0', -- Placeholder for CRC (index 4)
getServerId(), -- Server ID (already string)
num2bytestring(msgtype, 4), -- Message type
data -- Other
}
-- Calculate CRC string
packet[4] = crcTable(packet):reverse() -- Big endian order or something?
return table.concat(packet)
end
-- Ports and Data packages have the same start
-- It have length of 11 bytes and 4 fields
local deviceStateHeaderLen = 11
local function deviceStateHeader(id, desc, battery)
return ('< B BBB I6 B'):pack(
id, -- ID
0x02, -- State: connected
desc.mplus_connected and 0x02 or 0x01, -- Device model: full or no gyro
0x02, -- Connection type: Bluetooth
desc.mac, -- MAC address
getBatteryEnum(battery) -- Battery
)
end
local function processIncoming(data, sendcb, endpoint, wiistate)
-- Basic sanity check
-- DSUC = DSU Client?
if #data < 16 or data:sub(1, 4) ~= 'DSUC' then
return nil
end
local pVer = bytestring2num(data:sub(5, 6))
-- Check if we speak it
if pVer > maxPver then
return nil
end
local pSize = bytestring2num(data:sub(7, 8)) + 16
if pSize > #data then
-- Package is incomplete
log.warning(('Data underflow: expected %d bytes, got %d'):format(pSize, #data))
return nil
elseif pSize < #data then
-- Probably we're screwed, but let's don't give up yet
data = data:sub(1, pSize)
end
-- We calculate CRC string, so no need to convert to number
local crc = data:sub(9, 12)
local realCrc = crcTable({data:sub(1, 8), '\0\0\0\0', data:sub(13)}):reverse()
-- Calculate CRC of message without CRC
if crc ~= realCrc then
return nil
end
local clientID = bytestring2num(data:sub(13, 16))
local messageType = bytestring2num(data:sub(17, 20))
-- Cut down header data for fancier indexes
local data = data:sub(21, -1)
if messageType == IMessage.Version then
log.debug('Sending version')
sendcb(addHeader(num2bytestring(maxPver, 2), OMessage.Version, 1001))
elseif messageType == IMessage.Ports then
log.debug('Sending ports')
local numPadRequests = ('<I4'):unpack(data:sub(1, 4))
if numPadRequests > 4 then return nil end
-- Check sanity first
for i=1+4, numPadRequests+4 do
if bytestring2num(data:sub(i, i)) >= 4 then return nil end
end
for i=1+4, numPadRequests+4 do
local curRequest = bytestring2num(data:sub(i, i))
local desc = wiistate[curRequest + 1]
if desc then
local answer = deviceStateHeader(curRequest, desc, desc.iface:get_battery() or 0)..'\0'
sendcb(addHeader(answer, OMessage.Ports, 1001))
else
-- Looks like fine answer anyways
sendcb(addHeader(num2bytestring(i-5, 1)..('\0'):rep(12), OMessage.Ports, 1001))
end
end
elseif messageType == IMessage.Data then
log.debug('Data requested')
local regFlags = bytestring2num(data:sub(1, 1))
local regId = bytestring2num(data:sub(2, 2))
local regMac = bytestring2num(data:sub(3, 8))
local newdat = {time = getTime(); endpoint = endpoint; id = clientID}
if regFlags == 0 then
log.debug('...for all ports')
wiistate.all[clientID] = newdat
elseif (regFlags & 0x01) ~= 0 then
local wiiId = regId + 1
local desc = wiistate[wiiId]
if desc then
desc.clients[clientID] = newdat
end
log.debug('...for wiimote %d%s', wiiId, desc and '' or ' (not found)')
elseif (regFlags & 0x02) ~= 0 then
-- FIXME: it can be slow
for k,desc in ipairs(wiistate) do
if desc.mac == regMac then
desc.clients[clientID] = newdat
break
end
end
end
else
log.debug('Unknown message')
end
end
local config = config
local ACCEL_G = config.ACCEL_G
local GYRO_DEG_PER_S = config.GYRO_DEG_PER_S
local function sendReport(id, desc, wiistate, clients, battery)
local ckeys = config.keys
local dkeys = desc.keys
local caccel = config.accel
local daccel = desc.accel
local cgyro = config.gyro
local dgyro = desc.mplus
if #clients == 0 then
return
end
-- Wrappers
local function key(k)
return dkeys[ckeys[k]]
end
local function keyA(k)
return dkeys[ckeys[k]] and 0xFF or 0x00
end
local function stick(name, axis)
local conf = ckeys[name][axis]
if dkeys[conf.plus] then
return 255
elseif dkeys[conf.minus] then
return 001
else
return 128
end
end
local function accel(axis)
local info = caccel[axis]
return (info[2] * daccel[info[1]]) / ACCEL_G
end
local function gyro(axis)
local info = cgyro[axis]
return (info[2] * dgyro[info[1]]) / GYRO_DEG_PER_S
end
-- Struct: answerStart, package count (different for each client), answerEnd
local answerStart = deviceStateHeader(id, desc, battery)..'\x01'
local answerEnd = ('<BB c2 BBBB BBBBBBBBBBBB c12 I8 fff fff'):pack(
-- Common keys
(key 'left' and 0x80 or 0x00) |
(key 'down' and 0x40 or 0x00) |
(key 'right' and 0x20 or 0x00) |
(key 'up' and 0x10 or 0x00) |
(key 'options' and 0x08 or 0x00) |
(key 'R3' and 0x04 or 0x00) |
(key 'L3' and 0x02 or 0x00) |
(key 'share' and 0x01 or 0x00) ,
(key 'Y' and 0x80 or 0x00) |
(key 'B' and 0x40 or 0x00) |
(key 'A' and 0x20 or 0x00) |
(key 'X' and 0x10 or 0x00) |
(key 'R1' and 0x08 or 0x00) |
(key 'L1' and 0x04 or 0x00) |
(key 'R2' and 0x02 or 0x00) |
(key 'L2' and 0x01 or 0x00) ,
-- PS and Touch
'\0\0',
-- Joysticks
stick('leftjoy', 'x'),
stick('leftjoy', 'y'),
stick('rightjoy', 'x'),
stick('rightjoy', 'y'),
-- Keys doubled as analogs
keyA 'left',
keyA 'down',
keyA 'right',
keyA 'up',
keyA 'Y',
keyA 'B',
keyA 'A',
keyA 'X',
keyA 'R1',
keyA 'L1',
keyA 'R2',
keyA 'L2',
'\0\0\0\0\0\0\0\0\0\0\0\0', -- Touch data (add IR? Sadly, no Cemuhook side support :\)
desc.mvtime,
accel 'x',
accel 'y',
accel 'z',
gyro 'p',
gyro 'y',
gyro 'r'
)
for k,client in ipairs(clients) do
local pkgcnt = wiistate.pkgcnt[client.id]
wiistate.pkgcnt[client.id] = pkgcnt + 1
socket:send_to(client.endpoint, addHeader(table.concat({answerStart, ('<I4'):pack(pkgcnt), answerEnd}), OMessage.Data, 1001))
end
end
return {
process = processIncoming;
send = sendReport;
}