Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions .github/workflows/antserver.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
name: AntServer (Windows)

# Builds antserver.exe (the ANT+ server that the desktop app ships as AntServer.bin) from antserver/.
#
# The binary has to keep using the same shared libraries as the one shipped with the desktop app
# (MSVCP140.dll / VCRUNTIME140.dll from the VS2015 runtime, libusb0.dll and the SiLabs DLLs that are
# loaded at runtime). Therefore the build uses the same SDK sources from this repo and pins the
# MSVC v140 toolset instead of the toolset of the runner image, and the job fails if the binary imports
# a newer runtime.

on:
workflow_dispatch:
pull_request:
paths:
- 'antserver/**'
- '.github/workflows/antserver.yml'
push:
branches: [master]
paths:
- 'antserver/**'
- '.github/workflows/antserver.yml'

jobs:
build:
runs-on: windows-2022
timeout-minutes: 45

steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4

- uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # v2

- name: Install MSVC v140 toolset
shell: pwsh
run: |
$installer = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer"
$vs = & "$installer\vswhere.exe" -latest -property installationPath
$proc = Start-Process -FilePath "$installer\vs_installer.exe" -Wait -PassThru -ArgumentList @(
'modify', '--installPath', "`"$vs`"",
'--add', 'Microsoft.VisualStudio.Component.VC.140',
'--quiet', '--norestart', '--nocache')
# 3010 = success, reboot required
if ($proc.ExitCode -ne 0 -and $proc.ExitCode -ne 3010) { throw "installing the v140 toolset failed: $($proc.ExitCode)" }

- name: Build antserver.exe (Release, x86, v140)
shell: pwsh
run: |
# v140 defaults to the Windows 8.1 SDK, which is not on the runner. Use the newest Windows 10 SDK
# that the 2015 compiler can still parse: the headers of 10.0.22000 and newer need intrinsics
# (_mm_loadu_si64) that v140 does not have.
$sdk = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\Include" -Directory |
Where-Object { $_.Name -match '^10\.' -and [version]$_.Name -lt [version]'10.0.22000.0' } |
Sort-Object { [version]$_.Name } | Select-Object -Last 1
if (-not $sdk) { throw 'no Windows 10 SDK older than 10.0.22000 on this runner' }
Write-Host "Windows SDK: $($sdk.Name)"
msbuild antserver\ANT_Libraries.sln /m /nologo /p:Configuration=Release /p:Platform=x86 `
/p:PlatformToolset=v140 /p:WindowsTargetPlatformVersion=$($sdk.Name)
if ($LASTEXITCODE -ne 0) { throw 'build failed' }

- name: Check the shared libraries the binary depends on
shell: pwsh
run: |
$vsPath = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -property installationPath
$dumpbin = Get-ChildItem "$vsPath\VC\Tools\MSVC" -Recurse -Filter dumpbin.exe |
Where-Object { $_.FullName -match 'Hostx64\\x64' } | Select-Object -First 1
$out = & $dumpbin.FullName /dependents antserver\Release\antserver.exe
$deps = $out | Where-Object { $_ -match '^\s+\S+\.dll\s*$' } | ForEach-Object { $_.Trim() }
$deps | Tee-Object -FilePath dependencies.txt
# the desktop app ships MSVCP140.dll and VCRUNTIME140.dll of the VS2015 runtime only
$newer = $deps | Where-Object { $_ -match '(?i)^(vcruntime140_\d|msvcp140_\d|concrt|vcomp|msvcr)' }
if ($newer) { throw "binary depends on runtime libraries that the desktop app does not ship: $newer" }

- name: Smoke test (no ANT+ stick needed)
shell: pwsh
run: |
# the server echoes every request as debug/<request>; the host uses the echo of ping/<ts> as heartbeat
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = (Resolve-Path antserver\Release\antserver.exe).Path
$psi.RedirectStandardInput = $true
$psi.RedirectStandardOutput = $true
$psi.UseShellExecute = $false
$p = [System.Diagnostics.Process]::Start($psi)

function Send([string]$line) {
$p.StandardInput.WriteLine($line)
$p.StandardInput.Flush()
}

# returns the first output line that starts with the given prefix (the echo of the request comes first)
function Wait-Line([string]$prefix) {
$deadline = [DateTime]::UtcNow.AddSeconds(20)
while ($true) {
$left = [int]($deadline - [DateTime]::UtcNow).TotalMilliseconds
$read = $p.StandardOutput.ReadLineAsync()
if ($left -le 0 -or -not $read.Wait($left)) { $p.Kill(); throw "no output line starting with '$prefix'" }
if ($null -eq $read.Result) { throw 'server closed its output' }
if ($read.Result.StartsWith($prefix)) { return $read.Result }
}
}

Send 'ping/42'
Wait-Line 'debug/ping/42' | Out-Null

# open and close the device twice. There is no stick on the runner, so open fails, but it has to answer,
# release what it created and must not crash when it is opened again
foreach ($id in 1..4) {
if ($id % 2 -eq 1) { Send "request/$id/open/0" } else { Send "request/$id/close" }
Write-Host (Wait-Line "response/$id/")
}

Send 'ping/43'
Wait-Line 'debug/ping/43' | Out-Null

$p.StandardInput.Close()
if (-not $p.WaitForExit(5000)) { $p.Kill(); throw 'server did not exit after stdin was closed' }

- name: Package
shell: pwsh
run: |
New-Item -ItemType Directory -Force dist | Out-Null
Copy-Item antserver\Release\antserver.exe dist\ANTserver.bin
Copy-Item dependencies.txt dist\dependencies.txt
Get-FileHash dist\ANTserver.bin -Algorithm SHA256 | ForEach-Object { "$($_.Hash) ANTserver.bin" } | Set-Content dist\ANTserver.bin.sha256

- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: ANTserver.bin
path: dist/
if-no-files-found: error
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Use [Zadig](http://sourceforge.net/projects/libwdi/files/zadig/) to install the

__Using the AntServerBinding binding__

The `antserver.exe` needs to be deployed together with your app. You can find a pre-compiled version in the [./bin](./bin) directory, or you can compile it yourself based on the sources provided in the [./antserver](./antserver) directory
The `ANTServer.exe` needs to be deployed together with your app. You can find a pre-compiled version in the [./bin](./bin) directory, or you can compile it yourself based on the sources provided in the [./antserver](./antserver) directory


## Install
Expand Down
26 changes: 7 additions & 19 deletions antserver/ANT_LIB/software/serial/dsi_framer_ant.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ All rights reserved.
#include "checksum.h"
#include "dsi_thread.h"
#include "dsi_framer_ant.hpp"
#include "server_output.hpp"

#include <string>
#include <iostream>
Expand Down Expand Up @@ -2241,26 +2242,13 @@ void DSIFramerANT::ProcessMessage(void)
}
else
{
// Add message to the queue.
if ((USHORT)(usMessageHead - usMessageTail) < (USHORT)(sizeof(astMessageBuffer) / sizeof(ANT_MESSAGE_ITEM) - 1))
{
ucSize += (MESG_FRAME_SIZE - MESG_SYNC_SIZE);
astMessageBuffer[usMessageHead].ucSize = ucSize;
astMessageBuffer[usMessageHead].stANTMessage.ucMessageID = ucMessageID;
memcpy(astMessageBuffer[usMessageHead].stANTMessage.aucData, &aucRxFifo[0], ucSize);
usMessageHead++; // Rollover of usMessageHead happens automagically because our buffer size is MAX_USHORT + 1.

ucSize += (MESG_FRAME_SIZE - MESG_SYNC_SIZE);

cout << "message/";
for (int i = 0; i < ucSize; ++i)
cout << std::setfill('0') << std::setw(2) << std::hex << (int)aucRxFifo[i];
cout << "\n";

}
else
{
ucError = DSI_FRAMER_ANT_EQUEUE_OVERFLOW;
}
// The ANT server hands every message to its host application right away. Nobody reads the
// message queue (WaitForMessage() is never called), so the message must not be queued: the queue
// would be full after 65535 messages (about an hour with four sensors) and from then on no
// message would be forwarded any more, while the USB stick keeps receiving.
serverWriteMessage(aucRxFifo, ucSize);

DSIThread_CondSignal(&stCondMessageReady);

Expand Down
41 changes: 41 additions & 0 deletions antserver/ANT_LIB/software/serial/server_output.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#ifndef SERVER_OUTPUT_HPP
#define SERVER_OUTPUT_HPP

#include <iomanip>
#include <iostream>
#include <mutex>
#include <sstream>
#include <string>

// Everything the ANT server tells its host application is written to stdout, one line per message.
//
// stdout is written from more than one thread: the thread that reads the requests from stdin
// (responses, debug echo) and the thread that receives from the USB stick (messages).
// A line must therefore be written in one piece, otherwise two lines get mixed up and the host
// sees truncated messages ("Illegal message").

inline std::mutex& serverOutputMutex()
{
static std::mutex mutex;
return mutex;
}

// Writes one complete line to stdout and flushes it
inline void serverWriteLine(const std::string& line)
{
std::lock_guard<std::mutex> lock(serverOutputMutex());
std::cout << line << "\n";
std::cout.flush();
}

// Forwards a received ANT message to the host as "message/<hex>"
inline void serverWriteMessage(const unsigned char* data, size_t size)
{
std::ostringstream line;
line << "message/" << std::hex << std::setfill('0');
for (size_t i = 0; i < size; ++i)
line << std::setw(2) << static_cast<int>(data[i]);
serverWriteLine(line.str());
}

#endif // SERVER_OUTPUT_HPP
61 changes: 31 additions & 30 deletions antserver/Server/antserver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ All rights reserved.
#include "dsi_thread.h"
#include "dsi_serial_generic.hpp"
#include "dsi_debug.hpp"
#include "server_output.hpp"

#include <stdio.h>
#include <assert.h>
Expand Down Expand Up @@ -95,44 +96,40 @@ void readHex(char* buf, const char* txt) {
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
// The server is deliberately not deleted: it lives until the process ends and the process exit
// releases everything, there is nothing to gain from stopping the USB receive thread first.
Server* pclDemo = new Server();
pclDemo->WaitForInput();
return 0;
return 0; // NOSONAR
}

// The members of Server are initialized where they are declared, see antserver.h

////////////////////////////////////////////////////////////////////////////////
// Server
// ~Server
//
// Constructor, intializes Demo class
// Destructor, clean up and loose memory
//
////////////////////////////////////////////////////////////////////////////////
Server::Server()
Server::~Server()
{
ucChannelType = CHANNEL_TYPE_INVALID;
pclSerialObject = (DSISerialGeneric*)NULL;
pclMessageObject = (DSIFramerANT*)NULL;
uiDSIThread = (DSI_THREAD_ID)NULL;
bMyDone = FALSE;
bDone = FALSE;
bDisplay = TRUE;
bBroadcasting = FALSE;

memset(aucTransmitBuffer,0,ANT_STANDARD_DATA_PAYLOAD_SIZE);
ReleaseDevice();
}

////////////////////////////////////////////////////////////////////////////////
// ~Server
// ReleaseDevice
//
// Destructor, clean up and loose memory
// The receive thread of the USB stick reports to the framer, so the thread has to
// be stopped before the framer is destroyed.
//
////////////////////////////////////////////////////////////////////////////////
Server::~Server()
void Server::ReleaseDevice()
{
if(pclMessageObject)
delete pclMessageObject;

if(pclSerialObject)
delete pclSerialObject;
pclSerialObject->Close();

pclMessageObject.reset();
pclSerialObject.reset();
}

////////////////////////////////////////////////////////////////////////////////
Expand All @@ -148,7 +145,8 @@ void Server::WaitForInput() {
vector<string> res;
string delimiter = "/";

cout << "debug/" << line << "\n";
// echo of every request: the host uses the echo of its "ping/<ts>" requests to see that this server is alive
serverWriteLine("debug/" + line);

size_t pos_start = 0, pos_end, delim_len = delimiter.length();
std::string token;
Expand All @@ -169,20 +167,20 @@ void Server::WaitForInput() {
if (cmd == "open") {

BOOL opened = Init(stoi(res[3]), 0);
std::cout << "response/" << id << "/" << (opened? "true": "false") << "\n";
serverWriteLine("response/" + id + "/" + (opened? "true": "false"));
}
else if (cmd == "close") {

Close();
std::cout << "response/" << id << "/" << "\n";
serverWriteLine("response/" + id + "/");
}
//printf("response/%s/%s\n", id, "true");
//}

}
else if (res[0] == "message") {
if (pclMessageObject == NULL) {
cout << "error/channel_not_opened\n";
if (!pclMessageObject) {
serverWriteLine("error/channel_not_opened");
}
else {
const string data = res[1];
Expand Down Expand Up @@ -215,11 +213,14 @@ void Server::WaitForInput() {
// If not specified, 2 is passed in as invalid.
//
////////////////////////////////////////////////////////////////////////////////
BOOL Server::Init(UCHAR ucDeviceNumber_, UCHAR ucChannelType_)
BOOL Server::Init(UCHAR ucDeviceNumber_, UCHAR /*ucChannelType_*/)
{

BOOL bStatus;

// A previous open (that was not closed, or whose open failed) must not leak its objects
ReleaseDevice();

// Initialize condition var and mutex
UCHAR ucCondInit = DSIThread_CondInit(&condTestDone);
assert(ucCondInit == DSI_THREAD_ENONE);
Expand All @@ -228,7 +229,7 @@ BOOL Server::Init(UCHAR ucDeviceNumber_, UCHAR ucChannelType_)
assert(ucMutexInit == DSI_THREAD_ENONE);

// Create Serial object.
pclSerialObject = new DSISerialGeneric();
pclSerialObject = std::make_unique<DSISerialGeneric>();
assert(pclSerialObject);


Expand All @@ -243,15 +244,15 @@ BOOL Server::Init(UCHAR ucDeviceNumber_, UCHAR ucChannelType_)
assert(bStatus);

// Create Framer object.
pclMessageObject = new DSIFramerANT(pclSerialObject);
pclMessageObject = std::make_unique<DSIFramerANT>(pclSerialObject.get());
assert(pclMessageObject);

// Initialize Framer object.
bStatus = pclMessageObject->Init();
assert(bStatus);

// Let Serial know about Framer.
pclSerialObject->SetCallback(pclMessageObject);
pclSerialObject->SetCallback(pclMessageObject.get());

// Open Serial.
bStatus = pclSerialObject->Open();
Expand Down
Loading