Ejemplo n.º 1
0
def start_server(port):
	server = WebsocketServer(port)
	ws_log.debug("Server listening on port: %d" % port)
	server.set_fn_new_client(new_client)
	server.set_fn_client_left(client_left)
	server.set_fn_message_received(message_received)
	server.run_forever()
Ejemplo n.º 2
0
 def __init__(self, conf):
     global server
     super(WSService, self).__init__()
     self.conf = conf
     server = WebsocketServer(WSPORT, host='0.0.0.0')
     server.set_fn_new_client(newClient)
     server.set_fn_client_left(leftClient)
Ejemplo n.º 3
0
def start_server():
    """Start both the Game Manager and the Web Server"""

    # Prepare the web server with above functions
    logger.info("Init Web Socket Server")
    server = WebsocketServer(PORT, HOST)
    server.set_fn_new_client(onconnect)
    server.set_fn_client_left(ondisconnect)
    server.set_fn_message_received(onmessage)

    # Create a game manager
    logger.info("Init Game Manager")
    global manager
    manager = Manager(server)

    # Start the web server
    logger.info("Starting Server")
    server.run_forever()
    manager.safe_stop()
        # 6. Send Khan user data to the client
        #server.send_message(client, login_data)
    
def runWebsocketServer():
    global server
    server.run_forever()
def runAuthServer():
    global callback_server
    callback_server.serve_forever()





#PORT=9001
PORT=8080
SERVERHOST= "0.0.0.0"
server = WebsocketServer(PORT, SERVERHOST)
server.set_fn_new_client(new_client)
server.set_fn_client_left(client_left)
server.set_fn_message_received(message_received)

#server.run_forever()
#callback_server.serve_forever()

t1 = threading.Thread(target=runWebsocketServer, args=[])
t2 = threading.Thread(target=runAuthServer, args=[])
t1.start()
t2.start()

Ejemplo n.º 5
0
	for mod in modlist:
		mname = GetModuleName(phandle,mod)
		if mname.endswith(game["moduleName"]):
			memory_address = mod + game["memoryOffset"]

# read address
def readTicker():
	ReadProcessMemory(phandle, memory_address, ticker, ticker_s, byref(bytesRead))

def clientJoin(client,server):
	global client_num
	client_num += 1
	if(client_num==1):
		initTicker()

def clientLeave(client,server):
	global client_num
	client_num -= 1
	if(client_num==0):
		CloseHandle(phandle)

def clientMsg(client,server,message):
	readTicker()
	server.send_message(client,ticker.value.replace('m','.'))

print "Starting server on " + str(socket.gethostbyname(socket.gethostname()))
server = WebsocketServer(config["serverPort"],"0.0.0.0")
server.set_fn_new_client(clientJoin)
server.set_fn_client_left(clientLeave)
server.set_fn_message_received(clientMsg)
server.run_forever()
Ejemplo n.º 6
0
def doLogin(message, server):
    global unModel
#     obj = ast.literal_eval(message) //pour compatibilité avec Android
#     print message //aucune idée pourquoi mais il faut mettre cela pour que ça fonctionne avec Android!!?
    obj = json.loads(message)
    objLogin = obj["object"]
    unModel.nom = objLogin["name"]
    unModel.prenom = objLogin["firstname"]
    #Ack client
    dict={}
    dict["messageType"]="ackLogin"
    objJson = json.dumps(dict)
    server.send_message(wsIHM, objJson)
    
if __name__ == "__main__":
# Fixation du point de lecture de fichier
    os.chdir('/')#Obligation de donner le chemin du fichier avec le QPython
# routage des messages receptionnes    
    switch={
        "login":doLogin
    }
# Initialisation des models
    unModel = UnModel()
    
# Connexion au client web
    server = WebsocketServer(9999)
    server.set_fn_new_client(new_client) #définition de la fonction pour l arrivé d un nouveau client
    server.set_fn_message_received(rxMessage) #Définition de la fonction pour l arrivé d un nouveau message
    server.set_fn_client_left(clientLeft) #définition de la fonction pour la déconnexion d'un client
    
    server.run_forever()
Ejemplo n.º 7
0
def serve(port, host):
    from websocket_server import WebsocketServer
    from threading import Thread, Event
    import signal

    def message_received(client, server, message):
        print 'message_received:', message
        cmds = message.split('|')
        for cmd in cmds:
            if cmd.startswith('addr='):
                address = cmd[5:]
                if server.watched_addresses.has_key(address):
                    server.watched_addresses[address].append(client)
                else:
                    server.watched_addresses[address] = [client]
            if cmd == 'blocks':
                server.block_watchers.append(client)

    def client_left(client, server):
        print 'client_left:', client
        addrs = []
        for key in server.watched_addresses:
            if client in server.watched_addresses[key]:
                addrs.append(key)
        for addr in addrs:
            clients = server.watched_addresses[addr]
            clients.remove(client)
            if not clients:
                del server.watched_addresses[addr]
        if client in server.block_watchers:
            server.block_watchers.remove(client)

    def service_thread(ws_server, evt):
        from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
        from bitrisk.bitcoind_config import read_default_config
        import json
        import decimal
        config = read_default_config()
        testnet = ''
        if config.has_key('testnet'):
            testnet = config['testnet']
        rpc_user = config['rpcuser']
        rpc_password = config['rpcpassword']
        rpc_connection = AuthServiceProxy("http://%s:%s@%s:%s8332"%(rpc_user, rpc_password, host, testnet))
        
        conn = sqlite3.connect(db_filename)
        while not evt.wait(5):
            txs = get_db_txs(conn)
            for tx in txs:
                print 'tx:', tx
                tx = rpc_connection.gettransaction(tx)
                for details in tx['details']:
                    addr = details['address']
                    if ws_server.watched_addresses.has_key(addr):
                        def decimal_default(obj):
                            if isinstance(obj, decimal.Decimal):
                                return float(obj)
                            raise TypeError
                        msg = json.dumps(tx, default=decimal_default)
                        for client in ws_server.watched_addresses[addr]:
                            ws_server.send_message(client, msg)
            blocks = get_db_blocks(conn)
            for block in blocks:
                print 'block:', block
                for client in ws_server.block_watchers:
                    ws_server.send_message(client, block)

    server = WebsocketServer(port, host)
    server.watched_addresses = {}
    server.block_watchers = []
    server.set_fn_message_received(message_received)
    server.set_fn_client_left(client_left)
    evt = Event()
    thread = Thread(target=service_thread, args=(server, evt))

    thread.start()
    server.run_forever() # catches and exits on SIGINT
    evt.set() # stop service_thread
    thread.join()
Ejemplo n.º 8
0
        # print 'car position did not change'
        pos_check = 0
    idx0 = string_list[1].find("[")
    car_orient_tmp = eval(string_list[1][idx0:])
    orient_check = 1
    if np.linalg.norm(np.array(car_orient_tmp) - np.array(car_orient)) < 0.05:
        # print 'car orientation did not change'
        pos_check = 0
    if car_pos_tmp == [0, 0] and car_orient_tmp == [1, 0]:
        return
    car_pos = car_pos_tmp
    car_orient = car_orient_tmp
    new_car_param = pos_check + orient_check
    if new_car_param < 2:
        new_car_param = 0
    else:
        new_car_param = 1


server = WebsocketServer(9090, host='172.27.163.216')
server.set_fn_new_client(new_client)
server.set_fn_message_received(new_message)
server.set_fn_client_left(client_left)

path_pub = rospy.Publisher('web_socket/path', String, queue_size=1)
rospy.Subscriber('lane_driver/path', String, callback_path)
rospy.Subscriber("lane_driver/car", String, callback_car)
rospy.Subscriber("drive_param_fin", drive_param, callback_drive)
update_thread = Update()

server.run_forever()
Ejemplo n.º 9
0
class ServerWs(threading.Thread):
    def __init__(self, bartender):
        threading.Thread.__init__(self)
        self.bartender = bartender
        self.bartender.log("ServerWs", "Initialisation...")
        self.server = None

    def run(self):
        self.bartender.log(
            "ServerWs",
            f"Démarrage du serveur websocket sur l'adresse {self.bartender.config['ws']['ip']}:{self.bartender.config['ws']['port']}..."
        )
        try:
            self.server = WebsocketServer(
                self.bartender.config["ws"]["port"],
                host=self.bartender.config["ws"]["ip"],
                loglevel=logging.NOTSET)
            self.server.set_fn_new_client(self.new_client)
            self.server.set_fn_message_received(self.message_received)
            self.server.set_fn_client_left(self.client_left)
            self.bartender.log("ServerWs", "Serveur démarré")
            self.server.run_forever()
        except Exception as e:
            self.bartender.log(
                "ServerWs", "Erreur lors du démarrage du serveur : " + str(e))

    def close(self):
        self.bartender.log("ServerWs", "Arrêt du serveur websocket...")
        try:
            self.server.server_close()
            self.server = None
            self.bartender.log("ServerWs", "Arrêté")
        except Exception as e:
            self.bartender.log("ServerWs",
                               "Erreur lors de l'arrêt du serveur : " + str(e))

    def send_message(self, client, msg):
        self.bartender.log("ServerWs", f"Envoie (id:{client['id']}) : {msg}")
        self.server.send_message(client, msg)

    def send_message_to_all(self, msg):
        # self.bartender.log("ServerWs", f"Envoie (all) : {msg}")
        for client in self.server.clients:
            if (client != self.bartender.ethylotest):
                self.server.send_message(client, msg)

    def message_received(self, client, server, msg):
        self.bartender.log("ServerWs", f"Reçu (id:{client['id']}) : {msg}")
        self.bartender.message_received(client, server, msg)

    def new_client(self, client, server):
        self.bartender.log("ServerWs",
                           f"Nouvelle connexion (id:{client['id']})")
        self.bartender.newClient(client, server)

    def client_left(self, client, server):
        self.bartender.log("ServerWs", f"Déconnexion (id:{client['id']})")
        self.bartender.clientLeft(client, server)

    def getOtherClients(self, client):
        clients = []
        for other in self.server.clients:
            if (other != client):
                clients.append(other)
        return clients

    def kickClient(self, client):
        client['handler'].send_text("", opcode=0x8)
Ejemplo n.º 10
0
def serveWS(PORT=8988):
    wsServer = WebsocketServer(PORT, host='192.168.1.200')
    wsServer.set_fn_new_client(WS_new_client)
    wsServer.set_fn_client_left(WS_client_left)
    wsServer.set_fn_message_received(WS_onmessage)
    wsServer.run_forever()
Ejemplo n.º 11
0
class Plugin(indigo.PluginBase):

    ########################################
    # Main Plugin methods
    ########################################
    def __init__(self, pluginId, pluginDisplayName, pluginVersion,
                 pluginPrefs):
        indigo.PluginBase.__init__(self, pluginId, pluginDisplayName,
                                   pluginVersion, pluginPrefs)

        pfmt = logging.Formatter(
            '%(asctime)s.%(msecs)03d\t[%(levelname)8s] %(name)20s.%(funcName)-25s%(msg)s',
            datefmt='%Y-%m-%d %H:%M:%S')
        self.plugin_file_handler.setFormatter(pfmt)

        try:
            self.logLevel = int(self.pluginPrefs[u"logLevel"])
        except:
            self.logLevel = logging.INFO
        self.indigo_log_handler.setLevel(self.logLevel)

    def validatePrefsConfigUi(self, valuesDict):
        errorDict = indigo.Dict()

        try:
            self.logLevel = int(valuesDict[u"logLevel"])
        except:
            self.logLevel = logging.INFO
        self.indigo_log_handler.setLevel(self.logLevel)

        try:
            port = int(valuesDict[u"socketPort"])
        except:
            errorDict[u"socketPort"] = "Non-integer port number"
        else:
            if port < 1024:
                errorDict[u"socketPort"] = "Priviledged port number"

        if len(errorDict) > 0:
            return (False, valuesDict, errorDict)
        return (True, valuesDict)

    def closedPrefsConfigUi(self, valuesDict, userCancelled):
        if userCancelled:
            return

        self.logLevel = int(valuesDict[u"logLevel"])
        self.indigo_log_handler.setLevel(self.logLevel)

        if valuesDict[u"socketPort"] != self.socketPort:
            self.socketPort = valuesDict[u"socketPort"]
            self.start_websocket(int(self.socketPort))

    def startup(self):
        self.logger.info(u"Starting StreamDeck")
        self.triggers = {}
        self.activeConnections = {}

        # these are the Streamdeck devices and buttons that have Indigo devices to match
        self.activeDecks = {}
        self.activeButtons = {}

        # these are the known Streamdeck devices and buttons, may not have a matching Indigo device
        self.known_devices = indigo.activePlugin.pluginPrefs.get(
            u"known_devices", indigo.Dict())
        self.known_buttons = indigo.activePlugin.pluginPrefs.get(
            u"known_buttons", indigo.Dict())

        self.wsServer = None
        self.socketPort = self.pluginPrefs.get(u'socketPort', 9001)
        self.start_websocket(int(self.socketPort))

    def shutdown(self):
        self.logger.info(u"Stopping StreamDeck")
        indigo.activePlugin.pluginPrefs[u"known_devices"] = self.known_devices
        indigo.activePlugin.pluginPrefs[u"known_buttons"] = self.known_buttons

        if self.wsServer:
            self.wsServer.server_close()
            self.wsServer = None

    def start_websocket(self, port):
        if self.wsServer:
            self.logger.debug("Closing existing Websocket Server")
            self.wsServer.server_close()
            self.wsServer = None
        try:
            self.wsServer = WebsocketServer(
                port, '0.0.0.0')  # bind socket to all interfaces
            self.wsServer.set_fn_new_client(self.onConnect)
            self.wsServer.set_fn_client_left(self.onClose)
            self.wsServer.set_fn_message_received(self.onMessage)
            self.wsServer.timeout = 1.0
            self.logger.debug(
                u"Started Websocket Server on port {}".format(port))
        except Error as e:
            self.logger.warning(
                u"Error starting Websocket Server: {}".format(e))

    def runConcurrentThread(self):
        try:
            while True:
                if self.wsServer:
                    self.wsServer.handle_request()
                    self.sleep(0.1)
                else:
                    self.sleep(1)
        except self.StopThread:
            pass

    ####################

    def onConnect(self, client, server):
        self.logger.debug(u"onConnect client: {}".format(client['id']))
        self.activeConnections[client['id']] = client
        self.logger.debug(u"onConnect activeConnections: {}".format(
            self.activeConnections))

        reply = {"event": "connected", "clientID": client['id']}
        self.wsServer.send_message(client, json.dumps(reply))

    def onClose(self, client, server):
        self.logger.debug(u"onClose client: {}".format(client['id']))
        del self.activeConnections[client['id']]

    def onMessage(self, client, server, received):

        try:
            message = json.loads(received)
        except:
            self.logger.warning(
                u"onMessage from client {}, invalid JSON:\n{}".format(
                    client['id'], received))
            return

        self.logger.threaddebug(
            u"onMessage from client: {}, message: {}".format(
                client['id'], message))

        if not 'message-type' in message:
            self.logger.warning(
                "onMessage from client {}, no message-type, message: {}".
                format(client['id'], message))
            return

        if message['message-type'] == 'applicationInfo':
            self.applicationInfo(message, client)

        elif message['message-type'] in ['deviceDidConnect']:
            self.deviceDidConnect(message, client)

        elif message['message-type'] in ['deviceDidDisconnect']:
            self.deviceDidDisconnect(message, client)

        elif message['message-type'] in ['willAppear']:
            self.buttonWillAppear(message, client)

        elif message['message-type'] in ['willDisappear']:
            self.buttonWillDisappear(message, client)

        elif message['message-type'] in ['keyUp', 'keyDown']:
            self.keyPress(message, client)

    ####################

    def applicationInfo(self, message, client):
        for dev in message[u'payload'][u'devices']:
            self.logger.debug(
                u"onMessage applicationInfo Adding/Updating device: {}".format(
                    dev))

            deck = {}
            deck[u'id'] = dev[u'id']
            deck[u'name'] = dev[u'name']
            deck[u'columns'] = dev[u'size'][u'columns']
            deck[u'rows'] = dev[u'size'][u'rows']
            deck[u'type'] = dev.get(u'type', -1)
            deck[u'client'] = client['id']
            self.registerDeck(deck)

    def deviceDidConnect(self, message, client):
        self.logger.debug(
            u"onMessage deviceDidConnect Adding/Updating device: {}".format(
                message))

        deck = {}
        deck[u'id'] = message[u'payload'][u'device']
        deck[u'name'] = message[u'payload'][u'deviceInfo'][u'name']
        deck[u'columns'] = message[u'payload'][u'deviceInfo'][u'size'][
            u'columns']
        deck[u'rows'] = message[u'payload'][u'deviceInfo'][u'size'][u'rows']
        deck[u'type'] = message[u'payload'][u'deviceInfo'].get(u'type', -1)
        deck[u'client'] = client['id']
        self.registerDeck(deck)

    def registerDeck(self, deckDict):
        deckKey = safeKey(deckDict[u'id'])
        self.known_devices[deckKey] = deckDict

        if deckKey in self.activeDecks:  # If there's an active Indigo device, update the active state
            deckDevice = indigo.devices.get(int(self.activeDecks[deckKey]))
            if not deckDevice:
                self.logger.warning(
                    "registerDeck invalid Deck DeviceID: {}".format(deckDict))
            else:
                states_list = []
                states_list.append({'key': 'active', 'value': True})
                states_list.append({'key': 'name', 'value': deckDict[u'name']})
                states_list.append({
                    'key': 'columns',
                    'value': deckDict[u'columns']
                })
                states_list.append({'key': 'rows', 'value': deckDict[u'rows']})
                states_list.append({'key': 'type', 'value': deckDict[u'type']})
                states_list.append({
                    'key': 'clientID',
                    'value': deckDict['client']
                })
                deckDevice.updateStatesOnServer(states_list)

    def deviceDidDisconnect(self, message, client):
        self.logger.debug(u"onMessage deviceDidDisconnect: {}".format(message))
        deckKey = safeKey(message[u'payload'][u'device'])
        if deckKey in self.activeDecks:  # If there's an active Indigo device, update the active state
            deckDevice = indigo.devices.get(int(self.activeDecks[deckKey]))
            if not deckDevice:
                self.logger.warning(
                    "deviceDidDisconnect invalid Deck DeviceID: {}".format(
                        message))
            else:
                deckDevice.updateStateOnServer(key="active", value=False)

    def buttonWillAppear(self, message, client):
        self.logger.debug(u"onMessage buttonWillAppear: {}".format(message))
        buttonKey = safeKey(message[u'payload'][u'context'])
        button = {}
        button[u'id'] = message[u'payload'][u'context']
        button[u'device'] = message[u'payload'][u'device']
        button[u'column'] = message[u'payload'][u'payload'][u'coordinates'][
            u'column']
        button[u'row'] = message[u'payload'][u'payload'][u'coordinates'][
            u'row']
        button[u'settings'] = message[u'payload'][u'payload'][u'settings']
        button[u'name'] = "{}-{}-{}".format(
            self.known_devices[button[u'device']][u'name'], button[u'column'],
            button[u'row'])
        button[u'client'] = client['id']

        self.known_buttons[buttonKey] = button

        if buttonKey in self.activeButtons:  # If there's an active Indigo device, update the visible state
            buttonDevice = indigo.devices.get(
                int(self.activeButtons[buttonKey]))
            if not buttonDevice:
                self.logger.warning(
                    "buttonWillAppear invalid button DeviceID: {}".format(
                        message))
            else:
                states_list = []
                states_list.append({'key': 'visible', 'value': True})
                states_list.append({'key': 'name', 'value': button[u'name']})
                states_list.append({
                    'key': 'column',
                    'value': button[u'column']
                })
                states_list.append({'key': 'row', 'value': button[u'row']})
                states_list.append({'key': 'clientID', 'value': client['id']})
                buttonDevice.updateStatesOnServer(states_list)

    def buttonWillDisappear(self, message, client):
        self.logger.debug(u"onMessage buttonWillDisappear: {}".format(message))
        buttonKey = safeKey(message[u'payload'][u'context'])
        if buttonKey in self.activeButtons:  # If there's an active Indigo device, update the visible state
            buttonDevice = indigo.devices.get(
                int(self.activeButtons[buttonKey]))
            if not buttonDevice:
                self.logger.warning(
                    "buttonWillDisappear invalid button DeviceID: {}".format(
                        message))
            else:
                deckDevice.updateStateOnServer(key="visible", value=False)

    def keyPress(self, message, client):
        self.logger.debug(u"onMessage keyPress: {}".format(message))

        messageType = message['message-type']
        if messageType not in ['keyDown', 'keyUp']:
            self.logger.warning("keyPress unexpected message-type: {}".format(
                message['message-type']))
            return

        eventID = message[u'payload'][u'payload'][u'settings'][u'eventID']
        actionRequest = message[u'payload'][u'payload'][u'settings'][
            u'actionRequest']

        if actionRequest == u'action-group' and messageType == 'keyDown':

            indigo.actionGroup.execute(int(eventID))

        elif actionRequest == u'indigo-device-momentary' and messageType == 'keyDown':

            indigo.device.turnOn(int(eventID))

        elif actionRequest == u'indigo-device-momentary' and messageType == 'keyUp':

            indigo.device.turnOff(int(eventID))

        elif actionRequest == u'indigo-device-toggle' and messageType == 'keyDown':

            indigo.device.toggle(int(eventID))

        elif actionRequest == u'indigo-variable':

            indigo.variable.updateValue(int(eventID), value=messageType)

    ########################################

    def validateDeviceConfigUi(self, valuesDict, typeId, devId):
        errorsDict = indigo.Dict()
        if len(errorsDict) > 0:
            return (False, valuesDict, errorsDict)
        return (True, valuesDict)

    ########################################
    # Called for each enabled Device belonging to plugin
    ########################################

    def deviceStartComm(self, device):
        self.logger.info(u"{}: Starting Device".format(device.name))

        instanceVers = int(device.pluginProps.get('devVersCount', 0))
        if instanceVers == kCurDevVersCount:
            self.logger.threaddebug(
                u"{}: Device is current version: {}".format(
                    device.name, instanceVers))
        elif instanceVers < kCurDevVersCount:
            newProps = device.pluginProps
            newProps["devVersCount"] = kCurDevVersCount
            device.replacePluginPropsOnServer(newProps)
            self.logger.debug(u"{}: Updated device version: {} -> {}".format(
                device.name, instanceVers, kCurDevVersCount))
        else:
            self.logger.warning(u"{}: Invalid device version: {}".format(
                device.name, instanceVers))

        if device.deviceTypeId == "sdDevice":
            self.activeDecks[device.address] = device.id
        elif device.deviceTypeId == "sdButton":
            self.activeButtons[device.address] = device.id

    def deviceStopComm(self, device):
        self.logger.info(u"{}: Stopping Device".format(device.name))
        if device.deviceTypeId == "sdDevice":
            del self.activeDecks[device.id]
        elif device.deviceTypeId == "sdButton":
            del self.activeButtons[device.id]

    ########################################
    # Plugin Actions object callbacks
    ########################################

    def setButtonIcon(self, pluginAction, deckDevice, callerWaitingForResult):
        self.logger.debug(
            "setButtonIcon: pluginAction = {}".format(pluginAction))

        profile = indigo.activePlugin.substitute(pluginAction.props["profile"])
        deckDeviceID = pluginAction.props["device"]
        deckDict = self.known_devices[safeKey(deckDeviceID)]
        self.logger.debug("setButtonIcon: deckDict = {}".format(deckDict))
        socketClient = self.activeConnections[deckDict['client']]

        message = {
            "event": "setButtonIcon",
            "device": deckDeviceID,
            "profile": profile
        }
        self.wsServer.send_message(socketClient, json.dumps(message))

    def availableDeckList(self,
                          filter="",
                          valuesDict=None,
                          typeId="",
                          targetId=0):

        retList = []
        for key in self.known_devices:
            device = self.known_devices[key]
            retList.append((device['id'], device['name']))

        self.logger.debug("availableDeckList: retList = {}".format(retList))
        return retList

    def availableButtonList(self,
                            filter="",
                            valuesDict=None,
                            typeId="",
                            targetId=0):

        in_use = []
        for dev in indigo.devices.iter(filter="self.sdButton"):
            in_use.append(dev.pluginProps[u'context'])

        retList = []
        for key in self.known_buttons:
            button = self.known_buttons[key]
            if button['id'] not in in_use:
                retList.append((button['id'], button['name']))

        self.logger.debug("availableButtonList: retList = {}".format(retList))
        return retList

    # doesn't do anything, just needed to force other menus to dynamically refresh
    def menuChanged(self, valuesDict=None, typeId=None, devId=None):
        return valuesDict

    def validateActionConfigUi(self, valuesDict, typeId, devId):
        errorsDict = indigo.Dict()
        try:
            pass
        except:
            pass
        if len(errorsDict) > 0:
            return (False, valuesDict, errorsDict)
        return (True, valuesDict)

    ########################################
    # Menu Command Methods
    ########################################

    def dumpKnownDevices(self):
        self.logger.info(u"Known decks:\n{}".format(self.known_devices))
        self.logger.info(u"Known buttons:\n{}".format(self.known_buttons))

    def dumpActiveDevices(self):
        self.logger.info(u"Active decks:\n{}".format(self.activeDecks))
        self.logger.info(u"Active buttons:\n{}".format(self.activeButtons))

    def purgeKnownDevices(self):
        self.known_devices = {}
        self.known_buttons = {}

    ########################################
    # Event/Trigger Methods
    ########################################

    def triggerStartProcessing(self, trigger):
        self.logger.debug("Adding Trigger %s (%d) - %s" %
                          (trigger.name, trigger.id, trigger.pluginTypeId))
        assert trigger.id not in self.triggers
        self.triggers[trigger.id] = trigger

    def triggerStopProcessing(self, trigger):
        self.logger.debug("Removing Trigger %s (%d)" %
                          (trigger.name, trigger.id))
        assert trigger.id in self.triggers
        del self.triggers[trigger.id]

    def triggerCheck(self, device):

        for triggerId, trigger in sorted(self.triggers.iteritems()):
            self.logger.debug("Checking Trigger %s (%s), Type: %s" %
                              (trigger.name, trigger.id, trigger.pluginTypeId))
Ejemplo n.º 12
0
		time.sleep(0.01)
	client["handler"].connection.close()
	del clients[client['id']]
	print len(clients)

# When we recieve thing from WebSocket browser
def message_client(client,server,message):
	json_d = json.loads(message)
	try:
		if json_d["action"] == "connect":
			start_new_thread(start_new_shell,(client,server,json_d["host"],json_d["port"],json_d["username"],json_d["password"],))
		elif json_d["action"] == "key":
			chan = clients[client["id"]]['channel']
			chan.send(json_d["key"])
		elif json_d["action"] == "keySpecial":
			chan = clients[client["id"]]['channel']
			json_d["key"] = "\x1B" + json_d["key"]
			chan.send(json_d["key"])
		elif json_d["action"] == "keyCode":
			chan = clients[client["id"]]['channel']
			chan.send(chr(json_d["keyCode"]))
	except:
		bye_client(client, server)

# Listening to our desired port and setting up the connection
server = WebsocketServer(13254, host='0.0.0.0')
server.set_fn_new_client(new_client)
server.set_fn_client_left(bye_client)
server.set_fn_message_received(message_client)
server.run_forever()
Ejemplo n.º 13
0
class Template:
    # Initialize class variables
    # self.time_cycle to run an execution for atleast 1 second
    # self.process for the current running process
    def __init__(self):
        self.thread = None
        self.reload = False

        # Time variables
        self.time_cycle = 80
        self.ideal_cycle = 80
        self.iteration_counter = 0

        self.server = None
        self.client = None
        self.host = sys.argv[1]

        # Initialize the GUI, WEBRTC and Console behind the scenes
        self.console = console.Console()
        self.exercice = subprocess.Popen(["python", "consumer.py"],
                                         stdout=subprocess.PIPE,
                                         preexec_fn=os.setsid)

        self.gui = GUI(self.host, self.console)

    # Function for saving
    def save_code(self, source_code):
        with open('code/academy.py', 'w') as code_file:
            code_file.write(source_code)

    # Function for loading
    def load_code(self):
        with open('code/academy.py', 'r') as code_file:
            source_code = code_file.read()

        return source_code

    # Function to parse the code
    # A few assumptions:
    # 1. The user always passes sequential and iterative codes
    # 2. Only a single infinite loop
    def parse_code(self, source_code):
        # Check for save/load
        if (source_code[:5] == "#save"):
            source_code = source_code[5:]
            self.save_code(source_code)

            return "", "", 1

        elif (source_code[:5] == "#load"):
            source_code = source_code + self.load_code()
            self.server.send_message(self.client, source_code)

            return "", "", 1

        else:
            # Get the frequency of operation, convert to time_cycle and strip
            try:
                # Get the debug level and strip the debug part
                debug_level = int(source_code[5])
                source_code = source_code[12:]
            except:
                debug_level = 1
                source_code = ""

                source_code = self.debug_parse(source_code, debug_level)

            sequential_code, iterative_code = self.seperate_seq_iter(
                source_code)
            return iterative_code, sequential_code, debug_level

    # Function to parse code according to the debugging level
    def debug_parse(self, source_code, debug_level):
        if (debug_level == 1):
            # If debug level is 0, then all the GUI operations should not be called
            source_code = re.sub(r'GUI\..*', '', source_code)

        return source_code

    # Function to seperate the iterative and sequential code
    def seperate_seq_iter(self, source_code):
        if source_code == "":
            return "", ""

        # Search for an instance of while True
        infinite_loop = re.search(r'[^ \t]while\(True\):|[^ \t]while True:',
                                  source_code)

        # Seperate the content inside while True and the other
        # (Seperating the sequential and iterative part!)
        try:
            start_index = infinite_loop.start()
            iterative_code = source_code[start_index:]
            sequential_code = source_code[:start_index]

            # Remove while True: syntax from the code
            # And remove the the 4 spaces indentation before each command
            iterative_code = re.sub(r'[^ ]while\(True\):|[^ ]while True:', '',
                                    iterative_code)
            iterative_code = re.sub(r'^[ ]{4}', '', iterative_code, flags=re.M)

        except:
            sequential_code = source_code
            iterative_code = ""

        return sequential_code, iterative_code

    # The process function
    def process_code(self, source_code):
        # Reference Environment for the exec() function
        reference_environment = {
            'console': self.console,
            'print': print_function
        }
        iterative_code, sequential_code, debug_level = self.parse_code(
            source_code)

        # print("The debug level is " + str(debug_level)
        # print(sequential_code)
        # print(iterative_code)

        try:
            # The Python exec function
            # Run the sequential part
            gui_module = self.generate_modules()
            exec(sequential_code, reference_environment)

            # Run the iterative part inside template
            # and keep the check for flag
            while self.reload == False:
                start_time = datetime.now()

                # Execute the iterative portion
                exec(iterative_code, reference_environment)

                # Template specifics to run!
                finish_time = datetime.now()
                dt = finish_time - start_time
                ms = (dt.days * 24 * 60 * 60 +
                      dt.seconds) * 1000 + dt.microseconds / 1000.0

                # Keep updating the iteration counter
                if (iterative_code == ""):
                    self.iteration_counter = 0
                else:
                    self.iteration_counter = self.iteration_counter + 1

                # The code should be run for atleast the target time step
                # If it's less put to sleep
                if (ms < self.time_cycle):
                    time.sleep((self.time_cycle - ms) / 1000.0)

            print("Current Thread Joined!")

        # To print the errors that the user submitted through the Javascript editor (ACE)
        except Exception:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            self.console.print(str(exc_value))

    # Function to generate the modules for use in ACE Editor
    def generate_modules(self):
        # Define GUI module
        gui_module = imp.new_module("GUI")
        gui_module.GUI = imp.new_module("GUI")

        # Add GUI functions
        gui_module.GUI.showImage = self.gui.showImage
        gui_module.GUI.getImage = self.gui.getImage

        # Adding modules to system
        # Protip: The names should be different from
        # other modules, otherwise some errors
        sys.modules["GUI"] = gui_module

        return gui_module

    # Function to measure the frequency of iterations
    def measure_frequency(self):
        previous_time = datetime.now()
        # An infinite loop
        while self.reload == False:
            # Sleep for 2 seconds
            time.sleep(2)

            # Measure the current time and subtract from the previous time to get real time interval
            current_time = datetime.now()
            dt = current_time - previous_time
            ms = (dt.days * 24 * 60 * 60 +
                  dt.seconds) * 1000 + dt.microseconds / 1000.0
            previous_time = current_time

            # Get the time period
            try:
                # Division by zero
                self.ideal_cycle = ms / self.iteration_counter
            except:
                self.ideal_cycle = 0

            # Reset the counter
            self.iteration_counter = 0

            # Send to client
            try:
                self.server.send_message(
                    self.client,
                    "#freq" + str(round(1000 / self.ideal_cycle, 1)))
            except ZeroDivisionError:
                self.server.send_message(self.client, "#freq" + str(0))

    # Function to maintain thread execution
    def execute_thread(self, source_code):
        # Keep checking until the thread is alive
        # The thread will die when the coming iteration reads the flag
        if (self.thread != None):
            while self.thread.is_alive() or self.measure_thread.is_alive():
                pass

        # Turn the flag down, the iteration has successfully stopped!
        self.reload = False
        # New thread execution
        self.measure_thread = threading.Thread(target=self.measure_frequency)
        self.thread = threading.Thread(target=self.process_code,
                                       args=[source_code])
        self.thread.start()
        self.measure_thread.start()
        print("New Thread Started!")

    # The websocket function
    # Gets called when there is an incoming message from the client
    def handle(self, client, server, message):
        if (message[:5] == "#freq"):
            frequency = float(message[5:])
            self.time_cycle = 1000.0 / frequency
            self.server.send_message(self.client, "#ping")
            return

        try:
            # Once received turn the reload flag up and send it to execute_thread function
            code = message
            # print(repr(code))
            self.reload = True
            self.execute_thread(code)
        except:
            pass

    # Function that gets called when the server is connected
    def connected(self, client, server):
        self.client = client
        # Start the GUI update thread
        t = ThreadGUI(self.gui)
        t.start()

        # Initialize the ping message
        self.server.send_message(self.client, "#ping")

        print(client, 'connected')

    # Function that gets called when the connected closes
    def handle_close(self, client, server):
        os.killpg(os.getpgid(self.exercice.pid), signal.SIGKILL)
        print(client, 'closed')

    def run_server(self):
        self.server = WebsocketServer(port=1905, host=self.host)
        self.server.set_fn_new_client(self.connected)
        self.server.set_fn_client_left(self.handle_close)
        self.server.set_fn_message_received(self.handle)
        self.server.run_forever()
Ejemplo n.º 14
0
class Ui_MainWindow(object):
    # Called for every client connecting (after handshake)

    def new_client(self, client, server):
        self.listWidget_ip.addItem(util.get_time_ymd_hms() +
                                   "New client connected and was given id %d" %
                                   client['id'])

    # Called for every client disconnecting
    def client_left(self, client, server):
        self.listWidget_ip.addItem(util.get_time_ymd_hms() +
                                   "Client(%d) disconnected" % client['id'])

    # Called when a client sends a message
    def message_received(self, client, server, message):
        if len(message) > 200:
            message = message[:200] + '..'
        print("Client(%d) said: %s" % (client['id'], message))
        server.send_message_to_all("sadsadad")

    def set_server(self):
        PORT = 8444
        self.server = WebsocketServer(PORT)
        self.server.set_fn_new_client(self.new_client)
        self.server.set_fn_client_left(self.client_left)
        self.server.set_fn_message_received(self.message_received)

    def setupUi(self, MainWindow):
        threading.Thread(target=self.set_server).start()

        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(882, 728)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.btn_start = QtWidgets.QPushButton(self.centralwidget)
        self.btn_start.setGeometry(QtCore.QRect(810, 20, 61, 31))
        self.btn_send_test = QtWidgets.QPushButton(self.centralwidget)
        self.btn_send_test.setGeometry(QtCore.QRect(610, 20, 61, 31))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(12)
        self.btn_start.setFont(font)
        self.btn_start.setObjectName("btn_start")
        self.btn_send_test.setFont(font)
        self.btn_send_test.setObjectName("btn_send_test")
        self.listWidget_ip = QtWidgets.QListWidget(self.centralwidget)
        self.listWidget_ip.setGeometry(QtCore.QRect(530, 60, 341, 621))
        self.listWidget_ip.setObjectName("listWidget_ip")

        self.line_gap_price = QtWidgets.QLineEdit(self.centralwidget)
        self.line_gap_price.setGeometry(QtCore.QRect(230, 109, 61, 21))
        self.line_test = QtWidgets.QLineEdit(self.centralwidget)
        self.line_test.setGeometry(QtCore.QRect(230, 20, 61, 21))
        self.line_test2 = QtWidgets.QLineEdit(self.centralwidget)
        self.line_test2.setGeometry(QtCore.QRect(130, 20, 61, 21))
        self.line_gap_price.setObjectName("line_gap_price")
        self.line_instant_rise = QtWidgets.QLineEdit(self.centralwidget)
        self.line_instant_rise.setGeometry(QtCore.QRect(230, 150, 61, 20))
        self.line_instant_rise.setObjectName("line_instant_rise")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(30, 70, 151, 16))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(11)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(30, 110, 181, 20))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(11)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(30, 150, 181, 20))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(11)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(30, 190, 161, 20))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(11)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(30, 230, 171, 20))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(11)
        self.label_5.setFont(font)
        self.label_5.setObjectName("label_5")
        self.line_instant_fall = QtWidgets.QLineEdit(self.centralwidget)
        self.line_instant_fall.setGeometry(QtCore.QRect(230, 190, 61, 20))
        self.line_instant_fall.setObjectName("line_instant_fall")
        self.line_minute_rise = QtWidgets.QLineEdit(self.centralwidget)
        self.line_minute_rise.setGeometry(QtCore.QRect(230, 230, 61, 20))
        self.line_minute_rise.setObjectName("line_minute_rise")
        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(30, 260, 181, 20))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(11)
        self.label_6.setFont(font)
        self.label_6.setObjectName("label_6")
        self.line_minute_fall = QtWidgets.QLineEdit(self.centralwidget)
        self.line_minute_fall.setGeometry(QtCore.QRect(230, 260, 61, 21))
        self.line_minute_fall.setObjectName("line_minute_fall")
        self.btn_end = QtWidgets.QPushButton(self.centralwidget)
        self.btn_end.setGeometry(QtCore.QRect(530, 20, 61, 31))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(12)
        self.btn_end.setFont(font)
        self.btn_end.setObjectName("btn_end")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 882, 18))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.btn_start.setText(_translate("MainWindow", "开始"))

        self.line_gap_price.setText(_translate("MainWindow", "1"))
        self.line_instant_rise.setText(_translate("MainWindow", "1"))
        self.label.setText(_translate("MainWindow", "涨跌过滤(区间)"))
        self.label_2.setText(_translate("MainWindow", "差价(%)"))
        self.label_3.setText(_translate("MainWindow", "瞬时增长(%)"))
        self.label_4.setText(_translate("MainWindow", "顺势下跌(%)"))
        self.label_5.setText(_translate("MainWindow", "分钟增长(%)"))
        self.line_instant_fall.setText(_translate("MainWindow", "-1"))
        self.line_minute_rise.setText(_translate("MainWindow", "0.75"))
        self.label_6.setText(_translate("MainWindow", "分钟下跌(%)"))
        self.line_minute_fall.setText(_translate("MainWindow", "-1"))
        self.btn_end.setText(_translate("MainWindow", "停止"))
        self.btn_send_test.setText(_translate("MainWindow", "测试发送"))
        self.btn_send_test.clicked.connect(self.send_test)
        self.btn_start.clicked.connect(self.start)
        self.btn_end.clicked.connect(self.end)

    def check_today_data(self):
        while True:
            try:
                size_str = util.read_one_file(
                    r"C:\Users\hangqing1\Desktop\bin423\ShareMem.txt",
                    'gbk')[0]
                date_str, size = size_str.split('=')
                if date_str != util.get_today_date():
                    time.sleep(3)
                    continue
                else:
                    self.listWidget_ip.addItem(util.get_today_time() +
                                               "发现更新数据")
                    self.start_filter(size)
                    break
            except Exception as e:
                print(e)

    def start(self):
        size_str = util.read_one_file(
            r"C:\Users\hangqing1\Desktop\bin423\ShareMem.txt", 'gbk')[0]
        date_str, size = size_str.split('=')
        self.listWidget_ip.addItem(util.get_today_time() + "等待数据加载")

        if date_str != util.get_today_date():
            threading.Thread(target=self.check_today_data).start()
        else:
            self.start_filter(size)

    def start_filter(self, size):
        threading.Thread(target=self.server.run_forever).start()
        filter_conf = FilterConfig()

        filter_conf.price_gap_value = float(self.line_gap_price.text().strip())
        filter_conf.instant_rise_value = float(
            self.line_instant_rise.text().strip())
        filter_conf.instant_fall_value = float(
            self.line_instant_fall.text().strip())
        filter_conf.rise_in_minute_value = float(
            self.line_minute_rise.text().strip())
        filter_conf.fall_in_minute_value = float(
            self.line_minute_fall.text().strip())
        self.listWidget_ip.addItem(str(filter_conf.__dict__))
        self.new_filter = Filter(self.server, filter_conf)
        self.listWidget_ip.addItem("开始")
        filter_thread = threading.Thread(target=self.new_filter.run_filter,
                                         args=(int(size), ))
        filter_thread.start()
        self.listWidget_ip.addItem("过滤器开始启动")
        # 开启滚动条最下线程

    def send_test(self):
        self.server.send_message_to_all("test^test^test^test^test^test^0.5^" +
                                        self.line_test2.text() + "^" +
                                        self.line_test.text())

    def end(self):
        self.new_filter.filter_flag = False
        self.listWidget_ip.addItem("停止监控")
Ejemplo n.º 15
0
class SocConn(Communicator):

    def __init__(self):
        super().__init__()
        DEFAULT_SOC_PORT = 8765
        self.host = ''
        self.port = DEFAULT_SOC_PORT
        self.bus = WebsocketServer(host=self.host, port=self.port)

        self.recv_q = Queue()
        self.send_q = Queue()
        self.close_event = False

    def open(self):
        Thread(target=self.__open, daemon=True).start()
        Thread(target=self.__send_handler, daemon=True).start()
        return self.host, self.port

    def close(self):
        self.bus.server_close()

    def recv(self):
        if self.recv_q.empty():
            return None
        modi_message = self.recv_q.get()
        return modi_message

    def send(self, modi_message):
        self.send_q.put(modi_message)

    #
    # Helper Methods
    #
    def __open(self):
        def new_client(client, server):
            server.send_message_to_all(
                f'Hey all, a new client:{client} has joined us'
            )

        def client_left(client, server):
            server.send_message_to_all(
                f'Hey all, a client:{client} has left us'
            )

        # Set callback functions
        self.bus.set_fn_new_client(new_client)
        self.bus.set_fn_message_received(self.__recv_handler)
        self.bus.set_fn_client_left(client_left)

        # Run the server forever
        self.bus.run_forever()

    def __recv_handler(self, client, server, message):
        self.recv_q.put(message)

    def __send_handler(self):
        while not self.close_event:
            if self.send_q.empty():
                time.sleep(0.001)
                continue
            try:
                message = self.send_q.get()
                self.bus.send_message_to_all(message)
            except Exception:
                self.close_event = True
Ejemplo n.º 16
0
            cnt = 0
            print("imgpath :",imgdict)
            for imgpath in imgdict[1]:
                with open(imgpath,"rb") as imgf:
                    imgdict[1][cnt] = base64.b64encode(imgf.read()).decode('utf-8')
                cnt+=1
            send_data = {"img":[imgdict[1][0],imgdict[1][1]]}
        elif jkey == "in_data":
            ind = dict_data[jkey]
            time = datetime.now()
            print(type(time),time)
            uuid1 = str(uuid.uuid1())
            dir_path = f"/root/Picture/{ind['db']}/{time.year}/{time.month}/{time.day}/{time.hour}/"
            tfdir = f"{dir_path}top_{time.minute}-{time.second}_{uuid1}.png"
            sfdir = f"{dir_path}slanting_{time.minute}-{time.second}_{uuid1}.png"
            os.makedirs(dir_path, exist_ok=True)
            with open(tfdir, mode='wb') as ft,open(sfdir, mode='wb') as fs:
                ft.write(base64.b64decode(ind["img"][0].encode()))
                fs.write(base64.b64decode(ind["img"][1].encode()))
            send_data = sql(ind['db'],sqlgen(ind["mac"],time,tfdir,sfdir,ind["jstr"]),True)

            

    server.send_message(client,json.dumps(send_data,default=json_serial))


server = WebsocketServer(8080, host='0.0.0.0')
server.set_fn_new_client(new_client)
server.set_fn_message_received(recv)
server.set_fn_client_left(disconnect)
server.run_forever()
Ejemplo n.º 17
0
# Receive data from client and put it in the input queue
def communicateWithClient(client, server, msg):
    print('recv: ' + msg)
    carConnectionSem.acquire()
    if (carIsConnected and msg in validInput):
        inputSem.acquire()
        inputQueue.append(msg)
        inputSem.release()
    carConnectionSem.release()


# Websocket to talk to client
websocket = WebsocketServer(clientPort)
websocket.set_fn_new_client(onClientConnection)
websocket.set_fn_client_left(onClientDisconnection)
websocket.set_fn_message_received(communicateWithClient)


# Handle car communications
def communicateWithCar():

    while (runServer):
        # Wait for car to connect
        c, addr = carSock.accept()
        isConnected = True
        global carIsConnected
        carConnectionSem.acquire()
        carIsConnected = True
        carConnectionSem.release()
Ejemplo n.º 18
0
class CloudLink:
    def __init__(self):
        self.wss = None
        self.users = {}
        self.userlist = []
        self.handlers = []
        self.gdata = ""
        self.mode = 0  # 1=Host, 2=Client, 3=Plugin

    def host(self, port):
        if serverModeSupport:
            self.mode = 1
            self.wss = WebsocketServer(
                int(port)
            )  # Instanciate WebsocketServer alongside CloudLink module

            # Define callbacks to functions
            self.wss.set_fn_new_client(self.newConnection)
            self.wss.set_fn_message_received(self.gotPacket)
            self.wss.set_fn_client_left(self.closedConnection)

            # Run the server
            print("Now running in host mode on port {0}...".format(port))
            try:
                self.wss.serve_forever()
            except KeyboardInterrupt:
                if not len(self.users) == 0:
                    print("Shutdown in progress, please wait...")
                    # Tell all users to disconnect, and wait until all are disconnected
                    self.wss.send_message_to_all(json.dumps({"cmd": "ds"}))
                    while not len(self.users) == 0:
                        pass
                    print("All users disconnected, now exiting...")
                else:
                    print("Now exiting...")
                self.wss.server_close()
        else:
            print(
                "Error! Couldn't initialize mode 1: Support for Server mode has been disabled since you don't have the required websocket_server.py!"
            )
            sys.exit()

    def client(self):
        if clientOrPluginModeSupport:
            self.mode = 2
            print("Oops. This is a WIP feature. Sorry...")
            sys.exit()
        else:
            print(
                "Error! Couldn't initialize mode 2: Support for Client mode has been disabled since you don't have the required library websocket-client!"
            )
            sys.exit()

    def plugin(self):
        if clientOrPluginModeSupport:
            self.mode = 3
            print("Oops. This is a WIP feature. Sorry...")
            sys.exit()
        else:
            print(
                "Error! Couldn't initialize mode 3: Support for Plugin mode has been disabled since you don't have the required library websocket-client!"
            )
            sys.exit()

    def newConnection(self, client, server):
        if self.mode == 1:
            print("New connection: {0}".format(client['id']))
            self.users[str(client)] = {"name": "", "id": str(client['id'])}
            self.relayUserList(server, True, client)
            self.sendPacket(server, True, {
                "cmd": "gmsg",
                "id": client,
                "val": str(self.gdata)
            })

    def sendPacket(self, server, type, data):  # False:Public, True:Private
        if self.mode == 1:
            if "id" in data:
                id = data["id"]
                del data["id"]
            if type == False:
                server.send_message_to_all(json.dumps(data))
            elif type == True:
                server.send_message(id, json.dumps(data))

    def relayUserList(self, server, type, id):
        if self.mode == 1:
            y = ""
            for x in range(len(self.userlist)):
                y = str(y + self.userlist[x] + ";")
            self.sendPacket(server, type, {
                "cmd": "ulist",
                "id": id,
                "val": str(y)
            })

    def closedConnection(self, client, server):
        if self.mode == 1:
            if str(client) in self.users:
                if self.users[str(client)]['name'] in self.userlist:
                    print("Connection closed: {0} ({1})".format(
                        self.users[str(client)]['name'], client['id']))
                else:
                    print("Connection closed: {0}".format(client['id']))

                if self.users[str(client)]['name'] in self.userlist:
                    del self.userlist[self.userlist.index(
                        self.users[str(client)]['name'])]
                if client in self.handlers:
                    del self.handlers[self.handlers.index(client)]

                del self.users[str(client)]

                if not len(self.users) == 0:
                    self.relayUserList(server, False, client)

    def gotPacket(self, client, server, message):
        if self.mode == 1:
            err = False
            try:
                packet = json.loads(message)
            except Exception as e:
                err = True
            finally:
                if not err:
                    if "cmd" in packet:  # Check if the cmd parameter is specified
                        cmd = packet['cmd']
                        if "val" in packet:
                            val = packet["val"]
                        else:
                            val = ""
                        if "id" in packet:
                            try:
                                id = self.handlers[self.userlist.index(
                                    str(packet['id']))]
                            except Exception as e:
                                id = ""
                        else:
                            id = ""
                        if "name" in packet:
                            name = str(packet['name'])
                        else:
                            name = ""

                        if cmd == "clear":  # Clears comms
                            self.sendPacket(server, False, {
                                "cmd": "gmsg",
                                "val": ""
                            })
                            self.sendPacket(server, False, {
                                "cmd": "pmsg",
                                "val": ""
                            })
                        if cmd == "setid":  # Set username on server link
                            if "val" in packet:
                                if not client in self.handlers:
                                    self.userlist.append(val)
                                    self.handlers.append(client)
                                else:
                                    if self.users[str(
                                            client)]['name'] in self.userlist:
                                        self.userlist[self.userlist.index(
                                            self.users[str(
                                                client)]['name'])] = val
                                self.users[str(client)]['name'] = val
                                print("User {0} declared username: {1}".format(
                                    client['id'],
                                    self.users[str(client)]['name']))
                                self.relayUserList(server, False, client)
                        if cmd == "gmsg":  # Set global stream data values
                            self.gdata = str(val)
                            self.sendPacket(server, False, {
                                "cmd": "gmsg",
                                "val": self.gdata
                            })
                        if cmd == "pmsg":  # Set private stream data values
                            if not id == "":
                                self.sendPacket(server, True, {
                                    "cmd": "pmsg",
                                    "id": id,
                                    "val": val
                                })
                        if cmd == "gvar":  # Set global variable data values
                            self.sendPacket(server, False, {
                                "cmd": "gvar",
                                "name": name,
                                "val": val
                            })
                        if cmd == "pvar":  # Set private variable data values
                            if not id == "":
                                self.sendPacket(
                                    server, True, {
                                        "cmd": "pvar",
                                        "name": name,
                                        "id": id,
                                        "val": val
                                    })
Ejemplo n.º 19
0
	print('Client disconnected')

# Receive data from client and put it in the input queue
def communicateWithClient(client, server, msg):
	print('recv: ' + msg)
	carConnectionSem.acquire()
	if (carIsConnected and msg in validInput):
		inputSem.acquire()
		inputQueue.append(msg)
		inputSem.release()
	carConnectionSem.release()

# Websocket to talk to client
websocket = WebsocketServer(clientPort)
websocket.set_fn_new_client(onClientConnection)
websocket.set_fn_client_left(onClientDisconnection)
websocket.set_fn_message_received(communicateWithClient)

# Handle car communications
def communicateWithCar():

	while(runServer):
		# Wait for car to connect
		c, addr = carSock.accept()
		isConnected = True
		global carIsConnected
		carConnectionSem.acquire()
		carIsConnected = True
		carConnectionSem.release()
		
		print('Car connected')
Ejemplo n.º 20
0
def runwebsocketserver():
    _logger = logging.getLogger(__name__)
    camera = None
    frame = None

    def _frame_rate_statistics_generator() -> Generator[float, bool, None]:
        """
        统计视频帧率
        :return:
        """
        count = 0
        begin_time = time.time()
        break_ = False
        while not break_:
            if count != 100:
                fps = 0.0
            else:
                end_time = time.time()
                fps = count / (end_time - begin_time)
                count = 0
                begin_time = time.time()
            count += 1
            break_ = yield fps

    def _draw_face_info(image: np.ndarray, face_info: FaceInfo) -> None:
        """
        将人脸的信息绘制到屏幕上
        :param face_info: 人脸信息
        :return: None
        """
        # 绘制人脸位置
        rect = face_info.rect
        color = (255, 0, 0) if face_info.name else (0, 0, 255)
        cv.rectangle(image, rect.top_left, rect.bottom_right, color, 2)
        # 绘制人的其它信息
        x, y = rect.top_middle
        put_text(image, "%s" % face_info, bottom_middle=(x, y - 2))
        # 绘制人脸 ID
        info = "%d" % face_info.arc_face_info.face_id
        x, y = rect.top_left
        put_text(image, info, left_top=(x + 2, y + 2))

    def _show_image(image: np.ndarray) -> int:
        global frame
        frame = image
        #cv.imshow("ArcFace Demo", image)
        #cv.waitKey(1)
        with open("profile.yml", "r", encoding="utf-8") as file:
            profile: Dict[str, str] = yaml.load(file, yaml.Loader)
            server_on = profile["server-on"].encode()
        if server_on == 0:
            return True
        return False

    @timer(output=_logger.info)
    def _run_1_n(image_source: ImageSource, face_process: FaceProcess) -> None:
        """
        1:n 的整个处理的逻辑
        :image_source: 识别图像的源头
        :face_process: 用来对人脸信息进行提取
        :return: None
        """
        with ArcFace(ArcFace.VIDEO_MODE) as arcface:
            cur_face_info = None  # 当前的人脸
            frame_rate_statistics = _frame_rate_statistics_generator()
            while True:
                # 获取视频帧
                image = image_source.read()
                # 检测人脸
                faces_pos = arcface.detect_faces(image)
                if len(faces_pos) == 0:
                    # 图片中没有人脸
                    cur_face_info = None
                else:
                    # 使用曼哈顿距离作为依据找出最靠近中心的人脸
                    center_y, center_x = image.shape[:2]
                    center_y, center_x = center_y // 2, center_x // 2
                    center_face_index = -1
                    min_center_distance = center_x + center_y + 4
                    cur_face_index = -1
                    for i, pos in enumerate(faces_pos):
                        if cur_face_info is not None and pos.face_id == cur_face_info.arc_face_info.face_id:
                            cur_face_index = i
                            break
                        x, y = pos.rect.center
                        if x + y < min_center_distance:
                            center_face_index = i
                            min_center_distance = x + y
                    if cur_face_index != -1:
                        # 上一轮的人脸依然在,更新位置信息
                        cur_face_info.arc_face_info = faces_pos[cur_face_index]
                    else:
                        # 上一轮的人脸不在了,选择当前所有人脸的最大人脸
                        cur_face_info = FaceInfo(faces_pos[center_face_index])
                if cur_face_info is not None:
                    # 异步更新人脸的信息
                    if cur_face_info.need_update():
                        face_process.async_update_face_info(
                            image, cur_face_info)
                    # 绘制人脸信息
                    _draw_face_info(image, cur_face_info)
                    # 绘制中心点
                    # put_text(image, "x", bottom_middle=(center_x, center_y))
                # 显示到界面上
                if _show_image(image):
                    break
                # 统计帧率
                fps = next(frame_rate_statistics)
                if fps:
                    _logger.info("FPS: %.2f" % fps)

    @timer(output=_logger.info)
    def _run_m_n(image_source: ImageSource, face_process: FaceProcess) -> None:
        with ArcFace(ArcFace.VIDEO_MODE) as arcface:
            faces_info: Dict[int, FaceInfo] = {}
            frame_rate_statistics = _frame_rate_statistics_generator()
            while True:
                # 获取视频帧
                image = image_source.read()
                # 检测人脸
                faces_pos: Dict[int, ArcFaceInfo] = {}
                for face_pos in arcface.detect_faces(image):
                    faces_pos[face_pos.face_id] = face_pos
                # 删除过期 id, 添加新的 id
                cur_faces_id = faces_pos.keys()
                last_faces_id = faces_info.keys()
                for face_id in last_faces_id - cur_faces_id:
                    faces_info[face_id].cancel()  # 如果有操作在进行,这将取消操作
                    faces_info.pop(face_id)
                for face_id in cur_faces_id:
                    if face_id in faces_info:
                        # 人脸已经存在,只需更新位置就好了
                        faces_info[face_id].arc_face_info = faces_pos[face_id]
                    else:
                        faces_info[face_id] = FaceInfo(faces_pos[face_id])

                # 更新人脸的信息
                # for face_info in faces_info:
                #     face_process.async_update_face_info(image, face_info)
                opt_face_info = None
                for face_info in filter(lambda x: x.need_update(),
                                        faces_info.values()):
                    if opt_face_info is None or opt_face_info.rect.size < face_info.rect.size:
                        opt_face_info = face_info

                if opt_face_info is not None:
                    face_process.async_update_face_info(image, opt_face_info)
                # 绘制人脸信息
                for face_info in faces_info.values():
                    _draw_face_info(image, face_info)

                if _show_image(image):
                    break
                # 统计帧率
                fps = next(frame_rate_statistics)
                if fps:
                    _logger.info("FPS: %.2f" % fps)

    def new_client(client, server):
        print("New client connected and was given id %d" % client['id'])
        # 发送给所有的连接
        server.send_message_to_all("Hey all, a new client has joined us")

    def client_left(client, server):
        id = 1
        #print("Client(%d) disconnected" % client['id'])

    def message_received(client, server, message):
        if len(message) > 200:
            message = message[:200] + '..'
        print("Client(%d) said: %s" % (client['id'], message))
        #with open("profile.yml", "r", encoding="utf-8") as file:
        #    profile: Dict[str, str] = yaml.load(file, yaml.Loader)
        #    rtsp = profile["camera"][message].encode().decode("gbk", "strict")
        #global camera
        #camera.set_camera(rtsp)
        # 发送给所有的连接

    def from_vedio():
        thread2 = threading.Thread(target=face_recognition, args=(1, ))
        thread2.start()
        thread1 = threading.Thread(target=vedio_send, args=(1, ))
        thread1.start()
        print('webserver start')

    def vedio_send(n):
        global frame
        while True:
            with open("profile.yml", "r", encoding="utf-8") as file:
                profile: Dict[str, str] = yaml.load(file, yaml.Loader)
                server_on = profile["server-on"].encode()
            if server_on == 0:
                break
            if len(server.clients) > 0:
                image = cv.imencode('.jpg', frame)[1]
                base64_data = base64.b64encode(image)
                s = base64_data.decode()
                # print('data:image/jpeg;base64,%s'%s)
                server.send_message_to_all('data:image/jpeg;base64,%s' % s)
            time.sleep(0.01)

    def face_recognition(n):
        global camera
        camera = LocalCamera()
        with open("profile.yml", "r", encoding="utf-8") as file:
            profile: Dict[str, str] = yaml.load(file, yaml.Loader)
            ArcFace.APP_ID = profile["app-id"].encode()
            ArcFace.SDK_KEY = profile["sdk-key"].encode()
        face_process = FaceProcess()

        class AutoCloseOpenCVWindows:
            def __enter__(self):
                pass

            def __exit__(self, exc_type, exc_val, exc_tb):
                cv.destroyAllWindows()

        """
            加载人脸部分
            逻辑->30s刷新一次feature
        """
        update_feature = threading.Thread(target=face_process.load_features)
        update_feature.start()
        with face_process, AutoCloseOpenCVWindows():
            run = _run_m_n  #_run_1_n if args.single
            with camera:
                run(camera, face_process)

    server = WebsocketServer(port=8124, host='127.0.0.1')
    from_vedio()
    # 有设备连接上了
    server.set_fn_new_client(new_client)
    # 断开连接
    server.set_fn_client_left(client_left)
    # 接收到信息
    server.set_fn_message_received(message_received)
    # 开始监听
    server.run_forever()
Ejemplo n.º 21
0
class ScriptHandler(object):
    to_process = []

    def __init__(self):
        self.scripts = []
        self.API_Key = binascii.b2a_base64(os.urandom(15))[:-1]
        self.API_Socket = "ws://127.0.0.1:3337/streamlabs"
        self.websocket = None
        self.script_folders = [
            f for f in os.listdir(script_path)
            if os.path.isdir(os.path.join(script_path, f))
        ]
        for script_folder in self.script_folders:
            content = os.listdir(os.path.join(script_path, script_folder))
            script_name = script_folder + "_StreamlabsSystem"
            if script_name + ".py" in content and "UI_Config.json" in content:
                try:
                    specific_scripth_path = os.path.join(
                        script_path, script_folder)
                    self.scripts.append(
                        self.import_by_filename(
                            os.path.join(specific_scripth_path,
                                         script_name + ".py")))
                    self.insert_API_Key(specific_scripth_path)
                except Exception as e:
                    print e.message
                    traceback.print_exc()
            else:
                print("invalid script folder: " + script_folder)

    def insert_API_Key(self, dir_path):
        api_file = os.path.join(dir_path, "API_KEY.js")
        try:
            with codecs.open(api_file, encoding="utf-8-sig", mode="w") as f:
                f.write('var API_Key = "{0}";\nvar API_Socket = "{1}";'.format(
                    self.API_Key, self.API_Socket))
        except:
            traceback.print_exc()

    def start_websocket(self):
        self.websocket = WebsocketServer(3337, "127.0.0.1")
        self.websocket.set_fn_new_client(Parent.on_client_connect)
        self.websocket.set_fn_client_left(Parent.on_client_disconnect)
        self.websocket.set_fn_message_received(Parent.on_message)
        thread = Thread(target=self.websocket.run_forever)
        thread.daemon = True
        thread.start()
        Parent.websocket = self.websocket
        Parent.API_Key = self.API_Key

    def init(self):
        self.start_websocket()
        for script in self.scripts:
            script.Parent = Parent
            script.Init()

    def scripts_loop(self):
        self.init()
        next_t = 0
        live_check = 0
        while not stopped.is_set():
            if time.time() < live_check:
                Parent.stream_online = MixerChat.mixerApi.get_channel_online()
                live_check = time.time() + 120
            if len(self.to_process) > 0:
                data = self.to_process.pop(0)
                for script in self.scripts:
                    try:
                        script.Execute(data)
                    except Exception as e:
                        print 'Error', e.message
                        traceback.print_exc()
                    if Parent.stop:
                        Parent.stop = False
                        break
            if time.time() > next_t:
                next_t = time.time() + 0.1
                for script in self.scripts:
                    try:
                        script.Tick()
                    except Exception as e:
                        print 'Error', e.message
                        traceback.print_exc()

    @staticmethod
    def import_by_filename(filename):
        directory, module_name = os.path.split(filename)
        module_name = os.path.splitext(module_name)[0]

        path = list(sys.path)
        sys.path.insert(0, directory)
        try:
            module = __import__(module_name)
        finally:
            sys.path[:] = path  # restore
        return module
Ejemplo n.º 22
0
class websocketserver:

    cameras = {}
    tags = {}
    users = {}
    calibration = {}

    port=8001

    # Called for every client connecting (after handshake)
    def new_client_connection(self, client, server):
        print("New client connected and was given id %d" %  client['id'] +" and  address " + str(client['address']))
        server.send_message(client, "Client connected succesfully")


    # Called for every client disconnecting
    def client_left(self, client, server):
        print("Client(%d) disconnected" % client['id'])
        # Remove client from its list
        # TODO better delete (remove points etc...)

        if(str(client['address']) in self.cameras):
            print "Camera disconnected : " + str(client['address'])
            del self.cameras[str(client['address'])]

        elif(str(client['address']) in self.users):
            # Remove Tag assignement because User left
            print "User disconnected : " + str(client['address'])
            self.users[str(client['address'])].removeTag()
            del self.users[str(client['address'])]

        elif(str(client['address']) in self.calibration):
            print "Calibration disconnected : " + str(client['address'])
            del self.calibration[str(client['address'])]

        elif(str(client['address']) in self.tags):
            print "Tag disconnected : " + str(client['address'])
            # Remove Tag assignement to User because Tag left AND kill 3D point
            for key in self.users:
                if self.users[key].tag == self.tags[str(client['address'])]:
                    self.users[key].removeTag()
            del self.tags[str(client['address'])]


    # Called when a client sends a message
    def message_received(self, client, server, message):
        self.parseMessage(client, message)

    def __init__(self, host='127.0.0.1'):
        self.server = WebsocketServer(self.port, host)
        self.server.set_fn_new_client(self.new_client_connection)
        self.server.set_fn_client_left(self.client_left)
        self.server.set_fn_message_received(self.message_received)
        self.server.run_forever()


    def parseMessage(self, client, message):
        """
        Check who is the message from to redirect it to User / Tag / Camera / Calibration
        or create a new instance of User / Tag / Camera / Calibration
        :param client:
        :param message:
        :return:
        """
        if self.cameras.has_key(str(client['address'])):
            #print "Message from Camera"
            self.cameras[str(client['address'])].push(message)
            # Update all cameras counters
            #Todo: Change this method for checking all cameras for lost point (auto check inside point2D ?)
            for key in self.cameras.keys():
                self.cameras[key].update()

        elif self.users.has_key(str(client['address'])):
            print "Message from User"

        elif self.tags.has_key(str(client['address'])):
            print "Message from Tag"

        elif self.calibration.has_key(str(client['address'])):
            self.calibration[str(client['address'])].push(message)
            print "Message from Calibration"

        # This message is coming from an unknown client
        else:
            if message.split("-")[0] == "camera":
                self.cameras[str(client['address'])] = Camera(client, message.split("-")[1])
                # Add Observers linking every user to every camera's update
                for key in self.users:
                    if isinstance(self.users[key], User):
                        self.cameras[str(client['address'])].new2DPointNotifier.addObserver(self.users[key].position.newPoint2DObserver)
                        self.cameras[str(client['address'])].point2DdeletedNotifier.addObserver(self.users[key].position.point2DDeletedObserver)

            elif message.split("-")[0] == "tag":
                self.tags[str(client['address'])] = Tag(self.server, client, message.split("-")[1])
                for key in self.users:
                    if isinstance(self.users[key], User):
                        # Assign a Tag to User with no Tag
                        if self.users[key].tag == None:
                            self.users[key].setTag(self.tags[str(client['address'])])

            elif message.split("-")[0] == "user":
                user = User(self.server, client, message.split("-")[1])
                self.users[str(client['address'])] = user
                # Add Observers linking every user to every camera's update
                for key in self.cameras:
                    if isinstance(self.cameras[key], Camera):
                        self.cameras[key].new2DPointNotifier.addObserver(user.position.newPoint2DObserver)
                        self.cameras[key].point2DdeletedNotifier.addObserver(user.position.point2DDeletedObserver)

                for key in self.tags:
                    if isinstance(self.tags[key], Tag):
                        # Assign a Tag to new User
                        if self.tags[key].isAssigned() == False:
                            user.setTag(self.tags[key])

            elif message == "calibration":
                if(len(self.tags)>0):
                    self.calibration[str(client['address'])] = Calibration(self.server, client, self.cameras, self.tags.values()[0])
                else:
                    self.server.send_message(client, "Please connect a Tag first, and start Calibration again.")
Ejemplo n.º 23
0
 def __init__(self, host='127.0.0.1'):
     server = WebsocketServer(self.port, host)
     server.set_fn_new_client(self.new_client_connection)
     server.set_fn_client_left(self.client_left)
     server.set_fn_message_received(self.message_received)
     server.run_forever()
Ejemplo n.º 24
0
def on_client_left(client, server):
    print('Client {} Left.'.format(client['id']))


def on_message(client, server, message):
    print('Msg from Client {}: {}'.format(client['id'], message))

    # magic string for shutdown server :-)
    if message.startswith('close-server'):
        print('Stopping Server ...')
        thread.start_new_thread(kill_server, (ws_server,))
        print('Server stopped!')


ws_server.set_fn_new_client(on_new_client)
ws_server.set_fn_client_left(on_client_left)
ws_server.set_fn_message_received(on_message)

thread.start_new_thread(ws_server.run_forever, ())
ws_server.IS_ONLINE = True

while ws_server.IS_ONLINE:
    import time
    print('Trying to do something ...')
    time.sleep(30)

    print('Starting get profile ...')

    print('Save to ' + tmp_dir)
    ws_server.send_message_to_all(tmp_dir)
    time.sleep(10)
Ejemplo n.º 25
0
class websocketserver:

    cameras = {}
    tags = {}
    users = {}
    calibration = {}

    port=8001

    # Called for every client connecting (after handshake)
    def new_client_connection(self, client, server):
        print("New client connected and was given id %d" %  client['id'] +" and  address " + str(client['address']))
        server.send_message(client, "Client connected succesfully")


    # Called for every client disconnecting
    def client_left(self, client, server):
        print("Client(%d) disconnected" % client['id'])
        #TODO : Remove from list

    # Called when a client sends a message
    def message_received(self, client, server, message):
#        print("Client(%d) said: %s" % (client['id'], message))
        self.parseMessage(client, message)

    def __init__(self, host='127.0.0.1'):
        self.server = WebsocketServer(self.port, host)
        self.server.set_fn_new_client(self.new_client_connection)
        self.server.set_fn_client_left(self.client_left)
        self.server.set_fn_message_received(self.message_received)
        self.server.run_forever()


    def parseMessage(self, client, message):
        """
        Check who is the message from to redirect it to User / Tag / Camera / Calibration
        or create a new instance of User / Tag / Camera / Calibration
        :param client:
        :param message:
        :return:
        """
        if self.cameras.has_key(str(client['address'])):
            #print "Message from Camera"
            self.cameras[str(client['address'])].push(message)

        elif self.users.has_key(str(client['address'])):
            print "Message from User"

        elif self.tags.has_key(str(client['address'])):
            print "Message from Tag"

        elif self.calibration.has_key(str(client['address'])):
            self.calibration[str(client['address'])].push(message)
            print "Message from Calibration"

        # This message is coming from an unknown client
        else:
            if message.split("-")[0] == "camera":
                self.cameras[str(client['address'])] = Camera(client, message.split("-")[1])
                # Add Observers linking every user to every camera's update
                for key in self.users:
                    if isinstance(self.users[key], User):
                        self.cameras[str(client['address'])].new2DPointNotifier.addObserver(self.users[key].position.newPoint2DObserver)
                        self.cameras[str(client['address'])].point2DdeletedNotifier.addObserver(self.users[key].position.point2DDeletedObserver)

            elif message.split("-")[0] == "tag":
                print "Hello TAG"
                # TODO

            elif message.split("-")[0] == "user":
                user = User(client, self.server, message.split("-")[1])
                self.users[str(client['address'])] = user
                # Add Observers linking every user to every camera's update
                for key in self.cameras:
                    if isinstance(self.cameras[key], Camera):
                        self.cameras[key].new2DPointNotifier.addObserver(user.position.newPoint2DObserver)
                        self.cameras[key].point2DdeletedNotifier.addObserver(user.position.point2DDeletedObserver)

            elif message == "calibration":
                self.calibration[str(client['address'])] = Calibration(self.cameras, self.server, client)
Ejemplo n.º 26
0
class MockSocket:
    def __init__(self):
        self.last_messages = {}
        self.connected = False
        self.disconnected = False
        self.closed = False
        self.ws = None
        self.should_heartbeat = True
        self.fake_workers = []
        self.port = None
        self.launch_socket()
        self.handlers = {}
        while self.ws is None:
            time.sleep(0.05)
        time.sleep(1)

    def send(self, packet):
        self.ws.send_message_to_all(packet)

    def close(self):
        if not self.closed:
            self.ws.server_close()
            self.ws.shutdown()
            self.closed = True

    def do_nothing(self, *args):
        pass

    def launch_socket(self):
        def on_message(client, server, message):
            if self.closed:
                raise Exception('Socket is already closed...')
            if message == '':
                return
            packet_dict = json.loads(message)
            if packet_dict['content']['id'] == 'WORLD_ALIVE':
                self.ws.send_message(client,
                                     json.dumps({'type': 'conn_success'}))
                self.connected = True
            elif packet_dict['content']['type'] == 'heartbeat':
                pong = packet_dict['content'].copy()
                pong['type'] = 'pong'
                self.ws.send_message(
                    client,
                    json.dumps({
                        'type': data_model.SOCKET_ROUTE_PACKET_STRING,
                        'content': pong
                    }),
                )
            if 'receiver_id' in packet_dict['content']:
                receiver_id = packet_dict['content']['receiver_id']
                assignment_id = packet_dict['content']['assignment_id']
                use_func = self.handlers.get(receiver_id + assignment_id,
                                             self.do_nothing)
                use_func(packet_dict['content'])

        def on_connect(client, server):
            pass

        def on_disconnect(client, server):
            self.disconnected = True

        def run_socket(*args):
            port = 3030
            while self.port is None:
                try:
                    self.ws = WebsocketServer(port, host='127.0.0.1')
                    self.port = port
                except OSError:
                    port += 1
            self.ws.set_fn_client_left(on_disconnect)
            self.ws.set_fn_new_client(on_connect)
            self.ws.set_fn_message_received(on_message)
            self.ws.run_forever()

        self.listen_thread = threading.Thread(target=run_socket,
                                              name='Fake-Socket-Thread')
        self.listen_thread.daemon = True
        self.listen_thread.start()
Ejemplo n.º 27
0
class WSServer:
    def __init__(self, port=9007):
        self.port = port
        self.server = WebsocketServer(self.port, host='0.0.0.0')
        self.server.set_fn_new_client(self.on_connect)
        self.server.set_fn_message_received(self.on_msg)
        self.server.set_fn_client_left(self.on_disconnect)
        self.msg_lock = Lock()

    def ping(self):
        self.server.send_message_to_all(json.dumps({'action': 'ping'}))

        # pinging every 50 seconds to avoid disconnection
        t = Timer(50, self.ping)
        t.start()

    def on_connect(self, client, server):
        #server.send_message_to_all("Hey all, a new client has joined us")
        pass

    def on_disconnect(self, client, server):
        #server.send_message_to_all("Hey all, a new client has joined us")
        pass

    def on_msg(self, client, server, message):
        self.msg_lock.acquire()
        try:
            args = message.split(' ')
            command = args[0]
            args = args[1:]
            internal = 'internal_ws_' + command
            if hasattr(self, internal):
                getattr(self, internal)(client, *args)
            else:
                data = {'action': 'cmd', 'msg': 'not found'}
                self.server.send_message(client, json.dumps(data))
        except Exception as e:
            print("Error: ", e)

        connection.close()
        self.msg_lock.release()

    def run(self):
        self.ping()
        self.server.run_forever()

    def drop_seat(self, hold):
        session = hold.session
        layout = hold.layout

        row, col = hold.seat.split('-')
        data = {
            'action': 'drop',
            'session': session.id,
            'layout': layout.id,
            'row': row,
            'col': col,
        }

        hold.delete()

        confirmed = not session.is_seat_available(layout, row, col)
        if confirmed:
            data['action'] = 'confirm'

        self.server.send_message_to_all(json.dumps(data))

    def notify_confirmed(self):
        d = timezone.now()
        d = d - datetime.timedelta(seconds=80)
        holds = TicketSeatHold.objects.filter(date__gt=d, type="R")
        for h in holds:
            row, col = h.seat.split('-')
            data = {
                'action': 'confirm',
                'session': h.session.id,
                'layout': h.layout.id,
                'row': row,
                'col': col,
            }
            self.server.send_message_to_all(json.dumps(data))

    # Protocol definitions

    def internal_ws_autoseats(self, client, session, amount, user):
        session = Session.objects.get(id=session)
        seats = search_seats(session, int(amount))
        data = {
            'action': 'autoseat',
            'session': session.id,
            'seats': seats,
        }

        for s in seats:
            layout = SeatLayout.objects.get(id=s['layout'])
            seat = '{}-{}'.format(s['row'], s['col'])

            d2 = {
                'action': 'hold',
                'session': session.id,
                'layout': layout.id,
                'row': s['row'],
                'col': s['col'],
            }
            sh = TicketSeatHold(client=user,
                                layout=layout,
                                seat=seat,
                                session=session)
            sh.save()
            self.server.send_message_to_all(json.dumps(d2))

        if not seats:
            data['error'] = _('Not found contiguous seats, please, select manually using the green button')

        self.server.send_message(client, json.dumps(data))

    def internal_ws_get_events(self, client):
        events = serializers.serialize("json", Event.objects.all())
        self.server.send_message(client, events)

    def internal_ws_get_spaces(self, client, event):
        event = Event.objects.get(slug=event)
        spaces = serializers.serialize("json", event.spaces.all())
        self.server.send_message(client, spaces)

    def internal_ws_get_sessions(self, client, event, space):
        event = Event.objects.get(slug=event)
        space = event.spaces.get(slug=space)
        sessions = serializers.serialize("json", space.sessions.all())
        self.server.send_message(client, sessions)

    def internal_ws_hold_seat(self, client, session, layout, row, col, user):
        session = Session.objects.get(id=session)
        layout = SeatLayout.objects.get(id=layout)
        data = {
            'action': 'hold',
            'session': session.id,
            'layout': layout.id,
            'row': row,
            'col': col,
        }

        if not session.is_seat_holded(layout, row, col):
            seat = row + '-' + col
            sh = TicketSeatHold(client=user, layout=layout, seat=seat,
                                session=session)
            sh.save()
            self.server.send_message_to_all(json.dumps(data))
        else:
            data['action'] = 'holded'
            self.server.send_message(client, json.dumps(data))

    def internal_ws_drop_seat(self, client, session, layout, row, col, user):
        try:
            seat = row + '-' + col
            sh = TicketSeatHold.objects.get(client=user,
                                            type='H',
                                            layout=layout,
                                            seat=seat,
                                            session=session)
            self.drop_seat(sh)
        except:
            pass

    def internal_ws_add_ac(self, client, control, date, st):
        data = {
            'action': 'add_ac',
            'control': control,
            'date': date,
            'st': st,
        }
        log = LogAccessControl(access_control=AccessControl.objects.get(slug=control), status=st)
        log.save()
        self.server.send_message_to_all(json.dumps(data))

    def internal_ws_add_sale(self, client, window, date, payment, amount, price):
        data = {
            'action': 'add_sale',
            'window': window,
            'date': date,
            'payment': payment,
            'amount': amount,
            'price': price
        }
        self.server.send_message_to_all(json.dumps(data))

    def internal_ws_add_change(self, client, window, date, payment, amount, price):
        data = {
            'action': 'add_change',
            'window': window,
            'date': date,
            'payment': payment,
            'amount': amount,
            'price': price
        }
        self.server.send_message_to_all(json.dumps(data))
Ejemplo n.º 28
0
def SocketServerStart():
    server = WebsocketServer(SOCKET_PORT, HOST)
    server.set_fn_new_client(NewClient)
    server.set_fn_client_left(ClientLeft)
    server.set_fn_message_received(MessageReceived)
    server.run_forever()
Ejemplo n.º 29
0
#!/usr/bin/env python
from websocket_server import WebsocketServer
import hashlib
import os

def nuevo_cliente(client, server):
	print("Cliente (%s) nuevo" % client['address'][0])

def mensaje_recibido(client, server, mensaje):
	audio = hashlib.md5(client['address'][0]).hexdigest()
	file = open("podcast/"+audio, "ab")
	file.write(mensaje)
	file.close()

def desconectado(client, server):
	audio = hashlib.md5(client['address'][0]).hexdigest()
	os.remove("podcast/"+audio)
	print("Cliente (%s) desconectado" % client['address'][0])



PORT=9000
server = WebsocketServer(PORT,"192.168.1.2")
server.set_fn_new_client(nuevo_cliente)
server.set_fn_client_left(desconectado)
server.set_fn_message_received(mensaje_recibido)
server.run_forever()
Ejemplo n.º 30
0
class Template:
    # Initialize class variables
    # self.time_cycle to run an execution for atleast 1 second
    # self.process for the current running process
    def __init__(self):
        self.thread = None
        self.reload = False
        
        # Time variables
        self.time_cycle = 80
        self.ideal_cycle = 80
        self.iteration_counter = 0
        self.real_time_factor = 0
        self.frequency_message = {'brain': '', 'gui': '',  'rtf': ''}
                
        self.server = None
        self.client = None
        self.host = sys.argv[1]

        # Initialize the GUI, HAL and Console behind the scenes
        self.hal = HAL()
        self.gui = GUI(self.host, self.hal)
     
    # Function for saving   
    def save_code(self, source_code):
    	with open('code/academy.py', 'w') as code_file:
    		code_file.write(source_code)
    
    # Function for loading		
    def load_code(self):
    	with open('code/academy.py', 'r') as code_file:
    		source_code = code_file.read()
    		
    	return source_code

    # Function to parse the code
    # A few assumptions: 
    # 1. The user always passes sequential and iterative codes
    # 2. Only a single infinite loop
    def parse_code(self, source_code):
    	# Check for save/load
    	if(source_code[:5] == "#save"):
    		source_code = source_code[5:]
    		self.save_code(source_code)
    		
    		return "", ""
    	
    	elif(source_code[:5] == "#load"):
    		source_code = source_code + self.load_code()
    		self.server.send_message(self.client, source_code)
    
    		return "", ""

        elif(source_code[:5] == "#resu"):
                restart_simulation = rospy.ServiceProxy('/gazebo/unpause_physics', Empty)
                restart_simulation()

                return "", ""

        elif(source_code[:5] == "#paus"):
                pause_simulation = rospy.ServiceProxy('/gazebo/pause_physics', Empty)
                pause_simulation()

                return "", ""
    		
    	elif(source_code[:5] == "#rest"):
    		reset_simulation = rospy.ServiceProxy('/gazebo/reset_world', Empty)
    		reset_simulation()
    		self.gui.reset_gui()
    		return "", ""
    		
    	else:
    		# Get the frequency of operation, convert to time_cycle and strip
    		try:
        		# Get the debug level and strip the debug part
        		debug_level = int(source_code[5])
        		source_code = source_code[12:]
        	except:
        		debug_level = 1
        		source_code = ""
    		
    		source_code = self.debug_parse(source_code, debug_level)
    		sequential_code, iterative_code = self.seperate_seq_iter(source_code)
    		return iterative_code, sequential_code
			
        
    # Function to parse code according to the debugging level
    def debug_parse(self, source_code, debug_level):
    	if(debug_level == 1):
    		# If debug level is 0, then all the GUI operations should not be called
    		source_code = re.sub(r'GUI\..*', '', source_code)
    		
    	return source_code
    
    # Function to seperate the iterative and sequential code
    def seperate_seq_iter(self, source_code):
    	if source_code == "":
            return "", ""

        # Search for an instance of while True
        infinite_loop = re.search(r'[^ \t]while\(True\):|[^ \t]while True:', source_code)

        # Seperate the content inside while True and the other
        # (Seperating the sequential and iterative part!)
        try:
            start_index = infinite_loop.start()
            iterative_code = source_code[start_index:]
            sequential_code = source_code[:start_index]

            # Remove while True: syntax from the code
            # And remove the the 4 spaces indentation before each command
            iterative_code = re.sub(r'[^ ]while\(True\):|[^ ]while True:', '', iterative_code)
            iterative_code = re.sub(r'^[ ]{4}', '', iterative_code, flags=re.M)

        except:
            sequential_code = source_code
            iterative_code = ""
            
        return sequential_code, iterative_code


    # The process function
    def process_code(self, source_code):
        
        # Redirect the information to console
        start_console()

        iterative_code, sequential_code = self.parse_code(source_code)
        
        # Whatever the code is, first step is to just stop!
        self.hal.motors.sendV(0)
        self.hal.motors.sendW(0)

        # print("The debug level is " + str(debug_level)
        # print(sequential_code)
        # print(iterative_code)

        # The Python exec function
        # Run the sequential part
        gui_module, hal_module = self.generate_modules()
        reference_environment = {"GUI": gui_module, "HAL": hal_module}
        exec(sequential_code, reference_environment)

        # Run the iterative part inside template
        # and keep the check for flag
        while self.reload == False:
            start_time = datetime.now()

            # Execute the iterative portion
            exec(iterative_code, reference_environment)

            # Template specifics to run!
            finish_time = datetime.now()
            dt = finish_time - start_time
            ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0

            # Keep updating the iteration counter
            if (iterative_code == ""):
                self.iteration_counter = 0
            else:
                self.iteration_counter = self.iteration_counter + 1

            # The code should be run for atleast the target time step
            # If it's less put to sleep
            if (ms < self.time_cycle):
                time.sleep((self.time_cycle - ms) / 1000.0)

        close_console()
        print("Current Thread Joined!")

    # Function to generate the modules for use in ACE Editor
    def generate_modules(self):
        # Define HAL module
        hal_module = imp.new_module("HAL")
        hal_module.HAL = imp.new_module("HAL")
        hal_module.HAL.motors = imp.new_module("motors")

        # Add HAL functions
        hal_module.HAL.getPose3d = self.hal.pose3d.getPose3d
        hal_module.HAL.motors.sendV = self.hal.motors.sendV
        hal_module.HAL.motors.sendW = self.hal.motors.sendW
        hal_module.HAL.laser = self.hal.laser
        hal_module.HAL.getLaserData = self.hal.laser.getLaserData
        hal_module.HAL.bumper = self.hal.bumper

        # Define GUI module
        gui_module = imp.new_module("GUI")
        gui_module.GUI = imp.new_module("GUI")

        # Add GUI functions
        # gui_module.GUI.showImage = self.gui.showImage

        # Adding modules to system
        # Protip: The names should be different from
        # other modules, otherwise some errors
        sys.modules["HAL"] = hal_module
        sys.modules["GUI"] = gui_module

        return gui_module, hal_module
            
    # Function to measure the frequency of iterations
    def measure_frequency(self):
        previous_time = datetime.now()
        # An infinite loop
        while self.reload == False:
            # Sleep for 2 seconds
            time.sleep(2)
            
            # Measure the current time and subtract from the previous time to get real time interval
            current_time = datetime.now()
            dt = current_time - previous_time
            ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
            previous_time = current_time
            
            # Get the time period
            try:
            	# Division by zero
            	self.ideal_cycle = ms / self.iteration_counter
            except:
            	self.ideal_cycle = 0
            
            # Reset the counter
            self.iteration_counter = 0

            self.send_frequency_message()

    # Function to generate and send frequency messages
    def send_frequency_message(self):
        # This function generates and sends frequency measures of the brain and gui
        brain_frequency = 0; gui_frequency = 0
        try:
            brain_frequency = round(1000 / self.ideal_cycle, 1)
        except ZeroDivisionError:
            brain_frequency = 0

        try:
            gui_frequency = round(1000 / self.thread_gui.ideal_cycle, 1)
        except ZeroDivisionError:
            gui_frequency = 0

        self.frequency_message["brain"] = brain_frequency
        self.frequency_message["gui"] = gui_frequency
        self.frequency_message["rtf"] = self.real_time_factor

        message = "#freq" + json.dumps(self.frequency_message)
        self.server.send_message(self.client, message)
    
    # Function to maintain thread execution
    def execute_thread(self, source_code):
        # Keep checking until the thread is alive
        # The thread will die when the coming iteration reads the flag
        if(self.thread != None):
            while self.thread.is_alive() or self.measure_thread.is_alive():
                pass

        # Turn the flag down, the iteration has successfully stopped!
        self.reload = False
        # New thread execution
        self.measure_thread = threading.Thread(target=self.measure_frequency)
        self.thread = threading.Thread(target=self.process_code, args=[source_code])
        self.thread.start()
        self.measure_thread.start()
        print("New Thread Started!")

    # Function to track the real time factor from Gazebo statistics
    # https://stackoverflow.com/a/17698359
    # (For reference, Python3 solution specified in the same answer)
    def track_stats(self):
        args = ["gz", "stats", "-p"]
        # Prints gz statistics. "-p": Output comma-separated values containing-
        # real-time factor (percent), simtime (sec), realtime (sec), paused (T or F)
        stats_process = subprocess.Popen(args, stdout=subprocess.PIPE, bufsize=1)
        # bufsize=1 enables line-bufferred mode (the input buffer is flushed
        # automatically on newlines if you would write to process.stdin )
        with stats_process.stdout:
            for line in iter(stats_process.stdout.readline, b''):
                stats_list = [x.strip() for x in line.split(',')]
                self.real_time_factor = stats_list[0]


    # Function to read and set frequency from incoming message
    def read_frequency_message(self, message):
        frequency_message = json.loads(message)

        # Set brain frequency
        frequency = float(frequency_message["brain"])
        self.time_cycle = 1000.0 / frequency

        # Set gui frequency
        frequency = float(frequency_message["gui"])
        self.thread_gui.time_cycle = 1000.0 / frequency

        return

    # The websocket function
    # Gets called when there is an incoming message from the client
    def handle(self, client, server, message):
        if(message[:5] == "#freq"):
            frequency_message = message[5:]
            self.read_frequency_message(frequency_message)
            time.sleep(1)
            self.send_frequency_message()
            return
        
        try:
            # Once received turn the reload flag up and send it to execute_thread function
            code = message
            # print(repr(code))
            self.reload = True
            self.execute_thread(code)
        except:
            pass

    # Function that gets called when the server is connected
    def connected(self, client, server):
    	self.client = client
    	# Start the GUI update thread
    	self.thread_gui = ThreadGUI(self.gui)
    	self.thread_gui.start()

        # Start the real time factor tracker thread
        self.stats_thread = threading.Thread(target=self.track_stats)
        self.stats_thread.start()

        # Initialize the ping message
        self.send_frequency_message()
    	
    	print(client, 'connected')
    	
    # Function that gets called when the connected closes
    def handle_close(self, client, server):
    	print(client, 'closed')
    	
    def run_server(self):
    	self.server = WebsocketServer(port=1905, host=self.host)
    	self.server.set_fn_new_client(self.connected)
    	self.server.set_fn_client_left(self.handle_close)
    	self.server.set_fn_message_received(self.handle)
    	self.server.run_forever()
Ejemplo n.º 31
0
def webServer():
    
    usersfd = open("users.json", "r") 
    users = json.load(usersfd)
    usersfd.close()

    def new_client(client, server):
        print("New client connected and was given id %d" % client['id'])

    def client_left(client, server):
        print("Client(%d) disconnected" % client['id'])

    def message_received(client, server, message):
        #print("received message from client id %d " %  client['id'])
        #logging.info("received message from client id %d " %  client['id'])
        msg = json.loads(message)

        if msg["action"] == AUTHENTICATE:
            print 'msg is AUTHENTICATE' 
            resp = {"action": AUTHENTICATE, "data": None}
            username = msg["data"].get("username") if msg["data"].has_key("username") else None
            password = msg["data"].get("password") if msg["data"].has_key("password") else None

            if username and password and users.has_key(username) and password == users[username]:
                print "AUTHSUCCESS"
                resp["data"] = AUTHSUCCESS
            else:
                print "AUTHFAIL"
                resp["data"] = AUTHFAIL
                
            server.send_message(client, json.dumps(resp) )
            
        elif msg["action"] == GETBANNEDIPs:
            #print 'msg is GETBANNEDIPs' 
            #logging.info('msg is GETBANNEDIPs')
            resp = {"action": GETBANNEDIPs, "data": []}
            username = msg["data"].get("username") if msg["data"].has_key("username") else None
            password = msg["data"].get("password") if msg["data"].has_key("password") else None

            if username and password and users.has_key(username) and password == users[username]:
                for bannedIP in bannedIPs.values():
                    ip = {}
                    ip["IP"] = bannedIP.IP
                    ip["time"] = time.strftime("%b %d %H:%M:%S", time.localtime(bannedIP.time))
                    ip["timer"] = bannedIP.timer - (time.time() - bannedIP.time)
                    ip["service"] = bannedIP.service
                    resp["data"].append(ip)
                server.send_message(client, json.dumps(resp))
            else:
                print "AUTHFAIL"
                resp["data"] = AUTHFAIL
                server.send_message(client, json.dumps(resp))
        
        elif msg["action"] == GETFAILEDATTEMPTs:
            print 'msg is GETFAILEDATTEMPTs' 
            resp = {"action": GETFAILEDATTEMPTs, "data": []}
            username = msg["data"].get("username") if msg["data"].has_key("username") else None
            password = msg["data"].get("password") if msg["data"].has_key("password") else None
            if username and password and users.has_key(username) and password == users[username]:
                for failedAttempt in failedAttempts:
                    print "in FA"
                    print "FA=" + str(failedAttempt)
                    ip = {}
                    ip["IP"] = failedAttempt[0]
                    ip["attempts"] = []
                    ip["service"] = failedAttempt[1] 
                    for attempt in failedAttempts[failedAttempt]:
                        ip["attempts"].append(time.strftime("%b %d %H:%M:%S", time.localtime(attempt.time)))
                        
                    resp["data"].append(ip)

                server.send_message(client, json.dumps(resp))
            else:
                print "AUTHFAIL"
                resp["data"] = AUTHFAIL
                server.send_message(client, json.dumps(resp))

        elif msg["action"] == UNBANIPs:
            print 'msg is UNBANIPs'
            resp = {"action": UNBANIPs, "data": {}}
            username = msg["data"].get("username") if msg["data"].has_key("username") else None
            password = msg["data"].get("password") if msg["data"].has_key("password") else None
            if username and password and users.has_key(username) and password == users[username]:
	        unbanIP(msg["data"]["IP"], msg["data"]["service"])
	        resp["data"]["IP"] = msg["data"]["IP"]
	        resp["data"]["service"] = msg["data"]["service"]
                server.send_message(client, json.dumps(resp))
            else:
                print "AUTHFAIL"
                resp["data"] = AUTHFAIL
                server.send_message(client, json.dumps(resp))
	elif msg["action"] == CHANGECONFIG:
	    print 'msg is CHANGECONFIG'
            #changeconfig(bantimer,nofailedattempts,failinterval)
            data = msg["data"]
            for service in services.values():
                if service.name.lower() == data.get("service").lower():
                    changeConfig(data.get("bantimer"), data.get("threshold"), data.get("interval"), service)
            #server.send_message(client, json.dumps(resp))
	    


    
    global server        
    PORT=9001
    server = WebsocketServer(PORT, host='0.0.0.0')
    server.set_fn_new_client(new_client)
    server.set_fn_client_left(client_left)
    server.set_fn_message_received(message_received)
    server.run_forever()
Ejemplo n.º 32
0
 def startWebsocketServer(self):
     server = WebsocketServer(self.port, host = self.__host)
     server.set_fn_client_left(self.__client_left)
     server.set_fn_new_client(self.__new_client)
     server.set_fn_message_received(self.__msg_received)
     server.run_forever()