Class: BelliteJsonRpc Abstract

Inherits:
BelliteJsonRpcApi show all
Defined in:
lib/bellite.rb

Overview

This class is abstract.

Next level of Bellite server API implementation: Basic operations with server like Bellite.

Instance Method Summary collapse

Methods inherited from BelliteJsonRpcApi

#_connect, #auth, #bindEvent, #connect, #findCredentials, #perform, #ping, #ready, #respondsTo, #unbindEvent, #version

Constructor Details

#initialize(cred = false, logging = false) ⇒ BelliteJsonRpc

constructor.

Parameters:

  • cred (String) (defaults to: false)

    Server credentials

  • logging (Boolean) (defaults to: false)

    Logging flag



233
234
235
236
237
238
239
# File 'lib/bellite.rb', line 233

def initialize(cred=false, logging=false)
    @_resultMap = {}
    @_evtTypeMap = {}
    @_nextMsgId = 100
    super(cred)
    @logging = logging
end

Instance Method Details

#_invoke(method, params = nil) ⇒ Promise

Calls JSON-RPC method

Parameters:

  • method (String)

    Method to call

  • params (Hash, Array, String, Float, Fixnum) (defaults to: nil)

    parameters for method

Returns:



253
254
255
256
257
258
259
260
261
# File 'lib/bellite.rb', line 253

def _invoke(method, params=nil)
    msgId = @_nextMsgId
    @_nextMsgId += 1
    res = _newResult(msgId)
    if not _sendJsonRpc(method, params, msgId)
        res.reject('Bellite client not connected')
    end
    return res.promise
end

#_newResult(msgId) ⇒ Promise

returns new Promise object, attached to msgId

Parameters:

  • msgId (Fixnum)

    id of message for this result

Returns:



266
267
268
269
270
# File 'lib/bellite.rb', line 266

def _newResult(msgId)
    res = deferred()
    @_resultMap[msgId] = res
    return res
end

#_notify(method, params = nil) ⇒ Boolean

Notify JSON-RPC server by method call, but skip response

Parameters:

  • method (String)

    Method to call

  • params (Hash, Array, String, Float, Fixnum) (defaults to: nil)

    parameters for method

Returns:

  • (Boolean)

    true if sent



245
246
247
# File 'lib/bellite.rb', line 245

def _notify(method, params=nil)
    return _sendJsonRpc(method, params)
end

#_recvJsonRpc(msgList) ⇒ Object

Receives JSON-RPC response or call from JSON-RPC Server

Parameters:

  • msgList (Array<String>)

    Array of messages from Server



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/bellite.rb', line 314

def _recvJsonRpc(msgList)
    msgList.each do |msg|
        begin
            msg = JSON.parse(msg)
            isCall = msg.has_key?("method")
        rescue
            next
        end
        logRecv(msg)
        begin
            if isCall
                on_rpc_call(msg)
            else
                on_rpc_response(msg)
            end
        end
    end
end

#_sendJsonRpc(method, params = nil, msgId = false) ⇒ Boolean

Sends JSON-RPC call to server

Parameters:

  • method (String)

    Method to call

  • params (Hash, Array, String, Float, Fixnum) (defaults to: nil)

    parameters for method

  • msgId (Fixnum) (defaults to: false)

    Message Id. If default, it uses internal autoincrement counter

Returns:

  • (Boolean)

    True if sent



277
278
279
280
281
282
283
284
285
286
287
# File 'lib/bellite.rb', line 277

def _sendJsonRpc(method, params=nil, msgId=false)
    msg = {"jsonrpc" => "2.0", "method" => method}
    if params
        msg['params'] = params
    end
    if msgId
        msg['id'] = msgId
    end
    logSend(msg)
    return _sendMessage(JSON.fast_generate(msg))
end

#_sendMessage(msg) ⇒ Boolean

Sends JSON-RPC string to server

Parameters:

  • msg (String)

    JSON-encoded JSON-RPC call to send

Returns:

  • (Boolean)

    True if sent



292
293
294
# File 'lib/bellite.rb', line 292

def _sendMessage(msg)
    raise NotImplementedError('Subclass Responsibility')
end

#emit(key, *args) ⇒ Object

Calls event handler when event occured

Parameters:

  • key (String)

    Event name like ready

  • *args (Hash, Array, Float, String, Fixnum)

    Argument to pass to event handler(s).



406
407
408
409
410
411
412
413
414
415
416
# File 'lib/bellite.rb', line 406

def emit(key, *args)
    if @_evtTypeMap.has_key? key
        @_evtTypeMap[key].each do |fn|
            begin
                fn.call(self, *args)
            rescue
                puts "EMIT exception"
            end
        end
    end
end

#logRecv(msg) ⇒ Object

Puts received packets to STDOUT

Parameters:

  • msg (String)

    Same as for _sendMessage



306
307
308
309
310
# File 'lib/bellite.rb', line 306

def logRecv(msg)
    if @logging
        puts "recv ==> " + JSON.fast_generate(msg)
    end
end

#logSend(msg) ⇒ Object

Puts send packets to STDOUT

Parameters:

  • msg (String)

    Same as for _sendMessage



298
299
300
301
302
# File 'lib/bellite.rb', line 298

def logSend(msg)
    if @logging
        puts "send ==> " + JSON.fast_generate(msg)
    end
end

#on(key, fn = false) ⇒ Proc

Adds any event handler

Parameters:

  • key (String)

    Event name like ready

  • fn (Proc) (defaults to: false)

    Function to bind on event

Returns:

  • (Proc)

    Your event handler or bindEvent method to bind your handler later if you skip fn



391
392
393
394
395
396
397
398
399
400
401
# File 'lib/bellite.rb', line 391

def on(key, fn=false)
    bindEvent = lambda do |fn|
        (@_evtTypeMap[key]||=[]) << fn
        return fn
    end
    if not fn
        return bindEvent
    else
        return bindEvent.call(fn)
    end
end

#on_auth_failed(msg) ⇒ Object

Called when auth is failed Emits 'auth' event handlers with fail flag

Parameters:

  • msg (String)

    Message from JSON-RPC server



379
380
381
# File 'lib/bellite.rb', line 379

def on_auth_failed(msg)
    emit('auth', false, msg)
end

#on_auth_succeeded(msg) ⇒ Object

Called when auth is successfully ended Emits 'auth' and 'ready' event handlers

Parameters:

  • msg (String)

    Message from JSON-RPC server



371
372
373
374
# File 'lib/bellite.rb', line 371

def on_auth_succeeded(msg)
    emit('auth', true, msg)
    emit('ready')
end

#on_connect(cred, f_ready) ⇒ Object

Called on connect to remote JSON-RPC server.

Parameters:

  • cred (Hash)

    Server credentials: port, host, token and original credentials string

  • f_ready (Future)

    Ready future instance



362
363
364
365
366
# File 'lib/bellite.rb', line 362

def on_connect(cred, f_ready)
    auth(cred['token']) \
        .then(f_ready.method(:resolve), f_ready.method(:reject)) \
        .then(method(:on_auth_succeeded), method(:on_auth_failed))
end

#on_rpc_call(msg) ⇒ Object

Called on JSON-RPC call FROM server.

Parameters:

  • msg (String)

    Server response with call



335
336
337
338
339
340
# File 'lib/bellite.rb', line 335

def on_rpc_call(msg)
    if msg['method'] == 'event'
        args = msg['params']
        emit(args['evtType'], args)
    end
end

#on_rpc_response(msg) ⇒ Object

Called on JSON-RPC response (not call) from Server

Parameters:

  • msg (String)

    Server respon with data



344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/bellite.rb', line 344

def on_rpc_response(msg)
    tgt = @_resultMap.delete msg['id']
    if tgt == nil
        return
    end

    if msg.has_key?('error')
        tgt.reject(msg['error'])
    elsif msg['result'][0]
        tgt.reject(msg['result'])
    else
        tgt.resolve(msg['result'])
    end
end