Пример #1
0
    def __init__(self,
                 host,
                 port,
                 privkey,
                 nonce_update_interval=5.0,
                 nonce_offset=0):
        endpoint = 'http://{}:{}'.format(host, port)
        session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(pool_maxsize=50)
        session.mount(endpoint, adapter)

        self.transport = HttpPostClientTransport(
            endpoint,
            post_method=session.post,
            headers={'content-type': 'application/json'},
        )

        self.port = port
        self.privkey = privkey
        self.protocol = JSONRPCProtocol()
        self.sender = privatekey_to_address(privkey)
        # Needs to be initialized to None in the beginning since JSONRPCClient
        # gets constructed before the RaidenService Object.
        self.stop_event = None

        self.nonce_last_update = 0
        self.nonce_current_value = None
        self.nonce_lock = Semaphore()
        self.nonce_update_interval = nonce_update_interval
        self.nonce_offset = nonce_offset
Пример #2
0
    def __init__(self,
                 host,
                 port,
                 privkey,
                 nonce_update_interval=5.0,
                 nonce_offset=0):
        endpoint = 'http://{}:{}'.format(host, port)
        session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(pool_maxsize=50)
        session.mount(endpoint, adapter)

        self.transport = HttpPostClientTransport(
            endpoint,
            post_method=session.post,
            headers={'content-type': 'application/json'},
        )

        self.port = port
        self.privkey = privkey
        self.protocol = JSONRPCProtocol()
        self.sender = privatekey_to_address(privkey)

        self.nonce_last_update = 0
        self.nonce_current_value = None
        self.nonce_lock = Semaphore()
        self.nonce_update_interval = nonce_update_interval
        self.nonce_offset = nonce_offset
Пример #3
0
    def authenticate(self):
        """
        Performs authentication actions
        Patches `tinyrpc` to remove minor incompatibilities due to JSON-RPC
        protocol version differences. This is performed once.
        Initializes the RPCClient and RPCProxy instances that
        are used to make the requests to Lime.
        :return: None
        """
        logger.info("Authenticating LimeAPI client")
        if not LimeAPI._rpc_protocol_patched:
            LimeAPI.patch_json_rpc_protocol()
            LimeAPI._rpc_protocol_patched = True
        self.rpc_client = RPCClient(
            JSONRPCProtocol(),
            HttpPostClientTransport(endpoint=self.remote_api_url,
                                    headers=self.headers),
        )

        self.rpc_proxy = self.rpc_client.get_proxy()
        self.session_key = self.rpc_proxy.get_session_key(
            username=self.username, password=self.password)
        if not self._validate_session_key():
            raise Exception(f"Failed to validate session key: url={self.url} "
                            f"session_key={self.session_key}")
        self._authenticated = True
        logger.info(f"Acquired session key: {self.session_key}")
Пример #4
0
    def __init__(self, ip_hostname='pulsestreamer'):
        print("Connect to Pulse Streamer via JSON-RPC.")
        print("IP / Hostname:", ip_hostname)
        url = 'http://' + ip_hostname + ':8050/json-rpc'
        try:
            self.INFINITE = -1
            self.CONSTANT_ZERO = (0, 0, 0, 0)

            if sys.version_info.major > 2:
                client = RPCClient(url)
            else:
                client = RPCClient(JSONRPCProtocol(),
                                   HttpPostClientTransport(url))

            self.proxy = client.get_proxy()
            try:
                self.proxy.getSerial()
            except:
                try:
                    self.proxy.isRunning()
                    print(
                        "Pulse Streamer class not compatible with current firmware. Please update your firmware."
                    )
                    sys.exit(1)
                except:
                    print("No Pulse Streamer found at IP/Host-address: " +
                          ip_hostname)
                    sys.exit(1)
        except:
            print("No Pulse Streamer found at IP/Host-address: " + ip_hostname)
            sys.exit(1)
Пример #5
0
 def __init__(self, node_url=None):
     rpc_client = RPCClient(
         JSONRPCProtocol(),
         HttpPostClientTransport(
             node_url or os.getenv("RADIX_NODE_URL") or DEFAULT_NODE_URL
         ),
     )
     self._rpc_proxy = rpc_client.get_proxy(prefix=RPC_METHOD_PREFIX)
Пример #6
0
 def __init__(self, obj, one_way=False):
     url = obj.env['device_manager.settings']._get_param(
                                                 'mqtt_rpc_bridge_url')
     logger.debug('HTTP bridge url {}'.format(url))
     rpc_client = RPCClient(
         JSONRPCProtocol(),
         HttpPostClientTransport(url)
     )
     self.proxy = rpc_client.get_proxy(one_way=one_way)
Пример #7
0
def sessioned_client():
    session = requests.Session()
    adapter = requests.adapters.HTTPAdapter(pool_maxsize=100)
    session.mount('http://', adapter)
    client = HttpPostClientTransport(
        'http://%s:%d' % TEST_SERVER_ADDR,
        post_method=session.post
    )
    return client
Пример #8
0
 def __init__(self,
              host="127.0.0.1",
              port=4000,
              print_communication=True,
              privkey=None,
              sender=None):
     super(JSONRPCClient, self).__init__(port, print_communication, privkey,
                                         sender)
     self.transport = HttpPostClientTransport("http://{}:{}".format(
         host, port))
Пример #9
0
 def __init__(self,
              port=4000,
              print_communication=True,
              privkey=None,
              sender=None):
     "specify privkey for local signing"
     self.transport = HttpPostClientTransport(
         'http://127.0.0.1:{}'.format(port))
     self.print_communication = print_communication
     self.privkey = privkey
     self._sender = sender
Пример #10
0
    def __init__(self,
                 host: str,
                 port: int,
                 privkey: bytes,
                 gasprice: int = None,
                 nonce_update_interval: float = 5.0,
                 nonce_offset: int = 0):

        if privkey is None or len(privkey) != 32:
            raise ValueError('Invalid private key')

        endpoint = 'http://{}:{}'.format(host, port)
        self.session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(pool_maxsize=50)
        self.session.mount(endpoint, adapter)

        self.transport = HttpPostClientTransport(
            endpoint,
            post_method=self.session.post,
            headers={'content-type': 'application/json'},
        )

        self.port = port
        self.privkey = privkey
        self.protocol = JSONRPCProtocol()
        self.sender = privatekey_to_address(privkey)
        # Needs to be initialized to None in the beginning since JSONRPCClient
        # gets constructed before the RaidenService Object.
        self.stop_event = None

        self.nonce_last_update = 0
        self.nonce_available_value = None
        self.nonce_lock = Semaphore()
        self.nonce_update_interval = nonce_update_interval
        self.nonce_offset = nonce_offset
        self.given_gas_price = gasprice

        cache = cachetools.TTLCache(
            maxsize=1,
            ttl=RPC_CACHE_TTL,
        )
        cache_wrapper = cachetools.cached(cache=cache)
        self.gaslimit = cache_wrapper(self._gaslimit)
        cache = cachetools.TTLCache(
            maxsize=1,
            ttl=RPC_CACHE_TTL,
        )
        cache_wrapper = cachetools.cached(cache=cache)
        self.gasprice = cache_wrapper(self._gasprice)
Пример #11
0
    def setUpClass(cls):
        cls.context = zmq.Context()
        cls.subscriber = cls.context.socket(zmq.SUB)
        cls.remote_server = None

        cls.subscriber.connect("tcp://%s:5500" % HOST)
        cls.subscriber.setsockopt(zmq.SUBSCRIBE, "DEFAULT")
        cls.subscriber.setsockopt(zmq.SUBSCRIBE, "SUB_KEY")

        rpc_client = RPCClient(
            JSONRPCProtocol(),
            HttpPostClientTransport("http://%s:5501" % HOST))
        cls.remote_server = rpc_client.get_proxy()

        # Cross-test variables
        cls.coflow_id = ""
Пример #12
0
    def __init__(self, address='192.168.1.100'):

        if (toolbox.validate_ip(address)):
            self.ip = address
            self.url = 'http://' + self.ip + ':8050/json-rpc'
            try:
                self.client = RPCClient(JSONRPCProtocol(),
                                        HttpPostClientTransport(self.url))
            except:
                print('Error: cannot create RPC client!')
            try:
                self.ps = self.client.get_proxy()
            except:
                print('Error: cannot create proxy connection!')
        else:
            print("IP address not valid!")
Пример #13
0
 def __init__(self, ip_hostname='pulsestreamer'):
     print("Connect to Pulse Streamer via JSON-RPC.")
     print("IP / Hostname:", ip_hostname)
     self.ip_address = ip_hostname
     url = 'http://' + ip_hostname + ':8050/json-rpc'
     try:
         client = RPCClient(JSONRPCProtocol(),
                            HttpPostClientTransport(url, timeout=20))
         self.proxy = client.get_proxy()
         try:
             self.proxy.getSerial()
         except:
             try:
                 self.proxy.isRunning()
                 assert False, "Pulse Streamer class not compatible with current firmware. Please update your firmware." \
                     "For detailed information visit https://www.swabianinstruments.com/pulse-streamer-8-2-firmware/ " \
                     "or contact [email protected]"
             except AssertionError:
                 raise
             except:
                 assert False, "No Pulse Streamer found at IP/Host-address: " + ip_hostname
     except AssertionError:
         raise
     except:
         assert False, "No Pulse Streamer found at IP/Host-address: " + ip_hostname
     firmware_version = self.proxy.getFirmwareVersion()
     self.__version_1_1_or_higher = True if _compare_version_number(
         firmware_version, '1.1.0') >= 0 else False
     print("Pulse Streamer 8/2 firmware: v" + firmware_version)
     print("Client software: v" + __CLIENT_VERSION__)
     if (_compare_version_number(firmware_version) >= 0):
         print(
             "The Pulse Streamer 8/2 firmware is more up to date than your client software. We recommend to update your client software."
         )
         print(
             "For detailed information visit https://www.swabianinstruments.com/support/downloads/ or contact [email protected]"
         )
     elif (_compare_version_number(
             '.'.join(__CLIENT_VERSION__.split('.')[0:2] + ['0']),
             '.'.join(firmware_version.split('.')[0:2] + ['0'])) > 0):
         print(
             "Your client software is more up to date than the Pulse Streamer 8/2 firmware. We recommend to update the firmware of your Pulse Streamer 8/2."
         )
         print(
             "For detailed information visit https://www.swabianinstruments.com/support/downloads/ or contact [email protected]"
         )
Пример #14
0
    def __init__(self, args):
        cmd2.Cmd.__init__(self)

        self.prompt = "\n\033[1;33m# \033[0m"

        self.args = args

        uri = ''.join(
            ["http://", args['--host'], ":", args['--port'], "/jsonrpc"])

        rpc_client = RPCClient(JSONRPCProtocol(), HttpPostClientTransport(uri))

        self.xbmc = rpc_client

        self.input = namespaces.Input(self.xbmc)
        self.gui = namespaces.GUI(self.xbmc)
        self.jsonrpc = namespaces.JSONRPC(self.xbmc)
        self.video_library = namespaces.VideoLibrary(self.xbmc)
        self.player = namespaces.Player(self.xbmc)
Пример #15
0
 def __init__(self,
              host='127.0.0.1',
              port=4000,
              print_communication=True,
              privkey=None,
              sender=None,
              use_ssl=False,
              transport=None):
     "specify privkey for local signing"
     if transport is None:
         self.transport = HttpPostClientTransport(
             '{}://{}:{}'.format('https' if use_ssl else 'http', host,
                                 port),
             headers={'content-type': 'application/json'})
     else:
         self.transport = transport
     self.print_communication = print_communication
     self.privkey = privkey
     self._sender = sender
     self.port = port
Пример #16
0
    def __init__(self, zmq_context, source, destination, n_bytes):
        threading.Thread.__init__(self)

        self.key = "SENDER%i" % Sender.count
        Sender.count += 1

        self.subscriber = zmq_context.socket(zmq.SUB)
        self.subscriber.connect("tcp://%s:5500" % HOST)
        self.subscriber.setsockopt(zmq.SUBSCRIBE, self.key)

        rpc_client = RPCClient(
            JSONRPCProtocol(),
            HttpPostClientTransport("http://%s:5501" % HOST))
        self.remote_server = rpc_client.get_proxy()

        self.source = source
        self.destination = destination
        self.n_bytes = n_bytes

        self.result = ""
Пример #17
0
 def __init__(self, host='127.0.0.1', port=4000, print_communication=True,
              privkey=None, sender=None, use_ssl=False, transport=None):
     """
     Args:
         host (str): host address to connect to.
         port (int): port number to connect to.
         print_communication (bool): True to print the rpc communication.
         privkey: specify privkey for local signing
         sender (address): the sender address, computed from privkey if provided.
         use_ssl (bool): Use https instead of http.
         transport: Tiny rpc transport instance.
     """
     if transport is None:
         self.transport = HttpPostClientTransport('{}://{}:{}'.format(
             'https' if use_ssl else 'http', host, port), headers={'content-type': 'application/json'})
     else:
         self.transport = transport
     self.print_communication = print_communication
     self.privkey = privkey
     self._sender = sender
     self.port = port
Пример #18
0
 * we use the tinyrpc python package that allows us to represent the timetagger webserver
   as a python class and will hide all JSON-RPC details from us. 
 * The methods of this 'proxy class' are equivalent to the JSON-RPC interface

"""

#from jsonrpc import ServiceProxy
#timetagger = ServiceProxy('http://localhost:8080/json-rpc')

from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.transports.http import HttpPostClientTransport
from tinyrpc import RPCClient

rpc_client = RPCClient(
    JSONRPCProtocol(),
    HttpPostClientTransport('http://localhost:8080/json-rpc'))

# create the proxy class
timetagger = rpc_client.get_proxy()

timetagger.getSystemInfo()
timetagger.scanDevices()

res = timetagger.getDeviceList()
dev_id = res[0]['id']  # dev_id = '12520004J3' # FPGA serial number

res = timetagger.getModuleList(device=dev_id)
mod_id = res[0][
    'id']  # mod_id = 'ID-000001' # module created in web application beforehand

timetagger.getDeviceInfo(device=dev_id)
Пример #19
0
 def __init__(self, port=4000, print_communication=True):
     self.transport = HttpPostClientTransport(
         'http://127.0.0.1:{}'.format(port))
     self.print_communication = print_communication
import time
from threading import Thread

from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.transports.http import HttpPostClientTransport
from tinyrpc import RPCClient

rpc_client = RPCClient(
    JSONRPCProtocol(),
    HttpPostClientTransport('http://192.168.100.174:10090/'))

remote_server = rpc_client.get_proxy()

topicName = 'test_topic'
topicName = 'display_command'

k = 0


def queryTopics():
    while True:
        time.sleep(0.05)
        result = remote_server.ROSPublishTopics([])
        print "Server answered:"
        print result


prgThread = Thread(target=queryTopics)
prgThread.setDaemon(True)
prgThread.start()
Пример #21
0
def non_sessioned_client():
    client = HttpPostClientTransport('http://%s:%d' % TEST_SERVER_ADDR)
    return client
Пример #22
0
from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.transports.http import HttpPostClientTransport
from tinyrpc import RPCClient

rpc_client = RPCClient(
    JSONRPCProtocol(),
    HttpPostClientTransport('http://localhost:5000/v1/jsonrpc')
)

rpc_server = rpc_client.get_proxy()

print "pinging..."
pong = rpc_server.ping()
print "ping response: " + pong
resp = rpc_server.hello("Ashutosh")
print "hello world response: " + resp
from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.transports.http import HttpPostClientTransport
from tinyrpc import RPCClient
import time
import sys

rpc_client = RPCClient(JSONRPCProtocol(),
                       HttpPostClientTransport('http://192.168.1.100:8080/'))

remote_server = rpc_client.get_proxy()

try:
    vhf_data_rate = None
    uhf_data_rate = None
    sat_comm_data_rate = None
    while True:
        time.sleep(2)
        vhf_data_rate_json = remote_server.get_vhf_data_rate()
        vhf_data_rate = vhf_data_rate_json['vhf_rate']

        uhf_data_rate_json = remote_server.get_uhf_data_rate()
        uhf_data_rate = uhf_data_rate_json['uhf_rate']

        sat_comm_data_rate_json = remote_server.get_sat_comm_data_rate()
        sat_comm_data_rate = sat_comm_data_rate_json['satcomm_rate']

        print("\n\n\nCurrent VHF data rate is: ", vhf_data_rate)
        print("\n\n\nCurrent UHF data rate is: ", uhf_data_rate)
        print("\n\n\nCurrent SatComm data rate is: ", sat_comm_data_rate)

except KeyboardInterrupt:
Пример #24
0
#!/usr/bin/python

#
# pip install tinyrpc
#

from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.transports.http import HttpPostClientTransport
from tinyrpc import RPCClient

rpc_client = RPCClient(JSONRPCProtocol(),
                       HttpPostClientTransport('http://localhost:8080/'))

local = rpc_client.get_proxy()

s = '   This is a message  '
stripped = local.strip(str=s)

assert stripped == s.strip()

print 'rpc ok'

import sys
sys.exit(0)
Пример #25
0
'''
refer : https://github.com/mbr/tinyrpc/tree/master/examples
import gevent
import tinyrpc
import gevent-websocket
'''

from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.transports.http import HttpPostClientTransport
from tinyrpc import RPCClient

rpc_client = RPCClient(JSONRPCProtocol(),
                       HttpPostClientTransport('http://127.0.0.1:5000/'))

remote_server = rpc_client.get_proxy()

# call a method called 'reverse_string' with a single string argument
result = remote_server.reverse_string('Hello, World!')

print("Server answered: ", result)
Пример #26
0
from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.transports.http import HttpPostClientTransport
from tinyrpc import RPCClient

rpc_client = RPCClient(JSONRPCProtocol(),
                       HttpPostClientTransport('http://127.0.0.1:10090/'))

remote_server = rpc_client.get_proxy()

# call a method called 'reverse_string' with a single string argument
msgs = [{
    "topic": "tA",
    "params": {}
}, {
    "topic": "huh",
    "params": {}
}, {
    "topic": "/tf",
    "params": {
        "frame_id": "World",
        "child_frame_id": "Robot",
        "x": "10.0",
        "y": "2",
        "z": "3",
        "qx": "0.0",
        "qy": "0.7",
        "qz": "-0.7",
        "qw": "0.01"
    }
}, {
    "topic": "/tf",
Пример #27
0
# -*- coding: utf-8 -*-
"""Example RPC client for controlling a wotabag.

Requires tinrypc[httpclient] (https://github.com/mbr/tinyrpc).

"""

import time

from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.transports.http import HttpPostClientTransport
from tinyrpc import RPCClient

rpc_client = RPCClient(
    JSONRPCProtocol(),
    HttpPostClientTransport('http://raspberrypi.local:60715/'))

server = rpc_client.get_proxy(prefix='wotabag.')

# Retrieve server status
result = server.get_status()
print(result)

# Retrieve server playlist
result = server.get_playlist()
print(result)

# Test LED patterns
server.test_pattern()

# Start playback