@nuralogix.ai/dfx-api-client / WebSocket / events

There are three WebSocket events:

  • onmessage
  • onclose
  • onerror

onmessage

onmessage is emitted when a new response is sent from the server to the client. You can have your custom logic based on each actionId you are receiving as part of the response.

const apiClient = client();
apiClient.websocket.onmessage = (requestId: string, status: string, message: any, actionId: string) => {
  // When socket connection is opened, the library tries to
  // authenticate against server using the `apiClient.session.deviceToken`
  // property that is previously stored in the current instance of the apiClient.
  // When authenticated, a reponse with a '0718' actionId will be returned from the server.
  // Once received, you can subscribe to measurement results by sending a '0510' actionId.
  if (actionId === '0718') {
    apiClient.websocket.sendMessage(
      '0510',
      { Params: {ID: 'your-measurement-id-goes-here' }, RequestID: '' }
    );
  }
  // A '0510' actionId will be returned from the server when
  // are subscribed to measurement results.
  if (actionId === '0510') {
    if (Object.keys(message).length === 0) {
      // If you received an empty message then it means your
      // successfully subscribed to the measurement results.
      // here you can have your logic to start your measurement
    } else {
      // Otherwise, the measurement is already started and the
      // message contains measurement results. You can process/display results.
    }
  }
  // A 0506 actionId is emitted on each chunk number
  if (actionId === '0506') {
    console.log('ChunkOrder', message.ChunkOrder)
  }
}

onclose

onclose CloseEvent is emitted when the connection is closed.

const apiClient = client();
apiClient.websocket.onclose = (e: CloseEvent) => {
    console.log('connection closed!', e.code, e.reason, e.wasClean);
}

onerror

onerror Event is emitted when there is an error.

const apiClient = client();
apiClient.websocket.onerror = (e: Event) => {
    console.log('error', e);
}