123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- 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<AntDevices>
- Lazy =
- new Lazy<AntDevices>
- (() => new AntDevices());
- public static AntDevices Instance => Lazy.Value;
- #endregion
- public List<AntDevice> ScanResult { get; private set; }
- private List<AwaitDevice> awaitDevices;
- private AntChannel backgroundScanChannel;
- public void StartScan(List<AwaitDevice> devices)
- {
- awaitDevices = devices;
- if (backgroundScanChannel != null) backgroundScanChannel.Close();
- Debug.Log("Looking for ANT + Sensors");
- AntManager.Instance.Init();
- ScanResult = new List<AntDevice>();
- 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();
- }
- }
- }
- }
|