コード例 #1
0
def transmit():
    while True:
        time.sleep(1)
        # If there's something to transmit, make a connection and sent it out
        if (len(queue) > 0):

            # Attempt to connect, transmit all in queue if success
            print("Attempting connection...")
            try:
                sio = SocketIO(sys.argv[1],
                               verify=False,
                               wait_for_connection=False,
                               cert=('client.crt', 'client.key'))
                sio.wait(seconds=1)

                print("Connected")

                #sio.on('disconnect', on_disconnect)
                sio.on('response', on_response)

                queue2 = queue[:]  # Copy the list to resolve a bug in how the for loop works

                for id in queue2:
                    print("Transmitting " + str(id))
                    sio.emit('attend', {'ID': id})
                    sio.wait(seconds=1)

                #sio.disconnect()

            except ConnectionError:
                print('Server unreachable. Retrying shortly')
コード例 #2
0
def calibrate_PH():
    print("hey")
    devices    = AtlasI2C();
    socket_url = "localhost"

    socketIO = SocketIO(socket_url, 9000, verify=False)
    def start_calibrate(*arg):
        try:
            print("should be something")
            print(arg)
            a  = arg[0][u'data']
            print(a)
            if(a=="low"):
                command = "cal,low,4"
            if(a=="medium"):
                command = "cal,mid,7"
            if(a=="high"):
                command = "cal,high,10"
            print(command)
            mutex.acquire()
            devices.query(command)
            print("Command Successful")
            mutex.release()


        except ValueError:
            print("Wrong Command")
    socketIO.on('welcome',start_calibrate) #Listen to calibrating event
    socketIO.wait()
    while True: #keep the thread alive to continue listening
        pass
コード例 #3
0
class asyncSocketIo():
    def __init__(self, bot, settings):
        self.bot = bot
        self.settings = settings

        try:
            self.receive_events_thread._stop
        except Exception as e:
            pass

        self.socketio = SocketIO('https://sockets.streamlabs.com',
                                 params={'token': settings['socket_token']})
        self.socketio.on('event', self.on_event)
        self.socketio.on('disconnect', self.on_disconnect)

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

    def on_event(self, *args):
        DonationPointsModule.updatePoints(args, self.bot, self.settings)

    def on_disconnect(self, *args):
        log.error('Socket disconnected. Donations no longer monitored')
        self.bot.say('Socket disconnected. Donations no longer monitored')
        self.bot.execute_delayed(600, self.__init__, (self.bot, self.settings))

    def _receive_events_thread(self):
        self.socketio.wait()
コード例 #4
0
ファイル: helpers.py プロジェクト: silky/tributary
class SIOHelper(GenBase):
    def __init__(self, psp, url, send=None, channel='', records=False):
        self.validate(url, 'sio')
        self.__type = 'sio'
        self.url = url.replace('sio://', '')
        self.send = send
        self.channel = channel
        self.records = records

        self._data = []

        o = urlparse(self.url)

        self.socketIO = SocketIO(o.scheme + '://' + o.netloc, o.port)
        self.socketIO.on(self.channel, lambda data: self._data.append(data))
        self.url = o.path

        super(SIOHelper, self).__init__(psp)

    async def getData(self):
        if self.send:
            self.socketIO.emit(*self.send)
        t = threading.Thread(target=self.socketIO.wait)
        t.start()

        while 1:
            if self._data:
                c = 0
                for item in self._data:
                    c += 1
                    yield item
                self._data = self._data[:c]

            else:
                await asyncio.sleep(1)
コード例 #5
0
    def start_process(self):
        """main process start from here. """
        self.jwt_token = self.get_auth_code()
        # print("jwt token is: {}\n".format(self.jwt_token))
        params1 = self.util_obj.socket_connection['params1']
        params1["token"] = self.jwt_token

        # socketIO = SocketIO('192.168.0.60', 8080, params=params1)
        socketIO = SocketIO(self.util_obj.socket_connection['ip'],
                            self.util_obj.socket_connection['port'],
                            params=params1)

        socketIO.emit('server.version', {})
        socketIO.on('server.version', self.get_server_version)
        pLocationNamespace = socketIO.define(self.LocationNamespace,
                                             '/location')
        filterData = self.util_obj.filterData

        pLocationNamespace.emit('location:monitor:send:filter', filterData)
        pLocationNamespace.on('location:monitor:receive', self.on_aaa_response)
        try:
            socketIO.wait()
            # engineSocket.wait()
        except ConnectionError as ex:
            print("got connection error %s" % ex)
コード例 #6
0
ファイル: socket_client.py プロジェクト: liuxunxi/paper-code
class RetentionDashboardBlacklistSocket(RetentionDashboardSocket):
    def __init__(self, hostname, port):
        imageio.plugins.freeimage.download()
        self.hostname = hostname
        self.port = port
        self.update_blacklist = queue.Queue()
        self.socket = SocketIO(self.hostname, self.port)
        self.retention_dashboard_namespace = self.socket.define(
            RetentionDashboardBlacklistNamespace,
            Config.Socket.RETENTION_DASHBOARD_NAMESPACE)
        self.retention_dashboard_namespace.update_blacklist = self.update_blacklist
        self.socket.on(Config.Socket.UPDATE_BLACKLIST, \
                       self.retention_dashboard_namespace.on_update_pedestrian_blacklist())
        Thread(target=self.listen).start()

    def listen(self):
        self.socket.wait()

    def send_result(self, **kwargs):
        image_id = kwargs.get('image_id')
        self.retention_dashboard_namespace.emit(Config.Socket.NEW_FACE_EVENT,
                                                image_id)

    def get_update_blacklist(self):
        status = not self.update_blacklist.empty()
        if status:
            self.update_blacklist.get()
        return status
コード例 #7
0
class TwoWayClient(object):
    def __init__(self):
        self.socketIO = SocketIO(host, port)

        def on_connect():
            print("Server connected")

        def on_disconnect(*args):
            print("Server disconnected")

        def on_reconnect():
            print("Server reconnected")

        def on_time(*args):
            print(args[0])

        self.socketIO.on('connect', on_connect)  # This is not working
        self.socketIO.on('disconnect', on_disconnect)  # This works
        self.socketIO.on('reconnect', on_reconnect)  # This is not working
        self.socketIO.on('time', on_time)

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

        while True:
            some_input = input("Please input: ")
            self.socketIO.emit('custom', some_input)

    def _receive_events_thread(self):
        self.socketIO.wait()
コード例 #8
0
 def connect_run_forever(self):
     socketIO = SocketIO(self.ws_url, self.ws_port, LoggingNamespace)
     socketIO.on('connect', self._on_connect)
     socketIO.on('disconnect', self._on_disconnect)
     socketIO.on('reconnect', self._on_reconnect)
     socketIO.on('msg', self._on_msg)
     socketIO.wait()
コード例 #9
0
ファイル: test_socket.py プロジェクト: ahiroto/ParlAI
class TwoWayClient(object):
    def __init__(self):
        self.socketIO = SocketIO(host, port)
        
        def on_connect():
            print("Server connected")

        def on_disconnect(*args):
            print("Server disconnected")

        def on_reconnect():
            print("Server reconnected")

        def on_time(*args):
            print(args[0])

        self.socketIO.on('connect', on_connect) # This is not working
        self.socketIO.on('disconnect', on_disconnect) # This works
        self.socketIO.on('reconnect', on_reconnect) # This is not working
        self.socketIO.on('time', on_time)

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

        while True:
            some_input = input("Please input: ")
            self.socketIO.emit('custom', some_input)

    def _receive_events_thread(self):
        self.socketIO.wait()
def envoyerValeurDirect(jsonDonnee):
    global jsonValeur
    jsonValeur = jsonDonnee
    print(jsonValeur)

    connection = SocketIO('vps202433.vps.ovh.ca', 8080, LoggingNamespace)
    #connection = SocketIO('vps202845.vps.ovh.ca', 8080, LoggingNamespace)
    connection.on('salutation', lors_connection)
    connection.on('donnee_recu', on_send)

    connection.emit('emission-donnees-bouee', jsonValeur)  #envoie du json

    print("sent")
    connection.disconnect()
def envoyerDonneesAuServeur():
    global data
    donneeNonFormatee = data.decode()
    #donneeFormatee = json.dumps(donneeNonFormatee)
    print(donneeNonFormatee)

    connection = SocketIO('vps202433.vps.ovh.ca', 8080, LoggingNamespace)
    #connection = SocketIO('vps202845.vps.ovh.ca', 8080, LoggingNamespace)
    connection.on('salutation', lors_connection)
    connection.on('donnee_recu',on_send)  

    connection.emit('deverser-donnees-bouee', donneeNonFormatee) #envoie du json

    print("sent")
    connection.disconnect()  
コード例 #12
0
def connect_socket_io(dtable_server_url, dtable_uuid, jwt_token):
    host, port = parse_dtable_server_url(dtable_server_url)
    params = {'dtable_uuid': dtable_uuid}

    socketIO = SocketIO(host, port, params=params)
    socketIO.on('connect', on_connect)
    socketIO.on('reconnect', on_reconnect)
    socketIO.on('disconnect', on_disconnect)

    socketIO.emit(JOIN_ROOM, dtable_uuid, jwt_token)
    print('[ Seatable Socket IO Connected]')

    socketIO.on(UPDATE_DTABLE, on_update_dtable)
    socketIO.on(NEW_NOTIFICATION, on_new_notification)

    return socketIO
コード例 #13
0
        def parse_rrcs(self) -> NoReturn:
            """
            SocketIO connection to RIPE RIS to retrieve all active Route Collectors.
            """
            try:
                socket_io = SocketIO('http://stream-dev.ris.ripe.net/stream',
                                     wait_for_connection=False)

                def on_msg(msg):
                    self.available_ris = set(msg)
                    socket_io.disconnect()

                socket_io.on('ris_rrc_list', on_msg)
                socket_io.wait(seconds=3)
            except Exception:
                log.warning('RIPE RIS server is down. Try again later..')
コード例 #14
0
class Client(object):
    def __init__(self):
        self.socketio = SocketIO("http://twitchplaysnintendoswitch.com:8110")

        self.socketio.on("disableInternet", self.on_disable_internet)
        self.socketio.on("enableInternet", self.on_enable_internet)
        self.socketio.on("getInternetStatus", self.on_get_internet_status)
        self.socketio.on("disconnect", self.on_disconnect)
        self.socketio.emit("join", "proxy")

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

        self.start = time.process_time()
        self.end = time.process_time()

        self.status = False

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

    def on_event(self, event):
        #print(event)
        pass

    def on_disconnect(self):
        print("disconnected")
        os.system("killall python3")

    def on_disable_internet(*args):
        print("disabling proxy!")
        client.status = False
        sudoPassword = "******"
        command = "service squid stop"
        p = os.system("echo %s|sudo -S %s" % (sudoPassword, command))

    def on_enable_internet(*args):
        print("enabling proxy!")
        client.status = True
        sudoPassword = "******"
        command = "service squid restart"
        p = os.system("echo %s|sudo -S %s" % (sudoPassword, command))

    def on_get_internet_status(*args):
        print("checking status!")
        self.socketio.emit("internetStatus", client.status)

    def loop(self):
        self.end = time.process_time()
        diffInMilliSeconds = (self.end - self.start) * 1000
        if (diffInMilliSeconds > 1000 * 60 * 5):
            self.socketio.emit("join", "proxy")
            self.start = time.process_time()
コード例 #15
0
 def connectWSock(self):
     try:
         socketIO = SocketIO(self.operationConfigs['SOCK_ENDPOINT'], 3000, cookies={'sessionId': s.csrftoken},
                             wait_for_connection=False)
         socketIO.on('connect', on_connect)
         socketIO.on('/devices/updated', self.on_updated)
         socketIO.on('disconnect', on_disconnect)
         socketIO.on('reconnect', on_reconnect)
         socketIO.wait()
     except ConnectionError:
         logging.warning('Error connecting WebSockets\n')
コード例 #16
0
def socketio(
    url,
    callback,
    channel="",
    field="",
    sendinit=None,
    json=False,
    wrap=False,
    interval=1,
):
    """Connect to socketIO server and pipe results through the callback

    Args:
        url (str): url to connect to
        callback (callable): function to call on websocket data
        channel (str): socketio channel to connect through
        field (str): field to index result by
        sendinit (list): data to send on socketio connection open
        json (bool): load websocket data as json
        wrap (bool): wrap result in a list
        interval (int): socketio wai interval
    """
    from socketIO_client_nexus import SocketIO as SIO

    o = urlparse(url)
    socketIO = SIO(o.scheme + "://" + o.netloc, o.port)
    if sendinit:
        socketIO.emit(sendinit)

    while True:
        _data = []
        socketIO.on(channel, lambda data: _data.append(data))
        socketIO.wait(seconds=interval)
        for msg in _data:
            if json:
                msg = json.loads(msg)

            if field:
                msg = msg[field]

            if wrap:
                msg = [msg]

            callback(msg)
コード例 #17
0
def calibrate_PH():
    """
    This function creates a client endpoint in socket connection between nodeJS
    and python process, listens continuosly to socketIO event, calibrates PH-circuit
    with received information.
    If calibration succeed, send back a success message.
    Else, send back an error message.
    """
    devices    = AtlasI2C();
    socket_url = "localhost"

    socketIO = SocketIO(socket_url, 9000, verify=False)
    def start_calibrate(*arg):
        try:
            print(arg)
            a  = arg[0][u'data']
            print(a)
            commandList = { "low": "cal,low,4", "medium": "cal,mid,7","high":"cal,high,10"}
            command = commandList.get(a)
            logger.info(command)
            mutex.acquire()
            tempRecalibration = "T,"+str(measure_temperature(26))
            devices.query(tempRecalibration)
            sleep(0.3)
            devices.query(command)
            sleep(0.3)
            status = devices.query('cal,?')
            status = status[-1]
            socketIO.emit('success',status)
            f = open("/home/pi/Public/main/Server/status.txt","w+")
            f.write(status)
            f.close()
            logger.info("Calibration Command Successful,"+str(a))
            mutex.release()
        except :
            socketIO.emit("error")
            logger.debug("Wrong Command")
    socketIO.on('send_data',start_calibrate) #Listen to calibrating event
    socketIO.wait()
    while True: #keep the thread alive to continue listening to socket event
        pass
コード例 #18
0
ファイル: input.py プロジェクト: yijxiang/tributary
def socketio(url, callback, channel='', field='', sendinit=None, json=False, wrap=False, interval=1):
    o = urlparse(url)
    socketIO = SIO(o.scheme + '://' + o.netloc, o.port)
    if sendinit:
        socketIO.emit(sendinit)

    while True:
        _data = []
        socketIO.on(channel, lambda data: _data.append(data))
        socketIO.wait(seconds=interval)
        for msg in _data:
            if json:
                msg = json.loads(msg)

            if field:
                msg = msg[field]

            if wrap:
                msg = [msg]

            callback(msg)
コード例 #19
0
class TwoWayClient(object):
    def __init__(self):
        self.socketIO = SocketIO(host, port)

        def on_socket_open(*args):
            print("on_socket_open: ", args[0])
            self.socketIO.emit('agent_alive', {
                'task_group_id': 'test_group',
                'agent_id': '[World]'
            })

        def on_disconnect(*args):
            print("Server disconnected", args[0])

        def on_new_messgae(*args):
            print(args[0])

        self.socketIO.on('socket_open', on_socket_open)
        self.socketIO.on('disconnect', on_disconnect)  # This works
        self.socketIO.on('new_message', on_new_messgae)

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

        while True:
            some_input = input("Hit ENTER to send message:")
            self.socketIO.emit('new_message', {
                'task_group_id': 'test_group',
                'receiver_agent_id': 'Worker'
            })

    def _receive_events_thread(self):
        self.socketIO.wait()
コード例 #20
0
    def init(self, win):

        self.win = win
        print("Connecting to", win.server, LoggingNamespace)
        socketIO = SocketIO(win.server, 80)
        socketIO.on('connect', self.on_connect)
        socketIO.on('disconnect', self.on_disconnect)
        socketIO.on('reconnect', self.on_connect)
        socketIO.on('dev_online', self.on_device_connected)
        self.socketIO = socketIO

        thrd = threading.Thread(target=socketIO.wait)
        thrd.daemon = True
        thrd.start()
コード例 #21
0
ファイル: test_socket_relay.py プロジェクト: ahiroto/ParlAI
class TwoWayClient(object):
    def __init__(self):
        self.socketIO = SocketIO(host, port)
        
        def on_socket_open(*args):
            print("on_socket_open: ", args[0])
            self.socketIO.emit('agent_alive', {'task_group_id': 'test_group', 'agent_id': '[World]'})

        def on_disconnect(*args):
            print("Server disconnected", args[0])

        def on_new_messgae(*args):
            print(args[0])

        self.socketIO.on('socket_open', on_socket_open)
        self.socketIO.on('disconnect', on_disconnect) # This works
        self.socketIO.on('new_message', on_new_messgae)

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

        while True:
            some_input = input("Hit ENTER to send message:")
            self.socketIO.emit('new_message', {'task_group_id': 'test_group', 'receiver_agent_id': 'Worker'})

    def _receive_events_thread(self):
        self.socketIO.wait()
コード例 #22
0
class socket:
    def __init__(self, id):
        self.id = id
        self.socketIO = None
        self.token = None
        self.missatge_doctor = None
        self.esperar = True
        self.createsocket(id)

    def desconectar(self, id):
        self.socketIO.emit('disconnect', {'id': id})

    def createsocket(self, id):
        print id
        self.socketIO = SocketIO('https://ptin2018.herokuapp.com',
                                 params={"id": id})
        print "Socket creado"
        self.socketIO.wait(seconds=3)

    def receive_general(self, *args):
        print "Recibido"
        print args[0]
        self.token = args[0]

    def response(self, *args):
        print "response"
        print args

    def response_doctor(self, *args):
        print "response doctor"
        print args
        self.missatge_doctor = args
        self.esperar = False

    def envia_confirmacio(self):
        self.socketIO.wait(seconds=1)
        self.socketIO.emit('generalAuthentication', {
            'requester': self.id,
            'token': self.token
        })
        self.socketIO.on("generalResponse", self.response)
        self.socketIO.wait(seconds=1)

    def esperar_doctor(self):
        self.socketIO.on('pacientLocation', self.response_doctor)
        while self.esperar:
            self.socketIO.wait(seconds=3)
        self.esperar = True
        return self.missatge_doctor

    def envia_general(self, lat, lon):
        self.socketIO.emit('alarm', {
            'type': 2,
            'latitude': lat,
            'longitude': lon
        })
        print self.socketIO
        self.socketIO.on("generalAuthentication", self.receive_general)
        self.socketIO.wait(seconds=1)
コード例 #23
0
def websocket_config():
    socket = SocketIO(SOCKET_ADDR, SOCKET_PORT, LoggingNamespace)
    socket.on('connect', on_connect)
    socket.on('disconnect', on_disconnect)
    socket.on('reconnect', on_reconnect)

    logging.getLogger('socketIO-client').setLevel(logging.DEBUG)
    logging.basicConfig()
    return socket
コード例 #24
0
ファイル: ServerToPI.py プロジェクト: Penjiboy/Smartlock-IoT
pwm.start(float(85) / 10.0 + 2.5)

from socketIO_client_nexus import SocketIO, LoggingNamespace

Sock = SocketIO('38.88.74.79', 80)


def unlock():
    duty = float(185) / 10.0 + 2.5
    pwm.ChangeDutyCycle(duty)
    #start = time.time()
    print("door unlocked")


def lock():
    duty = float(85) / 10.0 + 2.5
    pwm.ChangeDutyCycle(duty)
    print("door locked")


def status(*args):
    if args[0] == 1: lock()
    elif args[0] == 0: unlock()
    else: print("error")


while True:
    #print("waiting\n")
    Sock.on("lockChanged", status)
    Sock.wait(seconds=1)
コード例 #25
0
ファイル: init_v21.py プロジェクト: g4w4/pyclient
                    elif message.type == 'video':
                        content =  str(message.save_media(pathSource,True))
                        socketIO.emit('newMessage',{'chat':message.sender.id,'message':content,'type':'video','caption':message.caption})
                    elif message.type == 'document':
                        content =  str(message.save_media(pathSource,True))
                        socketIO.emit('newMessage',{'chat':message.sender.id,'message':content,'type':'file','caption':message.caption})
                    elif message.type == 'audio' or message.type == 'ptt':
                        content =  str(message.save_media(pathSource,True))
                        os.rename(content, content+'.ogg')
                        socketIO.emit('newMessage',{'chat':message.sender.id,'message':content+'.ogg','type':'ogg','caption':message.caption})
                    else:
                        socketIO.emit('newMessage',{'chat':message.sender.id,'message':'Contenido No soportado'})


##### SOCKET LISSENER #####
socketIO.on('connect', on_connect)
socketIO.on('welcome', on_welcome)
socketIO.on('reconnect', on_reconnect)
socketIO.on('getQr',on_getQr)
socketIO.on('matchUpdate',on_matchUpdate)
socketIO.on('giveScreen',on_giveScreen)
socketIO.on('sendText',on_sendText)
socketIO.on('sendFile',on_sendFile)
socketIO.on('deleteChat',on_deleteChat)

socketIO.wait()


# def on_sendFile(*args):
#    try:
#         id = args[0][0]
コード例 #26
0
ファイル: init.py プロジェクト: g4w4/pyclient
            wsp['data'] = {'status': 'success', 'data': messagesArray}
            wsp['success'] = 'ok'
            socketIO.emit('sendAllMessages', wsp)

        else:

            wsp['success'] = 'desc'
            socketIO.emit('sendAllMessages', wsp)
    except:
        wsp['success'] = 'errorGetMessages'
        socketIO.emit('sendAllMessages', wsp)


# Auth #
socketIO.on('connect', on_connect)
socketIO.on('welcome', on_welcome)
socketIO.on('disconnect', on_disconnect)
socketIO.on('reconnect', on_reconnect)

# Connection Driver #
socketIO.on('getQr', on_getQr)
socketIO.on('getStatus', on_getStatus)
socketIO.on('getChatList', on_getChatList)
socketIO.on('sendMessage', on_sendMessage)
socketIO.on('sendMedia', on_sendMedia)
socketIO.on('getMessages', on_getMessages)

# # Listen
# socketIO.on('aaa_response', on_aaa_response)
# socketIO.emit('aaa')
コード例 #27
0
def main(_):
    counter = 0
    # Definition of the paths
    weights_path = 'yolov2-tiny-voc.weights'
    input_img_path = 'test_zzh_1.jpg'
    output_image_path = 'output/zzh_out.jpg'

    # If you do not have the checkpoint yet keep it like this! When you will run test.py for the first time it will be created automatically
    ckpt_folder_path = './ckpt/'

    # Definition of the parameters
    input_height = 416
    input_width = 416
    score_threshold = 0.1
    iou_threshold = 0.1

    # Definition of the session
    sess = tf.InteractiveSession()

    tf.global_variables_initializer().run()

    # Check for an existing checkpoint and load the weights (if it exists) or do it from binary file
    print('Looking for a checkpoint...')
    saver = tf.train.Saver()
    _ = weights_loader.load(sess, weights_path, ckpt_folder_path, saver)

    # ---------------------q-learning---------------------

    N_STATES = [1, 2, 3, 4, 5, 6, 7, 8, 9]  # 9种states
    ACTIONS = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]  # 可能的actions
    EPSILON = 0.9  # greedy policy 的概率
    ALPHA = 0.1  # for learning rate 的大小
    GAMMA = 0.9  # for discount factor 的大小
    episode = 0

    q_table = q_learning.build_q_table(N_STATES, ACTIONS)  # Initialize Q(s, a)
    print(q_table)
    step_counter = 0  # init step
    S = 1  # init state
    q_learning.update_env(episode, step_counter)  # update env

    # ---------------------q-learning---------------------

    # ------------------------预定义和加载数据-----------------------
    # -----------------连接目标服务器-------------------------------
    socketIO = SocketIO('10.8.204.12', 3333, LoggingNamespace)
    socketIO.on('connection', on_connect)
    socketIO.on('disconnect', on_disconnect)
    socketIO.on('reconnect', on_reconnect)
    # -------------------------------------------------------------
    time_1 = 0
    time_2 = 0
    Fps_past = 0
    Fps = 0

    host = '127.0.0.1'
    port = 12345
    buffsize = 65535

    ADDR = (host, port)

    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    soc.bind(ADDR)
    soc.listen(2)

    print('Wait for connection ...')
    soc_client, addr = soc.accept()
    print("Connection from :", addr)

    # 进行长连接不断接受信号, 每次data=的时候都会刷新所有接收到的值
    while True:
        data = ""
        data = soc_client.recv(buffsize).decode()
        while True:
            # data为初始化值是系统等待, 以防while占用太大的运算量
            if data == "":
                time.sleep(0.1)
            else:
                break
        # 服务器端 send 各个命令执行的操作
        if data == "time_start":
            # 用来记录总时间 (未用到)
            start_time = time.time()
            print(start_time)
            soc_client.send("done".encode())

        elif data == "time_stop":
            # 结束记录总时间 (未用到)
            stop_time = time.time()
            total_time = stop_time - start_time
            print(total_time)
            soc_client.send("done".encode())

        elif data == "finish":
            # 用来结束连接(未用到)
            soc_client.close()

        elif data == "time_1":
            # 用来接受time_1信息(初始化时间长度)
            soc_client.send("recive".encode())
            time_1 = soc_client.recv(buffsize).decode()
            time_1 = float(time_1)
            soc_client.send("done".encode())

        elif data == "time_2":
            # 用来接受time_2信息 (处理的时间长度)
            soc_client.send("recive".encode())
            time_2 = soc_client.recv(buffsize).decode()
            time_2 = float(time_2)
            soc_client.send("done".encode())

        elif data == "send_original_image":
            # 用来接受输出的原始图像 (记录下下载图像的时间为 recive_time)
            soc_client.send("recive".encode())
            recive_time = time.time()
            data_batches = ""
            new_data = ""

            # 开始下载
            print("downloading...")
            while True:
                new_data = soc_client.recv(buffsize).decode()

                # 结束时的处理
                if ((new_data[-1] == '%')):
                    data_batches = data_batches + new_data[:-1]
                    break
                # 循环体
                data_batches = data_batches + new_data

            print("processing...")
            # 加载下载的原图像解析为np array(注意imshow输出时要转化成np.uint8格式否则会黑屏)(<-坑)
            data_text = json.loads(data_batches)
            input_image = np.array(data_text)

            # 下载时间记录 (下载 + 解析)
            recive_time = time.time() - recive_time
            print("total time: {}".format(recive_time))
            soc_client.send("done".encode())

        elif data == "send_weight_cutpoint":
            # ---------------------q-learning---------------------
            Fps_past = Fps
            A = q_learning.choose_action(S, q_table, EPSILON)

            # ---------------------q-learning---------------------

            soc_client.send("{}".format(A).encode())
            # 记录时间 p4
            point_4 = time.time()
            data_batches = ""
            new_data = ""
            cut_point = ""

            # 开始下载
            print("downloading...")
            while True:
                new_data = soc_client.recv(buffsize).decode()
                # 结束时的处理 (cut point 作为倒数第二个值被接受在新变量中)
                if ((new_data[-1] == '%')):
                    data_batches = data_batches + new_data[:-2]
                    cut_point = new_data[-2:-1]
                    # print(cut_point)
                    break
                # 循环体
                data_batches = data_batches + new_data

            # 记录时间 p5 (time_3 为下载weight的时间)
            point_5 = time.time()
            time_3 = point_5 - point_4
            print("downloading time: {}".format(time_3))

            print("processing...")
            # 加载和解析数据
            data_text = json.loads(data_batches)
            predictions = np.array(data_text)
            cut_point = int(cut_point)
            predictions = inference(sess, predictions, cut_point)

            # 记录时间 p6 (time_4 为解析数据的时间)
            point_6 = time.time()
            time_4 = point_6 - point_5
            print("processing time: {}".format(time_4))

            print('Postprocessinasg...')
            # out_put images
            output_image = postprocessing(predictions, input_image,
                                          score_threshold, iou_threshold,
                                          input_height, input_width)
            # 记录时间 p7
            # time_5 为后处理的时间
            # 计算出后端的运行时间,中间的下载时间, 前端的预处理时间(不包括初始化时间),算出fps
            point_7 = time.time()
            time_5 = point_7 - point_6
            time_backend = time_4 + time_5
            time_downloading = time_3 + recive_time
            time_frontend = time_2
            time_total = time_backend + time_frontend + time_downloading
            Fps = 1. / time_total
            fps = "fps = {}".format(Fps)

            # 将图像格式转换成uint8 否则黑屏
            # 输出fps, 输出处理后的图像
            output_image = np.uint8(output_image)
            cv2.putText(output_image, str(fps), (5, 15),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 0, 255), 1)
            #cv2.imshow("hello", output_image)
            #if cv2.waitKey(1) & 0xFF == ord('q'):
            #break

            # 打印出所有可能用到的时间
            counter += 1
            print("time_load_model = {}".format(time_1))
            print("time_preprocess = {}".format(time_2))
            print("time_send_original_image = {}".format(recive_time))
            print("time_downloading = {}".format(time_downloading))
            print("time_load_jsons = {}".format(time_4))
            print("time_postprocess = {}".format(time_5))
            print("time_backend = {}".format(time_backend))
            print("time_frontend = {}".format(time_frontend))
            print("Fps = {}".format(Fps))

            # ---------------------q-learning---------------------

            S_, R = q_learning.get_env_feedback(A, Fps_past, Fps)
            print(str(S_) + "  " + str(S))
            q_predict = q_table.loc[S, A]
            with pd.option_context('display.max_rows', None,
                                   'display.max_columns', None):
                print(q_table)
            q_target = R + GAMMA * q_table.loc[S_, :].max(skipna=True)
            q_table.loc[S, A] += ALPHA * (q_target - q_predict)  # q_table 更新
            S = S_  # 探索者移动到下一个 state
            q_learning.update_env(episode, step_counter + 1)  # 环境更新

            step_counter += 1

            # ---------------------q-learning---------------------
            #--------------------多线程发送------------
            # Create a thread
            thread_socketIO = myThread(1, socketIO, "Frame-" + str(counter),
                                       output_image, Fps, cut_point,
                                       q_table.values)

            # Start a thread
            thread_socketIO.start()
            thread_socketIO.join()
            # --------------------多线程发送------------
            # 返回确认done
            soc_client.send("done".encode())
            # 下一个循环待命

            # ------------send---------
            pass
        else:
            pass
コード例 #28
0
class Client(object):

	def __init__(self):
		self.socketio = SocketIO("http://twitchplaysnintendoswitch.com:8110")

		# self.socketio.on("controllerState1", self.on_controller_state1)
		# self.socketio.on("controllerState2", self.on_controller_state2)
		# self.socketio.on("controllerState3", self.on_controller_state3)
		self.socketio.on("controllerState5", self.on_controller_state1)
		self.socketio.on("turnTimesLeft", self.on_turn_times_left)
		self.socketio.emit("join", "wiiu3dscontroller")

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

		self.start = time.clock()
		self.end = time.clock()
		
		self.botstart = time.clock()
		self.botend = time.clock()

		self.controllerStart = time.clock()
		self.controllerEnd = time.clock()

		self.lockon = False

		self.yeaVotes = 0
		self.nayVotes = 0
		self.voting = False
		self.currentPlayers = []

		self.laglessEnabled = True
		self.currentGame = "none"

		self.oldArgs2 = "800000000000000 128 128 128 128"




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

	def on_event(self, event):
		#print(event)
		pass

	def on_controller_command(*args):
		nextCommands.append(args)

	def on_turn_times_left(*args):
		try:
			client.currentPlayers = args[1]["usernames"]
		except:
			pass

	def on_controller_state(*args):

		if(not client.laglessEnabled):
			return

		state = args[1]
		cNum = args[2]

		print("controller state" + str(cNum) + ":", state)

		client.oldArgs2 = state

		controller = None

		if(cNum == 0):
			controller = controller1
		elif(cNum == 1):
			controller = controller2
		elif(cNum == 2):
			return
			cNum = 1
			controller = controller2
		elif(cNum == 3):
			return
			cNum = 1
			controller = controller2
		elif(cNum == 4):
			return
			cNum = 1
			controller = controller2

		controller.reset()

		inputs = state.split()
		cPlayer = ""
		try:
			cPlayer = client.currentPlayers[cNum]
		except:
			pass

		btns = inputs[0]
		LX = inputs[1]
		LY = inputs[2]
		RX = inputs[3]
		RY = inputs[4]

		controller.dpad = int(btns[0])
		if (btns[1] == "1"):
			controller.lstick = 1;
		if (btns[2] == "1"):
			controller.l = 1;
		if (btns[3] == "1"):
			controller.zl = 1;
		if (btns[4] == "1"):
			controller.minus = 1;
		if (btns[5] == "1"):
			try:
				if (cPlayer.lower() in modlist):
					controller.capture = 1
				else:
					controller.capture = 0
			except:
				controller.capture = 0
		if (btns[6] == "1"):
			controller.a = 1;
		if (btns[7] == "1"):
			controller.b = 1;
		if (btns[8] == "1"):
			controller.x = 1;
		if (btns[9] == "1"):
			controller.y = 1;
		if (btns[10] == "1"):
			controller.rstick = 1;
		if (btns[11] == "1"):
			controller.r = 1;
		if (btns[12] == "1"):
			controller.zr = 1;
		if (btns[13] == "1"):
			try:
				if (cPlayer.lower() in pluslist):
					controller.plus = 1
				else:
					controller.plus = 0
			except:
				controller.plus = 0
		if (btns[14] == "1"):
			try:
				if (cPlayer.lower() in modlist):
					controller.home = 1
				else:
					controller.home = 0
			except:
				controller.home = 0

		try:
			controller.LX = int(LX)
			controller.LY = 255-int(LY)
			controller.RX = int(RX)
			controller.RY = 255-int(RY)
		except:
			pass

		duration = 0.001
		reset = 0
		if(cNum == 0):
			send_and_reset(duration, reset)
		elif(cNum == 1):
			send_and_reset2(duration, reset)
		elif(cNum == 2):
			send_and_reset3(duration, reset)
		elif(cNum == 3):
			send_and_reset4(duration, reset)


	# player 1:
	def on_controller_state1(*args):
		client.on_controller_state(args[1], 0)


	def handleChat(self, username, message):
		print(message)

		# handle chat messages here

	def decreaseQueue(self):

		# handle queue from handlechat
		pass


	def loop(self):

		# control switch here:

		# every 5 minutes:
		self.botend = time.clock()
		diffInMilliSeconds = (self.botend - self.botstart)*1000
		if(diffInMilliSeconds > 1000*60*5):
			self.socketio.emit("join", "wiiu3dscontroller")
			self.botstart = time.clock()
			# msg = "Join the discord server! https://discord.gg/ARTbddH\
			# hate the stream delay? go here! https://twitchplaysnintendoswitch.com"
			# twitchBot.chat(msg)

		# every 6 seconds, probably doesn't need to do this so often:
		self.controllerEnd = time.clock()
		diffInMilliSeconds2 = (self.controllerEnd - self.controllerStart)*1000
		if(diffInMilliSeconds2 > 6000):
			self.socketio.emit("join", "wiiu3dscontroller")
			self.controllerStart = time.clock()


		response = twitchBot.stayConnected()
		if(response != "none"):
			# prevent crash
			try:
				username = re.search(r"\w+", response).group(0) # return the entire match
				username = username.lower()
				message = CHAT_MSG.sub("", response)
				message = message.strip()
				message = message.lower()
				self.handleChat(username, message)
			except:
				pass

		self.decreaseQueue()

	def _receive_events_thread(self):
		self.socketio.wait()
コード例 #29
0
ファイル: socket_manager.py プロジェクト: jojonki/ParlAI
class SocketManager():
    """SocketManager is a wrapper around socketIO to stabilize its packet
    passing. The manager handles resending packet, as well as maintaining
    alive status for all the connections it forms
    """

    # Time to acknowledge different message types
    ACK_TIME = {Packet.TYPE_ALIVE: 2,
                Packet.TYPE_MESSAGE: 2}

    # Default time before socket deemed dead
    DEF_SOCKET_TIMEOUT = 8

    def __init__(self, server_url, port, alive_callback, message_callback,
                 socket_dead_callback, task_group_id,
                 socket_dead_timeout=None):
        """
        server_url:           url at which the server is to be run
        port:                 port for the socket to operate on
        alive_callback:       function to be called on alive Packets, defined
                               alive_callback(self, pkt)
        message_callback:     function to be called on message Packets, defined
                               message_callback(self, pkt)
        socket_dead_callback: function to be called when a socket dies, should
                              return false if the socket_manager should ignore
                              the death and treat the socket as alive defined
                               on_socket_dead(self, worker_id, assignment_id)
        socket_dead_timeout:  time to wait between heartbeats before dying
        """
        self.server_url = server_url
        self.port = port
        self.alive_callback = alive_callback
        self.message_callback = message_callback
        self.socket_dead_callback = socket_dead_callback
        if socket_dead_timeout == None:
            self.socket_dead_timeout = self.DEF_SOCKET_TIMEOUT
        else:
            self.socket_dead_timeout = socket_dead_timeout
        self.task_group_id = task_group_id

        self.socketIO = None

        # initialize the state
        self.listen_thread = None
        self.queues = {}
        self.threads = {}
        self.run = {}
        self.last_heartbeat = {}
        self.packet_map = {}

        # setup the socket
        self._setup_socket()

    def get_my_sender_id(self):
        """Gives the name that this socket manager should use for its world"""
        return '[World_{}]'.format(self.task_group_id)

    def _send_world_alive(self):
        """Registers world with the passthrough server"""
        self.socketIO.emit(
            data_model.SOCKET_AGENT_ALIVE_STRING,
            {'id': 'WORLD_ALIVE', 'sender_id': self.get_my_sender_id()}
        )

    def _send_response_heartbeat(self, packet):
        """Sends a response heartbeat to an incoming heartbeat packet"""
        self.socketIO.emit(
            data_model.SOCKET_ROUTE_PACKET_STRING,
            packet.swap_sender().set_data('').as_dict()
        )

    def _send_ack(self, packet):
        """Sends an ack to a given packet"""
        ack = packet.get_ack().as_dict()
        self.socketIO.emit(data_model.SOCKET_ROUTE_PACKET_STRING, ack, None)

    def _send_packet(self, packet, connection_id, send_time):
        """Sends a packet, blocks if the packet is blocking"""
        # Send the packet
        pkt = packet.as_dict()
        shared_utils.print_and_log(
            logging.DEBUG,
            'Send packet: {}'.format(packet.data)
        )
        def set_status_to_sent(data):
            packet.status = Packet.STATUS_SENT
        self.socketIO.emit(
            data_model.SOCKET_ROUTE_PACKET_STRING,
            pkt,
            set_status_to_sent
        )

        # Handles acks and blocking
        if packet.requires_ack:
            if packet.blocking:
                # blocking till ack is received or timeout
                start_t = time.time()
                while True:
                    if packet.status == Packet.STATUS_ACK:
                        # Clear the data to save memory as we no longer need it
                        packet.data = None
                        break
                    if time.time() - start_t > self.ACK_TIME[packet.type]:
                        # didn't receive ACK, resend packet keep old queue time
                        # to ensure this packet is processed first
                        packet.status = Packet.STATUS_INIT
                        self._safe_put(connection_id, (send_time, packet))
                        break
                    time.sleep(shared_utils.THREAD_SHORT_SLEEP)
            else:
                # non-blocking ack: add ack-check to queue
                t = time.time() + self.ACK_TIME[packet.type]
                self._safe_put(connection_id, (t, packet))

    def _setup_socket(self):
        """Create socket handlers and registers the socket"""
        self.socketIO = SocketIO(self.server_url, self.port)

        def on_socket_open(*args):
            shared_utils.print_and_log(
                logging.DEBUG,
                'Socket open: {}'.format(args)
            )
            self._send_world_alive()
            self.alive = True

        def on_disconnect(*args):
            """Disconnect event is a no-op for us, as the server reconnects
            automatically on a retry"""
            shared_utils.print_and_log(
                logging.INFO,
                'World server disconnected: {}'.format(args)
            )
            self.alive = False

        def on_message(*args):
            """Incoming message handler for ACKs, ALIVEs, HEARTBEATs,
            and MESSAGEs"""
            packet = Packet.from_dict(args[0])
            packet_id = packet.id
            packet_type = packet.type
            connection_id = packet.get_sender_connection_id()
            if packet_type == Packet.TYPE_ACK:
                if packet_id not in self.packet_map:
                    # Don't do anything when acking a packet we don't have
                    return
                # Acknowledgements should mark a packet as acknowledged
                shared_utils.print_and_log(
                    logging.DEBUG,
                    'On new ack: {}'.format(args)
                )
                self.packet_map[packet_id].status = Packet.STATUS_ACK
                # If the packet sender wanted to do something on acknowledge
                if self.packet_map[packet_id].ack_func:
                    self.packet_map[packet_id].ack_func(packet)
                # clear the stored packet data for memory reasons
                self.packet_map[packet_id].data = None
            elif packet_type == Packet.TYPE_HEARTBEAT:
                # Heartbeats update the last heartbeat time and respond in kind
                self.last_heartbeat[connection_id] = time.time()
                self._send_response_heartbeat(packet)
            else:
                # Remaining packet types need to be acknowledged
                shared_utils.print_and_log(
                    logging.DEBUG,
                    'On new message: {}'.format(args)
                )
                self._send_ack(packet)
                # Call the appropriate callback
                if packet_type == Packet.TYPE_ALIVE:
                    self.last_heartbeat[connection_id] = time.time()
                    self.alive_callback(packet)
                elif packet_type == Packet.TYPE_MESSAGE:
                    self.message_callback(packet)

        # Register Handlers
        self.socketIO.on(data_model.SOCKET_OPEN_STRING, on_socket_open)
        self.socketIO.on(data_model.SOCKET_DISCONNECT_STRING, on_disconnect)
        self.socketIO.on(data_model.SOCKET_NEW_PACKET_STRING, on_message)

        # Start listening thread
        self.listen_thread = threading.Thread(
            target=self.socketIO.wait,
            name='Main-Socket-Thread'
        )
        self.listen_thread.daemon = True
        self.listen_thread.start()

    def open_channel(self, worker_id, assignment_id):
        """Opens a channel for a worker on a given assignment, doesn't re-open
        if the channel is already open. Handles creation of the thread that
        monitors that channel"""
        connection_id = '{}_{}'.format(worker_id, assignment_id)
        if connection_id in self.queues and self.run[connection_id]:
            shared_utils.print_and_log(
                logging.DEBUG,
                'Channel ({}) already open'.format(connection_id)
            )
            return
        self.run[connection_id] = True
        self.queues[connection_id] = PriorityQueue()

        def channel_thread():
            """Handler thread for monitoring a single channel"""
            # while the thread is still alive
            while self.run[connection_id]:
                try:
                    # Check if client is still alive
                    if (time.time() - self.last_heartbeat[connection_id]
                            > self.socket_dead_timeout):
                        self.run[connection_id] = False
                        self.socket_dead_callback(worker_id, assignment_id)

                    # Make sure the queue still exists
                    if not connection_id in self.queues:
                        self.run[connection_id] = False
                        break

                    # Get first item in the queue, check if we can send it yet
                    item = self.queues[connection_id].get(block=False)
                    t = item[0]
                    if time.time() < t:
                        # Put the item back into the queue,
                        # it's not time to pop yet
                        self._safe_put(connection_id, item)
                    else:
                        # Try to send the packet
                        packet = item[1]
                        if not packet:
                            # This packet was deleted out from under us
                            continue
                        if packet.status is not Packet.STATUS_ACK:
                            # either need to send initial packet
                            # or resend not-acked packet
                            self._send_packet(packet, connection_id, t)
                except Empty:
                    pass
                finally:
                    time.sleep(shared_utils.THREAD_MEDIUM_SLEEP)

        # Setup and run the channel sending thread
        self.threads[connection_id] = threading.Thread(
            target=channel_thread,
            name='Socket-Queue-{}'.format(connection_id)
        )
        self.threads[connection_id].daemon = True
        self.threads[connection_id].start()

    def close_channel(self, connection_id):
        """Closes a channel by connection_id"""
        shared_utils.print_and_log(
            logging.DEBUG,
            'Closing channel {}'.format(connection_id)
        )
        self.run[connection_id] = False
        if connection_id in self.queues:
            # Clean up packets
            packet_ids = list(self.packet_map.keys())
            for packet_id in packet_ids:
                if connection_id == \
                       self.packet_map[packet_id].get_receiver_connection_id():
                    del self.packet_map[packet_id]
            # Clean up other resources
            del self.queues[connection_id]
            del self.threads[connection_id]

    def delay_heartbeat_until(self, connection_id, delayed_time):
        """Delay a heartbeat prolong a disconnect until delayed_time"""
        self.last_heartbeat[connection_id] = delayed_time

    def close_all_channels(self):
        """Closes a channel by clearing the list of channels"""
        shared_utils.print_and_log(logging.DEBUG, 'Closing all channels')
        connection_ids = list(self.queues.keys())
        for connection_id in connection_ids:
            self.close_channel(connection_id)

    def socket_is_open(self, connection_id):
        return connection_id in self.queues

    def queue_packet(self, packet):
        """Queues sending a packet to its intended owner"""
        connection_id = packet.get_receiver_connection_id()
        if not self.socket_is_open(connection_id):
            # Warn if there is no socket to send through for the expected recip
            shared_utils.print_and_log(
                logging.WARN,
                'Can not send packet to worker_id {}: packet queue not found. '
                'Message: {}'.format(connection_id, packet.data)
            )
            return
        shared_utils.print_and_log(
            logging.DEBUG,
            'Put packet ({}) in queue ({})'.format(packet.id, connection_id)
        )
        # Get the current time to put packet into the priority queue
        self.packet_map[packet.id] = packet
        item = (time.time(), packet)
        self._safe_put(connection_id, item)

    def get_status(self, packet_id):
        """Returns the status of a particular packet by id"""
        return self.packet_map[packet_id].status

    def _safe_put(self, connection_id, item):
        """Ensures that a queue exists before putting an item into it, logs
        if there's a failure
        """
        if connection_id in self.queues:
            self.queues[connection_id].put(item)
        else:
            shared_utils.print_and_log(
                logging.WARN,
                'Queue {} did not exist to put a message in'.format(
                    connection_id
                )
            )
コード例 #30
0

def on_connect(self):
    print('[Connected]')


def on_reconnect(self):
    print('[Reconnected]')


def on_disconnect(self):
    print('[Disconnected]')


socketIO = SocketIO(WS_HOST, WS_PORT, LoggingNamespace)
socketIO.on('chiotte_response', on_chiotte_response)

distance_in_mm_old = 0
while running:
    distance_in_mm = tof.get_distance()
    if (distance_in_mm != distance_in_mm_old and 100 <= distance_in_mm <= 230):
        distance_in_mm_old = distance_in_mm
        data = json.dumps({
            "id": ID,
            "gender": POOP_LOCATION,
            "pq": distance_in_mm
        })
        print(data)
        socketIO.emit('chiotte', data)
        time.sleep(0.5)
コード例 #31
0
class SocketManager():
    """SocketManager is a wrapper around socketIO to stabilize its packet
    passing. The manager handles resending packet, as well as maintaining
    alive status for all the connections it forms
    """

    # Time to acknowledge different message types
    ACK_TIME = {Packet.TYPE_ALIVE: 2, Packet.TYPE_MESSAGE: 2}

    # Default time before socket deemed dead
    DEF_SOCKET_TIMEOUT = 8

    def __init__(self,
                 server_url,
                 port,
                 alive_callback,
                 message_callback,
                 socket_dead_callback,
                 task_group_id,
                 socket_dead_timeout=None):
        """
        server_url:           url at which the server is to be run
        port:                 port for the socket to operate on
        alive_callback:       function to be called on alive Packets, defined
                               alive_callback(self, pkt)
        message_callback:     function to be called on message Packets, defined
                               message_callback(self, pkt)
        socket_dead_callback: function to be called when a socket dies, should
                              return false if the socket_manager should ignore
                              the death and treat the socket as alive defined
                               on_socket_dead(self, worker_id, assignment_id)
        socket_dead_timeout:  time to wait between heartbeats before dying
        """
        self.server_url = server_url
        self.port = port
        self.alive_callback = alive_callback
        self.message_callback = message_callback
        self.socket_dead_callback = socket_dead_callback
        if socket_dead_timeout == None:
            self.socket_dead_timeout = self.DEF_SOCKET_TIMEOUT
        else:
            self.socket_dead_timeout = socket_dead_timeout
        self.task_group_id = task_group_id

        self.socketIO = None

        # initialize the state
        self.listen_thread = None
        self.queues = {}
        self.threads = {}
        self.run = {}
        self.last_heartbeat = {}
        self.packet_map = {}

        # setup the socket
        self._setup_socket()

    def get_my_sender_id(self):
        """Gives the name that this socket manager should use for its world"""
        return '[World_{}]'.format(self.task_group_id)

    def _send_world_alive(self):
        """Registers world with the passthrough server"""
        self.socketIO.emit(data_model.SOCKET_AGENT_ALIVE_STRING, {
            'id': 'WORLD_ALIVE',
            'sender_id': self.get_my_sender_id()
        })

    def _send_response_heartbeat(self, packet):
        """Sends a response heartbeat to an incoming heartbeat packet"""
        self.socketIO.emit(data_model.SOCKET_ROUTE_PACKET_STRING,
                           packet.swap_sender().set_data('').as_dict())

    def _send_ack(self, packet):
        """Sends an ack to a given packet"""
        ack = packet.get_ack().as_dict()
        self.socketIO.emit(data_model.SOCKET_ROUTE_PACKET_STRING, ack, None)

    def _send_packet(self, packet, connection_id, send_time):
        """Sends a packet, blocks if the packet is blocking"""
        # Send the packet
        pkt = packet.as_dict()
        print_and_log('Send packet: {}'.format(packet.data))

        def set_status_to_sent(data):
            packet.status = Packet.STATUS_SENT

        self.socketIO.emit(data_model.SOCKET_ROUTE_PACKET_STRING, pkt,
                           set_status_to_sent)

        # Handles acks and blocking
        if packet.requires_ack:
            if packet.blocking:
                # blocking till ack is received or timeout
                start_t = time.time()
                while True:
                    if packet.status == Packet.STATUS_ACK:
                        # Clear the data to save memory as we no longer need it
                        packet.data = None
                        break
                    if time.time() - start_t > self.ACK_TIME[packet.type]:
                        # didn't receive ACK, resend packet keep old queue time
                        # to ensure this packet is processed first
                        packet.status = Packet.STATUS_INIT
                        self._safe_put(connection_id, (send_time, packet))
                        break
                    time.sleep(THREAD_SHORT_SLEEP)
            else:
                # non-blocking ack: add ack-check to queue
                t = time.time() + self.ACK_TIME[packet.type]
                self._safe_put(connection_id, (t, packet))

    def _setup_socket(self):
        """Create socket handlers and registers the socket"""
        self.socketIO = SocketIO(self.server_url, self.port)

        def on_socket_open(*args):
            print_and_log('Socket open: {}'.format(args), False)
            self._send_world_alive()
            self.alive = True

        def on_disconnect(*args):
            """Disconnect event is a no-op for us, as the server reconnects
            automatically on a retry"""
            print_and_log('World server disconnected: {}'.format(args), False)
            self.alive = False

        def on_message(*args):
            """Incoming message handler for ACKs, ALIVEs, HEARTBEATs,
            and MESSAGEs"""
            packet = Packet.from_dict(args[0])
            packet_id = packet.id
            packet_type = packet.type
            connection_id = packet.get_sender_connection_id()
            if packet_type == Packet.TYPE_ACK:
                if packet_id not in self.packet_map:
                    # Don't do anything when acking a packet we don't have
                    return
                # Acknowledgements should mark a packet as acknowledged
                print_and_log('On new ack: {}'.format(args), False)
                self.packet_map[packet_id].status = Packet.STATUS_ACK
                # If the packet sender wanted to do something on acknowledge
                if self.packet_map[packet_id].ack_func:
                    self.packet_map[packet_id].ack_func(packet)
                # clear the stored packet data for memory reasons
                self.packet_map[packet_id].data = None
            elif packet_type == Packet.TYPE_HEARTBEAT:
                # Heartbeats update the last heartbeat time and respond in kind
                self.last_heartbeat[connection_id] = time.time()
                self._send_response_heartbeat(packet)
            else:
                # Remaining packet types need to be acknowledged
                print_and_log('On new message: {}'.format(args), False)
                self._send_ack(packet)
                # Call the appropriate callback
                if packet_type == Packet.TYPE_ALIVE:
                    self.last_heartbeat[connection_id] = time.time()
                    self.alive_callback(packet)
                elif packet_type == Packet.TYPE_MESSAGE:
                    self.message_callback(packet)

        # Register Handlers
        self.socketIO.on(data_model.SOCKET_OPEN_STRING, on_socket_open)
        self.socketIO.on(data_model.SOCKET_DISCONNECT_STRING, on_disconnect)
        self.socketIO.on(data_model.SOCKET_NEW_PACKET_STRING, on_message)

        # Start listening thread
        self.listen_thread = threading.Thread(target=self.socketIO.wait,
                                              name='Main-Socket-Thread')
        self.listen_thread.daemon = True
        self.listen_thread.start()

    def open_channel(self, worker_id, assignment_id):
        """Opens a channel for a worker on a given assignment, doesn't re-open
        if the channel is already open. Handles creation of the thread that
        monitors that channel"""
        connection_id = '{}_{}'.format(worker_id, assignment_id)
        if connection_id in self.queues and self.run[connection_id]:
            print_and_log('Channel ({}) already open'.format(connection_id),
                          False)
            return
        self.run[connection_id] = True
        self.queues[connection_id] = PriorityQueue()

        def channel_thread():
            """Handler thread for monitoring a single channel"""
            # while the thread is still alive
            while self.run[connection_id]:
                try:
                    # Check if client is still alive
                    if (time.time() - self.last_heartbeat[connection_id] >
                            self.socket_dead_timeout):
                        self.run[connection_id] = False
                        self.socket_dead_callback(worker_id, assignment_id)

                    # Make sure the queue still exists
                    if not connection_id in self.queues:
                        self.run[connection_id] = False
                        break

                    # Get first item in the queue, check if we can send it yet
                    item = self.queues[connection_id].get(block=False)
                    t = item[0]
                    if time.time() < t:
                        # Put the item back into the queue,
                        # it's not time to pop yet
                        self._safe_put(connection_id, item)
                    else:
                        # Try to send the packet
                        packet = item[1]
                        if not packet:
                            # This packet was deleted out from under us
                            continue
                        if packet.status is not Packet.STATUS_ACK:
                            # either need to send initial packet
                            # or resend not-acked packet
                            self._send_packet(packet, connection_id, t)
                except Empty:
                    pass
                finally:
                    time.sleep(THREAD_MEDIUM_SLEEP)

        # Setup and run the channel sending thread
        self.threads[connection_id] = threading.Thread(
            target=channel_thread,
            name='Socket-Queue-{}'.format(connection_id))
        self.threads[connection_id].daemon = True
        self.threads[connection_id].start()

    def close_channel(self, connection_id):
        """Closes a channel by connection_id"""
        print_and_log('Closing channel {}'.format(connection_id), False)
        self.run[connection_id] = False
        if connection_id in self.queues:
            # Clean up packets
            packet_ids = list(self.packet_map.keys())
            for packet_id in packet_ids:
                if connection_id == \
                       self.packet_map[packet_id].get_receiver_connection_id():
                    del self.packet_map[packet_id]
            # Clean up other resources
            del self.queues[connection_id]
            del self.threads[connection_id]

    def delay_heartbeat_until(self, connection_id, delayed_time):
        """Delay a heartbeat prolong a disconnect until delayed_time"""
        self.last_heartbeat[connection_id] = delayed_time

    def close_all_channels(self):
        """Closes a channel by clearing the list of channels"""
        print_and_log('Closing all channels')
        connection_ids = list(self.queues.keys())
        for connection_id in connection_ids:
            self.close_channel(connection_id)

    def socket_is_open(self, connection_id):
        return connection_id in self.queues

    def queue_packet(self, packet):
        """Queues sending a packet to its intended owner"""
        connection_id = packet.get_receiver_connection_id()
        if not self.socket_is_open(connection_id):
            # Warn if there is no socket to send through for the expected recip
            print_and_log(
                'Can not send packet to worker_id {}: packet queue not found. '
                'Message: {}'.format(connection_id, packet.data))
            return
        print_and_log(
            'Put packet ({}) in queue ({})'.format(packet.id, connection_id),
            False)
        # Get the current time to put packet into the priority queue
        self.packet_map[packet.id] = packet
        item = (time.time(), packet)
        self._safe_put(connection_id, item)

    def get_status(self, packet_id):
        """Returns the status of a particular packet by id"""
        return self.packet_map[packet_id].status

    def _safe_put(self, connection_id, item):
        """Ensures that a queue exists before putting an item into it, logs
        if there's a failure
        """
        if connection_id in self.queues:
            self.queues[connection_id].put(item)
        else:
            print_and_log('Queue {} did not exist to put a message in'.format(
                connection_id))
コード例 #32
0

def on_Response_B(*args):
    print('I got a reponse from server for event_B', args)


def on_Response_C(*args):
    print('I got a reponse from server for event_C', args)


def FuncA():
    print('FuncA: Now I got a message from server.')


socketIO = SocketIO('localhost', 3000, LoggingNamespace)
socketIO.on('connect', on_connect)
socketIO.on('disconnect', on_disconnect)
socketIO.on('reconnect', on_reconnect)
socketIO.on('event_A', FuncA)
# Listen
socketIO.on('Response_B', on_Response_B)
socketIO.emit('event_B')
socketIO.emit('event_B')
socketIO.wait(seconds=1)

# Stop listening
socketIO.off('Response_B')
socketIO.emit('event_B')
socketIO.wait(seconds=1)

# Listen only once
コード例 #33
0
from socketIO_client_nexus import SocketIO
import json

socketIO = SocketIO('localhost', 3000)


def welcome():
    print('welcome received')


socketIO.on('welcome', welcome)

message = {
    'name': 'hoang',
    'ids': ['54fjadb70f9756', '39f1ax451f6567'],
    'relation': 'nguoi la',
    'date': '06/05/2018'
}

socketIO.emit('client-event', json.loads(json.dumps(message)))

socketIO.wait()
コード例 #34
0
ファイル: message_socket.py プロジェクト: ahiroto/ParlAI
class MessageSocket():
    """MessageSocket is a wrapper around socketIO to simplify message sends
    and recieves into parlai from FB messenger.
    """

    def __init__(self, server_url, port, secret_token, message_callback):
        """
        server_url:           url at which the server is to be run
        port:                 port for the socket to operate on
        message_callback:     function to be called on incoming message objects
                              format: message_callback(self, data)
        """
        self.server_url = server_url
        self.port = port
        self.message_callback = message_callback

        self.socketIO = None
        self.auth_args = {'access_token': secret_token}

        # initialize the state
        self.listen_thread = None

        # setup the socket
        self._setup_socket()

    def _send_world_alive(self):
        """Registers world with the passthrough server"""
        self.socketIO.emit(
            'world_alive', {'id': 'WORLD_ALIVE', 'sender_id': 'world'}
        )

    def send_fb_payload(self, receiver_id, payload):
        """Sends a payload to messenger, processes it if we can"""
        api_address = 'https://graph.facebook.com/v2.6/me/messages'
        if payload['type'] == 'list':
            data = create_compact_list_message(payload['data'])
        else:
            data = payload['data']
        message = {
            "messaging_type": 'RESPONSE',
            "recipient": {
                "id": receiver_id
            },
            "message": {
                "attachment": data,
            }
        }
        response = requests.post(
            api_address,
            params=self.auth_args,
            json=message,
        )
        result = response.json()
        shared_utils.print_and_log(
            logging.INFO,
            '"Facebook response from message send: {}"'.format(result)
        )
        return result

    def send_fb_message(self, receiver_id, message, is_response,
                        quick_replies=None):
        """Sends a message directly to messenger"""
        api_address = 'https://graph.facebook.com/v2.6/me/messages'
        if quick_replies is not None:
            quick_replies = [create_reply_option(x, x) for x in quick_replies]
        ms = create_text_message(message, quick_replies)
        results = []
        for m in ms:
            if m['text'] == '':
                continue  # Skip blank messages
            payload = {
                "messaging_type": 'RESPONSE' if is_response else 'UPDATE',
                "recipient": {
                    "id": receiver_id
                },
                "message": m
            }
            response = requests.post(
                api_address,
                params=self.auth_args,
                json=payload
            )
            result = response.json()
            shared_utils.print_and_log(
                logging.INFO,
                '"Facebook response from message send: {}"'.format(result)
            )
            results.append(result)
        return results

    def _setup_socket(self):
        """Create socket handlers and registers the socket"""
        self.socketIO = SocketIO(self.server_url, self.port)

        def on_socket_open(*args):
            shared_utils.print_and_log(
                logging.DEBUG,
                'Socket open: {}'.format(args)
            )
            self._send_world_alive()
            self.alive = True

        def on_disconnect(*args):
            """Disconnect event is a no-op for us, as the server reconnects
            automatically on a retry"""
            shared_utils.print_and_log(
                logging.INFO,
                'World server disconnected: {}'.format(args)
            )
            self.alive = False

        def on_message(*args):
            """Incoming message handler for ACKs, ALIVEs, HEARTBEATs,
            and MESSAGEs"""
            message_data = args[0]
            shared_utils.print_and_log(
                logging.DEBUG,
                'Message data recieved: {}'.format(message_data)
            )
            for message_packet in message_data['entry']:
                self.message_callback(message_packet['messaging'][0])

        # Register Handlers
        self.socketIO.on('socket_open', on_socket_open)
        self.socketIO.on('disconnect', on_disconnect)
        self.socketIO.on('new_packet', on_message)

        # Start listening thread
        self.listen_thread = threading.Thread(
            target=self.socketIO.wait,
            name='Main-Socket-Thread'
        )
        self.listen_thread.daemon = True
        self.listen_thread.start()
コード例 #35
0
ファイル: script.py プロジェクト: barelydroning/pi_backend
    pulse_duration = pulse_end - pulse_start

    distance = round(17150 * pulse_duration, 2)

    return distance


    

# get_measurement()

# while (True):
#     distance = get_measurement()
#     print('Distance is:', distance)
#     time.sleep(.05)


thread = Thread(target=continuous_loop)
thread.setDaemon(True)
thread.start()
socket.on('connect', on_connect)
socket.on('disconnect', on_disconnect)
socket.on('reconnect', on_reconnect)
socket.on('command', on_command)
socket.on('socket_id', on_socket_id)

socket.emit('connect_rover')

socket.wait()