/// <summary> /// Sends a packet out over Bluetooth Low Energy. Spins up a watcher /// for advertisements from nearby servers who can receive the packet. /// </summary> /// <param name="packet"></param> private void SendPacketOverBluetoothLE( byte[] packet, IPAddress destinationAddress ) { // Fire up the Bluetooth Advertisement packet write // watcher IPv6ToBleAdvWatcherPacketWrite packetWriter = new IPv6ToBleAdvWatcherPacketWrite(); // Start the watcher. This causes it to write the // packet when it finds a suitable recipient. packetWriter.Start(packet, destinationAddress, staticRoutingTable ); // Wait for the watcher to signal the event that the // packet has transmitted. This should happen after the // watcher receives an advertisement OR a timeout of // 5 seconds occurs. Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while (!packetTransmissionFinished || stopwatch.Elapsed < TimeSpan.FromSeconds(5) ) { ; } stopwatch.Stop(); // Check transmission status if (!packetTransmittedSuccessfully) { Debug.WriteLine("Could not transmit the packet" + " over Bluetooth LE successfully." ); } else { // We successfully transmitted the packet! Cue fireworks. Debug.WriteLine("Successfully transmitted this " + "packet:\n" + Utilities.BytesToString(packet) + "\n" + "to this address:\n" + destinationAddress.ToString() ); } // Stop the watcher packetWriter.Stop(); // Reset the packet booleans for next time packetTransmissionFinished = false; packetTransmittedSuccessfully = false; }
//--------------------------------------------------------------------- // Listeners for when packets are transmitted or received //--------------------------------------------------------------------- /// <summary> /// Awaits the asynchronous packet transmission operations by listening /// for the event from the Adv watcher that signals whether the packet /// transmitted successfully. /// /// This is so a client can know when the packet has finished the /// transmission process. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> /// <returns></returns> private void WatchForPacketTransmission( IPv6ToBleAdvWatcherPacketWrite sender, PropertyChangedEventArgs eventArgs ) { if (eventArgs.PropertyName == "TransmittedSuccessfully") { packetTransmissionFinished = true; packetTransmittedSuccessfully = sender.TransmittedSuccessfully; } }