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);
         }
     }
 }
Exemple #2
0
        void InitHRM(int channelNumber)
        {
            var channelHrm       = usbDevice.getChannel(channelNumber);
            var heartRateDisplay = new HeartRateDisplay(channelHrm, network);

            hrmCommander = new HRMCommander(heartRateDisplay);
            hrmCommander.Start();
        }
Exemple #3
0
    // 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);
    }
        void InitHRM(int channelNumber)
        {
            Int32 deviceNumber = Int32.Parse(ConfigurationManager.AppSettings["hrm_device"]);

            if (deviceNumber < 0)
            {
                return;
            }
            var channelHrm       = usbDevice.getChannel(channelNumber);
            var heartRateDisplay = new HeartRateDisplay(channelHrm, network);

            hrmCommander = new HRMCommander(heartRateDisplay, (UInt16)deviceNumber);
            hrmCommander.Start();
        }
 private void action_SendAcknowledged()
 {
     //Acknowledged messages send an 8 byte payload and listen for an acknowledgement from a receiving device
     //They return a MessagingReturnCode indicating the result of the process.
     //The byte array sent in the transmission functions can be any length and will be automatically padded with zeros
     threadSafePrintLine("Sending Acknowledged Message from device 0", textBox_Display);
     if (device0.getChannel(0).sendAcknowledgedData(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }, 500) != ANT_ReferenceLibrary.MessagingReturnCode.Pass)
     {
         threadSafePrintLine("Acknowledged Message Failed", textBox_Display);
     }
     else
     {
         threadSafePrintLine("Acknowledged Message Succeeded", textBox_Display);
     }
 }
        ////////////////////////////////////////////////////////////////////////////////
        // 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);
                }
            }
        }
Exemple #7
0
        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);
        }
Exemple #8
0
    ////////////////////////////////////////////////////////////////////////////////
    // 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;
    }
Exemple #9
0
        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");
            }
        }
Exemple #10
0
        //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);
        }
        private void action_ReqStatus()
        {
            //The managed library has a function to request status that returns a ChannelStatus object
            threadSafePrintLine("Requesting Device 0 Status", textBox_Display);
            try
            {
                ANT_ChannelStatus chStatus = device0.getChannel(0).requestStatus(500);
                //Not all device types return a complete device status, so some of these fields may be inaccurate
                threadSafePrintLine("Device 0 Channel 0 Status: " + chStatus.BasicStatus + ", Network Number: " + chStatus.networkNumber + ", Type: " + chStatus.ChannelType, textBox_Display);
            }
            catch (Exception)
            {
                threadSafePrintLine("Requesting Device 0 Status Failed", textBox_Display);
            }

            //If present, request device 1 status too
            if (device1 != null)
            {
                threadSafePrintLine("Requesting Device 1 Status", textBox_Display);
                try
                {
                    ANT_ChannelStatus chStatus = device1.getChannel(0).requestStatus(500);
                    //Not all device types return a complete device status, so some of these fields may be inaccurate
                    threadSafePrintLine("Device 1 Channel 0 Status: " + chStatus.BasicStatus + ", Network Number: " + chStatus.networkNumber + ", Type: " + chStatus.ChannelType, textBox_Display);
                }
                catch (Exception)
                {
                    threadSafePrintLine("Requesting Device 1 Status Failed", textBox_Display);
                }
            }
        }
Exemple #12
0
        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 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();
        }
Exemple #14
0
        public void Start()
        {
            var feChannel  = usbDevice.getChannel(0);
            var bpChannel  = usbDevice.getChannel(1);
            var hrChannel  = usbDevice.getChannel(2);
            var bcChannel  = usbDevice.getChannel(3);
            var bscChannel = usbDevice.getChannel(4);

            feDisplay  = new FitnessEquipmentDisplay(feChannel, network);
            bpDisplay  = new BikePowerDisplay(bpChannel, network);
            hrDisplay  = new HeartRateDisplay(hrChannel, network);
            bcDisplay  = new BikeCadenceDisplay(bcChannel, network);
            bscDisplay = new BikeSpeedCadenceDisplay(bscChannel, network);

            BindEvents();
            _ = ConsumeClientDataAsync();

            feDisplay.TurnOn();
            bpDisplay.TurnOn();
            hrDisplay.TurnOn();
            bcDisplay.TurnOn();
            bscDisplay.TurnOn();
        }
        private void SetGeneralBroadcastMessage()
        {
            //At the given frequency specified by the set message period, a master channel will broadcast the contents of its buffer.
            //This buffer contains whatever was last sent by the device, so it is important to manage it if the master broadcast
            //contains information being used elsewhere. It is recommended to set the broadcast message to what it should be every time
            //you receive an EVENT_TX message
            //The sendBroadcast function sets the buffer. On a slave device, a single broadcast
            //message will be sent.
            byte[] fecArray = new byte[8];
            fecArray[0] = 0x10; // General FE Data Page
            fecArray[1] = 25;   // Trainer
            fecArray[2] = 0;
            fecArray[3] = 0;
            fecArray[4] = 0xFF;
            fecArray[5] = 0xFF;
            fecArray[6] = 0xFF;
            fecArray[7] = 0x18;

            if (!antDevice.getChannel(0).sendBroadcastData(fecArray))
            {
                threadSafePrintLine("Broadcast Message Failed");
            }
        }
Exemple #16
0
        ////////////////////////////////////////////////////////////////////////////////
        // 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");
                }
            }
        }
Exemple #17
0
        /*  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);
            }
        }
Exemple #18
0
    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;
    }
Exemple #19
0
    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;
    }
        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!");
            }
        }
Exemple #21
0
        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);
            }
        }
Exemple #22
0
        public AntPlusDevMgr()
        {
            if (antStick == null)
            {
                ANT_Common.enableDebugLogs();
                findUsableAntDevice();
            }

            if (AntPlusRacerConfig.getInstance().remoteControlDevNum_negativeIsOff > 0)
            {
                numChannelsForDevices = antStick.getNumChannels() - 1;
                RacerRemoteControl.startRemoteControl(antStick.getChannel(numChannelsForDevices));
            }
            else
            {
                numChannelsForDevices = antStick.getNumChannels();
            }

            //Add all devices from config
            foreach (AntPlusRacerConfig.RacerInput i in AntPlusRacerConfig.getInstance().enabledRacerInputs)
            {
                switch (i.type)
                {
                case AntPlusRacerConfig.RacerInputType.ant_BikeCad_UsingSpd:
                    ds_AntPlus_BikeSpd spdOnly = new ds_AntPlus_BikeSpd();
                    deviceList.Add(new AntPlus_Connection(spdOnly));
                    deviceList.Add(new AntPlus_Connection(new ds_AntPlus_BikeCad_UsingSpd(spdOnly)));
                    break;

                case AntPlusRacerConfig.RacerInputType.ant_BikeCadAndSpd:
                    deviceList.Add(new AntPlus_Connection(new ds_AntPlus_BikeSpdCad()));
                    break;

                case AntPlusRacerConfig.RacerInputType.ant_BikeSpd:
                    deviceList.Add(new AntPlus_Connection(new ds_AntPlus_BikeSpd()));
                    break;

                case AntPlusRacerConfig.RacerInputType.ant_FitEqpmt:
                    deviceList.Add(new AntPlus_Connection(new ds_AntPlus_Fit()));
                    break;

                case AntPlusRacerConfig.RacerInputType.ant_StrideSDM:
                    deviceList.Add(new AntPlus_Connection(new ds_AntPlus_StrideSDM()));
                    break;

                default:        //Not one of the ant types, ignore
                    break;
                }

                if (i.defaultDeviceId != 0)
                {
                    deviceList.Last().dataSource.searchProfile.deviceNumber = i.defaultDeviceId;
                }

                if (!String.IsNullOrWhiteSpace(i.displayName))
                {
                    deviceList.Last().dataSource.customSourceName = i.displayName;
                }
            }

            startNextSearch();
        }
        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();
        }
Exemple #24
0
    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);
        }
    }
Exemple #25
0
        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.");
            }
        }
        //Creates the ANTDevice instances and calls the setupAndOpen routine according to the selected demo mode
        private 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();

                //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;

                //Now handle the rest of the setup based on what mode we are in
                switch (comboBox_demoMode.SelectedIndex)
                {
                case 0:     //Dev 0 - Master, Dev1 - Slave
                    textBox_Display.Text = "Starting Mode: d0-Master, d1-Slave" + Environment.NewLine;

                    //In this library we can connect to multiple devices by creating a new instance of an ANTDevice
                    //So, in this mode we need a second device
                    try
                    {
                        device1 = new ANT_Device();
                    }
                    catch (Exception ex)        //Forward the exception with some more info
                    {
                        throw new Exception("Can not connect to second device, " + ex.Message);
                    }
                    textBox_device1.Text      = "Device 1 Connected" + Environment.NewLine;
                    textBox_device1.IsEnabled = true;

                    //We need to assign the device1 response function now too
                    device1.deviceResponse += new ANT_Device.dDeviceResponseHandler(device1_deviceResponse);
                    device1.getChannel(0).channelResponse += new dChannelResponseHandler(d1channel0_channelResponse);

                    //To be a little clearer we handle the setup in a common method which takes the device instance
                    //and the channel type enum
                    setupAndOpen(device0, ANT_ReferenceLibrary.ChannelType.BASE_Master_Transmit_0x10);
                    setupAndOpen(device1, ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00);
                    break;


                case 1:     //Dev 0 Only - Master
                    textBox_Display.Text      = "Starting Mode: d0 only - Master" + Environment.NewLine;
                    textBox_device1.Text      = "Device 1 Not Used" + Environment.NewLine;
                    textBox_device1.IsEnabled = false;
                    setupAndOpen(device0, ANT_ReferenceLibrary.ChannelType.BASE_Master_Transmit_0x10);
                    break;

                case 2:     //Dev 0 Only - Slave
                    textBox_Display.Text      = "Starting Mode: d0 only - Slave" + Environment.NewLine;
                    textBox_device1.Text      = "Device 1 Not Used" + Environment.NewLine;
                    textBox_device1.IsEnabled = false;
                    setupAndOpen(device0, ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00);
                    break;
                }
            }
            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);
        }
Exemple #27
0
        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 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);
            }
        }