123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- using System;
- 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 int DeviceID { get; } = 0;
- public bool Connected { get; private set; } = false;
- public List<AntDevice> 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<AntDevice>();
- 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)
- {
- }
- }
- }
|