SmartSpectraSDK
Vitals measurement entry point. Owns one processing pipeline and surfaces lifecycle events via on(). Lifecycle methods throw a JS Error on failure with numeric code (a SmartSpectraErrorCode value), message, and boolean retryable properties.
import { SmartSpectraSDK, PixelFormat, decodeMetrics } from '@smartspectra/node-sdk';
const sdk = new SmartSpectraSDK({ apiKey: 'YOUR_KEY' });
sdk.on('metrics', (buf, ts) => console.log(decodeMetrics(buf)));
sdk.useCustomInput();
sdk.start();
sdk.sendFrame(rgbBuf, width, height, stride, PixelFormat.kRGB, timestampUs);
await sdk.destroy();
Methods
-
static availableCameras(): CameraInfo[]No SDK instance, authentication, or capture required. Throws when discovery is unsupported.
-
constructor(options?: SmartSpectraOptions) -
start(): voidInitialize and begin the input configured with useCamera, useCustomInput, or useFile.
-
stop(): voidRequest the session to stop. Idempotent.
-
stopAsync(): Promise<void>Async variant of stop() — the native stop blocks until the pipeline drains; prefer this in event-loop-sensitive contexts.
-
reset(): voidRebuild after kError. Clears the source unless useCamera(selection, options) opted into retention. After typed selection, throws kInvalidState while stopAsync() is pending; await it before resetting.
-
waitUntilComplete(timeoutMs?: number): booleanBlock until the session reaches a terminal state (idle or error), or the timeout elapses. Returns true if the session settled, false on timeout.
timeoutMs <= 0(the default) waits indefinitely. Use afteruseFile()+start()to block until end-of-file. -
destroy(): Promise<void>Tear down the session. Idempotent. Await before constructing a replacement session when teardown ordering matters, since native SDK state is process-global.
-
requestInsight(text: string): numberDispatch an on-demand insight prompt; returns the request id. The matching Insight response arrives asynchronously through the
'insight'event with the same id. -
useCustomInput(frameTransform?: FrameTransformValue): thisSelect the custom frame-push input source (push frames via
sendFrame()afterstart()). Returnsthisfor chaining; call beforestart(). -
useCamera(selection: CameraSelection, options?: Omit<CameraOptions, 'deviceIndex'>): thisSelect a live camera as the input source. The SDK opens the camera and pumps frames internally on
start()— nosendFrame()needed. Returnsthisfor chaining. Captures in THIS process — for Electron, prefer the renderer SDK’suseMediaStream(). Select while stopped; explicit requests never fall back. Selection is resolved at startup and retained across stop/start/reset. Invalid or busy requests preserve the previous source. Pass CameraSelection.default for SDK selection. -
useCamera(options?: CameraOptions): thisSelect a camera by legacy index (default 0). Reset clears the source. @deprecated Pass an explicit CameraSelection and separate capture options instead.
-
useFile(videoPath: string, options?: VideoFileOptions): thisSelect a pre-recorded video file as the input source.
start()begins playback (non-blocking, on SDK worker threads); usewaitUntilComplete()or watch'processingStatus'for the idle transition to detect end-of-file. Returnsthisfor chaining. -
sendFrame( buffer: Uint8Array | Buffer, width: number, height: number, stride: number, pixelFormat: PixelFormatValue, timestampUs: number, ): booleanSubmits a raw video frame. Requires
useCustomInput()+start()first. -
on(event: 'processingStatus', callback: (status: ProcessingStatusValue) => void): thisRegister a callback for a named event. Replaces any previously registered callback for the same event. Returns
thisfor chaining. -
on(event: 'validationStatus', callback: (code: ValidationCodeValue, timestampUs: number, hint: string) => void): this -
on(event: 'metrics', callback: (buf: Buffer, timestampUs: number) => void): this -
on(event: 'accumulatedMetrics', callback: (buf: Buffer, timestampUs: number) => void): this -
on(event: 'insight', callback: (buf: Buffer, requestId: number) => void): this -
on(event: 'error', callback: (code: SmartSpectraErrorCodeValue, message: string, retryable: boolean) => void): this -
on(event: 'frameSentThrough', callback: (sent: boolean, timestampUs: number) => void): this -
on(event: 'videoOutput', callback: (buf: Buffer, width: number, height: number, stride: number, pixelFormat: PixelFormatValue, timestampUs: number) => void): this
Properties
-
static readonly version: stringSDK package version.
-
readonly processingStatus: ProcessingStatusValueCurrent ProcessingStatus integer value.
SmartSpectraOptions
Options passed to the SmartSpectra constructor.
apiKey?: string
API key for server-validated auth.
requestedMetrics?: number[]
MetricType integer codes. Defaults to breathingMetrics when omitted.
enableAccumulatedOutput?: boolean
Also emit an accumulated metrics packet at the end of each session.
logLevel?: SmartSpectraLogLevelValue
Verbosity of SDK logging, applied when the session initializes. Defaults to SmartSpectraLogLevel.kWarning (warnings and errors only).
enableTelemetry?: boolean
Aggregate SDK telemetry. Defaults to true; set false to opt out.
VideoFileOptions
Playback options for useFile().
timestampsPath?: string | null
Path to a per-frame timestamps file (one timestamp per line).
interframeDelayMs?: number
Throttle between frames in ms; omit/0 = as fast as possible.
startOffsetMs?: number
Seek this far into the file before playback (ms); omit/0 = start.
maxDurationMs?: number
Stop after this much content (ms); omit/0 = no limit.
frameTransform?: FrameTransformValue
Spatial transform applied to every frame.
CameraOptions
Capture settings, separate from camera selection.
deviceIndex?: number
@deprecated Use useCamera(CameraSelection.byId(id), options) instead.
width?: number
Capture width in px; omit/0 = SDK default.
height?: number
Capture height in px; omit/0 = SDK default.
fps?: number
Capture frame rate; omit/0 = SDK default.
frameTransform?: FrameTransformValue
Spatial transform applied to every frame.
FrameTransform
Frame transform applied by the SDK to every pushed frame.
readonly kNone: 0readonly kRotate90CW: 1readonly kRotate90CCW: 2readonly kRotate180: 3readonly kMirrorHorizontal: 4readonly kMirrorVertical: 5
PixelFormat
Pixel format of a raw frame buffer passed to sendFrame().
readonly kRGB: 0readonly kBGR: 1readonly kRGBA: 2readonly kBGRA: 3readonly kNV12: 4readonly kNV21: 5readonly kYUYV: 6
ProcessingStatus
Processing lifecycle status. Integer values are stable across SDK versions.
readonly kUninitialized: 0readonly kIdle: 1readonly kStarting: 2readonly kRunning: 3readonly kStopping: 4readonly kError: 5
ValidationCode
Measurement-readiness codes delivered via the ‘validationStatus’ event.
readonly kOk: 0readonly kNoFaceFound: 1readonly kMultipleFacesFound: 2readonly kFaceNotCentered: 3readonly kFaceSizeOutOfRange: 4readonly kTooDark: 5readonly kTooBright: 6readonly kChestNotVisible: 7readonly kCameraTuning: 10readonly kFrameRateTooLow: 11readonly kExcessiveMotion: 12readonly kFaceTooClose: 13readonly kFaceTooFar: 14readonly kFaceTooHigh: 15readonly kFaceTooLow: 16readonly kFaceNotForward: 17
SmartSpectraErrorCode
Error codes on errors thrown by lifecycle methods and delivered via the ‘error’ event.
readonly kOk: 0readonly kInvalidState: 1readonly kAuthenticationFailed: 2readonly kConfigurationFailed: 3readonly kCreditExhausted: 4readonly kNetworkError: 5readonly kServerError: 6readonly kInputUnavailable: 7readonly kProcessingFailed: 8readonly kFrameConversionFailed: 9readonly kNonMonotonicTimestamp: 10readonly kTimestampGap: 11
decodeMetrics()
Deserialize a protobuf Metrics buffer from the ‘metrics’ or ‘accumulatedMetrics’ events. Returns the decoded message if a class has been registered via setMetricsClass, otherwise the raw Buffer.
export declare function decodeMetrics(buf: Buffer): unknown
setMetricsClass()
Register a protobuf Metrics class exposing deserializeBinary(buf) (google-protobuf) or decode(buf) (protobufjs). decodeMetrics() will use it; otherwise the raw Buffer is returned.
export declare function setMetricsClass(cls: unknown): void
CameraInfo
Discovery snapshot. IDs are opaque and platform-local; rediscover before reuse.
readonly id: string
readonly name: string | null
readonly facing: CameraFacing
readonly lensType: CameraLensType
SmartSpectraLogLevel
Verbosity of SDK logging, set via the SmartSpectraSDK logLevel option. Levels are cumulative: a level shows its own messages plus everything more severe.
readonly kDebug: 0readonly kInfo: 1readonly kWarning: 2readonly kError: 3readonly kNone: 4
MetricType
MetricType integer codes accepted by requestedMetrics. Runtime values are generated from protobuf.
readonly CHEST_BREATHING: 0readonly ABDOMEN_BREATHING: 1readonly BREATHING_RATE: 2readonly BREATHING_AMPLITUDE: 3readonly APNEA: 4readonly RESPIRATORY_LINE_LENGTH: 5readonly BASELINE: 6readonly INHALE_EXHALE_RATIO: 7readonly EDA_TRACE: 10readonly FACE_LANDMARKS: 11readonly BLINKING: 12readonly TALKING: 13readonly EXPRESSIONS: 14readonly PULSE_RATE: 15readonly ARTERIAL_PRESSURE_TRACE: 16readonly HRV: 17
CameraSelection
readonly default: Readonly<{ kind: 'default' }>readonly front: Readonly<{ kind: 'front' }>readonly back: Readonly<{ kind: 'back' }>readonly byId: (id: string) => Readonly<{ kind: 'byId'; id: string }>
ProcessingStatusValue
export type ProcessingStatusValue = typeof ProcessingStatus[keyof typeof ProcessingStatus];
SmartSpectraLogLevelValue
export type SmartSpectraLogLevelValue = typeof SmartSpectraLogLevel[keyof typeof SmartSpectraLogLevel];
PixelFormatValue
export type PixelFormatValue = typeof PixelFormat[keyof typeof PixelFormat];
ValidationCodeValue
export type ValidationCodeValue = typeof ValidationCode[keyof typeof ValidationCode];
SmartSpectraErrorCodeValue
export type SmartSpectraErrorCodeValue = typeof SmartSpectraErrorCode[keyof typeof SmartSpectraErrorCode];
FrameTransformValue
export type FrameTransformValue = typeof FrameTransform[keyof typeof FrameTransform];
MetricTypeValue
export type MetricTypeValue = typeof MetricType[keyof typeof MetricType];
CameraFacing
export type CameraFacing = 'front' | 'back' | 'unknown';
CameraLensType
Best-effort classification. Missing metadata and multi-lens cameras are unknown; independent of digital zoom.
export type CameraLensType = 'unknown' | 'wideAngle' | 'ultraWide' | 'telephoto';