I have managed to link separate ANT interface programme and Unity in C# to link to a turbo and heart rate monitor. It uses a Memory Mapped File. Because the link is just data in the MMF, it doesn't matter that ANT is X86 and Unity is X64. It isn't an elegant solution but it works. Here's the relevant code in the ANT programme. The code in Unity is pretty similar. I pass gradient (to control the turbo) one way and power, heart rate and cadence the other way. Hopefully this is enough to get anyone who wants to try this method started. I always start the ANT programme from Unity before trying to read data in Unity. The hardest part was working out that it could be done this way!
As a side issue. When I first did this, I found my link to the Elite Turbo kept dropping out. The trick to prevent this was to send something to the turbo every few seconds minimum because anything over 10 seconds between talking to the turbo and it would drop the connection. I use 293 milliseconds, ie something out of sync with ANT's messages.
using System.IO.MemoryMappedFiles;
using System.Threading;
static MemoryMappedFile mmf;
static Mutex mutex;
static bool mutexCreated;
static void StartMemoryMappedFile()
{
try
{
mmf = MemoryMappedFile.OpenExisting("testmap");
}
catch
{
mmf = MemoryMappedFile.CreateNew("testmap", 30);
}
try
{
mutex = new Mutex(true, "testmapmutex", out mutexCreated);
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(1);
}
mutex.ReleaseMutex();
}
catch { }
}
static void WriteToMappedFile(float heartRate, float powerW, float cadence, float gradientPct)
{
mutex.WaitOne();
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(heartRate);
writer.Write(powerW);
writer.Write(cadence);
writer.Write(gradientPct);
}
mutex.ReleaseMutex();
}
static void ReadFromMappedFile(ref float heartRate, ref float powerW, ref float cadence, ref float gradientPct)
{
mutex.WaitOne();
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
BinaryReader reader = new BinaryReader(stream);
heartRate = reader.ReadSingle();
powerW = reader.ReadSingle();
cadence = reader.ReadSingle();
gradientPct = reader.ReadSingle();
}
mutex.ReleaseMutex();
}
static void WriteHeartRateToMappedFile(float newHheartRate)
{
float heartRate = 0;
float powerW = 0;
float cadence = 0;
float gradientPct = 0;
ReadFromMappedFile(ref heartRate, ref powerW, ref cadence, ref gradientPct);
WriteToMappedFile(newHheartRate, powerW, cadence, gradientPct);
}
static void WriteTurboToMappedFile(float newPowerW, float newCadence)
{
float heartRate = 0;
float powerW = 0;
float cadence = 0;
float gradientPct = 0;
ReadFromMappedFile(ref heartRate, ref powerW, ref cadence, ref gradientPct);
WriteToMappedFile(heartRate, newPowerW, newCadence, gradientPct);
}