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)
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 #3
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 #4
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"
Exemple #5
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()
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 #7
0
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
Exemple #8
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)
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 #10
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)
	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 #12
0
def main():
    logging.basicConfig(filename=settings.WEBSOCKET_CLIENT['logfile'],
                        level=logging.DEBUG)
    logging.debug('Started logging')
    num_samples = 120;
    socketIO = SocketIO('localhost', settings.NGINX_WEBSOCKET_PORT, secure=True)
    max_ts = None
    prev_cpu_data = [];
    # TODO handle multiple cpus
    for i in range(num_samples):
        prev_cpu_data.append({u'umode': 0, u'umode_nice': 0, u'smode': 0, u'idle': 0, u'ts': None})

    while True:
        # read from db
        auth_params = {'apikey': 'adminapikey'}

        # Get cpu metrics
        r = requests.get('https://localhost/api/sm/cpumetric/?format=json', verify=False, params = auth_params)
        cpu_data = r.json()
        tmp = []
        # find max timestamp
        if (len(cpu_data) < num_samples):
            for i in range(num_samples - len(cpu_data)):
                tmp.append({u'umode': 0, u'umode_nice': 0, u'smode': 0, u'idle': 0, u'ts': None})
            tmp.extend(cpu_data)
            cpu_data = tmp

        cpu_util = [];
        for i in range(num_samples):
            cpu_util.append({
                'umode': cpu_data[i][u'umode'] - prev_cpu_data[i][u'umode'],
                'umode_nice': cpu_data[i][u'umode_nice'] - prev_cpu_data[i][u'umode_nice'],
                'smode': cpu_data[i][u'smode'] - prev_cpu_data[i][u'smode'],
                'idle': cpu_data[i][u'idle'] - prev_cpu_data[i][u'idle']
                })


        # send to websocket
        new_cpu_data = False
        if cpu_data[num_samples-1][u'ts'] != prev_cpu_data[num_samples-1][u'ts']:
            new_cpu_data = True
        prev_cpu_data = cpu_data

        msg = {}
        if new_cpu_data:
            msg['cpu_util'] = cpu_util

        # Get loadavg metrics
        r = requests.get('https://localhost/api/sm/loadavg/?format=json', verify=False, params = auth_params)
        load_data = r.json()
        msg['load_avg'] = load_data

        if (r.status_code != 200):
            socketIO.emit('sm_data_update', {'msg': json.dumps(msg)}, on_response)
        else:
            logging.debug('invalid CPU data - JSON data invalid')

        # Sleep before getting the next set of data
        time.sleep(5)
Exemple #13
0
 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)
Exemple #14
0
def on_disconnect():
    ## try create new connect
    socketIO = SocketIO('http://demo.ilyra.vn', 1337, params=query)
    socketIO.on('connect', on_connect)
    socketIO.on('disconnect', on_disconnect)
    socketIO.on('reconnect', on_reconnect)
    socketIO.emit("get", emit_data)
    socketIO.on('command', on_aaa_response)
Exemple #15
0
 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)
Exemple #16
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()
Exemple #17
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 #18
0
 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)
Exemple #19
0
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 ClientSocketIO:
    def __init__(self, host, port, lamp_code):
        self.host = host
        self.port = port
        self.lamp_code = lamp_code
        self.socket_client = None

    def connect(self):
        if self.socket_client is None:
            self.socket_client = SocketIO(
                self.host,
                self.port,
                LoggingNamespace,
                params={'code': self.lamp_code},
            )
            self.socket_client.on('connect', self.on_connect)
            self.socket_client.on('disconnect', self.on_disconnect)
            self.socket_client.on('reconnect', self.on_reconnect)
            self.socket_client.on('message', self.on_message_response)
            self.socket_client.on('close', self.close)

    def close(self):
        self.socket_client.disconnect()

    def on_connect(self):
        print('Connected to host = ' + self.host + ' port = ' + str(self.port))

    def on_disconnect(self):
        print('disconnect to host = ' + self.host + ' port = ' +
              str(self.port))

    def on_reconnect(self):
        print('reconnect to host = ' + self.host + ' port = ' + str(self.port))

    def add_new_event(self, event, callback):
        self.socket_client.on(event, callback)

    def on_message_response(self, *args):
        for item in args:
            print('message response', item)

    def on_value_response(self, value):
        print('Value = ', value)

    def on_color_response(self, color):
        print('Color = ', color)

    def emit(self, message):
        if self.socket_client is not None:
            print('Sending message: ', message)
            self.socket_client.emit('message', message)

    def emit_close(self):
        if self.socket_client is not None:
            self.socket_client.emit('close', True)

    def wait(self):
        self.socket_client.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
Exemple #22
0
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()
Exemple #23
0
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 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
 def __init__(self, token):
     self.time = time.time()
     self.token = token
     socketIO = SocketIO('10.132.0.2', 5001)
     msg = input('Insira a mensagem a difundir pelo bot:\n> ')
     while True:
         time.sleep(5)
         socketIO.emit('bot_alert', {'building': self.token, 'value': msg})
         print(self.token)
Exemple #26
0
 def createSocket(self,port):
   #Create client socket 
   socket = SocketIO('localhost', port)

   #Use room name rpsock to join
   #Server can use this to send targetted messages
   socket.emit('join',{'socketid':'rpsock'})

   return socket
class PublishMediaFrameworkMessages:
    def on_auth_r(self, *args):
        print('on_auth_r', args)

    def __init__(self):
        self.socketio = SocketIO(media_hub_url, 80, LoggingNamespace)
        self.socketio.emit('auth', {'password': '******'}, self.on_auth_r)

        self.receive_events_thread = Thread(target=self._receive_events_thread)
        self.receive_events_thread.daemon = True
        self.receive_events_thread.start()

    def _receive_events_thread(self):
        self.socketio.wait()

    def publish(self):
        self.socketio.emit('sendCommand', 'electret', 'showScenesAndThemes', score)


#
# def on_auth_r(*args):
#     print('on_auth_r', args)
#
#
# def on_connect():
#     print('connect')
#
#
# def on_disconnect():
#     print('disconnect')
#
#
# def on_reconnect():
#     print('reconnect')
#
#
# def on_show_scenes_and_themes(*args):
#     print('on_show_scenes_and_themes', args)
#
#
# socketIO = SocketIO(media_hub_url, 80, LoggingNamespace)
#
# # APEP authenticate with web sockets
# socketIO.emit('auth', {'password': '******'}, on_auth_r)
# socketIO.wait_for_callbacks(seconds=10)
#
# socketIO.on('connect', on_connect)
# socketIO.on('disconnect', on_disconnect)
# socketIO.on('reconnect', on_reconnect)
#
# # socketIO.emit('sendCommand', data=('electret', 'showScenesAndThemes', score))
# socketIO.emit('sendCommand', 'electret', 'showScenesAndThemes', score)
#
# # electret_namespace.emit('sendCommand', payload, on_show_scenes_and_themes)
#
# socketIO.wait()
Exemple #28
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()
Exemple #29
0
 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)
Exemple #30
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()
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 ControlServerInbound(threading.Thread):
    
    def __init__(self, controlQueue, shutdownEvent, eventWaiting, serverURL, robotID, *args, **kwargs):
        self.logger = logging.getLogger(__name__)
        self.logger.addHandler(logging.NullHandler())
        self.serverURL = serverURL
        self.robotID = robotID
        self.controlQueue = controlQueue
        self.shutdownEvent = shutdownEvent
        self.eventWaiting = eventWaiting
        self.controlHostPort = None
        self.commandSocket = None
        self.disconnected = True
        super(ControlServerInbound, self).__init__(*args, **kwargs)
    
    def run(self):
        while not self.shutdownEvent.is_set(): #Retry every time the server fails to connect
            self.__controlServerSetup()
            self.__listenAndWait()
    
    def __getControlHostPort(self):
        url = 'https://{}/get_control_host_port/{}'.format(self.serverURL, self.robotID)
        self.logger.debug("Getting control host port from url: %s" % (url))
        response = ServerHelper.getWithRetry(url)
        self.controlHostPort = json.loads(response)
    
    def __controlServerSetup(self):
        self.__getControlHostPort()
        self.logger.debug("Connecting to control socket.io port: {}".format(self.controlHostPort))
        self.commandSocket = SocketIO(self.controlHostPort['host'], self.controlHostPort['port'], LoggingNamespace)
        self.logger.debug("Finished using socket io to connect to control host port: {}".format(self.controlHostPort))
        
        self.commandSocket.on('command_to_robot', self._handleCommand)
        self.commandSocket.on('disconnect', self._handleCommandDisconnect)
        self.commandSocket.on('connect', self._sendRobotID)
        self.commandSocket.on('reconnect', self._sendRobotID)
        self.disconnected = False
    
    def __listenAndWait(self):
        while(not self.shutdownEvent.is_set() and (self.disconnected == False)):
            self.commandSocket.wait(seconds=1)
                
    def _handleCommandDisconnect(self):
        self.logger.debug("Command Socket Disconnected")
        self.disconnected = True
    
    def _sendRobotID(self):
        self.commandSocket.emit('identify_robot_id', self.robotID)
        self.commandSocket.emit('libVer', {'library' : 'letsrobot_unofficial', 'version' : '0.0.1'})
    
    def _handleCommand(self, *args):
        #Send it upstream and notify the main thread there is work to do
        self.logger.debug("Received Command: {} from: {}".format(args[0]['command'],args[0]['user']))
        self.controlQueue.put(*args)
        self.eventWaiting.set()
Exemple #33
0
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 add_match(match):
    if _log_matches:
        with open("match.log", "a") as log_file:
            log_line = '{:%Y-%m-%d %H:%M:%S} {}\n'.format(datetime.now(), match.match_data_for_log())
            log_file.write(log_line)
    socketIO = SocketIO(config['url'], verify=False)
    socketIO.on('ackMatch', on_ack_match)
    socketIO.on('error', on_error)
    socketIO.on('refreshedData', on_refreshed_data)
    socketIO.emit('addMatch', match.get_match_data())
    socketIO.wait(seconds=5)
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)
Exemple #36
0
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
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 TagoRealTime:
    def __init__(self, address, token, callback):
        self.socket = SocketIO(address, 443, LoggingNamespace)
        self.token = token
        self.callback = callback

    def on_connect(self):
        self.socket.emit('register', self.token)

    def on_data(self, data):
        self.callback(data)
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 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()
Exemple #41
0
def main(e):
  if(len(sys.argv) > 1): #in seconds
    delay = getDelay(sys.argv[1])

  socketIO = SocketIO(HOST, PORT)
  while(True):
    print("here")
    xChange, yChange, zChange = e.calculate_attitude()
    solarPower = getSolarPower(xChange, yChange, zChange)
    socketIO.emit('fromIMU', {'x':xChange, 'y':yChange, 'z':zChange, 'solar':solarpower})
    time.sleep(delay)
Exemple #42
0
class mdsVolumio2(mds.mds):
    def establishConnection(self):

        for i in range(self.retriesAllowed):
            self.socketIO = None
            try:
                self.socketIO = SocketIO(self.playerComms.ipaddr,
                                         self.playerComms.port)

                self.socketIO.on('pushQueue', self.pushQueue)
                self.socketIO.on('pushState', self.pushState)

                #				self.socketIO.on(u'pushState', self.on_state_response)
                #				self.socketIO.on(u'pushQueue', self.on_queue_response)

                # Request initial values
                self.socketIO.emit(u'getQueue')
                self.socketIO.emit(u'getState')
                return
            except Exception as ex:
                del (self.socketIO)
                logger.exception('Error connecting on attempt {0}'.format(i +
                                                                          1))
                time.sleep(0.5)
                pass
        raise RuntimeError('Unable to connect')

    def shutdownConnection(self):
        if self.socketIO:
            del (self.socketIO)
        pass

    def listen(self):
        logger.debug('LISTENING')
        self.socketIO.wait(seconds=10)
        self.socketIO.emit(u'getQueue')
        self.socketIO.emit(u'getState')
        return True

    def pushQueue(self, *args):
        list = args[0]
        with self.lMDS:
            self.playerState['queue'] = list
        self.sendUpdate()

    def pushState(self, *args):
        # Read musicplayer status and update musicdata

        status = args[0]
        with self.lMDS:
            for k, v in status.iteritems():
                self.playerState[k] = v
        self.sendUpdate()
Exemple #43
0
    def remote(self, url, subscriptions):
        try:
            url, port = url.rsplit(':', 1)
        except ValueError:
            port = 80

        socket = SocketIO(url, int(port), RemoteNamespace)

        for selector in subscriptions:
            socket.emit('subscribe', selector)

        self.remotes.push(socket)
Exemple #44
0
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
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)
Exemple #46
0
def manage(socketio_handler):
    socketIO = SocketIO('http://localhost:5000', Namespace=MasterNamespace)
    #socketIO = SocketIO('https://autobotcloud.com', Namespace=MasterNamespace)
    namespace = socketIO.get_namespace()
    socketIO.on('connect', connected)
    socketIO.on('disconnect', disconnected)
    namespace.master = Master()
    socketio_handler.ws = socketIO  #trial code to hand over this instance of socketio to logging
    socketIO.emit('ready')
    logger.info("emitted ready")
    socketIO.emit('getbots')
    logger.info("emitted get bots")
    socketIO.wait()
Exemple #47
0
    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()
class ServicedShell(object):
    def __init__(self, serviceId=None, poolId='default', doPrint=False):
        self.socket = None
        if not serviceId:
            # Sample output for command: pgrep -flao "serviced proxy"
            # 1 /serviced/serviced proxy 0cce2766-0b89-6cb6-c883-1ae8b564cbbe su - zenoss -c "CONTROLPLANE_SYSTEM_USER=${CONTROLPLANE_SYSTEM_USER} CONTROLPLANE_SYSTEM_PASSWORD=${CONTROLPLANE_SYSTEM_PASSWORD} /opt/zenoss/bin/zopectl fg"
            process = subprocess.Popen('pgrep -flao "serviced proxy"', shell=True, stdout=subprocess.PIPE)
            serviceId = process.communicate()[0].split()[3]
        self.serviceId = serviceId
        self.poolId = poolId
        self.stdout = []
        self.stderr = []
        self.result = None
        self.doPrint = doPrint

    def onResult(self, *args):
        self.socket.disconnect()
        self.result = args[0]

    def onStdout(self, *args):
        ascii = "".join(map(chr, args))
        self.stdout.extend(ascii)
        if self.doPrint:
            sys.stdout.write("%s" % ascii)
            sys.stdout.flush()

    def onStderr(self, *args):
        ascii = "".join(map(chr, args))
        self.stderr.extend(ascii)
        if self.doPrint:
            sys.stderr.write("%s" % ascii)
            sys.stderr.flush()

    def run(self, command):
        self.socket = SocketIO(SERVICED_HOST, SERVICED_SHELL_PORT)
        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': self.serviceId, 'PoolId': self.poolId, 'Envv': []})
        self.socket.wait()

        if self.result['Termination'] != 0:
            raise ServicedShellError(self.result['Error'])

        result = {} 
        result['exitcode'] = self.result['ExitCode']
        result['service'] = self.serviceId
        result['pool'] = self.poolId
        result['stdout'] = self.stdout
        result['stderr'] = self.stderr
        return result
Exemple #49
0
class VolumioClient(object):
    def __init__(self, host="localhost", port=3000):
        self._host = host
        self._port = port
        self._status = ''
        self._title = ''
        self._artist = ''
        self._socketio = ''
        self._status_change_callback = ''
        self._title_change_callback = ''
        self._artist_change_callback = ''

    def on_status_change(self, callback):
        self._status_change_callback = callback

    def on_title_change(self, callback):
        self._title_change_callback = callback

    def on_artist_change(self, callback):
        self._artist_change_callback = callback

    # Callback function as response on 'getState', used to retrieve status, title, artist
    def on_push_state(self, *args):
        #    print('getstate', args)
        new_status = args[0]['status']
        if new_status != self._status:
            if self._status_change_callback:
                self._status_change_callback(new_status)
            self._status = new_status
        new_title = args[0]['title']
        if new_title != self._title:
            if self._title_change_callback:
                self._title_change_callback(new_title)
            self._title = new_title
        new_artist = args[0]['artist']
        if new_artist != self._artist:
            if self._artist_change_callback:
                self._artist_change_callback(new_artist)
            self._artist = new_artist

    def connect(self):
        self._socketio = SocketIO(self._host, self._port, LoggingNamespace)

        # getState response handler
        self._socketio.on('pushState', self.on_push_state)
        # getState command
        self._socketio.emit('getState')

    def wait(self):
        self._socketio.wait()
Exemple #50
0
class socketController:
    def __init__(self, address, port):
        self.socket = SocketIO(address, port, LoggingNamespace)
        self.socket.on('connect', self.onConnect)
        self.socket.on('disconnect', self.onDisconnect)

    def onConnect(self):
        print("connected to socket")

    def onDisconnect(self):
        print("Disconnected to socket")

    def sendData(self, event, data):
        self.socket.emit(event, data)
def main():
    # generate the client name. If none can be produced from the client's file, then
    # use a timestamp
    client_name = ""
    try:
        with open("client_file.txt", 'r') as f:
            list = f.readlines()
            client_name = list[0].strip()
    except:
        #register a new client
        print("registering as a new client")
        client_name = str(time.time())
        args = {'sender': client_name}

        socketIO = SocketIO('http://boingoreg.ngrok.io')
        socketIO.on('registration_ack', on_frame_response)
        socketIO.emit('registration_request', args)

        with open("client_file.txt", 'w') as f:
            f.write(client_name)

    print("Booting Client " + client_name)

    # main event loop sends packets until connection is lost
    # at which point it blocks polling for the socket
    #while True:
    #try:
    socketIO = SocketIO(
        'http://boingocam.ngrok.io')  #'http://boingocam.ngrok.io'
    socketIO.on('frame_ack', on_frame_response)
    #except:
    #    continue

    video = cv2.VideoCapture(0)
    while True:
        success, image = video.read()
        if not success:
            continue

        ret, jpeg = cv2.imencode('.jpg', image)

        args = {
            'frame': jpeg.tobytes().encode('base64'),
            'sender': client_name
        }
        print("emission")

        #try:
        socketIO.emit('frame', args)
        socketIO.wait(seconds=.1)
Exemple #52
0
def main():
    uid = sys.argv[1]
    #if sys.argv[4] != "local":
    #	with SocketIO(sys.argv['4'], 3000, LoggingNamespace) as socketIO:

    c = Cam()

    n = Net(sys.argv[2], sys.argv[3])
    n.build()
    n.load_model()

    socketIO = SocketIO(sys.argv[4], 80, LoggingNamespace)
    print "Loaded Socket"

    last_emoji = 0

    while True:
        try:
            cv2.imshow('webcam', c.read_adjusted())
        except:
            pass
        #cv2.imshow('webcamx4', cv2.resize(c.read_adjusted(), (192, 192)))
        try:
            m = n.ff(np.asarray(c.read_adjusted()).reshape(1, 48, 48, 1))
        except:
            m = [[1, 0, 0, 0, 0, 0, 0]]

        m = m[0]
        conf = max(m)
        emo = m.index(max(m))
        print LABELS[emo], conf

        if sys.argv[4] != "local" and last_emoji != emo:
            socketIO.emit('emojis', {
                "user_id": uid,
                "emoji": emo,
                "confidence": conf
            })
            print "emitted"

        last_emoji = emo

        if cv2.waitKey(1) == 27:
            break

    #if sys.argv[4] != "local":
    #	ws.send({"user_id": uid, "emoji": -1, "confidence": conf})
    #	ws.close()
    cv2.destroyAllWindows()
Exemple #53
0
    def _run(self):
        print("Starting socket client (%s, %s)..." % (self.host, self.port))
        while self.running:
            try:
                # Timeout every 60 seconds
                selection = select.select(self.connections, [], [], 60)
                read_sock, write_sock, error_sock = selection
            except select.error:
                print("ERROR!!!")
                continue
            else:
                for sock in read_sock:
                    if sock == 0:
                        # self._send(self.sock, encode({}))
                        continue
                    elif sock == self.sock:
                        try:
                            data = self._receive(sock)
                            if data:
                                message = decode(data)
                                print("Received: %s" % message)
                                if (self.ports is not None):
                                    name = message["name"]
                                    data = message["data"]
                                    websock_ports = self.ports["websockets"]
                                    port = websock_ports["txdispatch"]
                                    websock = SocketIO("localhost", port)
                                    websock.emit("socket", message)
                                    # self.websock.emit("message", data,
                                    #     room=)
                                else:
                                    print("Error: Ports not set!")
                        except socket.error:
                            # Client is no longer replying
                            print("Disconnecting...")
                            attempts = 5
                            reconnected = False
                            while not reconnected or attempts > 0:
                                time.sleep(5)
                                print("Trying to reconnect...")
                                reconnected = self._bind_socket()
                                if not reconnected:
                                    attempts = attempts - 1

                            if not reconnected:
                                self.running = False
                                break
        # Clear the socket connection
        self.stop()
Exemple #54
0
class GrFNNClient(object):
    ''' Encapsulates a client socket connection, and a hook for emitting actions/model updates '''
    def __init__(self, host='127.0.0.1', port=5000):
        self._socket = SocketIO(host, port, LoggingNamespace)

    def send_action(self, action_flag):
        # Use this to send only an action, as sometimes it isn't related to a model change
        self._socket.emit(GrFNNKey.ACTION, action_flag)

    def send_heartbeat(self, normalised_amps, peaks):
        # Use this to send normalised amplitude array and peaks (active oscillators)
        self._socket.emit(GrFNNKey.DATA, {
            GrFNNKey.AMPS: normalised_amps,
            GrFNNKey.PEAKS: peaks
        })
Exemple #55
0
class Botio(object):
    events = [
        'new edge',
        'new nodetype',
        'new node',
        'edit edge',
        'new edgetype',
        'edit node',
        'new edge from',
        'edit nodetype',
        'delete node',
        'new edge to',
        'edit edgetype',
        'delete edge',
    ]

    def __init__(self, host='http://localhost', port=3000):
        """  """

        print "connecting", "@ %s:%s" % (host, port)
        self.socket = SocketIO(host, port)

    # on

    def on(self, event, callback):
        self.socket.on(event, callback)

    # remove events

    # TODO ... .
    # .. .... ..

    # emit

    def emit(self, event, uid):
        self.socket.emit(event, uid)
        self.socket.wait(1)

    # listen / stop

    def listenTo(self, uid):
        self.emit('listenTo', uid)

    def stopListeningTo(self, uid):
        self.emit('stopListeningTo', uid)

    def stopListening(self, uid):
        self.emit('stopListening', uid)
Exemple #56
0
class SocketThread(Thread):
    """
    TODO:
    - add doc
    """
    def __init__(self, parent, api_url):
        Thread.__init__(self)
        self.parent = parent
        self.socketIO = SocketIO(api_url)
        self.socketIO.on('status_update', self.parent.on_status_update)

    def join_room(self, room):
        self.socketIO.emit('join_room', {'session_id': room})

    def run(self):
        self.socketIO.wait()
Exemple #57
0
class SocketIoHandler(EventHandler):
    def __init__(self, bot, url):
        self.bot = bot
        self.host, port_str = url.split(':')
        self.port = int(port_str)
        self.sio = SocketIO(self.host, self.port)

    def handle_event(self, event, sender, level, msg, data):
        if msg:
            data['msg'] = msg

        self.sio.emit('bot:broadcast', {
            'event': event,
            'account': self.bot.config.username,
            'data': data
        })
class FacebookSentimentAnalyser:
    def __init__(self, facebook_resource: FacebookResource, page: str, post_limit: int = 100):
        self.fb = facebook_resource
        self.page = page
        self.post_limit = post_limit
        self.socket_io = SocketIO('localhost', 5000)

    def run(self):
        fanpage = self.fb.extract_fanpage_name_from_url(self.page)

        reports = []
        i = 0
        for post in self.fb.get_all_posts(fanpage):

            post_report = self.process_post(post)
            self.publish_status({'status': 'POST_PROCESSED',
                                 'post': post,
                                 'report': post_report})
            reports.append(post_report)

            i += 1
            if i > self.post_limit:
                break

        final_report = self.merge_and_evalute_score(reports)
        self.publish_status({'status': 'PAGE_PROCESSED',
                             'report': final_report})
        return final_report

    def merge_and_evalute_score(self, reports):
        return {}

    def process_post(self, post: dict):
        comments_sentim = list(map(lambda com: self.get_text_sentiment(com['message']),
                                   self.fb.get_all_comments(post['id'])))

        if len(comments_sentim) == 0:
            return {}
        else:
            return {
                "score": sum(comments_sentim) / len(comments_sentim)
            }

    def preprocess_text(self, text: str):
        return None

    def get_text_sentiment(self, text: str):
        from textblob import TextBlob
        blob = TextBlob(text)
        return blob.sentiment.polarity

    def publish_status(self, data):
        self.socket_io.emit('processing_status', {
            'page': self.page,
            'data': data
        })