def main(): conf_file = sys.argv[1] if len(sys.argv) > 1 else "config.yml" with open(conf_file) as f: config = yaml.load(f) channel = config["irc"]["channel"] sio = SocketIO(config["state"]["host"], config["state"]["port"]) public_ns = sio.define(PublicNamespace, '/public') private_ns = sio.define(PrivateNamespace, '/private') bot = AvalonBot(private_ns) # TODO: figure out a less hacky solution. public_ns.bot = bot public_ns.channel = channel private_ns.bot = bot sio_t = threading.Thread(target=sio.wait) sio_t.start() bot.connect(config["irc"]["server"], config["irc"]["port"]) bot.register(config["irc"]["nick"]) bot.join(channel) bot.listen()
def changes(self, namespace): if namespace not in self.types: raise ValueError('wrong type of changes requested') socket = SocketIO(self.serverUrl, self.port, resource='socket', params={'token': self.jwt}, verify=False) socket.define(BaseNamespace, '/' + namespace) socket.on('message', self._on_socket_response) socket.wait() # Wait forever.
def audio_connect(device=None, samplerate=16000, block_duration=10, padding_duration=1000, host=None, port=None, channels=1, activate=True): if not activate: return global socket_state if host: socket = SocketIO(host, port) socket_state = socket.define(StateNamespace, '/state') samplerate = samplerate FRAMES_PER_BUFFER = int(samplerate * block_duration / 1000) NUM_PADDING_CHUNKS = int(padding_duration / block_duration) NUM_WINDOW_CHUNKS = int(250 / block_duration) ring_buffer = deque(maxlen=NUM_PADDING_CHUNKS) ring_buffer_flags = [0] * NUM_WINDOW_CHUNKS ring_buffer_index = 0 stream = audio.open(format=pyaudio.paInt16, channels=1, rate=samplerate, frames_per_buffer=FRAMES_PER_BUFFER, input=True, start=False, stream_callback=callback) stream.start_stream() STATE['main'] = "1"
def send(to, value): Peers.init() Mongo.init() used_inputs = [] new_inputs = [] try: transaction = TransactionFactory(fee=0.01, public_key=Config.public_key, private_key=Config.private_key, outputs=[Output(to=to, value=value)]) except NotEnoughMoneyException as e: print "not enough money yet" return except: raise try: transaction.transaction.verify() except: print 'transaction failed' TU.save(transaction.transaction) print 'Transaction generated successfully. Sending:', value, 'To:', to for peer in Peers.peers: try: socketIO = SocketIO(peer.host, peer.port, wait_for_connection=False) chat_namespace = socketIO.define(ChatNamespace, '/chat') chat_namespace.emit('newtransaction', transaction.transaction.to_dict()) socketIO.disconnect() print 'Sent to:', peer.host, peer.port except Exception as e: print e
class DocumentSyncTest(BaseTestCase): def setUp(self): super(DocumentSyncTest, self).setUp() self.client = SocketIO('localhost', config.SERVER_PORT, DocumentNamespace) self.doc = self.client.define(DocumentNamespace, DOCUMENT_NAMESPACE) global RECEIVED RECEIVED = {} def tearDown(self): super(DocumentSyncTest, self).tearDown() self.client.disconnect() def test_echo(self): self.doc.on('echo', on_echo_response) self.doc.emit('echo', 'hello world') self.client.wait(seconds=1) self.assertTrue(RECEIVED.get('on_echo_response', False)) def test_single_client(self): self.doc.on('userlist', on_userlist_response) self.doc.on('document', on_document_response) self.doc.emit('join', {'username': '******', 'document': DOCUMENT_ID}) self.client.wait(seconds=1) self.doc.emit('leave', {'username': '******', 'document': DOCUMENT_ID}) self.assertTrue(RECEIVED.get('on_userlist_response', False)) self.assertTrue(RECEIVED.get('on_document_response', False))
def main(use_gpu=False, console_mode=True, show_progress_bar=False, save_train_progress=False): client = None if bool_convert(console_mode): print('Running in console mode') else: try: socketIO = SocketIO('127.0.0.1', 80, Namespace=BaseNamespace) client = socketIO.define(BaseNamespace, '/train-ws') init_emitter(client) except Exception: print(f'Cannot connect to socket.io server, running in console mode') try: train_model( bool_convert(use_gpu), bool_convert(show_progress_bar), bool_convert(save_train_progress), ) except KeyboardInterrupt: print(f'Stopped by keyboard interrupt') except Exception as e: print(traceback.format_exc()) raise e finally: if client is not None: client.emit('stop')
class WebSocketClientThread(threading.Thread): def __init__(self, duration=''): self.__socketIO = None self.__ws_client = None self.__duration = duration super(WebSocketClientThread, self).__init__() def get_queue(self): return self.__ws_client.get_queue() def start(self): self.__socketIO = SocketIO('websocket.btcc.com', 80) self.__ws_client = self.__socketIO.define(BtccWebsocketClient) self.__ws_client.emit('subscribe', 'marketdata_cnybtc') self.__ws_client.emit('subscribe', 'grouporder_cnybtc') super(WebSocketClientThread, self).start() def run(self): super(WebSocketClientThread, self).run() if self.__duration != '': self.__socketIO.wait(self.__duration) else: self.__socketIO.wait() print '__socketIO.wait(30)' self.__ws_client.off('subscribe') self.__ws_client.disconnect() def stop(self): try: common.logger.info("WebSocketClientThread Stopping websocket client.") except Exception, e: common.logger.error("Error stopping websocket client: %s." % (str(e)))
class YetiSocket(): def __init__(self, host='localhost', port=5001): self.io = SocketIO(host, port) self.cam = self.io.define(CamNamespace, '/cam') self.cam.on('config_update', self.config_update) self.cam.on('manual_capture', self.manual_capture) self._thread = threading.Thread(target=self.io.wait) self._thread.daemon = True self._thread.start() def send(self, event, data): self.cam.emit(event, data) def config_update(self, data): print 'config update: %s' % data def manual_capture(self, data): print 'manual capture: ' + data def connect(self): self.cam.connect() def disconnect(self): self.cam.disconnect() self.io.disconnect() def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): self.disconnect()
def task_stat_updata(taskid, itemid, percent, message): class ProcessNamespace(BaseNamespace): def on_aaa_response(self, *args): print('on_process_response', args) def on_update_process(self, *args): print('on_aaa_response', args) tkid = taskid itid = itemid process = percent message = message socketIO = SocketIO('test.boonray.com', 8080) topic = taskid + '_' + itid process_socket = socketIO.define(ProcessNamespace, '/process') process_data = {'topic': topic, 'percent': process, 'message': message} def on_update_process(*args): messages = list(args) print('on_aaa_response', messages.get) process_socket.emit('update process', process_data) #process_socket.on('process_1288',on_update_process) print('msg send') socketIO.wait(3) time.sleep(1)
class Monitor(Thread): def __init__(self, name, description=None, host='localhost', port='8787', save_on_disk=True): super(Monitor, self).__init__(daemon=True) self._host = host self._port = port self._save_on_disk = save_on_disk self._description = description self._name = name self.start() def run(self): self._client = SocketIO(self._host, self._port, wait_for_connection=False) self._namespace = self._client.define(CogitareNamespace, '/cogitare') self._namespace._monitor = self self._namespace.emit( 'register', { 'name': self._name, 'description': self._description, 'save_on_disk': self._save_on_disk }) self._namespace.emit('machine', machine_status()) self._client.wait()
class Client(Thread): def __init__(self, target_env_class, env_name=''): Thread.__init__(self) self.target_env_class = target_env_class self.env_name = env_name self.socketIO = SocketIO('127.0.0.1', 5000) self.socketIO.on('connect', self.on_connect) self.socketIO.on('disconnect', self.on_disconnect) self.socketIO.on('reconnect', self.on_reconnect) self.socketIO.on('session_response', self.on_session_response) # self.socketIO.emit('session') # self.socketIO.wait() def run(self): self.socketIO.emit('session') self.socketIO.wait() def on_connect(self): print('client say connect') def on_reconnect(self): print('client say connect') def on_disconnect(self): print('disconnect') def on_session_response(self, new_id): print('Get id = {}'.format(new_id)) new_ns = '/' + str(new_id) + '/rl_session' self.connect_with_ns(new_ns) def connect_with_ns(self, ns): print('defins ns ={}'.format(ns)) new_env = self.socketIO.define(self.target_env_class, ns) new_env.set_name(self.env_name)
def start(): os.system('cls') if len(sys.argv) > 1: bot_id = sys.argv[1] else: bot_id = input('Please provide your Automagica Bot ID: \n') if len(sys.argv) > 2: host = sys.argv[2] else: host = 'https://portal.automagica.be' if len(sys.argv) > 3: port = sys.argv[3] else: port = None socketIO = SocketIO(host, port) bot = Bot bot.bot_id = bot_id while True: try: bot_namespace = socketIO.define(bot, '/bot') break except: os.system('cls') print('Connecting...') pass socketIO.wait()
class makeSocket: def __init__(self): self.socket = SocketIO("https://glws.org/f**k") self.fn = self.socket.define(f**k, "/f**k") def emitready(self): try: self.fn.emit("isReady",{"wanna_fuck": "no thanks I\'m under age"}) self.socket.wait(seconds=3) global globalready temp = globalready globalready = None return temp except TypeError: print 'something went wrong doing a ready command please try again' return False def emitgetdata(self, data): try: self.fn.emit("sendData", data) self.socket.wait(seconds=0.8) global globalgetData temp = globalgetData globalgetData = None return temp except TypeError: print 'something went wrong doing a sendData command please try again' return False
class CommandParser: __callbacks = {} def __init__(self): self.__path = command_namespace_path self.__port = port self.__room = room_name self.__hostname = hostname self.__socket = SocketIO(self.__hostname, self.__port, CommandNamespace) self.__namespace = self.__socket.define(CommandNamespace, self.__path) self.__namespace.set_listener(self.listener) self.__namespace.emit('join', {'room': room_name}) t = Thread(target=self.__socket.wait) t.start() def set_command_callback(self, command, command_callback): self.__callbacks[command] = command_callback def delete_command_callback(self, command): del self.__callbacks[command] def listener(self, command, data): try: self.__callbacks[command](data) except KeyError as e: print(e)
class Main(): def __init__(self, parent=None): self.clientId = sys.argv[1] self.param = int(sys.argv[2]) self.socketIO = SocketIO('localhost', 8080, BaseNamespace, params={"clientId": self.clientId}) self.namespace = self.socketIO.define(BaseNamespace, '/calc') self.namespace.on('change_param', self.change_param) def change_param(self, *args): self.param = int(args[0]) def run(self): while 1: x = npr.uniform(low=-200.0, high=200.0, size=self.param) y = npr.uniform(low=-200.0, high=200.0, size=self.param) x_buff = bytearray(x.tobytes()) y_buff = bytearray(y.tobytes()) self.namespace.emit('data', { "clientId": self.clientId, "x": x_buff, "y": y_buff }) self.socketIO.wait(seconds=1)
class KHUBConnection(object): """ Class to connect to the Kyanite backend server to send/receive data. Attributes: name: Name of the sensor/client server:Name or IP address of server . port:Port address of server . namespace: namespace at server . """ def __init__(self, name, server, port, namespace): self.socketIO = SocketIO(server, port) self.msg_namespace = self.socketIO.define(BaseNamespace, namespace) # self.msg_namespace.emit('sname', name) def send(self, eventType, data): """ Send the data as JSON data to the server. Attributes: eventType: Data event to be triggered at the server (String) data: Data to be sent (JSON) . """ self.msg_namespace.emit(eventType, data) def onEvent(self, eventName, callBack): """ Trigger callback for a given event. Attributes: eventName: Event name triggered by the server (String) callBack: Call back function name . """ self.msg_namespace.on('ops', callBack) def wait(self, options): """Wait the thread before exiting.""" self.socketIO.wait(seconds=options)
def _serverThead(): def _onstart(*args): print("server 连接成功") #self.chat.emit('message',"ok") _onupdate() def _onupdate(*args): print(args) if len(args)>0 and args[0].get('code')==3: _task = args[0]['data'] _task["filename"] = _task["name"] _task["per"] = random.randint(0,100) self.tasks.append(_task) self.addMission(_task["url"],os.path.join('test_file',_task["path"])) self.start() else: pass data = { "code":1, "tasks" :json.dumps(self.tasks) } self.chat.emit('onupdate',data) socket = SocketIO('127.0.0.1',8900) self.chat = socket.define(BaseNamespace, '/client') self.chat.on('onstart', _onstart) self.chat.on('onupdate', _onupdate) self.chat.emit('checkStatus',"ok") while True: socket.wait(seconds=1)
def run_sio_g(): socketIO = SocketIO('localhost', 5000, CamNamespace) cam_namespace = socketIO.define(CamNamespace, '/h264') cam_namespace.emit('start', {'cam': 'cam0_0'}) socketIO.wait(seconds=30) print("Out")
class socketIOClient(object): def __init__(self): self._server_ip = 'localhost' self._server_port = 5000 self.socketio = None def onConnect(self): logger.info("From Server: onConnect") def onDisconnect(self): logger.info("From Server: onDisconnect") def onReconnect(self): logger.info("From Server: onReconnect") def connect(self): logger.info("Connecting ...") try: self.socketio = SocketIO(self._server_ip, self._server_port, Main) self.socketio_namespace = self.socketio.define(TestClient, Namespace) except Exception, e: logger.error("connect() except {0}".format(e)) return try: self.socketio_namespace.on('connect', self.onConnect) self.socketio_namespace.on('disconnect', self.onDisconnect) self.socketio_namespace.on('reconnect', self.onReconnect) logger.info("socketio.on() success") except Exception, e: logger.error("socketio.on() except {0}".format(e))
class Transaction(object): def __init__(self): self.custom_timers = {} self.word_list = buildArray( ) self.word_list_length = len(self.word_list) self.socketIO = SocketIO(HOST, PORT) self.socketIO.define(Namespace) def makeCall( self, jsonObject ): start_timer = time.time() self.socketIO.message(jsonObject) self.socketIO.wait(0.01) namespace = self.socketIO.get_namespace() #print namespace.response latency = time.time() - start_timer self.custom_timers['trie_service_sockets'] = latency #if latency > 5: #writeErrorInfo('latency value of %f with %s' %(latency, url) ) #if r.status_code != 200: #writeErrorInfo('status code with %s is %s' %(r.status_code, url) ) #assert (r.status_code == 200), 'Bad HTTP Response' #assert ('suggestions' in namespace.response), 'No suggestions' def run(self): #get a random word from the word_list and call to typeahead whichPhrase = random.randrange(0,self.word_list_length) phrase = self.word_list[whichPhrase] word = phrase.split(" ")[0] #print 'word is %s' % word message = "" jsonObject = "" #loop through the chars in the word skipping the first #for char in word: # message = message + char # jsonObject = {'@class': 'com.glg.service.TrieObject', 'entity':'cm', 'prefix':message} # self.makeCall( jsonObject ) jsonObject = {'@class': 'com.glg.service.TrieObject', 'entity':'cm', 'prefix':word} self.makeCall( jsonObject )
def initialize(self, event, host, port, namespace): sio_base = SocketIO(host, port) sio = sio_base.define(BaseNamespace, '/' + namespace) self.handler.sio = sio self.handler.tgt_event = event socketserver.ThreadingTCPServer.__init__( self, (self.listen_host, self.listen_port), self.handler)
def listen_data(): socketio_cli = SocketIO(host=HOST, port=PORT, params={ 'app_eui': APP_EUI, 'token': TOKEN }) test_namespace = socketio_cli.define(TestNamespace, '/test') socketio_cli.wait()
def userver_listening(): try: socketio_cli = SocketIO(host=HOST, port=PORT, params={'app_eui': APP_EUI, 'token': TOKEN}) # global socketio_cli test_namespace = socketio_cli.define(TestNamespace, '/test') socketio_cli.wait() except Exception as e: ws_listening()
def run(ip, port, mocker): try: socketIO = SocketIO(ip, port, wait_for_connection=False) mocknamespace = socketIO.define(Namespace, '/mock') mocknamespace.callback(mocker.mockresponse.callback) mocknamespace.emit('join', jsonpickle.encode(mocker)) socketIO.wait() except ConnectionError: print('The server is down. Try again later.')
def play(handler): token = raw_input('Enter your token: ') global play_reversi play_reversi = handler # Use socketio with defined Namespace socketIO = SocketIO('localhost', 8100, params={'token': token}) gameplay = socketIO.define(ReversiNamespace, '/play') socketIO.wait()
def main(): init_publisher() socketIO = SocketIO(INPUT_URI, INPUT_PORT) socket_namespace = socketIO.define(Namespace, '/socket.io') rospy.loginfo( 'Started toggle_checker listening on uri: {}'.format(INPUT_URI)) while True: socketIO.wait(seconds=1)
def run(self): socketIO = SocketIO(BasesConfig.REMOTE_IP, BasesConfig.REMOTE_PORT) chat_namespace = socketIO.define(ChatNamespace, "/websocket/user_refresh") ChatNamespace.WORKER_ID = self.workerid ChatNamespace.RENDER_THREAD = self chat_namespace.emit( 'connect_event', {"workerid": self.workerid}) # 告知服务器的sid->workerid的映射 socketIO.wait()
def broadcast_transaction(self, transaction): for peer in Peers.peers: try: print peer.to_string() socketIO = SocketIO(peer.host, peer.port, wait_for_connection=False) chat_namespace = socketIO.define(ChatNamespace, '/chat') chat_namespace.emit('newtransaction', transaction.to_dict()) socketIO.disconnect() except Exception as e: print e
def openStream(self, id, options, callback): try: if options['query']: d = options except: ##options is an string d = {'query': options} if (self.accessToken): url = self.base + ':' + str( self.port) + '/api/wo/' + id + '/endpoint' headers = {'Authorization': 'Bearer ' + self.accessToken} r = requests.get(url, params=d, headers=headers, verify=False) if ('r' in locals() and r.status_code == 200): sid = r.content # print "sid:---"+sid # sio = 'http://webobservatory.soton.ac.uk'#+sid #sio = 'dev-001.ecs.soton.ac.uk' #print sio # class Namespace(BaseNamespace): # def on_connect(self): # print '[Connected]' class dataNamespace(BaseNamespace): #def on_aaa_response(self, *args): # print('on_aaa_response', args) def on_connect(self): print '[Connected]' pass def process(data): # print "process data" # print data callback(False, data, socketIO) # socketIO = SocketIO(sio,443,LoggingNamespace,verify=False) socketIO = SocketIO(self.base, self.port, verify=False) # socketIO = SocketIO(self.base, 9090) data_namespace = socketIO.define(dataNamespace, '/' + sid) #data_namespace.emit('stop') data_namespace.on('chunk', process) # data_namespace.emit('stop') # socketIO.emit("stop") # socketIO.wait(seconds=1) # data_namespace.wait() socketIO.wait() else: callback( "[ERROR] Open Stream Failed: Stream opening failed for:" + id, None, None)
def run(cls, config, mongo): used_inputs = [] new_inputs = [] for x in mongo.site_db.faucet.find({'active': True}): balance = BU.get_wallet_balance(config, mongo, x['address']) if balance >= 25: mongo.site_db.faucet.update({'_id': x['_id']}, { 'active': False, 'address': x['address'] }) continue last_id_in_blockchain = x.get('last_id') if last_id_in_blockchain and not mongo.db.blocks.find({ 'transactions.id': last_id_in_blockchain }).count(): continue try: transaction = TransactionFactory( config, mongo, block_height=BU.get_latest_block(config, mongo)['index'], fee=0.01, public_key=config.public_key, private_key=config.private_key, outputs=[Output(to=x['address'], value=5)]) except NotEnoughMoneyException as e: print "not enough money yet" return except Exception as e: print x try: transaction.transaction.verify() except: mongo.site_db.failed_faucet_transactions.insert( transaction.transaction.to_dict()) print 'faucet transaction failed' TU.save(config, mongo, transaction.transaction) x['last_id'] = transaction.transaction.transaction_signature mongo.site_db.faucet.update({'_id': x['_id']}, x) print 'saved. sending...', x['address'] for peer in Peers.peers: try: socketIO = SocketIO(peer.host, peer.port, wait_for_connection=False) chat_namespace = socketIO.define(ChatNamespace, '/chat') chat_namespace.emit('newtransaction', transaction.transaction.to_dict()) socketIO.disconnect() except Exception as e: print e
class Client: def __init__(self, target_env_class, i_cfg, project_name=None, retrain_model=False): # Thread.__init__(self) self.env_name = project_name self.socketIO = SocketIO('127.0.0.1', 5000) self.socketIO.on('connect', self.on_connect) self.socketIO.on('disconnect', self.on_disconnect) self.socketIO.on('reconnect', self.on_reconnect) self.socketIO.on('session_response', self.on_session_response) # for ctrl+C signal.signal(signal.SIGINT, self.signal_handler) # send_cfg = cfg if i_cfg == None else cfg self.send_cfg = i_cfg self.target_env_class = target_env_class #self.socketIO.emit('session', project_name, cfg) self.socketIO.emit('session', project_name, self.send_cfg, retrain_model) self.socketIO.wait() def signal_handler(self, signal, frame): #print(signal) print('You pressed Ctrl+C!') self.target_env_class.close() self.socketIO.disconnect() sys.exit(0) def on_connect(self): print('[I] Client connect') def on_reconnect(self): print('[I] Client reconnect') def on_disconnect(self): print('[I] Client disconnect') def on_session_response(self, new_id): print('[I] Get id = {}'.format(new_id)) new_ns = '/' + str(new_id) + '/rl_session' self.connect_with_ns(new_ns) def connect_with_ns(self, ns): # print('get ns ={}'.format(ns)) new_env = self.socketIO.define(self.target_env_class, ns) new_env.set_cfg(self.send_cfg) new_env.set_name(self.env_name)
def txn_broadcast_job(cls, transaction): Peers.init() for peer in Peers.peers: try: socketIO = SocketIO(peer.host, peer.port, wait_for_connection=False) chat_namespace = socketIO.define(ChatNamespace, '/chat') chat_namespace.emit('newtransaction', transaction.to_dict()) socketIO.wait(seconds=1) chat_namespace.disconnect() except Exception as e: pass
class WsThread(threading.Thread): def __init__(self, did): super(WsThread, self).__init__() self.ready = False self.did = did self.condition = threading.Condition() def _set_ready(self): self.condition.acquire() self.ready = True self.condition.notify_all() self.condition.release() def run(self): self.socketIO = SocketIO(IP, 3000, params={'did': self.did}) self.device_namespace = self.socketIO.define(Namespace, '/device') self._set_ready() self.socketIO.wait() def register_cmd_callbacks(self, handle, app): self.condition.acquire() while not self.ready: self.condition.wait() self.device_namespace.register_cmd_callbacks(handle, app) self.condition.release() def stop(self): self.condition.acquire() self.socketIO.disconnect() self.condition.release() def sendLog(self, critical, log): self.condition.acquire() while not self.ready: self.condition.wait() self.device_namespace.emit('device-log', { 'critical': critical, 'log': log }) self.condition.release() def sendVar(self, handle, value): self.condition.acquire() while not self.ready: self.condition.wait() self.device_namespace.emit('device-updateVariable', { 'handle': handle, 'value': value }) self.condition.release() def __del__(self): self.stop()
def punisher(configs): socket = SocketIO(configs['server_addr'], configs['server_port']) punisher_ns = socket.define(PunisherNamespace, '/punisher') try: socket.wait() except KeyboardInterrupt: pass
def once(self, emitEventname, data, respEventname=None, fun=None): try: io = SocketIO_Client(self.host, self.port, wait_for_connection=False, params=self.params) self.client = io.define(self.tNamespace, self.path) self.client.once(respEventname, fun) self.emit(emitEventname, data) except: print('The server is down. Try again later.')
def startcsdfeed(bot, trigger): """CSD feed""" class MainNamespace(BaseNamespace): def on_change(self, change): if change['type'] == 'categorize': if change['title'] == 'Category:Candidates for speedy deletion': if re.search('.\]\] added to category$', change['comment']): strippedtitle = change['comment'].lstrip('[[').rstrip(']] added to category') unspacedstrippedtitle = strippedtitle.replace(' ','_') bot.say('[Page CSD] ' + 'Wiki: ' + change['wiki'] + ' | Page: http://enwp.org/' + unspacedstrippedtitle + ' | User: '******'user']) def on_connect(self): bot.say('Connected.') self.emit('subscribe', 'en.wikipedia.org') bot.say('Subscribed to en.wikipedia.org feed.') bot.say('Connecting...') socketIO = SocketIO('https://stream.wikimedia.org') socketIO.define(MainNamespace, '/rc') socketIO.wait()
def broadcast(self): Peers.init(self.config, self.mongo, self.config.network) for peer in Peers.peers: try: socketIO = SocketIO(peer.host, peer.port, wait_for_connection=False) chat_namespace = socketIO.define(ChatNamespace, '/chat') chat_namespace.emit('new-fastgraph-transaction', self.to_dict()) socketIO.wait(seconds=1) chat_namespace.disconnect() except Exception as e: print e pass
def createSocketClient(self): socketIO = SocketIO(self.serverConfig["Host"], self.serverConfig["Port"]) resultsNamespace = socketIO.define(ResultsPublisherV1Namespace, '/result') print('Host', self.serverConfig["Host"]) print('Port', self.serverConfig["Port"]) print("Socket created", socketIO, "for pid", multiprocessing.current_process().pid) return resultsNamespace
def openStream(self, id, options, callback): try: if options['query']: d = options except: ##options is an string d = {'query':options} if (self.accessToken): url= self.base+':'+str(self.port)+'/api/wo/'+ id + '/endpoint' headers={ 'Authorization': 'Bearer ' + self.accessToken} r= requests.get(url,params=d, headers=headers, verify=False) if ('r' in locals() and r.status_code == 200): sid = r.content # print "sid:---"+sid # sio = 'http://webobservatory.soton.ac.uk'#+sid #sio = 'dev-001.ecs.soton.ac.uk' #print sio # class Namespace(BaseNamespace): # def on_connect(self): # print '[Connected]' class dataNamespace(BaseNamespace): #def on_aaa_response(self, *args): # print('on_aaa_response', args) def on_connect(self): print '[Connected]' pass def process(data): # print "process data" # print data callback(False, data,socketIO) # socketIO = SocketIO(sio,443,LoggingNamespace,verify=False) socketIO = SocketIO(self.base,self.port, verify=False) # socketIO = SocketIO(self.base, 9090) data_namespace = socketIO.define(dataNamespace,'/'+sid) #data_namespace.emit('stop') data_namespace.on('chunk',process) # data_namespace.emit('stop') # socketIO.emit("stop") # socketIO.wait(seconds=1) # data_namespace.wait() socketIO.wait() else: callback("[ERROR] Open Stream Failed: Stream opening failed for:"+id,None,None)
class Client(BaseApp): def __init__(self, settings=''): super(Client, self).__init__(settings) self.headers = {} self.cookies = {} self.params = {} self.ipproxy = {} self.socketIO = None self.namespace_dict = {} self.extend_context = {} self._init_param() def _init_param(self): self.headers = self.settings.get("headers", {}) self.cookies = self.settings.get("cookies", {}) self.params = self.settings.get("cookies", {}) self.ipproxy = self.settings.get("params", {}) self.ip = self.settings.get("ip", None) or 'localhost' self.port = self.settings.get("port", None) or self.DEFAULT_PORT def set_namespace(self, path, namespace): if not path or not namespace: return self.namespace_dict.update({path: namespace}) return self def set_context(self, key, obj): if not key or not obj: return self.extend_context.update({key: obj}) def run(self): print('开始客户端app') self.socketIO = SocketIO(self.ip, self.port) # 将环境设置到io对象中 setattr(self.socketIO, 'extend_context', self.extend_context) for path, namespace in self.namespace_dict.items(): self.socketIO.define(namespace, path) self.socketIO.wait()
def connect(self, cb): appId = self._xpush.appId userId = self._xpush.userId deviceId = self._xpush.deviceId token = self._xpush.token serverName = self._server.get( "name" ) q = { "A" : appId, "U" : userId, "D" : deviceId, "C" : self.chNm, "S" : serverName } if self._type == TYPE_SESSION : q["TK"] = token if self._channelOnly == True : q["MD"] = "CHANNEL_ONLY"; strArr = self._server.get( "url" ).split(":") protocol = strArr[0] host = strArr[1].replace( "//", "" ) port = int( strArr[2] ) socketIO = SocketIO( host, port, params= q ) if self._type == TYPE_SESSION : self.sessionNamespace = socketIO.define(SessionNamespace, "/"+self._type) else : self.channelNamespace = socketIO.define(ChannelNamespace, "/"+self._type) #socketIO.emit("aaa", {"xxx": "yyy"}) self._connected = True self._socket = socketIO #self._socket.wait() cb()
class Socket(object): def __init__(self, url, port, headers): self.socketIO = SocketIO(url, port, headers=headers) self.reader_namespace = self.socketIO.define(ReaderNamespace, '/readers') def statusUpdate(self, message): print message self.socketIO.wait(seconds=0.1) self.reader_namespace.emit('status update', message) def tagReading(self, package): self.reader_namespace.emit('tag reading', json.dumps(package)) self.socketIO.wait(seconds=0.1)
def init(): """ Init configuration for SocketIO client. Returns: Event client that will be able to set listeners. """ from socketIO_client import SocketIO, BaseNamespace from . import get_event_host path = get_event_host() socketIO = SocketIO(path, None) main_namespace = socketIO.define(BaseNamespace, "/events") socketIO.main_namespace = main_namespace return socketIO
class Server(object): def __init__(self, host, port): self.host = host self.port = port self.proxies = {} def set_proxy(self, protocol, url): self.proxies[protocol] = url logger.info('set proxy %s=%s' % (protocol, url)) def start(self): logger.info('Server started [%s:%d]...' % (self.host, self.port)) self.socket = SocketIO(self.host, self.port, proxies=self.proxies) self.namespace = self.socket.define(HubNamespace) self.namespace.set_home('sungtaek') self.namespace.add_agent(Led('led')) self.socket.wait()
class YetiSocket: def __init__(self, host='localhost', port=5001, config_update_callback=None, manual_capture_callback=None): self._thread = threading.Thread(target=self._worker, args=(host, port, config_update_callback, manual_capture_callback)) self._thread.daemon = True self._thread.start() def _worker(self, host, port, config_update_callback, manual_capture_callback): self.io = SocketIO(host, port) self.cam = self.io.define(LoggingNamespace, '/cam') if config_update_callback: self.cam.on('config_update', config_update_callback) if manual_capture_callback: self.cam.on('manual_capture', manual_capture_callback) self.io.wait() def alert(self, data): logger.info("Sending alert to server: %s" % data) self.cam.emit("alert", data) def config_updated(self, status): logger.info("Sending config updated result: %s" % status) self.cam.emit("config_updated", {"status":status}) def manual_capture_result(self, result): logger.info("Sending manual capture result: %s" % result) self.cam.emit("manual_capture_result", {"result":result}) def connect(self): self.cam.connect() def disconnect(self): self.cam.disconnect() self.io.disconnect() def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): self.disconnect()
class RBConnection(object): """ Class to connect to the ReadBridg animation server to send data. Attributes: name: Name of the sensor server:Name or IP address of server . port:Port address of server . """ def __init__(self, name, server, port): self.socketIO = SocketIO(server, port) self.msg_namespace = self.socketIO.define(BaseNamespace, '/fromremote') self.msg_namespace.emit('sname', name) def send(self, data): """Send the data as JSON data to the server.""" self.msg_namespace.emit('sensor_msg', data) def wait(self, options): """Wait the thread before exiting.""" self.socketIO.wait(seconds=options)
def run(bind_address, _worker_idx): worker_name = '(bind = {}, w = {})'.format(bind_address, _worker_idx) _socket_connect = Socket.connect def my_socket_connect(self: Socket, address): # logger.warning('socket {} bind to {}'.format(self, args.bind)) self.bind((bind_address, 0)) return _socket_connect(self, address) Socket.connect = my_socket_connect pool = ThreadPool() socks = [] state = GlobalState() class BindFanoutNamespace(FanoutNamespace): def __init__(self, io, path): super(BindFanoutNamespace, self).__init__(state, io, path) for rnd in range(batch_round): logger.warning('{}: round #{} start'.format(worker_name, rnd)) exp_conn_number = (rnd + 1) * batch_size for i in range(batch_size): # NOTE: 使用这种方式可能可以减少链接数量,因为默认是链接 '/'. But not working.!!! # sock = SocketIO(host=host, port=port, Namespace=FanoutNamespace) # NOTE: 后来我发现这个是可以work的,不过需要主动调用 connect(path = '/') sock = SocketIO(host=host, port=port) sock.define(BindFanoutNamespace, args.namespace) socks.append(sock) pool.spawn(sock.wait) while state.current_conn_number != exp_conn_number: logger.warning( '{}: current_conn = {}, exp_conn = {}'.format(worker_name, state.current_conn_number, exp_conn_number)) time.sleep(5) logger.warning('{}: round #{} ok. current_conn = {}'.format(worker_name, rnd, state.current_conn_number)) while state.rcv_msg_number != total_conn_number: logger.warning('{}: rcv_msg = {}, total_conn = {}'.format( worker_name, state.rcv_msg_number, total_conn_number)) time.sleep(2) for rnd in range(batch_round): logger.warning('{}: round #{} quit'.format(worker_name, rnd)) exp_conn_number = (batch_round - rnd - 1) * batch_size for s in socks[rnd * batch_size: (rnd + 1) * batch_size]: s.disconnect(path=args.namespace) s.disconnect() while state.current_conn_number != exp_conn_number: logger.warning( '{}: current_conn = {}, exp_conn = {}'.format(worker_name, state.current_conn_number, exp_conn_number)) time.sleep(5) # for s in socks: # s._close() empty = pool.join(timeout=10, raise_error=False) if not empty: logger.warning('{} join timeout. kill it'.format(worker_name)) pool.kill() logger.warning('{} QUIT !!!'.format(worker_name)) # return state return '{}: {}'.format(worker_name, str(state))
def on_change(self, change): print('(GY) on change') def on_connect(self): self.emit('my broadcast event', {'data': 'Hi, I am python client emit(on_connect even), Can you here me ?'} ) def on_playlist_change(self, *args): print('(GY) on_my_response', args) def on_my_response(self, *args): print('(GY) on_my_response', args) def on_test(self, *args): print('@@(GY) on_test', args) self.emit('my broadcast event', {'data': '@Hi, I am python client emit(on_test even), Can you here me ?'} ) if __name__ == '__main__': print '(GY) connect ....%s %s' % (host, port) socketIO = SocketIO(host, int(port), Main) print '(GY) socketIO define Namespace in ktv' oceanktv_namespace = socketIO.define(ktv,Namespace) while (1): oceanktv_namespace.emit('generic.broadcast', {'data': 'I am python client...broadcast emit '} ) socketIO.wait(seconds=1) # oceanktv_namespace.emit('playlist.change', {'data': {'count': 1, 'data': {'action': 'add', 'display_message': u'\u6d6a\u4eba\u60c5\u6b4c(MPEG2)', 'total_current': 2, 'total_finished': 0}}} ) socketIO.wait(seconds=1) pass print 'exit'
def stream(): #Initialize libmyo.init() feed = libmyo.device_listener.Feed() hub = libmyo.Hub() hub.run(1000, feed) myo = feed.wait_for_single_device() #Continuously collect and emit data while 1: try: gyro = myo.gyroscope accel = myo.acceleration myo_sock.emit('data', [time.clock(), gyro.x, gyro.y, gyro.z, accel.x, accel.y, accel.z]) time.sleep(0.02) except KeyboardInterrupt: break except: print 'Unexpected error' hub.shutdown() #Start data collection as separate thread socketIO = SocketIO('localhost', 3000) myo_sock = socketIO.define(MyoNamespace, '/myo_namespace') socketIO.wait(seconds=1) thread = threading.Thread(target=stream) thread.daemon=True thread.start() socketIO.wait();
print(script) subprocess.call(script, shell=True) deviceId = None try: print('Reading ID from disk') deviceId = open('/cdrom/.uid', 'r').read() if not deviceId: deviceId = 'generic' print('Read device ID: ' + str(deviceId)) except Exception as e: print(e) while True: try: print('Connecting to server via WebSocket') socketIO = SocketIO(REMOTE_SERVER, REMOTE_PORT, params={'device_id': 3}) deviceNamespace = socketIO.define(Namespace, '/device') deviceNamespace.emit('initial-config') socketIO.wait() except Exception as e: print(e) time.sleep(RETRY_INTERVAL)
#dev import pdb import logging class TestNamespace(BaseNamespace): def on_register(self, *args): print('on_register_response', args) def on_connect(self): print "connected" logging.basicConfig(level=logging.DEBUG) Pyro4.config.SERIALIZERS_ACCEPTED.add('pickle') daemon = Pyro4.Daemon() #ns = Pyro4.locateNS() uri = str(daemon.register(Remote)) ssid = Utils.getSSID() print ssid print uri #starting daemon for receiving mobile offloading requests socketIO = SocketIO('http://pytosboost.in', 5000) secretCode = "80e57849-8aba-4c23-ab42-2913a7454b08" test_namespace = socketIO.define(TestNamespace) package = {'ssid':ssid,'uri':uri,"ticket":secretCode} test_namespace.emit('register',package) socketIO.wait(seconds=1) daemon.requestLoop()
running = False signal.signal(signal.SIGINT, signal_handler) parser = argparse.ArgumentParser(description='Do fancy OpenCV stuff') parser.add_argument('--preview', action='store_true') args = parser.parse_args() logging.basicConfig(format='[%(levelname)s|%(asctime)s] %(message)s', level=logging.WARNING, datefmt="%Y-%m-%d %H:%M:%S") logger = logging.getLogger('magicmirror') logger.setLevel(logging.INFO) logger.info('starting socketio...') io = SocketIO('localhost', 8101) io2 = SocketIO('localhost', 8104) io_namespace = io.define(BaseNamespace, '/vision') io_namespace2 = io2.define(BaseNamespace, '/vision') resolution = (320, 240) box_size = (.3, .5) box_w = int(box_size[0] * resolution[0]) box_h = int(box_size[1] * resolution[1]) box_x = int((resolution[0] - box_w) / 2) box_y = int((resolution[1] - box_h) / 2) box_top_left = (box_x, box_y) box_bot_right = (box_w + box_x, box_h + box_y) current_dir = path.dirname(__file__) face_cascade = cv2.CascadeClassifier(path.join(current_dir, 'haarcascade_frontalface_default.xml'))
from socketIO_client import BaseNamespace, SocketIO logger = logging.getLogger('client') DEFAULT_LOGGING_FORMAT = '[%(asctime)s][%(levelname)s]%(filename)s@%(lineno)d: %(msg)s' logging.basicConfig(level=logging.INFO, format=DEFAULT_LOGGING_FORMAT) class FanoutNamespace(BaseNamespace): def on_connect(self): logger.info('on connect') # NOTE: 这个客户端的问题似乎比较多,我使用 `send` 是没有办法发送的 self.emit('message', 'message from client') self.emit('my_event', 'my event from client') def on_disconnect(self): logger.info('on disconnect') def on_message(self, data): logger.info('on message. msg = {}'.format(data)) def on_my_event(self, data): logger.info('on my event. msg = {}'.format(data)) socketIO = SocketIO('127.0.0.1', port=8080) notificiation_namespace: BaseNamespace = socketIO.define(FanoutNamespace, '/fanout') notificiation_namespace.emit('my_event', '!!! my event from client') notificiation_namespace.send('!!! message from client') notificiation_namespace.emit('message', '!!! message from client') socketIO.wait()
print('trade', args) def on_grouporder(self, *args): print('grouporder', args) def on_order(self, *args): print('order', args) def on_account_info(self, *args): print('account_info', args) def on_message(self, *args): print('message', args) def on_error(self, data): print(data) socketIO = SocketIO('websocket.btcc.com', 80) namespace = socketIO.define(Namespace) namespace.emit('subscribe', 'marketdata_cnybtc') namespace.emit('subscribe', 'marketdata_cnyltc') namespace.emit('subscribe', 'grouporder_cnybtc') namespace.emit('subscribe', 'grouporder_cnyltc') payload = get_postdata() arg = [json.dumps(payload), get_sign(payload)] namespace.emit('private', arg) socketIO.wait(seconds=2000000) namespace.disconnect()
except Queue.Full: with mood_queue.mutex: mood_queue.queue.clear() mood_queue.put_nowait(pad) def on_ocean_updated(self, *args): personality.openness = args[0].get('openness') personality.conscientiousness = args[0].get('conscientiousness') personality.extraversion = args[0].get('extraversion') personality.agreeableness = args[0].get('agreeableness') personality.neuroticism = args[0].get('neuroticism') print 'Personality updated' # connect to websocket server socket = SocketIO('127.0.0.1', 5000) socket_namespace = socket.define(SocketNamespace, '/socket') # define event callbacks socket_namespace.on('connected', socket_namespace.on_connected_response) socket_namespace.on('mood_updated', socket_namespace.on_mood_updated_response) socket_namespace.on('ocean_updated', socket_namespace.on_ocean_updated) # ***** # run loop # ***** while True: try: socket.wait(seconds=0.1) data = server.read(BYTES_TO_READ) if data: # put data into sensor class to calculate its occ value
class SocketIoJsonInterface(object): def __init__(self, url, socketIONamespace, events=None, version=None): if url.endswith('/'): # remove trailing slash url = url[:-1] self.url = url self.path = socketIONamespace self.events = events or {} self.version = version or pyfora.__version__ self.socketIO = None self.reactorThread = None self.namespace = None self.nextMessageId = 0 self.messageHandlers = {} self.lock = threading.Lock() self.connection_cv = threading.Condition(self.lock) self.connection_status = ConnectionStatus() def connect(self, timeout=None): timeout = timeout or 30.0 with self.lock: if self._isConnected(): raise ValueError("'connect' called when already connected") with self.lock: t0 = time.time() self.connection_status.status = ConnectionStatus.connecting while True: try: self.socketIO = SocketIO(self.url, wait_for_connection=False) break except (TimeoutError, ConnectionError): if time.time() - t0 > timeout: raise time.sleep(0.5) self.reactorThread = threading.Thread(target=self.socketIO.wait) if isinstance(self.socketIO._transport_instance, WebsocketTransport): self.socketIO._transport_instance._connection.lock = threading.Lock() self.reactorThread.daemon = True self.namespace = self.socketIO.define(self._namespaceFactory, self.path) self.reactorThread.start() while self.connection_status.status == ConnectionStatus.connecting and \ (time.time() - t0 < timeout): self.connection_cv.wait(timeout) if self.connection_status.status == ConnectionStatus.connected: return self if self.connection_status.status == ConnectionStatus.connecting: message = "Connection timed out" else: message = self.connection_status.message raise pyfora.ConnectionError(message) def close(self): with self.lock: if not self._isConnected(): return reactorThread = self.reactorThread self.reactorThread = None self.socketIO.disconnect() reactorThread.join() def isConnected(self): with self.lock: return self._isConnected() def send(self, message, callback): with self.lock: self._raiseIfNotConnected() messageId = self.nextMessageId self.nextMessageId += 1 self.messageHandlers[messageId] = callback def encoder(obj): if not isinstance(obj, dict) and hasattr(obj, 'toMemoizedJSON'): return obj.toMemoizedJSON() return obj message['messageId'] = messageId self.namespace.emit('message', {'body': json.dumps(message, default=encoder)}) def on(self, event, callback): if event in self.events: raise ValueError("Event handler for '%s' already exists" % event) self.events[event] = callback def _isConnected(self): return self.connection_status.status in [ConnectionStatus.connecting, ConnectionStatus.connected] def _raiseIfNotConnected(self): if not self._isConnected(): raise ValueError('Performing I/O on disconnected socket') def _namespaceFactory(self, *args, **kwargs): return Namespace(self._onConnected, *args, **kwargs) def _triggerEvent(self, event, *args, **kwargs): if event in self.events: self.events[event](*args, **kwargs) def _onConnected(self, namespace): namespace.on('disconnect', self._on_disconnect) namespace.on('handshake', self._on_handshake) namespace.emit('handshake', {'version': self.version}) def _on_handshake(self, handshake_response): with self.lock: if handshake_response == 'ok': self.connection_status.status = ConnectionStatus.connected else: self.connection_status.status = ConnectionStatus.disconnected self.connection_status.message = handshake_response self.connection_cv.notify() self.namespace.on('response', self._on_message) def _on_message(self, payload): def object_hook(obj): for k in obj: if isinstance(obj[k], unicode): obj[k] = obj[k].encode("utf8") return obj try: message = json.loads(payload, object_hook=object_hook) except: self._triggerEvent('invalid_message', payload) return messageId = message.get('messageId') if messageId is None: self._triggerEvent('special_message', message) return callback = self.messageHandlers.get(messageId) if callback is None: self._triggerEvent('unexpected_message', message) return if message.get('responseType') != 'SubscribeResponse': del self.messageHandlers[messageId] callback(message) def _on_disconnect(self): callbacks = [] with self.lock: self.connection_status.status = ConnectionStatus.disconnected self.connection_cv.notify() # respond to all pending messages with a failure callbacks = [ (cb, self._disconnect_failure_message(messageId)) for messageId, cb in self.messageHandlers.iteritems() ] self.messageHandlers.clear() self._triggerEvent('disconnect') for callback, message in callbacks: callback(message) def _disconnect_failure_message(self, messageId): return { "messageId": messageId, "responseType": "Failure", "message": "Disconnected from server" }
class AIBase(object): """Common features of all Cinch AI Agents. This provides an interface with the socketio server, handles known socket event messages, and includes common functions like checking play legality. When the agent receives indication that it is the active player, the play or bid methods are called, which must return the AI's desired play/bid. Attributes: room (int): The room number that the agent is in. pNum (int): The player number / seat number occupied by the agent. hand (list): The agent's hand of Card objects. gs (GS): The gamestate object used by the agent. name (str): The agent's name as identified in the model module. label (str): The label used to identify the agent in logs. socket (SocketIO): The socketio connection used to communicate with the main server. ns (BaseNamespace): The namespace used by the socket. """ # =============== # Agent Management & Communications # =============== def __init__(self, targetRoom, targetSeat, ident): """Initialize AI. The AI agent connects to the server, joins a game, and prepares to receive game data. Args: targetRoom (int): Target game room number. targetSeat (int): Target seat within game room. ident (dict): AI identifying info, including data like version number and AI description. This is provided from the AI model module via the manager. """ self.room = None self.pNum = None self.hand = [] self.gs = GS() self.name = ident['name'] self.label = self.name + "_" + str(targetSeat) self.setupSocket() self.ns.emit('nickname', self.label) self.join(targetRoom, targetSeat) self.pNum = targetSeat def __del__(self): """Cleanly shutdown AI agent.""" self.stop() def ackJoin(self, *args): """Callback for request to join room. Args: *args (list): Confirmation data after joining room. If successful, this will be a 1-element list with a dict containing `roomNum`, `seatChart`, and `mySeat` keys. Otherwise, it will be an empty list because the request resulted in an error. """ if len(args) == 0: # The agent will receive an 'err' event in this case. # TODO: look into intelligently handling this kind of error and # ensure it is not possible to sit in a bad seat. self.stop() return data = args[0] self.room = data['roomNum'] if self.room != 0: # Joining the lobby doesn't warrant any action self.pNum = data['mySeat'] log.info("{2}_AI joined Game {0} Seat {1}".format( self.room, self.pNum, self.name)) def on_err(self, msg): """Handle error event from server and log all data. Since some errors may be non-fatal, an error does not kill the agent. Args: msg (str): Error message. """ log.error("err: {0}".format(msg)) log.error("dump: {0} {1}".format(self.label, str(self.hand))) log.error("gs: {0}".format(self.gs)) def handle_game_action(self, *args): """Combination handler for bid and play. This calls the agent's `bid` or `play` method as appropriate. If it is not the agent's turn, the `think` method is called instead. If the game is over, no actions are taken. This is also called when receiving `startData`. Args: *args (list): Data transmitted by server with bid or play event. """ try: msg = args[0] except Exception as e: log.error("{0}: {1}".format(e.message, args)) return self.applyUpdate(msg) if 'win' in msg: # Game is over return if self.gs.activePlayer == self.pNum: if self.gs.mode == BID: self.bid() else: self.play() else: self.think() def setupSocket(self): """Create socket connection and configure namespace.""" self.socket = SocketIO('127.0.0.1', SOCKETIO_PORT) self.ns = self.socket.define(BaseNamespace, SOCKETIO_NS) self.ns.on('err', self.on_err) self.ns.on('bid', self.handle_game_action) self.ns.on('play', self.handle_game_action) self.ns.on('startData', self.handle_game_action) def applyUpdate(self, msg): """Update internal game information based on server message. Args: msg (dict): Message from server containing game state information and changes. """ self.gs.activePlayer = msg['actvP'] if 'win' in msg: self.stop() if 'playC' in msg: self.gs.cardsInPlay.append(cards.Card(msg['playC'])) if 'sco' in msg: self.gs.score = msg['sco'] if 'gp' in msg: self.gs.gp = msg['gp'] if 'mp' in msg: self.gs.mp = msg['mp'] if 'remP' in msg: self.gs.takenCards[msg['remP']].append(self.gs.cardsInPlay) self.gs.cardsInPlay = list() if 'dlr' in msg: self.gs.dealer = msg['dlr'] if 'addC' in msg: self.hand = [cards.Card(num) for num in msg['addC']] self.gs.reset() if 'trp' in msg: self.gs.trump = msg['trp'] if 'mode' in msg: self.gs.mode = msg['mode'] if 'actor' in msg: self.gs.actor = msg['actor'] if 'bid' in msg: self.gs.bidLog[msg['actor']] = msg['bid'] if msg['bid'] > self.gs.highBid: self.gs.highBid = msg['bid'] def join(self, room, seat): """Make request to join room. Args: room (int): Target room number seat (int): Target seat number """ self.ns.emit('join', room, seat, self.ackJoin) def start(self): """Activate AI.""" self.socket.wait() # Blocks until self.stop() def stop(self): """Gracefully shutdown AI agent.""" self.socket.disconnect() # TODO do any final cleanup (logging, etc) # =============== # Game Actions & Rules # =============== def send_bid(self, bid): """Send bid to server. Handle error response. TODO add callback to handle if an illegal bid was made; AIBase should provide failsafe methods. Args: bid (int): Bid amount (0-5, where PASS = 0) """ if self.is_legal_bid(bid): pass elif bid == 0: # Illegally tried to pass (stuck dealer) bid = 1 log.error("Agent illegally tried to pass; adjusting bid to 1.") else: log.error("Agent made illegal bid of {0}; adjusting bid to PASS." "".format(bid)) bid = 0 self.ns.emit('bid', bid) # Transmit bid to server if bid > 0: log.info("{0} bids {1}".format(self.label, bid)) else: log.info("{0} passes".format(self.label)) def send_chat(self, chat_msg): """Send chat-style message to server (for debugging & hijinks). Args: chat_msg (str): Message to send via chat channels. """ self.ns.emit('chat', chat_msg) def send_play(self, card): """Send proposed play to server and remove card from hand. If the AI sends an illegal play, there is no recovery. TODO: add callback to handle illegal play; AIBase should provide failsafe methods. Args: card (Card): Card object to play. It is assumed to have been checked for play legality by the caller. """ card_val = card.code self.ns.emit('play', card_val) log.info("{0} plays {1}".format(self.label, str(card))) self.hand.remove(card) def is_legal_bid(self, bid): """Check if proposed bid is legal. Return boolean. Args: bid (int): Bid value (0=PASS, 5=CINCH). """ if bid == 0: if self.pNum == self.gs.dealer and self.gs.highBid < 1: return False # Stuck dealer, must not pass else: return True # Always legal to pass otherwise elif bid < 0 or bid > 5: return False # Bid out of bounds elif bid > self.gs.highBid: return True elif bid == 5 and self.pNum == self.gs.dealer: return True else: return False def is_legal_play(self, card): """Check if proposed play is legal. Return boolean. card (Card): Proposed play. """ if len(self.gs.cardsInPlay) == 0: return True # No restriction on what can be led if card.suit == self.gs.trump: return True # Trump is always OK else: led = self.gs.cardsInPlay[0].suit if card.suit == led: return True # Followed suit else: for c in self.hand: if led == c.suit: return False # Could've followed suit but didn't return True # Throwing off # =============== # Intelligence # =============== def bid(self): """Bidding logic. This is to be implemented within each agent. This gets called only when game mode == BID and self is active player. """ raise NotImplementedError("bid() needs to be implemented in subclass.") def play(self): """Play logic. This is to be implemented within each agent. This gets called only when game mode == PLAY and self is active player. """ raise NotImplementedError( "play() needs to be implemented in subclass.") def think(self): """Thinking logic, optionally implemented within each agent. This gets called after bids/plays but when this agent is not the active player (e.g. for pruning move trees after a card is played). """ pass
class SocketService(threading.Thread, SentinelObject): def __init__(self, options, pingTimeout=1): threading.Thread.__init__(self) self.static_token = options['token'] self.options = options # saved for reconnect # self.__init_socket() self.commands = {} # this will hold the possible commands from server self._stop = threading.Event() # for stopping the thread, testing self.socket = None self.socketIO = None """ """ def init(self): self.__init_socket() """ """ def __init_socket(self): token = jwt.encode({"name": self.options["camera-id"]}, 'secret') ip = self.options["ip"] port = self.options["port"] socket = self.options["socket-id"] camera = self.options["camera-id"] self.socketIO = SocketIO(ip, port, params={'id': camera, 'token': token}) self.socket = self.socketIO.define(SocketServiceNamespace, socket) self.logger.debug("Init socket: [%s]" % socket) """ """ def get_socket(self): return self.socket """ """ def get_socketIO(self): return self.socketIO """ """ def __apply_command(self, command, param=None): if command in self.commands: if param is None: self.commands[command]() else: self.commands[command](param) """ """ def __handle_server_message(self, message): self.logger.debug("[%s] handle_server_message" % self.options["socket-id"]) # todo key check self.logger.debug(message) if 'command' not in message: self.logger.error("Missing command key.") self.logger.error(message) else: print len(message) if len(message) < 2: self.__apply_command(message['command']) else: self.__apply_command(message['command'], message) """ """ def disconnect(self): self.socketIO.disconnect(self.options["socket-id"]) # try: # self.socketIO.disconnect(self.options["socket-id"]) # except ConnectionError: # self.logger.error(self.options["socket-id"] + " connection error") """ """ def send(self, id, msg): try: self.connection_handler() self.socket.emit(id, msg) except websocket.WebSocketConnectionClosedException: self.logger.debug("[%s] reconnecting ..." % self.options["socket-id"]) except AttributeError, IndexError: self.logger.debug('Hiba történt az üzenet küldésekor') except ConnectionError: self.logger.debug('Kapcsolati hiba') self.__init_socket() self.socket.on(self.options["camera-id"], self.__handle_server_message)
def __enter__(self): sock = SocketIO('rhizi.local', 8080) ns_sock = sock.define(self.namespace, '/graph') self.sock = sock print sock return sock, ns_sock