Files
ANSCORE/modules/ANSUtilities/ANSUtilities.h
T
nghianguyenandClaude Opus 5 86b520d85c ANSAWSS3: recover from dead sockets, and report why an upload failed
Field logs showed clusters of uploads taking exactly 20004/20007/20003 ms —
the default _idleTimeoutMs — across several workers at the same instant, then
recurring. Cause: a connection whose request failed was returned to the pool,
so a socket silently dropped by a middlebox was handed to worker after worker,
each paying the full idle timeout to rediscover it. Chilkat's autoReconnect
only covers a cleanly closed connection, not a half-open one.

Connection handling:
- DiscardConnection(): a TRANSPORT failure closes the connection instead of
  pooling it (23 sites). An HTTP error status is not a transport failure - the
  server answered - so those connections are still reused.
- Pooled connections idle longer than 15 s are dropped at acquire time.
- First request on a reused connection uses a short idle timeout (a quarter of
  the configured one, 5 s by default); a fresh connection keeps the full one.
  A dead socket now costs ~5 s once, not 20 s repeatedly.
- One upload call is capped at 30 s wall-clock. The attempt count alone was not
  a time bound: 20 attempts x 20 s could block the caller for ~400 s.
- RetryLoop no longer gives up after one failed connect. Callers call Connect()
  once at startup, so returning left the handle dead for the process lifetime.
  Now backs off 3 s -> 30 s until connected or stopped.
- Connections carry the config generation they were built against, so a connect
  completing just after SetAuthentication cleared the pool cannot leave an
  unauthenticated connection behind (those uploads would 403).
- Stale per-request state is cleared on acquire: multipart uploadId/partNumber
  query params, and the gzip Content-Encoding set by UploadTextData. Not
  ClearAllHeaders - that wipes SigV4 state (fcc985e).

Return codes - upload exports now say whether a retry is worthwhile:
-20 permanent (bad argument, licence, or HTTP 4xx), -21 not connected yet,
-22 transient. Recorded per thread, since one handle is shared by many workers.
Success stays the only positive value, so rc == 1 and rc != 1 are unchanged.
Handle and exception codes (-1/-3/-4) made consistent across all upload
wrappers; some previously returned 0 for these.

Also fixes a misclassification this surfaced: Chilkat reports failure for an
HTTP 4xx delivered during an Expect: 100-continue exchange, so NoSuchBucket was
treated as a network error and retried 20 times before reporting "transient".
The failure path now checks the response status. Chilkat's ~2 KB error dump per
failure is compressed to one line carrying the actual S3 error code.

Verified against live S3: 14,701 uploads across 15 threads with a 150 s idle
gap, 0 failures, no call over 5 s (avg 90 ms, p95 136 ms), matching the
pre-change baseline; and all six return-code classes confirmed end to end.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-12 21:24:12 +10:00

595 lines
36 KiB
C++

#ifndef ANSULT_H
#define ANSULT_H
#define ANSULT_API __declspec(dllexport)
#pragma once
#include "LabVIEWHeader/extcode.h"
#include <map>
#include <string>
#include <vector>
#include "ANSLicense.h"
#include <CkRest.h>
#include "CkAuthGoogle.h"
#include "CkByteData.h"
#include <CkAuthAws.h>
#include <CkXml.h>
#include <CkCrypt2.h>
#include <CkSocket.h>
#include <opencv2/opencv.hpp>
#include <thread>
#include <atomic>
#include <chrono>
#include <functional>
namespace ANSCENTER {
// Discovered AIBOX / ANSVIS server on the local network.
struct ANSDeviceInfo {
std::string ip; // IPv4 address (dotted-decimal)
std::string name; // Device name from UDP probe, empty if HTTP-only
std::string firmware; // Version string ("-" if device did not report one)
int port{ 0 }; // TCP port the device's HTTP API answers on
// (AIBOX = 80, ANSVIS = 22211). 0 = unknown.
int source{ 0 }; // 1 = multicast, 2 = HTTP sweep, 3 = both
};
class ANSULT_API ANSUtilities {
private:
// Protects all shared mutable data
mutable std::recursive_mutex _mutex;
bool _isUnlockCodeValid{ false};
bool _isLicenseValid{ false};
std::string _licenseKey;
std::string _unlockCode;
std::string _proxyHost;
int _proxyPort{ 0 };
std::string _proxyUsername;
std::string _proxyPassword;
bool _bProxy{ false };
std::string _fireBaseSessionToken;
bool _bTls{ true };
int _port{ 443 };
bool _bAutoReconnect{ true };
bool _isAWSConnected{ false };
// Google Cloud Storage Authentication
CkAuthGoogle _authGoogle;
bool _isAuthenticated{ false };
SPDLogger& _logger = SPDLogger::GetInstance("ANSUtilities", false);
std::chrono::system_clock::time_point tokenGeneratedTime;
bool tokenInitialized = false;
static const int TOKEN_EXPIRY_SECONDS = 3600;
public:
ANSUtilities();
~ANSUtilities();
[[nodiscard]] bool Initialize(const std::string& licenseKey);
void CheckLicense();
void CheckUnlockCode();
[[nodiscard]] bool SetServerProxy(const std::string& proxyHost, int proxyPort, const std::string& proxyUsername, const std::string& proxyPassword);
[[nodiscard]] std::string GetFirebaseCloudMessageAcccessToken(std::string privateKey);
//AWS SNS Functions
[[nodiscard]] std::string CreateAWSSNSTopic(const std::string& topicName); // Will return the ARN of the topic
[[nodiscard]] bool DeleteAWSSNSTopic(const std::string& topicARN); // Will return the ARN of the topic
[[nodiscard]] std::string ListAWSSNSTopic(); // Will return the list ARN of the topic in string with ; concatenated
[[nodiscard]] std::string SubcribeSMSPhoneNumber(const std::string& topicARN, const std::string& phoneNumber);
[[nodiscard]] std::string SubscribeEmailAddress(const std::string& topicARN, const std::string& emailAddress);
[[nodiscard]] std::string SendMessageToTopic(const std::string& topicARN, const std::string& subjectContent, const std::string& messageContent);// Return the message ID
[[nodiscard]] std::string SendMessageToPhoneNumber(const std::string& phoneNumber, const std::string& messageContent);// Return the message ID
// Google Cloud Storage Upload using Chilkat
[[nodiscard]] bool AuthenticateGCS(const std::string& jsonKeyString);
[[nodiscard]] bool UploadMatToGCS(const std::string& bucketName, const std::string& objectName, const cv::Mat& image);
[[nodiscard]] bool UploadMatToGCS(const std::string& bucketName, const std::string& objectName, unsigned char* jpeg_string, int32 bufferLength);
[[nodiscard]] static bool CheckUnlockCode_S();
[[nodiscard]] static std::string AESEncryption(const std::string& inputString, const std::string& inputKey);
[[nodiscard]] static std::string AESDecryption(const std::string& encryptString, const std::string& inputKey);
[[nodiscard]] static std::string MD5HashFile(const std::string& inputFilePath);
// SMTP for office360 email sending
[[nodiscard]] static bool SendEmail(const std::string& smtpServer, int port,
const std::string& userName, const std::string& password,
const std::string& subjectContent,
const std::string& bodyHTMLContent,
const std::string& bodyTextContent,
const std::string& fromEmailSender,
const std::vector<std::string>& toEmails,
const std::vector<std::string>& ccEmails,
const std::vector<std::string>& bccEmails);
// Restart PC
[[nodiscard]] static bool RestartPC();
// Convert a UTF-8 encoded string to UTF-16LE byte string.
// Useful for LabVIEW which can display UTF-16LE Unicode text on Windows.
static std::string ConvertUTF8ToUTF16LE(const std::string& utf8Str);
// Decode JSON Unicode escape sequences (\uXXXX) to UTF-16LE byte string.
// Input: ASCII string with \uXXXX escapes (e.g., "\\u6c5f\\u6771 599")
// Output: UTF-16LE byte string for LabVIEW display.
static std::string DecodeJsonUnicodeToUTF16LE(const std::string& escapedStr);
// Convert a UTF-16LE byte string to UTF-8.
// Useful for receiving Unicode text from LabVIEW and converting to UTF-8 for internal processing.
static std::string ConvertUTF16LEToUTF8(const char* utf16leBytes, int byteLen);
// Convert UTF-16LE byte string (with optional BOM) to Unicode escape sequences (\uXXXX).
// Input: raw UTF-16LE bytes (BOM is auto-stripped if present).
// Output: ASCII string with \uXXXX for non-ASCII codepoints, plain ASCII chars preserved.
static std::string ConvertUTF16LEToUnicodeEscapes(const char* utf16leBytes, int byteLen);
// Convert Unicode escape sequences (\uXXXX) to UTF-8 string.
// Input: ASCII string with \uXXXX escapes (e.g., "\\u6c5f\\u6771 599")
// Output: UTF-8 encoded Unicode string.
static std::string ConvertUnicodeEscapesToUTF8(const std::string& escapedStr);
// Convert a UTF-8 string to Unicode escape sequences (\uXXXX).
// ASCII chars (0x20-0x7E) are preserved, all others become \uXXXX.
// Useful for encoding Unicode text into JSON-safe ASCII.
static std::string ConvertUTF8ToUnicodeEscapes(const std::string& utf8Str);
// Repair mixed-encoding input from LabVIEW text controls.
// LabVIEW may produce a mix of UTF-16LE pairs and UTF-8 multi-byte
// sequences in a single byte stream. It may also insert space (0x20) as
// a single byte without the 0x00 high byte.
// This function normalizes everything to proper UTF-16LE pairs.
// Input: raw bytes from LStrHandle (BOM should already be stripped).
// Output: clean UTF-16LE with proper 2-byte alignment.
static std::vector<unsigned char> RepairLabVIEWUTF16LE(const unsigned char* data, int len);
// Check if a byte sequence is valid UTF-8.
// Returns true if all bytes form valid UTF-8 sequences.
static bool IsValidUTF8(const unsigned char* data, int len);
// Double-escape \uXXXX sequences: \u1ee7 becomes \\u1ee7.
// Useful when the string will be embedded in JSON and the literal \uXXXX must survive parsing.
static std::string DoubleEscapeUnicode(const std::string& str);
// Convert UTF-8 to double-escaped Unicode: "Thủy" becomes "Th\\u1ee7y".
// Combines ConvertUTF8ToUnicodeEscapes + DoubleEscapeUnicode in one call.
static std::string ConvertUTF8ToDoubleEscapedUnicode(const std::string& utf8Str);
// Unescape double-escaped Unicode: "Th\\u1ee7y" becomes "Th\u1ee7y".
// Reverses DoubleEscapeUnicode so other languages can parse \uXXXX correctly.
static std::string UnescapeDoubleEscapedUnicode(const std::string& str);
// Read every Error-level event from "ANSLogger" in the Windows
// Application event log. Output: one line per event in the form
// "<DD/MM/YYYY h:mm:ss tt>: <event data string>\n"
// Time is converted to the user's local timezone and formatted
// using LOCALE_USER_DEFAULT (matches Event Viewer's display).
//
// clearAfterRead=true behaviour:
// * Calls EvtClearLog on the entire Application channel after
// reading. WARNING: this wipes every event from every source
// in the Application log, not just ANSLogger entries — there
// is no per-event delete API in Windows.
// * REQUIRES THE CALLING PROCESS TO BE ELEVATED (run as
// Administrator). Without elevation, EvtClearLog returns
// ERROR_ACCESS_DENIED (Win32 error 5) and the events remain
// in the log. The read still succeeds either way.
// * Failures are reported on stderr in the form
// "[ANSUtilities] EvtClearLog(Application) FAILED, GetLastError=N"
// and via DebugView under the "EVTLOG" tag. The C++ return
// value does NOT signal clear success — capture stderr or
// check Event Viewer afterwards to confirm.
[[nodiscard]] static std::string GetANSLoggerErrorEvents(bool clearAfterRead = false);
// Same as GetANSLoggerErrorEvents but only returns events that
// have NOT been returned by a previous call from this user
// account. The highest EventRecordID seen is persisted to
// HKCU\Software\ANSCENTER\ANSUtilities\EventLogWatermark\ANSLogger
// (REG_QWORD) and used as a Windows XPath filter
// (EventRecordID > N) on the next call. No admin needed for the
// skip mechanism — only for the optional clearAfterRead.
//
// Channel-clear handling: if Windows resets the Application
// channel's RecordID counter (typical after EvtClearLog), this
// function detects that the channel's current max RecordID is
// less than the stored watermark and resets the watermark to 0
// so no newly-written events are accidentally skipped.
//
// To force a re-read of all events, delete the registry value
// above and call again.
[[nodiscard]] static std::string GetANSLoggerErrorEventsSinceLastCall(bool clearAfterRead = false);
// Scan the local network for AIBOX / ANSVIS servers.
// Runs two strategies in parallel and merges results by IP:
// 1) UDP multicast probe to 230.50.200.150:58839 (with subnet
// broadcast fallback). App listens on UDP/58838 for replies
// in the form "<a>:<b>:<deviceName>:<firmware>".
// 2) HTTP /24 subnet sweep on every local IPv4 interface, GETing
// http://<host>/ServerApi with up to 64 concurrent connections.
// A device is recognized when the JSON body contains
// {"OK": true, "Version": "<firmware>"}.
// `timeoutMs` is the maximum scan window (default 5000 ms). Shorter
// values return faster but may miss slow devices. The call blocks
// until the window elapses, then returns the deduplicated list.
[[nodiscard]] static std::vector<ANSDeviceInfo> ScanDevices(int timeoutMs = 5000);
};
// Connection bundle for pool
struct S3Connection {
CkRest rest;
CkSocket socket;
CkAuthAws authAws;
// When this connection last completed a request successfully. A socket
// that a NAT/firewall silently killed while idle costs a full
// IdleTimeoutMs to discover, so anything idle longer than
// kMaxPooledIdleMs is dropped rather than handed out again.
std::chrono::steady_clock::time_point lastUsed{ std::chrono::steady_clock::now() };
// Value of ANSAWSS3::_configGen when this connection was built.
// A mismatch means it predates a Connect / SetAuthentication /
// SetServerProxy call — e.g. the background RetryLoop finished a
// connect just after SetAuthentication cleared the pool — so its
// endpoint, proxy or SigV4 state is stale and it must not be reused.
uint64_t configGen{ 0 };
};
class ANSULT_API ANSAWSS3 {
private:
bool _isUnlockCodeValid{ false };
bool _isLicenseValid{ false };
// Atomic because upload threads read _bConnected without a lock
// while Connect() / RetryLoop() can write it.
std::atomic<bool> _bConnected{ false };
bool _bAwsPath{ true }; // true = virtual-hosted (AWS), false = path-style (MinIO)
std::string _licenseKey;
std::string _unlockCode;
// ── Connection pool (replaces single _rest/_socket/_authAws) ──
std::mutex _poolMutex;
std::vector<std::unique_ptr<S3Connection>> _pool;
// ── Config (read-only after setup, protected by _configMutex) ──
std::mutex _configMutex;
std::string _fullAWSURL; // AWS S3 service URL
bool _bTls{ true };
int _port{ 443 };
bool _bAutoReconnect{ true };
std::string _serviceName;
std::string _bucketRegion;
std::string _baseDomain;
std::string _accessKey;
std::string _secretKey;
bool _authReady{ false };
// Request timeouts applied to every new S3Connection.
// _connectTimeoutMs : max time to wait for TCP/TLS connect.
// _idleTimeoutMs : max gap between bytes on a send/recv.
// Atomic so SetTimeouts can update them without holding _configMutex.
std::atomic<int> _connectTimeoutMs{ 10000 }; // 10 s
std::atomic<int> _idleTimeoutMs { 20000 }; // 20 s
// Shorter idle timeout used for the FIRST request on a connection
// taken from the pool. A pooled socket may have been silently
// dropped by a middlebox since it was last used; without this the
// caller pays the full _idleTimeoutMs (20 s by default) just to
// discover that. A fresh connection still gets the full
// _idleTimeoutMs, so the retry after a stale-socket failure is not
// penalised. Derived from _idleTimeoutMs by SetTimeouts().
std::atomic<int> _reusedIdleTimeoutMs{ 5000 }; // 5 s
// Bumped by Connect / SetAuthentication / SetServerProxy. Stamped
// into every S3Connection at creation; see S3Connection::configGen.
std::atomic<uint64_t> _configGen{ 1 };
// A pooled connection idle longer than this is closed instead of
// reused. Kept below the ~20 s after which S3 (and most NAT
// devices) stop caring about an idle keep-alive flow.
static constexpr int kMaxPooledIdleMs = 15000;
// Proxy settings
std::string _proxyHost;
int _proxyPort{ 0 };
std::string _proxyUsername;
std::string _proxyPassword;
bool _bProxy{ false };
SPDLogger& _logger = SPDLogger::GetInstance("ANSAWSS3", false);
// Pool helpers
// logOnFailure=false suppresses error-level logging on failure (still emits ANS_DBG).
// Used by TryConnect's first attempt, which is allowed to fail for path-style/MinIO servers.
std::unique_ptr<S3Connection> CreateConnection(bool logOnFailure = true);
std::unique_ptr<S3Connection> AcquireConnection();
// Return a healthy connection to the pool for reuse.
void ReleaseConnection(std::unique_ptr<S3Connection> conn);
// Close and destroy a connection instead of pooling it. Use on any
// TRANSPORT failure (send/recv failed, timeout): that socket is
// suspect, and putting it back means the next worker inherits the
// same stall. An HTTP error status is NOT a transport failure — the
// server answered — so those still go through ReleaseConnection.
void DiscardConnection(std::unique_ptr<S3Connection> conn);
std::string ExtractFileName(const std::string& filePath);
std::string GetContentType(const std::string& filePath);
// ---- Retry helper for transient / network-stability failures ----
// Each upload function delegates its per-attempt body to a lambda.
// The lambda returns one of these outcomes:
// Success -> stop, UploadWithRetry returns true
// Transient -> retry (up to kUploadMaxAttempts total)
// Permanent -> stop, UploadWithRetry returns false
// The lambda should write a short human-readable reason into
// `lastError` on any non-Success outcome so it can be logged.
enum class AttemptResult { Success, Transient, Permanent };
// Record the outcome of the current call for the calling thread.
static void SetCallStatus(int status);
// Shared licence / unlock / connected check for the upload entry
// points. Logs the reason and sets the per-thread call status
// (permanent for a licence problem, not-connected for a link that
// has not come up yet). Returns false if the call must not proceed.
bool CheckUploadPreconditions(const std::string& opName);
// Decide what a failed Chilkat request means, and dispose of the
// connection accordingly. Chilkat reports failure for an HTTP 4xx
// delivered during an Expect: 100-continue exchange, so "the call
// returned false" does NOT imply the network failed — a 404
// NoSuchBucket arrives this way. Retrying those wastes the whole
// retry budget and reports the wrong class to the caller.
// 4xx (except 408/429) -> Permanent, socket healthy -> pooled
// anything else -> Transient, socket suspect -> discarded
// Takes ownership of `conn`, and rewrites `lastError` into one
// readable line.
AttemptResult ClassifyFailedRequest(std::unique_ptr<S3Connection> conn,
std::string& lastError);
static constexpr int kUploadMaxAttempts = 20;
static constexpr int kUploadRetryDelayMs = 100;
// Wall-clock budget for one upload call, across all attempts. The
// attempt cap alone is not a bound on time: 20 attempts that each
// hit a 20 s idle timeout would block the caller for ~400 s. A new
// attempt is only started while inside this budget, so the worst
// case is the budget plus one in-flight attempt.
static constexpr int kUploadDeadlineMs = 30000;
bool UploadWithRetry(
const std::string& opName,
const std::function<AttemptResult(std::string& lastError)>& attemptFn);
// Background retry
std::thread _retryThread;
std::atomic<bool> _stopRetry{ false };
std::atomic<bool> _retryInProgress{ false };
void StopRetry();
void RetryLoop();
bool TryConnect(bool& awsPath);
public:
// ---- Call status codes -------------------------------------------
// Every upload entry point records one of these for the CALLING
// THREAD, so the C exports can tell the caller whether a retry is
// worth attempting without changing any function signature.
//
// These EXTEND the codes the C wrappers already return; they do not
// redefine any of them. Full set seen by a LabVIEW caller:
// 1 success
// 0 null / invalid argument passed to the export
// -1 handle not in the registry
// -2 upload failed, reason not classified (fallback)
// -3 std::exception escaped
// -4 unknown exception escaped
// -20 permanent: bad argument, licence, bucket, or HTTP 4xx
// -21 not connected yet / reconnect in progress
// -22 transient: network, timeout or 5xx after internal retries
//
// Retry rule for the caller: retry on -21 and -22 (and -2/-3/-4 if
// it wants to be generous); do NOT retry on -20 or 0 — those need a
// configuration or code fix. Success stays the only positive value,
// so both `rc == 1` and `rc != 1` remain correct tests.
static constexpr int kCallSuccess = 1;
static constexpr int kCallPermanentError = -20;
static constexpr int kCallNotConnected = -21;
static constexpr int kCallTransientError = -22;
// Status of the most recent upload call made ON THIS THREAD.
// Thread-local, so concurrent workers sharing one handle never see
// each other's result. Read it immediately after the call.
static int LastCallStatus();
ANSAWSS3();
~ANSAWSS3();
[[nodiscard]] bool Initialize(const std::string& licenseKey);
void CheckLicense();
void CheckUnlockCode();
[[nodiscard]] bool SetServerProxy(const std::string& proxyHost, int proxyPort, const std::string& proxyUsername, const std::string& proxyPassword);
// Returns: 1 = connected, 0 = failed (bad auth/URL), 2 = no internet (background retry started)
[[nodiscard]] int Connect(const std::string& baseDomain, const std::string& bucketRegion, const std::string& serviceName, int port, bool bTls, bool autoReconnect, bool& awsPath);
[[nodiscard]] bool SetAuthentication(const std::string& accessKey, const std::string& secretKey);
// Pre-populate the connection pool with `count` ready-to-use
// S3Connections. Creating a connection performs a TLS handshake
// inside CreateConnection(); doing it up-front in parallel keeps
// the first `count` concurrent uploads from serializing on handshake.
// Safe to call after Connect() + SetAuthentication() have succeeded.
// Returns the number of connections actually added to the pool
// (may be less than `count` on transient network issues).
int PrewarmConnectionPool(int count);
// Update request timeouts used by every new connection, and
// propagate them to all already-pooled connections so the new
// values take effect on the very next request.
// connectMs: max time to wait for TCP/TLS connect (>= 1000 ms)
// idleMs : max gap between bytes on send/recv (>= 1000 ms)
// Returns false on invalid input (values are left unchanged).
bool SetTimeouts(int connectMs, int idleMs);
[[nodiscard]] std::vector<std::string> ListBuckets();
[[nodiscard]] std::vector<std::string> ListBucketObjects(const std::string& bucketName);
[[nodiscard]] std::vector<std::string> ListBucketObjectsWithPrefix(const std::string& bucketName, const std::string& prefix);
[[nodiscard]] bool CreateBucket(const std::string& bucketName);
[[nodiscard]] bool DeleteBucket(const std::string& bucketName);
[[nodiscard]] bool CreateFolder(const std::string& bucketName, const std::string& prefix);
[[nodiscard]] bool DeleteFolder(const std::string& bucketName, const std::string& prefix);
[[nodiscard]] bool DeleteBucketObject(const std::string& bucketName, const std::string& objectName);
[[nodiscard]] std::string GetBucketRegion(const std::string& bucketName);
// Upload data to AWS S3
[[nodiscard]] bool UploadTextData(const std::string& bucketName, const std::string &textFilePath, std::string& uploadedFilePath);
[[nodiscard]] bool UploadFileStream(const std::string& bucketName, const std::string& dataFilePath, std::string& uploadedFilePath);
[[nodiscard]] bool UploadBinaryData(const std::string& bucketName, const std::string& dataFilePath, std::string& uploadedFilePath);
[[nodiscard]] bool UploadPrefixBinaryData(const std::string& bucketName, const std::string& prefix, const std::string& dataFilePath, const std::string& objectName, std::string& uploadedFilePath);
[[nodiscard]] bool UploadMultipartData(const std::string& bucketName, const std::string& dataFilePath, std::string& uploadedFilePath, int partSize=5242880);
[[nodiscard]] bool UploadPrefixMultipartData(const std::string& bucketName, const std::string& prefix, const std::string& dataFilePath, const std::string& fileName, std::string& uploadedFilePath, int partSize= 5242880);
[[nodiscard]] bool UploadPrefixJpegImage(const std::string& bucketName, const std::string& prefix, unsigned char* jpeg_string, int32 bufferLength, const std::string& fileName, std::string& uploadedFilePath);
[[nodiscard]] bool UploadJpegImage(const std::string& bucketName, unsigned char* jpeg_string, int32 bufferLength, const std::string& fileName, std::string& uploadedFilePath);
[[nodiscard]] bool DownloadFile(const std::string& bucketName, const std::string& objectName, const std::string& saveFilePath);
// Generate a temporary pre-signed URL (AWS Signature V4) for an
// object already stored in S3, so public users can access it
// without AWS credentials until it expires.
// bucketName, prefix, objectName: the SAME three values passed
// to UploadPrefixJpegImage when the object was uploaded.
// (objectName is what UploadPrefixJpegImage calls its
// `fileName` parameter — the last segment of the S3 key.)
// validDays: URL validity in days, 1..7 (AWS caps pre-signed
// URLs at 7 days).
// The object key is rebuilt as "<prefix>/<objectName>", so the URL
// points at exactly the key that was uploaded. This is a local
// signing operation: it performs no network I/O, but
// Connect()/SetAuthentication() must have been called so the
// credentials and endpoint are known.
[[nodiscard]] bool GeneratePresignedURL(const std::string& bucketName, const std::string& prefix, const std::string& objectName, int validDays, std::string& presignedURL);
};
}
extern "C" ANSULT_API int CreateANSUtilityHandle(ANSCENTER::ANSUtilities** Handle, const char* licenseKey);
extern "C" ANSULT_API int ReleaseANSUtilityHandle(ANSCENTER::ANSUtilities** Handle);
extern "C" ANSULT_API int GetFCMAccessToken(ANSCENTER::ANSUtilities** Handle, const char* privateKey, LStrHandle accessToken);
extern "C" ANSULT_API int CreateAWSSNSTopic(ANSCENTER::ANSUtilities** Handle, const char* snsTopicName, LStrHandle arnTopic);
extern "C" ANSULT_API int DeleteAWSSNSTopic(ANSCENTER::ANSUtilities** Handle, const char* arnTopic);
extern "C" ANSULT_API int ListASWTopics(ANSCENTER::ANSUtilities** Handle, LStrHandle arnTopics);
extern "C" ANSULT_API int AESEncryption(const char* inputString, const char* inputKey, LStrHandle encryptionMessage);
extern "C" ANSULT_API int AESDecryption(const char* encryptedString, const char* inputKey, LStrHandle decryptionMessage);
extern "C" ANSULT_API int MD5HashFile(const char* filePath, LStrHandle decryptionMessage);
extern "C" ANSULT_API int SubcribeSMSPhoneNumberAWSSNSTopic(ANSCENTER::ANSUtilities** Handle, const char* snsTopicName, const char* phoneNumber, LStrHandle subscribedARN);
extern "C" ANSULT_API int SubcribeEmailAddressAWSSNSTopic(ANSCENTER::ANSUtilities** Handle, const char* snsTopicName, const char* emailAddress, LStrHandle subscribedARN);
extern "C" ANSULT_API int SendMessageToAWSSNSTopic(ANSCENTER::ANSUtilities** Handle, const char* snsTopicName, const char* subjectContent,const char * messageContent, LStrHandle messageId);
extern "C" ANSULT_API int SendMessageToPhoneNumber(ANSCENTER::ANSUtilities** Handle, const char* phoneNumber, const char* messageContent, LStrHandle messageId);
extern "C" ANSULT_API int GetFCMAccessTokenCpp(ANSCENTER::ANSUtilities** Handle, const char* privateKey, std::string &accessToken);
extern "C" ANSULT_API int CreateAWSSNSTopicCpp(ANSCENTER::ANSUtilities** Handle, const char* snsTopicName, std::string& arnTopic);
extern "C" ANSULT_API int SubcribeSMSPhoneNumberAWSSNSTopicCpp(ANSCENTER::ANSUtilities** Handle, const char* snsTopicName, const char* phoneNumber, std::string& subscribedARN);
extern "C" ANSULT_API int SubcribeEmailAddressAWSSNSTopicCpp(ANSCENTER::ANSUtilities** Handle, const char* snsTopicName, const char* emailAddress, std::string& subscribedARN);
extern "C" ANSULT_API int SendMessageToAWSSNSTopicCpp(ANSCENTER::ANSUtilities** Handle, const char* snsTopicName, const char* subjectContent, const char* messageContent, std::string& messageId);
extern "C" ANSULT_API int SendMessageToPhoneNumberCpp(ANSCENTER::ANSUtilities** Handle, const char* phoneNumber, const char* messageContent, std::string& messageId);
extern "C" ANSULT_API int ListASWTopicsCpp(ANSCENTER::ANSUtilities** Handle, std::string& arnTopics);
// Static functions
extern "C" ANSULT_API int AESEncryptionCpp(const char* inputString, const char* inputKey, std::string& encryptedString);
extern "C" ANSULT_API int AESDecryptionCpp(const char* encryptedString, const char* inputKey, std::string& decryptionMessage);
// Google Cloud Storage
extern "C" ANSULT_API int SetupServerProxy(ANSCENTER::ANSUtilities** Handle, const char* hostName, int port, const char* userName, const char* passWord);
extern "C" ANSULT_API int AuthenticateGCS(ANSCENTER::ANSUtilities** Handle, const char* jsonKeyString);
extern "C" ANSULT_API int UploadMatToGCS(ANSCENTER::ANSUtilities** Handle, const char* bucketName, const char* objectName, unsigned char* jpeg_string, int32 bufferLength);
extern "C" ANSULT_API int UploadImageToGCS(ANSCENTER::ANSUtilities** Handle, const char* bucketName, const char* objectName, cv::Mat image);
extern "C" ANSULT_API int SendEmail(const char* smtpServer, int port,
const char* userName, const char* password,
const char* title, const char* bodyHTMLContent,
const char* bodyTextContent,
const char* fromEmailSender,
const char* toEmails,
const char* ccEmails,
const char* bccEmails);
extern "C" ANSULT_API int RebootSystem();
// Discover AIBOX / ANSVIS servers on the local network.
// Returns a JSON array of objects: [{"ip":"...","name":"...","firmware":"...","source":3}, ...]
// `source` is 1 = multicast, 2 = HTTP sweep, 3 = both.
// `timeoutMs` caps the scan duration (typical: 3000-10000 ms).
extern "C" ANSULT_API int ScanANSDevices(int timeoutMs, LStrHandle resultJson);
extern "C" ANSULT_API int ScanANSDevicesCpp(int timeoutMs, std::string& resultJson);
// Read all Error-level events from "ANSLogger" in the Windows Application
// event log. Returns a UTF-8 string with one event per line:
// "<DD/MM/YYYY h:mm:ss tt>: <event data>\n"
// `clearAfterRead` != 0 clears the entire Application channel afterwards
// (requires Administrator; see header comment on the C++ method).
extern "C" ANSULT_API int GetANSLoggerErrorEvents(int clearAfterRead, LStrHandle result);
extern "C" ANSULT_API int GetANSLoggerErrorEventsCpp(int clearAfterRead, std::string& result);
// Watermarked variant: only returns events not seen by previous calls.
// Watermark is stored in HKCU\Software\ANSCENTER\ANSUtilities\EventLogWatermark\ANSLogger
// (REG_QWORD). No admin needed for the skip; only for clearAfterRead.
extern "C" ANSULT_API int GetANSLoggerErrorEventsSinceLastCall(int clearAfterRead, LStrHandle result);
extern "C" ANSULT_API int GetANSLoggerErrorEventsSinceLastCallCpp(int clearAfterRead, std::string& result);
// Unicode conversion utilities for LabVIEW
extern "C" ANSULT_API int ANSConvertUTF8ToUTF16LE(const char* utf8Str, LStrHandle result, int includeBOM = 1);
extern "C" ANSULT_API int ANSDecodeJsonUnicodeToUTF16LE(const char* escapedStr, LStrHandle result);
extern "C" ANSULT_API int ANSConvertUTF16LEToUTF8(const unsigned char* utf16leBytes, int byteLen, LStrHandle result);
extern "C" ANSULT_API int ANSConvertUTF16LEToUnicodeEscapes(const unsigned char* utf16leBytes, int byteLen, LStrHandle result);
extern "C" ANSULT_API int ANSConvertUnicodeEscapesToUTF8(const char* escapedStr, LStrHandle result);
// LStrHandle-safe versions: input is LStrHandle (preserves null bytes in UTF-16LE data)
extern "C" ANSULT_API int ANSConvertUTF16LEToUTF8_LV(LStrHandle input, LStrHandle result);
extern "C" ANSULT_API int ANSConvertUTF16LEToUnicodeEscapes_LV(LStrHandle input, LStrHandle result);
extern "C" ANSULT_API int ANSConvertUTF8ToUnicodeEscapes(const char* utf8Str, LStrHandle result);
extern "C" ANSULT_API int ANSDoubleEscapeUnicode(const char* str, LStrHandle result);
extern "C" ANSULT_API int ANSConvertUTF8ToDoubleEscapedUnicode(const char* utf8Str, LStrHandle result);
extern "C" ANSULT_API int ANSUnescapeDoubleEscapedUnicode(const char* str, LStrHandle result);
// AWS S3 class
extern "C" ANSULT_API int CreateANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* licenseKey);
extern "C" ANSULT_API int ReleaseANSAWSHandle(ANSCENTER::ANSAWSS3** Handle);
extern "C" ANSULT_API int ConnectANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* baseDomain, const char* bucketRegion, const char* serviceName, int port, int bTls, int autoReconnect, int* awsPath);
extern "C" ANSULT_API int SetProxyANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* proxyHost, int proxyPort, const char* proxyUsername, const char* proxyPassword);
extern "C" ANSULT_API int SetAuthenticationANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* accessKey, const char* secretKey);
extern "C" ANSULT_API int ListBucketANSAWSHandle_CPP(ANSCENTER::ANSAWSS3** Handle, std::string &bucketList);
extern "C" ANSULT_API int ListBucketObjectsANSAWSHandle_CPP(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, std::string& bucketNameList);
extern "C" ANSULT_API int ListBucketObjectsWithPrefixANSAWSHandle_CPP(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* prefix, std::string& bucketNameList);
extern "C" ANSULT_API int GetRegionANSAWSHandle_CPP(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, std::string& region);
extern "C" ANSULT_API int ListBucketANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, LStrHandle bucketList);
extern "C" ANSULT_API int ListBucketObjectsANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, LStrHandle bucketNameList);
extern "C" ANSULT_API int ListBucketObjectsWithPrefixANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* prefix, LStrHandle bucketNameList);
extern "C" ANSULT_API int GetRegionANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, LStrHandle region);
extern "C" ANSULT_API int CreateBucketANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName);
extern "C" ANSULT_API int DeleteBucketANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName);
extern "C" ANSULT_API int CreateBucketPrefixANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char *prefix);
extern "C" ANSULT_API int DeleteBucketPrefixANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* prefix);
extern "C" ANSULT_API int DeleteBucketObjectANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* bucketObject);
extern "C" ANSULT_API int UploadTextDataANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* textDataPath, LStrHandle uploadedFilePath);
extern "C" ANSULT_API int UploadBinaryDataANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* binaryDataPath, LStrHandle uploadedFilePath);
extern "C" ANSULT_API int UploadFileStreamDataANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* fileDataPath, LStrHandle uploadedFilePath);
extern "C" ANSULT_API int UploadMultiPartDataANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* fileDataPath, int fileSize, LStrHandle uploadedFilePath);
extern "C" ANSULT_API int UploadJpegImageANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, unsigned char* jpeg_string, int32 bufferLength, const char* fileName, LStrHandle uploadedFilePath);
extern "C" ANSULT_API int UploadPrefixBinaryDataANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* prefix, const char* binaryDataPath, const char* objectName, LStrHandle uploadedFilePath);
extern "C" ANSULT_API int UploadPrefixMultiPartDataANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* prefix, const char* fileDataPath, const char* objectName, int fileSize, LStrHandle uploadedFilePath);
extern "C" ANSULT_API int UploadPrefixJpegImageANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* prefix, unsigned char* jpeg_string, int32 bufferLength, const char* fileName, LStrHandle uploadedFilePath);
extern "C" ANSULT_API int DownloadFileStreamANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* objectName, const char* savedFilePath);
extern "C" ANSULT_API int GeneratePresignedURLANSAWSHandle(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* prefix, const char* objectName, int validDays, LStrHandle presignedURL);
// C++ test APIs (use std::string& instead of LStrHandle)
extern "C" ANSULT_API int UploadTextDataANSAWSHandle_CPP(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* textDataPath, std::string& uploadedFilePath);
extern "C" ANSULT_API int UploadBinaryDataANSAWSHandle_CPP(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* binaryDataPath, std::string& uploadedFilePath);
extern "C" ANSULT_API int UploadFileStreamDataANSAWSHandle_CPP(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* fileDataPath, std::string& uploadedFilePath);
extern "C" ANSULT_API int UploadMultiPartDataANSAWSHandle_CPP(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* fileDataPath, int fileSize, std::string& uploadedFilePath);
extern "C" ANSULT_API int UploadJpegImageANSAWSHandle_CPP(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, unsigned char* jpeg_string, int32 bufferLength, const char* fileName, std::string& uploadedFilePath);
extern "C" ANSULT_API int UploadPrefixBinaryDataANSAWSHandle_CPP(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* prefix, const char* binaryDataPath, const char* objectName, std::string& uploadedFilePath);
extern "C" ANSULT_API int UploadPrefixMultiPartDataANSAWSHandle_CPP(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* prefix, const char* fileDataPath, const char* objectName, int fileSize, std::string& uploadedFilePath);
extern "C" ANSULT_API int UploadPrefixJpegImageANSAWSHandle_CPP(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* prefix, unsigned char* jpeg_string, int32 bufferLength, const char* fileName, std::string& uploadedFilePath);
extern "C" ANSULT_API int GeneratePresignedURLANSAWSHandle_CPP(ANSCENTER::ANSAWSS3** Handle, const char* bucketName, const char* prefix, const char* objectName, int validDays, std::string& presignedURL);
#endif