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)
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!'
示例#3
0
def login():
    image_response = fetch('https://livechan.net/captcha.jpg')
    image_data = image_response.read()

    with open('captcha.jpg', 'w') as f:
        f.write(image_data)
    os.system("open captcha.jpg")

    digits = int(raw_input("enter the captcha: "))
    post_params = {}
    post_params["digits"] = digits
    login_response = post('https://livechan.net/login', post_params)
    login_html = login_response.read()

    print login_html
    livechan_pass = get_password()
    if livechan_pass == "":
        login()

    global socketIO
    socketIO = SocketIO('https://livechan.net',
        cookies={'password_livechan': livechan_pass})
    socketIO.on('chat', on_chat)
    socketIO.on('user_count', on_user_count)
    thread.start_new_thread ( socketIO.wait, () )
示例#4
0
文件: bot.py 项目: pefoley2/avalon
def main():
    conf_file = sys.argv[1] if len(sys.argv) > 1 else "config.yml"
    with open(conf_file) as f:
        config = yaml.load(f)

    channel = config["irc"]["channel"]
    sio = SocketIO(config["state"]["host"], config["state"]["port"])

    public_ns = sio.define(PublicNamespace, '/public')
    private_ns = sio.define(PrivateNamespace, '/private')

    bot = AvalonBot(private_ns)
    # TODO: figure out a less hacky solution.
    public_ns.bot = bot
    public_ns.channel = channel
    private_ns.bot = bot

    sio_t = threading.Thread(target=sio.wait)
    sio_t.start()

    bot.connect(config["irc"]["server"], config["irc"]["port"])
    bot.register(config["irc"]["nick"])
    bot.join(channel)

    bot.listen()
示例#5
0
def login(callback=on_chat):
    #image_response = fetch('https://livechan.net/captcha.jpg')
    #image_data = image_response.read()

    #with open('captcha.jpg', 'w') as f:
    #    f.write(image_data)
    #os.system("open captcha.jpg")

    #digits = int(raw_input("enter the captcha: "))
    #post_params = {}
    #post_params["digits"] = digits
    #login_response = post('https://livechan.net/login', post_params)
    #login_html = login_response.read()

    cookie = cookielib.Cookie(version=0, name='password_livechan', value='somepassword', port=None, port_specified=False, domain='livechan.net',
            domain_specified=False, domain_initial_dot=False,
            path='/', path_specified=True, secure=False, expires=None,
            discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
    cookies.set_cookie(cookie)
    livechan_pass = get_password()
    if livechan_pass == "":
        print "wrong password"
        login()

    global socketIO
    socketIO = SocketIO('https://livechan.net',
        cookies={'password_livechan': livechan_pass})
    socketIO.on('chat', callback)
    socketIO.on('request_location', on_request_location)
    
    thread.start_new_thread ( socketIO.wait, () )
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)
示例#7
0
def run_socketio(args):
    log.debug("launched as socket.io client")

    def printout(text):
        if not text is None:
            print chr(27) + "[2J" # clear screen
            t = text.decorated(style=STYLES[args.style]())
            print "--------8<----------------8<----------------8<---------------8<--------"
            print t
            print "-------->8---------------->8---------------->8--------------->8--------"

    res = requests.get("http://%s:%s/%s%s" % (args.host, args.port, args.path, args.pad))

    cookie = res.headers['set-cookie']
    cookie = dict([(cookie[:cookie.find("=")], cookie[cookie.find("=")+1:])])

    reconnect = True
    while reconnect:
        socketIO = SocketIO(args.host, args.port, EtherpadService,
                                                            transports=['xhr-polling',
                                                                        'websocket'],
                                                            cookies=cookie,
                                                            padid=args.pad,
                                                            cb=printout)
        reconnect = socketIO.wait()
        del socketIO
示例#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)
示例#9
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
示例#10
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()
示例#11
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)
示例#12
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
示例#13
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()
示例#14
0
def main():
    app = App(False)
    socketIO = SocketIO(API_URL, 443, LoggingNamespace)
    socketIO.on('location', app.on_ws_location)

    Thread(target=socketIO.wait).start()
    app.MainLoop()
示例#15
0
class YetiSocket():
    def __init__(self, host='localhost', port=5001):
        self.io = SocketIO(host, port)
        self.cam = self.io.define(CamNamespace, '/cam')

        self.cam.on('config_update', self.config_update)
        self.cam.on('manual_capture', self.manual_capture)

        self._thread = threading.Thread(target=self.io.wait)
        self._thread.daemon = True
        self._thread.start()

    def send(self, event, data):
        self.cam.emit(event, data)

    def config_update(self, data):
        print 'config update: %s' % data

    def manual_capture(self, data):
        print 'manual capture: ' + data
        
    def connect(self):
        self.cam.connect()

    def disconnect(self):
        self.cam.disconnect()
        self.io.disconnect()

    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, exc_tb):
        self.disconnect()
示例#16
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!')
示例#17
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)
示例#18
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)
示例#19
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()
示例#20
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)
示例#21
0
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()
示例#22
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()
示例#23
0
 def test_channels(self):
     mainSocket = SocketIO('localhost', 8000, Namespace)
     chatSocket = mainSocket.connect('/chat', Namespace)
     newsSocket = mainSocket.connect('/news', Namespace)
     newsSocket.emit('aaa', PAYLOAD)
     sleep(0.5)
     self.assertNotEqual(mainSocket.namespace.payload, PAYLOAD)
     self.assertNotEqual(chatSocket.namespace.payload, PAYLOAD)
     self.assertEqual(newsSocket.namespace.payload, PAYLOAD)
示例#24
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 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)
示例#26
0
def punisher(configs):

    socket = SocketIO(configs['server_addr'], configs['server_port'])
    punisher_ns = socket.define(PunisherNamespace, '/punisher')

    try:
        socket.wait()

    except KeyboardInterrupt:

        pass
def create_sockets(server, port, n):
    sockets = []

    for i in range(0, n):
        socket = SocketIO(server, port)
        socket.on('result', print_result(i))
        socket.on('server_error', print_server_error(i))

        sockets.append(socket)

    return sockets
示例#28
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()
示例#29
0
    def openStream(self, id, options, callback):
        try:
            if options['query']:
                d = options
        except:
            ##options is an string
            d = {'query':options}


        if (self.accessToken):
            url= self.base+':'+str(self.port)+'/api/wo/'+ id + '/endpoint'
            headers={ 'Authorization': 'Bearer ' + self.accessToken}
            
            r= requests.get(url,params=d, headers=headers, verify=False)
            
        if ('r' in locals() and r.status_code == 200):
                sid = r.content
#                print "sid:---"+sid
#                sio = 'http://webobservatory.soton.ac.uk'#+sid
                #sio = 'dev-001.ecs.soton.ac.uk'
                #print sio
#                class Namespace(BaseNamespace):
#                    def on_connect(self):
#                        print '[Connected]'

                class dataNamespace(BaseNamespace):
                    #def on_aaa_response(self, *args):
                    #    print('on_aaa_response', args)
                    def on_connect(self):
                        print '[Connected]'
                        pass

                def process(data):
#                    print "process data"
#                    print data
                    callback(False, data,socketIO)


#               socketIO = SocketIO(sio,443,LoggingNamespace,verify=False)
                socketIO = SocketIO(self.base,self.port, verify=False)
#                socketIO = SocketIO(self.base, 9090)
                data_namespace = socketIO.define(dataNamespace,'/'+sid)


                #data_namespace.emit('stop')
                data_namespace.on('chunk',process)
#                data_namespace.emit('stop')
#                socketIO.emit("stop")
#                socketIO.wait(seconds=1)
#                data_namespace.wait()
                socketIO.wait()
        else:
            callback("[ERROR] Open Stream Failed: Stream opening failed for:"+id,None,None)
示例#30
0
    def on_qvote_poke(self, args):
        player, role = args
        bot.send(player, "Please vote with 'pass' or '{}'.".format("pass" if role == "good" else "fail"))

    def on_qvote_error(self, args):
        player, message = args
        bot.send(player, message)

    def on_qvote_confirmation(self, args):
        player, vote = args
        bot.send(player, "You voted to {} the quest.".format(vote))

# FIXME: kill globals

channel = config["irc"]["channel"]
sio = SocketIO(config["state"]["host"], config["state"]["port"], headers={"Authentication":config["secret"]})

bot = AvalonBot()
public_ns = sio.define(PublicNamespace, '/public')
private_ns = sio.define(PrivateNamespace, '/private')


def main():
    sio_t = threading.Thread(target=sio.wait)
    sio_t.start()

    bot.connect(config["irc"]["server"], config["irc"]["port"])
    bot.register(config["irc"]["nick"])
    bot.join(channel)

    bot.listen()
示例#31
0
                          bouncetime=1000)

    global player
    player = OMXPlayer(VIDEO_FILE_3, args=['--no-osd', '--no-keys', '-b'])
    player.play()
    # now what ?
    sleep(1)
    player.pause()

    #global eventletThread
    #eventletThread = eventlet.spawn(checkI2C)
    #eventletThread.wait()

    global i2cThread
    i2cThread = Thread(target=checkI2C)
    i2cThread.start()

    print "starting up"
    socketIO = SocketIO('192.168.42.1', 5000, LoggingNamespace)
    print socketIO.connected
    while socketIO.connected == False:
        print "not connected"
        sleep(2.0)
        socketIO = SocketIO('192.168.42.1', 5000, LoggingNamespace)

    socketIO.on('reset', reset_handler)
    socketIO.on('projector_off', projector_off_handler)
    socketIO.on('power_off', poweroff_handler)

    socketIO.wait()
示例#32
0
        'username': args.username,
        'password': args.password,
    }

    resp = requests.post(base_url + "/login", json=payload,
                         verify=args.verify)
    resp.raise_for_status()

    headers = {'X-Auth-Token': resp.json()['token']}

if args.scheme == 'http':
    host = args.host
else:
    host = '%s://%s' % (args.scheme, args.host)

socketIO = SocketIO(host, args.port, BaseNamespace, verify=args.verify)
socketIO.on('log', on_log)
socketIO.on('end', on_end)
socketIO.on('playbook-start', on_playbook_start)
socketIO.on('playbook-error', on_playbook_error)

print("Launching playbook")
resp = requests.post(base_url + "/playbooks/" + args.playbook,
                     verify=args.verify, headers=headers)
resp.raise_for_status()

# Extract the play id from the response
id = resp.headers['Location'].split('/')[-1]

# Join the room where the log messages will be broadcast
socketIO.emit('join', id)
示例#33
0
from socketIO_client import SocketIO
import json
from grocerystats import Grocerystats

# basic socket usage taken from Matt Dodge's example
SOCKET_HOST = 'http://eval.socket.nio.works'

# initiate new class to handle everything
# parameter is type of grocery user wants to track
grocery = Grocerystats(['fruit', 'vegetable'])

with SocketIO(SOCKET_HOST) as sock:
    # Set up our message handler
    sock.on('recvData', grocery.handle_message_two)
    # Join the "fruits" room
    sock.emit('ready', 'groceries')
    # Wait for messages to come through! Ctrl-C to quit
    sock.wait()
示例#34
0
from socketIO_client import SocketIO, LoggingNamespace

def on_connect():
    print('connect')

def on_disconnect():
    print('disconnect')

def on_reconnect():
    print('reconnect')

def on_aaa_response(*args):
    print('on_aaa_response', args)

socketIO = SocketIO('127.0.0.1', 3001, LoggingNamespace)
socketIO.on('connect', on_connect)
socketIO.on('disconnect', on_disconnect)
socketIO.on('reconnect', on_reconnect)

def on_send_msg(text):
    socketIO.emit('event-kaldi', {'msg':text})
    socketIO.wait(seconds=1)
import json
import random
import uuid
import threading

host = 'localhost'
port = 8000
missionControlAPI = missionControlAPI()

def on_connect():
    print('connect')

def on_disconnect():
    print('disconnect')

def on_reconnect():
    print('reconnect')

def server_details(*args):
    socketIO.emit('server_details',missionControlAPI.getServerDetails())

#Define the socketIO connection
socketIO = SocketIO(host, port)
socketIO.on('connect', on_connect)
socketIO.on('disconnect', on_disconnect)
socketIO.on('reconnect', on_reconnect)
socketIO.on('server_details', server_details)


示例#36
0
import logging
from socketIO_client import SocketIO, LoggingNamespace
import numpy as np

logging.getLogger('socketIO-client').setLevel(logging.DEBUG)
logging.basicConfig()

with SocketIO('localhost', 3333, LoggingNamespace) as socketIO:
    socketIO.emit('gesture', repr(np.random.uniform((10, 10, 10))))
    socketIO.wait(seconds=1)
from socketIO_client import SocketIO
import serial
import time

print("Comenzando...")
socketIO = SocketIO('201.174.122.203', 5001)
print("Conectado al servidor.")

arduino = serial.Serial('/dev/ttyACM0', 9600, timeout=3.0)
arduino.isOpen()
while True:
    arduino.write("s")
    sig = arduino.readline()
    #sig = str(input ("Servo position: "))
    if not sig:
        continue
    print(sig)
    socketIO.emit("angulo", sig)
    time.sleep(0.1)

arduino.close()
示例#38
0
import serial
import pygame
import time
import socket

from socketIO_client import SocketIO, LoggingNamespace

with SocketIO('127.0.0.1', 3000, LoggingNamespace) as socketIO:

    pygame.init()
    j = pygame.joystick.Joystick(0)
    j.init()
    print 'Initialized Joystick : %s' % j.get_name()

    numButtons = j.get_numbuttons()
    numAxes = j.get_numaxes()
    numHats = j.get_numhats()

    try:
        while True:
            pygame.event.pump()

            data = 0

            for i in range(0, numButtons):
                if j.get_button(i) != 0:
                    data += (1 << i)

            for i in range(numButtons, numButtons + numAxes * 2)[::2]:
                axis = j.get_axis((i - numButtons) / 2)
                if axis > 0:
    print("Proceso exitoso!\n")


def tarea(args):
    global name
    print("Proceso HowLongToBeat")
    try:
        print('Iniciando tarea con ' + args[0].replace(" ", "-"))
        name = args[0]  #es necesario para el metodo de arriba
        results = HowLongToBeat(0).search(name)
        result = max(results,
                     key=lambda element: element.similarity).gameplay_main
        if result != -1:
            send_json(
                format_result(result)
            )  # Da formato al valor obtenido, intercambia '½' por '.30'
        else:
            send_json("n/a")
    except ValueError as e:
        print(e)


socketIO = SocketIO(
    "http://young-harbor-56590.herokuapp.com")  #se conecta al server
socketIO.on('start-' + const.HLTB_SOCKET_TYPE,
            tarea)  # define que hacer cuando se actice el evento

socketIO.emit('connect-socket', const.HLTB_SOCKET_TYPE)
print("Conectado y escuchando.\n")
socketIO.wait(
)  #queda escuchando al server en caso de que se active algun evento
示例#40
0
from socketIO_client import SocketIO, LoggingNamespace
import sys
import time
# sys.path.append("../PyRow")
# import pyrow
# Opens socket connection to communicate between Erg Telemetry and NODE
addr = '127.0.0.1'
# addr = 'localhost'
port = 8080
print("listen to coonectios")
socketIO = SocketIO(addr, port, LoggingNamespace)
print("Meow")
# Send dummy data
# data = {'time':'','distance':'','driveLength': 1.24,'driveTime': 0.6,'strokeRecoveryTime': 1.42,'strokeRecoveryDistance': 9.86,'peakDriveForce': 181.70000000000002,'avgDriveForce': 102,'strokePower': 241,'strokeCalories': 1129,'strokeCount': 39}
# socketIO.emit('strokeData',data)
import random
distance = 0
distance1 = 0
distance2 = 0

mTime = 0
dx = 0
prev_time = 0
while 1:
    distance = distance + 1
    distance1 = distance1 + 1
    distance2 = distance2 + 1
    mTime = mTime + 0.5
    # data = {'time':'','distance':'','driveLength': 1.24,'driveTime': 0,'i':0,'strokeRecoveryTime': 0,'strokeRecoveryDistance': 9.86,'peakDriveForce': 181.70000000000002,'avgDriveForce': 102,'strokePower': 241,'strokeCalories': 1129,'strokeCount': 39}
    # socketIO.emit('strokeData',data)
    # data = {'time':'','distance':'','driveLength': 1.24,'driveTime': 0,'i':1,'strokeRecoveryTime': 0,'strokeRecoveryDistance': 9.86,'peakDriveForce': 181.70000000000002,'avgDriveForce': 102,'strokePower': 241,'strokeCalories': 1129,'strokeCount': 39}
示例#41
0
    load_config()
    config_updated = False
    wo = WatchdogObserver()
    wcuh = ConfigUpdateHandler(patterns=['*.ini'], ignore_directories=True)
    wo.schedule(wcuh, path='.', recursive=False)
    wo.start()

    def teardown():
        wo.stop()
        wo.join()

    while True:
        sleep(DELAY)
        try:
            pass
            with SocketIO(HOST, PORT, wait_for_connection=False) as socketIO:
                pm = Pymem('TrickyTowers.exe')
                while True:
                    if config_updated:
                        config_updated = False
                        break
                    start = default_timer()
                    data = parse(pm)
                    socketIO.emit('json', data)
                    # _exit(0)

                    end = default_timer()

                    delayed = end - start
                    to_sleep = DELAY - delayed
                    if to_sleep > 0:
示例#42
0
from socketIO_client import SocketIO

import config
from device import Car


def on_command(command):
    command = json.loads(command)
    direction = command["direction"]
    if direction is None:
        car.stop()
    elif direction == "up":
        car.go_forward()
    elif direction == "down":
        car.go_backward()
    elif direction == "left":
        car.turn_left()
    elif direction == "right":
        car.turn_right()


car = Car(config.FRONT_LEFT_PINS, config.FRONT_RIGHT_PINS,
          config.BACK_LEFT_PINS, config.BACK_RIGHT_PINS)

socket = SocketIO(config.SOCKETIO_HOST,
                  config.SOCKETIO_PORT,
                  resource=config.SOCKETIO_PATH)
socket.on('command', on_command)
socket.wait()
示例#43
0
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()
示例#44
0
class FxcmApi(object):
    """FXCM"""
    API_URL = 'https://api-demo.fxcm.com:443'
    WEBSOCKET_PORT = 443
    METHOD_GET = 'get'
    METHOD_POST = 'post'

    MODEL_OFFER = 'Offer'
    MODEL_ACCOUNT = 'Account'
    MODEL_ORDER = 'Order'
    MODEL_OPENPOSITION = 'OpenPosition'
    MODEL_SUMMARY = 'Summary'
    MODEL_PROPERTIES = 'Properties'
    MODEL_CLOSEDPOSITION = 'ClosedPosition'

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        self.url = ''
        self.port = ''
        self.token = ''
        self.proxy = ''

        self.sio = None
        self.bearer = ''
        self.headers = None

        self.queue = Queue()
        self.reqid = 0
        self.active = False
        self.reqThread = None
        self.sioThread = None

    #----------------------------------------------------------------------
    def connect(self, url, port, token, proxy=''):
        """连接"""
        self.url = url
        self.port = port
        self.token = token
        self.proxy = proxy

        self.active = True

        self.reqThread = Thread(target=self.runReq)
        self.reqThread.start()

        self.sioThread = Thread(target=self.runSio)
        self.sioThread.start()

    #----------------------------------------------------------------------
    def stop(self):
        """停止"""
        if self.active:
            self.active = False
            self.reqThread.join()

            self.sio._close()
            self.sioThread.join()

    #----------------------------------------------------------------------
    def initSocketIO(self):
        """初始化SocketIO客户端"""
        params = {'access_token': self.token, 'agent': "leiwang-rest-api"}

        proxy = {}
        if self.proxy:
            proxy['https'] = self.proxy

        self.sio = SocketIO(self.url, self.port, params=params, proxies=proxy)

        self.sio.on('connect', self.onConnect)
        self.sio.on('disconnect', self.onDisconnect)

    #----------------------------------------------------------------------
    def generateBearer(self):
        """创建通讯授权码"""
        self.bearer = "Bearer " + self.sio._engineIO_session.id + self.token

    #----------------------------------------------------------------------
    def generateHeaders(self):
        """生成通讯头部"""
        self.headers = {
            'User-Agent': 'request',
            'Authorization': self.bearer,
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        }

    #----------------------------------------------------------------------
    def runReq(self):
        """处理主动请求"""
        while self.active:
            try:
                d = self.queue.get(timeout=1)
                self.processReq(d)
            except Empty:
                pass

    #----------------------------------------------------------------------
    def runSio(self):
        """处理回调数据"""
        self.initSocketIO()
        self.generateBearer()
        self.generateHeaders()
        self.sio.wait()

    #----------------------------------------------------------------------
    def sendReq(self, method, uri, params, callback):
        """发出请求"""
        self.reqid += 1

        d = {
            'method': method,
            'uri': uri,
            'params': params,
            'callback': callback,
            'reqid': self.reqid
        }

        self.queue.put(d)

        return self.reqid

    #----------------------------------------------------------------------
    def processReq(self, d):
        """处理请求"""
        method = d['method']
        uri = d['uri']
        params = d['params']
        callback = d['callback']
        reqid = d['reqid']

        url = self.url + uri

        proxy = {}
        if self.proxy:
            proxy['https'] = self.proxy

        if method == self.METHOD_GET:
            resp = requests.get(url,
                                headers=self.headers,
                                params=params,
                                proxies=proxy)
        elif method == self.METHOD_POST:
            resp = requests.post(url,
                                 headers=self.headers,
                                 data=params,
                                 proxies=proxy)

        if resp.status_code == 200:
            data = resp.json()
            if data["response"]["executed"] is True:
                callback(data, reqid)
                return
            if 'response' in data:
                self.onError(data["response"]["error"], reqid)
        else:
            self.onError(u'HTTP请求失败,错误代码%s' % resp.status_code)

    #----------------------------------------------------------------------
    def getInstruments(self):
        """查询合约代码"""
        uri = '/trading/get_instruments'
        reqid = self.sendReq(self.METHOD_GET, uri, {}, self.onGetInstruments)
        return reqid

    #----------------------------------------------------------------------
    def getModel(self, model):
        """查询表"""
        uri = '/trading/get_model'
        params = {'models': model}
        reqid = self.sendReq(self.METHOD_GET, uri, params, self.onGetModel)
        return reqid

    #----------------------------------------------------------------------
    def subscribe(self, symbol):
        """订阅行情"""
        uri = '/subscribe'
        params = {'pairs': symbol}
        reqid = self.sendReq(self.METHOD_POST, uri, params, self.onSubscribe)
        self.sio.on(symbol, self.processPriceUpdate)
        return reqid

    #----------------------------------------------------------------------
    def unsubscribe(self, symbol):
        """退订行情"""
        uri = '/unsubscribe'
        params = {'pairs': symbol}
        reqid = self.sendReq(self.METHOD_POST, uri, params, self.onUnsubscribe)
        return reqid

    #----------------------------------------------------------------------
    def subscribeModel(self, model):
        """订阅表"""
        uri = '/trading/subscribe'
        params = {'models': model}
        reqid = self.sendReq(self.METHOD_POST, uri, params,
                             self.onSubscribeModel)
        self.sio.on(model, self.processModelUpdate)
        return reqid

    #----------------------------------------------------------------------
    def unsubscribeModel(self, model):
        """退订表"""
        uri = '/trading/unsubscribe'
        params = {'models': model}
        reqid = self.sendReq(self.METHOD_POST, uri, params,
                             self.onUnsubscribeModel)
        return reqid

    #----------------------------------------------------------------------
    def updateSubscriptions(self, symbol):
        """订阅报价表"""
        uri = '/trading/update_subscriptions'
        params = {'symbol': symbol, 'visible': 'true'}
        #params = {'symbol': symbol}
        reqid = self.sendReq(self.METHOD_POST, uri, params,
                             self.onUpdateSubscriptions)
        return reqid

    #----------------------------------------------------------------------
    def openTrade(self,
                  accountID,
                  symbol,
                  isBuy,
                  amount,
                  atMarket,
                  orderType,
                  timeInForce,
                  rate=0,
                  limit=0,
                  stop=0,
                  trailingStep=0,
                  isInPips=False):
        """市价开仓交易"""
        uri = '/trading/open_trade'
        params = {
            'account_id': accountID,
            'symbol': symbol,
            'is_buy': isBuy,
            'amount': amount,
            'at_market': atMarket,
            'order_type': orderType,
            'time_in_force': timeInForce,
            'is_in_pips': isInPips
        }

        if rate:
            params['rate'] = rate

        if rate:
            params['limit'] = limit

        if stop:
            params['stop'] = stop

        if trailingStep:
            params['trailing_step'] = trailingStep

        reqid = self.sendReq(self.METHOD_POST, uri, params, self.onOpenTrade)
        return reqid

    #----------------------------------------------------------------------
    def createEntryOrder(self,
                         accountID,
                         symbol,
                         isBuy,
                         rate,
                         amount,
                         orderType,
                         timeInForce,
                         limit=0,
                         stop=0,
                         trailingStep=0,
                         isInPips=False):
        """限价开仓交易"""
        uri = '/trading/create_entry_order'

        params = {
            'account_id': accountID,
            'symbol': symbol,
            'is_buy': isBuy,
            'rate': rate,
            'amount': amount,
            'order_type': orderType,
            'time_in_force': timeInForce,
            'is_in_pips': isInPips
        }

        if rate:
            params['limit'] = limit

        if stop:
            params['stop'] = stop

        if trailingStep:
            params['trailing_step'] = trailingStep

        reqid = self.sendReq(self.METHOD_POST, uri, params, self.onOpenTrade)
        return reqid

    #----------------------------------------------------------------------
    def closeTrade(self,
                   tradeID,
                   amount,
                   atMarket,
                   orderType,
                   timeInForce,
                   rate=0):
        """平仓交易"""
        uri = '/trading/close_trade'
        params = {
            'trade_id': tradeID,
            'amount': amount,
            'at_market': atMarket,
            'order_type': orderType,
            'time_in_force': timeInForce
        }

        if rate:
            params['rate'] = rate

        reqid = self.sendReq(self.METHOD_POST, uri, params, self.onCloseTrade)
        return reqid

    #----------------------------------------------------------------------
    def changeOrder(self, orderID, rate, range_, amount, trailingStep=0):
        """修改委托"""
        uri = '/trading/change_order'
        params = {
            'order_id': orderID,
            'rate': rate,
            'range': range_,
            'amount': amount
        }

        if trailingStep:
            params['trailing_step'] = trailingStep

        reqid = self.sendReq(self.METHOD_POST, uri, params, self.onChangeOrder)
        return reqid

    #----------------------------------------------------------------------
    def deleteOrder(self, orderID):
        """撤销委托"""
        uri = '/trading/delete_order'
        params = {'order_id': orderID}
        reqid = self.sendReq(self.METHOD_POST, uri, params, self.onDeleteOrder)
        return reqid

    #----------------------------------------------------------------------
    def onConnect(self):
        """连接回调"""
        print('onConnect')

    #----------------------------------------------------------------------
    def onDisconnect(self):
        """断开回调"""
        print('onClose')

    #----------------------------------------------------------------------
    def onError(self, error, reqid):
        """错误回调"""
        print('onError', error)

    #----------------------------------------------------------------------
    def onGetInstruments(self, data, reqid):
        """查询合约代码回调"""
        print(data, reqid)

    #----------------------------------------------------------------------
    def onGetModel(self, data, reqid):
        """查询表回调"""
        print('*' * 30)
        print(data)
        for d in data['offers']:
            #if str(d['currency']) == 'EUR/USD':
            #    print d
            print(d['currency'])  #, d['visible']
        #print len(data['summary'])
        #print data

    #----------------------------------------------------------------------
    def onSubscribe(self, data, reqid):
        """订阅行情回调"""
        print(data, reqid)

    #----------------------------------------------------------------------
    def onUnsubscribe(self, data, reqid):
        """退订行情回调"""
        print(data, reqid)

    #----------------------------------------------------------------------
    def onSubscribeModel(self, data, reqid):
        """订阅表回调"""
        print(data, reqid)

    #----------------------------------------------------------------------
    def onUnsubscribeModel(self, data, reqid):
        """退订表回调"""
        print(data, reqid)

    #----------------------------------------------------------------------
    def onUpdateSubscriptions(self, data, reqid):
        """订阅报价表回调"""
        print(data, reqid)

    #----------------------------------------------------------------------
    def onOpenTrade(self, data, reqid):
        """开仓回调"""
        print(data, reqid)

    #----------------------------------------------------------------------
    def onCloseTrade(self, data, reqid):
        """平仓回调"""
        print(data, reqid)

    #----------------------------------------------------------------------
    def onChangeOrder(self, data, reqid):
        """改单回调"""
        print(data, reqid)

    #----------------------------------------------------------------------
    def onDeleteOrder(self, data, reqid):
        """撤单回调"""
        print(data, reqid)

    #----------------------------------------------------------------------
    def processPriceUpdate(self, msg):
        """行情推送"""
        data = json.loads(msg)
        self.onPriceUpdate(data)

    #----------------------------------------------------------------------
    def processModelUpdate(self, msg):
        """表推送"""
        print(msg)
        data = json.loads(msg)
        self.onModelUpdate(data)

    #----------------------------------------------------------------------
    def onPriceUpdate(self, data):
        """行情推送"""
        print(data)

    #----------------------------------------------------------------------
    def onModelUpdate(self, data):
        """表推送"""
        print(data)
示例#45
0
class Muse(Device):
    def __init__(self, device_id=None):
        super().__init__(device_id)
        self.streams = {}
        self.pred_results = []
        self.train_results = []
        self.time_diff = 0  # difference between unix and muse time
        self.train_mode = True  # True for training, False for prediction

        # socket for communicating with whatever wants to pull prediction
        # results from Muse
        self.sio = socketio.AsyncServer(async_mode='sanic')
        self.app = Sanic()
        self.sio.attach(self.app)

    @staticmethod
    def available_devices():
        pass

    #
    # Callback functions
    #

    def on_retrieve_prediction_results(self, *args):
        """Callback function for saving prediction results"""
        results = args[0]
        self.pred_results.append(results)

    def on_train_results(self, *args):
        """Callback function for saving training results"""
        results = args[0]
        self.train_results.append(results)

    def print_results(self, *args):
        """Test callback function that simply prints out the results"""
        for arg in args:
            print(arg)

    #
    # Private device methods for handling data streams
    #

    def _create_eeg_stream(self):
        """Creates a stream that streams EEG data"""
        return EEGStream(thread_name='EEG_data', event_channel_name='P300')

    def _create_marker_stream(self):
        """Create a stream that streams marker data"""
        info = pylsl.StreamInfo('Markers', 'Markers', 4, 0, 'string',
                                'mywid32')
        self.marker_outlet = pylsl.StreamOutlet(info)
        return MarkerStream(thread_name='Marker_stream')

    def _create_ml_stream(self, data):
        """Creates a stream that combines the EEG and marker streams, and
        forms epochs based on timestamp"""
        if self.streams.get('eeg') is None:
            raise Exception(f"EEG stream does not exist")
        if self.streams.get('marker') is None:
            raise Exception(f"Marker stream does not exist")

        return MLStream(m_stream=self.streams['marker'],
                        eeg_stream=self.streams['eeg'],
                        event_time=data['event_time'],
                        train_epochs=data['train_epochs'])

    def _start_stream(self, stream):
        """Starts stream given stream name (one of 'eeg', 'marker', or 'ml')"""
        if self.streams.get(stream) is None:
            raise RuntimeError(
                "Cannot start {0} stream, stream does not exist".format(
                    stream))
        elif stream == 'ml':
            self.streams[stream].start(self.train_mode)
        else:
            self.streams[stream].lsl_connect()

    def _stop_stream(self, stream):
        """Stops stream given stream name (one of 'eeg', 'marker', or 'ml')"""
        if self.streams.get(stream) is None:
            raise RuntimeError(
                "Cannot stop {0} stream, stream does not exist".format(stream))
        else:
            self.streams[stream].stop()

    #
    # Methods for handling server communication
    #

    def neurostack_connect(self, ip='35.222.93.233', port=8001):
        """
        Connects to neurostack server at ip:port and starts marker and ML
        streams. If no arguments for ip and port are given, then connects to
        the default hardcoded address for a server on the cloud.
        """
        self.socket_client = SocketIO(ip, port)
        self.socket_client.connect()

        # assumes EEG stream has already been started
        for stream in ['marker', 'ml']:
            self._start_stream(stream)

        while len(self.streams['eeg'].data) == 0:
            time.sleep(0.1)

        self.time_diff = time.time() - self.streams['eeg'].data[-1][-1]

    def neurostack_disconnect(self):
        """Disconnects from neurostack server and stops marker and ML streams"""
        for stream in ['marker', 'ml']:
            self._stop_stream(stream)

        self.socket_client.disconnect()

    def send_train_data(self, uuid, eeg_data, p300):
        """
        Sends training data to neurostack server

        :param uuid: client's UUID
        :param eeg_data: one sample of EEG data to be used for training
        :param p300: True if this data represents a p300 signal, else False
        :returns: None
        """
        args = {'uuid': uuid, 'data': eeg_data, 'p300': p300}
        self.socket_client.emit("train_classifier", args,
                                self.on_train_results)
        self.socket_client.wait_for_callbacks(seconds=1)

    def send_predict_data(self, uuid, eeg_data):
        """
        Sneds prediction data to neurostack server

        :param uuid: client's UUID
        :param eeg_data: one sample of EEG data that we want to predict for
        :returns: None
        """
        args = {'uuid': uuid, 'data': eeg_data}
        self.socket_client.emit("retrieve_prediction_results", args,
                                self.on_retrieve_prediction_results)
        self.socket_client.wait_for_callbacks(seconds=1)

    def change_mode(self, train_mode=False):
        """
        self.train_mode=True for training mode
        self.train_mode=False for prediction mode
        """
        if self.streams['ml'] is None:
            raise Exception(f"ml stream does is not running")

        curr_mode = self.streams['ml'].get_mode()
        if curr_mode is not train_mode:
            self.train_mode = train_mode
            self.streams['ml'].set_mode(train_mode)

    def send_predict_data_test(self, uuid, eeg_data):
        """
        Tests endpoint for sending prediction data to neurostack server

        :param uuid: client's UUID
        :param eeg_data: one sample of EEG data that we want to predict for
        :returns: None
        """
        args = {'uuid': uuid, 'data': eeg_data}
        self.socket_client.emit("retrieve_prediction_results_test", args,
                                self.print_results)
        self.socket_client.wait_for_callbacks(seconds=1)

    def send_train_data_test(self, uuid, eeg_data, p300):
        """
        Tests endpoint for sending training data to neurostack server

        :param uuid: client's UUID
        :param eeg_data: one sample of EEG data to be used for training
        :param p300: True if this data represents a p300 signal, else False
        :returns: None
        """
        args = {'uuid': uuid, 'data': eeg_data, 'p300': p300}
        self.socket_client.emit("train_classifier_test", args,
                                self.print_results)
        self.socket_client.wait_for_callbacks(seconds=1)

    #
    # Methods for handling client-side communication
    #

    def initialize_handlers(self):
        """Initialize handlers for client-side communication"""
        self.sio.on("train", self.train_handler)
        self.sio.on("predict", self.predict_handler)

        self.sio.on("generate_uuid", self.generate_uuid_handler)

    async def train_handler(self, sid, args):
        """Handler for passing training data to Neurostack"""
        if not self.train_mode:
            self.change_mode(train_mode=True)
            time.sleep(.2)

        args = json.loads(args)
        uuid = args['uuid']
        timestamp = args['timestamp']
        p300 = args['p300']

        timestamp -= self.time_diff
        package = [
            str(timestamp),
            str(p300),  # target
            str(1),  # 1 event total
            str(uuid)  # epoch ID
        ]
        self.marker_outlet.push_sample(package)
        await self.start_event_loop()

        while len(self.train_results) == 0:
            time.sleep(.1)
        return self.train_results.pop(0)

    async def predict_handler(self, sid, args):
        """Handler for passing prediction data to Neurostack"""
        if self.train_mode:
            self.change_mode(train_mode=False)
            time.sleep(.2)

        args = json.loads(args)
        uuid = args['uuid']
        timestamp = args['timestamp']

        timestamp -= self.time_diff
        package = [
            str(timestamp),
            str(0),  # target
            str(1),  # 1 event total
            str(uuid)  # epoch ID
        ]
        self.marker_outlet.push_sample(package)
        await self.start_event_loop()

        while len(self.pred_results) == 0:
            time.sleep(.1)
        return self.pred_results.pop(0)

    async def generate_uuid_handler(self, sid, args):
        """Handler for sending a request to the server to generate a UUID"""
        return generate_uuid()

    async def start_event_loop(self):
        """
        Continuously pulls data from ml_stream and sends to server based on
        whether we are training or predicting
        """
        if self.streams.get('ml') is None:
            raise Exception(f"ml stream does not exist")

        data = None
        while data is None:
            # send training jobs to server
            if self.train_mode:
                data = self.streams['ml'].get_training_data()
                if data is not None:
                    uuid = data['uuid']
                    train_data = data['train_data']
                    train_targets = data['train_targets']
                    self.send_train_data(uuid, train_data, train_targets)
                    return

            # send prediction jobs to server
            else:
                data = self.streams['ml'].get_prediction_data()
                if data is not None:
                    uuid = data['uuid']
                    eeg_data = data['eeg_data']
                    self.send_predict_data(uuid, eeg_data)
                    return

            time.sleep(0.1)

    #
    # Public device metods
    #

    def connect(self, device_id=None):
        """
        Creates data streams if there are none and connects to EEG stream
        (since that is the one that is immediately needed for use)
        """
        if self.streams.get('eeg') is None:
            self.streams['eeg'] = self._create_eeg_stream()

        if self.streams.get('marker') is None:
            self.streams['marker'] = self._create_marker_stream()

        if self.streams.get('ml') is None:
            data = {
                'event_time': 0.4,
                'train_epochs': 120
            }  # 120 for 2 min, 240 for 4 min
            self.streams['ml'] = self._create_ml_stream(data)

        self.streams['eeg'].lsl_connect()

    def start(self):
        """Start streaming EEG data"""
        self.streams['eeg'].start()

        while len(self.streams['eeg'].data) == 0:
            time.sleep(0.1)

        self.time_diff = time.time() - self.streams['eeg'].data[-1][-1]

    def stop(self):
        """Stop streaming EEG data"""
        self.streams['eeg'].stop()

    def shutdown(self):
        """Disconnect EEG stream (and stop streaming data)"""
        for stream_name in ['eeg', 'marker', 'ml']:
            self.streams[stream_name] = None

    def get_info(self):
        pass
示例#46
0
from socketIO_client import SocketIO

socket = SocketIO('localhost', 3000)

username = input('What is your username?')

chat_message = input('\n')
while chat_message != 'quit':
    msg = {"contents": chat_message, "username": username}
    socket.emit('chat', msg)
    chat_message = input()
示例#47
0
    print 'PROD MODE *************'
    print "using prod port 8022"
    port = 8022
else:
    print "invalid environment"
    sys.exit(0)

if commandArgs.type == 'serial':
    # initialize serial connection
    serialBaud = 9600
    print "baud:", serialBaud
    #ser = serial.Serial('/dev/tty.usbmodem12341', 19200, timeout=1)  # open serial
    ser = serial.Serial(serialDevice, serialBaud, timeout=1)  # open serial

print 'using socket io to connect to', server
socketIO = SocketIO(server, port, LoggingNamespace)
print 'finished using socket io to connect to', server


def setServoPulse(channel, pulse):
    pulseLength = 1000000  # 1,000,000 us per second
    pulseLength /= 60  # 60 Hz
    print "%d us per period" % pulseLength
    pulseLength /= 4096  # 12 bits of resolution
    print "%d us per bit" % pulseLength
    pulse *= 1000
    pulse /= pulseLength
    pwm.setPWM(channel, 0, pulse)


if commandArgs.type == 'motor_hat':
示例#48
0
def pingSlave(address):
    bus.write_byte(address, 1)
    return -1


def readSlave(address):
    data = bus.read_byte(address)
    return data


def convertToWeight(voltage):
    weight = voltage
    return weight


setupArduinos(NUM_ARDUINOS)
socket = SocketIO('http://yf-server.herokuapp.com', 80, LoggingNamespace)

while True:
    sensorData = []
    for slaveAddr in arduinos:
        pingSlave(slaveAddr)
        time.sleep(.2)
        slaveData = readSlave(slaveAddr)
        sensorData.append(convertToWeight(slaveData))

    action = {'type': 'SET_SENSOR_STATES', 'sensors': sensorData}
    socket.emit('action', action)
    print str(sensorData)
示例#49
0

def generate_id(length, symbols=_id_symbols):
    n = len(symbols)
    symbol_gen = (symbols[random.randrange(0, n)] for i in range(length))
    return ''.join(symbol_gen)


if len(sys.argv) == 1:
    print "Usage: agent.py <room_id>"
    sys.exit(1)
else:
    room_id = sys.argv[1]

user_name = 'INDRA'
user_id = generate_id(USER_ID_LEN)

socket = SocketIO('localhost', 3000)
sa_payload = {'userName': user_name, 'room': room_id, 'userId': user_id}
socket.on('message', on_message)
socket.on('userList', on_user_list)
socket.emit('subscribeAgent', sa_payload, ack_subscribe_agent)

try:
    socket.wait()
except KeyboardInterrupt:
    pass
print "Disconnecting..."
socket.emit('disconnect')
socket.disconnect()
示例#50
0
            chat_namespace = socketIO.define(ChatNamespace, '/chat')
        else:
            print("Could not login to server")
            sys.exit(1)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Example MultiBot')
    parser.add_argument('token',
                        help='token for logging in as bot ' +
                        '(see SERVURL/token)')
    parser.add_argument('-c',
                        '--chat_host',
                        help='full URL (protocol, hostname; ' +
                        'ending with /) of chat server',
                        default='http://localhost')
    parser.add_argument('-p',
                        '--chat_port',
                        type=int,
                        help='port of chat server',
                        default=5000)
    args = parser.parse_args()

    with SocketIO(args.chat_host, args.chat_port) as socketIO:
        login_namespace = socketIO.define(LoginNamespace, '/login')
        login_namespace.emit('connectWithToken', {
            'token': args.token,
            'name': "MultiBot"
        })
        socketIO.wait()
示例#51
0
#elif commandArgs.env == "prod":
#    print "using prod port 8022"
#    port = 8022
#else:
#    print "invalid environment"
#    sys.exit(0)

print "initializing socket io"
print "server:", server
#print "port:", port

infoServerProtocol = commandArgs.info_server_protocol

print "trying to connect to app server socket io", commandArgs.app_server_socketio_host, commandArgs.app_server_socketio_port
appServerSocketIO = SocketIO(commandArgs.app_server_socketio_host,
                             commandArgs.app_server_socketio_port,
                             LoggingNamespace)
print "finished initializing app server socket io"


def getVideoPort():

    url = '%s://%s/get_video_port/%s' % (infoServerProtocol, infoServer,
                                         commandArgs.camera_id)
    response = robot_util.getWithRetry(url)
    return json.loads(response)['mpeg_stream_port']


def getAudioPort():

    url = '%s://%s/get_audio_port/%s' % (infoServerProtocol, infoServer,
示例#52
0
def on_connect():
    print('connect')


def on_yourid(data):
    global id
    print(data)
    id = data['id']
    print(id)


def deal_poker(data):
    print(data)


def on_aaa_response(*args):
    print('on_aaa_response', args)


socketIO = SocketIO('127.0.0.1', 3001, LoggingNamespace)
socketIO.on('yourid', on_yourid)
socketIO.wait(seconds=2)
print("id:{}".format(id))
socketIO.on('deal_poker', deal_poker)
socketIO.emit("MSG_DDZ_ENTER_TABLE", {
    'cmd': "join",
    "tableId": 1,
    "player": id
})
socketIO.wait(seconds=1000)
示例#53
0
    def start(self):
        self.sio = SocketIO(self.server, self.port, Namespace)

        #define callback function for what a certain event is happening
        self.sio.wait()
        logging.debug("connection started")
示例#54
0
def pkt_callback(pkt):
    #a=list(str(pkt))
    #prn=lambda x: x.sprintf("%IP.src%:%TCP.sport% -> %IP.dst%:%TCP.dport%::%TCP.payload%")
    #pkt.show()
    global a
    global cmd, data, t1, t2, unitID, ip_src, ip_dst, danger_ip, danger_data
    if (IP in pkt):
        ip_src = pkt[IP].src
        ip_dst = pkt[IP].dst
        tcp_sport = pkt[TCP].sport
        tcp_dport = pkt[TCP].dport
        danger_ip = "."
        danger_data = "0"
    #print(str(ip_src)+":"+str(tcp_sport)+" --> "+str(ip_dst)+":"+str(tcp_dport))
    payload = list(str(pkt))
    if (payload[-5] == '\x03' and payload[-4] == '\x00'
            and payload[-3] == '\x04' and payload[-2] == '\x00'
            and payload[-1] == '\x02'):
        cmd = "Read"
        unitID = str(ord(payload[-6]))
        data = "."
        print(cmd + " :" + data)
        print("ipsrc " + ip_src + " ipdst " + ip_dst + " cmd " + cmd +
              " danger_ip " + danger_ip + " danger_data " + danger_data)
    elif (payload[-5] == '\x06' and payload[-4] == '\x00'
          and payload[-3] == '\x04'):
        cmd = "Write"
        t1 = ord(payload[-1])
        t2 = ord(payload[-2])
        data = str((t2 * 256) + (t1))
        unitID = str(ord(payload[-6]))
        if ((ip_src != '192.168.0.21' and ip_src != '192.168.0.20')
                or (ip_dst != '192.168.0.21' and ip_dst != '192.168.0.20')):
            danger_ip = ip_src
            danger_data = "1"
        else:
            danger_ip = "."
            if (int(data) < 500 or int(data) > 10000):
                danger_data = "1"
            else:
                danger_data = "0"
        print(cmd + " :" + data)
        print("ipsrc " + ip_src + " ipdst " + ip_dst + " cmd " + cmd +
              " danger_ip " + danger_ip + " danger_data " + danger_data)
    elif (payload[-6] == '\x03' and payload[-5] == '\x04'
          and payload[-7] == '\x07'):
        cmd = "Response"
        unitID = str(ord(payload[-7]))
        t1 = ord(payload[-3])
        t2 = ord(payload[-4])
        data = str((t2 * 256) + (t1))
        print(cmd + " :" + data)
        print("ipsrc " + ip_src + " ipdst " + ip_dst + " cmd " + cmd +
              " danger_ip " + danger_ip + " danger_data " + danger_data)
    if ((ip_src != '192.168.0.21' and ip_src != '192.168.0.20')
            or (ip_dst != '192.168.0.21' and ip_dst != '192.168.0.20')):
        danger_ip = ip_src
        danger_data = "1"
    else:
        danger_ip = "."
        danger_data = "0"

    with SocketIO('localhost', 3000, LoggingNamespace) as socketIO:
        socketIO.emit(
            'scc', {
                "ipsrc": ip_src,
                "ipdst": ip_dst,
                "cmd": cmd,
                "data": data,
                "unitID": unitID,
                "dangerip": danger_ip,
                "dangerdata": danger_data
            })
示例#55
0
class VolumioClient:
    """ Class for the websocket client to Volumio """
    def __init__(self):
        HOSTNAME = 'localhost'
        PORT = 3000

        self._callback_function = False
        self._callback_args = False
        self.state = dict()
        self.state["status"] = ""
        self.prev_state = dict()
        self.prev_state["status"] = ""
        self.last_update_time = 0

        def _on_pushState(*args):
            self.state = args[0]
            if self._callback_function:
                self._callback_function(*self._callback_args)
            self.prev_state = self.state

        self._client = SocketIO(HOSTNAME, PORT, LoggingNamespace)
        self._client.on('pushState', _on_pushState)
        self._client.emit('getState', _on_pushState)
        self._client.wait_for_callbacks(seconds=1)

    def set_callback(self, callback_function, *callback_args):
        self._callback_function = callback_function
        self._callback_args = callback_args

    def play(self):
        self._client.emit('play')

    def pause(self):
        self._client.emit('pause')

    def toggle_play(self):
        try:
            if self.state["status"] == "play":
                self._client.emit('pause')
            else:
                self._client.emit('play')
        except KeyError:
            self._client.emit('play')

    def volume_up(self):
        self._client.emit('volume', '+')

    def volume_down(self):
        self._client.emit('volume', '-')

    def previous(self):
        self._client.emit('prev')

    def next(self):
        self._client.emit('next')

    def seek(self, seconds):
        self._client.emit('seek', int(seconds))

    def wait(self, **kwargs):
        self.wait_thread = Thread(target=self._wait, args=(kwargs))
        self.wait_thread.start()
        print "started websocket wait thread"
        return self.wait_thread

    def _wait(self, **kwargs):
        while True:
            self._client.wait(kwargs)
            print "websocket wait loop terminated, restarting"
示例#56
0
class SpeechToTextClient():
    def __init__(self):
        print('Init speech to text client')
        self.socket_url = "cognigy-stts.northeurope.cloudapp.azure.com"
        self.socket_port = 3002
        self.listening = False
        self.firstByte = True
        self.waitResult = True
        self.waitResultBrain = True
        self.config = '{"servicename": "google", "sample_rate": 22000}'
        self.socketIO = SocketIO(self.socket_url,
                                 self.socket_port,
                                 LoggingNamespace,
                                 params={'noTts': True})

        # bind events
        # bind only 1 event since python socket io wait only waits for 1 event
        #self.socketIO.on('stt', self.received_message)
        self.socketIO.on('brain_output', self.received_message_brain)

        # wait for brain first reply
        while self.waitResultBrain:
            self.socketIO.wait(10)

        # audio threading
        self.stream_audio_thread = threading.Thread(target=self.stream_audio)
        self.stream_audio_thread.start()
        self.counter = 0

    def received_message(self, message):
        # on message received, stop waiting
        print "Message received: " + str(message)
        self.waitResult = False
        self.listening = False
        self.counter = 0
        self.wait_for_input()

    def received_message_brain(self, message):
        # on receiving message from brain, stop waiting
        print "Brain reply received: " + str(message)
        self.waitResultBrain = False
        self.listening = False
        self.counter = 0
        self.wait_for_input()

    def wait_for_input(self):
        # wait for keyboard signal to start recording
        self.firstByte = True
        print('Listening to input')
        key_input = raw_input('Press enter to record...')
        if (key_input):
            print('Input detected')
            self.listening = True
            self.stream_audio()

    def stream_audio(self):
        # start audio stream
        self.waitResult = True
        self.waitResultBrain = True

        # create new subprocess for arecord
        print('Stream audio')
        reccmd = [
            "arecord", "-c", "1", "-D", "plughw:1,0", "-f", "S16_LE", "-r",
            "22000", "-t", "wav"
        ]
        p = subprocess.Popen(reccmd, stdout=subprocess.PIPE)

        # loop read stream while still listening
        while self.listening:
            self.counter += 1

            if (self.counter >= 100):
                print('Chunk end signal')
                self.socketIO.emit('stt_chunk_end')
                p.kill()
                self.firstByte = False
                self.listening = False
                print("Wait for result")

                while self.waitResultBrain:
                    print('waiting')
                    self.socketIO.wait(10)

            # read stream chunk and convert to binary array
            data = p.stdout.read(1024)
            data_bytes = fromstring(data, dtype=uint8)
            data_array = data_bytes.tolist()
            print(str(self.counter) + ' - ' + str(len(data_array)))

            if (self.firstByte):
                # if its first byte, send stt chunk start signal
                self.socketIO.emit('stt_chunk_start', self.config)
                self.firstByte = False

            # send audio chunk
            self.socketIO.emit('stt_chunk', data_array, self.counter)
示例#57
0
            'ip': ip,
            'name': printerName,
            'prices': prices,
            'category': category
        })


def print_data(*args):
    print 'printing ', args

    data = args[0]['data'].split('\n')
    for line in data:
        p.text(line.encode('utf-8') + '\n')


sock = SocketIO(serverIP, serverPort, PrintNamespace)
sock.on('print_data', print_data)
sock.wait()

#################################### Newer?
##!/usr/bin/python
## coding=UTF8
#
#from escpos import *
#import logging
#from socketIO_client import SocketIO, BaseNamespace
#import sys
#import socket
#
#logging.basicConfig(level=logging.ERROR)
#
示例#58
0
class Neurostack:
    def __init__(self,
                 devices=None):  # devices is one of the folders, arguments
        """
        Initialize a connection with an EEG device, and sets up an
        asynchronous connection with subscribers passed in.

        :param device: [Devices]
        """
        self.devices = devices

        # sanic server connects to app
        self.sio_app = socketio.AsyncServer(async_mode='sanic',
                                            cors_allowed_origins='*')
        self.sio_app_server = Sanic()
        self.sio_app.attach(self.sio_app_server)

        # socketIO client connects to neurostack server
        self.sio_neurostack = None

        self.train_results = {}
        self.predict_results = {}
        self.stream_raw_data = {}

    #
    # Methods for handling devices
    #

    def start(self, list_of_devices=None):
        """
        Start streaming EEG from device, and publish data to subscribers.

        :param list_of_devices: [Device] List of devices to start streaming. If none, all devices will start streaming.

        :return: None
        """
        if list_of_devices is None:
            devices_to_start = self.devices
        else:
            devices_to_start = list_of_devices

        for device in devices_to_start:
            device.start()

    def stop(self, list_of_devices=None):
        """
        Stop streaming EEG data from device, and stop publishing data to
        subscribers. Connection to device remains intact, and device is not
        turned off.

        :param list_of_devices: [Device] List of devices to stop streaming. If none, all devices will stop streaming.

        :return: None
        """
        if list_of_devices is None:
            devices_to_start = self.devices
        else:
            devices_to_start = list_of_devices

        for device in devices_to_start:
            device.stop()

    def shutdown(self, list_of_devices=None):
        """
        Close connection to device, WebSocket connections to publishers, and tag sources.

        :return: None
        """
        pass

    #
    # Methods for handling server-side communication
    #

    def neurostack_connect(self, ip='neurostack.neurotechuoft.com', port=8001):
        """
        Connects to neurostack server at ip:port. If no arguments for ip and
        port are given, then connects to the default hardcoded address for a
        server on the cloud.
        """
        self.sio_neurostack = SocketIO(ip, port)
        self.sio_neurostack.connect()

    def neurostack_disconnect(self):
        """Disconnects from neurostack server"""
        self.sio_neurostack.disconnect()

    def send_train_data(self, server_endpoint, uuid, eeg_data, label):
        """
        Sends training data to neurostack server

        :param server_endpoint: server API's endpoint
        :param uuid: client's UUID
        :param eeg_data: one sample of EEG data to be used for training
        :param label: this data's label
        :returns: None
        """
        args = {'uuid': uuid, 'data': eeg_data, 'label': label}
        self.sio_neurostack.emit(server_endpoint, args, self.on_train_results)
        self.sio_neurostack.wait_for_callbacks(seconds=1)

    def send_predict_data(self, server_endpoint, uuid, eeg_data):
        """
        Sneds prediction data to neurostack server

        :param server_endpoint: server API's endpoint
        :param uuid: client's UUID
        :param eeg_data: one sample of EEG data that we want to predict for
        :returns: None
        """
        args = {'uuid': uuid, 'data': eeg_data}
        self.sio_neurostack.emit(server_endpoint, args,
                                 self.on_predict_results)
        self.sio_neurostack.wait_for_callbacks(seconds=1)

    def send_train_data_test(self, uuid, eeg_data, label):
        """
        Tests endpoint for sending training data to neurostack server

        :param uuid: client's UUID
        :param eeg_data: one sample of EEG data to be used for training
        :param label: this data's label
        :returns: None
        """
        args = {'uuid': uuid, 'data': eeg_data, 'label': label}
        self.sio_neurostack.emit("test_train", args, self.print_results)
        self.sio_neurostack.wait_for_callbacks(seconds=1)

    def send_predict_data_test(self, uuid, eeg_data):
        """
        Tests endpoint for sending prediction data to neurostack server

        :param uuid: client's UUID
        :param eeg_data: one sample of EEG data that we want to predict for
        :returns: None
        """
        args = {'uuid': uuid, 'data': eeg_data}
        self.sio_neurostack.emit("test_predict", args, self.print_results)
        self.sio_neurostack.wait_for_callbacks(seconds=1)

    #
    # Methods for handling client-side communication
    #

    def initialize_handlers(self):
        """Initialize handlers for client-side communication"""

        # streaming raw data
        self.sio_app.on("start_streaming_raw_data",
                        self.start_streaming_raw_data_handler)
        self.sio_app.on("stop_streaming_raw_data",
                        self.stop_streaming_raw_data_handler)

        # training Neurostack model
        self.sio_app.on("p300_train", self.p300_train_handler)
        self.sio_app.on("p300_predict", self.p300_predict_handler)

        self.sio_app.on("left_right_train", self.left_right_train_handler)
        self.sio_app.on("left_right_predict", self.left_right_predict_handler)

        # misc
        self.sio_app.on("generate_uuid", self.generate_uuid_handler)

    def run(self, host='localhost', port=8002):
        """
        Runs Neurostack on host:port. This is used as an endpoint for
        client-side communication.

        :param host: local address to Neurostack on
        :param port: port to run Neurostack on
        :return: None
        """
        self.sio_app_server.run(host=host, port=port)

    async def start_streaming_raw_data_handler(self, sid, args):
        """
        Handler for streaming raw data

        :param sid: session ID (not important)
        :param args: arguments passed to this function. This should include:
            uuid: universally unique ID of user who wants to stop streaming
        """
        args = json.loads(args)
        uuid = args['uuid']
        self.stream_raw_data[uuid] = True

        # keep track of data from previous while loop iteration, so that the
        # same data is not sent twice.
        prev_data = None
        while self.stream_raw_data[uuid]:

            # TODO: devices[0] is the Muse that we set at the bottom, but we
            # want to support multiple or different devices
            data_stream = self.devices[0].data_stream
            eeg_channel_names = data_stream.get_eeg_channels()
            raw_data = data_stream.get_latest_data(eeg_channel_names)

            # TODO: raw data can be either a list or a dict right now, should we
            # just stick with dict?

            # in case while loop is running faster than device streaming rate
            if raw_data != prev_data:
                prev_data = raw_data
                await self.sio_app.emit('raw_data', raw_data)

    async def stop_streaming_raw_data_handler(self, sid, args):
        """
        Handler to tell neurostack to stop streaming raw data

        :param sid: session ID (not important)
        :param args: arguments passed to this function. This should include:
            uuid: universally unique ID of user who wants to stop streaming
        """
        args = json.loads(args)
        uuid = args['uuid']
        self.stream_raw_data[uuid] = False

        await self.sio_app.emit('raw_data', "streaming has stopped")

    async def p300_train_handler(self, sid, args):
        """P300 training handler"""
        args = json.loads(args)

        await self.train_handler(server_endpoint="p300_train",
                                 uuid=args['uuid'],
                                 timestamp=args['timestamp'],
                                 label=args['p300'])

    async def p300_predict_handler(self, sid, args):
        """P300 prediction handler"""
        args = json.loads(args)

        await self.predict_handler(server_endpoint="p300_predict",
                                   uuid=args['uuid'],
                                   timestamp=args['timestamp'])

    async def left_right_train_handler(self, sid, args):
        """Left-right training handler"""
        args = json.loads(args)

        await self.train_handler(server_endpoint="left_right_train",
                                 uuid=args['uuid'],
                                 timestamp=args['timestamp'],
                                 label=args['left'])

    async def left_right_predict_handler(self, sid, args):
        """Left-right prediction handler"""
        args = json.loads(args)

        await self.predict_handler(server_endpoint="left_right_predict",
                                   uuid=args['uuid'],
                                   timestamp=args['timestamp'])

    async def train_handler(self,
                            server_endpoint,
                            uuid,
                            timestamp,
                            label,
                            window=0.75):
        """
        Handler for passing training data to Neurostack

        TODO: something for sample rate

        :param server_endpoint: Neurostack server API endpoint
        :param uuid: client UUID
        :param timestamp: timestamp of data we are interested in, in unix time
        :param label: label for data
        :param window: window of data we are interested in, in seconds
        :return: None
        """
        # create list for uuid if not done already
        self.train_results[uuid] = self.train_results.get(uuid, [])

        # TODO: change API to specify device
        device = self.devices[0]

        # Wait until the device has enough data (ie. the time slice is complete)
        # then take 100ms - 750ms window for training
        while time.time() < timestamp + window:
            time.sleep(.01)

        # TODO: num_samples = window * sample rate
        timestamp -= self.devices[0].get_time_diff()
        data_dict = device.data_stream.get_eeg_data(start_time=timestamp + .1,
                                                    num_samples=128)
        data = list(data_dict.values())

        self.send_train_data(server_endpoint=server_endpoint,
                             uuid=uuid,
                             eeg_data=data,
                             label=label)

        # wait for results
        while len(self.train_results[uuid]) == 0:
            time.sleep(.01)
        result = self.train_results[uuid].pop(0)
        await self.sio_app.emit("train", result)

    async def predict_handler(self,
                              server_endpoint,
                              uuid,
                              timestamp,
                              window=0.75):
        """
        Handler for passing prediction data to Neurostack

        TODO: something for sample rate

        :param server_endpoint: Neurostack server API endpoint
        :param uuid: client UUID
        :param timestamp: timestamp of data we are interested in, in unix time
        :param window: window of data we are interested in, in seconds
        :return: None
        """
        # create list for uuid if not done already
        self.predict_results[uuid] = self.predict_results.get(uuid, [])

        # TODO: change API to specify device
        device = self.devices[0]

        # Wait until the device has enough data (ie. the time slice is complete)
        # then take 100ms - 750ms window for training. The window should
        # contain 0.65s * 256Hz = 166 samples.
        while time.time() < timestamp + window:
            time.sleep(.01)

        timestamp -= self.devices[0].get_time_diff()
        data_dict = device.data_stream.get_eeg_data(start_time=timestamp + .1,
                                                    num_samples=128)
        data = list(data_dict.values())

        self.send_predict_data(server_endpoint=server_endpoint,
                               uuid=uuid,
                               eeg_data=data)

        # wait for results
        while len(self.predict_results[uuid]) == 0:
            time.sleep(.01)
        result = self.predict_results[uuid].pop(0)
        await self.sio_app.emit("predict", result)

    async def generate_uuid_handler(self, sid, args):
        """Handler for sending a request to the server to generate a UUID"""
        uuid = generate_uuid()
        await self.sio_app.emit('generate_uuid', uuid)

    #
    # Callback functions
    #

    def on_train_results(self, *args):
        """Callback function for saving training results"""
        results = args[0]
        uuid = results['uuid']
        self.train_results[uuid].append(results)

    def on_predict_results(self, *args):
        """Callback function for saving prediction results"""
        results = args[0]
        uuid = results['uuid']
        self.predict_results[uuid].append(results)

    def print_results(self, *args):
        """Prints out results"""
        print(args)

    #
    # Other methods
    #

    def get_info(self, list_of_devices=None) -> []:
        """
        Return list of string representations of device info for specified
        devices (by calling get_info of each device).
        By default lists info of all devices under Neurostack.

        :return:
        """
        if list_of_devices is None:
            devices_to_start = self.devices
        else:
            devices_to_start = list_of_devices

        info = [device.get_info() for device in devices_to_start]
        return info
示例#59
0
def open_client():
    socketIO = SocketIO("streaming.plenar.io")

    socketIO.on('data', on_data)
    socketIO.on('internal_error', on_error)
    socketIO.wait()
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
        })