def post(self, request, *args, **kwargs): message = request.POST msg = { "shared_secret": message["shared_secret"], "target": message["target"], } color = "#00ff00" if message["level"] == "OK" or message["level"] == "UP" else "#ffff00" if \ message["level"] == "WARNING" else "#ff0000" if message["level"] == "DOWN" or message["level"] \ == "CRITICAL" else "#a0a0a0" if message["level"] == "UNKNOWN" else "#000000" if message["type"] == "host": msg["content"] = f"Host {message['level']} ALERT\n" \ f"\n" \ f"Host: {message['host']}\n" \ f"Alias: {message['alias']}\n" \ f"Output: {message['output']}\n" msg["content_formatted"] = f"<strong><font color=\"{color}\">Host {message['level']} ALERT</font>" \ f"</strong><br /><pre><code>Host: {message['host']}<br />Alias: " \ f"{message['alias']}<br />Output: {message['output']}</code></pre>" else: msg["content"] = f"Service {message['level']} ALERT\n" \ f"\n" \ f"Host: {message['host']}\n" \ f"Service: {message['description']}\n" \ f"Output: {message['output']}\n" msg["content_formatted"] = f"<strong><font color=\"{color}\">Service {message['level']} ALERT</font>" \ f"</strong><br /><pre><code>Host: {message['host']}<br />Service: " \ f"{message['description']}<br />Output: {message['output']}</code></pre>" ctx = Context.instance() socket = ctx.socket(PAIR) socket.connect("tcp://127.0.0.1:55555") socket.send_string(json.dumps(msg)) socket.close() return JsonResponse({"result": True})
def __init__(self, address='*', port1='5566', port2='5567'): print("Current libzmq version is %s" % zmq.zmq_version()) print("Current pyzmq version is %s" % zmq.pyzmq_version()) self.context = Context.instance() self.url1 = "tcp://{}:{}".format(address, port1) self.url2 = "tcp://{}:{}".format(address, port2) self.xpub_xsub_proxy()
def __init__(self): self.isServiceAvailable = True signal(SIGINT, self.exit_gracefully) signal(SIGTERM, self.exit_gracefully) self.logging = ErrorReportingClient(service="parser") self.context = Context.instance() self.refresh_coingecko_index() processes = [ Thread(target=self.refresh_coingecko_exchange_rates), Thread(target=self.refresh_ccxt_index), Thread(target=self.refresh_serum_index), Thread(target=self.refresh_iexc_index) ] for p in processes: p.start() for p in processes: p.join() self.jobQueue = Thread(target=self.job_queue) self.jobQueue.start() self.socket = self.context.socket(ROUTER) self.socket.bind("tcp://*:6900") print("[Startup]: Ticker Parser is online")
def __init__(self, domain="", camera_id: int = 0, openface_port: int = 6004, delay: int = 2, identifier=None): """ Args: camera_id: index of the camera you want to use (if you only have one camera: 0) """ Service.__init__(self, domain="", identifier=identifier) self.camera_id = camera_id self.openface_port = openface_port self.openface_running = False self.threshold = delay # provide number of seconds as parameter, one second = 15 frames ctx = Context.instance() self.openface_endpoint = ctx.socket(zmq.PAIR) self.openface_endpoint.bind(f"tcp://127.0.0.1:{self.openface_port}") startExtraction = f"{os.path.join(get_root_dir(), 'tools/OpenFace/build/bin/FaceLandmarkVidZMQ')} -device {self.camera_id} -port 6004" # todo config open face port self.p_openface = subprocess.Popen( startExtraction.split(), stdout=subprocess.PIPE) # start OpenFace self.extracting = False self.extractor_thread = None
def __init__(self, *, dealer_connect, pub_addr, pub_type, timeout=10, identity=None, **kwargs): self.ctx = Context.instance() if identity is None: import os self.identity = os.getpid().to_bytes(3, byteorder="big") log.debug("Got no identity. Using PID {}", identity) else: self.identity = identity self.timeout = timeout log.info("Connecting dealer to {}, with identity {}", dealer_connect, self.identity) self.dealer = self.ctx.socket(zmq.DEALER) self.dealer.setsockopt(zmq.IDENTITY, self.identity) self.dealer.connect(dealer_connect) self.pub = self.ctx.socket(zmq.PUB) getattr(self.pub, pub_type)(pub_addr) self.output = None self.proof = None
def __init__(self): self.isServiceAvailable = True self.isManager = False if len(environ["HOSTNAME"].split( "-")) != 2 else environ["HOSTNAME"].split("-")[1] == "0" if self.isManager: print("[Startup]: This instance is a database manager") else: print("[Startup]: This instance is a slave") signal(SIGINT, self.exit_gracefully) signal(SIGTERM, self.exit_gracefully) self.accountLock = Lock() self.guildLock = Lock() self.logging = ErrorReportingClient(service="database") self.context = Context.instance() self.accountsLink = database.collection("accounts").on_snapshot( self.update_account_properties) while not self.accountsReady: sleep(1) self.discordPropertiesGuildsLink = database.collection( "discord/properties/guilds").on_snapshot( self.update_guild_properties) while not self.guildsReady: sleep(1) self.discordPropertiesUnregisteredUsersLink = database.collection( "discord/properties/users").on_snapshot( self.update_unregistered_users_properties) while not self.usersReady: sleep(1)
def __init__(self, handler: Optional[Union[Callable[[str, str, str], None], Any]] = None, watch_cb: Optional[Callable[[str, str], None]] = None, unwatch_cb: Optional[Callable[[str, str], None]] = None, raw_cb: Optional[Callable[[Sequence[bytes]], None]] = None, bind_address: Optional[str] = None, connect_addresses: Optional[Iterable[str]] = None, interval: float = 0.1, ctx: Optional[Context] = None): self._bind_address = bind_address self._connect_addresses = list(connect_addresses) if handler \ and hasattr(handler, 'notify_line') \ and callable(getattr(handler, 'notify_line')): # treat handler as an object with notify_* methods self._line_cb = handler.notify_line self._watch = getattr(handler, 'notify_watch', watch_cb) self._unwatch = getattr(handler, 'notify_unwatch', unwatch_cb) else: # otherwise treat it as the handler function for lines self._line_cb = handler self._watch_cb = watch_cb self._unwatch_cb = unwatch_cb self._raw_cb = raw_cb self._interval = interval self._ctx = ctx or Context.instance() self._sub_socket = None self._pull_socket = None
def run(self): # REP port = 38780 context = Context.instance() socket = context.socket(zmq.REP) socket.bind("tcp://*:%s" % port) # Object_detection_for_adapter.py 依赖于shell中的变量,所以需要在命令行里启动 # ~/codelab_adapter目录 codelab_adapter_dir = pathlib.Path.home() / "codelab_adapter" script = "{}/ExploreOpencvDnn/main_for_adapter.py".format( codelab_adapter_dir) if (platform.system() == "Darwin"): # which python3 python = "/usr/local/bin/python3" if platform.system() == "Windows": python = "python" if platform.system() == "Linux": python = "/usr/bin/python3" cmd = [python, script] tf = subprocess.Popen(cmd) while self._running: tf_class = socket.recv_json().get("class") socket.send_json({"status": "200"}) # 发往scratch3.0中的eim积木 self.publish({"topic": "eim", "payload": tf_class}) # release socket tf.terminate() tf.wait() socket.close() context.term()
def __init__(self, connect_addresses: Iterable[str], ctx: Optional[Context] = None): self._ctx = ctx or Context.instance() self._socket = self._ctx.socket(PUSH) for address in connect_addresses: self._socket.connect('tcp://' + address)
def __init__(self, options): self.ctx = Context.instance() self.sck = self.ctx.socket(REQ) self.poller = Poller() self.opts = options self.sck.setsockopt(LINGER, 0) self.poller.register(self.sck, POLLIN)
def __init__(self, args): self.ctx = Context.instance() # set default options for all sockets self.ctx.linger = 0 self.logger = logging.getLogger('dcamp.app') self.args = args
def __init__(self, *args, **kwargs): self.context = Context.instance() self.loop = IOLoop.instance() self.control_socket = self.context.socket(SUB) self.control_socket.setsockopt(LINGER, 0) # discard unsent messages on close self.control_socket.setsockopt(SUBSCRIBE, '') self.control_socket.connect('tcp://{}:{}'.format(MANAGER_PUB_ADDRESS, MANAGER_PUB_PORT)) self.control_stream = ZMQStream(self.control_socket, self.loop) self.control_stream.on_recv_stream(self.control_handler)
def create_soc(self,url): self.ctx=Context.instance() self.pub = self.ctx.socket(zmq.PUB) try: self.pub.bind(url) self.topic_r=url except : print("zmq pub socket failed")
def __init__(self, app: Optional[Flask] = None, context: Optional[Context] = None, prefix: str = "ZMQ"): self.prefix = prefix self.app = app self.context = context or Context.instance() if app is not None: self.init_app(app)
def __init__(self): self.logger = logging.getLogger('manager-server') self.context = Context.instance() self.loop = IOLoop.instance() self.control_socket = self.context.socket(PUB) self.control_socket.setsockopt(LINGER, 0) # discard unsent messages on close self.control_socket.bind('tcp://{}:{}'.format(MANAGER_PUB_ADDRESS, MANAGER_PUB_PORT)) self.register_signals()
def create_soc(self, url): print("subscribe topic:" + url) self.ctx = Context.instance() self.sub = self.ctx.socket(zmq.SUB) try: self.sub.connect(url) except: print("zmq recv socket failed") self.sub.setsockopt(zmq.SUBSCRIBE, b"") self.enable()
def main(): store = DirectoryServerStore() context = Context.instance() try: directory_server(store, context) except KeyboardInterrupt: context.destroy() print('') except BaseException as e: context.destroy() raise e
def __init__(self, address='127.0.0.1', port='5566'): print("Current libzmq version is %s" % zmq.zmq_version()) print("Current pyzmq version is %s" % zmq.pyzmq_version()) if len(sys.argv) > 1: address = sys.argv[1] if len(sys.argv) > 2: port = sys.argv[2] self.context = Context.instance() self.url = "tcp://{}:{}".format(address, port) self.hostname = socket.gethostname() self.pub_ep_time()
def __init__(self): self.isServiceAvailable = True signal(SIGINT, self.exit_gracefully) signal(SIGTERM, self.exit_gracefully) self.logging = ErrorReportingClient(service="details_server") self.context = Context.instance() self.socket = self.context.socket(ROUTER) self.socket.bind("tcp://*:6900") print("[Startup]: Detail Server is online")
def __init__(self, pull_addr, pull_type, router_addr, router_type, gather_time, hash_algo): self.ctx = Context.instance() self.worker_deque = deque() self.gather_time = gather_time self.hash_checker = HashChecker(hash_algo) self.pull = self.ctx.socket(zmq.PULL) log.info('{} PULL socket to {}', 'Binding' if pull_type == 'bind' else 'Connecting', pull_addr) getattr(self.pull, pull_type)(pull_addr) self.router = self.ctx.socket(zmq.ROUTER) log.info('{} ROUTER socket to {}', 'Binding' if router_type == 'bind' else 'Connecting', router_addr) getattr(self.router, router_type)(router_addr)
def connect(addr, no_linger=True, auth=None, logger=None): """Creates the connection socket and connects to jomiel. Args: addr (string): The endpoint address to connect to no_linger (bool): If True, sets the socket option LINGER to 0 (disable). The default is True. auth (obj): The authentication options (if any). Use the curve_opts_new, ssh_opts_new and auth_opts_new functions from .auth logger (obj): The logger to use (if any) Returns: obj: the created socket TODO: - Depending on the --auth-mode value, apply whatever needs to be applied to establish the connection """ from zmq import Context, REQ, LINGER ctx = Context.instance() sck = ctx.socket(REQ) skip_connect = False if auth: if auth.curve: # Setup CURVE from .auth.curve import setup setup(sck, auth.curve, logger=logger) elif auth.ssh: # Setup SSH from .auth.ssh import setup setup(sck, addr, auth.ssh) skip_connect = True if not skip_connect: sck.connect(addr) if no_linger: sck.setsockopt(LINGER, 0) return sck
def setup(socket): """Load the CURVE certificates required for a secure server connection. Args: socket (obj): The zmq socket to use Returns: Nothing """ from jomiel.cache import opts from zmq import Context ctx = Context.instance() def auth_init(): """Start an authenticator for this context.""" from zmq.auth.thread import ThreadAuthenticator from jomiel.log import lg auth = ThreadAuthenticator(ctx, log=lg()) auth.start() auth.allow(opts.curve_allow) # Tell the authenticator to use the client certificates in the # specified directory. # from os.path import abspath pubdir = abspath(opts.curve_public_key_dir) auth.configure_curve(domain=opts.curve_domain, location=pubdir) return auth auth = auth_init() from jomiel_comm.auth.curve import load_cert_file (pubkey, seckey) = load_cert_file(opts.curve_server_key_file) socket.curve_secretkey = seckey socket.curve_publickey = pubkey # Must come before bind. socket.curve_server = True return auth
def __init__(self): self.isServiceAvailable = True signal(SIGINT, self.exit_gracefully) signal(SIGTERM, self.exit_gracefully) self.logging = ErrorReportingClient(service="quote_server") try: rawData = CoinGecko.connection.get_coin_by_id(id="bitcoin", localization="false", tickers=False, market_data=True, community_data=False, developer_data=False) CoinGecko.lastBitcoinQuote = rawData["market_data"]["current_price"]["usd"] except: pass self.context = Context.instance() self.socket = self.context.socket(ROUTER) self.socket.bind("tcp://*:6900") print("[Startup]: Quote Server is online")
def __init__(self, loop=None, endpoint="tcp://127.0.0.1:9999", server=True, type=zmq.ROUTER): super(ZeroActor, self).__init__() self.ctx = Context.instance() self.isserver = server self.socket = self.ctx.socket(type) self.endpoint = endpoint if loop is None: self.io = DecafIOThread() self.io.register_actor(self) self.io.start() self.run() else: self.io = loop self.io.register_actor(self) self.run()
def run(self): # REP port = 38779 context = Context.instance() socket = context.socket(zmq.REP) socket.bind("tcp://*:%s" % port) # Object_detection_for_adapter.py 依赖于shell中的变量,所以需要在命令行里启动 cmd = "/usr/bin/python3 /home/pi/Object_detection_for_adapter.py" tf = subprocess.Popen(cmd, shell=True) while self._running: tf_class = socket.recv_json().get("class") socket.send_json({"status": "200"}) # 发往scratch3.0中的eim积木 self.publish({"topic": "eim", "payload": tf_class}) # release socket tf.terminate() tf.wait() socket.close() context.term()
def __init__(self, pipe, local_ep, local_uuid, config_svc): Thread.__init__(self, name='dcamp.service.{}'.format(self)) self.ctx = Context.instance() self.__control_pipe = pipe assert isinstance(local_ep, EndpntSpec) self.__endpoint = local_ep assert isinstance(local_uuid, UUID) self.__uuid = local_uuid self.__cfgsvc = config_svc self.logger = getLogger('dcamp.service.%s' % self) self.poller = Poller() self.poller_timer = None self.poller.register(self.__control_pipe, POLLIN)
def __init__( self, pipe, ep, uuid, ): self.ctx = Context.instance() self.__control_pipe = pipe assert isinstance(ep, EndpntSpec) self.__endpoint = ep assert isinstance(uuid, UUID) self.__uuid = uuid self.__config_service = None self.logger = getLogger('dcamp.role.%s' % self) # { pipe: service, ...} self.__services = {}
def __init__(self, app, bind_address='127.0.0.1', bind_port=None, context=None, no_encryption=False, *args, **kwargs): """ Constructor. """ super(KoNetThread, self).__init__(*args, **kwargs) # Where we bind to. self.bind_address = str(bind_address) self.bind_port = int(bind_port) if bind_port else None # The local peer where we belong to. self.app = app # The context used to create sockets. self.context = context or Context.instance() # The socket we use to communicate. self.socket = None # Set this to disable encryption. self.no_encryption = no_encryption
class AlertsServer(object): accountProperties = DatabaseConnector(mode="account") registeredAccounts = {} zmqContext = Context.instance() # ------------------------- # Startup # ------------------------- def __init__(self): self.isServiceAvailable = True signal(SIGINT, self.exit_gracefully) signal(SIGTERM, self.exit_gracefully) self.logging = ErrorReportingClient(service="alerts") self.cache = {} def exit_gracefully(self): print("[Startup]: Alerts Server handler is exiting") self.isServiceAvailable = False # ------------------------- # Job queue # ------------------------- def run(self): while self.isServiceAvailable: try: sleep(Utils.seconds_until_cycle()) t = datetime.now().astimezone(utc) timeframes = Utils.get_accepted_timeframes(t) if "1m" in timeframes: self.update_accounts() self.process_price_alerts() except (KeyboardInterrupt, SystemExit): return except Exception: print(format_exc()) if environ["PRODUCTION_MODE"]: self.logging.report_exception() def update_accounts(self): try: self.registeredAccounts = self.accountProperties.keys() except (KeyboardInterrupt, SystemExit): pass except Exception: print(format_exc()) if environ["PRODUCTION_MODE"]: self.logging.report_exception() # ------------------------- # Price Alerts # ------------------------- def process_price_alerts(self): try: self.cache = {} users = database.document("details/marketAlerts").collections() with ThreadPoolExecutor(max_workers=20) as pool: for user in users: accountId = user.id authorId = accountId if accountId.isdigit() else self.registeredAccounts.get(accountId) if authorId is None: continue for alert in user.stream(): pool.submit(self.check_price_alert, authorId, accountId, alert.reference, alert.to_dict()) except (KeyboardInterrupt, SystemExit): pass except Exception: print(format_exc()) if environ["PRODUCTION_MODE"]: self.logging.report_exception() def check_price_alert(self, authorId, accountId, reference, alert): socket = AlertsServer.zmqContext.socket(REQ) socket.connect("tcp://candle-server:6900") socket.setsockopt(LINGER, 3) poller = Poller() poller.register(socket, POLLIN) try: currentPlatform = alert["request"].get("currentPlatform") currentRequest = alert["request"].get(currentPlatform) ticker = currentRequest.get("ticker") hashName = hash(dumps(ticker, option=OPT_SORT_KEYS)) if alert["timestamp"] < time() - 86400 * 30.5 * 3: if environ["PRODUCTION_MODE"]: database.document("discord/properties/messages/{}".format(str(uuid4()))).set({ "title": "Price alert for {} ({}) at {} {} expired.".format(ticker.get("base"), currentPlatform if ticker.get("exchange") is None else ticker.get("exchange").get("name"), alert.get("levelText", alert["level"]), ticker.get("quote")), "subtitle": "Price Alerts", "description": "Price alerts automatically cancel after 3 months. If you'd like to keep your alert, you'll have to schedule it again.", "color": 6765239, "user": authorId, "channel": alert["channel"] }) reference.delete() else: print("{}: price alert for {} ({}) at {} {} expired".format(accountId, ticker.get("base"), currentPlatform if ticker.get("exchange") is None else ticker.get("exchange").get("name"), alert.get("levelText", alert["level"]), ticker.get("quote"))) else: if hashName in self.cache: payload = self.cache.get(hashName) else: alert["request"]["timestamp"] = time() alert["request"]["authorId"] = authorId socket.send_multipart([b"alerts", b"candle", dumps(alert["request"])]) responses = poller.poll(30 * 1000) if len(responses) != 0: [payload, responseText] = socket.recv_multipart() payload = loads(payload) responseText = responseText.decode() if not bool(payload): if responseText != "": print("Alert request error:", responseText) if environ["PRODUCTION_MODE"]: self.logging.report(responseText) return self.cache[hashName] = payload else: raise Exception("time out") for candle in reversed(payload["candles"]): if candle[0] < alert["timestamp"]: break if (alert["placement"] == "below" and candle[3] is not None and candle[3] <= alert["level"]) or (alert["placement"] == "above" and candle[2] is not None and alert["level"] <= candle[2]): if environ["PRODUCTION_MODE"]: database.document("discord/properties/messages/{}".format(str(uuid4()))).set({ "title": "Price of {} ({}) hit {} {}.".format(ticker.get("base"), payload.get("platform") if ticker.get("exchange") is None else ticker.get("exchange").get("name"), alert.get("levelText", alert["level"]), ticker.get("quote")), "description": alert.get("triggerMessage"), "subtitle": "Price Alerts", "color": 6765239, "user": None if {"id": "public", "value": "public"} in currentRequest.get("preferences") else authorId, "channel": alert["channel"] }) reference.delete() else: print("{}: price of {} ({}) hit {} {}".format(accountId, ticker.get("base"), payload.get("platform") if ticker.get("exchange") is None else ticker.get("exchange").get("name"), alert.get("levelText", alert["level"]), ticker.get("quote"))) break except (KeyboardInterrupt, SystemExit): pass except Exception: print(format_exc()) if environ["PRODUCTION_MODE"]: self.logging.report_exception(user=f"{accountId}, {authorId}") socket.close()
def __init__(self, bind_address: str, ctx: Optional[Context] = None): self._ctx = ctx or Context.instance() self._socket = self._ctx.socket(PUB) self._socket.bind('tcp://' + bind_address)
def test_hunter(): with Hunter(Context.instance()) as h: assert isinstance(h, Hunter)
class TickerParser(object): zmqContext = Context.instance() @staticmethod def execute_parser_request(endpoint, parameters, timeout=5): socket = TickerParser.zmqContext.socket(REQ) payload, responseText = None, None socket.connect("tcp://parser:6900") socket.setsockopt(LINGER, 0) poller = Poller() poller.register(socket, POLLIN) socket.send_multipart([endpoint] + parameters) responses = poller.poll(timeout * 1000) if len(responses) != 0: response = socket.recv_multipart() socket.close() return response else: socket.close() raise Exception("time out") return None @staticmethod def find_exchange(raw, platform, bias): [success, exchange] = TickerParser.execute_parser_request( b"find_exchange", [raw.encode(), platform.encode(), bias.encode()]) exchange = None if exchange == b"" else loads(exchange) return bool(int(success)), exchange @staticmethod def match_ticker(tickerId, exchange, platform, bias): exchangeId = exchange.get("id").lower() if bool(exchange) else "" [ticker, error] = TickerParser.execute_parser_request(b"match_ticker", [ tickerId.encode(), exchangeId.encode(), platform.encode(), bias.encode() ]) ticker = None if ticker == b"" else loads(ticker) error = None if error == b"" else error.decode() return ticker, error @staticmethod def check_if_fiat(tickerId): [success, fiat] = TickerParser.execute_parser_request(b"check_if_fiat", [tickerId.encode()]) return bool(int(success)), fiat @staticmethod def get_listings(tickerBase, tickerQuote): [listings, total] = TickerParser.execute_parser_request( b"get_listings", [tickerBase.encode(), tickerQuote.encode()]) return loads(listings), int(total) @staticmethod def get_formatted_price_ccxt(exchangeId, symbol, price): [response] = TickerParser.execute_parser_request( b"get_formatted_price_ccxt", [exchangeId.encode(), symbol.encode(), str(price).encode()]) return response.decode() @staticmethod def get_formatted_amount_ccxt(exchangeId, symbol, amount): [response] = TickerParser.execute_parser_request( b"get_formatted_amount_ccxt", [exchangeId.encode(), symbol.encode(), str(amount).encode()]) return response.decode()
from zmq import Context from protocol.sensor_msgs.msg import CameraInfo from protocol.sensor_msgs.msg import Image from protocol.nav_msgs.msg import Odometry import cv2 from protocol.std_msgs.msg import Header import math import io from thirdparty.cv_bridge import CvBridge cv_bridge = CvBridge() camera_info = Odometry() camera_ = Image() ctx1 = Context.instance() url1 = "ipc:///tmp/buff_carla_ego_vehicle_odometry" sub1 = ctx1.socket(zmq.SUB) try: sub1.connect(url1) except: print("not ok") sub1.setsockopt(zmq.SUBSCRIBE, b'') ctx2 = Context.instance() url2 = "ipc:///tmp/buff_carla_ego_vehicle_camera_rgb_front_image_color" sub2 = ctx2.socket(zmq.SUB) sub2.connect(url2) sub2.setsockopt(zmq.SUBSCRIBE, b'') while True:
def __init__(self): super(ZmqActor, self).__init__() self.ctx = Context.instance()
def create_instance(cls, zmq_io_loop, io_threads=1): instance = cls() instance.zmq_context = ZmqContext.instance(io_threads) instance.zmq_io_loop = zmq_io_loop return instance
usage: python cozmo_server.py ref: https://github.com/anki/cozmo-python-sdk/blob/master/examples/apps/remote_control_cozmo.py#L335 ''' import time # time.sleep(7) # 树莓派开机等待 import zmq from zmq import Context import cozmo from cozmo.util import degrees, distance_mm, speed_mmps port = 38777 context = Context.instance() socket = context.socket(zmq.REP) socket.bind("tcp://*:%s" % port) quit_code = "quit!" def cozmo_program(robot: cozmo.robot.Robot): # import IPython;IPython.embed() while True: python_code = socket.recv_json().get("python_code") print("cozmo server", python_code) if not python_code: continue if python_code == "quit!":
import hashlib import sys import threading from queue import Queue from socketserver import BaseRequestHandler, ThreadingTCPServer import click import zmq from zmq import Context from logbook import Logger, StreamHandler StreamHandler(sys.stdout).push_application() tcp_log = Logger('TCP Server') push_log = Logger('Pusher') ctx = Context.instance() inp_queue = Queue() PUSH_CONNECT = None HASHER = None TCP_HOST = None TCP_PORT = None class TCPInputRequestHandler(BaseRequestHandler): def handle(self): data = self.request.recv(1024).strip() tcp_log.debug("from {} -> {}".format(self.client_address[0], data)) inp_hash = HASHER(data).digest() inp_queue.put(inp_hash) self.request.sendall(inp_hash)
class DatabaseConnector(object): zmqContext = Context.instance() def __init__(self, mode): self.mode = mode @staticmethod def execute_database_request(endpoint, parameters, timeout=1): socket = DatabaseConnector.zmqContext.socket(REQ) payload, responseText = None, None socket.connect("tcp://database:6900") socket.setsockopt(LINGER, 0) poller = Poller() poller.register(socket, POLLIN) socket.send_multipart([ endpoint, bytes(str(int((time() + timeout) * 1000)), encoding='utf8'), parameters ]) responses = poller.poll(timeout * 1000) if len(responses) != 0: [response] = socket.recv_multipart() socket.close() return loads(response) else: socket.close() return None def check_status(self): try: return DatabaseConnector.execute_database_request( bytes(self.mode + "_status", encoding='utf8'), b"") except: return False def keys(self, default={}): try: response = DatabaseConnector.execute_database_request(bytes( self.mode + "_keys", encoding='utf8'), b"", timeout=5.0) except: return default if response is None: return default return response def get(self, value, default=None): try: response = DatabaseConnector.execute_database_request( bytes(self.mode + "_fetch", encoding='utf8'), bytes(str(value), encoding='utf8')) except: return default if response is None: return default return response def match(self, value, default=None): try: response = DatabaseConnector.execute_database_request( bytes(self.mode + "_match", encoding='utf8'), bytes(str(value), encoding='utf8')) except: return default if response is None: return default return response
def __init__(self): self.__logger = logging.getLogger('PushClient') self.__context = Context.instance() self.__socket = self.__context.socket(SUB) self.num_received_messages = 0L