示例#1
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;
    }
示例#2
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");
            }
        }
        /// <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
        }
        private void startChannel()
        {
            //Just try this in case we get an active channel for some reason
            channel.closeChannel(500);
            channel.unassignChannel(500);

            if (!channel.assignChannel(ANT_ReferenceLibrary.ChannelType.BASE_Master_Transmit_0x10, 0, 500))
            {
                statusReport = "Failed to start, assign() failed";
            }
            else if (!channel.setChannelID((ushort)deviceNum, false, 9, 5, 500))
            {
                statusReport = "Failed to start, setChannelId() failed";
            }
            else if (!channel.setChannelFreq(57, 500))
            {
                statusReport = "Failed to start, setChannelFreq() failed";
            }
            else if (!channel.setChannelPeriod(32768, 500))
            {
                statusReport = "Failed to start, setChannelPeriod() failed";
            }
            else if (!channel.setChannelTransmitPower(ANT_ReferenceLibrary.TransmitPower.RADIO_TX_POWER_0DB_0x03, 500))
            {
                statusReport = "Failed to start, setChannelTransmitPower() failed";
            }
            else if (!channel.openChannel(500))
            {
                statusReport = "Failed to start, openChannel() failed";
            }
            else
            {
                statusReport = "Remote Control Channel is open";
            }
        }
示例#5
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);
    }
示例#6
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
        }
        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);
            }
        }
        /// <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();
            }
        }
示例#9
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.");
            }
        }
示例#10
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");
            }
        }
示例#11
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);
        }
    }
示例#12
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();
        }