Signal K
    Preparing search index...

    Interface ServerAPI

    SignalK server provides an interface to allow Plugins to:

    • Discover Features.
    • Access / update the full data model
    • send / receive deltas (updates)
    • Interact with APIs
    • Expose HTTP endpoints

    These functions are available via the app object passed to the plugin when it is invoked.

    Warning

    Typing is incomplete. If you find a missing or inaccurate type, please report it.

    interface ServerAPI {
        resourcesApi: ResourcesApi;
        activateRoute(dest: null | RouteDestination): Promise<void>;
        autopilotUpdate(deviceId: string, apInfo: { [path: string]: Value }): void;
        clearDestination(): Promise<void>;
        debug(msg: string): void;
        emitPropertyValue(name: string, value: any): void;
        error(msg: string): void;
        getCourse(): Promise<CourseInfo>;
        getDataDirPath(): string;
        getFeatures(onlyEnabled?: boolean): FeatureInfo;
        getMetadata(path: string): undefined | Metadata;
        getPath(path: string): any;
        getSelfPath(path: string): any;
        getSerialPorts(): Promise<Ports>;
        handleMessage(id: string, msg: any, skVersion?: SKVersion): void;
        onPropertyValues(name: string, cb: PropertyValuesCallback): () => void;
        putPath(
            aPath: string,
            value: string | number | boolean | object,
            updateCb: (err?: Error) => void,
            source: string,
        ): Promise<any>;
        putSelfPath(aPath: string, value: any, updateCb: () => void): Promise<any>;
        queryRequest(requestId: string): Promise<any>;
        readPluginOptions(): object;
        registerActionHandler(
            context: string,
            path: string,
            callback: () => void,
            source: string,
        ): void;
        registerAutopilotProvider(
            provider: AutopilotProvider,
            devices: string[],
        ): void;
        registerDeltaInputHandler(handler: DeltaInputHandler): void;
        registerHistoryProvider(
            provider: {
                getHistory: (
                    date: Date,
                    path: string,
                    cb: (deltas: object[]) => void,
                ) => void;
                hasAnydata: (options: object, cb: (hasResults: boolean) => void) => void;
                streamHistory: (
                    spark: any,
                    options: object,
                    onDelta: (delta: object) => void,
                ) => void;
            },
        ): void;
        registerPutHandler(
            context: string,
            path: string,
            callback: () => void,
            source: string,
        ): void;
        registerResourceProvider(provider: ResourceProvider): void;
        reportOutputMessages(count?: number): void;
        savePluginOptions(
            configuration: object,
            cb: (err: null | ErrnoException) => void,
        ): void;
        setDestination(
            dest:
                | null
                | (PointDestination & { arrivalCircle?: number | undefined; }),
        ): Promise<void>;
        setPluginError(msg: string): void;
        setPluginStatus(msg: string): void;
    }

    Hierarchy

    Index

    Autopilot API

    • Parameters

      • deviceId: string

        the autopilot device identifier

      • apInfo: { [path: string]: Value }

        object containing values keyed by AutopilotInfo

      Returns void

    Configuration

    • Returns the full path of the directory where the plugin can persist its internal data, e.g. data files, etc.

      Returns string

      let myDataFile = require('path').join( app.getDataDirPath(), 'somedatafile.ext')
      
    • Read the stored plugin configuration options.

      Returns object

      let options = app.readPluginOptions();
      
    • Save changes to the plugin's configuration options.

      Parameters

      • configuration: object
      • cb: (err: null | ErrnoException) => void

      Returns void

      let options = {
      myConfigValue = 'Something the plugin calculated'
      };

      app.savePluginOptions(options, () => {app.debug('Plugin options saved')});

    Course API

    • Set course to a specified position / waypoint.

      Parameters

      • dest: null | (PointDestination & { arrivalCircle?: number | undefined; })

        Object containing destination position information.

      Returns Promise<void>

    Data Model

    • Returns the entry for the provided path starting from the root of the full data model.

      Parameters

      • path: string

      Returns any

      let baseStations = app.getPath('shore.basestations');

      // baseStations:
      {
      'urn:mrn:imo:mmsi:2766140': {
      url: 'basestations',
      navigation: { position: {latitude: 45.2, longitude: 76.4} },
      mmsi: '2766140'
      },
      'urn:mrn:imo:mmsi:2766160': {
      url: 'basestations',
      navigation: { position: {latitude: 46.9, longitude: 72.22} },
      mmsi: '2766160'
      }
      }
    • Returns the entry for the provided path starting from vessels.self in the full data model.

      Parameters

      • path: string

      Returns any

      let uuid = app.getSelfPath('uuid');
      // Note: This is synonymous with app.getPath('vessels.self.uuid')

      app.debug(uuid);
      // urn:mrn:signalk:uuid:a9d2c3b1-611b-4b00-8628-0b89d014ed60
    • Emit a delta message.

      Note: These deltas are handled by the server in the same way as any other incoming deltas.

      Parameters

      • id: string
      • msg: any
      • OptionalskVersion: SKVersion

        Optional parameter to specify the Signal K version of the delta.

      Returns void

      app.handleMessage('my-signalk-plugin', {
      updates: [
      {
      values: [
      {
      path: 'navigation.courseOverGroundTrue',
      value: 1.0476934
      }
      ]
      }
      ]
      });

      Plugins emitting deltas that use Signal K v2 paths (like the Course API paths) should call handleMessage with the optional skVersion parameter set to v2. This prevents v2 API data getting mixed in v1 paths' data in full data model & the v1 http API.

      Omitting the skVersion parameter will cause the delta to be sent as v1.

    • Parameters

      • aPath: string
      • value: string | number | boolean | object
      • updateCb: (err?: Error) => void
      • source: string

      Returns Promise<any>

    • Parameters

      • aPath: string
      • value: any
      • updateCb: () => void

      Returns Promise<any>

    • Register a function to intercept all delta messages before they are processed by the server.

      The callback function should call next(delta) with either:

      • A modified delta (if it wants to alter the incoming delta)
      • With the original delta to process it normally.
      Important

      Not calling next(delta) will cause the incoming delta to be dropped and will only show in delta statistics.

      Other, non-delta messages produced by provider pipe elements are emitted normally.

      Parameters

      Returns void

      app.registerDeltaInputHandler((delta, next) => {
      delta.updates.forEach(update => {
      update.values.forEach(pathValue => {
      if(pathValue.startsWith("foo")) {
      pathValue.path = "bar"
      }
      })
      })
      next(delta)
      });

    Other

    • Returns the available APIs and Plugins.

      Example:

      let features = app.getFeatures();

      {
      "apis": [
      "resources","course"
      ],
      "plugins": [
      {
      "id": "anchoralarm",
      "name": "Anchor Alarm",
      "version": "1.13.0",
      "enabled": true
      },
      {
      "id": "autopilot",
      "name": "Autopilot Control",
      "version": "1.4.0",
      "enabled": false
      },
      {
      "id": "sk-to-nmea2000",
      "name": "Signal K to NMEA 2000",
      "version": "2.17.0",
      "enabled": false
      },
      {
      "id": "udp-nmea-sender",
      "name": "UDP NMEA0183 Sender",
      "version": "2.0.0",
      "enabled": false
      }
      ]
      }

      Parameters

      • OptionalonlyEnabled: boolean

        undefined (not provided): list all features

        • true: list only enabled features
        • false: list only disabled features

      Returns FeatureInfo

    • Parameters

      • context: string
      • path: string
      • callback: () => void
      • source: string

      Returns void

    • Parameters

      • provider: {
            getHistory: (
                date: Date,
                path: string,
                cb: (deltas: object[]) => void,
            ) => void;
            hasAnydata: (options: object, cb: (hasResults: boolean) => void) => void;
            streamHistory: (
                spark: any,
                options: object,
                onDelta: (delta: object) => void,
            ) => void;
        }

      Returns void

    • Register a handler to action PUT requests for a specific path.

      The action handler can handle the request synchronously or asynchronously.

      The callback parameter should be a function which accepts the following arguments:

      • context
      • path
      • value
      • callback

      For synchronous actions, the handler must return a value describing the response of the request:

      {
      state: 'COMPLETED',
      statusCode: 200
      }

      or

      {
      state:'COMPLETED',
      statusCode: 400,
      message:'Some Error Message'
      }

      The statusCode value can be any valid HTTP response code.

      For asynchronous actions, that may take considerable time to complete and the requester should not be kept waiting for the result, the handler must return:

      { state: 'PENDING' }
      

      When the action has completed the handler should call the callback function with the result:

      callback({ state: 'COMPLETED', statusCode: 200 })
      

      or

      callback({
      state:'COMPLETED',
      statusCode: 400,
      message:'Some Error Message'
      })

      Example: Synchronous response:

      function myActionHandler(context, path, value, callback) {
      if(doSomething(context, path, value)){
      return { state: 'COMPLETED', statusCode: 200 };
      } else {
      return { state: 'COMPLETED', statusCode: 400 };
      }
      }

      plugin.start = (options) => {
      app.registerPutHandler('vessels.self', 'some.path', myActionHandler, 'somesource.1');
      }

      Example: Asynchronous response:

      function myActionHandler(context, path, value, callback) {

      doSomethingAsync(context, path, value, (result) =>{
      if(result) {
      callback({ state: 'COMPLETED', result: 200 })
      } else {
      callback({ state: 'COMPLETED', result: 400 })
      }
      });

      return { state: 'PENDING' };
      }

      plugin.start = (options) => {
      app.registerPutHandler('vessels.self', 'some.path', myActionHandler);
      }

      Parameters

      • context: string
      • path: string
      • callback: () => void
      • source: string

      Returns void

    Property Values

    Resources API

    resourcesApi: ResourcesApi

    Access the Resources API to list, get, set, and delete resources.

    Serial Ports

    Status and Debugging

    • Log debug messages.

      This function exposes the debug method from the debug module. The npm module name is used as the debug name.

      app.debug() can take any type and will serialize it before outputting.

      Note

      Do not use debug from the debug module directly! Using app.debug() provided by the server ensures that the plugin taps into the server's debug logging system, including the helper switches in Admin UI's Server Log page.

      Parameters

      • msg: string

      Returns void

    • Parameters

      • msg: string

      Returns void

    • Report to the server that the plugin has sent data to other hosts, which will update the output message rate and icon in the Dashboard.

      Note: This function is for use when the plugin is sending data to hosts other than the Signal K server (e.g. network packets, http requests or messages sent to a broker).

      This function should NOT be used for deltas that the plugin sends with handleMessage()!

      Parameters

      • Optionalcount: number

        number of handled messages between the last call and this one. If omitted the call will count as one output message.

      Returns void

      app.reportOutputMessages(54);
      
    • Set the current error status of the plugin that is displayed in the plugin configuration UI and the Dashboard.

      The msg parameter should be a short text message describing the current status of the plugin.

      Parameters

      • msg: string

      Returns void

      app.setPluginError('Error connecting to database');
      

      Note: Replaces deprecated setProviderError()

    • Set the current status of the plugin that is displayed in the plugin configuration UI and the Dashboard.

      The msg parameter should be a short text message describing the current status of the plugin.

      Parameters

      • msg: string

      Returns void

      app.setPluginStatus('Initializing');
      // Do something
      app.setPluginStatus('Done initializing');

      Note: Replaces deprecated setProviderStatus()