private static void kinect_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            Skeleton[] skeletons = new Skeleton[0];

            using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
            {
                if (skeletonFrame != null)
                {
                    skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
                    skeletonFrame.CopySkeletonDataTo(skeletons);
                }
            }

            if (skeletons.Length != 0)
            {
                foreach (Skeleton skel in skeletons)
                {
                    if (skel.TrackingState == SkeletonTrackingState.Tracked)
                    {
                        SkeletonPoint leftWrist  = skel.Joints[JointType.WristLeft].Position;
                        SkeletonPoint rightWrist = skel.Joints[JointType.WristRight].Position;
                        SkeletonPoint hipCenter  = skel.Joints[JointType.HipCenter].Position;

                        int hipCenter_Z  = Convert.ToInt32(hipCenter.Z * 100);
                        int leftWrist_Z  = (hipCenter_Z - Convert.ToInt32(leftWrist.Z * 100)) < 0 ? 0 : hipCenter_Z - Convert.ToInt32(leftWrist.Z * 100);
                        int leftWrist_Y  = (Convert.ToInt32(leftWrist.Y * 100)) < 0 ? 0 : Convert.ToInt32(leftWrist.Y * 100);
                        int rightWrist_Z = (hipCenter_Z - Convert.ToInt32(rightWrist.Z * 100)) < 0 ? 0 : hipCenter_Z - Convert.ToInt32(rightWrist.Z * 100);
                        int rightWrist_Y = (Convert.ToInt32(rightWrist.Y * 100)) < 0 ? 0 : Convert.ToInt32(rightWrist.Y * 100);

                        Console.WriteLine("{0} | {1} | {2} | {3} | {4} | {5}", skel.TrackingId, leftWrist_Z, leftWrist_Y, rightWrist_Z, rightWrist_Y, hipCenter_Z);

                        try
                        {
                            BluetoothAddress addr = BluetoothAddress.Parse("00:80:37:2e:31:20");
                            Guid             serviceClass;
                            serviceClass = BluetoothService.BluetoothBase;
                            var ep  = new BluetoothEndPoint(addr, serviceClass, 2);
                            var cli = new BluetoothClient();

                            Console.WriteLine("Trying to connect...");
                            cli.Connect(ep);
                            Console.WriteLine("just connected");
                            Stream peerStream = cli.GetStream();

                            // Send this players left and right arm data
                            string msg = String.Format("{0}{1}{2}{3}{4}", Convert.ToChar(skel.TrackingId), Convert.ToChar(leftWrist_Y), Convert.ToChar(leftWrist_Z), Convert.ToChar(rightWrist_Y), Convert.ToChar(rightWrist_Z));
                            Console.WriteLine("Sending msg");
                            Byte[] to_send = System.Text.Encoding.ASCII.GetBytes(msg);
                            peerStream.Write(to_send, 0, to_send.Length);
                            peerStream.Close();
                            cli.Close();
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("ERROR: Could not connect to Bluetooth Server");
                        }
                        Thread.Sleep(100); // 10Hz update rate
                    }
                }
            }
        }
예제 #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BluetoothConnection"/> class.
 /// The server received a request.
 /// </summary>
 /// <param name="bluetoothClient">The bluetooth client.</param>
 internal BluetoothConnection(BluetoothClient bluetoothClient) : this()
 {
     Client = bluetoothClient;
     stream = Client.GetStream();
     Init();
 }
 public static Task ConnectAsync(this BluetoothClient client, BluetoothAddress address, Guid service)
 {
     return(Task.Factory.FromAsync(client.BeginConnect, client.EndConnect, address, service, null));
 }
예제 #4
0
        private ObexStatusCode Connect()
        {
            if (!connected)
            {
                if (ns == null)
                {
                    try {
                        if (uri.Host.Length == 0)
                        {
                            System.Diagnostics.Debug.Assert(m_alreadyConnectedObexStream != null);
                            System.Diagnostics.Debug.Assert(m_alreadyConnectedObexStream.CanRead &&
                                                            m_alreadyConnectedObexStream.CanWrite);
                            ns = m_alreadyConnectedObexStream;
                        }
                        else
                        {
                            BluetoothAddress ba;

                            if (BluetoothAddress.TryParse(uri.Host, out ba))
                            {
                                BluetoothClient cli = new BluetoothClient();
                                Guid            serviceGuid;

                                switch (uri.Scheme)
                                {
                                case SchemeNames.Ftp:
                                    serviceGuid = BluetoothService.ObexFileTransfer;
                                    break;

                                //potential for other obex based profiles to be added
                                case SchemeNames.Sync:
                                    serviceGuid = BluetoothService.IrMCSyncCommand;
                                    break;

                                case SchemeNames.Pbap:
                                    serviceGuid = BluetoothService.PhonebookAccessPse;
                                    break;

                                case SchemeNames.Map:
                                    serviceGuid = BluetoothService.MessageAccessProfile;
                                    break;

                                default:
                                    serviceGuid = BluetoothService.ObexObjectPush;
                                    break;
                                }

                                cli.Connect(ba, serviceGuid);
                                ns = cli.GetStream();
                            }
                            else
                            {
                                //assume a tcp host
                                s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                                IPAddress ipa       = null;
                                var       addresses = System.Net.Dns.GetHostAddresses(uri.Host);
                                if (addresses.Length > 0)
                                {
                                    ipa = addresses[0];
                                }
                                else
                                {
                                    throw new WebException("Host not recognised", WebExceptionStatus.NameResolutionFailure);
                                }

                                IPEndPoint ipep = new IPEndPoint(ipa, 650);

                                s.Connect(ipep);
                            }

                            if (ns == null) // BluetoothClient used above
                            {
                                ns = new System.Net.Sockets.NetworkStream(s, true);
                            }

                            // Timeout
                            //ns.ReadTimeout = timeout;
                            //ns.WriteTimeout = timeout;
                        }

                        return(Connect_Obex());
                    } finally {
                        if (s != null && !s.Connected)
                        {
                            s = null;
                        }
                    }
                }
            }
            Debug.Fail("Don't know that we every get here (Connect when connected).");
            return((ObexStatusCode)0);
        }
        private void recivebtms()
        {
            this.label1.Text = "CZEKAM NA DANE";
            label1.Refresh();
            BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
            byte[] bytecount = new byte[1024];
            File.Delete(dfile);

            byte[] flaga = new byte[1];
            flaga[0] = 0;
            BluetoothListener listener = new BluetoothListener(BluetoothService.SerialPort);

            listener.Start();
            int licznik = 0;

            client = listener.AcceptBluetoothClient();
            while (client.Connected == false && licznik != 30)
            {
                licznik += 1;

                label1.Text = "CZEKAM NA PO£¥CZENIE 30 sekund: " + licznik.ToString();
                label1.Focus();
                System.Threading.Thread.Sleep(1000);
                label1.Refresh();
            }

            if (licznik >= 30)
            {
                listener.Stop();


                label1.Text = "KONIEC CZASU";
                label1.Refresh();
            }
            else
            {
                //    Thread.Sleep(1000);
                //timeout += 1;


                Stream peerStream = client.GetStream();

                peerStream.Write(flaga, 0, 1);

                peerStream.Read(bytecount, 0, bytecount.Length);
                Thread.Sleep(2000);
                int lenght = BitConverter.ToInt32(bytecount, 0);
                this.label1.Text = "ODBIERAM DANE: " + (lenght / 1024).ToString() + " Kb";
                label1.Refresh();
                byte[] buffer = new byte[1024];



                if (peerStream.CanRead == true)
                {
                    int remaining = lenght;
                    while (remaining > 0)
                    {
                        peerStream.Flush();

                        int read = peerStream.Read(data, 0, data.Length);

                        if (remaining > 0)
                        {
                            System.IO.FileStream file = new FileStream(dfile, FileMode.Append, FileAccess.Write);
                            file.Write(data, 0, read);
                            file.Close();
                        }
                        remaining -= read;
                    }
                }

                flaga[0] = 2;
                peerStream.Write(flaga, 0, 1);
                listener.Stop();


                this.label1.Text = "ZAPISUJE DANE: " + (lenght / 1024).ToString() + "Kb " + "PROSZÊ CZEKAÆ";
                label1.Refresh();

                this.label1.Text = "DANE ZAPISANE";
                label1.Refresh();



                //BluetoothRadio.PrimaryRadio.Mode = RadioMode.PowerOff;
            }
        }
예제 #6
0
        public static void FindNXTDevices(object sender, DoWorkEventArgs eventArgs)
        {
            while (continueDeviceDiscovery)
            {
                if (!availableRobots.ContainsKey("USB")) // If a usb was not connected before test it now
                {
                    NXT usbNXT = new NXT("USB", new NXTUsbConnection());
                    if (usbNXT.nxtConn.IsConnected)
                    {
                        availableRobots.Add("USB", usbNXT);
                        OnDeviceAdded(usbNXT);
                    }
                }

                var btClient = new BluetoothClient();
                List <BluetoothClient> btRobots = new List <BluetoothClient>();
                btClient.InquiryLength = new TimeSpan(0, 0, 4);
                BluetoothDeviceInfo[] btDevices = btClient.DiscoverDevicesInRange();
                foreach (BluetoothDeviceInfo btDevice in btDevices)
                {
                    try
                    {
                        // The property InstalledServices only lists services for devices that have been paired with
                        // the computer already (rather than requesting it from the device). This is fine in our
                        // scenario since you cant get a service list off the devices unless it is already paired.
                        if (btDevice.InstalledServices.Contains(NXT32FeetBT.NXT_BT_SERVICE))
                        {
                            String nxtIdentifier = btDevice.DeviceAddress.ToString();
                            if (!availableRobots.ContainsKey(nxtIdentifier))
                            {
                                NXT foundNXT = new NXT(nxtIdentifier, new NXT32FeetBT(btDevice.DeviceAddress));
                                availableRobots.Add(nxtIdentifier, foundNXT);
                                OnDeviceAdded(foundNXT);
                            }
                            else
                            {
                                if (!availableRobots[nxtIdentifier].connected)
                                {
                                    availableRobots[nxtIdentifier].Reconnect();
                                }
                            }
                        }
                    }
                    catch (SocketException e) { } // Socket exception occurs if the device is not an nxt
                }

                // Check if any previously found devices were lost
                var btAddresses = from btDevice in btDevices
                                  select btDevice.DeviceAddress.ToString();

                foreach (NXT nxt in AvailableRobots.Values)
                {
                    if (!btAddresses.Contains(nxt.uniqueID))
                    {
                        nxt.connected = false;
                        nxt.OnDeviceDisconnected();
                    }
                }

                // Sleep for the designated poll interval
                Thread.Sleep(DEVICE_DISCOVERY_POLL_RATE);
            }
        }
예제 #7
0
파일: LiveView.cs 프로젝트: ekx/LiveViewLib
 public LiveView(BluetoothClient client)
 {
     this.client  = client;
     this.address = client.RemoteEndPoint.Address;
 }
예제 #8
0
        /// <summary>
        /// Recherche et active tous les appareils Wii voulant se synchroniser.
        /// </summary>
        /// <param name="removeExisting">Défaut: true; Supprime les appareils Wii connus</param>
        public static void DiscoverWiiDevices(bool removeExisting = true)
        {
            using (var bluetoothClient = new BluetoothClient()) {
                // Par défaut, on souhaite supprimer, les appareils Wii de notre listes d'appareils bluetooth.
                // Sinon, on peut pas recommencer une sync avec une wiimote/board/etc..
                // Du coup on les cherches tous et on les deletes.
                if (removeExisting)
                {
                    // On cherche tous les appareils bluetooth connus.
                    var bluetoothExistingList = bluetoothClient.DiscoverDevices(255, false, true, false);
                    foreach (var item in bluetoothExistingList)
                    {
                        // Si l'appareil ne contient pas Nintendo dans son nom, on le zappe.
                        if (!item.DeviceName.Contains("Nintendo"))
                        {
                            continue;
                        }
                        // Si c'est un appareil Nintendo, on le delete.
                        BluetoothSecurity.RemoveDevice(item.DeviceAddress);
                        item.SetServiceState(BluetoothService.HumanInterfaceDevice, false);
                    }
                }

                // On cherche tous les appareils bluetooth inconnus.
                var bluetoothDiscoveredList = bluetoothClient.DiscoverDevices(255, false, false, true);
                // Une variable utilisée pour filtrer les appareils en cours de synchro, qui ne sont pas de Nintendo
                var bluetoothIgnored = 0;
                foreach (var item in bluetoothDiscoveredList)
                {
                    // Au cas où un appareil ne venant pas de la Wii serait en cours de synchro.
                    if (!item.DeviceName.Contains("Nintendo"))
                    {
                        bluetoothIgnored += 1; // On augmente notre compteur et on ne fait rien avec l'appareil trouvé.
                        continue;
                    }

                    // SYNC PERMANTE ICI, SI JAMAIS ON EN A VRAIMENT BESOIN.

                    // On a trouvé un appareil venant de la Wii, on l'installe comme appareil HID, et on lui laisse un peu de temps pour finir tous ça.
                    item.SetServiceState(BluetoothService.HumanInterfaceDevice, true);
                }
                // Au cas où le pc est un peu long, on lui laisse le temps de finir l'installation avant de se connecter.
                // Valeur arbitraire.
                System.Threading.Thread.Sleep(5000);

                // On se connecte à chaque appareils une fois pour ne pas qu'ils partent en sommeil et disparaissent.
                if (bluetoothDiscoveredList.Length > bluetoothIgnored)
                {
                    // On cherche tous les appareils Wii.
                    var devices = new WiimoteCollection();
                    devices.FindAllWiimotes();

                    foreach (var wiiDevice in devices)
                    {
                        // On se connecte, set une led allumée/éteinte, et se déconnecte.
                        wiiDevice.Connect();
                        wiiDevice.SetLEDs(true, false, false, false);
                        wiiDevice.SetLEDs(false, false, false, false);
                        wiiDevice.Disconnect();
                    }
                }
            }
        }
예제 #9
0
        private void connect()
        {
            try
            {
                this.Dispatcher.Invoke(() =>
                {
                    ConnectionText.Text = "Attempting new Connection\n";
                });
                using (var btClient = new BluetoothClient())
                {
                    var btIgnored = 0;

                    // Find remembered bluetooth devices.
                    this.Dispatcher.Invoke(() =>
                    {
                        ConnectionText.Text += "Removing existing bluetooth devices...\n";
                    });

                    var btExistingList = btClient.DiscoverDevices(255, false, true, false);

                    foreach (var btItem in btExistingList)
                    {
                        if (!btItem.DeviceName.Contains("MSFT Band"))
                        {
                            continue;
                        }

                        BluetoothSecurity.RemoveDevice(btItem.DeviceAddress);
                        btItem.SetServiceState(BluetoothService.HumanInterfaceDevice, false);
                    }

                    // Find unknown bluetooth devices.
                    this.Dispatcher.Invoke(() =>
                    {
                        ConnectionText.Text += "Searching for bluetooth devices...\nMake sure band is in pair mode!\n";
                    });

                    var btDiscoveredList = btClient.DiscoverDevices(255, false, false, true);

                    foreach (var btItem in btDiscoveredList)
                    {
                        if (true && !btItem.DeviceName.Contains("MSFT Band"))
                        {
                            btIgnored += 1;
                            continue;
                        }

                        this.Dispatcher.Invoke(() =>
                        {
                            ConnectionText.Text += "Adding: " + btItem.DeviceName + " ( " + btItem.DeviceAddress + " )\n";
                        });


                        // Install as a HID device and allow some time for it to finish.
                        BluetoothSecurity.PairRequest(btItem.DeviceAddress, null);
                        //btItem.SetServiceState(BluetoothService.HumanInterfaceDevice, true);
                    }

                    // Allow slow computers to finish installation before connecting.

                    System.Threading.Thread.Sleep(4000);

                    // Connect and send a command, otherwise they sleep and the device disappears.

                    try
                    {
                        if (btDiscoveredList.Length > btIgnored)
                        {
                            this.Dispatcher.Invoke(() =>
                            {
                                ConnectionText.Text += "Finished - You can now close this window.\n";
                            });
                        }
                        else
                        {
                            this.Dispatcher.Invoke(() =>
                            {
                                ConnectionText.Text += "Finished - No band(s) found. Please try again.\n";
                            });
                        }
                    }
                    catch (Exception) { }
                }
            }
            catch (Exception ex)
            {
                this.Dispatcher.Invoke(() =>
                {
                    ConnectionText.Text += "Error: " + ex.Message + "\n";
                });
            }
        }
        private void sendbtms()
        {
            BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
            System.IO.FileStream file = new FileStream(ufile, FileMode.Open, FileAccess.Read);
            byte[] buffer             = new byte[file.Length];
            file.Read(buffer, 0, buffer.Length);
            long lenght = file.Length;

            byte[] flaga = new byte[1];
            byte[] bytec = BitConverter.GetBytes(lenght);
            label1.Text = "WYSY£AM";
            label1.Focus();
            label1.Refresh();
            flaga[0] = 22;
            BluetoothListener listener = new BluetoothListener(BluetoothService.SerialPort);

            listener.Start();
            int             licznik = 0;
            BluetoothClient client  = listener.AcceptBluetoothClient();

            while (client.Connected == false && licznik != 30)
            {
                licznik    += 1;
                label1.Text = "CZEKAM NA PO£¥CZENIE 30 sekund: " + licznik.ToString();
                label1.Focus();
                System.Threading.Thread.Sleep(1000);
                label1.Refresh();
            }
            if (licznik >= 30)
            {
                listener.Stop();
                label1.Text = "KONIEC CZASU";
                label1.Refresh();
            }
            else
            {
                //    Thread.Sleep(1000);
                //timeout += 1;


                Stream peerStream = client.GetStream();

                peerStream.Write(flaga, 0, 1);
                System.Threading.Thread.Sleep(3000);
                peerStream.Write(bytec, 0, bytec.Length);


                this.label1.Text = "Wysy³am: " + (lenght / 1024).ToString() + " Kb";
                label1.Refresh();
                peerStream.Write(buffer, 0, buffer.Length);
                System.Threading.Thread.Sleep(3000);
                flaga[0] = 3;
                peerStream.Write(flaga, 0, 1);
                listener.Stop();


                this.label1.Text = "DANE WYS£ANE: " + (lenght / 1024).ToString() + "Kb " + "PROSZÊ CZEKAÆ";
                label1.Refresh();
            }



            //BluetoothRadio.PrimaryRadio.Mode = RadioMode.PowerOff;
        }
예제 #11
0
파일: Form1.cs 프로젝트: D0d0d/VS_C_SH_LB_1
        private void Discover(List <BluetoothDeviceInfo> d)
        {
            lbx.Items.Clear();
            lbx_prop.Items.Clear();
            BluetoothClient bc = new BluetoothClient();

            BluetoothDeviceInfo[] DevList = bc.DiscoverDevices(4);

            string       maclist = "";
            StreamReader sr      = new StreamReader("mac_list.txt");

            maclist += sr.ReadToEnd();
            sr.Close();

            MatchCollection manufacture = Regex.Matches(maclist, @"([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F]).*[^\d]\n", RegexOptions.IgnoreCase);

            string[] mac = new string[manufacture.Count];
            for (int i = 0; i < manufacture.Count; i++)
            {
                MatchCollection temp = Regex.Matches(manufacture[i].ToString(), @"([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F]).*[^\d]\n", RegexOptions.IgnoreCase);
                mac[i] = temp[0].ToString();
            }

            foreach (BluetoothDeviceInfo device in DevList)
            {
                lbx.Items.Add(device.DeviceName);
                lbx.Items.Add("");
                lbx.Items.Add("");
                lbx.Items.Add("");
                lbx.Items.Add("");
                lbx.Items.Add("");
                lbx.Items.Add("");

                lbx_prop.Items.Add("Адрес: " + device.DeviceAddress);
                int k = 0;
                for (int i = 0; i < manufacture.Count; i++)
                {
                    if (mac[i][0] == device.DeviceAddress.ToString()[0] &&
                        mac[i][1] == device.DeviceAddress.ToString()[1] &&
                        mac[i][2] == device.DeviceAddress.ToString()[2] &&
                        mac[i][3] == device.DeviceAddress.ToString()[3] &&
                        mac[i][4] == device.DeviceAddress.ToString()[4] &&
                        mac[i][5] == device.DeviceAddress.ToString()[5]
                        )
                    {
                        k = i;
                        break;
                    }
                }
                lbx_prop.Items.Add("Производитель:" + manufacture[k]);
                lbx_prop.Items.Add("Тип:          " + manufacture[k]);
                lbx_prop.Items.Add("Сопряжен:     " + manufacture[k]);
                lbx_prop.Items.Add("Подключен:    " + manufacture[k]);
                lbx_prop.Items.Add("Сервисы:      " + manufacture[k]);
                lbx_prop.Items.Add("");
            }

            btn_discover.Text    = "Искать устройства";
            btn_discover.Enabled = true;
            this.Cursor          = Cursors.Default;
        }
예제 #12
0
        public BluetoothDeviceInfo[] GetPairDevices()
        {
            BluetoothClient client = new BluetoothClient();

            return(client.DiscoverDevices(10, false, true, false));
        }
예제 #13
0
        /// <summary>
        ///     Sends a message to the Parrot RF Service.
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task <XElement> SendMessageAsync(ParrotMessage message)
        {
            if (!BluetoothClient.Connected)
            {
                throw new Exception($"{nameof(ParrotClient)} is not connected.");
            }

            _waitingList.WaitOne();

            try
            {
                // Debug message
                Console.WriteLine($"=> Sending message '{message.Request}'");

                // Send message to Parrot
                var messageBytes = message.GetRequest();

                await BluetoothClient.GetStream().WriteAsync(messageBytes, 0, messageBytes.Length);

                await BluetoothClient.GetStream().FlushAsync();

                // Hold response element
                XElement answerElement;

                // Hold notifications
                var notifyElements = new List <XElement>();

                // Receive response(s)
                do
                {
                    answerElement = XElement.Parse(await ReceiveResponseAsync());

                    // Find notificiations
                    if (answerElement.Name == "notify")
                    {
                        notifyElements.Add(answerElement);
                    }
                    else if (answerElement.Name == "answer")
                    {
                        var notifyElement = answerElement.XPathSelectElement("/notify");
                        if (notifyElement != null)
                        {
                            notifyElements.Add(notifyElement);
                        }
                    }
                } while (answerElement.Name != "answer");

                // Handle notifications
                foreach (var notifyElement in notifyElements)
                {
                    var notifyPath = notifyElement?.Attribute("path")?.Value;
                    if (notifyPath == null)
                    {
                        continue;
                    }

                    var resource = ResourceManager.Resources.FirstOrDefault(x => x.Value.Equals(notifyPath)).Key;
                    if (resource == ResourceType.UnknownResource && ZikApi.KnowMessages.Contains(notifyPath))
                    {
                        Console.WriteLine($"=> Received unhandled notification {resource} ({notifyPath})");
                        continue;
                    }
                    else if (resource == ResourceType.UnknownResource)
                    {
                        throw new UnknownNotificationException($"Received an unknown notification: {notifyPath}");
                    }

                    // Debug message
                    Console.WriteLine($"=> Dispatching notification {resource} ({notifyPath})");

                    NotificationEvent?.AsyncSafeInvoke(this, new NotifyEventArgs(resource, notifyPath));
                }

                // Return
                return(answerElement);
            }
            finally
            {
                _waitingList.Release();
            }
        }
예제 #14
0
 public void changeStr(BluetoothClient bc, String s)
 {
     nameList[connessioniServer.IndexOf(bc)] = s;
 }
예제 #15
0
        private bool BluetoothConnect(string imuMemory, bool bluetooth, string imuBTName)
        {
            BluetoothDeviceInfo[] devices;
            WriteDataToBox("Connecting to IMU\n");
            String[] deviceaddress = new String[] { "" };
            if (File.Exists(imuMemory))
            {
                deviceaddress = File.ReadAllLines(imuMemory);
            }
            if (deviceaddress[0].Length > 0 && bluetooth == true)
            {
                WriteDataToBox("Attempting Quick Connect\n");
                byte[] address = { 0, 0, 0, 0, 0, 0 };

                for (int i = 0; i < 6; i++)
                {
                    address[i] = (byte)(Convert.ToInt32((deviceaddress[0][10 - (2 * i)].ToString() + deviceaddress[0][11 - (2 * i)].ToString()), 16));
                }
                BluetoothAddress btaddress = new BluetoothAddress(address);
                if (Comms.connectthroughbluetoothaddress(btaddress))
                {
                    WriteDataToBox("Connection Successful\n");
                    Comms.DataIn += new CommunicationsClass.EventHandler(Comms_OnDataIn);
                    return(true);
                }
                else
                {
                    if (bluetooth == true)
                    {
                        WriteDataToBox("Searching for Paired Bluetooth Device...\n");
                        BluetoothClient client = new BluetoothClient();
                        devices = client.DiscoverDevices();
                        foreach (BluetoothDeviceInfo d in devices)
                        {
                            if (d.DeviceName == imuBTName)
                            {
                                File.WriteAllText(imuMemory, d.DeviceAddress.ToString());
                                WriteDataToBox("Device Found\nAttempting Connection...\n");
                                if (Comms.connectthroughbluetooth(d))
                                {
                                    WriteDataToBox("Connection Successful\n");
                                    Comms.DataIn += new CommunicationsClass.EventHandler(Comms_OnDataIn);
                                    return(true);
                                }
                                else
                                {
                                    WriteDataToBox("Connection Failed\n");
                                    return(false);
                                }
                            }
                        }
                    }
                }
            }

            else
            {
                if (bluetooth == true)
                {
                    WriteDataToBox("Searching for Paired Bluetooth Device...\n");
                    BluetoothClient client = new BluetoothClient();
                    devices = client.DiscoverDevices();
                    foreach (BluetoothDeviceInfo d in devices)
                    {
                        if (d.DeviceName == imuBTName)
                        {
                            try
                            {
                                if (!File.Exists(imuMemory))
                                {
                                    FileStream imuMemoryFile = File.Create(imuMemory);
                                    Byte[]     imuAddress    = new UTF8Encoding(true).GetBytes(d.DeviceAddress.ToString());
                                    imuMemoryFile.Write(imuAddress, 0, imuAddress.Length);
                                    imuMemoryFile.Close();
                                }
                                else
                                {
                                    File.AppendAllText(imuMemory, d.DeviceAddress.ToString());
                                }
                                WriteDataToBox("Device Found\nAttempting Connection...\n");
                                if (Comms.connectthroughbluetooth(d))
                                {
                                    WriteDataToBox("Connection Successful\n");
                                    Comms.DataIn += new CommunicationsClass.EventHandler(Comms_OnDataIn);
                                    return(true);
                                }
                                else
                                {
                                    WriteDataToBox("Connection Failed\n");
                                    return(false);
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }
            return(false);
        }
예제 #16
0
        async void MainService()
        {
            try
            {
                bool hasConnected = false;

                //Main registry variable
                RegistryKey reg = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\AirPods Service", true);

                //Creates a bluetooth client
                BluetoothClient client = new BluetoothClient();

                //Bluetooth address
                BluetoothAddress address = null;

                //Checks to see if the bluetooth address in the registry is valid
                if (BluetoothAddress.TryParse(Convert.ToString(reg.GetValue("btAddress")), out BluetoothAddress result))
                {
                    //Sets the address
                    address = result;
                }
                else
                {
                    //Exits since its invalid
                    this.Close();
                }

                //Main loop
                while (true)
                {
                    //Get array of nearby bluetooth devices
                    BluetoothDeviceInfo[] deviceInfo = client.DiscoverDevices();

                    //Go through each item in deviceInfo array
                    foreach (var device in deviceInfo)
                    {
                        //Checks to see if its your AirPods and if they are connected
                        if (device.DeviceAddress == address && device.Connected)
                        {
                            //Checks if they have been connected before, this is to avoid the window popping up multiple times
                            if (!hasConnected)
                            {
                                //Writes the AirPods name to the registry
                                reg.SetValue("name", device.DeviceName);

                                hasConnected = true;

                                //Assuming the pop up executable is in the same folder, start it
                                System.Diagnostics.Process.Start(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "AirPods Window.exe"));

                                //Break the foreach loop
                                break;
                            }
                        }
                        else if (device.DeviceAddress == address)
                        {
                            hasConnected = false;
                        }
                    }

                    //Needed so it doesn't crash
                    await Task.Delay(500);
                }
            }
            catch (Exception e)
            {

                if (!Directory.Exists(@"C:\Users\" + Environment.UserName + @"\Documents\AirPods Logs"))
                {
                    Directory.CreateDirectory(@"C:\Users\" + Environment.UserName + @"\Documents\AirPods Logs");
                }
                string fileName = DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss");
                using (StreamWriter sw = new StreamWriter(@"C:\Users\" + Environment.UserName + @"\Documents\AirPods Logs\log " + fileName + ".txt"))
                {
                    sw.WriteLine(Convert.ToString(e));
                }
                this.Close();
            }
        }
예제 #17
0
        public FormMain()
        {
            InitializeComponent();
            Icon = Properties.Resources.AppIcon;

            try
            {
                string language = Properties.Settings.Default.Language;
                if (!string.IsNullOrEmpty(language))
                {
                    SetCulture(language);
                }
            }
            catch (Exception)
            {
                // ignored
            }

            comboBoxLanguage.Items.Clear();
            comboBoxLanguage.BeginUpdate();
            comboBoxLanguage.Items.Add(new LanguageInfo(Resources.Strings.LanguageEn, "en"));
            comboBoxLanguage.Items.Add(new LanguageInfo(Resources.Strings.LanguageDe, "de"));
            comboBoxLanguage.Items.Add(new LanguageInfo(Resources.Strings.LanguageRu, "ru"));
            comboBoxLanguage.EndUpdate();

            string culture  = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
            int    index    = 0;
            int    selIndex = -1;

            foreach (LanguageInfo languageInfo in comboBoxLanguage.Items)
            {
                if (string.Compare(languageInfo.Culture, culture, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    selIndex = index;
                }
                index++;
            }
            comboBoxLanguage.SelectedIndex = selIndex;

            listViewDevices.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.None);
            listViewDevices.Columns[1].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
            textBoxBluetoothPin.Text = @"1234";
            textBoxWifiPassword.Text = @"deepobdbmw";

            StringBuilder sr = new StringBuilder();

            try
            {
                _cli = new BluetoothClient();
            }
            catch (Exception ex)
            {
                sr.Append(string.Format(Resources.Strings.BtInitError, ex.Message));
            }
            _deviceList = new List <BluetoothDeviceInfo>();
            _wifi       = new Wifi();
            _wlanClient = new WlanClient();
            _test       = new Test(this);
            if (_wifi.NoWifiAvailable || _wlanClient.NoWifiAvailable)
            {
                if (sr.Length > 0)
                {
                    sr.Append("\r\n");
                }
                sr.Append(Resources.Strings.WifiAdapterError);
            }
            GetDirectories();

            _initMessage = sr.ToString();
            UpdateStatusText(string.Empty);
            UpdateButtonStatus();
        }
        private void Button1Click(object sender, RoutedEventArgs e)
        {
            var addr = BluetoothAddress.Parse("d0:37:61:c4:cb:25");


            var serviceClass = BluetoothService.SerialPort;
            var ep           = new BluetoothEndPoint(addr, serviceClass);

            _bluetoothClient = new BluetoothClient();

            _bluetoothClient.Connect(ep);
            //            Stream peerStream = cli.GetStream();

            BtProtocol.OutStream = _bluetoothClient.GetStream();
            MetaWatchService.inputOutputStream = BtProtocol.OutStream;
            BtProtocol.SendRtcNow();
            BtProtocol.GetDeviceType();
            BtProtocol.OutStream.Flush();


            _readThread = new Thread(() =>
            {
                while (true)
                {
                    BtProtocol.OutStream.ReadTimeout = 2000000;
                    var startByte = BtProtocol.OutStream.ReadByte();
                    if (startByte != 1)
                    {
                        continue;
                    }
                    var msgLen = BtProtocol.OutStream.ReadByte();
                    if (msgLen < 6)
                    {
                        MessageBox.Show("Ошибка приёма");
                        continue;
                    }
                    var msgType    = BtProtocol.OutStream.ReadByte();
                    var msgOptions = BtProtocol.OutStream.ReadByte();
                    var msgDataLen = msgLen - 6;

                    var data = new byte[msgDataLen];
                    BtProtocol.OutStream.Read(data, 0, msgDataLen);

                    //CRC
                    BtProtocol.OutStream.ReadByte();
                    BtProtocol.OutStream.ReadByte();

                    switch (msgType)
                    {
                    case (int)BtMessage.Message.GetDeviceTypeResponse:
                        switch (data[0])
                        {
                        case 2:
                            Dispatcher.Invoke(new Action(delegate
                            {
                                sbiConnect.Content = "Подключено!";
                            }), System.Windows.Threading.DispatcherPriority.Normal);

                            //MessageBox.Show("Цифровые!");
                            break;
                        }
                        break;

                    case (int)BtMessage.Message.ButtonEventMsg:
                        if ((data[0] & 0x1) == 0x1)
                        {
                            MessageBox.Show("A!");
                        }
                        if ((data[0] & 0x2) == 0x2)
                        {
                            MessageBox.Show("B!");
                        }
                        if ((data[0] & 0x4) == 0x4)
                        {
                            MessageBox.Show("C!");
                        }
                        if ((data[0] & 0x8) == 0x8)
                        {
                            MessageBox.Show("D!");
                        }

                        if ((data[0] & 0x20) == 0x20)
                        {
                            MessageBox.Show("E!");
                        }
                        if ((data[0] & 0x40) == 0x40)
                        {
                            MessageBox.Show("F!");
                        }
                        if ((data[0] & 0x80) == 0x80)
                        {
                            MessageBox.Show("S!");
                        }
                        break;

                    case (int)BtMessage.Message.ReadBatteryVoltageResponse:
                        var powerGood       = data[0];
                        var batteryCharging = data[1];
                        var voltage         = (data[3] << 8) | data[2];
                        var voltageAverage  = (data[5] << 8) | data[4];
                        MessageBox.Show(string.Format("volt:{0} avg:{1} powerGood:{2} batteryCharging: {3}",
                                                      voltage / 1000f, voltageAverage / 1000f, powerGood, batteryCharging));
                        break;
                    }
                }
            });
            _readThread.Start();
            //            var buf = new byte[2];
            //            var readLen = peerStream.Read(buf, 0, buf.Length);
            //            if (readLen == 2)
            //            {
            //                MessageBox.Show(buf[1].ToString());
            //            }


            //    peerStream.Write/Read ...
            //
            //e.g.

            /*var buf = new byte[1000];
             * var readLen = peerStream.Read(buf, 0, buf.Length);
             * if (readLen == 0)
             * {
             *  Console.WriteLine("Connection is closed");
             * }
             * else
             *
             * {
             *
             *  Console.WriteLine("Recevied {0} bytes", readLen);
             *
             * }*/
        }
예제 #19
0
        private ObexStatusCode Connect()
        {
            if (!connected)
            {
                if (ns == null)
                {
                    try {
#if NETCF
                        // Will be set to false in some Bluetooth cases (e.g. Widcomm and Bluetopia)...
                        bool isWinCeSockets = true;
#endif
                        if (uri.Host.Length == 0)
                        {
                            System.Diagnostics.Debug.Assert(m_alreadyConnectedObexStream != null);
                            System.Diagnostics.Debug.Assert(m_alreadyConnectedObexStream.CanRead &&
                                                            m_alreadyConnectedObexStream.CanWrite);
                            ns = m_alreadyConnectedObexStream;
                        }
                        else
                        {
                            BluetoothAddress ba;
                            IrDAAddress      ia;
                            if (BluetoothAddress.TryParse(uri.Host, out ba))
                            {
                                // No good on Widcomm! s = new Socket(AddressFamily32.Bluetooth, SocketType.Stream, BluetoothProtocolType.RFComm);
                                BluetoothClient cli;
                                if (_btFactory == null)
                                {
                                    cli = new BluetoothClient();
                                }
                                else
                                {
                                    cli = _btFactory.CreateBluetoothClient();
                                }
                                Guid serviceGuid;

                                switch (uri.Scheme)
                                {
                                case SchemeNames.Ftp:
                                    serviceGuid = BluetoothService.ObexFileTransfer;
                                    break;

                                //potential for other obex based profiles to be added
                                case SchemeNames.Sync:
                                    serviceGuid = BluetoothService.IrMCSyncCommand;
                                    break;

                                case SchemeNames.Pbap:
                                    serviceGuid = BluetoothService.PhonebookAccessPse;
                                    break;

                                default:
                                    serviceGuid = BluetoothService.ObexObjectPush;
                                    break;
                                }


                                BluetoothEndPoint bep = new BluetoothEndPoint(ba, serviceGuid);
                                cli.Connect(bep);
                                ns = cli.GetStream();
#if NETCF
                                try {
                                    Socket tmp = cli.Client; // Attempt to get the Socket
                                    Debug.Assert(isWinCeSockets);
                                } catch (NotSupportedException) {
                                    isWinCeSockets = false;
                                }
#endif
                            }
                            else if (IrDAAddress.TryParse(uri.Host, out ia))
                            {
                                //irda
                                s = new Socket(AddressFamily.Irda, SocketType.Stream, ProtocolType.IP);

                                IrDAEndPoint iep = new IrDAEndPoint(ia, "OBEX");

                                s.Connect(iep);
                            }
                            else
                            {
                                //assume a tcp host
                                s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                                IPAddress ipa;
                                try {
                                    ipa = IPAddress.Parse(uri.Host);
                                } catch {
                                    // Compile-time: warning CS0618: 'System.Net.Dns.Resolve(string)'
                                    //    is obsolete: 'Resolve is obsoleted for this type,
                                    //    please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202'
                                    // However GetHostEntry isn't supported on NETCFv1,
                                    // so just keep it and disable the warning on
                                    // the other platforms.
#if V1
/*
 #endif
 #pragma warning disable 618
 #if V1
 */
#endif
                                    ipa = System.Net.Dns.Resolve(uri.Host).AddressList[0];
#if V1
/*
 #endif
 #pragma warning restore 618
 #if V1
 */
#endif
                                }

                                IPEndPoint ipep = new IPEndPoint(ipa, 650);

                                s.Connect(ipep);
                            }

                            if (ns == null) // BluetoothClient used above
                            {
                                ns = new NetworkStream(s, true);
                            }

#if NETCF
                            if (isWinCeSockets)
                            {
                                // Winsock on WinCE does _not_ support timeouts!
                                ns = new InTheHand.Net.Bluetooth.Factory.TimeoutDecorStream(ns);
                            }
#endif
                            // Timeout
                            ns.ReadTimeout  = timeout;
                            ns.WriteTimeout = timeout;
                        }

                        return(Connect_Obex());
                    } finally {
                        if (s != null && !s.Connected)
                        {
                            s = null;
                        }
                    }
                }
            }
            Debug.Fail("Don't know that we every get here (Connect when connected).");
            return((ObexStatusCode)0);
        }
예제 #20
0
        private void connect()
        {
            try
            {
                this.Dispatcher.Invoke(() =>
                {
                    ConnectionText.Text = "Attempting new Connection\n";
                });
                using (var btClient = new BluetoothClient())
                {
                    var btIgnored = 0;

                    // Find remembered bluetooth devices.
                    this.Dispatcher.Invoke(() =>
                    {
                        ConnectionText.Text += "Removing existing bluetooth devices...\n";
                    });

                    if (true)//checkBox_RemoveExisting.Checked
                    {
                        var btExistingList = btClient.DiscoverDevices(255, false, true, false);

                        foreach (var btItem in btExistingList)
                        {
                            if (!btItem.DeviceName.Contains("Nintendo"))
                            {
                                continue;
                            }

                            BluetoothSecurity.RemoveDevice(btItem.DeviceAddress);
                            btItem.SetServiceState(BluetoothService.HumanInterfaceDevice, false);
                        }
                    }

                    // Find unknown bluetooth devices.
                    this.Dispatcher.Invoke(() =>
                    {
                        ConnectionText.Text += "Searching for bluetooth devices...\nPress the red sync button now to sync!\n";
                    });

                    var btDiscoveredList = btClient.DiscoverDevices(255, false, false, true);

                    foreach (var btItem in btDiscoveredList)
                    {
                        // Just in-case any non Wii devices are waiting to be paired.

                        if (true && !btItem.DeviceName.Contains("Nintendo")) //!checkBox_SkipNameCheck.Checked
                        {
                            btIgnored += 1;
                            continue;
                        }


                        this.Dispatcher.Invoke(() =>
                        {
                            ConnectionText.Text += "Adding: " + btItem.DeviceName + " ( " + btItem.DeviceAddress + " )\n";
                        });


                        // Install as a HID device and allow some time for it to finish.

                        btItem.SetServiceState(BluetoothService.HumanInterfaceDevice, true);
                    }

                    // Allow slow computers to finish installation before connecting.

                    System.Threading.Thread.Sleep(4000);

                    // Connect and send a command, otherwise they sleep and the device disappears.

                    try
                    {
                        if (btDiscoveredList.Length > btIgnored)
                        {
                            var deviceCollection = new WiimoteCollection();
                            deviceCollection.FindAllWiimotes();

                            foreach (var wiiDevice in deviceCollection)
                            {
                                wiiDevice.Connect();
                                wiiDevice.SetLEDs(true, false, false, false);
                                wiiDevice.Disconnect();
                            }
                            this.Dispatcher.Invoke(() =>
                            {
                                ConnectionText.Text += "Finished - You can now close this window.\n";
                            });
                        }
                        else
                        {
                            this.Dispatcher.Invoke(() =>
                            {
                                ConnectionText.Text += "Finished - No board(s) found. Please try again.\n";
                            });
                        }
                    }
                    catch (Exception) { }
                }
            }
            catch (Exception ex)
            {
                this.Dispatcher.Invoke(() =>
                {
                    ConnectionText.Text += "Error: " + ex.Message + "\n";
                });
            }
        }
예제 #21
0
        private void button_DeviceSearch_Click(object sender, EventArgs e)
        {
            ((Button)sender).Enabled = false;

            try
            {
                using (var btClient = new BluetoothClient())
                {
                    // PROBLEM:
                    // false false true: finds only unknown devices, which excludes existing but broken device entries.
                    // false true  true: finds broken entries, but even if powered off, so pairing attempts then crash.
                    // WORK-AROUND:
                    // Remove existing entries first, then find powered on entries.

                    var btIgnored = 0;

                    // Find remembered bluetooth devices.

                    label_Status.Text = "Removing existing bluetooth devices...";
                    label_Status.Refresh();

                    if (checkBox_RemoveExisting.Checked)
                    {
                        var btExistingList = btClient.DiscoverDevices(255, false, true, false);

                        foreach (var btItem in btExistingList)
                        {
                            if (!btItem.DeviceName.Contains("Nintendo"))
                            {
                                continue;
                            }

                            BluetoothSecurity.RemoveDevice(btItem.DeviceAddress);
                            btItem.SetServiceState(BluetoothService.HumanInterfaceDevice, false);
                        }
                    }

                    // Find unknown bluetooth devices.

                    label_Status.Text = "Searching for bluetooth devices...";
                    label_Status.Refresh();

                    var btDiscoveredList = btClient.DiscoverDevices(255, false, false, true);

                    foreach (var btItem in btDiscoveredList)
                    {
                        // Just in-case any non Wii devices are waiting to be paired.

                        if (!checkBox_SkipNameCheck.Checked && !btItem.DeviceName.Contains("Nintendo"))
                        {
                            btIgnored += 1;
                            continue;
                        }

                        label_Status.Text = "Adding: " + btItem.DeviceName + " ( " + btItem.DeviceAddress + " )";
                        label_Status.Refresh();

                        // Send special pin for permanent sync.

                        if (checkBox_PermanentSync.Checked)
                        {
                            // Sync button requires host address, holding 1+2 buttons requires device address.

                            var btPin = AddressToWiiPin(BluetoothRadio.PrimaryRadio.LocalAddress.ToString());

                            // Pin needs to be added before doing the pair request.

                            new BluetoothWin32Authentication(btItem.DeviceAddress, btPin);

                            // Null forces legacy pin request instead of SSP authentication.

                            BluetoothSecurity.PairRequest(btItem.DeviceAddress, null);
                        }

                        // Install as a HID device and allow some time for it to finish.

                        btItem.SetServiceState(BluetoothService.HumanInterfaceDevice, true);
                    }

                    // Allow slow computers to finish installation before connecting.

                    System.Threading.Thread.Sleep(4000);

                    // Connect and send a command, otherwise they sleep and the device disappears.

                    try
                    {
                        if (btDiscoveredList.Length > btIgnored)
                        {
                            var deviceCollection = new WiimoteCollection();
                            deviceCollection.FindAllWiimotes();

                            foreach (var wiiDevice in deviceCollection)
                            {
                                wiiDevice.Connect();
                                wiiDevice.SetLEDs(true, false, false, false);
                                wiiDevice.Disconnect();
                            }
                        }
                    }
                    catch (Exception) { }

                    // Status report.

                    label_Status.Text = "Finished - You can now close this window. Found: " + btDiscoveredList.Length + " Ignored: " + btIgnored;
                    label_Status.Refresh();
                }
            }
            catch (Exception ex)
            {
                label_Status.Text = "Error: " + ex.Message;
            }

            ((Button)sender).Enabled = true;
        }
예제 #22
0
 public void FindDevices()
 {
     localEndPoint    = new BluetoothEndPoint(choosenRadio.LocalAddress, BluetoothService.SerialPort);
     _client          = new BluetoothClient(localEndPoint);
     _bluetoothDevice = _client.DiscoverDevices();
 }
        private void search()
        {
            try
            {
                Guid uuid = BluetoothService.L2CapProtocol;
                BluetoothDeviceInfo bdi;
                BluetoothAddress    ba;
                byte tmp;
                bool found = false;
                int  discarded;

                bc = new BluetoothClient();

                bc.InquiryLength = new TimeSpan(0, 0, 0, int.Parse(OSAEObjectPropertyManager.GetObjectPropertyValue(gAppName, "Discover Length").Value), 0);
                nearosaeDevices  = bc.DiscoverDevices(10, false, false, true);

                for (int j = 0; j < nearosaeDevices.Length; j++)
                {
                    string addr = nearosaeDevices[j].DeviceAddress.ToString();

                    Object obj = OSAEObjectManager.GetObjectByAddress(addr);

                    if (obj == null)
                    {
                        if (OSAEObjectPropertyManager.GetObjectPropertyValue(gAppName, "Learning Mode").Value == "TRUE")
                        {
                            OSAEObjectManager.ObjectAdd(nearosaeDevices[j].DeviceName, nearosaeDevices[j].DeviceName, "BLUETOOTH DEVICE", nearosaeDevices[j].DeviceAddress.ToString(), string.Empty, true);
                            OSAEObjectPropertyManager.ObjectPropertySet(nearosaeDevices[j].DeviceName, "Discover Type", "0", gAppName);
                            if (gDebug)
                            {
                                Log.Debug(addr + " - " + nearosaeDevices[j].DeviceName + ": added to OSA");
                            }
                        }
                    }
                }

                OSAEObjectCollection objects = OSAEObjectManager.GetObjectsByType("BLUETOOTH DEVICE");

                foreach (OSAEObject obj in objects)
                {
                    found = false;
                    string address   = obj.Address;
                    byte[] byteArray = HexEncoding.GetBytes(address, out discarded);
                    tmp          = byteArray[0];
                    byteArray[0] = byteArray[5];
                    byteArray[5] = tmp;
                    tmp          = byteArray[1];
                    byteArray[1] = byteArray[4];
                    byteArray[4] = tmp;
                    tmp          = byteArray[2];
                    byteArray[2] = byteArray[3];
                    byteArray[3] = tmp;
                    ba           = new BluetoothAddress(byteArray);
                    bdi          = new BluetoothDeviceInfo(ba);
                    if (gDebug)
                    {
                        Log.Debug("Begin search for " + address);
                    }

                    for (int j = 0; j < nearosaeDevices.Length; j++)
                    {
                        if (nearosaeDevices[j].DeviceAddress.ToString() == address)
                        {
                            found = true;
                            if (gDebug)
                            {
                                Log.Debug(address + " - " + obj.Name + ": found with DiscoverDevices");
                            }
                        }
                    }
                    if (!found)
                    {
                        if (gDebug)
                        {
                            Log.Debug(address + " - " + obj.Name + ": failed with DiscoverDevices");
                        }
                    }

                    try
                    {
                        if (!found && (int.Parse(OSAEObjectPropertyManager.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 2 || Int32.Parse(OSAEObjectPropertyManager.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 0))
                        {
                            if (gDebug)
                            {
                                Log.Debug(address + " - " + obj.Name + ": attempting GetServiceRecords");
                            }

                            bdi.GetServiceRecords(uuid);
                            found = true;
                            if (gDebug)
                            {
                                Log.Debug(address + " - " + obj.Name + " found with GetServiceRecords");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (gDebug)
                        {
                            Log.Debug(address + " - " + obj.Name + " failed GetServiceRecords. exception: " + ex.Message);
                        }
                    }

                    try
                    {
                        if (!found && (int.Parse(OSAEObjectPropertyManager.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 3 || int.Parse(OSAEObjectPropertyManager.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 0))
                        {
                            if (gDebug)
                            {
                                Log.Debug(address + " - " + obj.Name + ": attempting Connection");
                            }
                            //attempt a connect
                            BluetoothEndPoint ep;
                            ep = new BluetoothEndPoint(bdi.DeviceAddress, BluetoothService.Handsfree);
                            //MessageBox.Show("attempt connect: " + pairedDevices[i].DeviceAddress);
                            bc.Connect(ep);
                            if (gDebug)
                            {
                                Log.Debug(address + " - " + obj.Name + " found with Connect attempt");
                            }
                            bc.Close();
                            found = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(address + " - " + obj.Name + " failed with Connect attempt. exception: " + ex.Message);
                    }

                    if (found)
                    {
                        OSAEObjectStateManager.ObjectStateSet(obj.Name, "ON", gAppName);
                        if (gDebug)
                        {
                            Log.Debug(obj.Name + " Status Updated in osae");
                        }
                    }
                    else
                    {
                        OSAEObjectStateManager.ObjectStateSet(obj.Name, "OFF", gAppName);
                        if (gDebug)
                        {
                            Log.Debug(obj.Name + " Status Updated in osae");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error searching for devices", ex);
            }
        }
예제 #24
0
        static void Main(string[] args)
        {
            var blt = new BluetoothClient();

            blt.init().Wait();
        }
예제 #25
0
 public void connectionCallbackFunction(IAsyncResult i_ConnectionResult)
 {
     BluetoothClient client = i_ConnectionResult.AsyncState as BluetoothClient;
 }
예제 #26
0
 /// <summary>
 /// Creates a new instance of the BluetoothConnection with the given client.
 /// </summary>
 /// <param name="bluetoothClient">The client to create a connection with.</param>
 /// <returns>The result.</returns>
 internal static BluetoothConnection CreateBluetoothConnection(BluetoothClient bluetoothClient)
 {
     return(new BluetoothConnection(bluetoothClient));
 }
 private static IAsyncResult BeginDiscoverDefault(this BluetoothClient client, AsyncCallback callback, object state)
 {
     return(client.BeginDiscoverDevices(32, true, true, true, true, callback, state));
 }
예제 #28
0
        async Task ReadButtonData()
        {
            while (_reconnect)
            {
                try
                {
                    //connect
                    do
                    {
                        try
                        {
                            _client.Connect(_device.DeviceAddress, _device.InstalledServices[3]);

                            //send events
                            Connected?.Invoke(this, new ButtonEventArgs()
                            {
                                ButtonName = Name
                            });
                        }
                        catch (Exception)
                        {
                            await Task.Delay(1000);
                        }
                    } while (_reconnect && !_client.Connected);

                    //read stream
                    if (_reconnect && _client.Connected)
                    {
                        _stream = _client.GetStream();
                        while (_reconnect)
                        {
                            var len = await _stream.ReadAsync(_buffer, 0, _buffer.Length);

                            //connection closed
                            if (len == 0)
                            {
                                //send events
                                Disconnected?.Invoke(this, new ButtonEventArgs()
                                {
                                    ButtonName = Name
                                });

                                //start listening again
                                if (_reconnect)
                                {
                                    _client.Close();
                                    _client.Dispose();
                                    _client = new BluetoothClient();                                     //create a new client - for some reason its not reusable at this point
                                    break;
                                }
                            }

                            //received data
                            else
                            {
                                var messages = _parser.GetMessage(_buffer, len);
                                if (messages != null)
                                {
                                    foreach (var message in messages)
                                    {
                                        if (message.Payload[1] == 1 && message.Payload[25] == 2)
                                        {
                                            //set events
                                            Pressed?.Invoke(this, new ButtonEventArgs()
                                            {
                                                ButtonName = Name
                                            });
                                        }

                                        if (message.Payload[1] == 1 && message.Payload[25] == 3)
                                        {
                                            //set events
                                            Released?.Invoke(this, new ButtonEventArgs()
                                            {
                                                ButtonName = Name
                                            });
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
        }
 public static Task <BluetoothDeviceInfo[]> DiscoverDevicesInRangeAsync(this BluetoothClient client)
 {
     return(Task.Factory.FromAsync(client.BeginDiscoverDefault, client.EndDiscoverDevices, null));
 }
예제 #30
0
        /// <summary>
        /// Attempts to connection over Bluetooth to the IMU device and establish a data stream from it. Provides several attempts
        /// at a connection and gets the IMU firmware number if required.
        /// </summary>
        /// <returns> T - Connection success, F - Connection failure.</returns>
        public bool connect()
        {
            while (!connection_established && attempt_number < max_attempts + 1)
            {
                try
                {
                    client = new BluetoothClient();
                    db_report("Connection Attempt: " + attempt_number + "/" + max_attempts + ".");
                    client.Connect(end_point);
                    connection_established = true;
                    db_report("Connected.");
                }
                catch
                {
                    db_report("Connection Failed. " + (max_attempts - attempt_number) + " remaining.");
                    attempt_number++;
                }
            }
            if (!connection_established)
            {
                db_report("Out of Connection Attempts.");
                return(false);
            }
            else
            {
                stream             = client.GetStream();
                stream_established = true;
                db_report("Stream Established");
                byte[] buf     = new byte[50];
                int    readLen = stream.Read(buf, 0, 15);
                var    welcome = Encoding.ASCII.GetString(buf);
                db_report(welcome);

                if (welcome.Contains("Connection Open"))
                {
                    connection_live = true;
                    if (!connection_info)
                    {
                        send_data("RegR");
                        stream.ReadTimeout = 5000;
                        try
                        {
                            while (!stream.DataAvailable)
                            {
                                // Waiting for IMU to begin streaming
                            }
                            int   i         = 0;
                            int[] info_data = new int[42];
                            while (i < 42)
                            {
                                int val = stream.ReadByte();
                                info_data[i] = val;
                                i++;
                            }
                            IMU_connection.set_connection_info(info_data[39], info_data[40], establish_device_details(IMU_connection.IMU_device_name));
                        }
                        catch (System.IO.IOException)
                        {
                            return(false);
                        }
                    }

                    return(true);
                }
            }
            return(false);
        }