using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Sensors.ANT { public abstract class AwaitDevice { public abstract int DeviceId { get; } public abstract bool Connected { get; } public abstract void Connect(AntDevice device); } public class AntDevices { #region singleton private static readonly Lazy Lazy = new Lazy (() => new AntDevices()); public static AntDevices Instance => Lazy.Value; #endregion public List ScanResult { get; private set; } private List awaitDevices; private AntChannel backgroundScanChannel; public void StartScan(List devices) { awaitDevices = devices; if (backgroundScanChannel != null) backgroundScanChannel.Close(); Debug.Log("Looking for ANT + Sensors"); AntManager.Instance.Init(); ScanResult = new List(); backgroundScanChannel = AntManager.Instance.OpenBackgroundScanChannel(0); backgroundScanChannel.onReceiveData += ReceivedBackgroundScanData; } private void ReceivedBackgroundScanData(byte[] data) { var deviceType = data[12]; // extended info Device Type byte var deviceNumber = data[10] | (data[11] << 8); var transType = data[13]; int period = -1; int radioFreq = -1; String deviceTypeName =""; switch (deviceType) { case AntplusDeviceType.BikePower: period = 8182; radioFreq = 57; deviceTypeName = "Power"; break; case AntplusDeviceType.BikeSpeed: period = 8118; radioFreq = 57; deviceTypeName = "Speed"; break; case AntplusDeviceType.HeartRate: period = 8070; radioFreq = 57; deviceTypeName = "HR"; break; } if (period < 0) { //Debug.Log($"Device type {deviceType} not supported"); return; } if (ScanResult.Any(d => d.deviceNumber == deviceNumber && d.transType == transType)) { return; } var foundDevice = new AntDevice { deviceType = deviceType, deviceNumber = deviceNumber, transType = transType, period = period, radiofreq = radioFreq }; foundDevice.name = $"{deviceTypeName}(" + foundDevice.deviceNumber + ")"; Debug.Log($"Found device: {foundDevice.name}"); ScanResult.Add(foundDevice); awaitDevices.FirstOrDefault(d => d.DeviceId == foundDevice.deviceNumber)?.Connect(foundDevice); if (awaitDevices.TrueForAll(d => d.Connected)) { Debug.Log("All desired devices found. Closing background scan channel;"); backgroundScanChannel.Close(); } } } }