IPC Live Streaming

Last Updated on : 2026-02-11 06:48:03download

ThingIPCSdk is an Internet Protocol Camera Software Development Kit provided by Tuya for HarmonyOS developers. It encapsulates all the core functionalities for interacting with Tuya’s smart camera devices, enabling you to easily build applications for intelligent security, home monitoring, smart homes, and more.

API description

ThingIPCSdk module

init

Functional description

Initializes ThingIPCSdk. This is a necessary step before using any of the SDK’s functionalities. The initialization process configures the SDK runtime environment and registers essential services and components.

Function signature

static init(context: Context);

Parameters

Parameter Type Description
context Context The HarmonyOS application component context, used by the SDK for internal calls to system APIs.

IPC SDK initialization should be performed as early as possible, ideally during program startup.

Example

ThingIPCSdk.init();

getCameraP2P

Functional description

Gets an IThingCameraP2P instance object.

Function signature

static getCameraP2P(devId: string): IThingCameraP2P;

Parameters

Parameter Type Description
devId string The device ID.

Return value

The IThingCameraP2P instance object.

getCloudCamera

Functional description

Gets an IThingCloudCamera instance object.

Function signature

static getCloudCamera(devId: string): IThingCloudCamera;

Parameters

Parameter Type Description
devId string The device ID.

Return value

The IThingCloudCamera instance object.

getSDCardManager

Functional description

Gets an IThingCameraSDCardManager instance object.

Function signature

static getSDCardManager(devId: string) : IThingCameraSDCardManager;

Parameters

Parameter Type Description
devId string The device ID.

Return value

The IThingCameraSDCardManager instance object.

IThingCameraP2P module

initP2P

Functional description

Initializes the P2P connection service. P2P initialization depends on the completion of user login and the creation of the MQTT connection. It is used to create a direct channel between devices, enabling low-latency audio and video transmission.

Function signature

initP2P(uid: string): void;

Parameters

Parameter Type Description
uid string The unique user identifier, obtained from the user information after login.

IThingCameraP2P initialization depends on the completion of login and MQTT initialization.

Example

export class TSmartDeviceController implements ITSmartLocalKeyProvider {
  public async getLocalKey(topicId: string): Promise<string | undefined> {
    if (topicId.startsWith(TSmartMqttConfig.TOPIC_PREFIX_DEVICE_IN)) {
      const device =
        await TSmartDeviceCache.get(topicId.replace(TSmartMqttConfig.TOPIC_PREFIX_DEVICE_IN, '')) as TSmartDeviceModel
      return device.localKey;
    }
    return "";
  }
}

...
IPCLog.d(this.logTag, "Logged in successfully" + resp);
TSmartMqtt.initClient(TSmartUser.getDomain()?.mobileMqttsUrl ?? '',
                (TSmartUser.getPartnerIdentity() ?? '') + (TSmartUser.getSid() ?? ''), TSmartUser.getSid() ?? '',
                (await MD5.digest(TSmartUser.getEcode())).substring(8, 24), new TSmartDeviceController());

TSmartMqtt.connect();
ThingIPCSdk.getP2P().initP2P(TSmartUser.getUid() as string);

bindXComponentContext

Functional description

Sets the playback window.

Function signature

bindXComponentContext(xComponentContext: XComponentContext) : void;

Parameters

Parameter Type Description
xComponentContext XComponentContext The context object for the video rendering component, used to receive video frame data from the camera. The value cannot be undefined. Even though the signature might allow it, a valid value must be passed during actual use.

Example

cameraP2P = ThingIPCSdk.getCameraP2P("devid");

XComponent({id: 'xcomponentId0',type: XComponentType.SURFACE,
            libraryname: 'thingvideorenderersdk'
}).onLoad((xComponentContext) => {
    this.xComponentContext0 = xComponentContext as XComponentContext;
    this.cameraP2P.bindXComponentContext(this.xComponentContext0);
}).onDestroy(() => {
    console.log('onDestroy');
}).id("xcomponent")

connect/connectWrapper()

Functional description

Creates a P2P connection.

Function signature

connect(): Promise<ThingCameraResponse<number>>;
connectWrapper() : Promise<ThingCameraResponse<void>>;

Return value

Promise<ThingCameraResponse<number>>: Asynchronously returns a session ID (in the Data field) and an error code.

disconnect

Functional description

Closes a P2P connection.

Function signature

disconnect(force : boolean): Promise<ThingCameraResponse<void>>;

Parameters

Parameter Type Description
force boolean
  • true: Force disconnect
  • false: Normal disconnect

Return value

Promise<ThingCameraResponse<void>>

After disconnecting, connect must be called again to perform operations.

isconnect

Functional description

Returns the current connection status.

Function signature

isConnected(): boolean;

Return value (Boolean)

  • true: Connected.
  • false: Not connected.

startPreview

Functional description

Starts live video preview.

Function signature

startPreview(callback : ThingCameraCallback): Promise<ThingCameraResponse<void>>;

Parameters

Parameter Type Description
callback ThingCameraCallback The callback.

Return value

Promise<ThingCameraResponse<void>>

You need to call connect first.

Example

IPCLog.d(this.logTag, 'ipc connect start')

if (TSmartUser.getUid() !== undefined) {
    this.cameraP2P.connectWrapper().then((result) => {
        if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
            IPCLog.d(this.logTag, 'ipc connect success')
            let previewCallBack: ThingCameraCallback = {
                    onResponse: (reason: string, errCode: number) => {
                      if (errCode >= 0) {
                        IPCLog.d(this.logTag, 'ipc preview success')
                      } else {
                        IPCLog.e(this.logTag, 'ipc preview fail')
                      }
                      return 0;
                    }
                  }
            this.cameraP2P.startPreview(previewCallBack).then((result) => {
                    if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
                      IPCLog.d(this.logTag, 'ipc preview return success')
                    } else {
                      IPCLog.e(this.logTag, 'ipc preview fail')
                    }
                  }).catch((e: TSmartAtopRequestError) => {
                    IPCLog.e(this.logTag, 'ipc preview fail' + e)
                  });
                } else {
                  IPCLog.e(this.logTag, 'ipc connect fail')
                }
              }).catch((e: TSmartAtopRequestError) => {
                IPCLog.e(this.logTag, 'ipc connect fail' + e)
              })
            } else {
              IPCLog.e(this.logTag, 'uid is undefined')
            }
    IPCLog.d(this.logTag, 'ipc connect end')

stopPreview

Functional description

Stops live preview.

Function signature

stopPreview(callback : ThingCameraCallback): Promise<ThingCameraResponse<void>>;

Parameters

Parameter Type Description
callback ThingCameraCallback The callback.

Return value

Promise<ThingCameraResponse<void>>

Example

IPCLog.d(this.logTag, 'ipc disconnect start')
    let stopPreviewCallBack: ThingCameraCallback = {
              onResponse(reason: string, errCode: number): number {
                IPCLog.d(this.logTag, 'ipc disconnect callback')
                return 0;
              }
    };
    this.cameraP2P.stopPreview(stopPreviewCallBack).then((result) => {
        if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
            IPCLog.d(this.logTag, 'ipc stopPreview return success')
        } else {
                IPCLog.e(this.logTag, 'ipc stopPreview fail')
        }
    }).catch((e: TSmartAtopRequestError) => {
        IPCLog.e(this.logTag, 'ipc preview fail' + e)
    });

    this.cameraP2P.disconnect(true).then((result) => {
        if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
            IPCLog.d(this.logTag, 'ipc disconnect return success')
        } else {
            IPCLog.e(this.logTag, 'ipc disconnect fail')
        }
    }).catch((e: TSmartAtopRequestError) => {
        IPCLog.e(this.logTag, 'ipc preview fail' + e)
    });

startPlayBack

Functional description

Plays back videos recorded on the device (cloud playback).

Function signature

startPlayBack(startTime : number, endTime : number, playTime : number, callback: ThingCameraFinishableCallback<string, string>): void;

Parameters

Parameter Type Description
startTime number The start timestamp of playback, in seconds.
endTime number The end timestamp of playback, in seconds.
playTime number The initial playback timestamp, in seconds.
callback ThingCameraFinishableCallback<string, string> The callback for playback progress/status.

Example

camera.startPlayBack(1620000000, 1620003600, 1620000000, {  
  onFinished(data, code) {  
    if (code === 0) console.log("Playback is completed");  
  },  
  onEvent(type, info1, info2, msg) {  
    console.log("Playback event:", type);  
  }  
});  

pausePlayBack

Functional description

Pauses the playback.

Function signature

pausePlayBack() : Promise<ThingCameraResponse<number>>;

Return value

Promise<ThingCameraResponse<number>>

Example

if (this.cameraP2P !== undefined) {
            IPCLog.d(this.logTag, "Pause playback of videos from SD card");
            this.cameraP2P.pausePlayBack().then((result) => {
              if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
                IPCLog.d(this.logTag, "Paused playback of videos from SD card successfully");
              } else {
                IPCLog.d(this.logTag, "Failed to pause playback of videos from SD card");
              }
            });
          } else {
            IPCLog.d(this.logTag, "Failed to pause playback of videos from SD card, this.cameraP2P === undefined");
          }

resumePlayBack

Functional description

Resumes the playback.

Function signature

resumePlayBack() : Promise<ThingCameraResponse<number>>;

Return value

Promise<ThingCameraResponse<number>>

Example

if (this.cameraP2P !== undefined) {
            IPCLog.d(this.logTag, "Resume playback of videos from SD card");
            this.cameraP2P.resumePlayBack().then((result) => {
              if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
                IPCLog.d(this.logTag, "Resumed playback of videos from SD card successfully");
              } else {
                IPCLog.d(this.logTag, "Failed to resume playback of videos from SD card");
              }
            });
          } else {
            IPCLog.d(this.logTag, "Failed to resume playback of videos from SD card, this.cameraP2P === undefined");
          }

stopPlayBack()

Functional description

Stops the playback.

Function signature

stopPlayBack() : Promise<ThingCameraResponse<void>>;

Return value

Promise<ThingCameraResponse<void>>

Example

if (this.cameraP2P !== undefined) {
            IPCLog.d(this.logTag, "Stop playback of videos from SD card");

            this.cameraP2P.stopPlayBack().then((result) => {
              if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
                IPCLog.d(this.logTag, "Stopped playback of videos from SD card successfully");
              } else {
                IPCLog.d(this.logTag, "Failed to stop playback of videos from SD card" + result.errorCodeNumber);
              }
            });
          } else {
            IPCLog.d(this.logTag, "Failed to stop playback of videos from SD card, this.cameraP2P === undefined");
          }

queryRecordDaysByMonth

Functional description

Queries the list of all dates within a specified month that have recorded video data, used to mark which days have available playback recordings in a calendar control.

Function signature

queryRecordDaysByMonth(month: number, year: number): Promise<ThingCameraResponse<string>>;

Parameters

Parameter Type Description
month number The month, ranging from 1 to 12.
year number The year. For example, 2025.

Return value

Promise<ThingCameraResponse<string>>

  • A P2P connection must be created first (connectWrapper or connect).
  • The returned date format is a two-digit string. For example, "01" and "26".
  • If there are no recordings for that month, the DataDays array is empty.

Example

let connectResult = await this.cameraP2P.connectWrapper();

          if (connectResult.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
            IPCLog.d(this.logTag, "Connected successfully");
            this.cameraP2P.queryRecordDaysByMonth(3, 2025).then((result) => {
              if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS && result.data !== undefined) {
                let playbackDays = JSON.parse(result.data) as Record<string, Array<string>>;
                IPCLog.d(this.logTag, "queryRecordDaysByMonth succeeded" + playbackDays["DataDays"].toString());
              } else {
                IPCLog.e(this.logTag, "queryRecordDaysByMonth failed " + result.errorCodeNumber);
              }
            })
          } else {
            IPCLog.d(this.logTag, "Failed to connect");
          }

queryRecordTimeSliceByDay

Functional description

Queries the detailed recording time slice information for a specified date, including the start/end time of each video clip, used to generate a timeline control.

Function signature

queryRecordTimeSliceByDay(day : number, month : number, year : number) : Promise<ThingCameraResponse<string>>;

Parameters

Parameter Type Description
day number The date, ranging from 1 to 31.
month number The month, ranging from 1 to 12.
year number The year. For example, 2025.

Return value

Promise<ThingCameraResponse<string>>

Example

let connectResult = await this.cameraP2P.connectWrapper();

          if (connectResult.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
            IPCLog.d(this.logTag, "Connected successfully");
            this.cameraP2P.queryRecordTimeSliceByDay(26, 3, 2025).then((result) => {
              if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS && result.data !== undefined) {
                IPCLog.d(this.logTag, "queryRecordTimeSliceByDay succeeded");
                let playbackBean = JSON.parse(result.data)  as ThingCameraPlayBackBean;
                // let playbackBean = ArkTSUtils.ASON.parse(json) as ThingCameraPlayBackBean;
                IPCLog.d(this.logTag, "queryRecordTimeSliceByDay succeeded" + playbackBean.items?.length);
                if (playbackBean.items !== undefined && playbackBean.items?.length > 0) {
                  this.mFirstThingCameraTimePieceBean = playbackBean.items[0];
                }
              } else {
                IPCLog.e(this.logTag, "queryRecordTimeSliceByDay failed" + result.errorCodeNumber);
              }
            })
          } else {
            IPCLog.d(this.logTag, "Failed to connect");
          }

startRecordLocalMp4

Functional description

Records and saves the live video stream to a local file.

Function signature

startRecordLocalMp4(recordParams: ThingCameraSnapshotParams): Promise<ThingCameraResponse<string>>;

Parameters

Parameter Type Description
recordParams ThingCameraSnapshotParams The address used to save the file.

ThingCameraSnapshotParams structure

Parameter Type Description
dir string The path where the file will be saved.
filename string The file name.
rotate number The angle of rotation.
saveToSysTem boolean Specifies whether to save the file to the system’s photo album. Permission is required.

Return value

Promise<ThingCameraResponse<string>>

Example

const response = await camera.startRecordLocalMp4({  
  dir: "/sdcard/videos",  
  fileName: "20231001",  
  rotate: 0  
});  

stopRecordLocalMp4

Functional description

Stops local recording.

Function signature

stopRecordLocalMp4(): Promise<ThingCameraResponse<string>>;

Return value

Promise<ThingCameraResponse<string>>: The final file path.

This needs to be used in conjunction with startRecordLocalMp4.

Example

const response = await camera.stopRecordLocalMp4();  
console.log("Video saved:", response.data);  

startAudioTalk/stopAudioTalk

Functional description

Starts/stops two-way audio talk.

Function signature

startAudioTalk() : Promise<ThingCameraResponse<void>>;
stopAudioTalk() : Promise<ThingCameraResponse<void>>;

Return value

Promise<ThingCameraResponse<void>>

Confirm that the device supports audio functionality.

Example

await camera.startAudioTalk(); // Start audio talk
await camera.stopAudioTalk();  // Stop audio talk

getVideoBitRateKbps

Functional description

Get the live video bitrate.

Function signature

getVideoBitRateKbps() : number;

Return value

The current bitrate (kbps).

Example

const bitrate = camera.getVideoBitRateKbps();  
console.log("Current bitrate", bitrate);  

setMute/getMute

Functional description

Sets/gets the mute status.

Function signature

setMute(mute : number) : Promise<ThingCameraResponse<void>>;
getMute() : number;

Parameters

Parameter Type Description
mute number
  • 0: Unmute
  • 1: Mute

Return value

  • Promise<ThingCameraResponse<void>>

  • number: Returns the current mute status.

Example

if (this.cameraP2P !== undefined) {
            IPCLog.d(this.logTag, "Mute");

            this.cameraP2P.setMute(1).then((result) => {
              if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
                IPCLog.d(this.logTag, "Muted successfully");
              } else {
                IPCLog.d(this.logTag, "Failed to mute" + result.errorCodeNumber);
              }
            });
          } else {
            IPCLog.d(this.logTag, "Failed to mute, this.cameraP2P === undefined");
          }

if (this.cameraP2P !== undefined) {
            this.cameraP2P.getMute()
          } else {
            IPCLog.d(this.logTag, "Failed to get the mute status, this.cameraP2P === undefined");
          }

requestCameraRtcConfig

Functional description

Requests the necessary RTC configuration information for camera P2P connection, such as password, token, and server address.

Function signature

requestCameraRtcConfig(devId: string): Promise<ThingCameraResponse<ThingCameraRtcConfig>>;

Parameters

Parameter Type Description
devId string The device ID.

ThingCameraRtcConfig structure

Parameter Type Description
devId string The device ID.
password string The password used for connection.
skill string The description of device capabilities.
p2pId string The unique identifier for the P2P connection.
p2pType number The underlying transport protocol type.
p2pSpecifiedType number The connection strategy.
p2pConfig string The configuration of the P2P server.
sessionTid string The session tracing ID.
vedioClaritys collections.Array The list of supported definitions.
virtualCameraUrl string The URL of the virtual camera.
virtualCameraEncryptKey string The key for the virtual camera.
vedioClarity number The video definition. Default value: 4.
audioAttributes ThingCameraConfigAudioAttributesBean The audio hardware capabilities.

Return value

Promise<ThingCameraResponse<ThingCameraRtcConfig>>: A response object containing the connection configuration.

Example

const configResult = await camera.requestCameraRtcConfig("device123");
if (configResult.errorCodeNumber === 0 && configResult.data) {
  console.log("Obtained configuration:", configResult.data);
  // Used to call createDevice
}

createDevice

Functional description

Creates a camera device instance based on the RTC configuration, initializing the underlying P2P object.

Function signature

createDevice(cameraConfig: ThingCameraRtcConfig): Promise<ThingCameraResponse<void>>;

Parameters

Parameter Type Description
cameraConfig ThingCameraRtcConfig The obtained configuration object.

Return value

Promise<ThingCameraResponse<void>>

Example

// Manual connection process
const configResult = await camera.requestCameraRtcConfig("device123");
if (configResult.data) {
  const createResult = await camera.createDevice(configResult.data);
  if (createResult.errorCodeNumber === 0) {
    // 设Device created successfully, you can call connect()
    await camera.connect();
  }
}

registerP2PCameraListener

Functional description

Registers a P2P camera event listener to receive events such as connection status, video frames, and audio data.

Function signature

registerP2PCameraListener(listener: OnP2PCameraListener): void;

Parameters

Parameter Type Description
listener OnP2PCameraListener The event listener object.

Example

const listener: OnP2PCameraListener = {
  onSessionStatusChanged: (sessionId, status, camera) => {
    console.log(`Connection status changes: ${sessionId}, status: ${status}`);
  },
  onReceiveFrameYUVData: (sessionId, y, u, v, frameInfo, camera) => {
    // Defines video frame processing (usually handled automatically by XComponent)
    console.log(`Received a video frame: ${frameInfo.nWidth}x${frameInfo.nHeight}`);
  },
  onReceiveAudioBufferData: (sessionId, pcm, audioInfo, camera) => {
    // Handle audio data
    console.log("Received audio data");
  }
};

camera.registerP2PCameraListener(listener);

unregisterP2PCameraListener

Functional description

Removes a registered event listener.

Function signature

unregisterP2PCameraListener(listener: OnP2PCameraListener): void;

Parameters

Parameter Type Description
listener OnP2PCameraListener The event listener object.

It is recommended to remove the listener promptly when the page is destroyed or when it is no longer needed to prevent memory leaks.

Example

// Remove the listener (for example, when the page is destroyed)
camera.unregisterP2PCameraListener(listener);

snapshot

Functional description

Takes a screenshot of the current video frame and saves it as a local image file.

Function signature

snapshot(snapshotParams: ThingCameraSnapshotParams): Promise<ThingCameraResponse<string>>;

Parameters

Parameter Type Description
snapshotParams ThingCameraSnapshotParams The file storage information.

ThingCameraSnapshotParams structure

Parameter Type Description
dir string The path where the file will be saved.
fileName string The file name.
rotate number The angle of rotation.
saveToSysTem boolean Specifies whether to save the file to the system’s photo album. Permission is required.

Return value

Promise<ThingCameraResponse<string>>: Returns the complete file path (in the Data field).

You need to call this function while in video preview mode, and make sure the directory has write permissions.

Example

const snapshotResult = await camera.snapshot({
  dir: "/sdcard/Pictures",
  fileName: "camera_20231001_120000",
  rotate: 0
});

if (snapshotResult.errorCodeNumber === 0) {
  console.log("Saved the snapshot to:", snapshotResult.data);
  // Result: /sdcard/Pictures/camera_20231001_120000.jpg
}

getVideoClarity

Functional description

Gets the current video definition settings.

Function signature

getVideoClarity(): Promise<ThingCameraResponse<number>>;

Return value

Promise<ThingCameraResponse<number>>: The current video definition value.

Example

const clarityResult = await camera.getVideoClarity();
if (clarityResult.errorCodeNumber === 0) {
  const currentClarity = clarityResult.data;
  console.log("Current video definition:", currentClarity); // For example, 4 (high definition)
}

setVideoClarity

Functional description

Sets the video definition.

Function signature

setVideoClarity(clarity: number): Promise<ThingCameraResponse<number>>;

Parameters

Parameter Type Description
clarity number The video definition. Valid values:
  • 2: Standard definition
  • 4: High definition
  • 8: Ultra high definition

Return value

Promise<ThingCameraResponse<number>>: The set video definition.

Example

// Set to high definition
const setResult = await camera.setVideoClarity(4);
if (setResult.errorCodeNumber === 0) {
  console.log("Set the definition to:", setResult.data);
}

getIsEchoData

Functional description

Gets the current status of audio echo data forwarding.

Function signature

getIsEchoData(): boolean;

Return value

  • true: Audio data is forwarded to the listener for processing.
  • false: Audio data is sent directly to the device (default).

Example

const isEcho = camera.getIsEchoData();
console.log("Echo mode:", isEcho ? "Transparent" : "Direct");

setIsEchoData

Functional description

Sets the processing mode of audio echo data.

Function signature

setIsEchoData(echoData: boolean): void;

Parameters

Parameter Type Description
echoData boolean
  • true: Audio data is forwarded to OnP2PCameraListener.onReceiveSpeakerEchoData.
  • false: Audio data is sent directly to the camera device.
  • false (Default): For standard talk scenarios, audio is transmitted directly.
  • true: For scenarios requiring pre-processing, such as echo cancellation, noise suppression, and audio effect addition.

Example

// Enable echo data forwarding (for custom audio processing)
camera.setIsEchoData(true);

// Register a listener to handle audio data
const listener: OnP2PCameraListener = {
  onReceiveSpeakerEchoData: (audioBuffer, sampleRate) => {
    // Customize audio processing logic, such as noise reduction and sound effects
    console.log(`Audio data: ${audioBuffer.byteLength}  bytes, sampling rate: ${sampleRate}`);
    // After processing, optionally send the data to the device
  }
};
camera.registerP2PCameraListener(listener);

supportLowPower

Functional description

Checks whether the device supports low power wake-up mode (e.g., for battery-powered devices).

Function signature

supportLowPower(): boolean;

Return value

  • true: The device supports low power wake-up.
  • false: The device does not support low power wake-up.

Example

if (cameraP2P.supportLowPower()) {  console.log("The device supports low power mode");}

startVideoTalk

Functional description

Starts the video talk functionality, establishing a video call connection.

Function signature

startVideoTalk(callback: ThingBaseCallback): number;

Parameters

Parameter Type Description
callback ThingBaseCallback The callback.

Return value

number: The request ID, used for identifying subsequent operations.

  • The device must support video talk functionality.
  • After a successful call, it must be used in conjunction with startVideoCapture and startSendVideoTalkData.

Example

const requestId = cameraP2P.startVideoTalk({
  onResponse: (reason: string, errCode: number) => {
    if (errCode >= 0) {
      console.log("Started a video talk successfully");
      // Start video capture and transmission
      cameraP2P.startVideoCapture(640, 480, 20);
      cameraP2P.startSendVideoTalkData(requestId);
    } else {
      console.log("Failed to start a video talk");
    }
    return 0;
  }});

pauseVideoTalk

Functional description

Pauses a video talk.

Function signature

pauseVideoTalk(callback: ThingBaseCallback): number;

Parameters

Parameter Type Description
callback ThingBaseCallback The callback.

Return value

number: The operation result code.

This can only be called when the video talk has already started.

Example

cameraP2P.pauseVideoTalk({
  onResponse: (reason: string, errCode: number) => {
    if (errCode >= 0) {
      console.log("Paused the video talk successfully");
    }                                                                 
    return 0;
  }
});

resumeVideoTalk

Functional description

Resumes a video talk.

Function signature

resumeVideoTalk(callback: ThingBaseCallback): number;

Parameters

Parameter Type Description
callback ThingBaseCallback The callback.

Return value

number: The request ID.

This can only be called when the video talk has already paused.

Example

const requestId = cameraP2P.resumeVideoTalk({
  onResponse: (reason: string, errCode: number) => {
    if (errCode >= 0) {
      console.log("Resumed the video talk successfully");
    }
    return 0;                                                                                      
  }
});

stopVideoTalk

Functional description

Stops a video talk.

Function signature

stopVideoTalk(): number;

Return value

number: The operation result code.

This will simultaneously stop video capture and data transmission.

Example

const result = cameraP2P.stopVideoTalk();
if (result >= 0) {
  console.log("Stopped the video talk successfully");
}

startVideoCapture

Functional description

Starts video capture.

Function signature

startVideoCapture(width: number, height: number, frameRate: number): number;

Parameters

Parameter Type Description
width number The width of the video frame.
height number The height of the video frame.
frameRate number The frame rate, ranging from 15 to 30. Default value: 20.

Return value

number: The operation result code.

This must be called after a video talk has started.

Example

const result = cameraP2P.startVideoCapture(640, 480, 20);
if (result >= 0) {
  console.log("Started video capture successfully");
}

stopVideoCapture

Functional description

Stops video capture.

Function signature

stopVideoCapture(): number;

Return value

number: The operation result code.

Video data transmission will stop automatically.

Example

const result = cameraP2P.stopVideoCapture();
if (result >= 0) {
  console.log("Stopped video capture successfully");
}

switchCamera

Functional description

Switches between cameras (front/rear camera toggle).

Function signature

switchCamera(): number;

Return value

number: The operation result code.

The device must support multiple cameras.

Example

const result = cameraP2P.switchCamera();
if (result >= 0) {
  console.log("Switched between cameras successfully");
}

startSendVideoTalkData

Functional description

Starts video encoding and sends video data to the device.

Function signature

startSendVideoTalkData(requestId: number): number;

Parameters

Parameter Type Description
requestId number The request ID of the video talk session.

Return value

number: The operation result code.

This must be called after a video capture has started.

Example

const result = cameraP2P.startSendVideoTalkData(requestId);
if (result >= 0) {
  console.log("Started video data transmission successfully");
}

stopSendVideoTalkData

Functional description

Stops video encoding and video data transmission.

Function signature

stopSendVideoTalkData(): number;

Return value

number: The operation result code.

The video capture will stop automatically.

Example

const result = cameraP2P.stopSendVideoTalkData();
if (result >= 0) {
  console.log("Stopped video data transmission successfully");
}

enableAudioEffect

Functional description

Enables or disables audio effects.

Function signature

enableAudioEffect(enable: boolean): number;

Parameters

Parameter Type Description
enable boolean
  • true: enable
  • false: disable

Return value

number: The operation result code.

This needs to be set before the audio talk starts.

Example

const result = cameraP2P.enableAudioEffect(true);
if (result >= 0) {
  console.log("Enabled audio effects successfully");
}

setAudioEffectParameters

Functional description

Sets audio effect parameters.

Function signature

setAudioEffectParameters(  robotizationSupported: boolean,  pitch: number,   time_scale: number,  normal_amp_scale: number,  robot_amp_scale: number): number;

Parameters

Parameter Type Description
robotizationSupported boolean Specifies whether robot voice effect is supported.
pitch number The pitch.
time_scale number The time scaling. Currently, only 1.0 is available.
normal_amp_scale number The normal voice volume scaling.
robot_amp_scale number The robot voice volume scaling.

Return value

number: The operation result code.

This must be set after audio effects are enabled.

Example

const result = cameraP2P.setAudioEffectParameters(true, 1.5, 1.0, 1.0, 1.2);
if (result >= 0) {
  console.log("Set audio effects parameters successfully.");
}

setDeviceFeatures

Functional description

Set device features.

Function signature

setDeviceFeatures(jsonFeatures: string): number;

Parameters

Parameter Type Description
jsonFeatures string Device features in JSON string.

Return value

number: The operation result code.

The JSON format must comply with device specifications.

Example

const features = {
  "video_quality": "high",
  "audio_format": "pcm"
};
const result = cameraP2P.setDeviceFeatures(JSON.stringify(features));
if (result >= 0) {
  console.log("Set device features successfully");
}

setVideoSplitInfo

Functional description

Sets video split information.

Function signature

setVideoSplitInfo(json: string): number;

Parameters

Parameter Type Description
json string The video split information in JSON string.

Return value

number: The operation result code.

This is used for video split display of multi-lens cameras.

Example

const splitInfo = {
  "split_type": "quad",
  "channels": 4
};
const result = cameraP2P.setVideoSplitInfo(JSON.stringify(splitInfo));
if (result >= 0) {
  console.log("Set video split info successfully");
}

startPlayBackDownload

Functional description

Starts to download playback videos.

Function signature

startPlayBackDownload(
  startTime: number,  stopTime: number,
  folderPath: string,  mp4FileName: string,
  thumbFileName: string,
  rotation: ThingCameraConstants.Rotation,
  version: number,
  callback: ThingProgressiveCallback): number;

Parameters

Parameter Type Description
startTime number The start timestamp.
stopTime number The end timestamp.
folderPath string The path where the file will be saved.
mp4FileName string The MP4 file name.
thumbFileName string The thumbnail file name.
rotation ThingCameraConstants.Rotation The angle of rotation.
version number The version number.
callback ThingProgressiveCallback The callback for the progress.

Return value

number: The operation result code.

Make sure the folder path has write permissions.

Example

const result = cameraP2P.startPlayBackDownload(
  1620000000,
  1620003600,
  "/sdcard/Download",
  "playback.mp4",
  "thumb.jpg",
  ThingCameraConstants.Rotation.ROTATION_0,
  1,{
    onResponse: (reason: string, errCode: number) => {
      console.log("Download response:", reason);
      return 0;
    },
    onProgress: (progress: number) => {
      console.log("Download progress:", progress + "%");
    }
  }
);

stopPlayBackDownload

Functional description

Stops downloading playback videos.

Function signature

stopPlayBackDownload(callback: ThingBaseCallback): number;

Parameters

Parameter Type Description
callback ThingBaseCallback The callback.

Return value

number: The operation result code.

Only ongoing download tasks can be stopped.

Example

const result = cameraP2P.stopPlayBackDownload({
  onResponse: (reason: string, errCode: number) => {
    if (errCode >= 0) {
      console.log("Stopped download successfully");
    }
    return 0;
  }
});

deletePlaybackDataByDay

Functional description

Deletes playback data by day.

Function signature

deletePlaybackDataByDay(day: string, callback: ThingFinishableCallback): number;

Parameters

Parameter Type Description
day string The date, in the format YYYYMMDD.
callback ThingFinishableCallback The callback.

Return value

number: The operation result code.

Deletion is irreversible. Proceed with caution.

Example

const result = cameraP2P.deletePlaybackDataByDay("20231201", {
  onFinished: (data: string, errCode: number) => {
    if (errCode >= 0) {
      console.log("Deleted");
    }
  },
  onResponse: (reason: string, errCode: number) => {
    return 0;
  }
});

deletePlaybackDataByFragments

Functional description

Deletes playback data by video clip.

Function signature

deletePlaybackDataByFragments(fragmentJson: string, callback: ThingFinishableCallback): number;

Parameters

Parameter Type Description
fragmentJson string The clip information in the JSON format.
callback ThingFinishableCallback The callback.

Return value

number: The operation result code.

The JSON format needs to include information about the clips to be deleted.

Example

const fragments = {
  "fragments": [
    {"startTime": 1620000000, "endTime": 1620003600}
  ]
};
const result = cameraP2P.deletePlaybackDataByFragments(JSON.stringify(fragments), {
  onFinished: (data: string, errCode: number) => {
    if (errCode >= 0) {
      console.log("Deleted the fragment");
    }
  }
});

startPreviewWithClarity

Functional description

Starts the preview with the specified definition.

Function signature

startPreviewWithClarity(
  clarity: ThingCameraConstants.VideoClarityMode,
  callback: ThingCameraCallback): Promise<ThingCameraResponse<void>>;

Parameters

Parameter Type Description
clarity ThingCameraConstants.VideoClarityMode The video definition mode.
callback ThingCameraCallback The callback.

Return value

Promise<ThingCameraResponse<void>>: The result of the asynchronous operation.

You can specify the video definition before previewing, avoiding the need to switch from the default one later.

Example

const result = await cameraP2P.startPreviewWithClarity(
  ThingCameraConstants.VideoClarityMode.THING_CLARITY_HD,  {
    onResponse: (reason: string, errCode: number) => {
      if (errCode >= 0) {
        console.log("Started high-definition preview successfully");
      }
      return 0;
    }
  }
);

setPlayBackSpeed

Functional description

Sets the playback speed of the video, used to control effects such as fast-forward and slow-motion during playback.

Function signature

setPlayBackSpeed(speed: number): Promise<ThingCameraResponse<void>>;

Parameters

Parameter Type Description
speed number The playback speed.

Return value

  • Promise<ThingCameraResponse<void>>: The result of the asynchronous operation.
  • errorCodeNumber: The error code.
  • ThingCameraErrorCode.SUCCESS: Set successfully.
  • ThingCameraErrorCode.CAMERA_OBJECT_NULL: The camera object is null.

For more information, see ThingCameraErrorCode.

  • This must be called after playback has started. Otherwise, the setting is invalid.
  • The speed range might vary depending on the device, so it is recommended to use a speed within the commonly used range.
  • After the speed is set, both the video playback and audio will adjust their playback rate accordingly.
  • Reverse playback functionality requires device support.

Example

// Set 2x fast-forward
const result = await cameraP2P.setPlayBackSpeed(2.0);
if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
  console.log("Playback speed set successfully: 2x speed");
} else {
  console.log("Failed to set playback speed, error code: " + result.errorCodeNumber);
}

// Set 0.5x slow motion
const slowResult = await cameraP2P.setPlayBackSpeed(0.5);
if (slowResult.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
  console.log("Playback speed set successfully: 0.5x slow motion");
}

// Set reverse playback at normal speed
const reverseResult = await cameraP2P.setPlayBackSpeed(-1.0);
if (reverseResult.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
  console.log("Playback speed set successfully: Reverse playback at normal speed");
}

Live streaming

Connect and start streaming

IPCLog.d(this.logTag, 'ipc connect start')

if (TSmartUser.getUid() !== undefined) {
    this.cameraP2P.connectWrapper().then((result) => {
        if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
            IPCLog.d(this.logTag, 'ipc connect success')
            let previewCallBack: ThingCameraCallback = {
                    onResponse: (reason: string, errCode: number) => {
                      if (errCode >= 0) {
                        IPCLog.d(this.logTag, 'ipc preview success')
                      } else {
                        IPCLog.e(this.logTag, 'ipc preview fail')
                      }
                      return 0;
                    }
                  }
            this.cameraP2P.startPreview(previewCallBack).then((result) => {
                    if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
                      IPCLog.d(this.logTag, 'ipc preview return success')
                    } else {
                      IPCLog.e(this.logTag, 'ipc preview fail')
                    }
                  }).catch((e: TSmartAtopRequestError) => {
                    IPCLog.e(this.logTag, 'ipc preview fail' + e)
                  });
                } else {
                  IPCLog.e(this.logTag, 'ipc connect fail')
                }
              }).catch((e: TSmartAtopRequestError) => {
                IPCLog.e(this.logTag, 'ipc connect fail' + e)
              })
            } else {
              IPCLog.e(this.logTag, 'uid is undefined')
            }
    IPCLog.d(this.logTag, 'ipc connect end')

Disconnect the live streaming

IPCLog.d(this.logTag, 'ipc disconnect start')
    let stopPreviewCallBack: ThingCameraCallback = {
              onResponse(reason: string, errCode: number): number {
                IPCLog.d(this.logTag, 'ipc disconnect callback')
                return 0;
              }
    };
    this.cameraP2P.stopPreview(stopPreviewCallBack).then((result) => {
        if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
            IPCLog.d(this.logTag, 'ipc stopPreview return success')
        } else {
                IPCLog.e(this.logTag, 'ipc stopPreview fail')
        }
    }).catch((e: TSmartAtopRequestError) => {
        IPCLog.e(this.logTag, 'ipc preview fail' + e)
    });

    this.cameraP2P.disconnect(true).then((result) => {
        if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
            IPCLog.d(this.logTag, 'ipc disconnect return success')
        } else {
            IPCLog.e(this.logTag, 'ipc disconnect fail')
        }
    }).catch((e: TSmartAtopRequestError) => {
        IPCLog.e(this.logTag, 'ipc preview fail' + e)
    });

SD card-stored video playback

Query SD card playback clip dates by month

let connectResult = await this.cameraP2P.connectWrapper();

          if (connectResult.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
            IPCLog.d(this.logTag, "Connected successfully");
            this.cameraP2P.queryRecordDaysByMonth(3, 2025).then((result) => {
              if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS && result.data !== undefined) {
                let playbackDays = JSON.parse(result.data) as Record<string, Array<string>>;
                IPCLog.d(this.logTag, "queryRecordDaysByMonth succeeded" + playbackDays["DataDays"].toString());
              } else {
                IPCLog.e(this.logTag, "queryRecordDaysByMonth failed" + result.errorCodeNumber);
              }
            })
          } else {
            IPCLog.d(this.logTag, "Failed to connect");
          }

Query video clips recorded on the SD card

let connectResult = await this.cameraP2P.connectWrapper();

          if (connectResult.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
            IPCLog.d(this.logTag, "Connected successfully");
            this.cameraP2P.queryRecordTimeSliceByDay(26, 3, 2025).then((result) => {
              if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS && result.data !== undefined) {
                IPCLog.d(this.logTag, "queryRecordTimeSliceByDay succeeded");
                let playbackBean = JSON.parse(result.data)  as ThingCameraPlayBackBean;
                // let playbackBean = ArkTSUtils.ASON.parse(json) as ThingCameraPlayBackBean;
                IPCLog.d(this.logTag, "queryRecordTimeSliceByDay succeeded" + playbackBean.items?.length);
                if (playbackBean.items !== undefined && playbackBean.items?.length > 0) {
                  this.mFirstThingCameraTimePieceBean = playbackBean.items[0];
                }
              } else {
                IPCLog.e(this.logTag, "queryRecordTimeSliceByDay failed" + result.errorCodeNumber);
              }
            })
          } else {
            IPCLog.d(this.logTag, "Failed to connect");
          }

Play back videos from the SD card

if (this.mFirstThingCameraTimePieceBean !== undefined) {
            IPCLog.d(this.logTag, "Play back videos from SD card");
            let startTime: number = this.mFirstThingCameraTimePieceBean.startTime ?? 0;
            let endTime = this.mFirstThingCameraTimePieceBean.endTime ?? 0;
            let playTime = startTime;
            let callback: ThingCameraFinishableCallback<string, string> = {
              onResponse: (reason: string, errCode: number): void => {
                IPCLog.d(this.logTag, "Play back videos from SD card onResponse " + errCode);
              },
              onFinished: (data: string, errCode: number): void => {
                IPCLog.d(this.logTag, "Play back videos from SD card onFinished " + errCode);
              },
              onEvent: (eventType: number, info1: number, info2: number, errInfo: string): void => {
                IPCLog.d(this.logTag, "Play back videos from SD card onEvent " + info1);
              }
            }
            this.cameraP2P.startPlayBack(startTime, endTime, playTime, callback);
          } else {
            IPCLog.d(this.logTag, "Failed to play back videos from SD card, no clip information available");
          }

Pause playback of videos from SD card

if (this.cameraP2P !== undefined) {
            IPCLog.d(this.logTag, "Pause playback of videos from SD card");
            this.cameraP2P.pausePlayBack().then((result) => {
              if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS)
               {
                IPCLog.d(this.logTag, "Paused playback of videos from SD card successfully");
              } else {
                IPCLog.d(this.logTag, "Failed to pause playback of videos from SD card");
              }
            });
          } else {
            IPCLog.d(this.logTag, "Failed to pause playback of videos from SD card, this.cameraP2P === undefined");
          }

Resume playback of videos from SD card

if (this.cameraP2P !== undefined) {
            IPCLog.d(this.logTag, "Resume playback of videos from SD card");
            this.cameraP2P.resumePlayBack().then((result) => {
              if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
                IPCLog.d(this.logTag, "Resumed playback of videos from SD card successfully");
              } else {
                IPCLog.d(this.logTag, "Failed to resume playback of videos from SD card");
              }
            });
          } else {
            IPCLog.d(this.logTag, "Failed to resume playback of videos from SD card, this.cameraP2P === undefined");
          }

Stop playback of videos from SD card

if (this.cameraP2P !== undefined) {
            IPCLog.d(this.logTag, "Stop playback of videos from SD card");

            this.cameraP2P.stopPlayBack().then((result) => {
              if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
                IPCLog.d(this.logTag, "Stopped playback of videos from SD card successfully");
              } else {
                IPCLog.d(this.logTag, "Failed to stop playback of videos from SD card" + result.errorCodeNumber);
              }
            });
          } else {
            IPCLog.d(this.logTag, "Failed to stop playback of videos from SD card, this.cameraP2P === undefined");
          }

Update mute status

if (this.cameraP2P !== undefined) {
            IPCLog.d(this.logTag, "Mute");

            this.cameraP2P.setMute(1).then((result) => {
              if (result.errorCodeNumber === ThingCameraErrorCode.SUCCESS) {
                IPCLog.d(this.logTag, "Muted successful");
              } else {
                IPCLog.d(this.logTag, "Failed to mute" + result.errorCodeNumber);
              }
            });
          } else {
            IPCLog.d(this.logTag, "Failed to mute, this.cameraP2P === undefined");
          }

Get mute status

if (this.cameraP2P !== undefined) {
            this.cameraP2P.getMute()
          } else {
            IPCLog.d(this.logTag, "Failed to get mute status, this.cameraP2P === undefined");
          }