123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- using System.Collections.Generic;
- using ANT_Managed_Library;
- using UnityEngine;
- namespace Sensors.ANT
- {
- public struct HrSensorData
- {
- public float HeartRate;
- }
- public class HrReceiver
- {
- private AntChannel backgroundScanChannel;
- private AntChannel deviceChannel;
- private HrSensorData sensorData;
- public HrReceiver()
- {
- }
- public HrReceiver(int deviceID)
- {
- DeviceID = deviceID;
- }
- public int DeviceID { get; }
- public bool Connected { get; private set; }
- public List<AntDevice> ScanResult { get; private set; }
- public HrSensorData SensorData => sensorData;
- //Start a background Scan to find the device
- public void StartScan()
- {
- Debug.Log("Looking for ANT + HeartRate sensor");
- 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
- switch (deviceType)
- {
- case AntplusDeviceType.HeartRate:
- {
- var deviceNumber = data[10] | (data[11] << 8);
- var transType = data[13];
- foreach (var d in ScanResult)
- if (d.deviceNumber == deviceNumber && d.transType == transType) //device already found
- return;
- var 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;
- }
- }
- }
- private void ConnectToDevice(AntDevice device)
- {
- AntManager.Instance.CloseBackgroundScanChannel();
- var 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];
- }
- private void ChannelResponse(ANT_Response response)
- {
- }
- }
- }
|