Esempio n. 1
0
        internal void ConfigureANT()
        {
            Console.WriteLine("Resetting module 0 ...");
            device0.ResetSystem();
            System.Threading.Thread.Sleep(500);

            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("Setting Channel ID...");
            channel0.setChannelSearchTimeout((byte)100, 100);
            if (channel0.setChannelID(0, false, 40, 0, 8192))
            {
                Console.WriteLine("Channel ID set");
            }
            else
            {
                Console.WriteLine("Error configuring Channel ID");
            }

            radarEquipmentDisplay = new BikeRadarDisplay(channel0, networkAntPlus);

            radarEquipmentDisplay.DataPageReceived          += radarEquipment_DataPageReceived;
            radarEquipmentDisplay.RadarSensorFound          += radarEquipment_Found;
            radarEquipmentDisplay.RadarTargetsAPageReceived += radarEquipment_RadarTargetsAPageReceived;
            radarEquipmentDisplay.RadarTargetsBPageReceived += radarEquipment_RadarTargetsBPageReceived;
            radarEquipmentDisplay.TurnOn();
        }
Esempio n. 2
0
        void findUsableAntDevice()
        {
            List <ANT_Device> unusableDevices = new List <ANT_Device>();

            try
            {
                antStick = new ANT_Device();

                //Get new devices until we
                //lowpri and prox search is enough now to ensure we get a device that behave as we expected
                while (antStick.getDeviceCapabilities().lowPrioritySearch == false || antStick.getDeviceCapabilities().ProximitySearch == false)
                {
                    unusableDevices.Add(antStick); //keep the last device ref so we don't see it again
                    antStick = new ANT_Device();   //this will throw an exception when there are no devices left
                }

                if (!antStick.setNetworkKey(0, ANTPLUS_NETWORK_KEY, 500))
                {
                    throw new ApplicationException("Failed to set network key");
                }
            }
            catch (Exception ex)
            {
                ANT_Device.shutdownDeviceInstance(ref antStick);                       //Don't leave here with an invalid device ref
                throw new Exception("Could not connect to valid USB2: " + ex.Message); //forward the exception
            }
            finally
            {
                //Release all the unusable devices
                foreach (ANT_Device i in unusableDevices)
                {
                    i.Dispose();
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Configure the host search parameters, and begin the search
        /// </summary>
        /// <param name="antDevice">ANT USB device</param>
        public void ConfigureHost(ANT_Device antDevice)
        {
            // Configure ANT channel parameters
            antfsHost.SetNetworkKey(Demo.NetworkNumber, Demo.NetworkKey);
            antfsHost.SetChannelID(Demo.DeviceType, Demo.TransmissionType);
            antfsHost.SetChannelPeriod(Demo.ChannelPeriod);

            // Configure search parameters
            if (antfsHost.AddSearchDevice(ClientDeviceID, Demo.ClientManufacturerID, Demo.ClientDeviceType) == 0)
            {
                throw new Exception("Error adding search device: ");
            }

            if (Demo.AntfsBroadcast)
            {
                // If we want to use ANT-FS broadcast mode, and start the channel in broadcast mode,
                // setup callback to handle responses for channel 0 while in broadcast mode
                channel0.channelResponse += new dChannelResponseHandler(HandleChannelResponses);

                // Configure the channel as a slave, and look for messages from the master in the channel callback
                // This demo will automatically switch to ANT-FS mode after a few seconds
                if (!antDevice.setNetworkKey(Demo.NetworkNumber, Demo.NetworkKey, 500))
                {
                    throw new Exception("Error configuring network key");
                }
                if (!channel0.assignChannel(ANT_ReferenceLibrary.ChannelType.BASE_Slave_Receive_0x00, Demo.NetworkNumber, 500))
                {
                    throw new Exception("Error assigning channel");
                }
                if (!channel0.setChannelID(DeviceNumber, false, Demo.DeviceType, Demo.TransmissionType, 500))
                {
                    throw new Exception("Error configuring Channel ID");
                }
                if (!channel0.setChannelFreq(Demo.SearchRF, 500))
                {
                    throw new Exception("Error configuring radio frequency");
                }
                if (!channel0.setChannelPeriod(Demo.ChannelPeriod, 500))
                {
                    throw new Exception("Error configuring channel period");
                }
                if (!channel0.openChannel(500))
                {
                    throw new Exception("Error opening channel");
                }
            }
            else
            {
                // Start searching directly for an ANT-FS client matching the search criteria
                // NOTE: If not interested in the payload while in broadcast mode and intend to start a session right away,
                // you can specify useRequestPage = true to search for broadcast devices, and automatically request them
                // to switch to ANT-FS mode
                antfsHost.SearchForDevice(Demo.SearchRF, ConnectRF, DeviceNumber);
            }

            Console.WriteLine("Searching for devices...");

            // Setup a timer, so that we can cancel the search if no device is found
            searchTimer = new Timer(SearchExpired, null, SearchTimeout * 1000, Timeout.Infinite); // convert time to milliseconds
        }
Esempio n. 4
0
 public void Init()
 {
     usbDevice = new ANT_Device();
     usbDevice.ResetSystem();
     usbDevice.setNetworkKey(0, NETWORK_KEY);
     network = new AntPlus.Types.Network(0, NETWORK_KEY, CHANNEL_FREQUENCY);
 }
Esempio n. 5
0
        private static void ConfigureANT()
        {
            WriteLog("Configuring ANT communication...");
            WriteLog("Resetting ANT USB Dongle...");
            device0.ResetSystem();              // Soft reset
            System.Threading.Thread.Sleep(500); // Delay 500ms after a reset

            WriteLog("Setting ANT network key...");
            if (device0.setNetworkKey(USER_NETWORK_NUM, USER_NETWORK_KEY, 500))
            {
                WriteLog("ANT network key setting successful");
            }
            else
            {
                throw new Exception("Error configuring network key");
            }

            WriteLog("Setting Channel ID...");
            //channel0.setChannelTransmitPower(ANT_ReferenceLibrary.TransmitPower.RADIO_TX_POWER_0DB_0x03,500);
            if (channel0.setChannelID(USER_DEVICENUM, USER_PAIRINGENABLED, USER_DEVICETYPE, USER_TRANSTYPE, USER_RESPONSEWAITTIME))  // Not using pairing bit
            {
                WriteLog("Channel ID: " + channel0.getChannelNum());
            }
            else
            {
                throw new Exception("Error configuring Channel ID");
            }

            genericControllableDevice = new GenericControllableDevice(channel0, networkAntPlus);
            genericControllableDevice.DataPageReceived += GenericControllableDevice_DataPageReceived;
            genericControllableDevice.TurnOn();
            //CheckUsbDongle();
        }
Esempio n. 6
0
 public void Reconnect(ANT_Device previousDevice)
 {
     device = previousDevice;
     device.deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse);
     device.serialError    += new ANT_Device.dSerialErrorHandler(SerialErrorHandler);
     device.ResetSystem();
     device.setNetworkKey(0, NETWORK_KEY, 500);
 }
Esempio n. 7
0
    public void Reconnect(ANT_Device previousDevice)
    {
        int usbNum = previousDevice.getOpenedUSBDeviceNum();

        devices[usbNum] = previousDevice;
        previousDevice.deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse);
        previousDevice.serialError    += new ANT_Device.dSerialErrorHandler(SerialErrorHandler);
        previousDevice.ResetSystem();
        previousDevice.setNetworkKey(0, NETWORK_KEY, 500);
    }
Esempio n. 8
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);
    }
        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();
        }
Esempio n. 10
0
    public void Init()
    {
        messageQueue = new Queue <ANT_Response>(16);
        errorQueue   = new Queue <SerialError>(16);
        channelList  = new List <AntChannel>();

        //init the device
        if (device == null)
        {
            device = new ANT_Device();
            device.deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse);
            device.serialError    += new ANT_Device.dSerialErrorHandler(SerialErrorHandler);
            device.ResetSystem();
            device.setNetworkKey(0, NETWORK_KEY, 500);
        }
    }
        private static void ConfigureANT()
        {
            Console.WriteLine("Resetting module 0 ...");
            device0.ResetSystem();
            System.Threading.Thread.Sleep(500);

            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("Setting Channel ID...");
            if (channel0.setChannelID(1, false, 17, 0, 8192))
            {
                Console.WriteLine("Channel ID set");
            }
            else
            {
                throw new Exception("Error configuring Channel ID");
            }

            Console.WriteLine("Setting Channel ID...");
            if (channel1.setChannelID(1, false, 11, 5, 8182))
            {
                Console.WriteLine("Channel ID set");
            }
            else
            {
                throw new Exception("Error configuring Channel ID");
            }

            fitnessEquipmentDisplay = new FitnessEquipmentDisplay(channel0, networkAntPlus);
            fitnessEquipmentDisplay.SpecificTrainerPageReceived += FitnessEquipmentDisplay_SpecificTrainerPage;
            fitnessEquipmentDisplay.TurnOn();

            bikePowerOnlySensor = new BikePowerOnlySensor(channel1, networkAntPlus);
            bikePowerOnlySensor.TurnOn();
        }
Esempio n. 12
0
        public Network()
        {
            device = new ANT_Device();                                                      // Create a device instance using the automatic constructor (automatic detection of USB device number and baud rate)
            device.deviceResponse += new ANT_Device.dDeviceResponseHandler(DeviceResponse); // Add device response function to receive protocol event messages

            device.ResetSystem();                                                           // Soft reset
            System.Threading.Thread.Sleep(500);                                             // Delay 500ms after a reset

            // If you call the setup functions specifying a wait time, you can check the return value for success or failure of the command
            // This function is blocking - the thread will be blocked while waiting for a response.
            // 500ms is usually a safe value to ensure you wait long enough for any response
            // If you do not specify a wait time, the command is simply sent, and you have to monitor the protocol events for the response,
            if (!device.setNetworkKey(USER_NETWORK_NUM, USER_NETWORK_KEY, 500))
            {
                throw new Exception("Error configuring network key");
            }

            device.enableRxExtendedMessages(true);
        }
Esempio n. 13
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);
            }
        }
Esempio n. 14
0
        public void Start()
        {
            try
            {
                usbDevice = new ANT_Device();
                usbDevice.ResetSystem();
                usbDevice.setNetworkKey(0, NETWORK_KEY);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.Read();
                return;
            }

            network = new AntPlus.Types.Network(0, NETWORK_KEY, CHANNEL_FREQUENCY);
            Console.WriteLine(ConfigurationManager.AppSettings["model"]);
            if (ConfigurationManager.AppSettings["ridermodel"] == "fec")
            {
                Console.WriteLine("Using FEC for physical model.");
                bikeModel = BikeModel.FEC;
            }
            else if (ConfigurationManager.AppSettings["ridermodel"] == "physics")
            {
                Console.WriteLine("Using integrated model for physical model.");
                bikeModel = BikeModel.BikePhysics;
            }

            AntManagerState.Initialize(Single.Parse(ConfigurationManager.AppSettings["cp"]));

            InitHRM(0);
            InitCAD(1);
            InitFEC(2);
            InitBP(3);
            InitSC(4);
            InitAC();
            InitFIT();
        }
Esempio n. 15
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);
            }
        }
Esempio n. 16
0
        ////////////////////////////////////////////////////////////////////////////////
        // ConfigureANT
        //
        // Resets the system, configures the ANT channel and starts the demo
        ////////////////////////////////////////////////////////////////////////////////
        private static void ConfigureANT()
        {
            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 (channel0.assignChannel(channelType, USER_NETWORK_NUM, 500))
            {
                Console.WriteLine("Channel assigned");
            }
            else
            {
                throw new Exception("Error assigning channel");
            }

            Console.WriteLine("Setting Channel ID...");
            if (channel0.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 (channel0.setChannelFreq(USER_RADIOFREQ, 500))
            {
                Console.WriteLine("Radio Frequency set");
            }
            else
            {
                throw new Exception("Error configuring Radio Frequency");
            }

            Console.WriteLine("Setting Channel Period...");
            if (channel0.setChannelPeriod(user_channelperiod, 500))
            {
                Console.WriteLine("Channel Period set");
            }
            else
            {
                throw new Exception("Error configuring Channel Period");
            }

            Console.WriteLine("Opening channel...");
            bBroadcasting = true;
            if (channel0.openChannel(500))
            {
                Console.WriteLine("Channel opened");
            }
            else
            {
                bBroadcasting = false;
                throw new Exception("Error opening channel");
            }

#if (ENABLE_EXTENDED_MESSAGES)
            // Extended messages are not supported in all ANT devices, so
            // we will not wait for the response here, and instead will monitor
            // the protocol events
            Console.WriteLine("Enabling extended messages...");
            device0.enableRxExtendedMessages(true);
#endif
        }
Esempio n. 17
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);
        }
    }
Esempio n. 18
0
        ////////////////////////////////////////////////////////////////////////////////
        // ConfigureANT
        //
        // Resets the system, configures the ANT channel and starts the demo
        ////////////////////////////////////////////////////////////////////////////////
        private static void ConfigureANT()
        {
            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 (channel0.assignChannel(channelType, USER_NETWORK_NUM, 500))
            {
                Console.WriteLine("Channel assigned");
            }
            else
            {
                throw new Exception("Error assigning channel");
            }

            Console.WriteLine("Setting Channel ID...");
            if (channel0.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 (channel0.setChannelFreq(USER_RADIOFREQ, 500))
            {
                Console.WriteLine("Radio Frequency set");
            }
            else
            {
                throw new Exception("Error configuring Radio Frequency");
            }

            Console.WriteLine("Setting Channel Period...");
            if (channel0.setChannelPeriod(USER_CHANNELPERIOD, 500))
            {
                Console.WriteLine("Channel Period set");
            }
            else
            {
                throw new Exception("Error configuring Channel Period");
            }

            Console.WriteLine("Opening channel...");
            bBroadcasting = true;
            if (channel0.openChannel(500))
            {
                Console.WriteLine("Channel opened");
            }
            else
            {
                bBroadcasting = false;
                throw new Exception("Error opening channel");
            }
        }
Esempio n. 19
0
        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();
        }
Esempio n. 20
0
        private void setupAndOpenScan(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
            {
                if (!deviceToSetup.setNetworkKey(0, USER_NETWORK_KEY, 500))
                {
//                    threadSafePrintLine("Network Key set to ... well, you know,  on net 0.", textBox_Display);
//                else
                    throw new Exception("Channel assignment operation failed.");
                }


                //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(USER_DEVICENUM, false, USER_DEVICETYPE, USER_TRANSTYPE, 500))
                {
//                    threadSafePrintLine("Set channel ID to " + USER_DEVICENUM + " " + USER_DEVICETYPE + " " + USER_TRANSTYPE, 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(USER_CHANNELPERIOD, 500))
                {
//                    threadSafePrintLine("Message Period set to " + USER_CHANNELPERIOD + "/32768 seconds per message", textBox_Display);
//                else
                    throw new Exception("Set Channel Period Op Faildd.");
                }

                if (!channel0.setChannelFreq(USER_RADIOFREQ, 500))
                {
//                    threadSafePrintLine("Message Radio Freq set to +" + USER_RADIOFREQ, textBox_Display);
//                else
                    throw new Exception("Set Radio Freq failed.");
                }

                if (!deviceToSetup.enableRxExtendedMessages(true, 500))
                {
//                    threadSafePrintLine("Requesting Extended Messages", textBox_Display);
//                else
                    throw new Exception("Extenned Message Request Failed.");
                }



                //Now we open the channel
                if (!deviceToSetup.openRxScanMode(500))
                {
//                    threadSafePrintLine("Opened Device in Scan mode" + 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);
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Configure the client beacon parameters, and start transmitting/beaconing
        /// </summary>
        /// <param name="antDevice">ANT USB device</param>
        public void ConfigureClient(ANT_Device antDevice)
        {
            // Configure ANT Channel parameters
            antfsClient.SetClientNetworkKey(0, Demo.NetworkKey);
            antfsClient.SetChannelID(Demo.DeviceType, Demo.TransmissionType);
            antfsClient.SetChannelPeriod(Demo.ChannelPeriod);

            // Setup client configuration parameters.
            // ANTFS_ClientParameters is a struct, so make sure to initialize ALL parameters
            ANTFS_ClientParameters clientConfig = new ANTFS_ClientParameters();

            clientConfig.BeaconDeviceType     = Demo.ClientDeviceType;
            clientConfig.BeaconManufacturerID = Demo.ClientManufacturerID;
            clientConfig.BeaconRadioFrequency = Demo.SearchRF;
            clientConfig.LinkPeriod           = Demo.LinkPeriod;
            clientConfig.AuthenticationType   = ClientAuthenticationType;
            clientConfig.IsDataAvailable      = DataAvailable;
            clientConfig.IsPairingEnabled     = PairingEnabled;
            clientConfig.IsUploadEnabled      = UploadEnabled;
            clientConfig.BeaconTimeout        = BeaconTimeout;
            clientConfig.PairingTimeout       = PairingTimeout;
            clientConfig.SerialNumber         = antDevice.getSerialNumber(); // Use the serial number of the USB stick to identify the client

            // Apply configuration
            antfsClient.Configure(clientConfig);

            // Configure friendly name and passkey (optional)
            antfsClient.SetFriendlyName(ClientFriendlyName);
            antfsClient.SetPassKey(PassKey);

            // Create directory, an add a single entry, of the configured size
            dirFS = new ANTFS_Directory();
            ANTFS_Directory.Entry fileEntry;
            fileEntry.FileIndex     = 1;
            fileEntry.FileSize      = TestFileSize;
            fileEntry.FileDataType  = 1;
            fileEntry.FileNumber    = 1;
            fileEntry.FileSubType   = 0;
            fileEntry.GeneralFlags  = (byte)(ANTFS_Directory.GeneralFlags.Read | ANTFS_Directory.GeneralFlags.Write | ANTFS_Directory.GeneralFlags.Erase);
            fileEntry.SpecificFlags = 0;
            fileEntry.TimeStamp     = 0; // TODO: Encode the timestamp properly
            dirFS.AddEntry(fileEntry);

            if (Demo.AntfsBroadcast)
            {
                // If we want to use ANT-FS broadcast mode, and start the channel in broadcast mode,
                // setup callback to handle responses for channel 0 while in broadcast mode
                channel0.channelResponse += new dChannelResponseHandler(HandleChannelResponses);

                // Configure the channel as a master, and look for the request message in the channel callback
                // to switch to ANT-FS mode
                if (!antDevice.setNetworkKey(Demo.NetworkNumber, Demo.NetworkKey, 500))
                {
                    throw new Exception("Error configuring network key");
                }
                if (!channel0.assignChannel(ANT_ReferenceLibrary.ChannelType.BASE_Master_Transmit_0x10, Demo.NetworkNumber, 500))
                {
                    throw new Exception("Error assigning channel");
                }
                if (!channel0.setChannelID((ushort)clientConfig.SerialNumber, false, Demo.DeviceType, Demo.TransmissionType, 500))
                {
                    throw new Exception("Error configuring Channel ID");
                }
                if (!channel0.setChannelFreq(Demo.SearchRF, 500))
                {
                    throw new Exception("Error configuring radio frequency");
                }
                if (!channel0.setChannelPeriod(Demo.ChannelPeriod, 500))
                {
                    throw new Exception("Error configuring channel period");
                }
                if (!channel0.openChannel(500))
                {
                    throw new Exception("Error opening channel");
                }
            }
            else
            {
                // If we want to start in ANT-FS mode, just open the beacon
                antfsClient.OpenBeacon();
            }
        }