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 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(); }
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); }
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(); }
//////////////////////////////////////////////////////////////////////////////// // Init // // Initialize demo parameters. // //////////////////////////////////////////////////////////////////////////////// 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); } } }
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); } } }
//////////////////////////////////////////////////////////////////////////////// // 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) { 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.device; channel = device.getChannel(userChannel); channel.channelResponse += new dChannelResponseHandler(ChannelResponse); channel.assignChannel(channelType, 0, 500); channel.setChannelID(deviceNum, pairing, deviceType, transType, 500); channel.setChannelFreq(radioFreq, 500); channel.setChannelPeriod(channelPeriod, 500); isBackgroundScan = false; channel.openChannel(); broadcasting = true; }
static public void startRemoteControl(ANT_Channel channel) { if (instance != null) { instance.stopChannel(); } instance = new RacerRemoteControl(channel); }
// 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); }
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(); } } }
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 }
void antChannel_channelResponse_FeSearch(ANT_Response response) { switch ((ANT_ReferenceLibrary.ANTMessageID)response.responseID) { case ANT_ReferenceLibrary.ANTMessageID.BROADCAST_DATA_0x4E: AntPlus_Connection newConn = deviceList[searchingDeviceIndex]; ANT_Response idResp = null; try { idResp = antStick.requestMessageAndResponse(searchChannel.getChannelNum(), ANT_ReferenceLibrary.RequestMessageID.CHANNEL_ID_0x51, 1000); } catch (Exception) { //Don't know what to do if we can't get id...could retry somewhere... break; } lock (newConn) { searchChannel.channelResponse -= antChannel_channelResponse_FeSearch; newConn.dataSource.searchProfile.deviceNumber = (ushort)(idResp.messageContents[1] + ((ushort)idResp.messageContents[2] << 8)); //Save to the search profile so we keep this id after dropouts newConn.connectedChannel = searchChannel; //Note: the low pri search happens before the high pri, so this isn't even doing anything. //newConn.connectedChannel.setChannelSearchTimeout(2, 500); //If we drop, we really want it back soon because it may be in use in a race, but we can't afford to ruin other channels staying in high priority. With the default search waveform, 5s is supposed to give us a really good rate of acquisition newConn.connectedChannel.setLowPrioritySearchTimeout(255, 500); //Search indefinitely newConn.antChannel_channelResponse_DataFetch(response); newConn.connectedChannel.channelResponse += newConn.antChannel_channelResponse_DataFetch; newConn.setConnStatus(AntPlus_Connection.ConnState.Connected); } searchChannel = null; //invalidate this channel as a search channel startNextSearch(); break; case ANT_ReferenceLibrary.ANTMessageID.RESPONSE_EVENT_0x40: if (response.messageContents[1] == (byte)ANT_ReferenceLibrary.ANTMessageID.EVENT_0x01) { //if(response.messageContents[2] == 0x01) //Search timeout causes close channel, so wait for that if (response.messageContents[2] == (byte)ANT_ReferenceLibrary.ANTEventID.EVENT_CHANNEL_CLOSED_0x07) //Closed channel { startNextSearch(); } } break; } }
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); } }
public void ConfigureContinuousScan(ANT_ReferenceLibrary.ChannelType channelType, byte radioFreq, ushort USBNum) { userChannel = 0; RXQueue = new Queue <byte[]>(16); messageQueue = new Queue <ANT_Response>(16); device = AntManager.Instance.devices[USBNum]; device.enableRxExtendedMessages(true, 500); channel = device.getChannel(0); channel.channelResponse += new dChannelResponseHandler(ChannelResponse); channel.assignChannelExt(ANT_ReferenceLibrary.ChannelType.ADV_TxRx_Only_or_RxAlwaysWildCard_0x40, 0, ANT_ReferenceLibrary.ChannelTypeExtended.ADV_AlwaysSearch_0x01, 500); channel.setChannelID(0, false, 0, 0, 500); channel.setChannelFreq(radioFreq, 500); channel.setChannelSearchTimeout(0); channel.setLowPrioritySearchTimeout((byte)0xFF); isBackgroundScan = true; channel.openChannel(); device.openRxScanMode(); broadcasting = true; }
public void ConfigureScan(byte userChannel) { this.userChannel = userChannel; RXQueue = new Queue <byte[]>(16); messageQueue = new Queue <ANT_Response>(16); device = AntManager.Instance.device; device.enableRxExtendedMessages(true, 500); channel = device.getChannel(userChannel); channel.channelResponse += new dChannelResponseHandler(ChannelResponse); channel.assignChannelExt(ANT_ReferenceLibrary.ChannelType.ADV_TxRx_Only_or_RxAlwaysWildCard_0x40, 0, ANT_ReferenceLibrary.ChannelTypeExtended.ADV_AlwaysSearch_0x01, 500); channel.setChannelID(0, false, 0, 0, 500); channel.setChannelFreq(57, 500); channel.setChannelSearchTimeout(0); channel.setLowPrioritySearchTimeout((byte)0xFF); isBackgroundScan = true; channel.openChannel(); broadcasting = true; }
public static void Tramp_Init() { try { bool flag = ANT.device0 == null; if (flag) { ANT.device0 = new ANT_Device(); } ANT.channel1 = ANT.device0.getChannel((int)ANT.USER_ANT_CHANNEL_tramp); ANT.channel1.channelResponse += new dChannelResponseHandler(ANT.Tramp_ChannelResponse); } catch (Exception ex) { bool flag2 = ANT.device0 == null; if (flag2) { throw new Exception("Could not connect to any device.\nDetails: \n " + ex.Message); } throw new Exception("Error connecting to ANT: " + ex.Message); } }
int cursorIndex = 0; // index to handle cursor display while transmitting in broadcast mode /// <summary> /// Setup ANT-FS client to process messages from connected device /// </summary> public void Start(ANT_Device antDevice) { PrintMenu(); try { // Create the ANT-FS client and attach it to a channel (in this case, 0) channel0 = antDevice.getChannel(0); antfsClient = new ANTFS_ClientChannel(channel0); // Setup callback to handle ANT-FS response events antfsClient.OnResponse += new Action <ANTFS_ClientChannel.Response>(HandleClientResponses); // Configure the client, and begin beaconing ConfigureClient(antDevice); while (!demoDone) { string command = Console.ReadLine(); HandleUserInput(command); Thread.Sleep(0); } } catch (ANTFS_Exception antEx) // Handle exceptions thrown by ANT Managed library { Console.WriteLine("ANT-FS Exception: " + antEx.Message); } catch (Exception ex) // Handle other exceptions { Console.WriteLine("Demo failed: " + ex.Message); Console.ReadLine(); } finally { Console.WriteLine("Disconnecting module..."); antDevice.Dispose(); // Close down the device completely and completely shut down all communication antfsClient.Dispose(); // Release all native resources used by the client Console.WriteLine("Demo has completed successfully!"); } }
public void Stop() { // Nothing to stop if not started or already finished. if (state == AntState.NotStarted || state == AntState.Finished) { return; } //if (state == AntState.StartFail || state == AntState.ConnectFail) // return; if (this.channel != null) { try { ANT_Channel tempChannel = this.channel; this.channel = null; tempChannel.closeChannel(RESPONSE_WAIT_TIME); tempChannel.Dispose(); } catch { } } if (this.device != null) { try { ANT_Device tempDevice = this.device; this.device = null; // We use a temp var here because this Dispose method is a little strange... tempDevice.Dispose(); } catch { } } UpdateState(AntState.Finished); }
public void EnableTracking() { Debug.Log("enable tracking of ANT+ device"); if (!nativeTransmitterIsRunning) { nativeTransmitterIsRunning = true; try { this.antDevice = new ANT_Device(ANT_ReferenceLibrary.PortType.USB, deviceNumber, this.BAUD_RATE, ANT_ReferenceLibrary.FramerType.basicANT); if (this.antDevice.getDeviceCapabilities().ExtendedMessaging) { this.antDevice.setLibConfig(ANT_ReferenceLibrary.LibConfigFlags.MESG_OUT_INC_RSSI_0x40 | ANT_ReferenceLibrary.LibConfigFlags.MESG_OUT_INC_DEVICE_ID_0x80); } this.antDevice.deviceResponse += new ANT_Device.dDeviceResponseHandler(this.handleANTResponses); this.antfsBroadcastChannel = this.antDevice.getChannel(this.deviceChannel); this.antfsBroadcastChannel.channelResponse += new dChannelResponseHandler(this.handleBroadcastChannelResponses); this.configureBroadcastChannel(); this.antDevice.serialError += new ANT_Device.dSerialErrorHandler(this.handleSerialError); } catch (ANT_Exception ex) { Debug.LogError(ex.Message); } } }
static void Main(string[] args) { byte USER_RADIOFREQ = 57; // RF Frequency + 2400 MHz //Do not distrubute this key byte[] USER_NETWORK_KEY = { 0xB9, 0xA5, 0x21, 0xFB, 0xBD, 0x72, 0xC3, 0x45 }; byte USER_NETWORK_NUM = 0; 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 HeartRate = new HeartRateDisplay(Channel0, AntPlusNetwork); HeartRate.TurnOn(); while (Console.KeyAvailable == false) { Console.WriteLine("Heart Rate=" + HeartRate.HeartRate); System.Threading.Thread.Sleep(500); } }
//////////////////////////////////////////////////////////////////////////////// // Init // // Initialize demo parameters. // //////////////////////////////////////////////////////////////////////////////// void Init() { textBoxGeneralLog.Text = "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 channel1 = device0.getChannel(USER_ANT_CHANNEL_VELOCITA); // Get channel from ANT device channel1.channelResponse += new dChannelResponseHandler(ChannelResponseVelocita); // Add channel response function to receive channel event messages channel0 = device0.getChannel(USER_ANT_CHANNEL_CADENZA); channel0.channelResponse += new dChannelResponseHandler(ChannelResponseCadenza); channel2 = device0.getChannel(USER_ANT_CHANNEL_POWER); // Get channel from ANT device channel2.channelResponse += new dChannelResponseHandler(ChannelResponsePower); // Add channel response function to receive channel event messages textBoxGeneralLog.Text = "cunfigurazione completata"; } 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); Console.WriteLine("cunfigurazione non completata"); } else { throw new Exception("Error connecting to ANT: " + ex.Message); Console.WriteLine("cunfigurazione non completata"); } } }
public void Start() { if (state != AntState.NotStarted) { Debug.LogWarningFormat("[AntStick] Start called a second time (ignored)."); return; } UpdateState(AntState.Starting); ushort deviceId = DEVICE_ID; try { string line = null; StreamReader reader = new StreamReader(ANT_DEVICE_ID_FILE_PATH, Encoding.Default); using (reader) { line = reader.ReadLine(); reader.Close(); } if (line == null) { Debug.LogWarningFormat("[AntStick] Could not get Ant Device ID from {0}. File exists but is empty.", ANT_DEVICE_ID_FILE_PATH); } else { deviceId = UInt16.Parse(line); } } catch (FileNotFoundException ex) { Debug.LogWarningFormat("[AntStick] Could not get Ant Device ID from {0}. File not found. {1}", ANT_DEVICE_ID_FILE_PATH, ex.Message); } catch (FormatException ex) { Debug.LogWarningFormat("[AntStick] Could not get Ant Device ID from {0}. Could not parse first line as ushort. {1}", ANT_DEVICE_ID_FILE_PATH, ex.Message); } catch (Exception ex) { Debug.LogWarningFormat("[AntStick] Could not get Ant Device ID from {0}. Exception occurred. {1}", ANT_DEVICE_ID_FILE_PATH, ex.Message); } Debug.LogFormat("[AntStick] Using Device ID {0}.", deviceId); Stats = new AntStats(); try { device = new ANT_Device(); } catch (ANT_Exception ex) { Debug.LogWarningFormat("[AntStick] Could not open device (perhaps something else is using it?).\n{0}", ex.Message); UpdateState(AntState.StartFail); Stop(); return; } try { channel = device.getChannel(CHANNEL); } catch (ANT_Exception ex) { Debug.LogWarningFormat("[AntStick] Could not get channel {0}.\n{1}", CHANNEL, ex.Message); UpdateState(AntState.StartFail); Stop(); return; } device.deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse); channel.channelResponse += new dChannelResponseHandler(ChannelResponse); try { if (!device.setNetworkKey(NETWORK_NUMBER, NETWORK_KEY, RESPONSE_WAIT_TIME)) { Debug.LogWarning("[AntStick] Failed to set network key."); UpdateState(AntState.StartFail); Stop(); return; } if (!channel.assignChannel(CHANNEL_TYPE, NETWORK_NUMBER, RESPONSE_WAIT_TIME)) { Debug.LogWarning("[AntStick] Failed to assign channel."); UpdateState(AntState.StartFail); Stop(); return; } if (!channel.setChannelID(deviceId, PAIRING_ENABLED, DEVICE_TYPE, TRANSMISSION_TYPE, RESPONSE_WAIT_TIME)) { Debug.LogWarning("[AntStick] Failed to set channel Id."); UpdateState(AntState.StartFail); Stop(); return; } if (!channel.setChannelPeriod(CHANNEL_PERIOD, RESPONSE_WAIT_TIME)) { Debug.LogWarning("[AntStick] Failed to set channel period."); UpdateState(AntState.StartFail); Stop(); return; } if (!channel.setChannelFreq(CHANNEL_FREQUENCY, RESPONSE_WAIT_TIME)) { Debug.LogWarning("[AntStick] Failed to set channel frequency."); UpdateState(AntState.StartFail); Stop(); return; } if (!channel.openChannel(RESPONSE_WAIT_TIME)) { Debug.LogWarning("[AntStick] Failed to open the channel."); UpdateState(AntState.StartFail); Stop(); return; } } catch (ANT_Exception ex) { Debug.LogWarningFormat("[AntStick] Could not configure channel.\n{0}", ex.Message); UpdateState(AntState.StartFail); Stop(); return; } StartConnectTimeout(); }
private void setupAndOpen(ANT_Device deviceToSetup, ANT_ReferenceLibrary.ChannelType channelType) { //We try-catch and forward exceptions to the calling function to handle and pass the errors to the user try { //To access an ANTChannel on a paticular device we need to get the channel from the device //Once again, this ensures you have a valid object associated with a real-world ANTChannel //ie: You can only get channels that actually exist ANT_Channel channel0 = deviceToSetup.getChannel(0); //Almost all functions in the library have two overloads, one with a response wait time and one without //If you give a wait time, you can check the return value for success or failure of the command, however //the wait time version is blocking. 500ms is usually a safe value to ensure you wait long enough for any response. //But with no wait time, the command is simply sent and you have to monitor the device response for success or failure. //To setup channels for communication there are three mandatory operations assign, setID, and Open //Various other settings such as message period and network key affect communication //between two channels as well, see the documentation for further details on these functions. //So, first we assign the channel, we have already been passed the channelType which is an enum that has various flags //If we were doing something more advanced we could use a bitwise or ie:base|adv1|adv2 here too //We also use net 0 which has the public network key by default if (channel0.assignChannel(channelType, 0, 500)) { threadSafePrintLine("Ch assigned to " + channelType + " on net 0.", textBox_Display); } else { throw new Exception("Channel assignment operation failed."); } //Next we have to set the channel id. Slaves will only communicate with a master device that //has the same id unless one or more of the id parameters are set to a wild card 0. If wild cards are included //the slave will search until it finds a broadcast that matches all the non-wild card parameters in the id. //For now we pick an arbitrary id so that we can ensure we match between the two devices. //The pairing bit ensures on a search that you only pair with devices that also are requesting //pairing, but we don't need it here so we set it to false if (channel0.setChannelID(12345, false, 67, 89, 500)) { threadSafePrintLine("Set channel ID to 12345, 67, 89", textBox_Display); } else { throw new Exception("Set Channel ID operation failed."); } //Setting the channel period isn't mandatory, but we set it slower than the default period so messages aren't coming so fast //The period parameter is divided by 32768 to set the period of a message in seconds. So here, 16384/32768 = 1/2 sec/msg = 2Hz if (channel0.setChannelPeriod(16384, 500)) { threadSafePrintLine("Message Period set to 16384/32768 seconds per message", textBox_Display); } //Now we open the channel if (channel0.openChannel(500)) { threadSafePrintLine("Opened Channel" + Environment.NewLine, textBox_Display); } else { throw new Exception("Channel Open operation failed."); } } catch (Exception ex) { throw new Exception("Setup and Open Failed. " + ex.Message + Environment.NewLine); } }
void startNextSearch() { if (searchChannel != null || antStick == null) //Check if device is present and the channel is valid { //Ensure we are still connected try { searchChannel.requestStatus(1000); //Check if we get an exception...means we are disconnected, otherwise continue } catch (Exception) { try { //We get to this code almost always because the device is dead, so try to restart it ANT_Device.shutdownDeviceInstance(ref antStick); searchChannel = null; foreach (AntPlus_Connection i in deviceList) { i.connectedChannel = null; } findUsableAntDevice(); //Now fall through and attempt to restart search } catch (Exception) { //System.Windows.MessageBox.Show("Opening Device Failed. Try removing then re-inserting the stick, then try again."); return; } } } //end check if device and search channel (if there is one) are valid //Check if we still need to search or have all the equipment already List <int> usedChannels = new List <int>(); foreach (AntPlus_Connection i in deviceList) { switch (i.getConnStatus()) { case AntPlus_Connection.ConnState.Closed: case AntPlus_Connection.ConnState.Searching: i.setConnStatus(AntPlus_Connection.ConnState.InSrchQueue); break; case AntPlus_Connection.ConnState.InSrchQueue: break; case AntPlus_Connection.ConnState.Connected: case AntPlus_Connection.ConnState.DrpdToSrch: usedChannels.Add(i.connectedChannel.getChannelNum()); break; } } if (usedChannels.Count == deviceList.Count) { return; //we have all the equipment already } //Get new search channel if neccesary if (searchChannel == null) { if (usedChannels.Count >= numChannelsForDevices) { return; //no free channels } //Find the first free channel and start the search for (int i = 0; i < numChannelsForDevices; ++i) { if (!usedChannels.Contains(i)) { searchChannel = antStick.getChannel(i); searchChannel.channelResponse += new dChannelResponseHandler(antChannel_channelResponse_FeSearch); break; } } } //Search for a search period for given device parameters //Find the next device to search for while (true) //We know there is at least one device we need to search for, because of the check above, so this will never loop infinitely { ++searchingDeviceIndex; if (searchingDeviceIndex >= deviceList.Count) { searchingDeviceIndex = 0; } if (deviceList[searchingDeviceIndex].connectedChannel == null) { break; } } //Now set the channel parameters to start the next search try { if (searchChannel == null) { throw new ApplicationException("Couldn't allocate a channel for search"); } ds_AntPlus.AntChannelProfile srch = deviceList[searchingDeviceIndex].dataSource.searchProfile; deviceList[searchingDeviceIndex].setConnStatus(AntPlus_Connection.ConnState.Searching); if (!searchChannel.assignChannel(ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00, 0, 500)) { //Usually because the channel is in wrong state searchChannel.closeChannel(500); searchChannel.unassignChannel(500); if (!searchChannel.assignChannel(ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00, 0, 500)) { throw new ApplicationException("Failed to assign channel"); } } //Handle setting the search timeout byte timeout = 4; //default 4*2.5=10 seconds for each device if (deviceList.Count - usedChannels.Count == 1) { timeout = 255; //search forever if we only have one device to find; If one of the other devices resets it will startNextSearch again so we won't get stuck } if (!searchChannel.setLowPrioritySearchTimeout(timeout, 500)) { throw new ApplicationException("Failed to set low-pri search timeout"); } if (!searchChannel.setChannelSearchTimeout(0, 500)) { throw new ApplicationException("Failed to set search timeout"); } if (!searchChannel.setChannelFreq(srch.rfOffset, 500)) { throw new ApplicationException("Failed to set channel frequency"); } if (!searchChannel.setChannelPeriod(srch.messagePeriod, 500)) { throw new ApplicationException("Failed to set channel period"); } if (!searchChannel.setChannelID(srch.deviceNumber, srch.pairingEnabled, srch.deviceType, srch.transType, 500)) { throw new ApplicationException("Failed to set channel ID"); } if (!searchChannel.openChannel(500)) { throw new ApplicationException("Failed to open channel"); } } catch (Exception ex) { //System.Windows.MessageBox.Show("Search Channel Open Failed: " + ex.Message +". If you still need to connect other fitness equipment, you may need to restart the application."); } }
//////////////////////////////////////////////////////////////////////////////// // ConfigureANT // // Resets the system, configures the ANT channel and starts the demo //////////////////////////////////////////////////////////////////////////////// void ConfigureANT(byte USER_NETWORK_NUM, ANT_ReferenceLibrary.ChannelType channelType, byte USER_DEVICETYPE, ushort USER_CHANNELPERIOD, ANT_Channel channel) { textBoxGeneralLog.Text = "configure"; Console.WriteLine("Resetting module..."); // device0.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, Console.WriteLine("Setting network key..."); if (device0.setNetworkKey(USER_NETWORK_NUM, USER_NETWORK_KEY, 500)) { Console.WriteLine("Network key set"); } else { throw new Exception("Error configuring network key"); } Console.WriteLine("Assigning channel..."); if (channel.assignChannel(channelType, USER_NETWORK_NUM, 500)) { Console.WriteLine("Channel assigned"); } else { throw new Exception("Error assigning channel"); } Console.WriteLine("Setting Channel ID..."); if (channel.setChannelID(USER_DEVICENUM, false, USER_DEVICETYPE, USER_TRANSTYPE, 500)) // Not using pairing bit { Console.WriteLine("Channel ID set"); } else { throw new Exception("Error configuring Channel ID"); } Console.WriteLine("Setting Radio Frequency..."); if (channel.setChannelFreq(USER_RADIOFREQ, 500)) { Console.WriteLine("Radio Frequency set"); } else { throw new Exception("Error configuring Radio Frequency"); } Console.WriteLine("Setting Channel Period..."); if (channel.setChannelPeriod(USER_CHANNELPERIOD, 500)) { Console.WriteLine("Channel Period set"); } else { throw new Exception("Error configuring Channel Period"); } Console.WriteLine("Opening channel..."); bBroadcasting = true; if (channel.openChannel(500)) { Console.WriteLine("Channel opened"); } else { bBroadcasting = false; throw new Exception("Error opening channel"); } }
private RacerRemoteControl(ANT_Channel channel) { this.channel = channel; startChannel(); channel.channelResponse += new dChannelResponseHandler(channel_channelResponse); }
static async void Init() { try { WriteLog("Connecting to ANT USB Dongle..."); //device0 = new ANT_Device(); // Create a device instance using the automatic constructor (automatic detection of USB device number and baud rate) device0.serialError += new ANT_Device.dSerialErrorHandler(SerialError); 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 WriteLog("ANT USB Dongle initialization successful"); WriteLog("ANT USB Dongle Device Number: " + device0.getOpenedUSBDeviceNum()); WriteLog("ANT USB Dongle Serial Number: " + device0.getSerialNumber()); USER_DEVICENUM = (ushort)device0.getOpenedUSBDeviceNum(); bReset = false; List <Task> tasks = new List <Task>(); tasks.Add(Task.Factory.StartNew(() => { while (!bReset) { WriteLog("Checking ANT USB Dongle..."); Byte[] bytes = new byte[8]; try { if (channel0.sendBroadcastData(bytes)) { WriteLog("ANT USB Dongle is operationnal"); } else { WriteLog("ANT USB Dongle is not operationnal"); } } catch (Exception ex) { WriteLog("Problem with ANT USB Dongle..."); } System.Threading.Thread.Sleep(5000); } })); await Task.WhenAll(tasks); } catch (Exception ex) { Console.WriteLine("Exception: " + ex); } /* * if (device0 == null) // Unable to connect to ANT * { * throw new Exception("Could not connect to any ANT device.\n" + * "Details: \n " + ex.Message); * } * else * { * throw new Exception("Error connecting to ANT device: " + ex.Message); * } * } */ }
private void InitAnt() { try { String path = Application.dataPath + "/Plugins"; ANT_Common.CustomDllSearchPath = Path.GetFullPath(path); _device = new ANT_Device(); _device.deviceResponse += DeviceResponse; _channel = _device.getChannel(userAntChannel); _channel.channelResponse += ChannelResponse; System.Threading.Thread.Sleep(500); if (_device.setNetworkKey(USER_NETWORK_NUM, USER_NETWORK_KEY, 500)) { Debug.Log("Network key set"); } else { throw new Exception("Error configuring network key"); } if (!_channel.assignChannel(ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00, USER_NETWORK_NUM, 500)) { throw new Exception("Error assigning channel"); } if (_channel.setChannelID(userDeviceNum, false, userDeviceType, userTransmissionType, 500) ) // Not using pairing bit { Debug.Log("Channel ID set"); } else { throw new Exception("Error configuring Channel ID"); } if (_channel.setChannelFreq(userUserRadioFreq, 500)) { Debug.Log("Radio Frequency set"); } else { throw new Exception("Error configuring Radio Frequency"); } Debug.Log("Setting Channel Period..."); if (_channel.setChannelPeriod(userChannelPeriod, 500)) { Debug.Log("Channel Period set"); } else { throw new Exception("Error configuring Channel Period"); } if (!_channel.openChannel(500)) { throw new Exception("Error during opening channel"); } _device.enableRxExtendedMessages(true); } catch (Exception e) { if (_device == null) { throw new Exception("Could not connect to any ANT device\nDetails:\n" + e); } throw new Exception("Error connecting to ANT: " + e.Message); } }