示例#1
0
文件: api.py 项目: Pepe74/panstamp
    def get_endpoint(endp):
        """
        Get Lagarto endpoint
        
        @param endp: endpoint identification string
        format 1: process.location.name
        format 2: process.id
        
        @return lagarto endpoint object
        """
        epd = endp.split('.')
        length = len(epd)
        epid = None
        eploc = None
        epname = None
        if length == 3:
            eploc = epd[1]
            epname = epd[2]
        else:
            epd = endp.partition('.')
            epid = epd[2]
        
        procname = epd[0]
        lagarto_endp = LagartoEndpoint(endp_id=epid, location=eploc, name=epname, procname=procname)

        try:
            status = NetworkAPI.lagarto_client.request_status(procname, [lagarto_endp.dumps(enable_value=False)])
            if status is not None:
                if len(status) > 0:
                    lagarto_endp = LagartoEndpoint(endpstr=status[0], procname=procname)
                    return lagarto_endp
            return None
        except:
            raise
示例#2
0
 def _http_json_set_value(uids, locations, names, values):
     """
     Set single or multiple endpoint values on data source
     
     @param uids: list of endpoint ids
     @param locations: list of endpoint locations
     @param names: list of endpoint names
     @param values: list of endpoint values
     
     @return list of endpoint values in JSON format
     """
     # Create list of JSON endpoint data
     req = []
     if values is not None:
         if len(values) > 0:
             for i, val in enumerate(values):
                 if len(locations) == len(names) > i:
                     endp = LagartoEndpoint(location = locations[i], name=names[i], value=val)
                 elif len(uids) > i:
                     endp = LagartoEndpoint(endp_id=uids[i], value=val)
                 req.append(endp.dumps())
     else:
         return None
                 
     status = LagartoHttpServer.data_server.set_status(req)
     
     if status is not None:
         if len(status) > 0:
             # Create complete Lagarto status message
             http_server = LagartoHttpServer.address + ":" + str(LagartoHttpServer.port)
             response = LagartoMessage(proc_name=LagartoHttpServer.proc_name, http_server=http_server, status=status)
             return json.dumps(response.dumps())
             
     return None
示例#3
0
    def _http_simple_set_value(uid, location, name, value):
        """
        Set endpoint value on data source
        
        @param uid: endpoint unique id
        @param location: endpoint location
        @param name: endpoint name
        @param value: new endpoint value
        
        @return endpoint value in raw string format
        """
        if LagartoHttpServer.disable_set_value:
            return None

        endp = LagartoEndpoint(endp_id=uid, location=location, name=name, value=value)
        status = LagartoHttpServer.data_server.set_status([endp.dumps()])
        
        if status is not None:
            if len(status) == 1:
                if "value" in status[0]:   
                    res = str(status[0]["value"])
                    if "unit" in status[0]:
                        res += " " + status[0]["unit"]
                    return res
                
        return None
示例#4
0
    def _http_simple_set_value(self, uid, location, name, value):
        """
        Set endpoint value on data source
        
        @param uid: endpoint unique id
        @param location: endpoint location
        @param name: endpoint name
        @param value: new endpoint value
        
        @return endpoint value in raw string format
        """
        endp = LagartoEndpoint(endp_id=uid,
                               location=location,
                               name=name,
                               value=value)
        status = LagartoHttpServer.data_server.set_status([endp.dumps()])

        if status is not None:
            if len(status) == 1:
                if "value" in status[0]:
                    res = str(status[0]["value"])
                    if "unit" in status[0]:
                        res += " " + status[0]["unit"]
                    return res

        return None
示例#5
0
    def _http_json_set_value(self, uid, location, name, value):
        """
        Set single or multiple endpoint values from data source
        
        @param uids: endpoint id
        @param locations: endpoint location
        @param names: endpoint name
        @param values: endpoint value
        
        @return list of endpoint values in JSON format
        """
        # Create list of JSON endpoint data
        req = []
        if value is not None:
            if uid is not None:
                endp = LagartoEndpoint(endp_id=uid, value=value)
            elif location is not None and name is not None:
                endp = LagartoEndpoint(location = location, name=name, value=value)

            req.append(endp.dumps())
        else:
            return None
                    
        status = self.data_server.set_status(req)
        
        if status is not None:
            if len(status) > 0:
                # Create complete Lagarto status message
                http_server = self.address + ":" + str(self.port)
                response = LagartoMessage(proc_name=self.proc_name, http_server=http_server, status=status)
                return json.dumps(response.dumps())
                
        return None
示例#6
0
    def notify_status(self, event):
        """
        Notify status to the master application (callback)
        To be implemented by subclass
        
        @param event: message received from publisher in JSON format
        """
        reload(webscripts)
        attributes = dir(webscripts.WebScripts)

        for endp in event["status"]:
            # Create lagarto endpoint
            lagarto_endp = LagartoEndpoint(endpstr=endp,
                                           procname=event["procname"])
            # Run event script
            evnscript = EventScript("network", lagarto_endp)
            # Update network event in API
            NetworkAPI.event = [
                event["procname"] + "." + endp["location"] + "." +
                endp["name"], endp["value"]
            ]

            # Wait if time event currently running
            while TimeAPI.event:
                time.sleep(0.1)

            # Run web script
            for attr in attributes:
                if attr.startswith("evn_"):
                    event_func = getattr(webscripts.WebScripts, attr)
                    event_func()
示例#7
0
 def _http_json_get_value(uids=None, locations=None, names=None):
     """
     Get single or multiple endpoint values from data source
     
     @param uids: list of endpoint ids
     @param locations: list of endpoint locations
     @param names: list of endpoint names
     
     @return list of endpoint values in JSON format
     """
     # Create list of JSON endpoint data
     req = []
     if uids is not None and locations is not None and names is not None:
         if len(uids) > 0:
             for uid in uids:
                 endp = LagartoEndpoint(endp_id=uid)
                 req.append(endp.dumps())
         elif len(locations) == len(names) > 0:
             for i, loc in enumerate(locations):
                 endp = LagartoEndpoint(location=loc, name=names[i])
                 req.append(endp.dumps())
     else:  # Return whole network status
         req = None
                 
     status = LagartoHttpServer.data_server.get_status(req)
     
     if status is not None:
         if len(status) > 0:
             # Create complete Lagarto status message
             http_server = LagartoHttpServer.address + ":" + str(LagartoHttpServer.port)
             response = LagartoMessage(proc_name=LagartoHttpServer.proc_name, http_server=http_server, status=status)
             return json.dumps(response.dumps())
             
     return None
示例#8
0
    def _http_json_get_value(self, uid=None, location=None, name=None):
        """
        Get single or multiple endpoint values from data source
        
        @param uid: endpoint uid
        @param location: endpoint locations
        @param name: endpoint name
        
        @return list of endpoint values in JSON format
        """
        # Create list of JSON endpoint data
        req = []
        if uid is not None:
            endp = LagartoEndpoint(endp_id=uid)
            req.append(endp.dumps())
        elif location is not None and name is not None:
            endp = LagartoEndpoint(location=location, name=name)
            req.append(endp.dumps())
        else:  # Return whole network status
            req = None

        status = self.data_server.get_status(req)

        if status is not None:
            if len(status) > 0:
                # Create complete Lagarto status message
                http_server = self.address + ":" + str(self.port)
                response = LagartoMessage(proc_name=self.proc_name,
                                          http_server=http_server,
                                          status=status)
                return json.dumps(response.dumps())

        return None
示例#9
0
    def get_endpoint(endp):
        """
        Get Lagarto endpoint
        
        @param endp: endpoint identification string
        format 1: process.location.name
        format 2: process.id
        
        @return lagarto endpoint object
        """
        epd = endp.split('.')
        length = len(epd)
        epid = None
        eploc = None
        epname = None
        if length == 3:
            eploc = epd[1]
            epname = epd[2]
        else:
            epd = endp.partition('.')
            epid = epd[2]

        procname = epd[0]
        lagarto_endp = LagartoEndpoint(endp_id=epid,
                                       location=eploc,
                                       name=epname,
                                       procname=procname)

        try:
            status = NetworkAPI.lagarto_client.request_status(
                procname, [lagarto_endp.dumps(enable_value=False)])
            if status is not None:
                if len(status) > 0:
                    lagarto_endp = LagartoEndpoint(endpstr=status[0],
                                                   procname=procname)
                    return lagarto_endp
            return None
        except:
            raise
示例#10
0
    def _http_simple_get_value(self, uid, location, name):
        """
        Get endpoint value from data source
        
        @param uid: endpoint unique id
        @param location: endpoint location
        @param name: endpoint name
        
        @return endpoint value in raw string format
        """
        endp = LagartoEndpoint(endp_id=uid, location=location, name=name)

        status = LagartoHttpServer.data_server.get_status([endp.dumps()])

        if status is not None:
            if len(status) == 1:
                if "value" in status[0]:
                    res = str(status[0]["value"])
                    if "unit" in status[0]:
                        res += " " + status[0]["unit"]
                    return res
                
        return None
示例#11
0
    def __init__(self, server):
        """
        Class constructor
        
        @param server: Speech recognition server
        """
        ## Speech recognition server
        self.server = server

        ## File name
        self.filepath = os.path.join(working_dir, "config", "speechnet.json")

        ## Speech recognition endpoint
        self.input = LagartoEndpoint(endp_id="sprinp",
                                     location="speech",
                                     name="input",
                                     vtype="str",
                                     direction="inp",
                                     value="")
        ## Text to speech endpoint
        self.output = LagartoEndpoint(endp_id="ttsout",
                                      location="speech",
                                      name="output",
                                      vtype="str",
                                      direction="out",
                                      value="")

        # List of endpoints
        self.endpoints = [self.input, self.output]

        # Read config file
        try:
            self.read()
        except:
            self.save()
            pass
示例#12
0
    def http_command_received(self, command, params):
        """
        Process command sent from HTTP server. Method to be overrided by data consumer.
        Method required by LagartoClient
        
        @param command: command string
        @param params: dictionary of parameters
        
        @return True if command successfukky processed by server.
        Return False otherwise
        """
        try:
            if command == "get_server_list":
                return self.get_servers()

            elif command == "get_endpoint_list":
                return self.get_endpoints(params["server"])

            elif command == "set_endpoint_value":
                location = None
                name = None
                endp_id = None

                if "id" in params:
                    endp_id = params["id"]
                if "location" in params:
                    location = params["location"]
                    if "name" in params:
                        name = params["name"]

                endpoint = LagartoEndpoint(endp_id=endp_id,
                                           location=location,
                                           name=name,
                                           value=params["value"],
                                           procname=params["procname"])
                return self.set_endpoint(endpoint)

            elif command == "set_from_opensense":
                if "feed_id" not in params:
                    return None

                endp = None
                for key, value in OpenSense.feed_ids.iteritems():
                    if value == params["feed_id"]:
                        endp = value

                if endp is None:
                    return None
                endp_data = endp.split(".")
                if len(endp_data) != 3:
                    return None

                endpoint = LagartoEndpoint(location=endp_data[1],
                                           name=endp_data[2],
                                           value=params["value"],
                                           procname=endp_data[0])
                return self.set_endpoint(endpoint)

            elif command == "get_event_list":
                return WebEvent.get_events()

            elif command == "get_event":
                if "id" in params:
                    try:
                        event = WebEvent(params["id"])
                        return event.dumps()
                    except:
                        pass

            elif command == "delete_event":
                if "id" in params:
                    event = WebEvent(params["id"])
                    event.delete()
                    return "event_panel.html"

            elif command == "config_event_name":
                if "id" in params:
                    event = WebEvent(params["id"])
                    event.name = params["name"]
                    event.save()
                    return True

            elif command == "set_event_line":
                if "id" in params:
                    event = WebEvent(params["id"])
                    linenb = params["linenb"]
                    event.set_line(params["line"], linenb, params["type"])
                    event.save()
                    return "edit_event.html"

            elif command == "delete_event_line":
                if "id" in params:
                    event = WebEvent(params["id"])
                    linenb = params["linenb"]
                    event.delete_line(linenb)
                    event.save()
                    return "edit_event.html"

            elif command == "edit_db_table":
                self.database.edit_table(params["name"],
                                         params["endpoints"].split(','),
                                         params["interval"])
                return "db_panel.html"

            elif command == "delete_db_table":
                self.database.delete_table(params["name"])
                return "db_panel.html"

            elif command == "edit_graph":
                columns = None
                if "columns" in params:
                    columns = params["columns"].split(',')
                title = None
                if "title" in params:
                    title = params["title"]
                graphtype = None
                if "type" in params:
                    graphtype = params["type"]
                samples = None
                if "samples" in params:
                    samples = params["samples"]
                start = None
                if "starttime" in params:
                    start = params["starttime"]
                end = None
                if "endtime" in params:
                    end = params["endtime"]
                miny = None
                if "miny" in params:
                    miny = params["miny"]
                maxy = None
                if "maxy" in params:
                    maxy = params["maxy"]
                show_grid = False
                if "show_grid" in params:
                    show_grid = (params["show_grid"].lower()
                                 in ["true", "on", "yes", "enable"])
                self.database.edit_graph(graph_name=params["name"],
                                         table_name=params["table"],
                                         columns=columns,
                                         title=title,
                                         graphtype=graphtype,
                                         samples=samples,
                                         start=start,
                                         end=end,
                                         miny=miny,
                                         maxy=maxy,
                                         show_grid=show_grid)
                return "graph_panel.html"

            elif command == "delete_graph":
                self.database.delete_graph(params["name"])
                return "graph_panel.html"

            elif command == "query_db_table":
                columns = None
                start = None
                end = None
                samples = None
                if "table" in params:
                    if "columns" in params:
                        columns = params["columns"].split(',')
                    if "start" in params:
                        start = params["start"].replace('+', ' ')
                    if "end" in params:
                        end = params["end"].replace('+', ' ')
                    if "samples" in params:
                        samples = params["samples"]
                return self.database.query_table(params["table"], columns,
                                                 start, end, samples)

        except LagartoException as ex:
            ex.log()
        except Exception as ex:
            print ex
            pass

        return False