예제 #1
0
        private async void FINGER_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (Validations.CheckTextBox(tbxName, tbxAcadimicId).Equals(true))
            {
                var dialog = new MessageDialog("Check Valuing fields");
                await dialog.ShowAsync();
            }
            else
            {
                try
                {
                    await DatabaseManagement.CountAllStudentsData(newfpid);

                    try
                    {
                        await BluetoothConnection.SendCommand(newfpid.Text);

                        FingerStatusText.Text = gloablvalue.checksend(gloablvalue.RecivedText);
                        FINGER.IsTapEnabled   = false;
                        HideFINGER.Begin();
                        BtN_Menu.IsTapEnabled = false;
                    }
                    catch (Exception)
                    {
                        FingerStatusText.Text = "error in sending fingerprint id !";
                    }
                }
                catch (Exception)
                {
                    FingerStatusText.Text = "error in count student data!";
                }
            }
        }
예제 #2
0
        /// <summary>
        /// Starts a Bluetooth server and listens for incoming <see cref="BluetoothConnection"/>s.
        /// </summary>
        public async Task StartBluetoothListener()
        {
            if (IsBluetoothOnline || !AllowBluetoothConnections || !BluetoothConnection.IsBluetoothSupported)
            {
                return;
            }

            bluetoothListener = new BluetoothListener(ConnectionFactory.GUID);
            bluetoothListener.Start();
            IsBluetoothOnline = !IsBluetoothOnline;

            while (IsBluetoothOnline)
            {
                BluetoothClient bluetoothClient = await Task.Factory.FromAsync(bluetoothListener.BeginAcceptBluetoothClient, bluetoothListener.EndAcceptBluetoothClient, TaskCreationOptions.PreferFairness);

                BluetoothConnection bluetoothConnection = ConnectionFactory.CreateBluetoothConnection(bluetoothClient);
                bluetoothConnection.NetworkConnectionClosed += connectionClosed;

                //Inform all subscribers.
                if (connectionEstablished != null &&
                    connectionEstablished.GetInvocationList().Length > 0)
                {
                    connectionEstablished(bluetoothConnection, ConnectionType.Bluetooth);
                }
            }
        }
예제 #3
0
        private async void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            //try
            //{
            DatabaseManagement.InsertAllStudentsData(tbxAcadimicId.Text, tbxName.Text, newfpid.Text);
            var dlg = new MessageDialog(tbxName.Text + " added.");
            await dlg.ShowAsync();

            tbxAcadimicId.Text  = "";
            tbxName.Text        = "";
            FINGER.IsTapEnabled = true;
            btnAdd.IsEnabled    = false;
            //try
            //{
            await BluetoothConnection.SendCommand("+");

            FingerStatusText.Text = gloablvalue.checksend(gloablvalue.RecivedText);
            BtN_Menu.IsTapEnabled = true;
            //}
            //catch (Exception)
            //{
            //    var dlg2 = new MessageDialog("error to run device again!");
            //    await dlg.ShowAsync();
            //    BtN_Menu.IsTapEnabled = true;
            //}
            //}
            //catch (Exception)
            //{
            //    var dlg = new MessageDialog("error to add in database!");
            //    await dlg.ShowAsync();
            //}
        }
예제 #4
0
        private async void ShowFINGER_Completed(object sender, object e)
        {
            FingerStatusText.Text = gloablvalue.checksend(gloablvalue.RecivedText);
            if (gloablvalue.checksend(gloablvalue.RecivedText) == "Stored!")
            {
                FingerStatusText.Text   = "Id = " + newfpid.Text + " Stored!";
                btnAdd.IsEnabled        = true;
                gloablvalue.RecivedText = "";
                HideFINGER.Stop();
                ShowFINGER.Stop();
            }
            else if (gloablvalue.checksend(gloablvalue.RecivedText) == "Fingerprints did not match")
            {
                FingerStatusText.Text = "Fingerprints did not match"
                                        + "\r\n" + "Click on Take fingerprint to try again";
                HideFINGER.Stop();
                ShowFINGER.Stop();
                await BluetoothConnection.SendCommand("+");

                FINGER.IsTapEnabled   = true;
                BtN_Menu.IsTapEnabled = true;
            }
            else
            {
                FingerStatusText.Text = gloablvalue.checksend(gloablvalue.RecivedText);
                //FingerStatusText.Text = "Error at receiving, please click again";
                //HideFINGER.Stop();
                //ShowFINGER.Stop();
                //await BluetoothConnection.SendCommand("+");
                //FINGER.IsTapEnabled = true;
                //BtN_Menu.IsTapEnabled = true;
                HideFINGER.Begin();
            }
        }
        public ShellViewModel(
            IEventAggregator eventAggregator,
            SocketClient socketClient,
            RobotCommand moveCommand,
            ControllerClass controllerClass
            )
        {
            _socketClient    = socketClient;
            _dashboardClient = new SocketClient(eventAggregator);

            _roboServer = new SocketServer(eventAggregator);

            _robotCommand    = moveCommand;
            _controllerClass = controllerClass;

            _eventAggregator = eventAggregator;
            _eventAggregator.Subscribe(this);

            _controllerClass.StartController();

            _serial       = new SerialCommunication(eventAggregator);
            _BTConnection = new BluetoothConnection(eventAggregator);

            ComPortList       = SerialPort.GetPortNames();
            BaudRateList      = DataLists.GetBaudRates();
            MotorStepTypeList = DataLists.GetStepTypes();
        }
        public BluetoothConnection ConnectToBluetoothDevice()
        {
            bluetoothConnection = new BluetoothConnection();
            //bluetoothConnection.deviceName = "SESTO-L1808016";
            if (SelectedBluetoothDevice == null)
            {
                Debug.WriteLine("******** NO device selected ***********");
                MessagingCenter.Send(this, Constants.MESSAGE_DEVICE_SELECTED);
                return(null);
            }
            bluetoothConnection.deviceName = SelectedBluetoothDevice;

            try
            {
                Debug.WriteLine("CONNECTION 1");
                BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
                Debug.WriteLine("CONNECTION 2");
                BluetoothDevice bluetoothDevice = (from device in bluetoothAdapter.BondedDevices
                                                   where device.Name == bluetoothConnection.deviceName
                                                   select device).FirstOrDefault();
                Debug.WriteLine("CONNECTION 3");
                BluetoothSocket bluetoothSocket = bluetoothDevice.CreateInsecureRfcommSocketToServiceRecord(Java.Util.UUID.FromString(Constants.UUID));
                Debug.WriteLine("CONNECTION 4");
                bluetoothSocket.Connect();
                Debug.WriteLine("CONNECTION 5");
                bluetoothConnection.bluetoothSocket = bluetoothSocket;

                return(bluetoothConnection);
            }
            catch (Exception) {
                throw;
            }
        }
예제 #7
0
        private async void EndButton_Click(object sender, RoutedEventArgs e)
        {
            //try
            //{
            string duration = ht.Text + ":" + mt.Text + ":" + st.Text;

            DatabaseManagement.InsertLectureData(txtbxLecName.Text, gloablvalue.CurrentId, datetime, duration, txtbxRoom.Text);
            mytimer.Stop();
            HideFINGER.Stop();
            ShowFINGER.Stop();
            gloablvalue.NewLecId = "";
            //try
            //{
            await BluetoothConnection.SendCommand(",");

            Frame.Navigate(typeof(AllLec));
            //}
            //catch (Exception)
            //{
            //    var dialo2g = new MessageDialog("device not ending the fingerprint..!");
            //    await dialo2g.ShowAsync();
            //}
            //}
            //catch (Exception)
            //{
            //    var dialog = new MessageDialog("Error in insert lecture data !");
            //    await dialog.ShowAsync();
            //}
        }
예제 #8
0
        public byte[] SendCommand(byte[] Command)
        {
            Byte[] MessageLength = { 0x00, 0x00 };
            string log           = "";

            // Send Message
            MessageLength[0] = (byte)Command.Length;
            log += "TX: ";
            for (int i = 0; i < Command.Length; i++)
            {
                log += Command[i].ToString("X2") + " ";
            }
            log += Environment.NewLine;

            BluetoothConnection.Write(MessageLength, 0, MessageLength.Length);
            BluetoothConnection.Write(Command, 0, Command.Length);

            // Get Response
            List <byte> response = new List <byte>();
            int         length   = BluetoothConnection.ReadByte() + 256 * BluetoothConnection.ReadByte();

            log += "RX: ";
            for (int i = 0; i < length; i++)
            {
                response.Add((byte)BluetoothConnection.ReadByte());
                log += response.Last().ToString("X2") + " ";
            }
            log += Environment.NewLine;

            logWrite(log);
            return(response.ToArray());
        }
예제 #9
0
        public string BuildBluetoothConnectionChannelsString(string macAddress)
        {
            BluetoothConnection connection = new BluetoothConnection(macAddress);

            connection.Open(); // Check connection

            try
            {
                ServiceDiscoveryHandlerImplementation serviceDiscoveryHandler = new ServiceDiscoveryHandlerImplementation();
                BluetoothDiscoverer.FindServices(global::Android.App.Application.Context, macAddress, serviceDiscoveryHandler);

                while (!serviceDiscoveryHandler.Finished)
                {
                    Task.Delay(100);
                }

                StringBuilder sb = new StringBuilder();
                foreach (ConnectionChannel connectionChannel in serviceDiscoveryHandler.ConnectionChannels)
                {
                    sb.AppendLine(connectionChannel.ToString());
                }
                return(sb.ToString());
            }
            finally
            {
                try
                {
                    connection?.Close();
                }
                catch (ConnectionException) { }
            }
        }
예제 #10
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
            if (gloablvalue.Currenttype != "Admin")
            {
                NewAccountBtn.Visibility  = Visibility.Collapsed;
                AllAccountsBtn.Visibility = Visibility.Collapsed;
                AddStudentBtn.Visibility  = Visibility.Collapsed;
                AllStudentsBtn.Visibility = Visibility.Collapsed;
            }
            else
            {
                NewLecBtn.Visibility = Visibility.Collapsed;
                AllLecBtn.Visibility = Visibility.Collapsed;
            }

            try
            {
                await BluetoothConnection.SendCommand("+");

                FingerStatusText.Text = gloablvalue.checksend(gloablvalue.RecivedText);
            }
            catch (Exception)
            {
                FingerStatusText.Text = "An error occured!";
            }
        }
예제 #11
0
        private void sendRobotMessage(RobotAction action, String message)
        {
            // Format the message
            string robotMessage = RobotMessage.FormatRobotMessage((int)action, message);

            // Send the Bluetooth data
            BluetoothConnection.Write(robotMessage);
        }
예제 #12
0
        private async void ShowFINGER_Completed(object sender, object e)
        {
            FingerStatusText.Text = gloablvalue.checksend(gloablvalue.RecivedText);
            gloablvalue.attendid  = gloablvalue.checksend(gloablvalue.RecivedText);

            if (gloablvalue.attendid == "F")
            {
                FingerStatusText.Text = "Put your finger!";
            }
            else
            {
                FingerStatusText.Text = gloablvalue.attendid;
                await DatabaseManagement.SearchStudentFingerPrint(studentid, Acadimicid, studentname, fingerprintid); //get fingerprint was get from fingerprint and search on student id if found return it

                if (studentid.Text == "NULL")
                {
                    FingerStatusText.Text = "An error occured!";
                }
                else if (studentid.Text == "Not Found")
                {
                    FingerStatusText.Text = "Id = " + gloablvalue.attendid + " not stored!";
                }
                else
                {
                    await DatabaseManagement.CheckAttend(state);

                    if (state.Text == "Not Found")
                    {
                        DatabaseManagement.InsertAllStudentsInLecData(gloablvalue.NewLecId, studentid.Text, Acadimicid.Text, studentname.Text, fingerprintid.Text);
                        FingerStatusText.Text = "Done id = " + gloablvalue.attendid;
                    }
                    else if (state.Text == "Found")
                    {
                        FingerStatusText.Text = "Id = " + gloablvalue.attendid + " Attend Before";
                    }
                    else
                    {
                        FingerStatusText.Text = "An error occured!";
                    }
                }
                //try
                //{
                await BluetoothConnection.SendCommand("-");

                //}
                //catch (Exception)
                //{
                //    var dialo2g = new MessageDialog("error in start device, click again.");
                //    await dialo2g.ShowAsync();
                //}
            }
            HideFINGER.Begin();
        }
예제 #13
0
        private async void CheckDevice(BluetoothConnection oBc)
        {
            if (oBluetooth.CheckConnection())
            {
                oBluetooth.CloseConnection();
            }

            lblState.Text = "Checking Device ...";

            bool isValid = await oBluetooth.OpenPairedDevice(oBc.device_name, oBc.device_address, false);

            lblState.Text = (isValid) ? "Device Connected" : "Invalid Device";
        }
예제 #14
0
        private void SetPickerSelection(int index)
        {
            if (index == -1 || pkrDevices.Items.Count == 0)
            {
                return;
            }

            BluetoothConnection oBc = (BluetoothConnection)pkrDevices.SelectedItem;

            if (oBc != null && oBluetooth != null)
            {
                CheckDevice(oBc);
            }
        }
예제 #15
0
    void Start()
    {
        CameraParents = new Transform[Cameras.Length];
        for (int i = 0; i < CameraParents.Length; i++)
        {
            CameraParents[i] = Cameras[i].transform.parent.parent.parent.transform;
        }

        blueC = gameObject.GetComponent <BluetoothConnection>();

        changeCamera(true);

        currentCamera = 0;
    }
예제 #16
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            MessagingCenter.Subscribe <MainPage, int>(this, "dc_motor", (sender, e) =>  // this is going from MainPage to HERE (Board)
            {
                data = e;
                Output_To_Bluetooth();
            });

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            BluetoothSocket _socket = null;

            {
                myConnection = new BluetoothConnection();
                myConnection.getAdapter();
                myConnection.thisAdapter.StartDiscovery();

                try
                {
                    myConnection.getDevice();
                    myConnection.thisDevice.SetPairingConfirmation(false);
                    myConnection.thisDevice.SetPairingConfirmation(true);
                    myConnection.thisDevice.CreateBond();
                }
                catch (Exception)
                {}
                myConnection.thisAdapter.CancelDiscovery();

                try
                { _socket = myConnection.thisDevice.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805f9b34fb")); }
                catch (Exception)
                {}

                myConnection.thisSocket = _socket;

                try
                {
                    myConnection.thisSocket.Connect();
                }
                catch (Exception)
                {}
            };

            LoadApplication(new App());
        }
예제 #17
0
        protected async override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
            try
            {
                await BluetoothConnection.SendCommand(",");

                //gloablvalue.RecivedText = "";
                //gloablvalue.Status = "";
            }
            catch (Exception)
            {
                FingerStatusText.Text = "An error occured!";
            }
        }
예제 #18
0
        private async void FINGERIMG_Tapped(object sender, TappedRoutedEventArgs e)
        {
            //try
            //{
            await BluetoothConnection.SendCommand("-");

            HideFINGER.Begin();
            FINGERIMG.IsTapEnabled = false;
            Title2.Text            = "Taking attendance..";
            //}
            //catch (Exception)
            //{
            //    var dialo2g = new MessageDialog("error in start device, click again.");
            //    await dialo2g.ShowAsync();
            //}
        }
예제 #19
0
 private async void ConnectBTN_Click(object sender, RoutedEventArgs e)
 {
     if (txtbxDeviceName.Text != "")
     {
         if (ConnectBTN.Tag.ToString() == "connect")
         {
             gloablvalue.DeviceName = txtbxDeviceName.Text;
             ConnectBTN.IsEnabled   = false;
             if (gloablvalue.DeviceState == "-1")//device not connect
             {
                 BluetoothConnection.ConnectToDevice();
                 Devicestate_txt.Text = "Connecting...";
                 newrec_txt.Text      = gloablvalue.checksend(gloablvalue.RecivedText);
                 Hide.Begin();
             }
         }
         else if (ConnectBTN.Tag.ToString() == "Dissconnect")
         {
             if (gloablvalue.DeviceState == "1")//device connected
             {
                 ConnectBTN.IsEnabled = false;
                 try
                 {
                     BluetoothConnection.CloseDevice();
                     Devicestate_txt.Text = "' " + gloablvalue.DeviceName + " ' " + " Dissconnected";
                     ConnectBTN.Content   = "connect";
                     ConnectBTN.Tag       = "connect";
                     ConnectBTN.IsEnabled = true;
                     //gloablvalue.DeviceState = "-1";
                 }
                 catch (Exception)
                 {
                     // ...
                 }
             }
         }
     }
     else
     {
         var dlg = new MessageDialog("please type a device name..");
         await dlg.ShowAsync();
     }
 }
예제 #20
0
        protected override void OnCreate(Bundle bundle)
        {

            var obj = DependencyService.Get<PortableInterface>().GetLogicFromAndroidProject();
            base.OnCreate(bundle);
            Xamarin.Forms.Forms.Init(this, bundle);
            
            //Haal de button uit de layout bron
            //verbind hieraan een event
            Arm ButtonUp = new Arm();
            

            Button Bleuthootconnect = FindViewById<Button>(Bleutooth.ClassIdProperty(Bleuthootconnect));
            Button BleuthootDisconnect = FindViewById<Button>(;
            Button ButtonOmhoog = FindViewById<Button>(Arm.ClassIdProperty(ButtonUp));
            Button ButtonVooruit = FindViewById<Button>(Wielen.ClassIdProperty(ButtonFront));
            Button ButtonAchteruit = FindViewById<Button>(Resource.Id.button4);
            Button ButtonRechts = FindViewById<Button>(Resource.Id.button5);
            Button ButtonLinks = FindViewById<Button>(Resource.Id.buttonPanel);
           

            
            BluetoothSocket _socket = null;


            System.Threading.Thread listenThread = new System.Threading.Thread(Listener);
            listenThread.Abort();

            Bleuthootconnect.Click += delegate
            {
                //deze code heb ik van de volgende website:https://www.instructables.com/3-LED-Backlight-Xamarin-and-Arduino-With-HC05/
                listenThread.Start();
                myConnection = new BluetoothConnection();
                myConnection.getAdapter();
                myConnection.thisAdapter.StartDiscovery();

                try
                {
                    myConnection.getDevice();
                    myConnection.thisDevice.SetPairingConfirmation(false);

                    myConnection.thisDevice.SetPairingConfirmation(true);
                    myConnection.thisDevice.CreateBond();

                }
                catch (Exception ex)
                {

                }
                myConnection.thisAdapter.CancelDiscovery();

                _socket = myConnection.thisDevice.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));

                myConnection.thisSocket = _socket;

                //   System.Threading.Thread.Sleep(500);
                try {
                    myConnection.thisSocket.Connect();
                    //deze kan later nog worden gemaakt voorlopig geeft dit nog een error.
                    //Connected.Text = "Verbonden!";
                    BleuthootConnect.Enabled = true;
                    BleuthootDisconnect.Enabled = false;

                    if (listenThread.IsAlive == false)
                    {
                        listenThread.Start();
                    }


                }
                catch (Exception CloseEX)
                {

                }


                myConnection.thisSocket = _socket;

                try
                {
                    myConnection.thisSocket.Connect();

                    Bleuthootconnect.Text = "verbonden met de arduino!!! kusjes Enrick xxx";
                    BleuthootDisconnect.Enabled = true;
                    Bleuthootconnect.Enabled = false;
                    if (listenThread.IsAlive == false)
                    {
                        listenThread.Start();
                    }
                }
                catch (Exception ex)
                { Console.WriteLine("connect to device", ex); }
            };

            BleuthootDisconnect.Click += delegate
            {

                try
                {
                    //is de connectie aan ja of nee?
                    Bleuthootconnect.Enabled = true;

                    myConnection.thisDevice.Dispose();
                    //dit moet 187 zijn want dit is de nummer om te verbinden met de bleuthoot module HC05.
                    myConnection.thisSocket.OutputStream.WriteByte(187);
                    myConnection.thisSocket.OutputStream.Close();

                    myConnection.thisSocket.Close();

                    myConnection = new BluetoothConnection();
                    _socket = null;

                    Bleuthootconnect.Text = "Not connected to the Arduino!";
                }
                catch { }
            };


            ButtonVooruit.Click += delegate
            {
                try
                {
                    //De nummer die moet worden doorgegeven voor vooruit de gaan is 4.
                    myConnection.thisSocket.OutputStream.WriteByte(4);
                    myConnection.thisSocket.OutputStream.Close();
                }
                catch (Exception ex)
                {

                    Console.WriteLine(ex.Message);
                }

            };
            ButtonAchteruit.Click += delegate
            {
                try
                {
                    //bij het nummer 3 wordt het commando achteruit rijden geactiveerd
                    myConnection.thisSocket.OutputStream.WriteByte(3);
                    myConnection.thisSocket.OutputStream.Close();
                }
                catch (Exception)
                {

                    throw;
                }
            };
            ButtonLinks.Click += delegate
            {
                try
                {
                    //bij het nummer 1 wordt het commando links rijden geactiveerd
                    myConnection.thisSocket.OutputStream.WriteByte(1);
                    myConnection.thisSocket.OutputStream.Close();
                }
                catch (Exception)
                {

                    throw;
                }
            };

            ButtonOmhoog.Click += delegate
            {
                try
                {
                    //bij deze 3 commando's gaat de arm helemaal naar boven. 
                    myConnection.thisSocket.OutputStream.WriteByte(8);
                    myConnection.thisSocket.OutputStream.WriteByte(10);
                    myConnection.thisSocket.OutputStream.WriteByte(12);
                    myConnection.thisSocket.OutputStream.Close();
                }
                catch (Exception)
                {

                    throw;
                }
            };
        }
예제 #21
0
 public void Close()
 {
     BluetoothConnection.Close();
 }
예제 #22
0
 public void Open(string portName, int timeout)
 {
     BluetoothConnection.PortName = portName;
     BluetoothConnection.Open();
     BluetoothConnection.ReadTimeout = timeout;
 }
예제 #23
0
 void Start()
 {
     blueC = GameObject.FindGameObjectWithTag("GameController").GetComponent <BluetoothConnection>();
 }
예제 #24
0
        /// <summary>
        /// Run example
        /// </summary>
        public static void RunExample()
        {
            NetworkComms.ConnectionEstablishTimeoutMS = int.MaxValue;

            SendReceiveOptions nullCompressionSRO = new SendReceiveOptions(DPSManager.GetDataSerializer <ProtobufSerializer>(), null, null);

            NetworkComms.DefaultSendReceiveOptions = nullCompressionSRO;

            //We need to define what happens when packets are received.
            //To do this we add an incoming packet handler for a 'Message' packet type.
            //
            //We will define what we want the handler to do inline by using a lambda expression
            //http://msdn.microsoft.com/en-us/library/bb397687.aspx.
            //We could also just point the AppendGlobalIncomingPacketHandler method
            //to a standard method (See AdvancedSend example)
            //
            //This handler will convert the incoming raw bytes into a string (this is what
            //the <string> bit means) and then write that string to the local console window.
            NetworkComms.AppendGlobalIncomingPacketHandler <string>("Message", (packetHeader, connection, incomingString) => { Console.WriteLine("\n  ... Incoming message from " + connection.ToString() + " saying '" + incomingString + "'."); });

            //Start listenning
            BluetoothRadio defaultRadio = BluetoothRadio.PrimaryRadio;

            defaultRadio.Mode = RadioMode.Discoverable;
            Connection.StartListening(ConnectionType.Bluetooth, new BluetoothEndPoint(defaultRadio.LocalAddress, ServiceGUID), true);

            //Print the address we are listening on to make sure everything
            //worked as expected.
            Console.WriteLine("Listening for messages on:");
            foreach (var localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.Bluetooth))
            {
                Console.WriteLine("{0}", localEndPoint);
            }

            PeerDiscovery.EnableDiscoverable(PeerDiscovery.DiscoveryMethod.BluetoothSDP);

            //We loop here to allow any number of test messages to be sent and received
            while (true)
            {
                //Request a message to send somewhere
                Console.WriteLine("\nPlease enter your message and press enter (Type 'exit' to quit):");
                string stringToSend = Console.ReadLine();

                //If the user has typed exit then we leave our loop and end the example
                if (stringToSend == "exit")
                {
                    break;
                }
                else
                {
                    //Once we have a message we need to know where to send it
                    //We have created a small wrapper class to help keep things clean here
                    var endpoints = PeerDiscovery.DiscoverPeers(PeerDiscovery.DiscoveryMethod.BluetoothSDP, 1000);

                    ConnectionInfo targetServerConnectionInfo = new ConnectionInfo(new BluetoothEndPoint(new BluetoothAddress(0xE0B9A5FB552BL), ServiceGUID));

                    //There are loads of ways of sending data (see AdvancedSend example for more)
                    //but the most simple, which we use here, just uses an IP address (string) and port (integer)
                    //We pull these values out of the ConnectionInfo object we got above and voila!
                    var connection = BluetoothConnection.GetConnection(targetServerConnectionInfo);

                    connection.SendObject("Message", "Hello world");
                }
            }

            //We should always call shutdown on comms if we have used it
            NetworkComms.Shutdown();
        }
예제 #25
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            Button buttonConnect    = FindViewById <Button>(Resource.Id.button1);
            Button buttonDisconnect = FindViewById <Button>(Resource.Id.button2);

            Button button1On = FindViewById <Button>(Resource.Id.button3);
            Button button2On = FindViewById <Button>(Resource.Id.button4);

            TextView        connected = FindViewById <TextView>(Resource.Id.textView1);
            BluetoothSocket _socket   = null;

            System.Threading.Thread listenThread = new System.Threading.Thread(listener);
            listenThread.Abort();

            buttonConnect.Click += delegate
            {
                listenThread.Start();

                myConnection = new BluetoothConnection();

                myConnection.getAdapter();

                myConnection.thisAdapter.StartDiscovery();

                try
                {
                    myConnection.getDevice();

                    myConnection.thisDevice.SetPairingConfirmation(false);

                    myConnection.thisDevice.SetPairingConfirmation(true);

                    myConnection.thisDevice.CreateBond();
                }
                catch (Exception deviceEX)
                {
                }
                myConnection.thisAdapter.CancelDiscovery();

                _socket = myConnection.thisDevice.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));

                myConnection.thisSocket = _socket;

                try
                {
                    myConnection.thisSocket.Connect();

                    connected.Text = "Connected!";

                    buttonDisconnect.Enabled = true;

                    buttonConnect.Enabled = false;

                    if (listenThread.IsAlive == false)
                    {
                        listenThread.Start();
                    }
                }
                catch (Exception CloseEX)
                {
                }
            };

            buttonDisconnect.Click += delegate
            {
                try
                {
                    buttonConnect.Enabled = true;
                    listenThread.Abort();

                    myConnection.thisDevice.Dispose();

                    myConnection.thisSocket.OutputStream.WriteByte(187);
                    myConnection.thisSocket.OutputStream.Close();

                    myConnection.thisSocket.Close();

                    myConnection = new BluetoothConnection();
                    _socket      = null;

                    connected.Text = "Disconnected!";
                }
                catch { }
            };



            button1On.Click += delegate
            {
                try
                {
                    myConnection.thisSocket.OutputStream.WriteByte(1);
                    myConnection.thisSocket.OutputStream.WriteByte(1);
                    myConnection.thisSocket.OutputStream.WriteByte(1);
                    myConnection.thisSocket.OutputStream.Close();
                }
                catch (Exception outPutEX)
                {
                }
            };

            button2On.Click += delegate
            {
                try
                {
                    myConnection.thisSocket.OutputStream.WriteByte(2);
                    myConnection.thisSocket.OutputStream.WriteByte(2);
                    myConnection.thisSocket.OutputStream.WriteByte(2);
                    myConnection.thisSocket.OutputStream.Close();
                }
                catch (Exception outPutEX)
                {
                }
            };

            void listener()
            {
                byte[] read = new byte[1];

                TextView readTextView = FindViewById <TextView>(Resource.Id.textView2);
                TextView timeTextView = FindViewById <TextView>(Resource.Id.textView3);

                while (true)
                {
                    try
                    {
                        myConnection.thisSocket.InputStream.Read(read, 0, 1);
                        myConnection.thisSocket.InputStream.Close();
                        RunOnUiThread(() =>
                        {
                            if (read[0] == 1)
                            {
                                readTextView.Text = "Relais AN";
                            }
                            else if (read[0] == 0)
                            {
                                readTextView.Text = "Relais AUS";
                                timeTextView.Text = "";
                            }
                        });
                    }
                    catch { }
                }
            }
        }