Support scanning ANSVIS servers device
This commit is contained in:
@@ -1309,5 +1309,425 @@ namespace ANSCENTER
|
|||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
} // namespace ANSCENTER
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// ScanDevices — AIBOX / ANSVIS discovery on the local LAN
|
||||||
|
//
|
||||||
|
// Port of the AIBOX Flutter app's MulticastService
|
||||||
|
// (lib/src/core/network/multicast/multicast_service.dart). AIBOX boxes and
|
||||||
|
// ANSVIS servers answer the same UDP probe and the same /ServerApi HTTP
|
||||||
|
// endpoint, so one scan finds both. DebugView: filter "[ANSDISC]".
|
||||||
|
//
|
||||||
|
// Wire protocol:
|
||||||
|
// UDP: probe text "Hello, Multicast" -> 230.50.200.150:58839 and subnet
|
||||||
|
// broadcast :58839. Devices reply to UDP/58838 with
|
||||||
|
// "<a>:<b>:<deviceName>:<firmware>".
|
||||||
|
// HTTP: GET http://<ip>/ServerApi -> 200 + JSON with
|
||||||
|
// {"OK": true, "Version": "<firmware>"}.
|
||||||
|
//
|
||||||
|
// Implementation: a UDP listener thread + a periodic UDP sender + a 64-way
|
||||||
|
// HTTP sweep populate one mutex-guarded map. After `timeoutMs` the map is
|
||||||
|
// converted to a deduplicated vector and returned.
|
||||||
|
// ============================================================================
|
||||||
|
#include <winsock2.h>
|
||||||
|
#include <ws2tcpip.h>
|
||||||
|
#include <iphlpapi.h>
|
||||||
|
#include <winhttp.h>
|
||||||
|
#include <mutex>
|
||||||
|
#include <condition_variable>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <chrono>
|
||||||
|
#include <queue>
|
||||||
|
|
||||||
|
#pragma comment(lib, "ws2_32.lib")
|
||||||
|
#pragma comment(lib, "iphlpapi.lib")
|
||||||
|
#pragma comment(lib, "winhttp.lib")
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
// ---- Protocol constants (mirror AIBOX MulticastService) -----------------
|
||||||
|
constexpr const char* kMulticastGroup = "230.50.200.150";
|
||||||
|
constexpr unsigned short kProbePort = 58839; // device listens here
|
||||||
|
constexpr unsigned short kListenPort = 58838; // we listen here
|
||||||
|
constexpr const char* kProbeMessage = "Hello, Multicast";
|
||||||
|
constexpr int kMulticastTtl = 225;
|
||||||
|
constexpr int kHttpConcurrency = 64;
|
||||||
|
constexpr int kHttpConnectTimeoutMs = 700;
|
||||||
|
constexpr int kHttpProbeTimeoutMs = 2500;
|
||||||
|
constexpr int kUdpProbeIntervalMs = 2000;
|
||||||
|
constexpr const wchar_t* kHttpUserAgent = L"ANSUtilities-Scan/1.0";
|
||||||
|
constexpr const wchar_t* kHttpPath = L"/ServerApi";
|
||||||
|
|
||||||
|
// ---- Winsock init (refcounted; safe to call repeatedly) -----------------
|
||||||
|
struct WsaScope {
|
||||||
|
bool ok{false};
|
||||||
|
WsaScope() {
|
||||||
|
WSADATA d{};
|
||||||
|
ok = (WSAStartup(MAKEWORD(2, 2), &d) == 0);
|
||||||
|
}
|
||||||
|
~WsaScope() { if (ok) WSACleanup(); }
|
||||||
|
WsaScope(const WsaScope&) = delete;
|
||||||
|
WsaScope& operator=(const WsaScope&) = delete;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- Local IPv4 interfaces ----------------------------------------------
|
||||||
|
struct LocalSubnet {
|
||||||
|
std::string prefix; // "192.168.1." (final dot included)
|
||||||
|
in_addr localAddr{};
|
||||||
|
in_addr broadcast{};
|
||||||
|
};
|
||||||
|
|
||||||
|
std::vector<LocalSubnet> EnumerateLocalSubnets() {
|
||||||
|
std::vector<LocalSubnet> out;
|
||||||
|
ULONG bufLen = 16 * 1024;
|
||||||
|
std::vector<char> buf(bufLen);
|
||||||
|
DWORD rc = GetAdaptersAddresses(AF_INET,
|
||||||
|
GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER,
|
||||||
|
nullptr, reinterpret_cast<PIP_ADAPTER_ADDRESSES>(buf.data()), &bufLen);
|
||||||
|
if (rc == ERROR_BUFFER_OVERFLOW) {
|
||||||
|
buf.resize(bufLen);
|
||||||
|
rc = GetAdaptersAddresses(AF_INET,
|
||||||
|
GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER,
|
||||||
|
nullptr, reinterpret_cast<PIP_ADAPTER_ADDRESSES>(buf.data()), &bufLen);
|
||||||
|
}
|
||||||
|
if (rc != NO_ERROR) {
|
||||||
|
ANS_DBG("ANSDISC", "GetAdaptersAddresses failed rc=%lu", static_cast<unsigned long>(rc));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
auto* adapter = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(buf.data());
|
||||||
|
for (; adapter; adapter = adapter->Next) {
|
||||||
|
if (adapter->OperStatus != IfOperStatusUp) continue;
|
||||||
|
if (adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue;
|
||||||
|
for (auto* ua = adapter->FirstUnicastAddress; ua; ua = ua->Next) {
|
||||||
|
if (!ua->Address.lpSockaddr || ua->Address.lpSockaddr->sa_family != AF_INET) continue;
|
||||||
|
auto* sin = reinterpret_cast<sockaddr_in*>(ua->Address.lpSockaddr);
|
||||||
|
// Skip APIPA 169.254.x.x — multicast on link-local rarely useful.
|
||||||
|
unsigned char b0 = reinterpret_cast<unsigned char*>(&sin->sin_addr)[0];
|
||||||
|
unsigned char b1 = reinterpret_cast<unsigned char*>(&sin->sin_addr)[1];
|
||||||
|
if (b0 == 169 && b1 == 254) continue;
|
||||||
|
if (b0 == 127) continue;
|
||||||
|
|
||||||
|
char ipStr[INET_ADDRSTRLEN] = {};
|
||||||
|
inet_ntop(AF_INET, &sin->sin_addr, ipStr, sizeof(ipStr));
|
||||||
|
std::string s(ipStr);
|
||||||
|
auto lastDot = s.find_last_of('.');
|
||||||
|
if (lastDot == std::string::npos) continue;
|
||||||
|
|
||||||
|
LocalSubnet net;
|
||||||
|
net.prefix = s.substr(0, lastDot + 1);
|
||||||
|
net.localAddr = sin->sin_addr;
|
||||||
|
inet_pton(AF_INET, (net.prefix + "255").c_str(), &net.broadcast);
|
||||||
|
out.push_back(net);
|
||||||
|
ANS_DBG("ANSDISC", "iface ip=%s subnet=%s/24", ipStr, net.prefix.c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- Parse "<a>:<b>:<name>:<firmware>" reply ----------------------------
|
||||||
|
void ParseUdpReply(const std::string& body, std::string& name, std::string& firmware) {
|
||||||
|
std::vector<std::string> parts;
|
||||||
|
size_t start = 0;
|
||||||
|
for (size_t i = 0; i <= body.size(); ++i) {
|
||||||
|
if (i == body.size() || body[i] == ':') {
|
||||||
|
parts.emplace_back(body.data() + start, i - start);
|
||||||
|
start = i + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (parts.size() > 3) { name = parts[2]; firmware = parts[3]; }
|
||||||
|
else { name = "Unknown"; firmware = "-"; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Parse {"OK":true,"Version":"x"} ------------------------------------
|
||||||
|
// Tiny scan rather than a JSON dependency. Looks for the two keys with any
|
||||||
|
// amount of whitespace; rejects anything that doesn't say "OK":true.
|
||||||
|
bool ParseServerApiJson(const std::string& body, std::string& version) {
|
||||||
|
auto pos = body.find("\"OK\"");
|
||||||
|
if (pos == std::string::npos) return false;
|
||||||
|
pos = body.find(':', pos);
|
||||||
|
if (pos == std::string::npos) return false;
|
||||||
|
++pos;
|
||||||
|
while (pos < body.size() && (body[pos] == ' ' || body[pos] == '\t')) ++pos;
|
||||||
|
if (body.compare(pos, 4, "true") != 0) return false;
|
||||||
|
|
||||||
|
version.clear();
|
||||||
|
pos = body.find("\"Version\"");
|
||||||
|
if (pos == std::string::npos) { version = "-"; return true; }
|
||||||
|
pos = body.find(':', pos);
|
||||||
|
if (pos == std::string::npos) { version = "-"; return true; }
|
||||||
|
pos = body.find('"', pos);
|
||||||
|
if (pos == std::string::npos) { version = "-"; return true; }
|
||||||
|
++pos;
|
||||||
|
auto end = body.find('"', pos);
|
||||||
|
if (end == std::string::npos) { version = "-"; return true; }
|
||||||
|
version = body.substr(pos, end - pos);
|
||||||
|
if (version.empty()) version = "-";
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Shared scan state --------------------------------------------------
|
||||||
|
enum SourceMask { kSrcMulticast = 1, kSrcSweep = 2 };
|
||||||
|
|
||||||
|
struct ScanState {
|
||||||
|
std::mutex mu;
|
||||||
|
std::unordered_map<std::string, ANSCENTER::ANSDeviceInfo> found;
|
||||||
|
std::atomic<bool> stop{false};
|
||||||
|
|
||||||
|
void merge(const std::string& ip, const std::string& name,
|
||||||
|
const std::string& firmware, int srcBit) {
|
||||||
|
std::lock_guard<std::mutex> lk(mu);
|
||||||
|
auto& d = found[ip];
|
||||||
|
if (d.ip.empty()) d.ip = ip;
|
||||||
|
// Prefer non-empty / non-"-" values, regardless of which source ran first.
|
||||||
|
if (!name.empty() && d.name.empty()) d.name = name;
|
||||||
|
if (!firmware.empty() && firmware != "-" &&
|
||||||
|
(d.firmware.empty() || d.firmware == "-")) d.firmware = firmware;
|
||||||
|
else if (!firmware.empty() && d.firmware.empty()) d.firmware = firmware;
|
||||||
|
d.source |= srcBit;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- UDP listener thread -------------------------------------------------
|
||||||
|
// Single socket bound to 0.0.0.0:58838, joined to 230.50.200.150 on every
|
||||||
|
// local interface. Reads with a short timeout so it can poll `stop`.
|
||||||
|
void RunUdpListener(ScanState& state, const std::vector<LocalSubnet>& subnets) {
|
||||||
|
SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||||
|
if (s == INVALID_SOCKET) {
|
||||||
|
ANS_DBG("ANSDISC", "UDP socket() failed err=%d", WSAGetLastError());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
BOOL on = TRUE;
|
||||||
|
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&on), sizeof(on));
|
||||||
|
setsockopt(s, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<char*>(&on), sizeof(on));
|
||||||
|
|
||||||
|
sockaddr_in bindAddr{};
|
||||||
|
bindAddr.sin_family = AF_INET;
|
||||||
|
bindAddr.sin_port = htons(kListenPort);
|
||||||
|
bindAddr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||||
|
if (bind(s, reinterpret_cast<sockaddr*>(&bindAddr), sizeof(bindAddr)) != 0) {
|
||||||
|
ANS_DBG("ANSDISC", "UDP bind :%u failed err=%d", kListenPort, WSAGetLastError());
|
||||||
|
closesocket(s);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Join multicast group on every interface so we receive replies on any path.
|
||||||
|
for (const auto& net : subnets) {
|
||||||
|
ip_mreq mreq{};
|
||||||
|
inet_pton(AF_INET, kMulticastGroup, &mreq.imr_multiaddr);
|
||||||
|
mreq.imr_interface = net.localAddr;
|
||||||
|
if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP,
|
||||||
|
reinterpret_cast<char*>(&mreq), sizeof(mreq)) != 0) {
|
||||||
|
ANS_DBG("ANSDISC", "IP_ADD_MEMBERSHIP on %.*s failed err=%d",
|
||||||
|
static_cast<int>(net.prefix.size() - 1), net.prefix.c_str(),
|
||||||
|
WSAGetLastError());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
char buf[2048];
|
||||||
|
sockaddr_in from{};
|
||||||
|
int fromLen = sizeof(from);
|
||||||
|
while (!state.stop.load(std::memory_order_relaxed)) {
|
||||||
|
fd_set rfds; FD_ZERO(&rfds); FD_SET(s, &rfds);
|
||||||
|
timeval tv{ 0, 200 * 1000 }; // 200 ms
|
||||||
|
int sel = select(0, &rfds, nullptr, nullptr, &tv);
|
||||||
|
if (sel <= 0) continue;
|
||||||
|
int n = recvfrom(s, buf, sizeof(buf), 0,
|
||||||
|
reinterpret_cast<sockaddr*>(&from), &fromLen);
|
||||||
|
if (n <= 0) continue;
|
||||||
|
std::string body(buf, n);
|
||||||
|
if (body == kProbeMessage) continue; // our own echo
|
||||||
|
char ipStr[INET_ADDRSTRLEN] = {};
|
||||||
|
inet_ntop(AF_INET, &from.sin_addr, ipStr, sizeof(ipStr));
|
||||||
|
std::string name, fw;
|
||||||
|
ParseUdpReply(body, name, fw);
|
||||||
|
ANS_DBG("ANSDISC", "UDP reply from %s name=%s fw=%s",
|
||||||
|
ipStr, name.c_str(), fw.c_str());
|
||||||
|
state.merge(ipStr, name, fw, kSrcMulticast);
|
||||||
|
}
|
||||||
|
closesocket(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- UDP sender thread ---------------------------------------------------
|
||||||
|
// Sends "Hello, Multicast" to the multicast group out each interface and
|
||||||
|
// to each subnet broadcast. Repeats every kUdpProbeIntervalMs.
|
||||||
|
void RunUdpSender(ScanState& state, const std::vector<LocalSubnet>& subnets) {
|
||||||
|
SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||||
|
if (s == INVALID_SOCKET) {
|
||||||
|
ANS_DBG("ANSDISC", "sender socket() failed err=%d", WSAGetLastError());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
BOOL on = TRUE;
|
||||||
|
setsockopt(s, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<char*>(&on), sizeof(on));
|
||||||
|
int ttl = kMulticastTtl;
|
||||||
|
setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
|
||||||
|
reinterpret_cast<char*>(&ttl), sizeof(ttl));
|
||||||
|
|
||||||
|
sockaddr_in mc{};
|
||||||
|
mc.sin_family = AF_INET;
|
||||||
|
mc.sin_port = htons(kProbePort);
|
||||||
|
inet_pton(AF_INET, kMulticastGroup, &mc.sin_addr);
|
||||||
|
|
||||||
|
auto sendOnce = [&]() {
|
||||||
|
for (const auto& net : subnets) {
|
||||||
|
// Pin multicast egress to this interface so it leaves each NIC.
|
||||||
|
setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
|
||||||
|
reinterpret_cast<const char*>(&net.localAddr),
|
||||||
|
sizeof(net.localAddr));
|
||||||
|
sendto(s, kProbeMessage, static_cast<int>(strlen(kProbeMessage)), 0,
|
||||||
|
reinterpret_cast<sockaddr*>(&mc), sizeof(mc));
|
||||||
|
sockaddr_in bc{};
|
||||||
|
bc.sin_family = AF_INET;
|
||||||
|
bc.sin_port = htons(kProbePort);
|
||||||
|
bc.sin_addr = net.broadcast;
|
||||||
|
sendto(s, kProbeMessage, static_cast<int>(strlen(kProbeMessage)), 0,
|
||||||
|
reinterpret_cast<sockaddr*>(&bc), sizeof(bc));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
sendOnce();
|
||||||
|
auto next = std::chrono::steady_clock::now() + std::chrono::milliseconds(kUdpProbeIntervalMs);
|
||||||
|
while (!state.stop.load(std::memory_order_relaxed)) {
|
||||||
|
auto now = std::chrono::steady_clock::now();
|
||||||
|
if (now >= next) {
|
||||||
|
sendOnce();
|
||||||
|
next = now + std::chrono::milliseconds(kUdpProbeIntervalMs);
|
||||||
|
} else {
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
closesocket(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- One synchronous HTTP probe via WinHTTP -----------------------------
|
||||||
|
// On AIBOX/ANSVIS reply: out_version is set and returns true. Otherwise false.
|
||||||
|
bool ProbeHttp(const std::string& ip, std::string& out_version) {
|
||||||
|
HINTERNET hSession = WinHttpOpen(kHttpUserAgent,
|
||||||
|
WINHTTP_ACCESS_TYPE_NO_PROXY,
|
||||||
|
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
|
||||||
|
if (!hSession) return false;
|
||||||
|
WinHttpSetTimeouts(hSession,
|
||||||
|
kHttpConnectTimeoutMs, kHttpConnectTimeoutMs,
|
||||||
|
kHttpProbeTimeoutMs, kHttpProbeTimeoutMs);
|
||||||
|
|
||||||
|
std::wstring host(ip.begin(), ip.end());
|
||||||
|
HINTERNET hConn = WinHttpConnect(hSession, host.c_str(),
|
||||||
|
INTERNET_DEFAULT_HTTP_PORT, 0);
|
||||||
|
if (!hConn) { WinHttpCloseHandle(hSession); return false; }
|
||||||
|
|
||||||
|
HINTERNET hReq = WinHttpOpenRequest(hConn, L"GET", kHttpPath,
|
||||||
|
nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
|
||||||
|
if (!hReq) {
|
||||||
|
WinHttpCloseHandle(hConn); WinHttpCloseHandle(hSession);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ok = false;
|
||||||
|
if (WinHttpSendRequest(hReq, L"Accept: application/json\r\n", static_cast<DWORD>(-1L),
|
||||||
|
WINHTTP_NO_REQUEST_DATA, 0, 0, 0) &&
|
||||||
|
WinHttpReceiveResponse(hReq, nullptr))
|
||||||
|
{
|
||||||
|
DWORD status = 0, statusSize = sizeof(status);
|
||||||
|
if (WinHttpQueryHeaders(hReq,
|
||||||
|
WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
|
||||||
|
WINHTTP_HEADER_NAME_BY_INDEX, &status, &statusSize,
|
||||||
|
WINHTTP_NO_HEADER_INDEX) && status == 200)
|
||||||
|
{
|
||||||
|
std::string body;
|
||||||
|
DWORD avail = 0;
|
||||||
|
// Cap body at 64 KB — /ServerApi is a few hundred bytes.
|
||||||
|
while (body.size() < 65536 && WinHttpQueryDataAvailable(hReq, &avail) && avail) {
|
||||||
|
std::vector<char> buf(avail);
|
||||||
|
DWORD read = 0;
|
||||||
|
if (!WinHttpReadData(hReq, buf.data(), avail, &read)) break;
|
||||||
|
body.append(buf.data(), read);
|
||||||
|
}
|
||||||
|
ok = ParseServerApiJson(body, out_version);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WinHttpCloseHandle(hReq);
|
||||||
|
WinHttpCloseHandle(hConn);
|
||||||
|
WinHttpCloseHandle(hSession);
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- HTTP sweep: 64-way worker pool consuming a queue of IPs ------------
|
||||||
|
void RunHttpSweep(ScanState& state, const std::vector<LocalSubnet>& subnets) {
|
||||||
|
std::queue<std::string> q;
|
||||||
|
for (const auto& net : subnets) {
|
||||||
|
for (int h = 1; h <= 254; ++h) {
|
||||||
|
q.push(net.prefix + std::to_string(h));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ANS_DBG("ANSDISC", "HTTP sweep targets=%zu workers=%d", q.size(), kHttpConcurrency);
|
||||||
|
|
||||||
|
std::mutex qmu;
|
||||||
|
auto worker = [&]() {
|
||||||
|
for (;;) {
|
||||||
|
if (state.stop.load(std::memory_order_relaxed)) return;
|
||||||
|
std::string ip;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lk(qmu);
|
||||||
|
if (q.empty()) return;
|
||||||
|
ip = std::move(q.front());
|
||||||
|
q.pop();
|
||||||
|
}
|
||||||
|
std::string ver;
|
||||||
|
if (ProbeHttp(ip, ver)) {
|
||||||
|
ANS_DBG("ANSDISC", "HTTP hit %s version=%s", ip.c_str(), ver.c_str());
|
||||||
|
state.merge(ip, std::string(), ver, kSrcSweep);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
std::vector<std::thread> pool;
|
||||||
|
pool.reserve(kHttpConcurrency);
|
||||||
|
for (int i = 0; i < kHttpConcurrency; ++i) pool.emplace_back(worker);
|
||||||
|
for (auto& t : pool) t.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
} // anonymous namespace
|
||||||
|
|
||||||
|
namespace ANSCENTER {
|
||||||
|
|
||||||
|
std::vector<ANSDeviceInfo> ANSUtilities::ScanDevices(int timeoutMs) {
|
||||||
|
if (timeoutMs < 500) timeoutMs = 500; // floor: enough for one UDP burst
|
||||||
|
|
||||||
|
ANS_DBG("ANSDISC", "ScanDevices: enter timeoutMs=%d", timeoutMs);
|
||||||
|
WsaScope wsa;
|
||||||
|
if (!wsa.ok) {
|
||||||
|
ANS_DBG("ANSDISC", "WSAStartup failed");
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto subnets = EnumerateLocalSubnets();
|
||||||
|
if (subnets.empty()) {
|
||||||
|
ANS_DBG("ANSDISC", "no usable IPv4 interfaces; aborting scan");
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
ScanState state;
|
||||||
|
|
||||||
|
std::thread tListen([&]{ RunUdpListener(state, subnets); });
|
||||||
|
std::thread tSend ([&]{ RunUdpSender (state, subnets); });
|
||||||
|
std::thread tSweep ([&]{ RunHttpSweep (state, subnets); });
|
||||||
|
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(timeoutMs));
|
||||||
|
state.stop.store(true, std::memory_order_relaxed);
|
||||||
|
|
||||||
|
tListen.join();
|
||||||
|
tSend.join();
|
||||||
|
tSweep.join();
|
||||||
|
|
||||||
|
std::vector<ANSDeviceInfo> result;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lk(state.mu);
|
||||||
|
result.reserve(state.found.size());
|
||||||
|
for (auto& kv : state.found) result.push_back(std::move(kv.second));
|
||||||
|
}
|
||||||
|
ANS_DBG("ANSDISC", "ScanDevices: exit found=%zu", result.size());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace ANSCENTER
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,14 @@
|
|||||||
#include <functional>
|
#include <functional>
|
||||||
|
|
||||||
namespace ANSCENTER {
|
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 source{ 0 }; // 1 = multicast, 2 = HTTP sweep, 3 = both
|
||||||
|
};
|
||||||
|
|
||||||
class ANSULT_API ANSUtilities {
|
class ANSULT_API ANSUtilities {
|
||||||
private:
|
private:
|
||||||
// Protects all shared mutable data
|
// Protects all shared mutable data
|
||||||
@@ -144,6 +152,20 @@ namespace ANSCENTER {
|
|||||||
// Unescape double-escaped Unicode: "Th\\u1ee7y" becomes "Th\u1ee7y".
|
// Unescape double-escaped Unicode: "Th\\u1ee7y" becomes "Th\u1ee7y".
|
||||||
// Reverses DoubleEscapeUnicode so other languages can parse \uXXXX correctly.
|
// Reverses DoubleEscapeUnicode so other languages can parse \uXXXX correctly.
|
||||||
static std::string UnescapeDoubleEscapedUnicode(const std::string& str);
|
static std::string UnescapeDoubleEscapedUnicode(const std::string& str);
|
||||||
|
|
||||||
|
// 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
|
// Connection bundle for pool
|
||||||
struct S3Connection {
|
struct S3Connection {
|
||||||
@@ -345,6 +367,13 @@ extern "C" ANSULT_API int SendEmail(const char* smtpServer, int port,
|
|||||||
|
|
||||||
extern "C" ANSULT_API int RebootSystem();
|
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);
|
||||||
|
|
||||||
// Unicode conversion utilities for LabVIEW
|
// Unicode conversion utilities for LabVIEW
|
||||||
extern "C" ANSULT_API int ANSConvertUTF8ToUTF16LE(const char* utf8Str, LStrHandle result, int includeBOM = 1);
|
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 ANSDecodeJsonUnicodeToUTF16LE(const char* escapedStr, LStrHandle result);
|
||||||
|
|||||||
@@ -21,7 +21,9 @@ target_link_libraries(ANSUtilities
|
|||||||
)
|
)
|
||||||
|
|
||||||
if(WIN32)
|
if(WIN32)
|
||||||
target_link_libraries(ANSUtilities PRIVATE ${WIN_COMMON_LIBS} crypt32)
|
# WIN_COMMON_LIBS covers ws2_32, iphlpapi, etc. winhttp is needed for the
|
||||||
|
# ScanDevices HTTP /ServerApi sweep.
|
||||||
|
target_link_libraries(ANSUtilities PRIVATE ${WIN_COMMON_LIBS} crypt32 winhttp)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
target_compile_definitions(ANSUtilities PRIVATE UNICODE _UNICODE ANSUTILITIES_EXPORTS)
|
target_compile_definitions(ANSUtilities PRIVATE UNICODE _UNICODE ANSUTILITIES_EXPORTS)
|
||||||
|
|||||||
@@ -2973,3 +2973,81 @@ extern "C" ANSULT_API int DownloadFileStreamANSAWSHandle_V2(uint64_t handleVal,
|
|||||||
catch (std::exception& e) { return 0; }
|
catch (std::exception& e) { return 0; }
|
||||||
catch (...) { return 0; }
|
catch (...) { return 0; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// ScanANSDevices — discover AIBOX / ANSVIS servers on the local network.
|
||||||
|
// Returns 1 on success (resultJson populated, possibly with empty "[]"), 0
|
||||||
|
// on internal failure. The static C++ method does its own license/error
|
||||||
|
// handling; this wrapper just serializes the device list to JSON.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
static std::string JsonEscape(const std::string& s) {
|
||||||
|
std::string out;
|
||||||
|
out.reserve(s.size() + 2);
|
||||||
|
for (char c : s) {
|
||||||
|
switch (c) {
|
||||||
|
case '"': out += "\\\""; break;
|
||||||
|
case '\\': out += "\\\\"; break;
|
||||||
|
case '\n': out += "\\n"; break;
|
||||||
|
case '\r': out += "\\r"; break;
|
||||||
|
case '\t': out += "\\t"; break;
|
||||||
|
default:
|
||||||
|
if (static_cast<unsigned char>(c) < 0x20) {
|
||||||
|
char buf[8];
|
||||||
|
snprintf(buf, sizeof(buf), "\\u%04x", static_cast<unsigned char>(c));
|
||||||
|
out += buf;
|
||||||
|
} else {
|
||||||
|
out += c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string DevicesToJson(const std::vector<ANSCENTER::ANSDeviceInfo>& devs) {
|
||||||
|
std::string j = "[";
|
||||||
|
for (size_t i = 0; i < devs.size(); ++i) {
|
||||||
|
if (i) j += ',';
|
||||||
|
j += "{\"ip\":\""; j += JsonEscape(devs[i].ip); j += "\",";
|
||||||
|
j += "\"name\":\""; j += JsonEscape(devs[i].name); j += "\",";
|
||||||
|
j += "\"firmware\":\""; j += JsonEscape(devs[i].firmware); j += "\",";
|
||||||
|
j += "\"source\":"; j += std::to_string(devs[i].source);
|
||||||
|
j += '}';
|
||||||
|
}
|
||||||
|
j += ']';
|
||||||
|
return j;
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" ANSULT_API int ScanANSDevicesCpp(int timeoutMs, std::string& resultJson) {
|
||||||
|
ANS_DBG("ANSUTIL", "ScanANSDevicesCpp: timeoutMs=%d", timeoutMs);
|
||||||
|
try {
|
||||||
|
auto devs = ANSCENTER::ANSUtilities::ScanDevices(timeoutMs);
|
||||||
|
resultJson = DevicesToJson(devs);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
catch (const std::exception& e) {
|
||||||
|
ANS_DBG("ANSUTIL", "ScanANSDevicesCpp threw: %s", e.what());
|
||||||
|
resultJson = "[]";
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
catch (...) {
|
||||||
|
ANS_DBG("ANSUTIL", "ScanANSDevicesCpp threw unknown");
|
||||||
|
resultJson = "[]";
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" ANSULT_API int ScanANSDevices(int timeoutMs, LStrHandle resultJson) {
|
||||||
|
ANS_DBG("ANSUTIL", "ScanANSDevices: timeoutMs=%d", timeoutMs);
|
||||||
|
if (!resultJson) return -1;
|
||||||
|
try {
|
||||||
|
std::string j;
|
||||||
|
ScanANSDevicesCpp(timeoutMs, j);
|
||||||
|
int size = static_cast<int>(j.size());
|
||||||
|
MgErr error = DSSetHandleSize(resultJson, sizeof(int32) + size * sizeof(uChar));
|
||||||
|
if (error != noErr) return -2;
|
||||||
|
(*resultJson)->cnt = size;
|
||||||
|
if (size > 0) memcpy((*resultJson)->str, j.data(), size);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
catch (...) { return -1; }
|
||||||
|
}
|
||||||
|
|||||||
@@ -386,6 +386,39 @@ int ANSLLMOllamaTest() {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Exercise ANSCENTER::ANSUtilities::ScanDevices — discovers AIBOX boxes and
|
||||||
|
// ANSVIS servers on the local LAN via UDP multicast + HTTP /ServerApi sweep.
|
||||||
|
// Run on a machine connected to the same subnet as at least one device.
|
||||||
|
// DebugView (filter "[ANSDISC]") shows per-device hits and per-interface joins.
|
||||||
|
int ScanDevicesTest()
|
||||||
|
{
|
||||||
|
std::cout << "\n===== ScanDevices (AIBOX / ANSVIS discovery) =====" << std::endl;
|
||||||
|
|
||||||
|
// 1) Direct static C++ call.
|
||||||
|
const int timeoutMs = 5000;
|
||||||
|
std::cout << "Scanning for " << timeoutMs << " ms ..." << std::endl;
|
||||||
|
auto devices = ANSCENTER::ANSUtilities::ScanDevices(timeoutMs);
|
||||||
|
|
||||||
|
std::cout << "Found " << devices.size() << " device(s):" << std::endl;
|
||||||
|
for (const auto& d : devices) {
|
||||||
|
const char* src = (d.source == 3) ? "both"
|
||||||
|
: (d.source == 2) ? "sweep"
|
||||||
|
: (d.source == 1) ? "multicast"
|
||||||
|
: "unknown";
|
||||||
|
std::cout << " " << d.ip
|
||||||
|
<< " name=\"" << d.name << "\""
|
||||||
|
<< " firmware=\"" << d.firmware << "\""
|
||||||
|
<< " source=" << src << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) Exercise the C extern entrypoint that LabVIEW uses.
|
||||||
|
std::string json;
|
||||||
|
int rc = ScanANSDevicesCpp(timeoutMs, json);
|
||||||
|
std::cout << "\nScanANSDevicesCpp rc=" << rc << " json=" << json << std::endl;
|
||||||
|
|
||||||
|
return static_cast<int>(devices.size());
|
||||||
|
}
|
||||||
|
|
||||||
int main()
|
int main()
|
||||||
{
|
{
|
||||||
//ANSLLMOllamaTest();
|
//ANSLLMOllamaTest();
|
||||||
@@ -393,11 +426,13 @@ int main()
|
|||||||
//std::cout << "===== MinIO (path-style) =====" << std::endl;
|
//std::cout << "===== MinIO (path-style) =====" << std::endl;
|
||||||
//ANSFTechMinIOTest();
|
//ANSFTechMinIOTest();
|
||||||
|
|
||||||
std::cout << "\n===== AWS S3 (virtual-host) =====" << std::endl;
|
//std::cout << "\n===== AWS S3 (virtual-host) =====" << std::endl;
|
||||||
ANSAWSTest();
|
//ANSAWSTest();
|
||||||
//ANSLLMTest();
|
//ANSLLMTest();
|
||||||
//SendEmailExample();
|
//SendEmailExample();
|
||||||
//uploadFileToGoogleStorage();
|
//uploadFileToGoogleStorage();
|
||||||
// EncrypyionExample();
|
// EncrypyionExample();
|
||||||
|
|
||||||
|
ScanDevicesTest();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user