svgui/pyjs/jsonrpc/jsonrpc.py
author Andrey Skvortsov <andrej.skvortzov@gmail.com>
Wed, 07 Dec 2016 19:24:16 +0300
changeset 1596 f5868f866d2b
parent 728 e0424e96e3fd
child 1730 64d8f52bc8c8
permissions -rw-r--r--
stop PLC before unloading


This fixes segmentation fault if service was quit without stopping it.
It has happened if Beremiz service was quit using taskbar icon or by
closing Beremiz IDE (in case of autostarted local service).

In second case to trigger the bug following step has to be done:
1. Open Beremiz IDE
2. Open project, compile and connect to LOCAL:// runtime
3. Transfer and start the PLC program
4. Open other project without disconneting the PLC runtime
5. Close Beremiz IDE
import gluon.contrib.simplejson as simplejson
import types
import sys

class JSONRPCServiceBase:

    def __init__(self):
        self.methods={}

    def response(self, id, result):
        return simplejson.dumps({'version': '1.1', 'id':id,
                                 'result':result, 'error':None})
    def error(self, id, code, message):
        return simplejson.dumps({'id': id,
                                 'version': '1.1',
                                 'error': {'name': 'JSONRPCError',
                                           'code': code,
                                           'message': message
                                           }
                                     })

    def add_method(self, name, method):
        self.methods[name] = method

    def process(self, data):
        data = simplejson.loads(data)
        id, method, params = data["id"], data["method"], data["params"]
        if method in self.methods:
            try:
                result =self.methods[method](*params)
                return self.response(id, result)
            except BaseException:
                etype, eval, etb = sys.exc_info()
                return self.error(id, 100, '%s: %s' %(etype.__name__, eval))
            except:
                etype, eval, etb = sys.exc_info()
                return self.error(id, 100, 'Exception %s: %s' %(etype, eval))
        else:
            return self.error(id, 100, 'method "%s" does not exist' % method)

    def listmethods(self):
        return self.methods.keys()