using UnityEngine; using System.Collections.Generic; using ANT_Managed_Library; using System; public struct HRSensorData { public float HeartRate; } public class HrReceiver { private AntChannel backgroundScanChannel; private AntChannel deviceChannel; private HRSensorData sensorData; public int DeviceID { get; } = 0; public bool Connected { get; private set; } = false; public List ScanResult { get; private set; } public HRSensorData SensorData => sensorData; public HrReceiver() { } public HrReceiver(int deviceID) => this.DeviceID = deviceID; //Start a background Scan to find the device public void StartScan() { Debug.Log("Looking for ANT + HeartRate sensor"); AntManager.Instance.Init(); ScanResult = new List(); backgroundScanChannel = AntManager.Instance.OpenBackgroundScanChannel(0); backgroundScanChannel.onReceiveData += ReceivedBackgroundScanData; } void ReceivedBackgroundScanData(Byte[] data) { byte deviceType = (data[12]); // extended info Device Type byte switch (deviceType) { case AntplusDeviceType.HeartRate: { int deviceNumber = (data[10]) | data[11] << 8; byte transType = data[13]; foreach (AntDevice d in ScanResult) { if (d.deviceNumber == deviceNumber && d.transType == transType) //device already found return; } AntDevice foundDevice = new AntDevice(); foundDevice.deviceType = deviceType; foundDevice.deviceNumber = deviceNumber; foundDevice.transType = transType; foundDevice.period = 8070; foundDevice.radiofreq = 57; foundDevice.name = "heartrate(" + foundDevice.deviceNumber + ")"; ScanResult.Add(foundDevice); if (deviceNumber == DeviceID) { Debug.Log($"Desired HR Sensor with id {deviceNumber} found!"); ConnectToDevice(foundDevice); } else { Debug.Log($"HR sensor ({deviceNumber}) found and added to ScanResult"); } break; } } } void ConnectToDevice(AntDevice device) { AntManager.Instance.CloseBackgroundScanChannel(); byte channelID = AntManager.Instance.GetFreeChannelID(); deviceChannel = AntManager.Instance.OpenChannel(ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00, channelID, (ushort) device.deviceNumber, device.deviceType, device.transType, (byte) device.radiofreq, (ushort) device.period, false); Connected = true; deviceChannel.onReceiveData += Data; deviceChannel.onChannelResponse += ChannelResponse; deviceChannel.hideRXFAIL = true; } //Deal with the received Data private void Data(Byte[] data) { sensorData.HeartRate = (data[7]); } void ChannelResponse(ANT_Response response) { } }