# 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 {
notificationsApi: NotificationsApi;
radarApi: RadarApi;
registerRadarProvider: (provider: RadarProvider) => void;
registerWeatherProvider: (provider: WeatherProvider) => void;
resourcesApi: ResourcesApi;
selfContext: string;
selfId: string;
selfType: string;
streambundle: StreamBundle;
subscriptionmanager: SubscriptionManager;
weatherApi: WeatherApi;
getHistoryApi?: (providerId?: string) => Promise<HistoryApi>;
getRadarApi?: () => Promise<RadarApi>;
activateRoute(dest: RouteDestination | null): Promise<void>;
autopilotUpdate(deviceId: string, apInfo: { [path: string]: Value }): void;
clearDestination(): Promise<void>;
debug(msg: any, ...args: any[]): void;
emitPropertyValue(name: string, value: unknown): void;
error(msg: string): void;
getCourse(): Promise<CourseInfo>;
getDataDirPath(): string;
getFeatures(onlyEnabled?: boolean): Promise<FeatureInfo>;
getMetadata(path: string): Metadata | undefined;
getPath(path: string): unknown;
getSelfPath(path: string): unknown;
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<unknown>;
putSelfPath(
aPath: string,
value: unknown,
updateCb: () => void,
): Promise<unknown>;
queryRequest(requestId: string): Promise<unknown>;
readPluginOptions(): object;
registerActionHandler(
context: string,
path: string,
callback: ActionHandler,
source?: string,
): void;
registerAutopilotProvider(
provider: AutopilotProvider,
devices: string[],
): void;
registerDeltaInputHandler(handler: DeltaInputHandler): void;
registerHistoryApiProvider(provider: HistoryApi): void;
registerHistoryProvider(
provider: {
getHistory: (
date: Date,
path: string,
cb: (deltas: object[]) => void,
) => void;
hasAnydata: (options: object, cb: (hasResults: boolean) => void) => void;
streamHistory: (
spark: unknown,
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: ErrnoException | null) => void,
): void;
setDestination(
dest:
| (PointDestination & { arrivalCircle?: number | undefined; })
| null,
): Promise<void>;
setPluginError(msg: string): void;
setPluginStatus(msg: string): void;
unregisterHistoryApiProvider(): void;
}

#### Hierarchy

- PropertyValuesEmitter
- ResourceProviderRegistry
- WithResourcesApi
- WeatherProviderRegistry
- RadarProviderRegistry
- WithRadarApi
- WithHistoryApi
- HistoryProviderRegistry
- CourseApi
- WithNotificationsApi
- SelfIdentity
  - ServerAPI

- Defined in serverapi.ts:33

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

notificationsApi
selfContext
selfId
selfType
getHistoryApi?
getRadarApi?
getFeatures
queryRequest
registerActionHandler
registerHistoryApiProvider
registerHistoryProvider
registerPutHandler
unregisterHistoryApiProvider

### Property Values

emitPropertyValue
onPropertyValues

### Radar API

radarApi
registerRadarProvider

### 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. Callable in plugin's `start()` function and later, not in plugin constructor function.

  #### Returns string

  #### Example

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

  - Defined in serverapi.ts:305

### readPluginOptions

- readPluginOptions(): object

  Read the stored plugin configuration options.

  #### Returns object

  #### Example

      let options = app.readPluginOptions();

  - Defined in serverapi.ts:293

### savePluginOptions

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

  Save changes to the plugin's configuration options.

  #### Parameters

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

  #### Returns void

  #### Example

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

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

  - Defined in serverapi.ts:278

## Course API

### activateRoute

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

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

  #### Parameters

  - dest: RouteDestination | null

    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:
  | (PointDestination & { arrivalCircle?: number | undefined; })
  | null,
  ): Promise<void>

  Set course to a specified position / waypoint.

  #### Parameters

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

    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:134

### subscriptionmanager

subscriptionmanager: SubscriptionManager

#### See

Processing data from the server

- Defined in serverapi.ts:140

### getMetadata

- getMetadata(path: string): Metadata | undefined

  #### Parameters

  - path: string

  #### Returns Metadata | undefined

  - Defined in serverapi.ts:101

### getPath

- getPath(path: string): unknown

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

  #### Parameters

  - path: string

  #### Returns unknown

  #### Remarks

  Returns `unknown` because the Signal K data model is dynamic and path-dependent. Callers should validate the returned type at runtime.

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

### getSelfPath

- getSelfPath(path: string): unknown

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

  #### Parameters

  - path: string

  #### Returns unknown

  #### Remarks

  Returns `unknown` because the Signal K data model is dynamic and path-dependent. Callers should validate the returned type at runtime.

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

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

### putPath

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

  Call the PUT handler for a path with a specified context.

  #### Parameters

  - aPath: string

    The path for the PUT request

  - value: string | number | boolean | object

    The value to send in the PUT request

  - updateCb: (err?: Error) => void

    Callback invoked when the update completes, with error if failed

  - source: string

    The source identifier for this update

  #### Returns Promise<unknown>

  - Defined in serverapi.ts:124

### putSelfPath

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

  Call the PUT handler for a path on the vessel's own context.

  #### Parameters

  - aPath: string

    The path for the PUT request

  - value: unknown

    The value to send in the PUT request

  - updateCb: () => void

    Callback invoked when the update completes

  #### Returns Promise<unknown>

  - Defined in serverapi.ts:110

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

## Other

### notificationsApi

notificationsApi: NotificationsApi

Inherited from WithNotificationsApi.notificationsApi

- Defined in notificationsapi.ts:59

### selfContext

selfContext: string

Inherited from SelfIdentity.selfContext

- Defined in serverapi.ts:479

### selfId

selfId: string

Inherited from SelfIdentity.selfId

- Defined in serverapi.ts:478

### selfType

selfType: string

Inherited from SelfIdentity.selfType

- Defined in serverapi.ts:477

### `Optional` getHistoryApi

getHistoryApi?: (providerId?: string) => Promise<HistoryApi>

Returns a promise for a History API implementation, or rejects if unavailable. The property is optional to support explicitly older servers that do not have a history api provider.

When called without arguments, returns a proxy to the default provider. When called with a provider id, returns that specific provider's HistoryApi instance.

#### Type Declaration

- - (providerId?: string): Promise<HistoryApi>

  - #### Parameters

    - `Optional` providerId: string

      Optional id of a specific history provider plugin. If omitted, returns the default provider.

    #### Returns Promise<HistoryApi>

    Promise that resolves to a HistoryApi instance if available, or rejects with an error if not.

Inherited from WithHistoryApi.getHistoryApi

- Defined in history.ts:137

### `Optional` getRadarApi

getRadarApi?: () => Promise<RadarApi>

Returns a promise for the active Radar API implementation, or rejects if unavailable. The property is optional to support older servers that do not have radar API support.

#### Type Declaration

- - (): Promise<RadarApi>

  - #### Returns Promise<RadarApi>

    Promise that resolves to a RadarApi instance if available, or rejects with an error if not.

Inherited from WithRadarApi.getRadarApi

- Defined in radarapi.ts:788

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

  Query the status of an async request by its ID.

  #### Parameters

  - requestId: string

    The request ID to query

  #### Returns Promise<unknown>

  Promise resolving to the request status/result

  - Defined in serverapi.ts:147

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

### registerHistoryApiProvider

- registerHistoryApiProvider(provider: HistoryApi): void

  #### Parameters

  - provider: HistoryApi

  #### Returns void

  Inherited from HistoryProviderRegistry.registerHistoryApiProvider

  - Defined in history.ts:116

### registerHistoryProvider

- registerHistoryProvider(
  provider: {
  getHistory: (
  date: Date,
  path: string,
  cb: (deltas: object[]) => void,
  ) => void;
  hasAnydata: (options: object, cb: (hasResults: boolean) => void) => void;
  streamHistory: (
  spark: unknown,
  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: unknown,
    options: object,
    onDelta: (delta: object) => void,
    ) => void;
    }

    - ##### getHistory: (date: Date, path: string, cb: (deltas: object[]) => void) => void

    - ##### hasAnydata: (options: object, cb: (hasResults: boolean) => void) => void

    - ##### streamHistory: (spark: unknown, options: object, onDelta: (delta: object) => void) => void

  #### Returns void

  - Defined in serverapi.ts:409

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

### unregisterHistoryApiProvider

- unregisterHistoryApiProvider(): void

  #### Returns void

  Inherited from HistoryProviderRegistry.unregisterHistoryApiProvider

  - Defined in history.ts:117

## Property Values

### emitPropertyValue

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

  Emit a property value that can be received by listeners.

  #### Parameters

  - name: string

    The property name identifier

  - value: unknown

    The value to emit (can be any type including functions)

  #### Returns void

  Inherited from PropertyValuesEmitter.emitPropertyValue

  - Defined in propertyvalues.ts:45

### onPropertyValues

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

  #### Parameters

  - name: string
  - cb: PropertyValuesCallback

  #### Returns () => void

  Inherited from PropertyValuesEmitter.onPropertyValues

  - Defined in propertyvalues.ts:50

## Radar API

### radarApi

radarApi: RadarApi

Access the Radar API to get radar info and manage radars.

Inherited from RadarProviderRegistry.radarApi

- Defined in radarapi.ts:760

### registerRadarProvider

registerRadarProvider: (provider: RadarProvider) => void

Register a radar provider plugin. See Radar Provider Plugins documentation for details.

Inherited from RadarProviderRegistry.registerRadarProvider

- Defined in radarapi.ts:754

## Resources API

### resourcesApi

resourcesApi: ResourcesApi

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

Inherited from ResourceProviderRegistry.resourcesApi

- Defined in resourcesapi.ts:405

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

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

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

### error

- error(msg: string): void

  #### Parameters

  - msg: string

  #### Returns void

  - Defined in serverapi.ts:152

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

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

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

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