class WxSocket(threading.Thread): def __init__(self, callbacks, host, port): super(WxSocket, self).__init__() self.callbacks = callbacks self.host = host self.port = port self.daemon = True #this will kill the thread when the main thread exits self.start() #this is the worker function that will be held in the other thread def run(self): self.io = SocketIO(self.host, self.port, LoggingNamespace) for event, callback in self.callbacks.iteritems(): self.io.on(event, callback) self.io.wait() def connect(self): self.io.connect() def disconnect(self): self.io.disconnect() def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): self.disconnect()
def send_data(save_path): """ Sends all the data files that are present in the specified path to the Qbike server. :param save_path: Requires the path in which the trips are saved. :return: Nothing. The data is sent to the Server and the txt files are removed from the path's directory. """ end = False Trip_nb = 100 while end == False: if not os.path.isfile('C:\Users\Joren\Documents\Ir 1B\P&O\P&O 3\Tryouts\Trips\Trip1.txt'): end = True else: for nb in reversed(range(0, 100)): Trip = os.path.join(save_path, "Trip" + str(nb) + ".txt") Trip_nb = str(nb) if os.path.isfile(Trip): break Trip_path = os.path.join(save_path, r"Trip" + Trip_nb + r".txt") with open(Trip_path, "r") as Trip: batch = json.load(Trip) info = {'purpose': 'batch-sender', 'groupID': "cwa2", 'userID': ID} socketIO = SocketIO('dali.cs.kuleuven.be', 8080) socketIO.on('server_message', on_response) socketIO.emit('start', json.dumps(info), on_response) socketIO.wait(2) socketIO.emit('batch-tripdata', json.dumps(batch), on_response) socketIO.wait(5) os.remove(Trip_path) print "Sent Data"
class TestClient(object): def on_bot_uttered(self, event): self.flusso.append((logging.INFO, '[-] bot_uttered: ' + event['text'])) try: self.answerList.append(event['text']) except KeyError: pass def __init__(self, section, server, port, flusso, secs): self.answerList = [] self.flusso = flusso i = 0 self.newSocket = SocketIO(server, port) self.newSocket.on('bot_uttered', self.on_bot_uttered) for client_msg in section['client']: self.flusso.append( (logging.INFO, "[+] usr_uttered: " + client_msg)) self.newSocket.emit('user_uttered', { 'message': client_msg, 'customData': "" }) self.newSocket.wait(seconds=secs) self.newSocket.disconnect() flag_num = (len(self.answerList) == len(section['server'])) flag_test = all( list( map(lambda x: bool(re.search(x[1], x[0])), zip(self.answerList, section['server'])))) if flag_num and flag_test: self.flusso.append((logging.INFO, "[!] Test PASSED")) else: self.flusso.append((logging.ERROR, "[!] Test FAILED"))
def connect(): """Sends the starting signal to the server.""" arduino = serial.Serial('/dev/serial/by-id/usb-Gravitech_ARDUINO_NANO_13BP1066-if00-port0', 115200) info_start = {'purpose': 'realtime-sender', 'groupID': "cwa2", 'userID': "r0462183"} metadata = {'other':"trip ended"} #string "trip ended" stored in metadata under key 'other' to be able to filter on realtime trips easier on the bicyclus website print "Setting up for server connection ..." while True: #connection tests everywhere they are needed to minimise amount of connection errors if try_connection() == True: socketIO = SocketIO('dali.cs.kuleuven.be', 8080) break time.sleep(2) while True: if try_connection() == True: socketIO.on('server_message', on_emit) break socketIO.wait(2) print "Trying to send start signal for trip ..." while True: if try_connection() == True: socketIO.emit('start', json.dumps(info_start), on_emit) print "Connection verified, start signal sent." socketIO.wait(2) break socketIO.wait(2) info_end = {"_id":startID, "meta": metadata} return info_end
class Broadcaster(object): port = 8080 host = "localhost" def __init__(self, port=8080, host="localhost"): self.port = port self.host = host self.socketIO = SocketIO(host, int(port)) self.socketIO.on("ack", self.logACK) def logACK(self, data): print("Acknowledgement received for %s" % data['original']) def emit(self, event, data): self.socketIO.emit(event, data) def on(self, event, callback): self.socketIO.on(event, callback) def wait(self, millis): self.socketIO.wait(millis) def wait_forever(self): self.socketIO.wait()
class WebSocketIO: def __init__(self): global host global port self.socketIO = SocketIO(host, port, LoggingNamespace) self.socketIO.on('wiiscale-connect', self.receive_connect) self.socketIO.on('wiiscale-disconnect', self.receive_disconnect) def wait(self): self.socketIO.wait(seconds = 1) def send_status(self, status): self.socketIO.emit('wiiscale-status', {'status': status}) def send_weight(self, totalWeight): self.socketIO.emit('wiiscale-weight', {'totalWeight': totalWeight}) # def send_connection_status(self, status): # self.socketIO.emit('wiiscale-connection', {'status': status}) # Accepts True or False as argument def receive_connect(self): global sleep sleep = False def receive_disconnect(self): global board global sleep sleep = True board.disconnect()
def tradeEvent_sl(self, ws_host, ws_port, brokerToken, ws_EmitEvent=userData['ws_event_sl'], ws_OnEvent=userData['ws_event_sl'], waitTime=userData['ws_waitTime'], logs=0): def result_handler(*args): self.socketsEvent = json.loads(json.dumps(*args)) io.disconnect() # 建立socket连接 io = SocketIO(ws_host, ws_port, params=brokerToken) # 发起开仓请求 io.emit(ws_EmitEvent, '', result_handler) # 监听开仓result io.on(ws_OnEvent, result_handler) # 设置监听超时时间 io.wait(seconds=waitTime) try: return self.socketsEvent except: print( "Error: OnlineTrade srv abnormal!!!! webSockets monitor sl event fail." )
def ListenIO(self): # socketIO = SocketIO('192.168.1.33', 3000) # socketIO = SocketIO('192.168.1.223', 3000) socketIO = SocketIO('localhost', 3000) socketIO.on('serverToPython', self.listener) socketIO.emit('clientType', 'Python') socketIO.wait(seconds = 6000)
def login(callback=on_chat): cookie = cookielib.Cookie(version=0, name='password_livechan', value=config.nolimitCookie, port=None, port_specified=False, domain='kotchan.org', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False) cookies.set_cookie(cookie) livechan_pass = get_password() if livechan_pass == "": print("wrong password") login() global socketIO socketIO = SocketIO('https://kotchan.org', cookies={'password_livechan': livechan_pass}) socketIO.on('chat', callback) socketIO.on('request_location', on_request_location) thread.start_new_thread(socketIO.wait, ())
class WebsocketRemoteControl(object): def __init__(self, bot): self.bot = bot self.host, port_str = self.bot.config.websocket_server_url.split(":") self.port = int(port_str) self.sio = SocketIO(self.host, self.port) self.sio.on("bot:process_request:{}".format(self.bot.config.username), self.on_remote_command) self.thread = threading.Thread(target=self.process_messages) def start(self): self.thread.start() return self def process_messages(self): self.sio.wait() def on_remote_command(self, command): name = command["name"] command_handler = getattr(self, name, None) if not command_handler or not callable(command_handler): self.sio.emit( "bot:send_reply", {"response": "", "command": "command_not_found", "account": self.bot.config.username} ) return if "args" in command: command_handler(*args) return command_handler() def get_player_info(self): player_info = self.bot.get_inventory()["responses"]["GET_INVENTORY"] self.sio.emit( "bot:send_reply", {"result": player_info, "command": "get_player_info", "account": self.bot.config.username} )
def main(): global commandArgs global robotID global appServerSocketIO parser = argparse.ArgumentParser(description='start robot control program') parser.add_argument('robot_id', help='Robot ID') parser.add_argument('--reverse-ssh-key-file', default='/home/pi/reverse_ssh_key1.pem') parser.add_argument('--reverse-ssh-host', default='[email protected]') commandArgs = parser.parse_args() print commandArgs robotID = commandArgs.robot_id print "connecting to app server socket.io" appServerSocketIO = SocketIO('robotstreamer.com', 8022, LoggingNamespace) print "finished connecting to app server" appServerSocketIO.on('connect', onHandleAppServerConnect) appServerSocketIO.on('reconnect', onHandleAppServerReconnect) appServerSocketIO.on('disconnect', onHandleAppServerDisconnect) appServerSocketIO.on('reverse_ssh_8872381747239', startReverseSshProcess) appServerSocketIO.on('end_reverse_ssh_8872381747239', endReverseSshProcess) while True: appServerSocketIO.wait(seconds=1)
class Client(object): def __init__(self, client_factory): self.logger = logging.getLogger('Graduation') self.socket = None self.client_factory = client_factory self.host = client_factory.host self.port = client_factory.port def connect(self): self.socket = SocketIO(self.host, self.port, LoggingNamespace); self.socket.on('device_data_response', self.on_response); self.sendMessage(0) self.socket.wait() def on_response(self): time.sleep(2); tem = random.randint(0, 40); self.sendMessage(tem) def sendMessage(self, tem): data = dict(); data["id"] = 1 data["name"] = "name" params = dict(); params["temperature"] = tem data["params"] = params self.socket.emit('device_data', data)
def login(): image_response = fetch('https://livechan.net/captcha.jpg') image_data = image_response.read() with open('captcha.jpg', 'w') as f: f.write(image_data) os.system("open captcha.jpg") digits = int(raw_input("enter the captcha: ")) post_params = {} post_params["digits"] = digits login_response = post('https://livechan.net/login', post_params) login_html = login_response.read() print login_html livechan_pass = get_password() if livechan_pass == "": login() global socketIO socketIO = SocketIO('https://livechan.net', cookies={'password_livechan': livechan_pass}) socketIO.on('chat', on_chat) socketIO.on('user_count', on_user_count) thread.start_new_thread ( socketIO.wait, () )
class SocketServerThread(threading.Thread): """A socket server to hold the connection.""" def __init__(self): super(SocketServerThread, self).__init__() threading.Thread.__init__(self) def run(self): try: print("threading has begun") self.io = SocketIO('http://10.224.59.158', 3000, verify=False) print("Created new SocketServer") self.io.on('connected', self.handleClientMessage) self.io.on('reply', self.on_server_response) self.io.wait() return except (e): print("There was an error in the server thread.") print("threading has completed") # self.io.wait(seconds=10) def on_connect(self): print('[Connected]') def on_server_response(self, responseObj): print('Server response received', type(responseObj)) # responseDict = json.loads(responseObj) sublime.active_window().active_view().run_command("annotate_log", responseObj) def handleServerMessage(self, *args): print("Server Message", args) def handleClientMessage(self, *args): print("Client Message", args)
class AudioCommandThread(object): def __init__(self): print "AudioCommandThread" self.play_thread = PlayVoidAudio() self.socketio = SocketIO(host, port) self.socketio.on('startvoid', self.on_start) self.receive_events_thread = Thread(target=self._receive_events_thread) self.receive_events_thread.daemon = True self.receive_events_thread.start() while True: try: check = raw_input() except EOFError: check = "" self.socketio.emit('event', check) def on_start(self, event): print "on_start" self.play_thread_start_join = Thread(target=self.play_thread.run, ) self.play_thread_start_join.start() def on_reset(self, event): print('Play Stopped...') # self.play_thread.terminate() # # wait for actual termination to close up recording screen # self.play_thread_start_join.join() def _receive_events_thread(self): self.socketio.wait()
class cloud_links_core: def __init__(self, host, port, post_namespace, rpc): self.host = host self.port = port self.post_namespace = post_namespace self.host_url = host + ":" + str(port) + post_namespace self.rpc = rpc #self.__onReady() self.socketIO = SocketIO(self.host, port) self.socketIO.on('my_request', self.on_my_resquest) # self.socketIO.on('redirect', self.on_redirect) def __onReady(self): request_json = pyjsonrpc.create_request_json("onReady") self.send_msg(request_json) def send_msg(self, value): requests.post(self.host_url, value) # parsed_response = json.loads(response) # print json.dumps(parsed_response, indent=4) def on_my_resquest(self, request): parsed_request = json.loads(request) print json.dumps(parsed_request, indent=4) response_json = self.rpc.call(request)
def main(sip,port): global SERVER_IP global SERVER_PORT global SERVER_ADDR global socketIO global machine SERVER_IP = sip SERVER_PORT = port SERVER_ADDR = SERVER_IP + ":" + str(SERVER_PORT) socketIO = SocketIO(SERVER_IP, SERVER_PORT, LoggingNamespace) enter_nick() machine = sm("Test") signal.signal(signal.SIGINT, exit_match) socketIO.on(cs.JOIN_MATCH, machine.sock_onjoin_match) socketIO.on(cs.NEW_MATCH, machine.sock_match_confirm) socketIO.on(cs.BEGIN_MATCH, machine.sock_begin_match) socketIO.on(cs.RESULT, machine.sock_onresult) socketIO.on(cs.REMATCH, machine.sock_onrematch) socketIO.on(cs.LEAVE, machine.sock_onleave) socketIO.wait()
def main(): app = App(False) socketIO = SocketIO(API_URL, 443, LoggingNamespace) socketIO.on('location', app.on_ws_location) Thread(target=socketIO.wait).start() app.MainLoop()
def main(argv): (roombaPort, launcherPort, production) = parse_args(argv) global launcher_port launcher_port = launcherPort print("launcher on port %s" % launcher_port) global roomba_port roomba_port = roombaPort print("roomba on port %s" % roomba_port) global roomba # define roomba as unscoped global variable global launcher # define launcher as unscoped global variable try: roomba = Serial(port = roombaPort, baudrate = const.ROOMBA_BAUD_RATE) # open serial connection to roomba except SerialException: print('Serial connection to Roomba over %s could not be established' % roombaPort) sys.exit(-1) try: launcher = Serial(port = launcherPort, baudrate = const.LAUNCHER_BAUD_RATE, writeTimeout = None) # open serial connection to launcher except SerialException: print('Serial connection to launcher over %s could not be established' % launcherPort) sys.exit(-1) roomba.write(const.SEQ_START) # start time.sleep(1) roomba.write(const.SEQ_MODE_SAFE) # enter safe mode time.sleep(0.2) socketIO = SocketIO(const.PROD_SERVER_HOST, const.PROD_SERVER_PORT, CommandControl, verify = False) if production else SocketIO(const.DEV_SERVER_HOST, const.DEV_SERVER_PORT, CommandControl) socketIO.on('command', on_command) socketIO.on('client-disconnect', on_client_disconnect) socketIO.wait()
def login(callback=on_chat): #image_response = fetch('https://livechan.net/captcha.jpg') #image_data = image_response.read() #with open('captcha.jpg', 'w') as f: # f.write(image_data) #os.system("open captcha.jpg") #digits = int(raw_input("enter the captcha: ")) #post_params = {} #post_params["digits"] = digits #login_response = post('https://livechan.net/login', post_params) #login_html = login_response.read() cookie = cookielib.Cookie(version=0, name='password_livechan', value='somepassword', port=None, port_specified=False, domain='livechan.net', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False) cookies.set_cookie(cookie) livechan_pass = get_password() if livechan_pass == "": print "wrong password" login() global socketIO socketIO = SocketIO('https://livechan.net', cookies={'password_livechan': livechan_pass}) socketIO.on('chat', callback) socketIO.on('request_location', on_request_location) thread.start_new_thread ( socketIO.wait, () )
class TestJoinExistingRoom(IODrawTestCase): # use uuid to avoid conflicts on retesting ROOM = "test_join_existing-" + str(uuid.uuid4()) def setUp(self): super().setUp() self.socket2 = SocketIO('localhost', 5000, LoggingNamespace) def on_init_room(self, data): logger.info("on_init_room: Received {} ({})".format(data, type(data))) self.assertIsInstance(data, dict, msg='Expected a dict') self.assertEqual(len(data['pic']), 1, msg='Expected key pic {} to be of len(1)'.format( data['pic'])) self.assertListEqual(data['pic'][0]['from'], [0, 0]) self.assertListEqual(data['pic'][0]['to'], [300, 200]) def test_draw(self): self.socketIO.emit('joinRequest', {"room": TestJoinExistingRoom.ROOM}) self.socketIO.wait(seconds=1) self.socketIO.emit('draw', {'from': [0, 0], 'to': [300, 200]}) self.socketIO.wait(seconds=1) self.socket2.wait(seconds=1) self.socket2.on('initRoom', self.on_init_room) self.socket2.emit('joinRequest', {"room": TestJoinExistingRoom.ROOM}) self.socket2.wait(seconds=1)
class LoveSocket: def __init__(self): self.io = None self.hearts = 0 self.poos = 0 def start(self): threading.Thread(target=self.__start).start() def __start(self): self.io = SocketIO(LOVE_SOCKET_URL, verify=False) self.io.on("love", self.__add_love) self.io.on("poo", self.__add_poo) self.io.wait() def stop(self): self.io.disconnect() self.io = None def reset_hearts(self): hearts = self.hearts self.hearts = 0 return hearts def reset_poos(self): poos = self.poos self.poos = 0 return poos def __add_love(self, *args): self.hearts += 1 def __add_poo(self, *args): self.poos += 1
def main(): global TWITTER boxxy = None if isfile(FILENAME): # save file so create boxxy from file with open(FILENAME, 'r') as f: boxxy = jp.decode(f.read()) else: # no save so create new client boxxy = Boxxy() socketIO = SocketIO('live.12urenloop.be', 8080, LoggingNamespace, resource='socket.io') paths = { "/ping": boxxy.ping, "/state": boxxy.state, "/lap": boxxy.lap, "/position": boxxy.position } for path, method in paths.items(): socketIO.on(path, method) socketIO.wait(seconds=3600 * 12)
def watch_mempool(crypto, callback=lambda tx: print(tx['txid']), verbose=False): if verbose: import logging logging.getLogger('socketIO-client').setLevel(logging.DEBUG) logging.basicConfig() services = get_optimal_services(crypto, 'address_balance') for service in services: socketio_url = service.socketio_url if not socketio_url: continue try: socketIO = SocketIO( socketio_url, verify=False, ) # namespace=LoggingNamespace) socketIO.emit('subscribe', 'inv') socketIO.on('tx', callback) socketIO.wait() except KeyboardInterrupt: return except: print("failed")
def ListenIO(self): # socketIO = SocketIO('192.168.1.33', 3000) # socketIO = SocketIO('192.168.1.223', 3000) socketIO = SocketIO('localhost', 3000) socketIO.on('serverToPython', self.listener) socketIO.emit('clientType', 'Python') socketIO.wait(seconds=6000)
class TagoRealTime: def __init__(self, address, token, callback): self.socket = SocketIO(address, 443, LoggingNamespace) self.token = token self.callback = callback def run(self, environment, data, token): if len(data) == 0: data = [] context = {"token": token, "environment": environment} self.callback(context, data) def on_connect(self, arg): print arg['result'] def on_scope(self, arg): for x in arg: self.run(x['environment'], x['data'], self.token) def listening(self, wait): self.socket.emit('register:analysis', self.token) self.socket.on('register:analysis', self.on_connect) self.socket.on('run:analysis', self.on_scope) if wait: self.socket.wait(seconds=wait) else: self.socket.wait() return self.socket def get_socket(): self.socket
class AtlasStream(object): CHANNEL_RESULT = "atlas_result" CHANNEL_PROBE = "atlas_probestatus" CHANNEL_ERROR = "atlas_error" CHANNELS = { "result": CHANNEL_RESULT, "probe": CHANNEL_PROBE, "error": CHANNEL_ERROR, } def __init__(self): """Initialize stream""" self.iosocket_server = "atlas-stream.ripe.net" self.iosocket_resource = "/stream/socket.io" self.socketIO = None def connect(self): """Initiate the channel we want to start streams from.""" self.socketIO = SocketIO(host=self.iosocket_server, port=80, resource=self.iosocket_resource, transports=["websocket"]) def disconnect(self): """Exits the channel k shuts down connection.""" self.socketIO.disconnect() self.socketIO.__exit__([]) def bind_channel(self, channel, callback): """Bind given channel with the given callback""" try: self.socketIO.on(self.CHANNELS[channel], callback) except KeyError: print("The given channel: <{0}> is not valid".format(channel)) def start_stream(self, stream_type, **stream_parameters): """Starts new stream for given type with given parameters""" if stream_type in ("result", "probestatus"): self.subscribe(stream_type, **stream_parameters) else: print("Given stream type: <{0}> is not valid".format(stream_type)) def subscribe(self, stream_type, **parameters): """Subscribe to stream with give parameters.""" parameters.update({"stream_type": stream_type}) self.socketIO.emit('atlas_subscribe', parameters) def timeout(self, seconds=None): """ Times out all streams after n seconds or wait forever if seconds is None """ if seconds is None: self.socketIO.wait() else: self.socketIO.wait(seconds=seconds)
def check_pushould(self): socketio = SocketIO( self.pushurl, params={"client_token": str(self.client_token)}, verify=False) socketio.on("send", self.add_status) socketio.emit("subscribe", {"room": "TestSecurity"}) socketio.wait()
def run(self): """ Method that runs forever """ while True: socketIO = SocketIO( 'rover-sensors-data-provider.52.35.15.130.nip.io', proxies={'https': 'http://proxy.compaq.com:8080'}) socketIO.on('telemetry', self.set_telemetry_data) socketIO.wait()
def get_bearer(myUrl_base): mytoken='c2340cde1dbf571ab43d235cfa7b0f940ed6b429' websocket_port=443 socketIO=SocketIO(myUrl_base,websocket_port,params={'access_token':'{}'.format(mytoken)}) socketIO.on('connect',connect) socketIO.on('disconnect',close) bearer_access_token='Bearer '+ socketIO._engineIO_session.id + mytoken return(bearer_access_token)
def test_events(self): global ON_RESPONSE_CALLED ON_RESPONSE_CALLED = False socketIO = SocketIO('localhost', 8000) socketIO.on('ddd', on_response) socketIO.emit('aaa', PAYLOAD) sleep(0.5) self.assertEqual(ON_RESPONSE_CALLED, True)
def test_events(self): global ON_RESPONSE_CALLED ON_RESPONSE_CALLED = False socketIO = SocketIO('localhost', 8000, transports=['xhr-polling']) socketIO.on('ddd', on_response) socketIO.emit('aaa', PAYLOAD) sleep(2) self.assertEqual(ON_RESPONSE_CALLED, True)
def check_pushould(self): socketio = SocketIO(self.pushurl, params={"transports": ["polling", "websocket"], "client_token": str(self.client_token)}, verify=False) socketio.on('send', self.add_message) socketio.emit("subscribe", {"room": "sadpandapush"}) socketio.wait()
def hkube_simulator(ip, port): print('runing hkube simulator pipeline on: {}:{}...'.format(ip, port)) socket_io = SocketIO(ip, port) socket_io.emit('connect') socket_io.emit('initialize') socket_io.emit('start') socket_io.on('started', print('simulator pipeline started')) socket_io.wait()
class ExaBGP(): def __init__(self, prefixes, host): self.host = host self.prefixes = prefixes self.sio = None signal.signal(signal.SIGTERM, self.exit) signal.signal(signal.SIGINT, self.exit) signal.signal(signal.SIGCHLD, signal.SIG_IGN) def start(self): with Connection(RABBITMQ_HOST) as connection: self.connection = connection self.exchange = Exchange('bgp-update', channel=connection, type='direct', durable=False) self.exchange.declare() try: self.sio = SocketIO('http://' + self.host, namespace=BaseNamespace) def exabgp_msg(bgp_message): msg = { 'type': bgp_message['type'], 'communities': bgp_message.get('communities', []), 'timestamp': float(bgp_message['timestamp']), 'path': bgp_message.get('path', []), 'service': 'exabgp|{}'.format(self.host), 'prefix': bgp_message['prefix'], 'peer_asn': int(bgp_message['peer_asn']) } if mformat_validator(msg): with Producer(connection) as producer: msgs = normalize_msg_path(msg) for msg in msgs: key_generator(msg) log.debug(msg) producer.publish(msg, exchange=self.exchange, routing_key='update', serializer='json') else: log.warning('Invalid format message: {}'.format(msg)) self.sio.on('exa_message', exabgp_msg) self.sio.emit('exa_subscribe', {'prefixes': self.prefixes}) self.sio.wait() except KeyboardInterrupt: self.exit() except Exception: log.exception('exception') def exit(self): print('Exiting ExaBGP') if self.sio is not None: self.sio.disconnect() self.sio.wait()
class Sentiment(): HOST = 'https://emosapi.com' PORT = 443 APPKEY = '<APP KEY>' APPSECRET = '<APP SECRET>' socket_io = None s_thread_login = None s_thread_post = None def connect(self): self.socket_io = SocketIO(self.HOST, self.PORT, verify=False) self.socket_io.on('success', self.on_success) self.socket_io.on('response', self.on_response) self.socket_io.emit( 'login', {'appkey': self.APPKEY, 'appsecret': self.APPSECRET} ) self.s_thread_login = threading.Thread(target=self.socket_io.wait) self.s_thread_login.start() def on_success(self, res): print("SUCCESS:", res) if res.get('action') == 'login' and res.get('code') == 100: self.socket_io.emit( 'post', { 'api': 'Sentimentv2', 'version': 'emotion', 'params': { 'text': 'required parameter', # Hard coded test text. 'lang':'en-us' } } ) self.s_thread_post = threading.Thread(target=self.socket_io.wait) self.s_thread_post.start() else: raise Exception("Login failed") def on_response(self, res): print("RESPONSE", res) # Disconnect when get API response. self.disconnect() def disconnect(self): if not self.socket_io: raise Exception("Please connect first.") print("disconnect before:", self.socket_io.connected) self.socket_io.disconnect() print("disconnect after:", self.socket_io.connected) self.socket_io = None self.s_thread_login = None self.s_thread_post = None
def run(self): def on_connect(): self.logger.debug('You have connected') def on_disconnect(): self.logger.debug('You have been disconnected') def on_reconnect(): self.logger.debug('You have reconnected') def on_conferGo(*args): self.logger.debug('Mesage to go to conference received.') #get the data that was passed in pwd = args[0]['passwd'] url = args[0]['url'] user = args[0]['user'] whitelist = False #need to check the password is valid against the user record #cannot handle via job queue, as we need ENVIRON[listen] to stay off while cconfernece open self.ENVIRON["listen"] = False time.sleep(1) if whitelist: result = subprocess.Popen([ "chromium-browser", "--use-fake-ui-for-media-stream", url ], stdout=subprocess.PIPE) else: result = subprocess.Popen([ "chromium-browser", "--use-fake-ui-for-media-stream", url ], stdout=subprocess.PIPE) def on_conferKill(*args): self.logger.debug('Mesage to kill conference instance received.') result = subprocess.Popen(['killall', 'chromium-browse'], stdout=subprocess.PIPE) self.ENVIRON["listen"] = True # Connect to the server TOKEN = self.ENVIRON["api_token"] SUBSCR = self.ENVIRON["api_login"] USRNAME = self.ENVIRON["devicename"] qstring = {'token': TOKEN, 'subscriber': SUBSCR, 'user': USRNAME} self.logger.debug('Attempting to connect with %s - %s - %s' % (TOKEN, SUBSCR, USRNAME)) socketIO = SocketIO(self.URL, 443, params=qstring) # Set up custom listeners socketIO.on('connect', on_connect) socketIO.on('disconnect', on_disconnect) socketIO.on('reconnect', on_reconnect) socketIO.on('conferGo', on_conferGo) socketIO.on('conferKill', on_conferKill) socketIO.wait()
def main(): global socketIO global model model = nn.load_model('models/004.txt') socketIO = SocketIO(host, 5000, LoggingNamespace) socketIO.on('airead', algorithm) socketIO.on('error', error) socketIO.emit('aictl', user) socketIO.wait()
def client(): print 'Waiting for connection...' GPIO.output(18, GPIO.HIGH) socketIO = SocketIO('sentiment-of-things.mybluemix.net', 80, LoggingNamespace) socketIO.on('sentiment', sentiment_handler) socketIO.wait() GPIO.output(18, GPIO.LOW) print 'Ending the connection'
def send_data(cookies): socketio = SocketIO(SOCKETIO_HOST, SOCKETIO_PORT, SocketioNamespace, cookies=cookies) socketio.on(DATA_RESPONSE_TOPIC, SocketioNamespace.on_data_response) socketio.emit(DATA_TOPIC, {'data': random.randint(10, 100)}) socketio.wait(seconds=5) threading.Timer(data_rate, send_data, [cookies]).start()
class CanvasClient(object): def __init__(self, options): self.name = options["name"] self.moduleName = options["moduleName"] self.className = options["className"] if not self.className: raise Exception("Must give python modules a class name in options") self.serverIP = options["serverIP"] self.serverPort = options["serverPort"] self.options = options module = importlib.import_module("modules.%s" % self.moduleName) klass = getattr(module, self.className) self.module = klass(self, self.options) self.socket = None def connect(self): self.socketIO = SocketIO(self.serverIP, self.serverPort) self.socketIO.on('event', self.onEvent) self.socketIO.on('action', self.onAction) self.socketIO.wait() def disconnect(self): self.socketIO.disconnect() def onEvent(self, message): print "%s %s %s" % (self.name, "onEvent", message) self.module.onEvent(message) sys.stdout.flush() def onAction(self, message): print "%s %s %s" % (self.name, "onAction", message) if "to" in message and message["to"] == self.name: self.module.onAction(message) sys.stdout.flush() def emitEvent(self, event, eventData): message = { "from": self.name, "event": event, "data": eventData } print "%s %s %s" % (self.name, "emitEvent", message) self.socketIO.emit("event", message) sys.stdout.flush() def emitAction(self, to, action, data): message = { "from": self.name, "to": to, "action": action, "data": data } print "%s %s %s" % (self.name, "emitAction", message) self.socketIO.emit("action", message) sys.stdout.flush()
def run(self): i = 0 for i in range(0, 3): socket_client = SocketIO('192.168.43.120', 3000, LoggingNamespace) socket_client.on('/r/home/kitchen', on_subscribe) socket_client.emit('subscribe', 'home/kitchen') # socket_client.wait(seconds=10000000) #socket_client.on_message socket_client.disconnect() p1(i)
def check_pushould(self): socketio = SocketIO(self.pushurl, params={ "transports": ["polling", "websocket"], "client_token": str(self.client_token) }, verify=False) socketio.on('send', self.add_message) socketio.emit("subscribe", {"room": "sadpandapush"}) socketio.wait()
class WebsocketRemoteControl(object): def __init__(self, bot): self.bot = bot self.host, port_str = self.bot.config.websocket_server_url.split(':') self.port = int(port_str) self.sio = SocketIO(self.host, self.port) self.sio.on( 'bot:process_request:{}'.format(self.bot.config.username), self.on_remote_command ) self.thread = threading.Thread(target=self.process_messages) def start(self): self.thread.start() return self def process_messages(self): self.sio.wait() def on_remote_command(self, command): name = command['name'] command_handler = getattr(self, name, None) if not command_handler or not callable(command_handler): self.sio.emit( 'bot:send_reply', { 'response': '', 'command': 'command_not_found', 'account': self.bot.config.username } ) return if 'args' in command: command_handler(*args) return command_handler() def get_player_info(self): request = self.bot.api.create_request() request.get_player() request.get_inventory() response_dict = request.call() inventory = response_dict['responses'].get('GET_INVENTORY', {}) player_info = response_dict['responses'].get('GET_PLAYER', {}) self.sio.emit( 'bot:send_reply', { 'result': {'inventory': inventory, 'player': player_info}, 'command': 'get_player_info', 'account': self.bot.config.username } )
class SocketStream(object): def __init__(self, address, port): # connect to socket self.socket = SocketIO(address, port) def apply(self, func): # trigger events self.socket.on('message', func) # wait forever... self.socket.wait()
class AtlasStream(object): CHANNEL_RESULT = "atlas_result" CHANNEL_PROBE = "atlas_probe" CHANNEL_ERROR = "atlas_error" CHANNELS = {"result": CHANNEL_RESULT, "probe": CHANNEL_PROBE, "error": CHANNEL_ERROR} def __init__(self, **kwargs): """Initialize stream""" self.iosocket_server = "atlas-stream.ripe.net" self.iosocket_resource = "/stream/socket.io" self.socketIO = None def connect(self): """Initiate the channel we want to start streams from.""" self.socketIO = SocketIO( host=self.iosocket_server, port=80, resource=self.iosocket_resource, transports=["websocket"] ) def disconnect(self): """Exits the channel k shuts down connection.""" self.socketIO.disconnect() self.socketIO.__exit__([]) def bind_stream(self, stream_type, callback): """Bind given type stream with the given callback""" try: self.socketIO.on(self.CHANNELS[stream_type], callback) except KeyError: print "The given stream type: <{}> is not valid".format(stream_type) def start_stream(self, stream_type, **stream_parameters): """Starts new stream for given type with given parameters""" if stream_type in ("result", "probestatus"): self.subscribe(stream_type, **stream_parameters) else: print "Given stream type: <%s> is not valid" % stream_type def subscribe(self, stream_type, **parameters): """Subscribe to stream with give parameters.""" parameters.update({"stream_type": stream_type}) self.socketIO.emit("atlas_subscribe", parameters) def timeout(self, seconds=None): """ Times out all streams after n seconds or wait forever if seconds is None """ if seconds is None: self.socketIO.wait() else: self.socketIO.wait(seconds=seconds)
class Connection: def __init__(self, application, server, port): self.application = application self.server = server self.port = port self.connection_opened = False self.trip_started = False self.trip_id = None #self.open_connection() def send_data(self, data): to_send = {'_id':self.trip_id, "sensorData":data} print("tries to send: ",to_send) self.socket.emit('rt-sensordata', json.dumps(to_send)) def open_connection(self): self.socket = SocketIO(self.server, self.port) self.socket.on('server_message', self.on_response) self.connection_opened = True self.thread = threading.Thread(name='connection', target=self.action) self.thread.start() def close_connection(self): self.socket.disconnect() def start_trip(self): data = {'purpose':'realtime-sender', 'groupID':self.application.group_id, 'userID':self.application.user_id} self.socket.emit('start', json.dumps(data)) def stop_trip(self): data = {'_id':self.trip_id, "meta":None} self.socket.emit('endBikeTrip', json.dumps(data)) self.trip_started = False def live_trip_active(self): return self.connection_opened and self.trip_started def on_response(self, *args): parsed = args[0] print "received data:",args[0] if "Connection accepted. Ready to receive realtime data." in parsed: self.trip_started = True self.trip_id = parsed['_id'] print("trip started, id = ", self.trip_id) elif "bikeTrip saved to Database" in parsed: self.trip_started = False print("trip saved to database!") elif "illegal JSON data received" in parsed: print("saving data to database failed") elif u'Welcome' in parsed: print("Welcome! ", parsed) else: print("error: ",parsed) def action(self): while self.socket.connected: self.wait() def wait(self): self.application.send_data() time.sleep(.2) self.socket.wait(.5)
class ServicedShell(object): def __init__(self, logstash): self.logstash = logstash self.socket = None self.jobid = str(uuid4()) def onResult(self, *args): self.logstash.log({ "type": "celerylog", "jobid": self.jobid, "logtype": "exitcode", "exitcode": args[0]['ExitCode'] }) self.socket.disconnect() self.logstash.disconnect() def onStdout(self, *args): for l in args: self.logstash.log({ "type": "celerylog", "jobid": self.jobid, "logtype": "stdout", "stdout": str(l) }) def onStderr(self, *args): for l in args: self.logstash.log({ "type": "celerylog", "jobid": self.jobid, "logtype": "stderr", "stderr": str(l) }) def run(self, service_id, command): self.logstash.log({ "type": "celerylog", "jobid": self.jobid, "logtype": "command", "command": command, "service_id": service_id, }) self.socket = SocketIO(ELASTIC_HOST, 50000) self.socket.on('result', self.onResult) self.socket.on('stdout', self.onStdout) self.socket.on('stderr', self.onStderr) self.socket.emit( 'process', { 'Command': command, 'IsTTY': False, 'ServiceID': service_id, 'Envv': [] }) self.socket.wait()
class CsSocket: def __init__(self, port): #initialization self.port = port # Socket.io port self.socketIO = SocketIO('localhost', port) # connect to localhost self.socketIO.wait(seconds = 1) # check every second self.socketIO.on("connect", on_connect_function) # on connect event function def parse(self, str): arg_arr = str.split(" ") # split at spaces if arg_arr[0] == "sco" and len(arg_arr) > 0: # check for proper score event self.socketIO.emit(arg_arr[0], str[4:]) # send score event
def create_sockets(server, port, n): sockets = [] for i in range(0, n): socket = SocketIO(server, port) socket.on('result', print_result(i)) socket.on('server_error', print_server_error(i)) sockets.append(socket) return sockets
class Device: def __init__(self,name): self.status = "off" self.socketIO = SocketIO('localhost',3001) self.socketIO.emit('sendName',{'sendName':name}) self.name = '' self.socketIO.on('recName',self.setName) self.socketIO.wait(seconds=1) def setName(self,*recName): print recName self.name = recName[0]['name'] print self.name
def run(self): try: def onMessage(*args): print "msg->", args socketIO = SocketIO(self.host, self.port) socketIO.on(self.onMsg, onMessage); socketIO.wait(seconds=self.waitFor) self.completed = True except Exception, error: self.completed = False
class WebsocketRemoteControl(object): def __init__(self, bot): self.bot = bot self.host, port_str = self.bot.config.websocket_server_url.split(':') self.port = int(port_str) self.sio = SocketIO(self.host, self.port) self.sio.on( 'bot:process_request:{}'.format(self.bot.config.username), self.on_remote_command ) self.thread = threading.Thread(target=self.process_messages) self.logger = logging.getLogger(type(self).__name__) def start(self): self.thread.start() return self def process_messages(self): self.sio.wait() def on_remote_command(self, command): name = command['name'] command_handler = getattr(self, name, None) if not command_handler or not callable(command_handler): self.sio.emit( 'bot:send_reply', { 'response': '', 'command': 'command_not_found', 'account': self.bot.config.username } ) return if 'args' in command: command_handler(*args) return command_handler() def get_player_info(self): try: self.sio.emit( 'bot:send_reply', { 'result': {'inventory': inventory.jsonify_inventory(), 'player': self.bot._player}, 'command': 'get_player_info', 'account': self.bot.config.username } ) except Exception as e: self.logger.error(e)
def handle(self, *args, **options): from ripe.atlas.sagan import PingResult from simon_app.api_views import getCountryFromIpAddress msm=args[0] def atlas_result(*args): my_result = PingResult(args[0]) try: packet_loss = my_result.packets_sent - my_result.packets_received except: packet_loss = 0 try: res = RipeAtlasPingResult( probe_id=my_result.probe_id, measurement_id=my_result.measurement_id, ip_destination=my_result.destination_address, ip_origin=my_result.origin, country_destination=getCountryFromIpAddress(my_result.destination_address), country_origin=getCountryFromIpAddress(my_result.origin), ip_version=my_result.af, testype='icmp', min_rtt=my_result.rtt_min, max_rtt=my_result.rtt_max, ave_rtt=my_result.rtt_average, median_rtt=my_result.rtt_median, number_probes=my_result.packets_sent, packet_loss=packet_loss ) if res.is_valid(): print res res.save() except Exception as e: print e from socketIO_client import SocketIO # print "Subscribing to RIPE Atlas measurement ID: %s" % msm socketIO = SocketIO('https://atlas-stream.ripe.net/stream/socket.io', 443) socketIO.on("atlas_result", atlas_result) socketIO.emit("atlas_subscribe", {'stream_type': 'result', 'msm': msm}) socketIO.wait()