Beispiel #1
0
        public void ServerConnectThread()
        {
            updateUI("Server started, waiting for client");
            bluetoothListener = new BluetoothListener(mUUID);
            bluetoothListener.Start();
            conn = bluetoothListener.AcceptBluetoothClient();

            updateUI("Client has connected");
            connected = true;

            //Stream mStream = conn.GetStream();
            mStream = conn.GetStream();

            while (connected)
            {
                try
                {
                    byte[] received = new byte[1024];
                    mStream.Read(received, 0, received.Length);
                    string receivedString = Encoding.ASCII.GetString(received);
                    //updateUI("Received: " + receivedString);
                    handleBluetoothInput(receivedString);
                    //byte[] send = Encoding.ASCII.GetBytes("Hello world");
                    //mStream.Write(send, 0, send.Length);
                }
                catch (IOException e)
                {
                    connected = false;
                    updateUI("Client disconnected");
                    disconnectBluetooth();
                }
            }
        }
        public void ServerConnectThread()
        {
            _screenWriterCallBT("Bluetooth Server started, waiting for clients..");
            BluetoothListener blueListener = new BluetoothListener(mUUID);
            blueListener.Start();
            BluetoothClient conn = blueListener.AcceptBluetoothClient();
            _screenWriterCallBT("Bluetooth Client has connected");
            bool disconnectedClient = false;

            while (true)
            {

                try
                {
                    if (disconnectedClient)
                    {
                        _screenWriterCallBT("Bluetooth server waiting for client");
                        conn = blueListener.AcceptBluetoothClient();
                        disconnectedClient = false;
                    }

                    Stream mStream = conn.GetStream();
                    byte[] recieved = new byte[1024];
                    mStream.Read(recieved, 0, recieved.Length);
                    string content = Encoding.ASCII.GetString(recieved).TrimEnd('\0');
                    if (content.Length == 0)
                    {
                        disconnectedClient = true;
                    }

                    _screenWriterCallBT("Recieved: " + content + "via bluetooth");

                    ParseJson parseJson = new ParseJson(_videoFormActionDelegate, _imageFormActionDelegate);
                    JsonReturn = parseJson.InitialParsing(content); //parse message

                    byte[] sent = Encoding.ASCII.GetBytes(JsonReturn);
                    mStream.Write(sent, 0, sent.Length);
                    string messageSent = Encoding.ASCII.GetString(sent);
                    _screenWriterCallBT("sent via Bluetooth: " + messageSent);
                }
                catch (IOException exception)
                {
                    _screenWriterCallBT("Bluetooth Client has disconnected. Exception:" + exception + "\n");
                }
            }
        }
        public void StartListening()
        {
            BluetoothListener btl = new BluetoothListener(MyService);
            btl.Start();
            listening = true;
            while (listening)
            {

                Console.WriteLine("wait for device");
                BluetoothClient conn = btl.AcceptBluetoothClient();
                Console.WriteLine("device accepted");
                DispatchConnection(conn);

            }
        }
Beispiel #4
0
 /*public static void md5(string source)
 {
     byte[] data = System.Text.Encoding.UTF8.GetBytes(source);
     MD5 md = MD5.Create();
     byte [] cryptoData = md.ComputeHash(data);
     Console.WriteLine(System.Text.Encoding.UTF8.GetString(cryptoData));
     md.Clear();
 }
 */
 public void Listen()
 {
     try { new BluetoothClient(); }
     catch (Exception ex)
     {
         var msg = "Bluetooth init failed: " + ex;
         MessageBox.Show(msg);
         throw new InvalidOperationException(msg, ex);
     }
     Bluetoothlistener = new BluetoothListener(OurServiceClassId);
     Bluetoothlistener.ServiceName = OurServiceName;
     Bluetoothlistener.Start();
     Bluetoothclient = Bluetoothlistener.AcceptBluetoothClient();
     byte[] data = new byte[1024];
     Ns = Bluetoothclient.GetStream();
     Ns.BeginRead(data, 0, data.Length, new AsyncCallback(ReadCallBack), data);
     DataAvailable(this, "Begin to read");
 }
        private void doListen(object sender, ElapsedEventArgs e)
        {
            if (isSlave && !listen)
            {
                Bluetoothlistener = new BluetoothListener(BluetoothService.SerialPort);
                Bluetoothlistener.Start();
                localClient = Bluetoothlistener.AcceptBluetoothClient();
                isPaired = true;
            }

            listen = true;

                if (localClient != null && localClient.Connected && !stop)
                {
                    try
                    {
                        byte[] data = new byte[6];

                        Ns = localClient.GetStream();
                        Ns.ReadTimeout = 5000;
                        Ns.Read(data, 0, data.Length);
                        listenAttemps = 0;
                        // event message
                        if (onReceiveMessage != null)
                        {
                            Console.WriteLine("RECEIVED " + data);
                            onReceiveMessage.Invoke(ASCIIEncoding.ASCII.GetString(data));
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                        listenAttemps++;
                        //Connexion coupé
                        if (onConnectionEnded_Event != null && listenAttemps >= 20)
                        {
                            onConnectionEnded_Event.Invoke("cut");
                        }
                    }
                }
                else if(stop)
                {
                    Ns.Dispose();
                    Ns.Close();
                    closeConnection();
                    init(macAddr);
                }
                else if (!localClient.Connected)
                {
                    Console.WriteLine("Connection Terminer ou jamais initié");
                }
        }
        public void MakeConnection()
        {
            BluetoothClient thisRadio = GetRadio();

            if (thisRadio == null)
            {
                SetError("Bluetooth radio not found");
                return;
            }

            BluetoothDeviceInfo pulseOx = GetPulseOx(thisRadio);

            if (pulseOx == null)
            {
                SetError("Pulse oximeter not found");
                return;
            }

            noninEndpoint = new BluetoothEndPoint(pulseOx.DeviceAddress, BluetoothService.SerialPort);

            /* Listen mode   */
            if (ATREnabled)
            {
                BluetoothListener btListen = new BluetoothListener(BluetoothService.SerialPort);
                btListen.Start();
                noninClient = btListen.AcceptBluetoothClient();
            }

            /* Connect mode */
            else
            {
                noninClient = new BluetoothClient();

                try
                {
                    noninClient.Connect(noninEndpoint);
                }

                catch (SocketException ex)
                {
                    SetError("Couldn't connect to pulse oximeter", ex);
                }
            }

            if (noninClient.Connected)
            {
                connectionBegin = DateTime.Now;
            }

            GetMostRecentReading();
        }
Beispiel #7
0
        internal void ServerListeningThread()
        {
            try
            {
                serverStarted = false; // just making sure server start is in sync
                try
                {
                    blueListener = new BluetoothListener(mUUID);
                    blueListener.Start();
                    serverStarted = true;
                }
                catch (Exception ex)
                {
                    serverStarted = false;
                    Log.Unhandled(ex);
                    if (noBlockingMode)
                    {
                        Log.BtServer("Bluetooth enhet er ikke støttet, er slått av, eller mangler." + ex.Message, true);
                    }
                    else
                    {
                        Log.ErrorDialog(ex, "Problem oppstod ved start av Bluetooth listener.\nBluetooth enhet er ikke støttet, er slått av, eller mangler. Kan også oppstå når der er problem med programvaren/driver til Bluetooth maskinvaren.", "Bluetooth serveren kan ikke starte.");
                    }
                }

                Log.BtServer("Bluetooth server har startet. Aksepterer tilkoblinger fra alle MScanner mobiler fra versjon " + main.appConfig.blueServerMinimumAcceptedVersion);
                while (true)
                {
                    try
                    {
                        if (!serverStarted)
                            break;

                        if (blueListener.Pending())
                        {
                            using (BluetoothClient client = blueListener.AcceptBluetoothClient())
                            {
                                ClientConnected(client);
                            }
                        }
                    }
                    catch (SocketException ex) { Log.BtServer("Lese/skrive feil: " + ex.Message); break; }
                    catch (Exception ex) { Log.Unhandled(ex); break; }
                }

                if (blueListener != null)
                    blueListener.Stop();

                if (blueListener != null)
                    Log.BtServer("Server avslått");

                serverStarted = false;
            }
            catch (Exception ex)
            {
                Log.BtServer("Generell feil: " + ex.Message);
            }
            finally
            {
                if (blueListener != null)
                {
                    blueListener.Stop();
                    blueListener = null;
                }
                serverStarted = false;
            }
        }
Beispiel #8
0
 /// <summary>
 /// Waiting to accept connection with Android. (PC as Slave)
 /// </summary>
 /// <param name="listener">Listen requests to accept and connect</param>
 /// <param name="client">Created from accepted connection</param>
 /// <returns></returns>
 private static bool ConnectAndroid(ref BluetoothListener listener, ref BluetoothClient client)
 {
     try
     {
         listener = new BluetoothListener(BluetoothService.RFCommProtocol);
         listener.Start();
         client = listener.AcceptBluetoothClient();
         return true;
     }
     catch (Exception)
     {
         MessageBox.Show(@"Error. Connection is failed!");
         return false;
     }
 }
        public override void receive_file(String devicename, String bluid, int not)
        {
            try
            {
                _stopwatch.Start();
                scan_transfer_speed();                

                _bluetooth_guid = Guid.Parse(bluid);
                _bluetooth_listener = new BluetoothListener(_bluetooth_guid);
                _bluetooth_listener.Start();

                _bluetooth_client = _bluetooth_listener.AcceptBluetoothClient();
                _netstream = _bluetooth_client.GetStream();

                _filestream = new FileStream(this.filepath, FileMode.Create, FileAccess.ReadWrite);

                int length;
                _buffer = new byte[65000];
                
                while ((length = _netstream.Read(_buffer, 0, _buffer.Length)) != 0)
                {
                    while (_writing) { }

                    _count_received_bytes += length;

                    _filestream.Write(_buffer, 0, length);
                }

                _timer_ts.Close();
                _stopwatch.Stop();

                int _transferspeed = _count_received_bytes / 1024;
                _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), "kB/s");
                this.callback.on_transfer_speed_change(_message, this.results);
                this.main_view.text_to_logs(_message);

                _filestream.Dispose();
                _filestream.Close();

                _netstream.Dispose();
                _netstream.Close();

                _bluetooth_client.Dispose();
                _bluetooth_client.Close();

                _bluetooth_listener.Stop();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message);
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, devicename);
            }
        }               
Beispiel #10
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            serviceClass = BluetoothService.SerialPort;
            var lsnr = new BluetoothListener(serviceClass);
            lsnr.Start();
            worker.ReportProgress(0);
            conn = lsnr.AcceptBluetoothClient();
            worker.ReportProgress(1);
            connected = true;
            Stream peerStream = conn.GetStream();
            byte[] buf = new byte[1];
            while (true)
            {
                int readLen = peerStream.Read(buf, 0, buf.Length);
                string val = ASCIIEncoding.ASCII.GetString(buf);
                if (readLen == 0)
                {
                    worker.ReportProgress(2);
                    break;
                }
                else
                {
                    if (dic.ContainsKey(val))
                    {
                        au3.Send(dic[val]);

                    }
                  /*  else
                    {
                        worker.ReportProgress(3);
                        label4.Text = "Please Report: Undefined " + val;
                    }
                 */

                }
            }
        }
        public void ServerConnectThread()
        {
            serverStarted = true;
            updateUI("Server started, waiting for clients");
            BluetoothListener blueListener = new BluetoothListener(mUUID);
            blueListener.Start();
            conn = blueListener.AcceptBluetoothClient();
            updateUI("Client has connected");
            Stream mStream = conn.GetStream();

            bool initialized = false;

            while(true)
            {
                try
                {
                    byte[] received = new byte[1024];
                    mStream.Read(received, 0, received.Length);

                    updateUI("Received" + Encoding.ASCII.GetString(received));

                    if (initialized == false)
                    {
                        //parse json here
                        JObject input = JObject.Parse(Encoding.ASCII.GetString(received));

                        //send updates to vjoy program
                        vjoy.setCoefficient(input);

                        initialized = true;
                    }
                    //Console.WriteLine("recieved: " + received);

                    try
                    {
                        //parse json here
                        JObject payload = JObject.Parse(Encoding.ASCII.GetString(received));

                        //send updates to vjoy program
                        vjoy.setValues(payload);
                    }
                    catch(JsonReaderException bluetoothError)
                    {
                        Console.WriteLine("BLUETOOTH ERROR: " + bluetoothError.ToString());
                    }

                    

                    byte[] sent = Encoding.ASCII.GetBytes("Hello World");
                    mStream.Write(sent, 0, sent.Length);
                }
                catch (IOException exception)
                {
                    updateUI("Client has disconnected");
                    break;
                }

            }

        }