14 KiB
source_files, generated_at, model, schema_version, sha256
| source_files | generated_at | model | schema_version | sha256 | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
2026-04-16T03:47:56.020895+00:00 | Qwen/Qwen3-Coder-Next-FP8 | 1 | 39cf8ff3a187bfe6 |
CANFDApiProxy Module Documentation
1. Purpose
This module provides a C# client-side API proxy for interacting with a remote CAN FD device’s RESTful HTTP/HTTPS API. It encapsulates low-level HTTP communication, request/response serialization, and error handling to expose a strongly-typed, asynchronous interface for retrieving and setting device configuration, status, and diagnostic data (e.g., CAN bus state, LEDs, serial number, file operations). It serves as the primary integration point for applications needing programmatic access to the device’s REST endpoints, abstracting away the underlying JSON/HTTP mechanics and enforcing consistent error handling via CanApiException.
2. Public Interface
CANFD (Singleton Class)
The main public entry point. Exposes asynchronous methods for GET and POST operations against device endpoints.
Public Methods
-
public static CANFD API { get; }
Gets the singleton instance of theCANFDclass. -
public async Task<UsbTreeMessage> GetUsbTree(string deviceHost, CancellationToken cancellationToken)
Retrieves USB tree topology from the device viaGET /usb-tree. -
public async Task<BatteryMessage> GetBattery(string deviceHost, CancellationToken cancellationToken)
Retrieves battery status viaGET /battery. -
public async Task<DiagnosticMessageRow[]> GetBIST(string deviceHost, CancellationToken cancellationToken)
Retrieves Built-In Self-Test (BIST) results viaPOST /diagnosticswith{"format":"csv"}; parses CSV response intoDiagnosticMessageRow[]. -
public async Task<CalibrationMessage> GetCalibrationDate(string deviceHost, CancellationToken cancellationToken)
Retrieves calibration date viaGET /calibration-date. -
public async Task<SerialMessage> GetSerial(string deviceHost, CancellationToken cancellationToken)
Retrieves device serial number viaGET /serial. -
public async Task<LEDsMessage> GetLEDs(string deviceHost, CancellationToken cancellationToken)
Retrieves LED status (color, state) for CAN1–CAN4 and device-level status flags (Status,Battery,Pwr,Sts) viaGET /leds. Internally deserializesCANInfoInternaland constructsLEDsMessage. -
public async Task<CANInfoMessage> GetCANInfo(string deviceHost, CancellationToken cancellationToken)
Retrieves CAN interface info (e.g., mode, bitrate) for CAN1–CAN4 viaGET /can-info. -
public async Task<CANStateMessage> GetCANState(string deviceHost, CancellationToken cancellationToken)
Retrieves CAN interface state (e.g., active, error-active) and last update timestamp for CAN1–CAN4 viaGET /can-state. -
public async Task<CANStatsMessage> GetCANStats(string deviceHost, CancellationToken cancellationToken)
Retrieves CAN interface statistics (STD/EXT frames, errors, overruns, bus load) for CAN1–CAN4 viaGET /can-stats. -
public async Task<CANConfigMessage> GetCANConfig(string deviceHost, CancellationToken cancellationToken)
Retrieves CAN interface configuration (bitrates, SJW, FD flags, included status) for CAN1–CAN4 andPipeviaGET /can-config. -
public async Task<DeviceInfoMessage> GetDeviceInfo(string deviceHost, CancellationToken cancellationToken)
Retrieves device hardware/software info viaGET /device-info. -
public async Task<NtpMessage> GetNtp(string deviceHost, CancellationToken cancellationToken)
Retrieves NTP configuration/status viaGET /ntp. -
public async Task<PowerMessage> GetPower(string deviceHost, CancellationToken cancellationToken)
Retrieves power state viaGET /power. -
public async Task<ServicesMessage> GetServices(string deviceHost, CancellationToken cancellationToken)
Retrieves enabled services viaGET /services. -
public async Task<NetworkMessage> GetNetwork(string deviceHost, CancellationToken cancellationToken)
Retrieves network configuration viaGET /network. -
public async Task<ClocksMessage> GetClocks(string deviceHost, CancellationToken cancellationToken)
Retrieves clock/time info viaGET /clocks. -
public async Task<EventPinMessage> GetEventPin(string deviceHost, CancellationToken cancellationToken)
Retrieves event pin configuration/status viaGET /event-pin. -
public async Task<RecordingMessage> GetRecording(string deviceHost, CancellationToken cancellationToken)
Retrieves recording status viaGET /recording. -
public async Task<UsbStatsMessage> GetUsbStats(string deviceHost, CancellationToken cancellationToken)
Retrieves USB statistics viaGET /usb-stats. -
public async Task<SerialMessage> SetSerial(string deviceHost, SerialRequest serialRequest, CancellationToken cancellationToken)
Sets device serial number viaPOST /serial. -
public async Task<PowerMessage> SetPowerOff(string deviceHost, CancellationToken cancellationToken)
Powers off device viaPOST /powerwith{"cmd":"off"}. -
public async Task<PowerMessage> SetPowerReboot(string deviceHost, CancellationToken cancellationToken)
Reboots device viaPOST /powerwith{"cmd":"reboot"}. -
public async Task<CANConfigMessage> SetCANConfig(string deviceHost, CANConfigRequest canConfigRequest, CancellationToken cancellationToken)
Configures CAN interface(s) viaPOST /can-config. -
public async Task<LEDsPostMessage> SetLEDs(string deviceHost, LedName led, LedCmd cmd, LedColor color, CancellationToken cancellationToken)
Controls LED viaPOST /ledswith{"led":"...", "cmd":"...", "color":"..."}. -
public async Task<ClocksMessage> SetClocks(string deviceHost, DateTime dateTime, CancellationToken cancellationToken)
Sets device clock viaPOST /clockswith{"cmd":"set", "time":"yyyy-MM-dd HH:mm:ss"}. -
public async Task<ClocksMessage> SyncClocks(string deviceHost, CancellationToken cancellationToken)
Syncs device clock viaPOST /clockswith{"cmd":"sync"}. -
public async Task<RecordingMessage> SetRecordingStart(string deviceHost, CancellationToken cancellationToken)
Starts recording viaPOST /recordingwith{"cmd":"start"}. -
public async Task<RecordingMessage> SetRecordingTriggerCheck_Quick(string deviceHost, CancellationToken cancellationToken)
Performs quick trigger check viaPOST /recordingwith{"cmd":"triggercheck_quick"}. -
public async Task<RecordingMessage> SetRecordingStop(string deviceHost, CancellationToken cancellationToken)
Stops recording viaPOST /recordingwith{"cmd":"stop"}. -
public async Task<NetworkMessage> SetNetwork(string deviceHost, NetworkRequest networkRequest, CancellationToken cancellationToken)
Sets network configuration viaPOST /network. -
public async Task<EventPinMessage> SetEventPinArm(string deviceHost, CancellationToken cancellationToken)
Arms event pin viaPOST /event-pinwith{"cmd":"arm"}. -
public async Task<EventPinMessage> SetEventPinDisarm(string deviceHost, CancellationToken cancellationToken)
Disarms event pin viaPOST /event-pinwith{"cmd":"disarm"}. -
public async Task<StatusMessage> Delete(string deviceHost, string usbPath, CancellationToken cancellationToken)
Deletes file/directory on device viaPOST /filewith{"cmd":"delete", "path":"..."}. ValidatesusbPathis non-null/empty. -
public async Task Download(string deviceHost, string usbPath, string destinationDirectory, TimeSpan timeOut, CancellationToken cancellationToken)
Downloads file/directory (as.zipif directory) from device to local path. ValidatesusbPath,destinationDirectory, and thatdestinationDirectoryexists. UsesPOST /filewith{"cmd":"download", "path":"..."}and reads response as stream. -
public async Task<StatusMessage> Upload(string deviceHost, string uploadUsbPath, string sourcefile, TimeSpan timeOut, CancellationToken cancellationToken)
Uploads local file to device viaPOST /filewith multipart form data (cmd=upload,path=uploadUsbPath,file=<bytes>). ValidatesuploadUsbPath,sourcefile, and thatsourcefileexists.
Supporting Types (Internal)
-
RESTWrapper(internal static class)
Encapsulates HTTP communication logic.public static int Port { get; set; } = 5000
Default port for API calls.public static Protocol Protocol { get; set; } = Protocol.http
Protocol used (httporhttps).public static TimeSpan Timeout { get; set; } = 30s
Default HTTP timeout.public static async Task<string> GetResourceAsync(...)
Performs GET request; throwsCanApiExceptionon non-2xx status (including deserialized error message).public static async Task<string> PostResourceAsync<T>(...)
Performs JSON POST request; throwsCanApiExceptionon non-2xx status.public static async Task<Stream> SendResourceReadAsStreamAsync<T>(...)
Performs POST request and returns response asStream(for large downloads).public static async Task<string> PostResourceReadAsStringAsync(...)
Performs multipart form POST and returns response asstring.public static async Task WriteStreamToFileAsync(Stream inputStream, string filePath)
Writes stream to file.
-
HttpClientFactory(internal static class)
Creates configuredHttpClientinstances.public static HttpClient CreateHttpClient()
Returns a newHttpClientwithAccept: application/jsonheader and cleared default headers.
-
CanApiException(public class)
Custom exception for API errors.public int? StatusCode { get; set; }
HTTP status code if available.- Constructors:
(string, Exception),(string, int).
-
Protocol(public enum)
http,https. -
CommandName(internal enum)
Maps logical command names to REST endpoint paths (viaDescriptionAttribute):Serial,LEDs,Battery,CalibrationDate,CANInfo,CANState,CANStats,CANConfig,DeviceInfo,Ntp,Power,Services,Network,Clocks,EventPin,Recording,UsbStats,UsbTree,File,Diagnostics.
3. Invariants
- Host Validation: All public methods in
CANFDandRESTWrapperrequiredeviceHostto be non-null/non-empty; otherwise,ArgumentNullExceptionis thrown. - Path Validation:
Delete,Download, andUploadmethods requireusbPath/sourcefile/destinationDirectoryto be non-null/non-empty and, where applicable, exist on the filesystem. - Timeout Isolation:
DownloadandUploadtemporarily overrideRESTWrapper.Timeoutand restore it in afinallyblock. - Error Handling: Non-2xx HTTP responses trigger
CanApiExceptionwith status code and deserialized error message (if available). Specific handling for400,403,404,500,503. - JSON Content-Type: All POST requests use
application/jsonormultipart/form-dataas appropriate. - Protocol Consistency: All endpoints use the same
ProtocolandPort(configurable at class level). - CancellationToken Propagation: All async methods accept and propagate
CancellationToken; cancellation results inCanApiExceptionwith message"An API call was cancelled or timedout".
4. Dependencies
External Dependencies
Microsoft.Extensions.Http: Used viaIHttpClientFactoryinHttpClientFactory.Newtonsoft.Json: Used for JSON serialization/deserialization (JsonConvert.DeserializeObject<T>,PostAsJsonAsync).CsvHelper: Used inGetBISTto parse CSV responses.System.Net.Http: Core HTTP client functionality.System.IO: File/stream operations (FileStream,File.ReadAllBytes,CopyToAsync).
Internal Dependencies
CANFDApiProxy.Messages: Contains response message types (e.g.,UsbTreeMessage,BatteryMessage,StatusMessage,LEDsPostMessage,CANConfigMessage, etc.).CANFDApiProxy.Requests: Contains request types (e.g.,SerialRequest,CANConfigRequest,LEDsRequest,FileRequest,NetworkRequest,ClocksRequest,CanPostRequest).CANFDApiProxy.Interfaces:ICANFDApiinterface implemented byCANFD.
Inferred Consumers
- Any application or library requiring programmatic access to the CAN FD device’s REST API (e.g., test harnesses, UI clients, logging services).
5. Gotchas
RESTWrapper.Timeoutis global state: ChangingRESTWrapper.Timeoutaffects all subsequent calls until changed again.Download/Uploadtemporarily override it, but concurrent calls may interfere.CANInfoInternalis an internal implementation detail:GetLEDs,GetCANInfo,GetCANState,GetCANStats, andGetCANConfigall deserialize the same internal type (CANInfoInternal) and manually construct the public message types. Changes to the device’s/leds,/can-info, etc., response structure may break these methods.IsDirectoryheuristic is flawed:CANFD.IsDirectoryusesPath.GetExtension(fileOrDirectory)to infer directory vs. file. This is unreliable (e.g., directories without extensions, files with no extension). TheBuildFilePathlogic assumes directories end with/or lack an extension, but this may not match the device’s behavior.GetBISTCSV parsing is fragile: UsesCsvHelperwithPrepareHeaderForMatchto lowercase headers. Assumes device CSV headers matchDiagnosticMessageRowproperty names case-insensitively; any mismatch will cause silent failures or exceptions.PostAsJsonAsyncusesPostAsJsonAsyncextension: Relies onSystem.Net.Http.Jsonextension (not shown in source), which may not be available in all environments.WriteStreamToFileAsyncresets stream position: Only resets ifinputStream.CanSeek; otherwise, it may start from current position.- No retry logic: Transient network errors or server overload are not retried; callers must implement retry policies.
Protocolenum is lowercase:Protocol.http→"http"(viaToString()), but HTTP/HTTPS schemes are case-insensitive per RFC. This is consistent but non-standard (typically"HTTP"/"HTTPS").CommandName.DescriptionAttris internal: Only used internally; external consumers cannot leverage this enum mapping directly.