Exemple #1
0
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
Exemple #2
0
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"
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)
Exemple #4
0
        def waiter(username, password, usertype, session_key):
            ioplugin = SocketIO(self.host, self.port)

            def on_identify(message):
                if not 'ID' in message:
                    obj = {
                        'username': username,
                        'password': password,
                        'usertype': usertype,
                        'django_id': session_key
                    }
                    ioplugin.emit('login', obj)
                else:
                    self.do_event(ioplugin)
                # end if
            # end def

            def on_error_login():
                print "Errror ", username, password, usertype, session_key
            # end def

            def on_success_login():
                self.do_event(ioplugin)
            # end def

            ioplugin.on('identify', on_identify)
            ioplugin.on('error-login', on_error_login)
            ioplugin.on('success-login', on_success_login)
            ioplugin.emit('identify', {'django_id': session_key, 'usertype': usertype})
            ioplugin.wait(seconds=1)
Exemple #5
0
class SocketIOHandler(object):

    def __init__(self, cfg):
        """
        save the server config..
        """
        self.server_address = cfg['graphite_ip']
        self.server_port = cfg['graphite_port']
        self.namespace = cfg['graphite_namespace']
        self.socketIO = None
        self.channel = None

    def handle(self, non_metrics):
        if len(non_metrics) == 0:
            logging.debug('No metrics be handled!')
            return

        nm_list = []
        for nm in non_metrics:
            nm_list.append(dumps(nm.to_dict()))  # serialized to json
        msg_type = non_metrics[0].type
        self.socketIO = SocketIO(self.server_address, self.server_port, BaseNamespace)
        self.channel = self.socketIO.connect(self.namespace, BaseNamespace)
        self.channel.emit(msg_type, nm_list, self.on_response)  # send to server
        self.socketIO.wait(forCallbacks=True)
        logging.debug('SokcetIOHandler emitting %s to sever:\n %s' % (msg_type, dumps(nm_list)))

    def on_response(self, *args):
        # is it necessary?
        self.socketIO.disconnect()
        logging.debug('emit non metrics success!')
Exemple #6
0
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)
Exemple #7
0
 def run(self, args):
     print('Listening to %s' % args.relay_url)
     try:
         worker = Worker(args.server_url, args.queue_token)
         worker.work()
         Namespace.channel = 'q/' + args.queue_token
         Namespace.worker = worker
         socket = SocketIO(
             args.relay_url, Namespace=Namespace, wait_for_connection=False)
         socket.wait()
     except ServerConnectionError:
         print_error('The server is down. Try again later.')
     except RelayConnectionError:
         print_error('The relay is down. Try again later.')
     except HTTPBadRequest:
         print_error(
             'There was an error processing your request.\n'
             '- Check that the server URL is correct (--server_url).\n'
             '- Upgrade the framework (pip install -U crosscompute).')
     except HTTPUnauthorized:
         print_error(
             'The server rejected the token. '
             'Make sure your token is valid.')
     except KeyboardInterrupt:
         pass
Exemple #8
0
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()
Exemple #9
0
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()
Exemple #10
0
class Socket(threading.Thread):
    def __init__(self, url):
        threading.Thread.__init__(self)
        self.url = url
        self.isConnect = False
        # self.socketIO = None
        self.socketIO = SocketIO(self.url, 3000, LoggingNamespace)
        self.start()

    def listen(self):
        self.socketIO.on("connect", self.on_connect)
        self.socketIO.on('disconnect', self.on_disconnect)
        self.socketIO.on('reconnect', self.on_reconnect)

    def run(self):
        print('[GROBOT] connecting http://localhost:3000')
        # self.socketIO = SocketIO(self.url, 3000, LoggingNamespace)
        self.listen()
        while True:
            self.socketIO.wait(seconds=1)

    def on_connect(self):
        self.isConnect = True
        print("[GROBOT] http://localhost:3000 CONNECTED ")

    def on_disconnect(self):
        self.isConnect = False
        print("[GROBOT] DISCONNECTED")

    def on_reconnect(self):
        print("[GROBOT] CONNECTED")
Exemple #11
0
    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."
            )
Exemple #12
0
 def test_emit_with_callback(self):
     global ON_RESPONSE_CALLED
     ON_RESPONSE_CALLED = False
     socketIO = SocketIO('localhost', 8000)
     socketIO.emit('aaa', PAYLOAD, on_response)
     socketIO.wait(forCallbacks=True)
     self.assertEqual(ON_RESPONSE_CALLED, True)
Exemple #13
0
 def test_emit_with_callback(self):
     global ON_RESPONSE_CALLED
     ON_RESPONSE_CALLED = False
     socketIO = SocketIO('localhost', 8000)
     socketIO.emit('aaa', PAYLOAD, on_response)
     socketIO.wait(forCallbacks=True)
     self.assertEqual(ON_RESPONSE_CALLED, True)
Exemple #14
0
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)
Exemple #15
0
def init_socket(host, port, electionID):
    socketio = SocketIO(host, port)
    socketio.on('SyncBulletinBoard', updateData)
    socketio.on('syncElectionAdministrator', updateData)
    socketio.on('syncElectionAuthorities', addEBold)
    socketio.emit('requestFullSync', {'election': electionID})
    socketio.wait(seconds=2)
Exemple #16
0
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()
Exemple #17
0
 def start(self):
     io = SocketIO('http://' + host,
                   port=socketIOPort,
                   params={'token': token})  # create connection with params
     io.on(EVENT_TICK, self.onEventTick)
     io.on(EVENT_TICKS_CHANGED, self.onEventTicksChanged)
     io.on(EVENT_TICKS, self.onEventTicks)
     io.on(EVENT_TRADE, self.onEventTrade)
     io.on(EVENT_TRADES, self.onEventTrades)
     io.on(EVENT_ORDER, self.onEventOrder)
     io.on(EVENT_ORDERS, self.onEventOrders)
     io.on(EVENT_POSITION, self.onEventPosition)
     io.on(EVENT_POSITIONS, self.onEventPositions)
     io.on(EVENT_ACCOUNT, self.onEventAccount)
     io.on(EVENT_ACCOUNTS, self.onEventAccounts)
     io.on(EVENT_CONTRACT, self.onEventContract)
     io.on(EVENT_CONTRACTS, self.onEventContracts)
     io.on(EVENT_ERROR, self.onEventError)
     io.on(EVENT_ERRORS, self.onEventErrors)
     io.on(EVENT_GATEWAY, self.onEventGateway)
     io.on(EVENT_GATEWAYS, self.onEventGateways)
     io.on(EVENT_LOG, self.onEventLog)
     io.on(EVENT_LOGS, self.onEventLogs)
     io.on(EVENT_THREAD_STOP, self.onEventThreadStop)
     io.wait()
Exemple #18
0
class Client1(object):
    def __init__(self, server_host, server_port):
        self.sio = SocketIO(server_host, server_port)
        self.register_handles()
        print("启动客户端Client1(sent wakeup)")
        self.sio.emit('client_ready')
        self.sio.wait()
        self.blindness
        self.req_num = 1

    def register_handles(self):
        def req_train():
            # self.req_num = self.req_num+1
            print('继续请求第' + '次更新:')
            self.sio.emit('client_ready')

        def on_connect():
            print('connect')

        def on_disconnect():
            print('disconnect')

        def on_reconnect():
            print('reconnect')

        def on_blind(*args):
            req = args[0]
            self.blindness = req['blind']
            print('blind=', self.blindness)
            self.sio._close()

        self.sio.on('connect', on_connect)
        self.sio.on('disconnect', on_disconnect)
        self.sio.on('reconnect', on_reconnect)
        self.sio.on('blind', on_blind)
Exemple #19
0
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)
Exemple #20
0
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 g_socketIO, g_start_time, g_objects_lock
    g_objects_lock = threading.Lock()

    if (len(sys.argv) < 2):
        print "Usage:", sys.argv[
            0], " {S|L|SL} (S=speaking, L=listening) - defaults to SL"
    if (len(sys.argv) == 1):
        sys.argv.append("SL")  # Default arguments

    print "Listening to " + HOST + ":" + str(PORT)

    g_socketIO = SocketIO(HOST, PORT, Namespace)

    print "Emitting adduser"
    g_socketIO.emit("adduser", socket.getfqdn() + ";" + str(os.getpid()))

    g_start_time = time.time()
    if ("S" in sys.argv[1]):
        print "Starting speaking"
        thread1 = threading.Thread(target=heartbeat_thread)
        thread1.daemon = True
        thread1.start()
    if ("L" in sys.argv[1]):
        print "Starting listening"
        g_socketIO.wait()
    else:
        time.sleep(60 * 60 * 24 * 365 * 100)
def send(lines):
    print(lines)

    data = []

    for line in lines:
        if line == "\n":
            pass
        else:
            print(line)

            frame = line.strip()[2:-3].split(', ')
            freqandtime = frame[1].split('\\')[0]
            freq, time = freqandtime[1:].split('%')
            mac = frame[0]

            if not data:
                data = [mac, freq, time]
            elif float(data[2]) <= float(time):
                print("HERE")
                data = [mac, freq, time]

    print("Outputting: " + str(data[1]))
    sleep(4)
    socketIO = SocketIO('127.0.0.1', 5000)
    socketIO.emit('alfred set freq', str(data[1]))
    socketIO.wait(1)
Exemple #23
0
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")
Exemple #24
0
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(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()
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()
class SocketProxy(object):
    def __init__(self, id, host, port):
        self.client = SocketIO(host, port, BaseNamespace)
        self.client.on('log', self.on_log)
        self.client.on('end', self.on_end)
        self.client.on('playbook-start', self.on_playbook_start)
        self.client.on('playbook-stop', self.on_playbook_stop)
        self.client.on('playbook-error', self.on_playbook_error)
        self.client.emit('join', id)

    def on_log(self, message):
        emit("log", message)

    def on_end(self, message):
        emit("end")
        self.client.disconnect()

    def on_playbook_start(self, playbook):
        emit("playbook-start", playbook)

    def on_playbook_stop(self, playbook):
        emit("playbook-stop", playbook)

    def on_playbook_error(self, playbook):
        emit("playbook-error", playbook)

    def wait(self):
        self.client.wait()  # seconds=5)
        # Hack! _close is needed to *really* close the connection
        self.client._close()
Exemple #28
0
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)
Exemple #29
0
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)
Exemple #30
0
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)
Exemple #31
0
 def run(self, args):
     print('Listening to %s' % args.relay_url)
     try:
         worker = Worker(args.server_url, args.queue_token)
         worker.work()
         Namespace.channel = 'q/' + args.queue_token
         Namespace.worker = worker
         socket = SocketIO(args.relay_url,
                           Namespace=Namespace,
                           wait_for_connection=False)
         socket.wait()
     except ServerConnectionError:
         print_error('The server is down. Try again later.')
     except RelayConnectionError:
         print_error('The relay is down. Try again later.')
     except HTTPBadRequest:
         print_error(
             'There was an error processing your request.\n'
             '- Check that the server URL is correct (--server_url).\n'
             '- Upgrade the framework (pip install -U crosscompute).')
     except HTTPUnauthorized:
         print_error('The server rejected the token. '
                     'Make sure your token is valid.')
     except KeyboardInterrupt:
         pass
class Command(BaseCommand):
    args = '<hostname> <public port> <runserver port> <socket port>'
    help = 'Listens over socket.io websocket'

    def handle(self, *args, **options):
        if len(args) != 4:
            raise Exception("Arguments needed: %s" % self.args)

        # parse arguments
        runserver_host = "%s:%s" % (args[0], args[2])
        runserver_cmd = "python manage.py runserver %s" % runserver_host
        nodejs_cmd = "node %s %s %s %s" % (nodjango_indexjs, args[1], args[2], args[3])

        try:
            # start nodejs proxy
            proc2 = Popen(nodejs_cmd, shell=True, preexec_fn=os.setsid, stdout=sys.stdout, stderr=sys.stderr)

            # start django runserver
            proc1 = Popen(runserver_cmd, shell=True, preexec_fn=os.setsid, stdout=sys.stdout, stderr=sys.stderr)

            time.sleep(2)

            # start django private socketio
            self.socket = SocketIO('127.0.0.1', int(args[3]), Namespace=DjangoNamespace)
            print '* * *\t django socket started'
            self.socket.wait()

        finally:
            print 'killing...'
            os.killpg(proc1.pid, signal.SIGTERM)
            os.killpg(proc2.pid, signal.SIGTERM)
            print 'killed!'
	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)
Exemple #34
0
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)
Exemple #35
0
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()
Exemple #36
0
        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 intent_received(hermes, intentMessage):
    sentence = 'You asked for '

    if intent_message.intent.intent_name == 'onOffIntent':
        print('searchWeatherForecast')
    else:
        return

    device = intentMessage.slots.device.first().value
    state = intentMessage.slots.state.first().value

    if len(intentMessage.slots.room) > 0:
        room = intentMessage.slots.room.first().value

    if len(intentMessage.slots.location) > 0:
        location = intentMessage.slots.location.first().value

        for i, c in enumerate(location):
            if c.isupper():
                print i
                locationObject = location[i:len(location)]
                print locationObject
                break

    result_sentence = "Schalte {0} {1}".format(str(device), str(state))

    #socket.io
    socketIO = SocketIO('192.168.2.121', 3000)
    socketIO.emit('snips')
    socketIO.wait(seconds=1)

    #tts + end_session
    current_session_id = intentMessage.session_id
    hermes.publish_end_session(current_session_id, result_sentence)
def send (lines):
	print(lines)
	
	data = []
	
	for line in lines:
		if line == "\n":
			pass
		else:
			print (line)

			frame = line.strip()[2:-3].split(', ')
			freqandtime = frame[1].split('\\')[0]
			freq,time = freqandtime[1:].split('%')
			mac = frame[0]

			if not data:
				data = [mac,freq,time]
			elif float(data[2]) <= float(time):
				print("HERE")
				data = [mac,freq,time]

	print ("Outputting: " + str(data[1]))
	sleep(4)
	socketIO = SocketIO('127.0.0.1', 5000)
	socketIO.emit('alfred set freq', str(data[1]))
	socketIO.wait(1)
Exemple #39
0
 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)
Exemple #40
0
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")
Exemple #41
0
        def waiter(username, password, usertype, session_key):
            ioplugin = SocketIO(self.host, self.port)

            def on_identify(message):
                if not 'ID' in message:
                    obj = {
                        'username': username, 
                        'password': password,
                        'usertype': usertype, 
                        'django_id': session_key
                    }
                    ioplugin.emit('login', obj)
                else:
                    self.do_event(ioplugin)
                # end if
            # end def

            def on_error_login():
                raise "Error"
            # end def
            def on_success_login():
                self.do_event(ioplugin)
            # end def

            ioplugin.on('identify', on_identify)
            ioplugin.on('error-login', on_error_login)
            ioplugin.on('success-login', on_success_login)
            ioplugin.emit('identify', {'django_id': session_key, 'usertype': usertype})
            ioplugin.wait(seconds=1)
Exemple #42
0
def socketio_start_listening(cookies):
    socketio = SocketIO(SOCKETIO_HOST,
                        SOCKETIO_PORT,
                        SocketioNamespace,
                        cookies=cookies)
    socketio.wait(seconds=60)
    socketio_start_listening(cookies)
Exemple #43
0
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
def main():
    global g_socketIO,g_start_time,g_objects_lock
    g_objects_lock = threading.Lock()

    if(len(sys.argv)<2):
        print "Usage:",sys.argv[0]," {S|L|SL} (S=speaking, L=listening) - defaults to SL"
    if(len(sys.argv)==1):
        sys.argv.append("SL")	# Default arguments

    print "Listening to "+HOST+":"+str(PORT)

    g_socketIO = SocketIO(HOST, PORT, Namespace)

    print "Emitting adduser"
    g_socketIO.emit("adduser",socket.getfqdn()+";"+str(os.getpid()))

    g_start_time = time.time()
    if("S" in sys.argv[1]):
        print "Starting speaking"
        thread1 = threading.Thread(target=heartbeat_thread)
        thread1.daemon = True
        thread1.start()
    if("L" in sys.argv[1]):
        print "Starting listening"
        g_socketIO.wait()
    else:
        time.sleep(60*60*24*365*100)
Exemple #45
0
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)
Exemple #46
0
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 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}
        )
Exemple #48
0
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))
Exemple #49
0
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()
Exemple #50
0
 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 play(handler):
    token = raw_input('Enter your token: ')
    global play_reversi
    play_reversi = handler
    # Use socketio with defined Namespace
    socketIO = SocketIO('localhost', 8100, ReversiNamespace, params={'token': token})

    socketIO.wait()
Exemple #52
0
 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()
Exemple #53
0
 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()
Exemple #54
0
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 ices_get_next():
    global io, file, HOST, PORT, STATION, TOKEN
    io = SocketIO(HOST, PORT, Namespace)
    io.emit('next', { 'station': STATION, 'token': TOKEN })
    io.wait(seconds=1)
    io.disconnect()
    path = file.encode('utf8') # Path to audio file, must be of 'str' type (not 'unicode'), e.g. "/music/Beatles - Yesterday.mp3"
    file = '' # Clear so it wont repeat in case the 'next' callback timeouts
    return path
Exemple #56
0
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 ices_init():
    global io, alive, HOST, PORT, STATION, TOKEN
    io = SocketIO(HOST, PORT, Namespace)
    io.emit('alive', { 'station': STATION, 'token': TOKEN })
    io.wait(seconds=1)
    io.disconnect()
    if alive:
        return 1 # Succees
    else:
        return 0 # Failure
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)
Exemple #59
0
def run_socketio(args):
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    res = opener.open("http://%s:%s/p/%s" % (args.host, args.port, args.pad))

    session = res.headers['set-cookie']

    socketIO = SocketIO(args.host, args.port, EtherpadService,
                                                        session=session,
                                                        padid=args.pad)
    socketIO.wait()