Beispiel #1
0
 def connections_list(self, request):
     if dric.support.accept.xml_over_json(request):
         root = etree.Element('connections')
         for connection_name in self.connections:
             connection = self.connections[connection_name]
             e = etree.SubElement(root, 'connection')
             for key in connection:
                 # maybe implement a visitor pattern or similar for special cases. Or make all values implement a 'toXml(parent)' function...
                 if key == 'systems':
                     systems = etree.SubElement(e, 'systems')
                     for system_name in connection[key]:
                         system = etree.SubElement(systems, 'system')
                         system.text = unicode(system_name)
                 elif key == 'reply_address':
                     reply_address_element = etree.SubElement(e, 'reply')
                     host, port = connection[key]
                     etree.SubElement(reply_address_element,
                                      'port').text = str(port)
                     etree.SubElement(reply_address_element,
                                      'host').text = str(host)
                 else:
                     parameter = etree.SubElement(e, key)
                     parameter.text = unicode(connection[key])
             e.set('name', connection_name)
         return dric.Response(etree.tostring(root,
                                             xml_declaration=True,
                                             encoding='UTF-8'),
                              content_type="application/xml")
     elif dric.support.accept.json_over_xml(request):
         return dric.JSONResponse(
             [self.connections[cname] for cname in self.connections])
     else:
         raise dric.exceptions.NotAcceptable()
Beispiel #2
0
    def datasources_list(self, request):
        all = request.args.get('all', False, bool)
        out = []
        for source_name in self.sources():
            if all:
                out.append(source_name)
            elif not (hasattr(self.source(source_name), 'noplot')
                      and self.source(source_name).noplot is True):
                out.append(source_name)

        if dric.support.accept.xml_over_json(request):
            root = etree.Element('datasources')
            for source_name in out:
                source = self.sources()[source_name]
                s = etree.SubElement(root, 'datasource')
                if hasattr(source, 'noplot') and source.noplot is True:
                    s.set('noplot', 'noplot')
                if hasattr(source,
                           'isTimeSerie') and source.isTimeSerie is True:
                    s.set('isTimeSerie', 'isTimeSerie')
                s.text = source_name
            return dric.XMLResponse(root)
        elif dric.support.accept.json_over_xml(request):
            return dric.JSONResponse(out)
        else:
            raise dric.exceptions.NotAcceptable()
Beispiel #3
0
 def get_esid_list(self, request):
     if dric.support.accept.xml_over_json(request):
         root = ET.Element('systems')
         root.set('version', '1')
         for esid in self.esids:
             esid_el = ET.SubElement(root, 'systemid')
             esid_el.text = esid
         return dric.XMLResponse(root)
     elif dric.support.accept.json_over_xml(request):
         return dric.JSONResponse(self.esids)
     else:
         raise dric.exceptions.NotAcceptable('xml or json')
Beispiel #4
0
 def route_bindings_list(self, request):
     accepted = request.accept_mimetypes.best_match(
         ['application/xml', 'text/xml', 'application/json'])
     if accepted == 'application/xml' or accepted == 'text/xml':
         elemBindings = etree.Element("bindings")
         for binding in self.bindings:
             elemBinding = etree.SubElement(elemBindings, 'binding')
             elemBinding.text = binding
         return dric.Response(etree.tostring(elemBindings,
                                             xml_declaration=True,
                                             encoding='UTF-8'),
                              content_type=accepted)
     elif accepted == 'application/json':
         return dric.JSONResponse([binding for binding in self.bindings])
     else:
         return dric.Response('Not acceptable', status=406)
Beispiel #5
0
    def connection_enums(self, connection_name, enum, request):
        """ show all command in enum for the connection """
        connection_name = connection_name.split("-")[0]  # also accept esid
        if connection_name not in self.connections:
            raise dric.exceptions.NotFound(
                "Connection '{}' not found".format(connection_name))
        connection = self.connections[connection_name]

        binding_name = connection.properties['binding']
        # if binding_name not in self.bindings:
        #     raise dric.exceptions.NotFound("Binding '{}' not found".format(binding_name))
        # binding = self.bindings[binding_name]()(None)
        # binding = connection.mavlink

        module = inspect.getmodule(connection.mavlink)
        if enum not in module.enums: raise dric.exceptions.NotFound
        output = []
        for cmd in module.enums[enum]:
            entry = module.enums[enum][cmd]
            if entry.name == '{}_ENUM_END'.format(enum): continue
            output.append({
                'name': entry.name,
                'id': cmd,
                'description': entry.description,
                'param': entry.param
            })

        if dric.support.accept.xml_over_json(request):
            root = etree.Element('commands')
            root.set('connection', connection_name)
            root.set('binding', binding_name)
            for entry in output:
                c = etree.SubElement(root, 'command')
                c.set('name', entry['name'])
                c.set('id', str(entry['id']))
                d = etree.SubElement(c, 'description')
                d.text = entry['description']
                for key in entry['param']:
                    p = etree.SubElement(c, 'parameter')
                    p.set('index', str(key))
                    p.text = entry['param'][key]
            return dric.XMLResponse(root)
        elif dric.support.accept.json_over_xml(request):
            return dric.JSONResponse(output)
        else:
            raise dric.exceptions.NotAcceptable()
Beispiel #6
0
 def debug_routes(self, request):
     if dric.support.accept.xml_over_json(request):
         root = etree.Element('routes')
         for endpoint, route in self.routes:
             e = etree.SubElement(root, 'route')
             e.set('endpoint', endpoint)
             e.text = route
         return dric.Response(etree.tostring(root,
                                             xml_declaration=True,
                                             encoding='UTF-8'),
                              content_type="application/xml")
     elif dric.support.accept.json_over_xml(request):
         return dric.JSONResponse([{
             'endpoint': endpoint,
             'route': route
         } for endpoint, route in self.routes])
     else:
         raise dric.exceptions.NotAcceptable()
Beispiel #7
0
 def get_units(self, request):
     accept = request.accept_mimetypes.best_match(['application/xml', 'text/xml', 'application/json'])
     if accept == 'application/xml' or accept == 'text/xml':
         root = ET.Element('types')
         for name in self.enabled_conversions:
             messagetype = ET.SubElement(root, 'type')
             messagetype.set('name', name)
             conversions = self.enabled_conversions[name]
             for key in conversions:
                 elemkey = ET.SubElement(messagetype, 'key', {'name': key})
                 elemkey.text = str(conversions[key][1])
         return dric.Response(ET.tostring(root, encoding='UTF-8'), content_type=accept)
     else:
         root = {}
         for name in self.enabled_conversions:
             root[name] = {}
             conversions = self.enabled_conversions[name]
             for key in conversions:
                 root[name][key] = str(conversions[key][1])
         return dric.JSONResponse(root)
Beispiel #8
0
 def send_command_debug(self, request):
     if dric.support.accept.xml_over_json(request):
         root = etree.Element('history')
         for esid, command, parameters in self.sent_commands:
             c = etree.SubElement(root, 'command')
             c.set('command', command)
             c.set('target', esid)
             if parameters is not None:
                 for name in parameters:
                     p = etree.SubElement(c, 'parameter')
                     p.set('name', str(name))
                     p.text = str(parameters[name])
         return dric.XMLResponse(root)
     elif dric.support.accept.json_over_xml(request):
         return dric.JSONResponse([{
             'esid': esid,
             'command': command,
             'parameters': parameters
         } for esid, command, parameters in self.sent_commands])
     else:
         raise dric.exceptions.NotAcceptable()
Beispiel #9
0
 def debug_routes(self, request):
     if dric.support.accept.xml_over_json(request):
         root = etree.Element('websockets')
         for endpoint, route, protocols in self.wsl:
             e = etree.SubElement(root, 'websocket')
             e.set('endpoint', endpoint)
             e.set('route', route)
             for protocol in protocols:
                 p = etree.SubElement(e, 'protocol')
                 p.text = protocol
         return dric.Response(etree.tostring(root,
                                             xml_declaration=True,
                                             encoding='UTF-8'),
                              content_type="application/xml")
     elif dric.support.accept.json_over_xml(request):
         return dric.JSONResponse([{
             'endpoint': endpoint,
             'route': route,
             'protocols': protocols
         } for endpoint, route, protocols in self.wsl])
     else:
         raise dric.exceptions.NotAcceptable()
Beispiel #10
0
    def get_message(self, esid, name, request):
        try:
            range_from = request.args.get('from', 0, type=float)
            range_to = request.args.get('to', float('inf'), type=float)
            if range_from > range_to:
                raise dric.exceptions.BadRequest('from cannot be smaller than to')
            try:
                channel_name, system_id = esid.split('-')
            except ValueError:
                raise dric.exceptions.BadRequest('Malformed esid')
            if channel_name not in self.__channels:
                raise dric.exceptions.NotFound('Channel {} not found'.format(channel_name))
            channel = self.__channels[channel_name]
            fi = channel.index
            fr = channel.raw

            # go to end of file
            fi.seek(-PACKET_SIZE, os.SEEK_END)
            packet_count = fi.tell() / PACKET_SIZE
            print('{} packets'.format(packet_count))

            # read timestamp
            end_timestamp, = struct.unpack('!d', fi.read(8))
            if end_timestamp < range_from:
                raise dric.exceptions.NotFound('From is in the future')

            # search for from_range
            m = self.find_start_packet(fi, packet_count, range_from)
            fi.seek(m * PACKET_SIZE)
            timestamp = range_from
            mavlink = channel.mavlink(None)
            output = []
            while timestamp < range_to:
                try:
                    try:
                        timestamp, offset, length = struct.unpack('!dQh', fi.read(PACKET_SIZE))
                    except:
                        traceback.print_exc()
                        break
                    # print('{}: @{} len{}'.format(timestamp, offset, length))
                    fr.seek(offset)
                    data = fr.read(length)

                    # print(binascii.hexlify(data))

                    messages = mavlink.parse_buffer(data)
                    print(messages)
                    if messages is not None:
                        for message in messages:
                            message_esid = "{}-{}".format(channel_name, message.get_srcSystem())
                            if esid != message_esid:
                                continue
                            #if esid not in self.connection['systems']:
                            #    self.connection['systems'].append(esid)
                            #    self.update_driconxwsockets()
                            output.append({ 
                                'timestamp': timestamp, 
                                'esid': esid,
                                'type': message.get_type(),
                                'message': message.to_dict() 
                            })
                            # dric.bus.publish('MAVLINK', message.get_type(), esid, message.to_dict())

                except Exception as e:
                    traceback.print_exc()
            
            return dric.JSONResponse(output)
        except Exception as e:
            print(e)
            raise e
        raise dric.exceptions.InternalServerError()
Beispiel #11
0
 def list_maps(self, request):
     maps = list()
     for map_dir in listdir(self.source_dir):
         if (isdir(map_dir)):
             maps.append(map_dir)
     return dric.JSONResponse(listdir(self.source_dir))