File size: 5,010 Bytes
7e9dc27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
-- This file is part of broadcaster library
-- Licensed under MIT License
-- Copyright (c) 2019 Ranx
-- https://github.com/r4nx/broadcaster
-- Version 0.2.0

local proto = {}

local packet = require 'broadcaster.packet'
local utils = require 'broadcaster.utils'
local Session = require 'broadcaster.session'
local inspect = require 'inspect'

local logger = require 'log'
local sessions = {}

-- Args:
--    bin <table> - binary sequence
--    callback <function> - function to call when session is finished
--      (session is passed as first argument to callback)
function proto.processPacket(bin, callback)
    logger.trace('>> processPacket')
    proto.collectOldSessions()
    local packetCode = utils.binToDec({unpack(bin, 1, 3)})
    logger.debug('packet code: ' .. packetCode)

    packetProcessors = utils.switch({
        [packet.PACKETS_ID.START_TRANSFER] = function()
            logger.debug('start packet identified')
            local startPacket = packet.StartTransferPacket.unpack(bin)
            local sessionId = startPacket.sessionId

            if sessions[sessionId] ~= nil then
                sessions[sessionId] = nil
                logger.warn(('session collision: session %d was removed'):format(sessionId))
                return
            end

            sessions[sessionId] = Session()
            logger.debug('created new session ' .. sessionId)
        end,
        [packet.PACKETS_ID.DATA] = function()
            logger.debug('data packet identified')
            local result, returned = pcall(packet.DataPacket.unpack, bin)
            if not result then
                logger.warn('failed to unpack:\n' .. returned)
                return
            end
            local sessionId = returned.sessionId

            local sess = sessions[sessionId]
            if sess ~= nil then
                sess:appendData(returned.data)
            else
                logger.warn('cannot found session for data packet: ' .. sessionId)
                logger.warn('sessions list:\n  ' .. inspect(sessions))
            end
        end,
        [packet.PACKETS_ID.HANDLER_ID] = function()
            logger.debug('handler id packet identified')
            local result, returned = pcall(packet.HandlerIdPacket.unpack, bin)
            if not result then
                logger.warn('failed to unpack:\n' .. returned)
                return
            end
            local sessionId = returned.sessionId

            local sess = sessions[sessionId]
            if sess ~= nil then
                sess:appendHandlerId(returned.handlerId)
            else
                logger.warn('cannot found session for handler id packet: ' .. sessionId)
                logger.warn('sessions list:\n  ' .. inspect(sessions))
            end
        end,
        [packet.PACKETS_ID.STOP_TRANSFER] = function()
            logger.debug('stop packet identified')
            local stopTransferPacket = packet.StopTransferPacket.unpack(bin)
            local sessionId = stopTransferPacket.sessionId

            local sess = sessions[sessionId]
            if sess ~= nil then
                sessions[sessionId] = nil
                logger.debug(('removed session %d because stop packet received'):format(sessionId))
                callback(sess)
            else
                logger.warn('cannot found session for stop transfer packet: ' .. sessionId)
                logger.warn('sessions list:\n  ' .. inspect(sessions))
            end
        end,
        default = function() logger.warn('cannot identify packet') end
    })

    packetProcessors:case(packetCode)
end

local function randomSessionId()
    math.randomseed(os.time() ^ 5)
    return math.random(0, 15)  -- 4 bit
end

-- Args:
--    data <table> - table of decimal numbers
--    handlerId <table> - encoded handler id
-- Returns:
--    Table of binary sequences
function proto.packData(data, handlerId)
    local sessionId = randomSessionId()
    local packets = {packet.StartTransferPacket(sessionId):pack()}

    for _, handlerIdPart in ipairs(handlerId) do
        packets[#packets + 1] = packet.HandlerIdPacket(handlerIdPart, sessionId):pack()
    end

    for _, dataPart in ipairs(data) do
        packets[#packets + 1] = packet.DataPacket(dataPart, sessionId):pack()
    end

    packets[#packets + 1] = packet.StopTransferPacket(sessionId):pack()

    return packets
end

function proto.sendData(...)
    logger.warn('sendData function is deprecated and will be removed, use packData instead')
    return proto.packData(...)
end

function proto.collectOldSessions()
    for sessionId, sess in pairs(sessions) do
        if os.time() - sess.lastUpdate > 30 then
            sessions[sessionId] = nil
            logger.debug('collected old session ' .. sessionId)
        end
    end
end

function proto.getSessions()
    return sessions
end

return proto