def __init__(self): self._req_socket = nnpy.Socket(nnpy.AF_SP, nnpy.REQ) self._req_socket.connect('ipc://' + os.environ["KF_HOME"] + '/calendar/rep.ipc') self._sub_socket = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) self._sub_socket.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') self._sub_socket.connect('ipc://' + os.environ["KF_HOME"] + '/calendar/rep.ipc') self._current = 0 self._cbs = [] self._lock = threading.Lock() self._started = True self._sub_thread = threading.Thread(target=self.__loop) self._sub_thread.run()
def __init__(self, plugin_id, verbose=False): """ Initialize the object. plugin_id -- ID of this plugin verbose -- whether or not to enable verbose logging """ self.manager_socket = nnpy.Socket(nnpy.AF_SP, nnpy.REQ) self.manager_conn = \ self.manager_socket.connect(_IPC_BASE + 'gateway.addonManager') if verbose: print('IpcClient: Connected to server, registering...') try: self.manager_socket.send( json.dumps({ 'messageType': 'registerPlugin', 'data': { 'pluginId': plugin_id, } }).encode('utf-8')) except NNError as e: print('IpcClient: Failed to send message: {}'.format(e)) return try: resp = self.manager_socket.recv() except NNError as e: print('IpcClient: Error receiving message: {}'.format(e)) return if verbose: print('IpcClient: Received manager message: {}'.format(resp)) try: resp = json.loads(resp.decode('utf-8')) if not resp or 'messageType' not in resp or \ resp['messageType'] != 'registerPluginReply': raise ValueError() self.plugin_socket = nnpy.Socket(nnpy.AF_SP, nnpy.PAIR) self.plugin_conn = self.plugin_socket.connect( _IPC_BASE + resp['data']['ipcBaseAddr']) if verbose: print('IpcClient: Registered with PluginServer') except ValueError: print('IpcClient: Unexpected registration reply from gateway: {}'. format(resp))
def main(): addr = "tcp://127.0.0.1:8000" s1 = nnpy.Socket(nnpy.AF_SP, nnpy.REQ) s2 = nnpy.Socket(nnpy.AF_SP, nnpy.REP) s1.bind(addr) s2.connect(addr) s1.send(b"HELLO") s2.recv() s2.send(b"ACK") res = s1.recv() print("sys.version:\n{}\n\nres:\n{}".format(sys.version, res))
def digest_connect(self): sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) notifications_socket = self.controller.client.bm_mgmt_get_info( ).notifications_socket sub.connect(notifications_socket) sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') return sub
def counter_bot(send_to, box_id, interval=1.0, silent=False): """一秒ごとに適当なメッセージを投げる. スキーマ登録: crcr schema add --name counterbot count:int body:string :param str send_to: :param UUID box_id: """ socket = nnpy.Socket(nnpy.AF_SP, nnpy.REQ) socket.connect(send_to) i = 0 while True: i += 1 msg = json.dumps( { 'request': 'new_message', 'box_id': str(box_id), 'payload': { 'count': i, 'body': "Greetings from a bot", } }, indent=2, ensure_ascii=False ) socket.send(msg) if not silent: click.echo('I sent a message {} times'.format(i)) sleep(interval)
def update_decoder(): global viterbi_last_sec, reed_solomon_last_sec, skipped_symbols_last_sec, gain_last_sec, \ frequency_last_sec, omega_last_sec, i_symbol, q_symbol sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) sub.connect('tcp://192.168.1.109:6002') sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') viterbi_last_sec = 0 reed_solomon_last_sec = 0 skipped_symbols_last_sec = 0 viterbi_errors = 0 reed_solomon_errors = 0 skipped_symbols = 0 num = 1 timeold = 0 while True: data = json.loads(sub.recv()) time = datetime.fromisoformat(data['timestamp'][:-1]).second if time != timeold: viterbi_last_sec = int(viterbi_errors / num) reed_solomon_last_sec = int(reed_solomon_errors / num) skipped_symbols_last_sec = int(skipped_symbols / num) #print(num, viterbi_last_sec, reed_solomon_last_sec, skipped_symbols_last_sec) viterbi_errors = 0 reed_solomon_errors = 0 skipped_symbols = 0 num = 0 timeold = time viterbi_errors += data['viterbi_errors'] reed_solomon_errors += data['reed_solomon_errors'] skipped_symbols += data['skipped_symbols'] num += 1
def rand_bot(send_to, box_id): """ダミーのデータを投げる. スキーマ登録: crcr schema add --name dummybot count:int body:text :param str send_to: """ socket = nnpy.Socket(nnpy.AF_SP, nnpy.REQ) socket.connect(send_to) box_id = str(box_id) i = 0 while True: i += 1 req = { 'request': 'new_message', 'box_id': box_id, 'payload': { # 'count': i, 'at': datetime.datetime.utcnow().isoformat('T'), 'value': random.randint(-32768, 32767), } } raw = json.dumps(req).encode('utf-8') click.echo('send: {!r}'.format(raw)) socket.send(raw) resp = socket.recv() click.echo(' recv: {!r}'.format(resp)) time.sleep(random.randint(1, 100) / 1000.0)
def update_demodulator(): global viterbi_last_sec, reed_solomon_last_sec, skipped_symbols_last_sec, gain_last_sec, \ frequency_last_sec, omega_last_sec, i_symbol, q_symbol sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) sub.connect('tcp://192.168.1.109:6001') sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') gain_last_sec = 0 frequency_last_sec = 0 omega_last_sec = 0 gain = 0 frequency = 0 omega = 0 num = 1 timeold = 0 while True: data = json.loads(sub.recv()) time = datetime.fromisoformat(data['timestamp'][:-1]).second if time != timeold: gain_last_sec = round(gain / num, 3) frequency_last_sec = round(frequency / num, 2) omega_last_sec = round(omega / num, 3) #print(num, gain_last_sec, frequency_last_sec, omega_last_sec) gain = 0 frequency = 0 omega = 0 num = 0 timeold = time gain += data['gain'] frequency += data['frequency'] omega += data['omega'] num += 1
def __init__(self, dev, socket_addr): threading.Thread.__init__(self) self.daemon = True self.dev = dev self.socket_addr = socket_addr self.socket = nnpy.Socket(nnpy.AF_SP, nnpy.PAIR) self.socket.bind(socket_addr)
def recv_msgs(socket_addr, client): def get_msg_type(msg): type_, = struct.unpack('3s', msg[:3]) return type_ json_init(client) sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) sub.connect(socket_addr) sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') while True: msg = sub.recv() msg_type = get_msg_type(msg) print msg_type length = len(msg) #switch_id, cxt_id, list_id, buffer_id, num_samples = struct.unpack("<iiiQI", msg ) one = struct.unpack(">%dc" % length, msg[:length]) #two = struct.unpack( "I" , msg[:2] ) print one try: p = MSG_TYPES.get_msg_class(msg_type)(msg, length) except: print "Unknown msg type", msg_type continue p.extract() print p print p.data()
def __init__(self, queue, notification_socket, verbose=True): self.verbose = verbose self.queue = queue self.sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) self.sub.connect(notification_socket) self.sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '')
def recv_msgs(socket_addr, client): def get_msg_type(msg): type_, = struct.unpack('i', msg[:4]) return type_ json_init(client) sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) sub.connect(socket_addr) sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') while True: msg = sub.recv() msg_type = get_msg_type(msg) try: p = MSG_TYPES.get_msg_class(msg_type)(msg) except: print "Unknown msg type", msg_type continue p.extract() print p if p.type_ == MSG_TYPES.CONFIG_CHANGE: print "The JSON config has changed" print "Requesting new config from switch,", print "which may cause some log messages to be dropped" json_init(client)
def bitcoin_bot(send_to, box_id): """Bitcoinの取引をCircleCoreに送信. スキーマ登録: crcr schema add --name bitcoinbot address:string btc:float :param str send_to: """ socket = nnpy.Socket(nnpy.AF_SP, nnpy.REQ) socket.connect(send_to) websocket.enableTrace(True) receiver = websocket.create_connection('wss://ws.blockchain.info/inv') receiver.send('{"op":"unconfirmed_sub"}') box_id = str(box_id) while True: res = json.loads(receiver.recv()) for transaction in res['x']['out']: req = { 'request': 'new_message', 'box_id': str(box_id), 'payload': { 'address': transaction['addr'], 'btc': transaction['value'] / 10**8, }, } raw = json.dumps(req).encode('utf-8') print('send: {!r}'.format(raw)) socket.send(raw) resp = socket.recv() print(' recv: {!r}'.format(resp))
def echo_bot(receive_from, send_to, box_id): socket = nnpy.Socket(nnpy.AF_SP, nnpy.REQ) socket.connect(send_to) websocket.enableTrace(True) receiver = websocket.create_connection(receive_from) while True: receiver = websocket.create_connection(receive_from, timeout=10) i = 0 while True: i += 1 try: msg = receiver.recv() except websocket.WebSocketTimeoutException: logger.error("I'm not received new messages anymore. Reconnecting...") break for j, dic in enumerate(json.loads(msg)): req = { 'request': 'new_message', 'box_id': str(box_id), 'payload': dic, } raw = json.dumps(req).encode('utf-8') print('send: {!r}'.format(raw)) socket.send(raw) resp = socket.recv() print(' recv: {!r}'.format(resp))
def __init__(self, device_number, socket_addr, rcv_timeout): self.device_number = device_number self.socket_addr = socket_addr self.socket = nnpy.Socket(nnpy.AF_SP, nnpy.PAIR) self.socket.connect(socket_addr) self.rcv_timeout = rcv_timeout self.socket.setsockopt(nnpy.SOL_SOCKET, nnpy.RCVTIMEO, rcv_timeout) self.buffers = defaultdict(list)
def _check_ptf_nn_agent_availability(self, socket_addr): """Verify the nanomsg socket address exposed by ptf_nn_agent is available.""" sock = nnpy.Socket(nnpy.AF_SP, nnpy.PAIR) sock.connect(socket_addr) try: return wait_until(1, 0.2, lambda:sock.get_statistic(self.NN_STAT_CURRENT_CONNECTIONS) == 1) finally: sock.close()
def test(): client = nnpy.Socket(nnpy.AF_SP, nnpy.PULL) client.connect("tcp://%s:%d" % (NANO_HOST, NANO_PORT)) while True: msg = client.recv() if msg == "quit": client.close() break
def __init__(self, name, timeout): self.name = name self.timeout = timeout self.subscribers = {} self.sub_inputs = [] sub1 = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) sub1.connect(Constants.pub_addr) sub1.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') self.sub1_fd = sub1.getsockopt(level=nnpy.SOL_SOCKET, option=nnpy.RCVFD) self.subscribers[self.sub1_fd] = sub1 self.sub_inputs.append(self.sub1_fd) self.client = nnpy.Socket(nnpy.AF_SP, nnpy.REQ) self.client.connect(Constants.reg_addr)
def __init__(self, project, desc, addr="tcp://127.0.0.1:1337"): super(ReportMonitor, self).__init__(project, desc) self.sock = nnpy.Socket(nnpy.AF_SP, nnpy.PUB) self.sock.connect(addr) # TODO: Send message to archive existing (with date?) and start new. self.sock.send(self._fmt_start())
def test(size): client = nnpy.Socket(nnpy.AF_SP, nnpy.PUSH) client.connect("tcp://%s:%d" % (NANO_HOST, NANO_PORT)) msg = bytes("0" * size) for i in range(0, COUNT): client.send(msg) client.send("quit") client.close()
def _runIpcListener(self): sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) sub.connect(self.ipc_addr) sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') while self.runFlag: msg = sub.recv() print msg self.ipc_queue.put(msg)
def run_digest_loop(self): sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) notifications_socket = self.controller.client.bm_mgmt_get_info().notifications_socket sub.connect(notifications_socket) sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') while True: msg = sub.recv() self.recv_msg_digest(msg)
def run_digest_loop(self): sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) notifications_socket = "ipc:///tmp/bmv2-0-notifications.ipc" sub.connect(notifications_socket) sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') while True: msg = sub.recv() self.recv_msg_digest(msg)
def __init__(self, socket_url): """init. 接続を開く. :param str socket_url: socketのURI """ self._socket = nnpy.Socket(nnpy.AF_SP, nnpy.REP) self._socket.bind(socket_url)
def run_digest_loop(self): sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) sub.connect('ipc:///tmp/bmv2-0-notifications.ipc') sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') print "run_digest_loop" while True: msg = sub.recv() #print "msg:",msg self.recv_msg_digest(msg)
def test_basic(self): pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB) pub.setsockopt(nnpy.SOL_SOCKET, nnpy.IPV4ONLY, 0) pub.bind('inproc://foo') self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy.DOMAIN), 1) sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) sub_conn = sub.connect('inproc://foo') sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') pub.send('FLUB') poller = nnpy.PollSet((sub, nnpy.POLLIN)) self.assertEqual(len(poller.poll()), 1) self.assertEqual(poller.poll()[0], 1) self.assertEqual(sub.recv().decode(), 'FLUB') self.assertEqual(pub.get_statistic(nnpy.STAT_MESSAGES_SENT), 1) pub.close() sub.shutdown(sub_conn)
def await_notifications(self): sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) sock = self.controller.client.bm_mgmt_get_info().notifications_socket log("socket = {}".format(sock)) sub.connect(sock) sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') log("connected to socket.") while True: self.on_notify(sub.recv())
def create_socket(self, socket_folder, name, nn_mode): socket_path = os.path.join(socket_folder, name + '.sock') socket_addr = 'ipc://' + socket_path socket = nnpy.Socket(nnpy.AF_SP, nn_mode) socket.bind(socket_addr) fd = None if nn_mode != nnpy.PUB: fd = socket.getsockopt(level=nnpy.SOL_SOCKET, option=nnpy.RCVFD) self._logger.info('%s ready: %s', name, socket_path) return socket, fd
def test_basic_nn_error(self): address = 'inproc://timeout-always' req = nnpy.Socket(nnpy.AF_SP, nnpy.REQ) req.connect(address) req.setsockopt(nnpy.SOL_SOCKET, nnpy.RCVTIMEO, 500) with self.assertRaises(nnpy.errors.NNError): req.recv()
def __init__(self, dev, socket_addr, nn_rcv_buf=0, nn_snd_buf=0): threading.Thread.__init__(self) self.daemon = True self.dev = dev self.socket_addr = socket_addr self.socket = nnpy.Socket(nnpy.AF_SP, nnpy.PAIR) if nn_rcv_buf != 0: self.socket.setsockopt(nnpy.SOL_SOCKET, nnpy.RCVBUF, nn_rcv_buf) if nn_snd_buf != 0: self.socket.setsockopt(nnpy.SOL_SOCKET, nnpy.SNDBUF, nn_snd_buf) self.socket.bind(socket_addr)