//////////////////////////////////////////////////////////////////////////////// // ConfigureAnt // // You can find how to initialize devices on thisisant.com in the download documents section // ANT+ DEVICE PROFILES // //////////////////////////////////////////////////////////////////////////////// public void ConfigureAnt(ANT_ReferenceLibrary.ChannelType channelType, byte userChannel, ushort deviceNum, byte deviceType, byte transType, byte radioFreq, ushort channelPeriod, bool pairing, int USBNum) { this.channelType = channelType; this.userChannel = userChannel; this.deviceNum = deviceNum; this.deviceType = deviceType; this.transType = transType; this.radioFreq = radioFreq; this.channelPeriod = channelPeriod; this.pairing = pairing; RXQueue = new Queue <byte[]>(16); messageQueue = new Queue <ANT_Response>(16); device = AntManager.Instance.devices[USBNum]; channel = device.getChannel(userChannel); channel.channelResponse += new dChannelResponseHandler(ChannelResponse); channel.assignChannel(channelType, 0, 0); channel.setChannelID(deviceNum, pairing, deviceType, transType, 0); channel.setChannelFreq(radioFreq, 0); channel.setChannelPeriod(channelPeriod, 0); channel.setLowPrioritySearchTimeout(0); isBackgroundScan = false; channel.openChannel(); broadcasting = true; }
IEnumerator Reconnect(uint serial) { Debug.Log("looking for usb device " + serial.ToString()); // polling to try and find the USB device while (true) { if (ANT_Common.getNumDetectedUSBDevices() > 0) { ANT_Device device = new ANT_Device(); if (device.getSerialNumber() == serial) { Debug.Log("usb found!"); AntManager.Instance.Reconnect(device); foreach (AntChannel channel in AntManager.Instance.channelList) { channel.ReOpen(); } yield break; } else { device.Dispose(); } } yield return(new WaitForSeconds(0.1f)); } }
/// <summary> /// Shut down the ant device connection. /// </summary> public static void Shutdown() { // Clean up ANT Console.WriteLine("Disconnecting module..."); ANT_Device.shutdownDeviceInstance(ref device0); // Close down the device completely and completely shut down all communication Console.WriteLine("Demo has completed successfully!"); }
static void Init() { try { Console.WriteLine("Attempting to connect to an ANT USB device..."); device0 = new ANT_Device(); // Create a device instance using the automatic constructor (automatic detection of USB device number and baud rate) device0.deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse); // Add device response function to receive protocol event messages channel0 = device0.getChannel(USER_ANT_CHANNEL); // Get channel from ANT device channel0.channelResponse += new dChannelResponseHandler(ChannelResponse); // Add channel response function to receive channel event messages Console.WriteLine("Initialization was successful!"); } catch (Exception ex) { if (device0 == null) // Unable to connect to ANT { throw new Exception("Could not connect to any device.\n" + "Details: \n " + ex.Message); } else { throw new Exception("Error connecting to ANT: " + ex.Message); } } }
public PowerChannel(ANT_Device device, int ant_channel, byte network_num, ushort deviceNumber) { channel = device.getChannel(ant_channel); // Get channel from ANT device channel.channelResponse += ChannelResponse; // Add channel response function to receive channel event messages if (!channel.assignChannel(ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00, network_num, 500)) { throw new Exception("Error assigning channel"); } if (!channel.setChannelID(deviceNumber, false, POWER_DEVICE_TYPE, USER_TRANSTYPE, 500)) { throw new Exception("Error configuring Channel ID"); } if (!channel.setChannelFreq(USER_RADIOFREQ, 500)) { throw new Exception("Error configuring Radio Frequency"); } if (!channel.setChannelPeriod(USER_CH_PERIOD, 500)) { throw new Exception("Error configuring Channel Period"); } }
static ANT_ReferenceLibrary.ChannelType channelType; ///< 0 = Master, 1 = Slave /// <summary> /// Initialize parameters for a HRM device connection. /// </summary> public static void Init() { try { Console.WriteLine("Attempting to connect to an ANT USB device..."); // Create a device instance using the automatic constructor (automatic detection of USB device number and baud rate) device0 = new ANT_Device(); // Add device response function to receive protocol event messages device0.deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse); // Get channel from ANT device channel0 = device0.getChannel(USER_ANT_CHANNEL); // Add channel response function to receive channel event messages channel0.channelResponse += new dChannelResponseHandler(ChannelResponse); Console.WriteLine("Initialization was successful!"); } catch (Exception ex) { // Unable to connect to ANT // Please make sure you have an usb that is able to connect to garmin devices. // It is required for this project, see: https://buy.garmin.com/en-US/US/p/10997. if (device0 == null) { throw new Exception("Could not connect to any device.\n" + "Details: \n " + ex.Message); } else { throw new Exception("Error connecting to ANT: " + ex.Message); } } Start(); }
public void Shutdown() { // Clean up ANT Debug.WriteLine("Disconnecting module..."); ANT_Device.shutdownDeviceInstance(ref device); // Close down the device completely and completely shut down all communication Debug.WriteLine("ANT device shutdowned successfully!"); }
public void Init() { usbDevice = new ANT_Device(); usbDevice.ResetSystem(); usbDevice.setNetworkKey(0, NETWORK_KEY); network = new AntPlus.Types.Network(0, NETWORK_KEY, CHANNEL_FREQUENCY); }
internal bool Init() { bool result = true; try { Console.WriteLine("Attempting to connect to an ANT USB device 0..."); device0 = new ANT_Device(); device0.deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse); channel0 = device0.getChannel(0); channel0.channelResponse += new dChannelResponseHandler(ChannelResponse0); Console.WriteLine("Initialization 0 was successful!"); } catch (Exception ex) { result = false; if (device0 == null) { Console.WriteLine("Could not connect to device 0.\n" + "Details: \n " + ex.Message); } else { Console.WriteLine("Error connecting to ANT: " + ex.Message); } } return(result); }
/// <summary> /// Configure the host search parameters, and begin the search /// </summary> /// <param name="antDevice">ANT USB device</param> public void ConfigureHost(ANT_Device antDevice) { // Configure ANT channel parameters antfsHost.SetNetworkKey(Demo.NetworkNumber, Demo.NetworkKey); antfsHost.SetChannelID(Demo.DeviceType, Demo.TransmissionType); antfsHost.SetChannelPeriod(Demo.ChannelPeriod); // Configure search parameters if (antfsHost.AddSearchDevice(ClientDeviceID, Demo.ClientManufacturerID, Demo.ClientDeviceType) == 0) { throw new Exception("Error adding search device: "); } if (Demo.AntfsBroadcast) { // If we want to use ANT-FS broadcast mode, and start the channel in broadcast mode, // setup callback to handle responses for channel 0 while in broadcast mode channel0.channelResponse += new dChannelResponseHandler(HandleChannelResponses); // Configure the channel as a slave, and look for messages from the master in the channel callback // This demo will automatically switch to ANT-FS mode after a few seconds if (!antDevice.setNetworkKey(Demo.NetworkNumber, Demo.NetworkKey, 500)) { throw new Exception("Error configuring network key"); } if (!channel0.assignChannel(ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00, Demo.NetworkNumber, 500)) { throw new Exception("Error assigning channel"); } if (!channel0.setChannelID(DeviceNumber, false, Demo.DeviceType, Demo.TransmissionType, 500)) { throw new Exception("Error configuring Channel ID"); } if (!channel0.setChannelFreq(Demo.SearchRF, 500)) { throw new Exception("Error configuring radio frequency"); } if (!channel0.setChannelPeriod(Demo.ChannelPeriod, 500)) { throw new Exception("Error configuring channel period"); } if (!channel0.openChannel(500)) { throw new Exception("Error opening channel"); } } else { // Start searching directly for an ANT-FS client matching the search criteria // NOTE: If not interested in the payload while in broadcast mode and intend to start a session right away, // you can specify useRequestPage = true to search for broadcast devices, and automatically request them // to switch to ANT-FS mode antfsHost.SearchForDevice(Demo.SearchRF, ConnectRF, DeviceNumber); } Console.WriteLine("Searching for devices..."); // Setup a timer, so that we can cancel the search if no device is found searchTimer = new Timer(SearchExpired, null, SearchTimeout * 1000, Timeout.Infinite); // convert time to milliseconds }
//Creates the ANTDevice instances and calls the setupAndOpen routine according to the selected demo mode public bool startUp() { //The managed library will throw ANTExceptions on errors //We run this in a try catch because we want to print any errors instead of crash try { //Regardless of selection we need to connect to the first device //The library has an automatic constructor to automatically connect to the first available device //You can still manually choose which device to connect to by using the parameter constructor, // ie: ANTDeviceInstance = new ANTDevice(0, 57600) device0 = new ANT_Device(); //device0 = new ANT_Device(0, 57600); //First we want to setup the response functions so we can see the feedback as we setup //To do this, the device and each channel have response events which are fired when feedback //is received from the device, including command acknowledgements and transmission events. device0.deviceResponse += new ANT_Device.dDeviceResponseHandler(device0_deviceResponse); device0.getChannel(0).channelResponse += new dChannelResponseHandler(d0channel0_channelResponse); // textBox_device0.Text = "Device 0 Connected" + Environment.NewLine; // textBox_Display.Text = "Starting Mode: d0 only - Slave Scan" + Environment.NewLine; setupAndOpenScan(device0, ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00); } catch (Exception ex) { // textBox_Display.AppendText("Error: " + ex.Message + Environment.NewLine); // if (device0 == null) //We print another message if we didn't connect to any device to be a little more helpful // textBox_Display.AppendText("Could not connect to any devices, ensure an ANT device is connected to your system and try again." + Environment.NewLine); // textBox_Display.AppendText(Environment.NewLine); return(false); } return(true); }
static void SerialError(ANT_Device sender, ANT_Managed_Library.ANT_Device.serialErrorCode error, bool isCritical) { WriteLog("Processing SerialError: " + error); WriteLog("Trying to recover USB ANT Dongle..."); device0 = null; channel0 = null; bReset = true; while (device0 == null) { try { WriteLog("Trying to connect to USB ANT Dongle..."); device0 = new ANT_Device(); } catch (Exception ex) { } System.Threading.Thread.Sleep(1000); } WriteLog("USB ANT Dongle has been recovered"); Init(); ConfigureANT(); }
static void Init() { try { Console.WriteLine("Attempting to connect to an ANT USB device 0..."); device0 = new ANT_Device(); device0.deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse); channel0 = device0.getChannel(0); channel0.channelResponse += new dChannelResponseHandler(ChannelResponse0); Console.WriteLine("Initialization 0 was successful!"); channel1 = device0.getChannel(1); channel1.channelResponse += new dChannelResponseHandler(ChannelResponse1); Console.WriteLine("Initialization 1 was successful!"); } catch (Exception ex) { if (device0 == null) { throw new Exception("Could not connect to device 0.\n" + "Details: \n " + ex.Message); } else { throw new Exception("Error connecting to ANT: " + ex.Message); } } }
void findUsableAntDevice() { List <ANT_Device> unusableDevices = new List <ANT_Device>(); try { antStick = new ANT_Device(); //Get new devices until we //lowpri and prox search is enough now to ensure we get a device that behave as we expected while (antStick.getDeviceCapabilities().lowPrioritySearch == false || antStick.getDeviceCapabilities().ProximitySearch == false) { unusableDevices.Add(antStick); //keep the last device ref so we don't see it again antStick = new ANT_Device(); //this will throw an exception when there are no devices left } if (!antStick.setNetworkKey(0, ANTPLUS_NETWORK_KEY, 500)) { throw new ApplicationException("Failed to set network key"); } } catch (Exception ex) { ANT_Device.shutdownDeviceInstance(ref antStick); //Don't leave here with an invalid device ref throw new Exception("Could not connect to valid USB2: " + ex.Message); //forward the exception } finally { //Release all the unusable devices foreach (ANT_Device i in unusableDevices) { i.Dispose(); } } }
public void Init(byte USBDeviceNum = 0) { if (ANT_Common.getNumDetectedUSBDevices() < USBDeviceNum) { Debug.Log("ANT+ cannot detect USB device #" + USBDeviceNum); return; } // if (deviceList == null) // deviceList = new List<ANT_Device>(); if (messageQueue == null) { messageQueue = new Queue <ANT_Response>(16); } if (errorQueue == null) { errorQueue = new Queue <SerialError>(16); } if (channelList == null) { channelList = new List <AntChannel>(); } //init the device if (devices[USBDeviceNum] == null) { devices[USBDeviceNum] = new ANT_Device(USBDeviceNum, 57000); devices[USBDeviceNum].deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse); devices[USBDeviceNum].serialError += new ANT_Device.dSerialErrorHandler(SerialErrorHandler); devices[USBDeviceNum].ResetSystem(); devices[USBDeviceNum].setNetworkKey(0, NETWORK_KEY, 500); } }
void SerialErrorHandler(ANT_Device sender, ANT_Device.serialErrorCode error, bool isCritical) { if (onSerialError != null) { SerialError serialError = new SerialError(sender, error, isCritical); errorQueue.Enqueue(serialError); } }
public void Reconnect(ANT_Device previousDevice) { device = previousDevice; device.deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse); device.serialError += new ANT_Device.dSerialErrorHandler(SerialErrorHandler); device.ResetSystem(); device.setNetworkKey(0, NETWORK_KEY, 500); }
public void Reconnect(ANT_Device previousDevice) { int usbNum = previousDevice.getOpenedUSBDeviceNum(); devices[usbNum] = previousDevice; previousDevice.deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse); previousDevice.serialError += new ANT_Device.dSerialErrorHandler(SerialErrorHandler); previousDevice.ResetSystem(); previousDevice.setNetworkKey(0, NETWORK_KEY, 500); }
// Use this for initialization void Start() { current_speed = 0; current_rpm = 0; speedData = new ANTRawData[2]; rpmData = new ANTRawData[2]; if (bikeController == null) { bikeController = GameObject.FindWithTag("Player").GetComponent <BikeControl>(); } try { dev0 = new ANT_Device(); dev0.deviceResponse += new ANT_Device.dDeviceResponseHandler(dev0_deviceResponse); dev0.getChannel(0).channelResponse += new dChannelResponseHandler(speedSensorResponse); dev0.getChannel(1).channelResponse += new dChannelResponseHandler(cadenceSensorResponse); dev0.setNetworkKey(0, new byte[] { 0xB9, 0xA5, 0x21, 0xFB, 0xBD, 0x72, 0xC3, 0x45 }); channel_speed = dev0.getChannel(0); channel_cadence = dev0.getChannel(1); channel_speed.assignChannel(ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00, 0, timeout); channel_speed.setChannelID(0, false, 123, 0, timeout); channel_speed.setChannelPeriod(8118, timeout); channel_speed.setChannelFreq(57, timeout); channel_speed.openChannel(timeout); channel_cadence.assignChannel(ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00, 0, timeout); channel_cadence.setChannelID(0, false, 122, 0, timeout); channel_cadence.setChannelPeriod(8102, timeout); channel_cadence.setChannelFreq(57, timeout); channel_cadence.openChannel(timeout); StartCoroutine(UpdateCoroutine()); StartCoroutine(WaitForDecreaseSpeed()); StartCoroutine(DecreaseSpeed()); bikeController.is_ant_used = true; } catch (System.Exception) { bikeController.is_ant_used = false; } finally { } Debug.Log("ANT Reset : " + bikeController.is_ant_used); }
private void button3_Click(object sender, EventArgs e) //pulsante fine { button2.Enabled = true; button3.Enabled = false; MessageBox.Show("SESSIONE INTERROTTA"); ANT_Device.shutdownDeviceInstance(ref device0); // Close down the device completely and completely shut down all communication trainerSpeeds.Maximum = 1; listViewTrainers.Enabled = true; }
public void DisableTracking() { nativeTransmitterIsRunning = false; lock (this) { if (this.antDevice != null) { this.antDevice.Dispose(); this.antDevice = (ANT_Device)null; this.antfsBroadcastChannel = (ANT_Channel)null; this.closeBroadcastChannel(); } } }
public void StartCommunication() { antDevice = new ANT_Device(); var networkKeyString = File.ReadAllLines("ant-network.key").FirstOrDefault(l => !l.StartsWith("#"))?.Trim(); antDevice.setNetworkKey(0, StringToByteArray(networkKeyString)); antDevice.deviceResponse += new ANT_Device.dDeviceResponseHandler(device0_deviceResponse); antDevice.getChannel(0).channelResponse += new dChannelResponseHandler(d0channel0_channelResponse); threadSafePrintLine("ANT+ USB Device Connected"); setupAndOpen(antDevice, ANT_ReferenceLibrary.ChannelType.BASE_Master_Transmit_0x10, 17, 0); // FE-C setupAndOpen(antDevice, ANT_ReferenceLibrary.ChannelType.BASE_Master_Transmit_0x10, 11, 1); // Power SetNextBroadcastMessage(); }
static void AllocateUSBDongle() { WriteLog("Allocating USB ANT Dongle..."); try { device0 = new ANT_Device(); Init(); ConfigureANT(); } catch (Exception ex) { WriteLog("USB ANT Dongle is already allocated !"); } }
private void CloseAllChannles() { if (channel0 != null) { Console.WriteLine("Closing Channel"); channel0.closeChannel(); channel0.Dispose(); channel0 = null; } if (device0 != null) { device0.Dispose(); device0 = null; } //dispose time and wait object and semaphore }
public void Init() { messageQueue = new Queue <ANT_Response>(16); errorQueue = new Queue <SerialError>(16); channelList = new List <AntChannel>(); //init the device if (device == null) { device = new ANT_Device(); device.deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse); device.serialError += new ANT_Device.dSerialErrorHandler(SerialErrorHandler); device.ResetSystem(); device.setNetworkKey(0, NETWORK_KEY, 500); } }
static void ReleaseUSBDongle() { WriteLog("Releasing USB ANT Dongle..."); try { channel0.closeChannel(); System.Threading.Thread.Sleep(1000); device0.ResetSystem(); device0.ResetUSB(); ANT_Device.shutdownDeviceInstance(ref device0); } catch (Exception ex) { WriteLog("USB ANT Dongle is already released !"); } }
public void ReOpen(ANT_Device device) { if (broadcasting) { return; } this.device = device; if (!isBackgroundScan) { ConfigureAnt(channelType, userChannel, deviceNum, deviceType, transType, radioFreq, channelPeriod, pairing, device.getOpenedUSBDeviceNum()); } else { ConfigureScan(userChannel, (ushort)device.getOpenedUSBDeviceNum()); } }
public Network() { device = new ANT_Device(); // Create a device instance using the automatic constructor (automatic detection of USB device number and baud rate) device.deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse); // Add device response function to receive protocol event messages device.ResetSystem(); // Soft reset System.Threading.Thread.Sleep(500); // Delay 500ms after a reset // If you call the setup functions specifying a wait time, you can check the return value for success or failure of the command // This function is blocking - the thread will be blocked while waiting for a response. // 500ms is usually a safe value to ensure you wait long enough for any response // If you do not specify a wait time, the command is simply sent, and you have to monitor the protocol events for the response, if (!device.setNetworkKey(USER_NETWORK_NUM, USER_NETWORK_KEY, 500)) { throw new Exception("Error configuring network key"); } device.enableRxExtendedMessages(true); }
public static void Init() { try { ANT_TAPING.device0 = new ANT_Device(); ANT_TAPING.device0.deviceResponse += new ANT_Device.dDeviceResponseHandler(ANT_TAPING.DeviceResponse); ANT_TAPING.channel0 = ANT_TAPING.device0.getChannel((int)ANT_TAPING.USER_ANT_CHANNEL); ANT_TAPING.channel0.channelResponse += new dChannelResponseHandler(ANT_TAPING.ChannelResponse); } catch (Exception ex) { bool flag = ANT_TAPING.device0 == null; if (flag) { throw new Exception("Could not connect to any device.\nDetails: \n " + ex.Message); } throw new Exception("Error connecting to ANT: " + ex.Message); } }
/* public static async void SendDeviceProperties() * { * try * { * Console.WriteLine("Sending device properties:"); * Random random = new Random(); * TwinCollection telemetryConfig = new TwinCollection(); * reportedProperties["DeviceProperty"] = random.Next(1, 6); * Console.WriteLine(JsonConvert.SerializeObject(reportedProperties)); * * await Client.UpdateReportedPropertiesAsync(reportedProperties); * } * catch (Exception ex) * { * Console.WriteLine(); * Console.WriteLine("Error in sample: {0}", ex.Message); * } * } */ private static async void SendTelemetryAsync(CancellationToken token) { try { //ANT Part byte USER_RADIOFREQ = 57; // RF Frequency + 2400 MHz //ANTPLUS KEY byte[] USER_NETWORK_KEY = { 0xB9, 0xA5, 0x21, 0xFB, 0xBD, 0x72, 0xC3, 0x45 }; // key byte USER_NETWORK_NUM = 0; //Use USB dongle to connect ANT+ device ANT_Device USB_Dongle; USB_Dongle = new ANT_Device(); USB_Dongle.ResetSystem(); USB_Dongle.setNetworkKey(USER_NETWORK_NUM, USER_NETWORK_KEY); ANT_Channel Channel0 = USB_Dongle.getChannel(0); Network AntPlusNetwork = new Network(USER_NETWORK_NUM, USER_NETWORK_KEY, USER_RADIOFREQ); HeartRateDisplay HR = new HeartRateDisplay(Channel0, AntPlusNetwork); HR.TurnOn(); Console.WriteLine(">>ANT+ Tuen on..."); while (true) { byte currentHeartbeat = HR.HeartRate; var telemetryDataPoint = new { heartbeat = currentHeartbeat, }; var messageString = JsonConvert.SerializeObject(telemetryDataPoint); var message = new Message(Encoding.ASCII.GetBytes(messageString)); token.ThrowIfCancellationRequested(); await Client.SendEventAsync(message); Console.WriteLine("{0} > Sending heartbeat signal : {1}", DateTime.Now, messageString); await Task.Delay(1000); } } catch (Exception ex) { Console.WriteLine(); Console.WriteLine("Intentional shutdown: {0}", ex.Message); } }