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() def append(self, tuple): self.wsl.append(tuple) class WebsocketPass(dric.FunPass): def __init__(self, target): self.target = target return super(WebsocketPass, self).__init__(pass_id=None, attr_name='ws') def loadfun(self, plugin, name, function, *args, **kwargs): tuple = (function.event, function.route, function.supported_protocols) self.target.append(tuple) # register plugin plugin = WebSocketListPlugin() dric.register(__name__, plugin) # register pass dric.get_pass_manager().add_pass(WebsocketPass(plugin))
import dric from os.path import isfile from mimetypes import guess_type from werkzeug.wsgi import wrap_file class StaticContentPlugin(dric.Plugin): @dric.route('static-content', '/content/<path:path>') def serve(self, request, path): if isfile(path): f = open(path, 'rb') mimetype = guess_type(request.url) return dric.GzipResponse(wrap_file(request.environ, f), mimetype=mimetype[0], content_type=mimetype[0], direct_passthrough=True) else: raise dric.NotFound() dric.register(__name__, StaticContentPlugin())
ws.send( unicode(str(MissingParameterWsError('data', msg)))) elif 'esid' not in parsed: ws.send( unicode(str(MissingParameterWsError('esid', msg)))) else: event = Event(CLIENT, parsed, parsed['esid']) environ = Environ(ws=ws) try: self.state = self.state.next_state(event, environ) self.resetTimeout() except NoStateTransitionError as e: ws.send( unicode( str(NoStateTransitionErrorWsError(msg, e)))) except StateInitializationError as e: ws.send( unicode( str(StateInitializationErrorWsError( msg, e)))) finally: self.wsl.pop(myrandomkey) def debug(self, ws, parsed): if parsed['command'] == '_GET_STATE': ws.send(unicode(json.dumps({'state': self.state.name}))) dric.register(__name__, WaypointPlugin())
class MavlinkHeartbeatSenderPlugin(dric.Plugin): def __init__(self, freq=1): self.interval = 1 / freq def start(self): driconxplugin = dric.pg.get_plugin("driconx.driconx") self.connections = driconxplugin.connections spawn(self.send_heartbeats) def send_heartbeats(self): while (1): for connection_name in self.connections: connection = self.connections[connection_name] for esid in connection.properties['systems']: command_parameters = { 'type': int(6), # replace hard coded 'autopilot': int(8), 'base_mode': int(0), 'custom_mode': int(0), 'system_status': int(4), 'mavlink_version': int(3) } dric.bus.publish('SEND_MAVLINK', esid, 'HEARTBEAT', command_parameters) sleep(self.interval) dric.register(__name__, MavlinkHeartbeatSenderPlugin())
try: handler.push(e) except: self.handlers['*']['*'].remove(handler) if channel in self.handlers and '*' in self.handlers[channel]: for handler in self.handlers[channel]['*']: try: handler.push(e) except: self.handlers[channel]['*'].remove(handler) if channel in self.handlers and system in self.handlers[channel]: for handler in self.handlers[channel][system]: try: handler.push(e) except: self.handlers[channel][system].remove(handler) def parse(self, esid): match = self.ESID.match(esid) if not match: raise dric.exceptions.BadRequest() channel = match.group(1) system = match.group(2) return channel, system dric.register(__name__, MAVLinkErrorPlugin())
channel.raw.write(data) channel.index.write(struct.pack('!dQh', self.time(), channel.raw.tell() - len(data), len(data))) except Exception as e: print(e) def open_channel(self, channel_name, mavlink): if channel_name in self.__channels: return dbpath = join(self.channels_rootdir, channel_name) file_raw = open(dbpath + '.raw', 'a+b', 0) file_index = open(dbpath + '.index', 'a+b', 0) self.__channels[channel_name] = Channel(file_raw, file_index, type(mavlink)) def time(self): if sys.platform == "win32": mytime = time.clock() else: mytime = time.time() return mytime dric.register(__name__, MavlinkRawDBPlugin()) class Channel(object): def __init__(self, file_raw, file_index, mavlink): self.raw = file_raw self.index = file_index self.mavlink = mavlink
raise dric.exceptions.BadRequest('Arguments "esid" is missing.') try: target_system = int(esid.split('-')[1]) except: raise dric.exceptions.BadRequest( 'Could not extract target system from esid "{}".'.format(esid)) command_parameters = { 'target_system': int(target_system ), # uint8_t System which should execute the command 'target_component': 0, # uint8_t Component which should execute the command, 0 for all components 'command': 400, 'confirmation': 0, 'param1': float(state), 'param2': float(0), 'param3': float(0), 'param4': float(0), 'param5': float(0), 'param6': float(0), 'param7': float(0), } dric.bus.publish('SEND_MAVLINK', esid, 'COMMAND_LONG', command_parameters) dric.register(__name__, QuickArmPlugin())
def inject_content_scripts(scripts): name = __name__ + '-content-script-' + join(sample(ascii_letters, 8), '') dric.register(name, ContentScriptInjector(scripts))
def get_connection_from_request(self, request): connection_properties = loads(request.get_data(as_text=True)) connection_name = connection_properties['name'] return (self.get_connection_from_name(connection_name), connection_name) def get_connection_from_name(self, connection_name): if connection_name not in self.connections: raise dric.exceptions.NotFound( "Connection '{}' not found".format(connection_name)) return self.connections[connection_name] driconxplugin = DriconxPlugin() dric.register(__name__, driconxplugin) class BindingFunPass(dric.FunPass): def __init__(self, pass_id, target): self.target = target return super(BindingFunPass, self).__init__(pass_id) def loadfun(self, plugin, name, function, binding_name): self.target.bindings[binding_name] = function dric.get_pass_manager().add_pass( BindingFunPass('mavlink-binding', driconxplugin))
if key in conversions: if key in filtering_message.message: converted = dric.bus.publish('convert', conversions[key][0], conversions[key][1], filtering_message.message[key]) if converted is not None and len(converted) > 0: filtering_message.message[key] = converted[0] return filtering_message @dric.route('mavlink.units', '/mavlink/units') 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) dric.register(__name__, ConversionPlugin())
sleep_time = request.args.get('p', 0, type=int) / 1000.0 if 's' not in request.args: raise dric.NotFound source_name = request.args.get('s', type=str) _logger.debug('Incoming connection for datasource %s', source_name) sid = None if 'sid' in request.args: sid = request.args.get('sid', type=str) if sid not in self.__start_times: self.clean() self.__start_times[sid] = time() start_time = self.__start_times[sid] else: start_time = time() if self.has_source(source_name) is False: raise dric.NotFound _logger.info('Serving datasource %s', source_name) _Helper(self.source, ws, request, source_name, sleep_time, start_time, sid).start() except dric.NotFound: ws.send(pack('!i', 404)) dric.register(__name__, DatasourceWebsocketPlugin()) inject_content_script(path='/content/core/dsws/js/datasources.js', runat='start')
import dric from .mavricbinding import MAVLink class MavricBinding(dric.Plugin): @dric.funpass('mavlink-binding', 'mavric') def binding(self): return MAVLink dric.register(__name__, MavricBinding())
class DefinitionPlugin(dric.Plugin): @dric.route('driconx-definitions.xml', '/driconx/bindings/<definitonfile>') def definitions(self, definitonfile, request): pass class CommonBinding(dric.Plugin): @dric.funpass('mavlink-binding', 'common') def binding(self): return CommonMAVLink class StandardBinding(dric.Plugin): @dric.funpass('mavlink-binding', 'standard') def binding(self): return CommonMAVLink class MinimalBinding(dric.Plugin): @dric.funpass('mavlink-binding', 'minimal') def binding(self): return MinimalMAVLink def name(binding): return "driconx.default_bindings/{}".format(binding) dric.register(name('common'), CommonBinding()) dric.register(name('standard'), StandardBinding()) dric.register(name('minimal'), MinimalBinding())
Status codes: 1: Request message sent 2: PARAM_VALUE message received 3: last PARAM_VALUE message received, server will close the connection, and client should close the connection 4: timeout """ # Wait for end of previous connection. # We are asynchronous, so we do not need to worry about thread-safety here if self.piq.wait(ws, esid) is False: return # start the action try: _, target_system = esid.split('-') target_system_id = int(target_system) except: raise dric.exceptions.BadRequest( 'Cannot extract target system from esid "{}".'.format(esid)) fields = {'target_system': target_system_id, 'target_component': 0} self.piq.one_shot = False dric.bus.publish('SEND_MAVLINK', esid, 'PARAM_REQUEST_LIST', fields) ws.send(unicode('1:{}')) # wait for action to be terminated self.piq.wait_for_termination() dric.register(__name__, ParamProtocolPlugin())
@dric.on('SEND_MAVLINK') def listen(self, esid, command, parameters): self.sent_commands.append((esid, command, parameters)) @dric.route('mavlink_send_command_debug', '/mavlink/debug/sent_commands') 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() dric.register(__name__, MavCommandPlugin()) dric.register('debug_' + __name__, MavCommandPluginDebugger())
def inject_content_script(path, runat='async'): name = __name__ + '-content-script-' + path dric.register(name, ContentScriptInjector({'path':path, 'runat':runat}))
def __create_handler(self, esid): if esid not in self.handlers: self.handlers[esid] = Handler() name = "map-position/global${}".format(esid) dric.add_datasource(name, self.handlers[esid]) class Handler(object): def __init__(self, sleep=0.1): self.noplot = True self.message = None self.hudmessage = None self.localmessage = None self.sleep = sleep def __call__(self): while True: if self.message is not None and self.hudmessage is not None and self.localmessage is not None: yield pack('!7d', self.message.lat, self.message.lon, self.message.alt, self.hudmessage.heading, self.localmessage.y, self.localmessage.x, self.localmessage.z ) sleep(self.sleep) dric.register(__name__, PositionPlugin())
def __call__(self, context): queue = [] self.queues[context['cid']] = queue while True: while len(queue) > 0: try: popped = queue.pop(0) yield pack('!dd', popped[0] - context['start'], popped[1]) except (ValueError, TypeError) as e: _logger.exception('Expected double. %s %s given.', type(popped[1]), popped[1], exc_info=e) sleep(self.sleep) class MavlinkFullMessageDatasource(object): def __init__(self, sleep=1, noplot=True): self.sleep = sleep self.noplot = noplot self.data = {} def push(self, data): self.data = data def __call__(self): while True: json_text = (dumps(self.data, separators=(',',':'))) yield pack('!d', time()) + json_text sleep(self.sleep) dric.register('MAVLINK/listener', MavlinkListener())
content_type=mimetype[0], direct_passthrough=True) except (IOError, OSError): raise dric.NotFound() @dric.route('map-info', '/map/<string:name>') def map_info(self, name, request): path = abspath(join(self.source_dir, name, 'info.json')) try: f = open(path, 'rb') mimetype = 'application/json' return dric.Response(wrap_file(request.environ, f), mimetype=mimetype[0], content_type=mimetype[0], direct_passthrough=True) except (IOError, OSError): raise dric.NotFound() @dric.route('map-maps', '/map/maps') 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)) dric.register(__name__, MapPlugin()) #dric.support.inject_content_script('/content/plugins/map/leaflet/leaflet.css') #dric.support.inject_content_script('/content/plugins/map/leaflet/leaflet.js')