# 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 {
registerWeatherProvider: (provider: WeatherProvider) => void;
resourcesApi: ResourcesApi;
selfContext: string;
selfId: string;
selfType: string;
streambundle: StreamBundle;
subscriptionmanager: SubscriptionManager;
weatherApi: WeatherApi;
activateRoute(dest: null | RouteDestination): Promise<void>;
autopilotUpdate(deviceId: string, apInfo: { [path: string]: Value }): void;
clearDestination(): Promise<void>;
debug(msg: any, ...args: any[]): void;
emitPropertyValue(name: string, value: any): void;
error(msg: string): void;
getCourse(): Promise<CourseInfo>;
getDataDirPath(): string;
getFeatures(onlyEnabled?: boolean): Promise<FeatureInfo>;
getMetadata(path: string): undefined | Metadata;
getPath(path: string): any;
getSelfPath(path: string): any;
getSerialPorts(): Promise<Ports>;
handleMessage(id: string, msg: Partial<Delta>, 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: ActionHandler,
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: ActionHandler,
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

- PropertyValuesEmitter
- ResourceProviderRegistry
- WeatherProviderRegistry
- CourseApi
- SelfIdentity
  - ServerAPI

- Defined in serverapi.ts:29

##### Index

### Autopilot API

autopilotUpdate
registerAutopilotProvider

### Configuration

getDataDirPath
readPluginOptions
savePluginOptions

### Course API

activateRoute
clearDestination
getCourse
setDestination

### Data Model

streambundle
subscriptionmanager
getMetadata
getPath
getSelfPath
handleMessage
putPath
putSelfPath
registerDeltaInputHandler

### Other

selfContext
selfId
selfType
getFeatures
queryRequest
registerActionHandler
registerHistoryProvider
registerPutHandler

### Property Values

emitPropertyValue
onPropertyValues

### Resources API

resourcesApi
registerResourceProvider

### Serial Ports

getSerialPorts

### Status and Debugging

debug
error
reportOutputMessages
setPluginError
setPluginStatus

### Weather API

registerWeatherProvider
weatherApi

## Autopilot API

### autopilotUpdate

- autopilotUpdate(deviceId: string, apInfo: { [path: string]: Value }): void

  #### Parameters

  - deviceId: string

    the autopilot device identifier

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

    object containing values keyed by AutopilotInfo

  #### Returns void

  Inherited from AutopilotProviderRegistry.autopilotUpdate

  - Defined in autopilotapi.ts:484

### registerAutopilotProvider

- registerAutopilotProvider(provider: AutopilotProvider, devices: string[]): void

  #### Parameters

  - provider: AutopilotProvider
  - devices: string[]

  #### Returns void

  Inherited from AutopilotProviderRegistry.registerAutopilotProvider

  - Defined in autopilotapi.ts:474

## Configuration

### getDataDirPath

- getDataDirPath(): string

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

  #### Returns string

  #### Example

      let myDataFile = require('path').join( app.getDataDirPath(), 'somedatafile.ext')

  - Defined in serverapi.ts:273

### readPluginOptions

- readPluginOptions(): object

  Read the stored plugin configuration options.

  #### Returns object

  #### Example

      let options = app.readPluginOptions();

  - Defined in serverapi.ts:262

### savePluginOptions

- savePluginOptions(
  configuration: object,
  cb: (err: null | ErrnoException) => void,
  ): void

  Save changes to the plugin's configuration options.

  #### Parameters

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

  #### Returns void

  #### Example

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

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

  - Defined in serverapi.ts:247

## Course API

### activateRoute

- activateRoute(dest: null | RouteDestination): Promise<void>

  Follow a route in the specified direction and starting at the specified point.

  #### Parameters

  - dest: null | RouteDestination

    Object containing route information.

    - returns: Resolved Promise on success.

  #### Returns Promise<void>

  Inherited from CourseApi.activateRoute

  - Defined in course.ts:43

### clearDestination

- clearDestination(): Promise<void>

  Cancels navigation to the current point or route being followed.

  #### Returns Promise<void>

  Inherited from CourseApi.clearDestination

  - Defined in course.ts:20

### getCourse

- getCourse(): Promise<CourseInfo>

  Retrieves the current course information.

  #### Returns Promise<CourseInfo>

  Inherited from CourseApi.getCourse

  - Defined in course.ts:13

### setDestination

- setDestination(
  dest:
  | null
  | (PointDestination & { arrivalCircle?: number | undefined; }),
  ): Promise<void>

  Set course to a specified position / waypoint.

  #### Parameters

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

    Object containing destination position information.

  #### Returns Promise<void>

  Inherited from CourseApi.setDestination

  - Defined in course.ts:30

## Data Model

### streambundle

streambundle: StreamBundle

- Defined in serverapi.ts:106

### subscriptionmanager

subscriptionmanager: SubscriptionManager

#### See

Processing data from the server

- Defined in serverapi.ts:112

### getMetadata

- getMetadata(path: string): undefined | Metadata

  #### Parameters

  - path: string

  #### Returns undefined | Metadata

  - Defined in serverapi.ts:84

### getPath

- getPath(path: string): any

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

  #### Parameters

  - path: string

  #### Returns any

  #### Example

      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'
        }
      }

  - Defined in serverapi.ts:79

### getSelfPath

- getSelfPath(path: string): any

  Returns the entry for the provided path starting from `vessels.self` in the full data model.

  #### Parameters

  - path: string

  #### Returns any

  #### Example

      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

  - Defined in serverapi.ts:52

### handleMessage

- handleMessage(id: string, msg: Partial<Delta>, skVersion?: SKVersion): void

  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: Partial<Delta>
  - `Optional` skVersion: SKVersion

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

  #### Returns void

  #### Example

      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`.

  - Defined in serverapi.ts:231

### putPath

- putPath(
  aPath: string,
  value: string | number | boolean | object,
  updateCb: (err?: Error) => void,
  source: string,
  ): Promise<any>

  #### Parameters

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

  #### Returns Promise<any>

  - Defined in serverapi.ts:95

### putSelfPath

- putSelfPath(aPath: string, value: any, updateCb: () => void): Promise<any>

  #### Parameters

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

  #### Returns Promise<any>

  - Defined in serverapi.ts:90

### registerDeltaInputHandler

- registerDeltaInputHandler(handler: DeltaInputHandler): void

  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

  - handler: DeltaInputHandler

  #### Returns void

  #### Example

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

  - Defined in serverapi.ts:167

## Other

### selfContext

selfContext: string

Inherited from SelfIdentity.selfContext

- Defined in serverapi.ts:448

### selfId

selfId: string

Inherited from SelfIdentity.selfId

- Defined in serverapi.ts:447

### selfType

selfType: string

Inherited from SelfIdentity.selfType

- Defined in serverapi.ts:446

### getFeatures

- getFeatures(onlyEnabled?: boolean): Promise<FeatureInfo>

  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

  - `Optional` onlyEnabled: boolean

    `undefined` (not provided): list all features

    - `true`: list only enabled features
    - `false`: list only disabled features

  #### Returns Promise<FeatureInfo>

  Inherited from WithFeatures.getFeatures

  - Defined in features.ts:50

### queryRequest

- queryRequest(requestId: string): Promise<any>

  #### Parameters

  - requestId: string

  #### Returns Promise<any>

  - Defined in serverapi.ts:116

### registerActionHandler

- registerActionHandler(
  context: string,
  path: string,
  callback: ActionHandler,
  source?: string,
  ): void

  #### Parameters

  - context: string
  - path: string
  - callback: ActionHandler
  - `Optional` source: string

  #### Returns void

  - Defined in serverapi.ts:370

### registerHistoryProvider

- 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

  #### 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

  - Defined in serverapi.ts:377

### registerPutHandler

- registerPutHandler(
  context: string,
  path: string,
  callback: ActionHandler,
  source?: string,
  ): 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: ActionHandler
  - `Optional` source: string

  #### Returns void

  - Defined in serverapi.ts:363

## Property Values

### emitPropertyValue

- emitPropertyValue(name: string, value: any): void

  #### Parameters

  - name: string
  - value: any

  #### Returns void

  Inherited from PropertyValuesEmitter.emitPropertyValue

  - Defined in propertyvalues.ts:43

### onPropertyValues

- onPropertyValues(name: string, cb: PropertyValuesCallback): () => void

  #### Parameters

  - name: string
  - cb: PropertyValuesCallback

  #### Returns () => void

  Inherited from PropertyValuesEmitter.onPropertyValues

  - Defined in propertyvalues.ts:48

## Resources API

### resourcesApi

resourcesApi: ResourcesApi

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

Inherited from ResourceProviderRegistry.resourcesApi

- Defined in resourcesapi.ts:409

### registerResourceProvider

- registerResourceProvider(provider: ResourceProvider): void

  Used by Resource Provider plugins to register each resource type it handles. See `Resource Provider Plugins` for details.

  #### Parameters

  - provider: ResourceProvider

  #### Returns void

  Inherited from ResourceProviderRegistry.registerResourceProvider

  - Defined in resourcesapi.ts:402

## Serial Ports

### getSerialPorts

- getSerialPorts(): Promise<Ports>

  Returns Ports object which contains information about the serial ports available on the machine.

  #### Returns Promise<Ports>

  - Defined in serverapi.ts:398

## Status and Debugging

### debug

- debug(msg: any, ...args: any[]): void

  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: any
  - ...args: any[]

  #### Returns void

  - Defined in serverapi.ts:137

### error

- error(msg: string): void

  #### Parameters

  - msg: string

  #### Returns void

  - Defined in serverapi.ts:121

### reportOutputMessages

- reportOutputMessages(count?: number): 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

  - `Optional` count: number

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

  #### Returns void

  #### Example

      app.reportOutputMessages(54);

  - Defined in serverapi.ts:420

### setPluginError

- setPluginError(msg: string): void

  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

  #### Example

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

  Note: Replaces deprecated `setProviderError()`

  - Defined in serverapi.ts:201

### setPluginStatus

- setPluginStatus(msg: string): void

  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

  #### Example

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

  Note: Replaces deprecated `setProviderStatus()`

  - Defined in serverapi.ts:185

## Weather API

### registerWeatherProvider

registerWeatherProvider: (provider: WeatherProvider) => void

Used by Weather Provider plugins to register the weather service from which the data is sourced. See `Weather Provider Plugins` for details.

Inherited from WeatherProviderRegistry.registerWeatherProvider

- Defined in weatherapi.ts:119

### weatherApi

weatherApi: WeatherApi

Access the Weather API to get observations, forcasts and warnings.

Inherited from WeatherProviderRegistry.weatherApi

- Defined in weatherapi.ts:125