### Complete End-to-End Dahua API Example in C# Source: https://context7.com/vov4uk/dahua.api/llms.txt A full application workflow including initialization, login, querying device info, listing and downloading recordings, and cleanup. This example requires proper credentials and network access to the device. Ensure the file paths for saving snapshots and recordings exist. ```csharp using Dahua.Api; using System; using System.IO; using System.Linq; using System.Threading.Tasks; DahuaApi.Init(); try { using var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password"); // Device info Console.WriteLine($"Machine: {session.ConfigService.GetMachineName()}"); Console.WriteLine($"Serial: {session.ConfigService.GetDeviceSerialNumber()}"); Console.WriteLine($"Type: {session.ConfigService.GetDeviceType()}"); Console.WriteLine($"FW: {session.ConfigService.GetSoftwareVersion()}"); Console.WriteLine($"Time: {session.ConfigService.GetTime()}"); // Sync device clock session.ConfigService.SetTime(DateTime.Now); // Channels Console.WriteLine("Channels: " + string.Join(", ", session.AllChannels.Select(c => $"{c.Id}:{c.Name}"))); // RTSP URLs string rtsp = session.GetRtspUrl(1, DahuaStreamType.Main, "admin", "password"); Console.WriteLine($"Stream: {rtsp}"); // Snapshot byte[] snap = session.PictureService.ManualSnap(1); await File.WriteAllBytesAsync(@"C:\snap.jpg", snap); // Download first recording of today var videos = session.VideoService.FindFiles(DateTime.Today, DateTime.Now); Console.WriteLine($"Recordings today: {videos.Count}"); if (videos.Any()) { var v = videos.First(); string dest = $@ ``` -------------------------------- ### Start Downloading a Recording - VideoService.StartDownloadFile Source: https://context7.com/vov4uk/dahua.api/llms.txt Initiates an asynchronous download of a recorded file. The destination path must end in .mp4. Returns a download handle on success, or 0/negative on failure. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { var files = session.VideoService.FindFiles(DateTime.Today, DateTime.Now); var video = files.First(); string dest = $ প্রাকৃতিক{video.Date:yyyyMMdd_HHmmss}_{video.Duration}.mp4"; long downloadId = session.VideoService.StartDownloadFile(video, dest); if (downloadId > 0) Console.WriteLine($"Download started: handle={downloadId}, destination={dest}"); else Console.WriteLine("Failed to start download."); } ``` -------------------------------- ### ConfigService Operations Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Provides methods to get and set device configuration details. ```APIDOC ## ConfigService Operations ### Description Provides access to various device configuration settings. ### Methods #### Get Machine Name ```cs session.ConfigService.GetMachineName(); ``` #### Get Device Serial Number ```cs session.ConfigService.GetDeviceSerialNumber(); ``` #### Get Device Type ```cs session.ConfigService.GetDeviceType(); ``` #### Get Device Time ```cs session.ConfigService.GetTime(); ``` #### Set Device Time ```cs var currentTime = DateTime.Now; session.ConfigService.SetTime(currentTime); ``` ``` -------------------------------- ### Get and Set Device Time Source: https://context7.com/vov4uk/dahua.api/llms.txt Reads the current clock from the device or synchronizes the device clock to a provided DateTime value. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { // Read current device time DateTime deviceTime = session.ConfigService.GetTime(); Console.WriteLine($"Device time: {deviceTime}"); // e.g. 07/05/2024 14:32:01 // Sync device clock to local machine time session.ConfigService.SetTime(DateTime.Now); Console.WriteLine("Device time synchronized."); } ``` -------------------------------- ### Get Device Current Time Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Retrieves the current system time from the Dahua device. ```csharp session.ConfigService.GetTime(); ``` -------------------------------- ### Get Device Type Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Retrieves the type of the connected Dahua device. ```csharp session.ConfigService.GetDeviceType(); ``` -------------------------------- ### Get Device Machine Name Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Retrieves the machine name of the connected Dahua device. ```csharp session.ConfigService.GetMachineName(); ``` -------------------------------- ### Get Device Serial Number Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Retrieves the serial number of the connected Dahua device. ```csharp session.ConfigService.GetDeviceSerialNumber(); ``` -------------------------------- ### VideoService.StartDownloadFile Source: https://context7.com/vov4uk/dahua.api/llms.txt Initiates an asynchronous download of a recorded file to a local path. The path must end in .mp4 (the extension is appended automatically if missing). Returns a positive long download handle on success, or 0/negative on failure. ```APIDOC ## VideoService.StartDownloadFile — Begin Downloading a Recording `StartDownloadFile(remoteFile, destinationPath)` initiates an asynchronous download of a recorded file to a local path. The path must end in `.mp4` (the extension is appended automatically if missing). Returns a positive `long` download handle on success, or `0`/negative on failure. ### Request - **remoteFile**: The remote file to download. - **destinationPath**: The local path to save the downloaded file. ### Response - **long**: A positive download handle on success, or `0`/negative on failure. ### Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { var files = session.VideoService.FindFiles(DateTime.Today, DateTime.Now); var video = files.First(); string dest = $ירתC:\Recordings\{video.Date:yyyyMMdd_HHmmss}_{video.Duration}.mp4"; long downloadId = session.VideoService.StartDownloadFile(video, dest); if (downloadId > 0) Console.WriteLine($"Download started: handle={downloadId}, destination={dest}"); else Console.WriteLine("Failed to start download."); } ``` ``` -------------------------------- ### Initialize and Cleanup Dahua SDK Source: https://context7.com/vov4uk/dahua.api/llms.txt Call DahuaApi.Init() once at application startup to initialize the SDK. Ensure DahuaApi.Cleanup() is called at application shutdown to release resources. ```csharp DahuaApi.Init(); // ... use the SDK ... DahuaApi.Cleanup(); ``` -------------------------------- ### Retrieve Software Version Source: https://context7.com/vov4uk/dahua.api/llms.txt Returns the device's current firmware/software version string. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { string version = session.ConfigService.GetSoftwareVersion(); Console.WriteLine($"Firmware: {version}"); // e.g. "V4.001.0000001.0" } ``` -------------------------------- ### Using `using` / IDisposable Source: https://context7.com/vov4uk/dahua.api/llms.txt Demonstrates how to use the `IDisposable` interface implementation of `DahuaApi` to ensure sessions are automatically logged out and resources are cleaned up. ```APIDOC ## Using `using` / IDisposable `DahuaApi` implements `IDisposable`; calling `Dispose()` is equivalent to calling `Logout()`, making it safe to wrap the session in a `using` block. ```csharp DahuaApi.Init(); using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { Console.WriteLine(session.ConfigService.GetMachineName()); } // Logout() called automatically here DahuaApi.Cleanup(); ``` ``` -------------------------------- ### SDK Initialization and Cleanup Source: https://context7.com/vov4uk/dahua.api/llms.txt Initializes the Dahua NetSDK before any other operations and cleans up resources when the application exits. These are static methods that affect the global SDK state. ```APIDOC ## SDK Initialization and Cleanup `DahuaApi.Init()` must be called once before any other SDK operation; it initializes the underlying Dahua NetSDK. `DahuaApi.Cleanup()` releases all SDK resources and should be called when the application exits. These are static methods that operate globally across all sessions. ```csharp // One-time SDK initialization at application startup DahuaApi.Init(); // ... use the SDK ... // Release all native SDK resources at application shutdown DahuaApi.Cleanup(); ``` ``` -------------------------------- ### ConfigService.GetSoftwareVersion Source: https://context7.com/vov4uk/dahua.api/llms.txt Returns the device's current firmware/software version string. ```APIDOC ## ConfigService.GetSoftwareVersion Returns the device's current firmware/software version string. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { string version = session.ConfigService.GetSoftwareVersion(); Console.WriteLine($"Firmware: {version}"); // e.g. "V4.001.0000001.0" } ``` ### Response #### Success Response (200) - **softwareVersion** (string) - The firmware/software version of the device. ``` -------------------------------- ### VideoService - DownloadFile Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Initiates the download of a video file and provides progress updates. ```APIDOC ## VideoService.StartDownloadFile & GetDownloadPosition ### Description Starts the download of a specified video file to a local destination path and allows monitoring of the download progress. ### Method ```cs var downloadId = session.VideoService.StartDownloadFile(RemoteFile video, string destinationPath); var downloadProgress = session.VideoService.GetDownloadPosition(downloadId); ``` ### Parameters - **video** ([RemoteFile](https://github.com/vov4uk/Dahua.Api/blob/main/src/Dahua.Api/Data/RemoteFile.cs)) - The video file object to download. - **destinationPath** (string) - The local path where the file will be saved. - **downloadId** (long) - The unique identifier for the download operation. ### Returns - **StartDownloadFile**: `long` - The ID of the initiated download. - **GetDownloadPosition**: An object containing download progress details, including `downloadSize`, `totalSize`, and `success` status. ### Example ```cs // Assuming 'videos' is a collection of RemoteFile objects obtained from FindFiles foreach (var video in videos) { Console.WriteLine(video.Name); var name = $"{video.Date.ToString(DateFormat)}_{video.Duration}.mp4"; var destinationPath = Path.Combine(@"C:\Users\{Environment.UserName}\Desktop", name); var downloadId = session.VideoService.StartDownloadFile(video, destinationPath); if (downloadId > 0) { Console.WriteLine($"Downloading {destinationPath}"); do { await Task.Delay(5000); var downloadProgress = session.VideoService.GetDownloadPosition(downloadId); Console.WriteLine($"Downloading {downloadProgress} %"); if (downloadProgress.downloadSize == downloadProgress.totalSize) { session.VideoService.StopDownloadFile(downloadId); break; } else if (!downloadProgress.success) { throw new InvalidOperationException($"UpdateDownloadProgress failed, progress value = {downloadProgress}"); } } while (true); Console.WriteLine($"Downloaded {destinationPath}"); } } ``` ``` -------------------------------- ### Initialization Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Initializes the Dahua API. This should be called before any other API operations. ```APIDOC ## Initialization ### Description Initializes the Dahua API. This must be called before any other operations. ### Code ```cs DahuaApi.Init(); ``` ``` -------------------------------- ### Poll Download Progress - VideoService.GetDownloadPosition Source: https://context7.com/vov4uk/dahua.api/llms.txt Polls the progress of an ongoing download. Returns success status, total size, and downloaded size in KB. Continue polling until downloaded size equals total size. If success is false, an error occurred. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { var files = session.VideoService.FindFiles(DateTime.Today, DateTime.Now); var video = files.First(); string dest = $ naturais{video.Date:yyyyMMdd_HHmmss}.mp4"; long downloadId = session.VideoService.StartDownloadFile(video, dest); if (downloadId > 0) { while (true) { await Task.Delay(2000); var (success, totalSize, downloadSize) = session.VideoService.GetDownloadPosition(downloadId); if (!success) throw new InvalidOperationException("Download progress check failed."); int pct = totalSize > 0 ? (downloadSize * 100 / totalSize) : 0; Console.WriteLine($"Progress: {downloadSize}/{totalSize} KB ({pct}%)"); if (downloadSize == totalSize) { session.VideoService.StopDownloadFile(downloadId); Console.WriteLine($"Download complete: {dest}"); break; } } } } ``` -------------------------------- ### Initialize Dahua API Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Call this method before any other Dahua API operations. Ensure it's called once during application startup. ```csharp DahuaApi.Init(); ``` -------------------------------- ### Retrieve Device Type/Model Source: https://context7.com/vov4uk/dahua.api/llms.txt Returns the device type/model string (e.g., NVR model number or IP camera model). ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { string type = session.ConfigService.GetDeviceType(); Console.WriteLine($"Device type: {type}"); // e.g. "NVR4116-4KS2" } ``` -------------------------------- ### ConfigService.GetTime and SetTime Source: https://context7.com/vov4uk/dahua.api/llms.txt `GetTime()` reads the current clock from the device and returns it as a `DateTime`. `SetTime(dateTime)` synchronizes the device clock to the provided value. ```APIDOC ## ConfigService.GetTime and SetTime `GetTime()` reads the current clock from the device and returns it as a `DateTime`. `SetTime(dateTime)` synchronizes the device clock to the provided value. ### Parameters #### GetTime - None #### SetTime - **dateTime** (DateTime) - The desired date and time to set on the device. ### Request Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { // Read current device time DateTime deviceTime = session.ConfigService.GetTime(); Console.WriteLine($"Device time: {deviceTime}"); // e.g. 07/05/2024 14:32:01 // Sync device clock to local machine time session.ConfigService.SetTime(DateTime.Now); Console.WriteLine("Device time synchronized."); } ``` ### Response #### GetTime Success Response (200) - **deviceTime** (DateTime) - The current date and time on the device. #### SetTime Success Response (200) - **status** (string) - Indicates success of the time synchronization. ``` -------------------------------- ### Login to Dahua Device and Handle Disconnection Source: https://context7.com/vov4uk/dahua.api/llms.txt Use DahuaApi.Login() to authenticate with a device. The returned session provides access to device information and services. Subscribe to the Disconnected event for unexpected connection loss. Adjust CommandTimeout as needed. Always ensure session.Logout() or session.Dispose() is called. ```csharp DahuaApi.Init(); DahuaApi session = null; try { session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password"); Console.WriteLine($"Connected: {session.Connected}"); // true Console.WriteLine($"Host: {session.Host}"); // 192.168.1.63 Console.WriteLine($"UserId: {session.UserId}"); // e.g. 1 // Subscribe to unexpected disconnection session.Disconnected += (s, e) => Console.WriteLine("Device disconnected!"); // Adjust command timeout (default 5000 ms) session.CommandTimeout = 8000; } catch (DahuaApiException ex) { Console.WriteLine($"Login failed: {ex.ErrorMessage}"); // e.g. "Password is not correct" or "Network connection failed" } finally { session?.Logout(); DahuaApi.Cleanup(); } ``` -------------------------------- ### Build RTSP Stream URL Source: https://context7.com/vov4uk/dahua.api/llms.txt Constructs a fully-formed RTSP URL for live streaming. Ensure correct channel ID, stream type, and credentials are used. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { // Main stream on channel 1 string mainUrl = session.GetRtspUrl(1, DahuaStreamType.Main, "admin", "password"); Console.WriteLine(mainUrl); // rtsp://admin:password@192.168.1.63:554/cam/realmonitor?channel=1&subtype=1 // Sub stream on channel 2 (NVR) string subUrl = session.GetRtspUrl(2, DahuaStreamType.Sub, "admin", "password"); Console.WriteLine(subUrl); // rtsp://admin:password@192.168.1.63:554/cam/realmonitor?channel=2&subtype=2 } ``` -------------------------------- ### Find Videos on Default IP Channel Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Retrieves a list of video files recorded on the default IP channel within a specified date range. Requires the session object obtained after login. ```csharp var videos = session.VideoService.FindFiles(DateTime.Today, DateTime.Now); ``` -------------------------------- ### Channel Information Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Retrieves and prints a list of all available IP channels for an NVR. ```APIDOC ## Get All Channels ### Description Retrieves a list of all IP channels available on the NVR. For IP cameras, use `hikapi.DefaultIpChannel`. ### Method ```cs Console.WriteLine("Channel:" + string.Join(",", session.AllChannels.Select(t => $"Channel{t.Id}_{t.Name}"))); ``` ### Returns - A string representation of all channels, formatted as `ChannelID_ChannelName`. ``` -------------------------------- ### VideoService.GetDownloadPosition Source: https://context7.com/vov4uk/dahua.api/llms.txt Polls the progress of an ongoing file download. Returns a tuple indicating success, total size, and downloaded size in KB. This should be polled in a loop until the downloaded size equals the total size. ```APIDOC ## VideoService.GetDownloadPosition — Poll Download Progress `GetDownloadPosition(fileHandler)` returns a tuple `(bool success, int totalSize, int downloadSize)` where sizes are in KB. Poll this in a loop until `downloadSize == totalSize` to detect completion. If `success` is `false`, the download has encountered an error. ### Parameters - **fileHandler** (long): The handle of the download to poll. ### Response - **success** (bool): True if the progress check was successful, false otherwise. - **totalSize** (int): The total size of the file in KB. - **downloadSize** (int): The amount of data downloaded so far in KB. ### Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { var files = session.VideoService.FindFiles(DateTime.Today, DateTime.Now); var video = files.First(); string dest = $ירתC:\Recordings\{video.Date:yyyyMMdd_HHmmss}.mp4"; long downloadId = session.VideoService.StartDownloadFile(video, dest); if (downloadId > 0) { while (true) { await Task.Delay(2000); var (success, totalSize, downloadSize) = session.VideoService.GetDownloadPosition(downloadId); if (!success) throw new InvalidOperationException("Download progress check failed."); int pct = totalSize > 0 ? (downloadSize * 100 / totalSize) : 0; Console.WriteLine($"Progress: {downloadSize}/{totalSize} KB ({pct}%)"); if (downloadSize == totalSize) { session.VideoService.StopDownloadFile(downloadId); Console.WriteLine($"Download complete: {dest}"); break; } } } } ``` ``` -------------------------------- ### Handle DahuaApiException in C# Source: https://context7.com/vov4uk/dahua.api/llms.txt Demonstrates how to catch and process DahuaApiException, accessing the Message and ErrorMessage properties for detailed error information. Ensure DahuaApi.Init() is called before and DahuaApi.Cleanup() after the try-finally block. ```csharp DahuaApi.Init(); try { var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "wrongpassword"); } catch (DahuaApiException ex) { // ex.Message => SDK call expression string, e.g. "() => CLIENT_Login(...)" // ex.ErrorMessage => "Password is not correct" Console.WriteLine($"SDK error: {ex.ErrorMessage}"); Console.WriteLine(ex.ToString()); // includes both ErrorMessage and stack trace } finally { DahuaApi.Cleanup(); } ``` -------------------------------- ### Login Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Logs into the Dahua device and returns a session object for further operations. ```APIDOC ## Login ### Description Logs into the Dahua device using provided credentials and network details. Returns a session object that can be used for subsequent API calls. ### Method ```cs var session = DahuaApi.Login(string ipAddress, int port, string username, string password); ``` ### Parameters - **ipAddress** (string) - The IP address of the Dahua device. - **port** (int) - The port number for the Dahua device (default is 37777). - **username** (string) - The username for authentication. - **password** (string) - The password for authentication. ### Returns - [DahuaApi](https://github.com/vov4uk/Dahua.Api/blob/main/src/Dahua.Api/DahuaApi.cs) - A session object representing the authenticated connection. ``` -------------------------------- ### List All IP Channels on a Dahua Device Source: https://context7.com/vov4uk/dahua.api/llms.txt Access the session.AllChannels property after login to retrieve a collection of IpChannel objects. Each object contains the channel's ID and Name. This is useful for NVRs with multiple connected cameras. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { // Print all channel IDs and names foreach (var ch in session.AllChannels) { Console.WriteLine($"Channel {ch.Id}: {ch.Name}"); } // Output (NVR with 4 cameras): // Channel 1: // Channel 2: // Channel 3: // Channel 4: // For a single IP camera the default channel is always channel 1 int defaultChannel = session.AllChannels.First().Id; // 1 } ``` -------------------------------- ### Capture Snapshot to File - PictureService.SnapPictureToFile Source: https://context7.com/vov4uk/dahua.api/llms.txt Captures a snapshot on a specified channel and writes the JPEG directly to a file path. An overload exists to trigger the snapshot without saving to a specific file, relying on device-side handling. Both use quality level 6 and image size 2. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { // Write snapshot directly to a file path (avoids loading full image into memory) string outputPath = $ naturais{DateTime.Now:yyyyMMdd_HHmmss}.jpg"; session.PictureService.SnapPictureToFile(channelId: 1, fileName: outputPath); Console.WriteLine($"Snapshot saved to: {outputPath}"); // Trigger snapshot without specifying a local file (device-side save) session.PictureService.SnapPictureToFile(channelId: 1); Console.WriteLine("Snapshot triggered on device."); } ``` -------------------------------- ### GetRtspUrl Source: https://context7.com/vov4uk/dahua.api/llms.txt Constructs a fully-formed RTSP URL for live streaming using the device's configured RTSP port. Supports different stream types. ```APIDOC ## GetRtspUrl — Build RTSP Stream URL `session.GetRtspUrl(channelId, streamType, userName, password)` constructs a fully-formed RTSP URL for live streaming using the device's configured RTSP port. `DahuaStreamType` values are `Main` (1), `Sub` (2), `StreamType3` (3), and `StreamType4` (4). ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { // Main stream on channel 1 string mainUrl = session.GetRtspUrl(1, DahuaStreamType.Main, "admin", "password"); Console.WriteLine(mainUrl); // rtsp://admin:password@192.168.1.63:554/cam/realmonitor?channel=1&subtype=1 // Sub stream on channel 2 (NVR) string subUrl = session.GetRtspUrl(2, DahuaStreamType.Sub, "admin", "password"); Console.WriteLine(subUrl); // rtsp://admin:password@192.168.1.63:554/cam/realmonitor?channel=2&subtype=2 } ``` ### Response #### Success Response (200) - **rtspUrl** (string) - The generated RTSP URL. ``` -------------------------------- ### VideoService.StopDownloadFile Source: https://context7.com/vov4uk/dahua.api/llms.txt Signals the SDK to finalize or cancel a download identified by its handle. This must be called after a download completes or if it needs to be aborted early. ```APIDOC ## VideoService.StopDownloadFile — Finalize or Abort a Download `StopDownloadFile(fileHandler)` signals the SDK to finalize or cancel a download identified by its handle. Must always be called after a download completes or if the download needs to be aborted early. ### Parameters - **fileHandler** (long): The handle of the download to stop. ### Response - **bool**: True if the stop operation was successful, false otherwise. ### Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { var files = session.VideoService.FindFiles(DateTime.Today, DateTime.Now); long downloadId = session.VideoService.StartDownloadFile(files.First(), @"C:\Recordings\clip.mp4"); // Abort download early after 10 seconds await Task.Delay(10000); bool stopped = session.VideoService.StopDownloadFile(downloadId); Console.WriteLine(stopped ? "Download aborted." : "Stop call failed (already done?)."); } ``` ``` -------------------------------- ### Download Video File Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Initiates the download of a video file from the Dahua device. It includes progress monitoring and handles the download process until completion or failure. ```csharp foreach (var video in videos) { Console.WriteLine(video.Name); var name = $"{video.Date.ToString(DateFormat)}_{video.Duration}.mp4"; var destinationPath = Path.Combine(@$"C:\\Users\\{Environment.UserName}\\Desktop", name); var downloadId = session.VideoService.StartDownloadFile(video, destinationPath); if (downloadId > 0) { Console.WriteLine($"Downloading {destinationPath}"); do { await Task.Delay(5000); var downloadProgress = session.VideoService.GetDownloadPosition(downloadId); Console.WriteLine($"Downloading {downloadProgress} %"); if (downloadProgress.downloadSize == downloadProgress.totalSize) { session.VideoService.StopDownloadFile(downloadId); break; } else if (!downloadProgress.success) { throw new InvalidOperationException($"UpdateDownloadProgress failed, progress value = {downloadProgress}"); } } while (true); Console.WriteLine($"Downloaded {destinationPath}"); } } ``` -------------------------------- ### ConfigService.GetMachineName Source: https://context7.com/vov4uk/dahua.api/llms.txt Retrieves the user-defined name assigned to the device. Returns an empty string if no name is set. ```APIDOC ## ConfigService.GetMachineName Retrieves the user-defined name assigned to the device. Returns an empty string if no name is set. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { string name = session.ConfigService.GetMachineName(); Console.WriteLine($"Machine name: {name}"); // e.g. "BackyardNVR" } ``` ### Response #### Success Response (200) - **machineName** (string) - The user-defined name of the device, or an empty string if not set. ``` -------------------------------- ### PictureService.ManualSnap Source: https://context7.com/vov4uk/dahua.api/llms.txt Triggers an immediate snapshot on the specified channel and returns the JPEG image data as a byte array. This data can then be saved to disk or processed further. ```APIDOC ## PictureService.ManualSnap — Capture Snapshot as Byte Array `ManualSnap(channelId)` triggers an immediate snapshot on the specified channel and returns the JPEG image data as a `byte[]` (up to 1 MB). The raw bytes can be saved to disk, served over HTTP, or processed in memory. ### Parameters - **channelId** (int): The ID of the channel to capture the snapshot from. ### Response - **byte[]**: The JPEG image data of the snapshot. ### Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { // Capture snapshot from channel 1 byte[] jpegData = session.PictureService.ManualSnap(channelId: 1); Console.WriteLine($"Snapshot size: {jpegData.Length} bytes"); // Save to disk string path = $ירתC:\Snapshots\snap_{DateTime.Now:yyyyMMdd_HHmmss}.jpg"; await File.WriteAllBytesAsync(path, jpegData); Console.WriteLine($"Saved: {path}"); } ``` ``` -------------------------------- ### Find Videos on Specific IP Channel Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Retrieves a list of video files recorded on a specific IP channel within a specified date range. Requires the session object obtained after login. ```csharp int channel = 2; var videos = session.VideoService.FindFiles(DateTime.Today, DateTime.Now, channel); ``` -------------------------------- ### AllChannels — Listing IP Channels Source: https://context7.com/vov4uk/dahua.api/llms.txt Retrieves a collection of all available IP channels from the logged-in device. Each channel is represented by an `IpChannel` object containing its ID and Name. ```APIDOC ## AllChannels — Listing IP Channels After login, `session.AllChannels` returns an `IReadOnlyCollection` populated from the device's `NET_DEVICEINFO`. Each `IpChannel` has `Id` (1-based channel number) and `Name`. For a single IP camera, use `IpChannel` with `Id = 1`; for an NVR, iterate all channels to address each connected camera. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { // Print all channel IDs and names foreach (var ch in session.AllChannels) { Console.WriteLine($"Channel {ch.Id}: {ch.Name}"); } // Output (NVR with 4 cameras): // Channel 1: // Channel 2: // Channel 3: // Channel 4: // For a single IP camera the default channel is always channel 1 int defaultChannel = session.AllChannels.First().Id; // 1 } ``` ``` -------------------------------- ### ConfigService.GetDeviceType Source: https://context7.com/vov4uk/dahua.api/llms.txt Returns the device type/model string (e.g., NVR model number or IP camera model). ```APIDOC ## ConfigService.GetDeviceType Returns the device type/model string (e.g., NVR model number or IP camera model). ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { string type = session.ConfigService.GetDeviceType(); Console.WriteLine($"Device type: {type}"); // e.g. "NVR4116-4KS2" } ``` ### Response #### Success Response (200) - **deviceType** (string) - The model name or type of the device. ``` -------------------------------- ### ConfigService.GetDeviceSerialNumber Source: https://context7.com/vov4uk/dahua.api/llms.txt Returns the device's unique serial number string as reported by the hardware. ```APIDOC ## ConfigService.GetDeviceSerialNumber Returns the device's unique serial number string as reported by the hardware. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { string serial = session.ConfigService.GetDeviceSerialNumber(); Console.WriteLine($"Serial: {serial}"); // e.g. "4K0BF7APAZ94B3E" } ``` ### Response #### Success Response (200) - **serialNumber** (string) - The unique serial number of the device. ``` -------------------------------- ### Stop Download - VideoService.StopDownloadFile Source: https://context7.com/vov4uk/dahua.api/llms.txt Finalizes or cancels a download using its handle. This method should be called upon download completion or if the download needs to be aborted. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { var files = session.VideoService.FindFiles(DateTime.Today, DateTime.Now); long downloadId = session.VideoService.StartDownloadFile(files.First(), @"C:\Recordings\clip.mp4"); // Abort download early after 10 seconds await Task.Delay(10000); bool stopped = session.VideoService.StopDownloadFile(downloadId); Console.WriteLine(stopped ? "Download aborted." : "Stop call failed (already done?)."); } ``` -------------------------------- ### Retrieve Device Machine Name Source: https://context7.com/vov4uk/dahua.api/llms.txt Retrieves the user-defined name assigned to the device. Returns an empty string if no name is set. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { string name = session.ConfigService.GetMachineName(); Console.WriteLine($"Machine name: {name}"); // e.g. "BackyardNVR" } ``` -------------------------------- ### Login and Logout Source: https://context7.com/vov4uk/dahua.api/llms.txt Authenticates against a Dahua device using provided credentials and returns a session instance. The session can be used to interact with the device and must be logged out or disposed when no longer needed. ```APIDOC ## Login and Logout `DahuaApi.Login(host, port, username, password)` authenticates against a Dahua device and returns a `DahuaApi` session instance. The session exposes `Connected`, `UserId`, `Host`, `AllChannels`, and `CommandTimeout` properties. Calling `session.Logout()` or `session.Dispose()` terminates the authenticated session. The `Disconnected` event fires when the device drops the connection unexpectedly (not when `Logout()` is called explicitly). ```csharp DahuaApi.Init(); DahuaApi session = null; try { session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password"); Console.WriteLine($"Connected: {session.Connected}"); // true Console.WriteLine($"Host: {session.Host}"); // 192.168.1.63 Console.WriteLine($"UserId: {session.UserId}"); // e.g. 1 // Subscribe to unexpected disconnection session.Disconnected += (s, e) => Console.WriteLine("Device disconnected!"); // Adjust command timeout (default 5000 ms) session.CommandTimeout = 8000; } catch (DahuaApiException ex) { Console.WriteLine($"Login failed: {ex.ErrorMessage}"); // e.g. "Password is not correct" or "Network connection failed" } finally { session?.Logout(); DahuaApi.Cleanup(); } ``` ``` -------------------------------- ### Login to Dahua Device Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Establishes a session with a Dahua device using its IP address, port, username, and password. The returned session object is used for subsequent API calls. ```csharp var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "pass"); ``` -------------------------------- ### Capture Snapshot as Byte Array - PictureService.ManualSnap Source: https://context7.com/vov4uk/dahua.api/llms.txt Triggers an immediate snapshot on a specified channel and returns the JPEG image data as a byte array. The data can be saved to disk or processed in memory. Requires channelId. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { // Capture snapshot from channel 1 byte[] jpegData = session.PictureService.ManualSnap(channelId: 1); Console.WriteLine($"Snapshot size: {jpegData.Length} bytes"); // Save to disk string path = $ naturais{DateTime.Now:yyyyMMdd_HHmmss}.jpg"; await File.WriteAllBytesAsync(path, jpegData); Console.WriteLine($"Saved: {path}"); } ``` -------------------------------- ### Print IP Channel List Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Retrieves and prints a list of all available IP channels on the connected Dahua device. For IP cameras, use hikapi.DefaultIpChannel. ```csharp Console.WriteLine("Channel:" + string.Join(",", session.AllChannels.Select(t => $"Channel{t.Id}_{t.Name}"))); ``` -------------------------------- ### ConfigService.GetRtspPort Source: https://context7.com/vov4uk/dahua.api/llms.txt Returns the RTSP server port configured on the device (typically 554). This is used internally by `GetRtspUrl` but can also be queried directly. ```APIDOC ## ConfigService.GetRtspPort Returns the RTSP server port configured on the device (typically 554). This is used internally by `GetRtspUrl` but can also be queried directly. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { int rtspPort = session.ConfigService.GetRtspPort(); Console.WriteLine($"RTSP port: {rtspPort}"); // e.g. 554 } ``` ### Response #### Success Response (200) - **rtspPort** (integer) - The configured RTSP port number. ``` -------------------------------- ### Query Recorded Videos Source: https://context7.com/vov4uk/dahua.api/llms.txt Queries recorded video files within a specified time range. Supports querying the default channel or a specific NVR channel. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { // Query today's recordings on default channel var files = session.VideoService.FindFiles(DateTime.Today, DateTime.Now); Console.WriteLine($"Found {files.Count} recordings"); foreach (var f in files) { Console.WriteLine($" {f.Name} | Start: {f.Date} | Duration: {f.Duration}s | Size: {f.Size / 1024}KB"); } // Query a specific NVR channel (channel 2) over a date range var ch2Files = session.VideoService.FindFiles( new DateTime(2024, 7, 1), new DateTime(2024, 7, 2), channelId: 2 ); Console.WriteLine($"Channel 2 recordings: {ch2Files.Count}"); } ``` -------------------------------- ### VideoService - FindFiles Source: https://github.com/vov4uk/dahua.api/blob/main/README.md Finds video files within a specified date range. ```APIDOC ## VideoService.FindFiles ### Description Retrieves a list of video files recorded within a specified time range. This method can be used for the default IP channel or a specific one. ### Parameters - **startTime** (DateTime) - The start of the time range to search for videos. - **endTime** (DateTime) - The end of the time range to search for videos. - **channelId** (int, optional) - The ID of the specific IP channel to search. If not provided, the default IP channel is used. ### Returns - IReadOnlyCollection<[RemoteFile](https://github.com/vov4uk/Dahua.Api/blob/main/src/Dahua.Api/Data/RemoteFile.cs)> - A collection of `RemoteFile` objects representing the found video files. ### Examples #### Default IP Channel ```cs var videos = session.VideoService.FindFiles(DateTime.Today, DateTime.Now); ``` #### Specific IP Channel ```cs int channel = 2; var videos = session.VideoService.FindFiles(DateTime.Today, DateTime.Now, channel); ``` ``` -------------------------------- ### Retrieve Device Serial Number Source: https://context7.com/vov4uk/dahua.api/llms.txt Returns the device's unique serial number string as reported by the hardware. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { string serial = session.ConfigService.GetDeviceSerialNumber(); Console.WriteLine($"Serial: {serial}"); // e.g. "4K0BF7APAZ94B3E" } ``` -------------------------------- ### Retrieve Channel Name Source: https://context7.com/vov4uk/dahua.api/llms.txt Returns the configured display name of a specific channel by its 1-based channel ID. ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { foreach (var ch in session.AllChannels) { string chName = session.ConfigService.GetChannelName(ch.Id); Console.WriteLine($"Channel {ch.Id} name: {chName}"); // Channel 1 name: FrontDoor // Channel 2 name: Garage } } ``` -------------------------------- ### VideoService.FindFiles Source: https://context7.com/vov4uk/dahua.api/llms.txt Queries recorded video files within a specified time range. Supports querying all channels or a specific channel. ```APIDOC ## VideoService.FindFiles — Query Recorded Videos `FindFiles(startTime, endTime)` queries all recorded video files in a time range on the default channel (channel 0). The overload `FindFiles(startTime, endTime, channelId)` targets a specific channel on an NVR. Returns `IReadOnlyCollection`, where each file exposes `Name`, `Date` (start time), `Duration` (seconds), and `Size` (bytes). Files with `Duration == 0` are automatically filtered out. ### Parameters #### Path Parameters - None #### Query Parameters - **startTime** (DateTime) - The beginning of the time range to search for recordings. - **endTime** (DateTime) - The end of the time range to search for recordings. - **channelId** (integer, optional) - The specific channel ID to query. If omitted, queries the default channel (0). #### Request Body - None ### Request Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { // Query today's recordings on default channel var files = session.VideoService.FindFiles(DateTime.Today, DateTime.Now); Console.WriteLine($"Found {files.Count} recordings"); foreach (var f in files) { Console.WriteLine($" {f.Name} | Start: {f.Date} | Duration: {f.Duration}s | Size: {f.Size / 1024}KB"); } // Query a specific NVR channel (channel 2) over a date range var ch2Files = session.VideoService.FindFiles( new DateTime(2024, 7, 1), new DateTime(2024, 7, 2), channelId: 2 ); Console.WriteLine($"Channel 2 recordings: {ch2Files.Count}"); } ``` ### Response #### Success Response (200) - **recordedFiles** (IReadOnlyCollection) - A collection of remote file objects, each containing `Name`, `Date`, `Duration`, and `Size`. ``` -------------------------------- ### PictureService.SnapPictureToFile Source: https://context7.com/vov4uk/dahua.api/llms.txt Captures a snapshot on the specified channel and writes the JPEG directly to the given file path. An overload exists to trigger the snapshot without saving to a specific file. ```APIDOC ## PictureService.SnapPictureToFile — Capture Snapshot Directly to File `SnapPictureToFile(channelId, fileName)` captures a snapshot on the specified channel and writes the JPEG directly to the given file path. The overload `SnapPictureToFile(channelId)` (no file name) triggers the snapshot request without saving to a specific file (relies on device-side handling). Both methods use quality level 6, image size 2, in non-triggered mode. ### Parameters - **channelId** (int): The ID of the channel to capture the snapshot from. - **fileName** (string, optional): The path to save the snapshot file. If omitted, the snapshot is handled by the device. ### Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { // Write snapshot directly to a file path (avoids loading full image into memory) string outputPath = $ירתC:\Snapshots\channel1_{DateTime.Now:yyyyMMdd_HHmmss}.jpg"; session.PictureService.SnapPictureToFile(channelId: 1, fileName: outputPath); Console.WriteLine($"Snapshot saved to: {outputPath}"); // Trigger snapshot without specifying a local file (device-side save) session.PictureService.SnapPictureToFile(channelId: 1); Console.WriteLine("Snapshot triggered on device."); } ``` ``` -------------------------------- ### ConfigService.GetChannelName Source: https://context7.com/vov4uk/dahua.api/llms.txt Returns the configured display name of a specific channel by its 1-based channel ID. ```APIDOC ## ConfigService.GetChannelName Returns the configured display name of a specific channel by its 1-based channel ID. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```csharp using (var session = DahuaApi.Login("192.168.1.63", 37777, "admin", "password")) { foreach (var ch in session.AllChannels) { string chName = session.ConfigService.GetChannelName(ch.Id); Console.WriteLine($"Channel {ch.Id} name: {chName}"); // Channel 1 name: FrontDoor // Channel 2 name: Garage } } ``` ### Response #### Success Response (200) - **channelName** (string) - The display name of the specified channel. ```