Exemple #1
0
class JSONRPCClient:
    """The JSON-RPC client."""

    def __init__(self, host, port):
        self.sock = socket.socket()
        self.sock.connect((host, port))
        self.ID = 0
        self.shared_memory = SharedMemory()

    def close(self):
        """Closes the connection."""
        self.sock.close()

    def send(self, msg):
        """Sends a message to the server."""
        self.sock.sendall(msg.encode())
        return self.sock.recv(1024).decode()

    def invoke(self, method, *params):
        """Invokes a remote function."""
        self.shared_memory.increment_id()
        req = {
            'id': self.shared_memory.get_id(),
            'jsonrpc': '2.0',
            'method': method
        }
        if len(params) > 0:
            req['params'] = params
        req_json = json.dumps(req)
        msg = self.send(req_json)
        resp = json.loads(msg)
        switcher = {
            -32601: AttributeError('Method not found'),
            -32602: TypeError('Invalid params')
        }
        if 'error' not in msg:
            resp = resp['result']
        else:
            raise switcher.get(resp['error']['code'])
        return resp

    def __getattr__(self, name):
        """Invokes a generic function."""
        def inner(*params):
            return self.invoke(name, *params)
        return inner
def main():
    guide_pid = 0
    runner_pid = 0

    def shutdown():
        try:
            if ('guide_pid' in globals()) or ('guide_pid' in locals()):
                print('Kill Guide')
                os.kill(guide_pid, signal.SIGTERM)
            if ('runner_pid' in globals()) or ('runner_pid' in locals()):
                print('Kill Runner')
                os.kill(runner_pid, signal.SIGTERM)
            print('Done')

        except Exception as ex:
            print("It's a Pistol Exception in shutdown")
            g_log.exception(ex)

    try:
        #しっぽモーターを使って自立させる
        stand_on_tail_motor()

        # logフォルダの生成
        if not os.path.exists('./log/'):
            os.mkdir('./log/')

        # 日本時間に変更
        set_timezone_jst()

        # 日付フォーマッタを YYYYmmddHHMMSS に指定した
        log_datetime = strftime("%Y%m%d%H%M%S")
        print("Start time is {}".format(log_datetime))

        renice_processes()

        # プロセス間共有メモリ
        sh_mem = SharedMemory()

        # 設定ファイル読み込み
        setting = load_settings()

        runner_pid = os.fork()

        if runner_pid == 0:
            # NOTE: 倒立振子ライブラリを使う場合はrunner()を、ライントレーサー開発等で倒立振子ライブラリを使いたくない場合はrunner_stub()を使用すること
            runner(sh_mem, setting, log_datetime)
            print('Runner Done')
            sys.exit()

        guide_pid = os.fork()

        if guide_pid == 0:  # In a child process
            guide(sh_mem, setting, log_datetime)
            print('Guide Done')
            sys.exit()

        pistol(sh_mem)

        shutdown()

    except KeyboardInterrupt as ex:
        if (runner_pid > 0) and (guide_pid > 0):
            print("It's a KeyboardInterrupt")
            shutdown()
        elif (runner_pid == 0) or (guide_pid == 0):
            sleep(10)

    except Exception as ex:
        if (runner_pid > 0) and (guide_pid > 0):
            print("It's a Pistol Exception")
            g_log.exception(ex)
            shutdown()
        elif (runner_pid == 0):
            print("It's a Runner Exception in shutdown")
            g_log.exception(ex)
        elif (guide_pid == 0):
            print("It's a Guide Exception in shutdown")
            g_log.exception(ex)
Exemple #3
0

def callback_pmsg_timer(params):
    """Sends the command /pmsgs to the server"""
    try:
        params[0].sendall('/pmsgs'.encode())
    except ConnectionAbortedError:
        print('Aborted')


# Define socket host and port
SERVER_HOST = '127.0.0.1'
SERVER_PORT = 8000

# Initializes the shared memory
shared_memory = SharedMemory()

# Create socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to server
client_socket.connect((SERVER_HOST, SERVER_PORT))

username = input('> ')
client_socket.sendall(username.encode())

res = client_socket.recv(1024).decode()
print(res)

if check_response(res.split(), '/username', 'ok'):
    shared_memory.set_authenticated(True)
Exemple #4
0
def shareable_wrap(existing_obj=None,
                   shmem_name=None,
                   cls=None,
                   shape=(0, ),
                   strides=None,
                   dtype=None,
                   format=None,
                   **kwargs):
    """Provides a fast, convenient way to encapsulate objects that support
    the buffer protocol as both producer and consumer, duplicating the
    original object's data in shared memory and returning a new wrapped
    object that when serialized via pickle does not serialize its data.

    The function has been written in a general way to potentially work with
    any object supporting the buffer protocol as producer and consumer.  It
    is known to work well with NumPy ndarrays.  Among the Python core data
    types and standard library, there are a number of objects supporting
    the buffer protocol as a producer but not as a consumer.

    Without an example of a producer+consumer of the buffer protocol in
    the Python core to demonstrate the use of this function, this function
    was removed from multiprocessing.shared_memory."""

    augmented_kwargs = dict(kwargs)
    extras = dict(shape=shape, strides=strides, dtype=dtype, format=format)
    for key, value in extras.items():
        if value is not None:
            augmented_kwargs[key] = value

    if existing_obj is not None:
        existing_type = getattr(existing_obj, "_proxied_type",
                                type(existing_obj))

        #agg = existing_obj.itemsize
        #size = [ agg := i * agg for i in existing_obj.shape ][-1]
        # TODO: replace use of reduce below with above 2 lines once available
        size = reduce(lambda x, y: x * y, existing_obj.shape,
                      existing_obj.itemsize)

    else:
        assert shmem_name is not None
        existing_type = cls
        size = 1

    shm = SharedMemory(shmem_name, size=size)

    class CustomShareableProxy(existing_type):
        def __init__(self, *args, buffer=None, **kwargs):
            # If copy method called, prevent recursion from replacing _shm.
            if not hasattr(self, "_shm"):
                self._shm = shm
                self._proxied_type = existing_type
            else:
                # _proxied_type only used in pickling.
                assert hasattr(self, "_proxied_type")
            try:
                existing_type.__init__(self, *args, **kwargs)
            except Exception:
                pass

        def __repr__(self):
            if not hasattr(self, "_shm"):
                return existing_type.__repr__(self)
            formatted_pairs = ("%s=%r" % kv
                               for kv in self._build_state(self).items())
            return f"{self.__class__.__name__}({', '.join(formatted_pairs)})"

        #def __getstate__(self):
        #    if not hasattr(self, "_shm"):
        #        return existing_type.__getstate__(self)
        #    state = self._build_state(self)
        #    return state

        #def __setstate__(self, state):
        #    self.__init__(**state)

        def __reduce__(self):
            return (
                shareable_wrap,
                (
                    None,
                    self._shm.name,
                    self._proxied_type,
                    self.shape,
                    self.strides,
                    self.dtype.str if hasattr(self, "dtype") else None,
                    getattr(self, "format", None),
                ),
            )

        def copy(self):
            dupe = existing_type.copy(self)
            if not hasattr(dupe, "_shm"):
                dupe = shareable_wrap(dupe)
            return dupe

        @staticmethod
        def _build_state(existing_obj, generics_only=False):
            state = {
                "shape": existing_obj.shape,
                "strides": existing_obj.strides,
            }
            try:
                state["dtype"] = existing_obj.dtype
            except AttributeError:
                try:
                    state["format"] = existing_obj.format
                except AttributeError:
                    pass
            if not generics_only:
                try:
                    state["shmem_name"] = existing_obj._shm.name
                    state["cls"] = existing_type
                except AttributeError:
                    pass
            return state

    proxy_type = type(
        f"{existing_type.__name__}Shareable",
        CustomShareableProxy.__bases__,
        dict(CustomShareableProxy.__dict__),
    )

    if existing_obj is not None:
        try:
            proxy_obj = proxy_type(buffer=shm.buf,
                                   **proxy_type._build_state(existing_obj))
        except Exception:
            proxy_obj = proxy_type(buffer=shm.buf,
                                   **proxy_type._build_state(
                                       existing_obj, True))

        mveo = memoryview(existing_obj)
        proxy_obj._shm.buf[:mveo.nbytes] = mveo.tobytes()

    else:
        proxy_obj = proxy_type(buffer=shm.buf, **augmented_kwargs)

    return proxy_obj
Exemple #5
0
def print_session(key_id):
    #memory = SharedMemory
    print(SharedMemory.get(key_id))
Exemple #6
0
 def __init__(self, host, port):
     self.sock = socket.socket()
     self.sock.connect((host, port))
     self.ID = 0
     self.shared_memory = SharedMemory()
Exemple #7
0
from shared_memory import SharedMemory
from printing import print_session

SharedMemory.modify('nome', 'Ivan')
SharedMemory.modify('nome', 'Juan')
SharedMemory.modify('nome', 'John')
print_session('nome')