예제 #1
2
        public bool SetAddress(BluetoothAddress address)
        {
            try
            {
                //Set BT Device Address
                blt_address = address;

                //Set BT Device Pin
                BluetoothSecurity.SetPin((BluetoothAddress)blt_address, "1234");

                // Create a connection channel specifying the Bluetooth-Serial end-points
                blt_endPoint = new BluetoothEndPoint((BluetoothAddress)blt_address, BluetoothService.SerialPort);

                return true;
            }
            catch
            {
                return false;
            }
        }
예제 #2
2
        /// <summary>
        /// Asynchrones Verbinden zu dem Client.
        /// </summary>
        /// <param name="dev_name">Der Name des Geräts.</param>
        public void connect_to_be(string dev_name)
        {
            add = get_device_address(dev_name);

            BluetoothEndPoint BEP = new BluetoothEndPoint(add, BluetoothUUID);

            client = new BluetoothClient();

            object connection = false;
            try
            {
                client.BeginConnect(BEP, new AsyncCallback(start_read), client);
            }
            catch (Exception excep)
            {
                Debug.WriteLine(excep.ToString());
            }
        }
        /// <summary>
        /// Sends the data to the Receiver.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="content">The content.</param>
        /// <returns>If was sent or not.</returns>
        public async Task<bool> Send(Device device, string content)
        {
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }

            if (string.IsNullOrEmpty(content))
            {
                throw new ArgumentNullException("content");
            }

            // for not block the UI it will run in a different threat
            var task = Task.Run(() =>
            {
                using (var bluetoothClient = new BluetoothClient())
                {
                    try
                    {
                        var ep = new BluetoothEndPoint(device.DeviceInfo.DeviceAddress, _serviceClassId);
                       
                        // connecting
                        bluetoothClient.Connect(ep);

                        // get stream for send the data
                        var bluetoothStream = bluetoothClient.GetStream();

                        // if all is ok to send
                        if (bluetoothClient.Connected && bluetoothStream != null)
                        {
                            // write the data in the stream
                            var buffer = System.Text.Encoding.UTF8.GetBytes(content);
                            bluetoothStream.Write(buffer, 0, buffer.Length);
                            bluetoothStream.Flush();
                            bluetoothStream.Close();
                            return true;
                        }
                        return false;
                    }
                    catch
                    {
                        // the error will be ignored and the send data will report as not sent
                        // for understood the type of the error, handle the exception
                    }
                }
                return false;
            });
            return await task;
        }
        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);

            }*/
        }
예제 #5
1
        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, Int32.Parse(osae.GetObjectPropertyValue(pName, "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 = osae.GetObjectByAddress(addr);

                    if (obj == null)
                    {
                        if (osae.GetObjectPropertyValue(pName, "Learning Mode").Value == "TRUE")
                        {
                            osae.ObjectAdd(nearosaeDevices[j].DeviceName, nearosaeDevices[j].DeviceName, "BLUETOOTH DEVICE", nearosaeDevices[j].DeviceAddress.ToString(), "", true);
                            osae.ObjectPropertySet(nearosaeDevices[j].DeviceName, "Discover Type", "0");
                            logging.AddToLog(addr + " - " + nearosaeDevices[j].DeviceName + ": added to OSA", true);
                        }
                    }
                }

                List<OSAEObject> objects = osae.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);
                    logging.AddToLog("begin search for " + address, false);

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

                    }

                    try
                    {
                        if (!found && (Int32.Parse(osae.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 2 || Int32.Parse(osae.GetObjectPropertyValue(obj.Name, "Discover Type").Value) == 0))
                        {
                            logging.AddToLog(address + " - " + obj.Name + ": attempting GetServiceRecords", false);

                            bdi.GetServiceRecords(uuid);
                            found = true;
                            logging.AddToLog(address + " - " + obj.Name + " found with GetServiceRecords", false);

                        }
                    }
                    catch (Exception ex)
                    {
                        logging.AddToLog(address + " - " + obj.Name + " failed GetServiceRecords. exception: " + ex.Message, false);

                    }

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

                    if (found)
                    {
                        osae.ObjectStateSet(obj.Name, "ON");
                        logging.AddToLog("Status Updated in osae", false);
                    }
                    else
                    {
                        osae.ObjectStateSet(obj.Name, "OFF");
                        logging.AddToLog("Status Updated in osae", false);
                    }

                }
            }
            catch (Exception ex)
            {
                logging.AddToLog("Error searching for devices: " + ex.Message, true);
            }
        }
        public static void GetImages(BluetoothEndPoint endpoint, Color tagColor)
        {
            InTheHand.Net.Sockets.BluetoothClient btc = new InTheHand.Net.Sockets.BluetoothClient();
            btc.Connect(endpoint);
            var nws = btc.GetStream();
            byte[] emptySize = BitConverter.GetBytes(0); //
            if (BitConverter.IsLittleEndian) Array.Reverse(emptySize); // redundant but usefull in case the number changes later..
            nws.Write(emptySize, 0, emptySize.Length); // write image size
            int imgCount = GetImgSize(nws);
            nws = btc.GetStream();
            for (int i = 0; i < imgCount; i++)
            {
                MemoryStream ms = new MemoryStream();
                int size = GetImgSize(nws);
                if (size == 0) continue;
                byte[] buffer = new byte[size];
                int read = 0;

                while ((read = nws.Read(buffer, 0, buffer.Length)) != 0)
                {
                    ms.Write(buffer, 0, read);
                }
                SurfaceWindow1.AddImage(System.Drawing.Image.FromStream(ms), tagColor);
            }
        }
예제 #7
0
        /// <summary>
        /// Attempt to connect to the BluetoothDevice, without trying to pair first.
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        public static async Task<Boolean> connectToDeviceWithoutPairing(BluetoothDevice device) {
            BluetoothEndPoint endPoint = new BluetoothEndPoint(device.btDeviceInfo.DeviceAddress, BluetoothService.SerialPort);
            BluetoothClient client = new BluetoothClient();
            if (!device.Authenticated) {
                return false;
            }
            else {
                try {
                    client.Connect(endPoint);

                    if (devicesStreams.Keys.Contains(device)) {
                        devicesStreams.Remove(device);
                    }
                    devicesStreams.Add(device, client.GetStream());

                    if (devicesClients.Keys.Contains(device)) {
                        devicesClients.Remove(device);
                    }
                    devicesClients.Add(device, client);
                }
                catch (Exception ex) {
                    //System.Console.Write("Could not connect to device: " + device.DeviceName + " " + device.DeviceAddress);
                    return false;
                }
                return true;
            }
        }
예제 #8
0
        public bool ConnectToSphero(string spheroName)
        {
            if (_client == null)
                return false;

            if (_peers == null)
                return false;

            var device = _peers.FirstOrDefault(x => x.DeviceName == spheroName);
            if (device == null)
                return false;

            try
            {
                var serviceClass = BluetoothService.SerialPort;
                var ep = new BluetoothEndPoint(device.DeviceAddress, serviceClass);
                _client.Connect(ep);
                _stream = _client.GetStream();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <inheritdoc />
        protected override void EstablishConnectionSpecific()
        {
            if (btClient == null) ConnectSocket();

            //We should now be able to set the connectionInfo localEndPoint
            var localEndPoint = btClient.Client.LocalEndPoint as BluetoothEndPoint;
            localEndPoint = new BluetoothEndPoint(localEndPoint.Address, ConnectionInfo.RemoteBTEndPoint.Service, localEndPoint.Port);

            NetworkComms.UpdateConnectionReferenceByEndPoint(this, ConnectionInfo.RemoteEndPoint, localEndPoint);
            ConnectionInfo.UpdateLocalEndPointInfo(localEndPoint);

            btClient.Client.ReceiveBufferSize = NetworkComms.MaxReceiveBufferSizeBytes;
            btClient.Client.SendBufferSize = NetworkComms.SendBufferSizeBytes;

            //We are going to be using the networkStream quite a bit so we pull out a reference once here
            btClientNetworkStream = btClient.GetStream();
                        
            //Start listening for incoming data
            StartIncomingDataListen();

            //If the application layer protocol is enabled we handshake the connection
            if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled)
                ConnectionHandshake();
            else
            {
                //If there is no handshake we can now consider the connection established
                TriggerConnectionEstablishDelegates();

                //Trigger any connection setup waits
                connectionSetupWait.Set();
            }            
        }
 public static void SendBluetooth(BluetoothEndPoint endpoint, BitmapSource bms)
 {
     InTheHand.Net.Sockets.BluetoothClient btc = new InTheHand.Net.Sockets.BluetoothClient();
     btc.Connect(endpoint);
     byte[] img = BmSourceToByteArr(bms);
     var nws = btc.GetStream();
     byte[] imgSize = BitConverter.GetBytes(img.Length);
     if (BitConverter.IsLittleEndian) Array.Reverse(imgSize);
     nws.Write(imgSize, 0, imgSize.Length); // write image size
     nws.Write(img, 0, img.Length); // Write image
     nws.Flush();
 }
예제 #11
0
 private async void DoConnect(Action<IConnectedSphero> onSuccess, Action<Exception> onError)
 {
     try
     {
         var serviceClass = BluetoothService.SerialPort;
         var ep = new BluetoothEndPoint(PeerInformation.DeviceAddress, serviceClass);
         var client = new BluetoothClient();
         client.Connect(ep);
         var stream = client.GetStream();
         onSuccess(new ConnectedSphero(PeerInformation, stream));
     }
     catch (Exception exception)
     {
         onError(exception);
     }
 }
        static BluetoothUtils()
        {
            // Define common Pin codes for Bluetooth devices

            PrimaryRadio = BluetoothRadio.PrimaryRadio;
            if (PrimaryRadio == null) {
                //Console.WriteLine("No radio hardware or unsupported software stack");
                return;
            }

            // Local bluetooth MAC address 
            var mac = PrimaryRadio.LocalAddress;
            if (mac == null) {
                //Console.WriteLine("No local Bluetooth MAC address found");
                return;
            }
            DeviceList = new List<BluetoothDeviceInfo>();
            // mac is mac address of local bluetooth device
            //LocalEndpoint = new BluetoothEndPoint(mac, BluetoothService.SerialPort);
            LocalEndpoint = new BluetoothEndPoint(mac, Guid);             
            // client is used to manage connections
            LocalClient = new BluetoothClient(LocalEndpoint);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SenderBluetoothService"/> class. 
        /// </summary>
        public SenderBluetoothService()
        {
            // this guid is random, only need to match in Sender & Receiver
            // this is like a "key" for the connection!
            _serviceClassId = new Guid("e0cbf06c-cd8b-4647-bb8a-263b43f0f974");

            myRadio = BluetoothRadio.PrimaryRadio;
            if (myRadio == null)
            {
                Console.WriteLine("No radio hardware or unsupported software stack");
                //return;
            }
            RadioMode mode = myRadio.Mode;
            // Warning: LocalAddress is null if the radio is powered-off.
            Console.WriteLine("* Radio, address: {0:C}", myRadio.LocalAddress);

            // mac is mac address of local bluetooth device
             localEndpoint = new BluetoothEndPoint(myRadio.LocalAddress, BluetoothService.SerialPort);
            // client is used to manage connections
            bluetoothClient = new BluetoothClient(localEndpoint);
            // component is used to manage device discovery
            localComponent = new BluetoothComponent(bluetoothClient);
        }
        public override Stream GetStream()
        {
            if (Stream == null)
            {
                BluetoothDeviceInfo devInfo = GetDeviceInfo(DeviceName);

                if (devInfo == null)
                    return null;

                BluetoothEndPoint ep = new BluetoothEndPoint(devInfo.DeviceAddress, BluetoothService.SerialPort);
                BluetoothClient.Connect(ep);
                Stream peerStream = BluetoothClient.GetStream();

                if (BluetoothClient.Connected)
                {
                    Stream = peerStream;
                    return Stream;
                }
                else
                    return null;
            }
            else
                return Stream;
        }
예제 #15
0
        //========================================================
        // controls the connection
        // starts the connection
        // if check_radio == 1 the radio will be checked
        public bool Start(int check_radio)
        {
            try
            {

                // make sure radio is on
                if(check_radio == 1)
                    TurnON_BT_Radio();

                // clean up bluetooth if it was open
                if (bc != null)
                {
                    bc.Close();
                    bc.Dispose();
                }

                bc = new BluetoothClient();

                if (bc != null)
                {
                    // check the bt end point
                    if (blt_endPoint == null)
                        blt_endPoint = new BluetoothEndPoint((BluetoothAddress)blt_address, BluetoothService.SerialPort);

                    // check the intialization of the stream
                    if (ns != null)
                    {
                        ns.Close();
                        ns.Dispose();
                    }

                    return true;

                }

                return false;
            }
            catch(Exception e)
            {
                status = e.ToString();
                return false;
            }
        }
예제 #16
0
 protected override void OpenConnection()
 {
     btEndpoint = new BluetoothEndPoint(addr, g);
     btClient = new BluetoothClient();
     btClient.Connect(btEndpoint);
     peerStream = btClient.GetStream();
 }
예제 #17
0
        // close the connection
        public void CloseConnection()
        {
            if (bc != null)
            {
                bc.Close();
                bc.Dispose();
            }

            if (ns != null)
            {
                ns.Close();
                ns.Dispose();
            }

            blt_endPoint = null;
        }
예제 #18
0
        private BluetoothClient GetRadio()
        {
            BluetoothRadio btradio = BluetoothRadio.PrimaryRadio;

            if (btradio == null)
            {
                return null;
            }

            BluetoothEndPoint endPoint = new BluetoothEndPoint(btradio.LocalAddress, serviceGuid);
            BluetoothClient thisRadio = new BluetoothClient(endPoint);

            return thisRadio;
        }
예제 #19
0
        void bgCominucate_DoWork(object sender, DoWorkEventArgs e)
        {
            using (var bluetoothClient = new BluetoothClient())
            {
                try
                {
                    var ep = new BluetoothEndPoint(((Device)e.Argument).DeviceInfo, MyConsts.MyServiceUuid);

                    // connecting  
                    bluetoothClient.Connect(ep);

                    Stream peerStream = bluetoothClient.GetStream();

                    StreamReader sr = new StreamReader(peerStream);
                    int line;
                    // Read and display lines from the file until the end of 
                    // the file is reached.
                    while (true)//(line = sr.ReadLine()) != null)
                    {
                        line = sr.Read();
                        if (line != -1)
                        {
                            stream.WriteAsync(BitConverter.GetBytes(((Device)e.Argument).PlayerID), 0, 4);
                            stream.WriteAsync(BitConverter.GetBytes(line), 0, 4);
                        }
                    }
                }
                catch
                {
                    // the error will be ignored and the send data will report as not sent  
                    // for understood the type of the error, handle the exception  
                }
            }
        }
        private void SendZip()
        {
            Logger.LogEvent(true, "MainViewModel.SendZip 200");

            this.wasCanceled = false;
            this.IsScanning = true;
            this.Status = "Trying to establish connection and transfer file..";
            var success = false;
            Exception lastEx = null;

            if (BluetoothRadio.PrimaryRadio.Mode == RadioMode.PowerOff)
            {
                BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
            }

            Logger.LogEvent(true, "MainViewModel.SendZip 201");

            Task.Factory.StartNew(() =>
            {
                if (this.selectedDevice != null)
                {
                    var bluetoothClient = new BluetoothClient();
                    NetworkStream bluetoothStream = null;

                    this.connectionIntervalFinished = false;

                    System.Timers.Timer aTimer = new System.Timers.Timer();
                    aTimer.Elapsed += this.OnTimedEvent;
                    // Set the Interval to 20 second.
                    aTimer.Interval = 20000;
                    aTimer.Start();

                    var device = this.realDevices.FirstOrDefault(x => x.DeviceAddress.Sap == this.selectedDevice.DeviceAddressSap);

                    Logger.LogEvent(true, "MainViewModel.SendZip 201.5 device.DeviceName: {0}", device.DeviceName);

                    var ep = new BluetoothEndPoint(device.DeviceAddress, _serviceClassId);

                    Logger.LogEvent(true, "MainViewModel.SendZip 201.75 ep.Address: {0}", ep.Address);

                    while (!this.connectionIntervalFinished && !success && !this.wasCanceled)
                    {
                        try
                        {
                            Logger.LogEvent(true, "MainViewModel.SendZip 201.8 connectionIntervalFinished: {0} , \n success: {1} , \n wasCanceled: {2}",
                                connectionIntervalFinished, success, wasCanceled);

                            // connecting
                            bluetoothClient.Connect(ep);

                            Logger.LogEvent(true, "MainViewModel.SendZip 201.9");

                            // get stream for send the data
                            bluetoothStream = bluetoothClient.GetStream();

                            Logger.LogEvent(true, "MainViewModel.SendZip 201.95");

                            // if all is ok to send
                            if (bluetoothClient.Connected && bluetoothStream != null)
                            {
                                this.Status = "Connection is established and ready to send.";
                                // write the data in the stream

                                var fileInfo = new FileInfo(this.lastZipPath);

                                Logger.LogEvent(true, "MainViewModel.SendZip 202");

                                //var buffer = System.Text.Encoding.UTF8.GetBytes();
                                int fileLength;
                                if (int.TryParse(fileInfo.Length.ToString(), out fileLength))
                                {
                                    var sizeBuffer = LastMileHealth.Helpers.Utils.IntToByteArray(fileLength);
                                    //var sizeBuffer = BitConverter.GetBytes(fileLength);

                                    Logger.LogEvent(true, "MainViewModel.SendZip 203 sizeBuffer: {0}", sizeBuffer.Length);

                                    //TODO: CHUNKS! 4096 //BinaryWriter bw = new BinaryWriter(bluetoothStream);
                                    var fileBuffer = System.IO.File.ReadAllBytes(this.lastZipPath);

                                    var buffer = LastMileHealth.Helpers.Utils.Combine(sizeBuffer, fileBuffer);

                                    Logger.LogEvent(true, "MainViewModel.SendZip 204 sizeBuffer: {0}", buffer.Length);

                                    bluetoothStream.Write(buffer, 0, buffer.Length);
                                    //bluetoothStream.Flush();

                                    // TODO: async method StartListen for responce
                                    byte[] receivedIntBytes = new byte[4];
                                    var tst = bluetoothStream.Read(receivedIntBytes, 0, 4);
                                    var receivedInt = LastMileHealth.Helpers.Utils.ByteArrayToInt(receivedIntBytes);

                                    Logger.LogEvent(true, "MainViewModel.SendZip 205 sizeBuffer: {0}", receivedInt);

                                    if (receivedInt == fileLength)
                                    {
                                        success = true;
                                        Logger.LogEvent(true, "MainViewModel.SendZip 206");
                                    }
                                }
                                else
                                {
                                    this.Status = "Too big file!";
                                    MessageBox.Show("Too big file!");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogEvent(true, "MainViewModel.SendZip 207 Exception = {0} , \nStack = {1}", ex.Message, ex.StackTrace);
                            lastEx = ex;
                        }
                        finally
                        {
                            //if (bluetoothClient != null)
                            //{
                            //    //bluetoothStream.Flush();
                            //    //bluetoothStream.Close();

                            //    bluetoothClient.Close();
                            //    bluetoothClient.Dispose();
                            //}
                        }
                    }

                    Logger.LogEvent(true, "MainViewModel.SendZip 208");

                    this.StopTimer(aTimer);
                    //if (bluetoothStream != null)
                    //{
                    //    bluetoothStream.Flush();
                    //    bluetoothStream.Close();
                    //}

                    if (bluetoothClient != null)
                    {
                        Logger.LogEvent(true, "MainViewModel.SendZip 209");

                        bluetoothClient.Close();
                        bluetoothClient.Dispose();
                        bluetoothClient = null;
                    }

                    Logger.LogEvent(true, "MainViewModel.SendZip 210");
                }
            }).ContinueWith(taskState =>
            {
                Logger.LogEvent(true, "MainViewModel.SendZip 211");

                this.IsScanning = false;

                if (success)
                {
                    this.Status = string.Format("File \"{0}\" has been transferred to {1}!", Path.GetFileNameWithoutExtension(this.lastZipPath) + ".lmu", this.selectedDevice.Name);
                    this.ClearAfterSendOrCancel();
                }
                else if (!this.wasCanceled)
                {
                    this.Status = "Form transfering failed.";

                    Logger.LogEvent(true, "MainViewModel.SendZip 212 lastEx: {0}", lastEx == null ? "IsNULL" : "Not NULL");

                    if (lastEx != null)
                    {
                        if (lastEx is SocketException)
                        {
                            var socketEx = (SocketException)lastEx;

                            BluetoothRadio.PrimaryRadio.Mode = RadioMode.PowerOff;

                            if (socketEx.SocketErrorCode == SocketError.AddressNotAvailable || socketEx.SocketErrorCode == SocketError.TimedOut)
                            {
                                MessageBox.Show("Selected bluetooth device is not available. Please press \"App Update\" button on an appropriate device before sending forms.", "Destination device is not reachable.",
                                    MessageBoxButton.OK, MessageBoxImage.Warning);
                            }
                            else if (socketEx.SocketErrorCode == SocketError.InvalidArgument || socketEx.SocketErrorCode == SocketError.Shutdown)
                            {
                                MessageBox.Show("Try one of next solutions:\n- Try to restart the application\n- Unpair devices in settings (for both devices) and pair them again.\n",
                                    "Bluetooth connection problem.", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            else// if (lastEx.Message.Contains("invalid argument was supplied")) // (lastEx as SocketException).SocketErrorCode == SocketError.Shutdown
                            {
                                MessageBox.Show("Try one of next solutions:\n- Try to restart the application;\n- Unpair devices in settings (for both devices) and pair them again;\n- Go to Start > Type services.msc > Services Local > Then scroll down the list till you see 'Bluetooth Support Service' > Right click on it and then Stop the process and then start it up again;\n- Update bluetooth drivers;",
                                    "Bluetooth connection problem.", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }

                        Logger.LogEvent(true, "MainViewModel.SendZip 213");

                        this.AddExceptionToLog(lastEx);
                    }

                    this.SelectedDeviceIndex = -1;
                }

                Logger.LogEvent(true, "MainViewModel.SendZip 214");

            }, TaskScheduler.FromCurrentSynchronizationContext());

            Logger.LogEvent(true, "MainViewModel.SendZip 215");
        }
예제 #21
0
 /// <summary>
 /// Create a client port for connection to a remote device.  Auto allocates a port from the COM0-9 range.
 /// </summary>
 /// <param name="endPoint">Remote device to connect to.</param>
 /// <returns></returns>
 public static BluetoothSerialPort CreateClient(BluetoothEndPoint endPoint)
 {
     BluetoothSerialPort bsp = new BluetoothSerialPort("COM", 9);
     bsp.pep.Local = false;
     bsp.pep.Address = endPoint.Address;
     bsp.pep.Service = endPoint.Service;
     
     for (int iPort = 8; iPort > -1; iPort--)
     {
         try
         {
             bsp.Register();
             break;
         }
         catch
         {
             bsp.portIndex = iPort;
         }
     }
     return bsp;
 }
 /// <summary>
 /// Create a connection for the selected device.
 /// </summary>
 /// <param name="device">The device.</param>
 public void DeviceConnection(Device device)
 {
     if (device == null)
     {
         throw new ArgumentNullException("device");
     }
     var ep = new BluetoothEndPoint(device.DeviceInfo.DeviceAddress, _serviceClassId);
     // connecting
     if (bluetoothClient.Connected == false)
     {
         bluetoothClient.BeginConnect(device.DeviceInfo.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), device);
     }
 }
예제 #23
0
파일: Bluetooth.cs 프로젝트: smo-key/NXTLib
        private void _search()
        {
            if (!IsInitialized) { throw new NXTLinkNotInitialized(); }
            _bricklist = new List<Brick>();
            List<Brick> bricks = new List<Brick>();
            lock (commLock)
            {
                BluetoothDeviceInfo[] peers = client.DiscoverDevicesInRange();

                foreach (BluetoothDeviceInfo info in peers)
                {
                    if (info.ClassOfDevice.Value != 2052) { continue; }

                    BluetoothEndPoint ep = new BluetoothEndPoint(info.DeviceAddress, NXT_GUID);
                    //BluetoothSecurity.SetPin(info.DeviceAddress, "1234");
                    BrickInfo _brick = new BrickInfo();
                    _brick.address = info.DeviceAddress.ToByteArray();
                    _brick.name = info.DeviceName;
                    Brick brick = new Brick(this, _brick);
                    bricks.Add(brick);
                }
            }
            _bricklist = bricks;
            return;
        }
예제 #24
0
파일: OBDSerial.cs 프로젝트: cail/obdgauge
        public void SerialOpen(String portName, BaudRates baud)
        {
            if (portName.StartsWith("COM")){
                BasicPortSettings portSettings = new BasicPortSettings();
                portSettings.BaudRate = baud;
                mPort = new Port(portName+":", portSettings);
                mPort.RThreshold = 1;
                mPort.SThreshold = 1;	// send 1 byte at a time
                mPort.InputLen = 0;
                mPort.Open();
                mPort.DataReceived +=new Port.CommEvent(mPort_DataReceived);
            }else{

                try{
                    BluetoothAddress address = BluetoothAddress.Parse(portName);
                    bluetoothClient = new BluetoothClient();
                    bluetoothClient.SetPin(address, "0000");
                    BluetoothEndPoint btep = new BluetoothEndPoint(address, BluetoothService.SerialPort, 1);
                    bluetoothClient.Connect(btep);
                    stream = bluetoothClient.GetStream();
                    if (stream == null){
                        bluetoothClient.Close();
                        bluetoothClient = null;
                    }else{
                        if (stream.CanTimeout){
                            stream.WriteTimeout = 2;
                            stream.ReadTimeout = 2;
                        }
                    }
                }catch(System.IO.IOException){
                    bluetoothClient = null;
                }

            }
        }
예제 #25
0
        /// <summary>
        /// Returns a list of <see cref="EndPoint"/> corresponding to possible local listeners of the provided
        /// <see cref="ConnectionType"/> with a local EndPoint with matching <see cref="IPAddress"/>.
        /// If no matching listeners exist returns empty list.
        /// </summary>
        /// <param name="connectionType">Connection type to match. Use ConnectionType.Undefined to match all.</param>
        /// <param name="localEndPointToMatch">The <see cref="IPEndPoint"/> to match to local listeners. Use IPAddress.Any
        /// to match all addresses. Use port 0 to match all ports.</param>
        /// <returns></returns>
        public static List <EndPoint> ExistingLocalListenEndPoints(ConnectionType connectionType, EndPoint localEndPointToMatch)
        {
            if (connectionType == ConnectionType.Undefined)
            {
                throw new ArgumentException("ConnectionType.Undefined may not be used with this override. Please see others.", "connectionType");
            }
            if (localEndPointToMatch == null)
            {
                throw new ArgumentNullException("localEndPointToMatch");
            }

#if NET4 || NET35
            if (connectionType == ConnectionType.Bluetooth)
            {
                InTheHand.Net.BluetoothEndPoint btEndPointToMatch = localEndPointToMatch as InTheHand.Net.BluetoothEndPoint;

                if (btEndPointToMatch == null)
                {
                    throw new ArgumentException("Local endpoint must be a BluetoothEndPoint for Bluetooth connection type", "localEndPointToMatch");
                }

                List <EndPoint> btResult = new List <EndPoint>();
                lock (staticConnectionLocker)
                {
                    if (listenersDict.ContainsKey(connectionType))
                    {
                        foreach (EndPoint endPoint in listenersDict[connectionType].Keys)
                        {
                            var btEndPoint = endPoint as InTheHand.Net.BluetoothEndPoint;
                            if (btEndPointToMatch.Address == BluetoothAddress.None && btEndPointToMatch.Service == BluetoothService.Empty)
                            {
                                btResult.Add(btEndPoint);
                            }
                            else if (btEndPointToMatch.Address != BluetoothAddress.None && btEndPointToMatch.Service == BluetoothService.Empty)
                            {
                                //Match the address
                                if (btEndPoint.Address.Equals(btEndPointToMatch.Address) &&
                                    listenersDict[connectionType][btEndPoint].IsListening)
                                {
                                    btResult.Add(btEndPoint);
                                }
                            }
                            else if (btEndPointToMatch.Address == BluetoothAddress.None && btEndPointToMatch.Service != BluetoothService.Empty)
                            {
                                //Match the service
                                if (btEndPoint.Service.Equals(btEndPointToMatch.Service) &&
                                    listenersDict[connectionType][btEndPoint].IsListening)
                                {
                                    btResult.Add(btEndPoint);
                                }
                            }
                            else if (endPoint.Equals(localEndPointToMatch) && listenersDict[connectionType][endPoint].IsListening)
                            {
                                btResult.Add(endPoint);
                                break;
                            }
                        }
                    }
                }

                return(btResult);
            }
#endif

            IPEndPoint ipEndPointToMatch = localEndPointToMatch as IPEndPoint;

            List <EndPoint> result = new List <EndPoint>();
            lock (staticConnectionLocker)
            {
                if (listenersDict.ContainsKey(connectionType))
                {
                    foreach (EndPoint endPoint in listenersDict[connectionType].Keys)
                    {
                        IPEndPoint ipEndPoint = endPoint as IPEndPoint;
                        if (ipEndPointToMatch != null && (ipEndPointToMatch.Address == IPAddress.Any || ipEndPointToMatch.Address == IPAddress.IPv6Any) && ipEndPointToMatch.Port == 0)
                        {
                            //Add if listening
                            if (listenersDict[connectionType][ipEndPoint].IsListening)
                            {
                                result.Add(ipEndPoint);
                            }
                        }
                        else if (ipEndPointToMatch != null && !(ipEndPointToMatch.Address == IPAddress.Any || ipEndPointToMatch.Address == IPAddress.IPv6Any) && ipEndPointToMatch.Port == 0)
                        {
                            //Match the IP Address
                            if (ipEndPoint.Address.Equals(ipEndPointToMatch.Address) &&
                                listenersDict[connectionType][ipEndPoint].IsListening)
                            {
                                result.Add(ipEndPoint);
                            }
                        }
                        else if (ipEndPointToMatch != null && (ipEndPointToMatch.Address == IPAddress.Any || ipEndPointToMatch.Address == IPAddress.IPv6Any) && ipEndPointToMatch.Port > 0)
                        {
                            //Match the port
                            if (ipEndPoint.Port == ipEndPointToMatch.Port &&
                                listenersDict[connectionType][ipEndPoint].IsListening)
                            {
                                result.Add(ipEndPoint);
                            }
                        }
                        else if (endPoint.Equals(localEndPointToMatch) && listenersDict[connectionType][endPoint].IsListening)
                        {
                            result.Add(endPoint);
                            break;
                        }
                    }
                }
            }

            return(result);
        }
        private void init(String macAddress)
        {
            isPaired = false;
            isScanDone = false;
            isConnected = false;
            isSlave = true;
            stop = false;
            robots = new List<BluetoothDeviceInfo>();

            //Bind de la carte bluetooth
            try
            {
                localEndpoint = new BluetoothEndPoint(BluetoothAddress.Parse(macAddress), BluetoothService.SerialPort);
                localClient = new BluetoothClient(localEndpoint);
                localComponent = new BluetoothComponent(localClient);
            }

            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            localComponent.DiscoverDevicesProgress += new EventHandler<DiscoverDevicesEventArgs>(component_DiscoverDevicesProgress);
            localComponent.DiscoverDevicesComplete += new EventHandler<DiscoverDevicesEventArgs>(component_DiscoverDevicesComplete);
        }
예제 #27
0
        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();
        }
예제 #28
0
		/// <summary>
		/// Create a client port for connection to a remote device.
		/// </summary>
		/// <param name="portPrefix">Port name e.g. "COM4"</param>
		/// <param name="endPoint">Remote device to connect to</param>
		/// <returns>A BluetoothSerialPort.</returns>
		public static BluetoothSerialPort CreateClient(string portName, BluetoothEndPoint endPoint)
		{
            string portPrefix;
            int portIndex;
            SplitPortName(portName, out portPrefix, out portIndex);
			BluetoothSerialPort bsp = new BluetoothSerialPort(portPrefix, portIndex);
			bsp.pep.Local = false;
			bsp.pep.Address = endPoint.Address;
			bsp.pep.Service = endPoint.Service;

            bsp.Register();

			return bsp;
		}
        /// <summary>
        /// Sends the data to the Receiver.
        /// </summary>
        /// <param name="device">The device.</param>
        /// <param name="content">The content.</param>
        /// <returns>If was sent or not.</returns>
        public async Task<bool> Send(Device device, string content)
        {
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }

            if (string.IsNullOrEmpty(content))
            {
                throw new ArgumentNullException("content");
            }

            // for not block the UI it will run in a different threat
            var task = Task.Run(() =>
            {
                using (var bluetoothClient = new BluetoothClient())
                {
                    try
                    {
                        BluetoothRadio myRadio = BluetoothRadio.PrimaryRadio;
                        if (myRadio == null)
                        {
                            Console.WriteLine("No radio hardware or unsupported software stack");
                            //return;
                        }
                        RadioMode mode = myRadio.Mode;
                        // Warning: LocalAddress is null if the radio is powered-off.
                        Console.WriteLine("* Radio, address: {0:C}", myRadio.LocalAddress);

                        // mac is mac address of local bluetooth device
                        BluetoothEndPoint localEndpoint = new BluetoothEndPoint(myRadio.LocalAddress, BluetoothService.SerialPort);
                        // client is used to manage connections
                        BluetoothClient localClient = new BluetoothClient(localEndpoint);
                        // component is used to manage device discovery
                        BluetoothComponent localComponent = new BluetoothComponent(localClient);

                        var ep = new BluetoothEndPoint(device.DeviceInfo.DeviceAddress, _serviceClassId);

                        // get stream for send the data
                        var bluetoothStream = bluetoothClient.GetStream();

                        // if all is ok to send
                        if (bluetoothClient.Connected && bluetoothStream != null)
                        {
                            // write the data in the stream
                            var buffer = System.Text.Encoding.UTF8.GetBytes(content);
                            bluetoothStream.Write(buffer, 0, buffer.Length);
                            bluetoothStream.Flush();
                            bluetoothStream.Close();
                            return true;
                        }
                        return false;
                    }
                    catch
                    {
                        // the error will be ignored and the send data will report as not sent
                        // for understood the type of the error, handle the exception
                    }
                }
                return false;
            });

            return await task;
        }
예제 #30
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;
                            IrDAAddress ia;
                            if(BluetoothAddress.TryParse(uri.Host,out ba))
                            {
                                s = new Socket(AddressFamily32.Bluetooth, SocketType.Stream, BluetoothProtocolType.RFComm);
                                Guid serviceGuid;

                                switch (uri.Scheme)
                                {
                                    case "obex-ftp":
                                        serviceGuid = BluetoothService.ObexFileTransfer;
                                        break;
                                    //potential for other obex based profiles to be added
                                    case "obex-sync":
                                        serviceGuid = BluetoothService.IrMCSyncCommand;
                                        break;
                                    default:
                                        serviceGuid = BluetoothService.ObexObjectPush;
                                        break;
                                }


                                BluetoothEndPoint bep = new BluetoothEndPoint(ba, serviceGuid);
                                s.Connect(bep);
                            }
                            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);
                            }
                     
                            ns = new NetworkStream(s, true);

#if V2 && WinXP
                            ns.ReadTimeout = timeout;
                            ns.WriteTimeout = timeout;
#endif
                        }

                        //do obex negotiation
                        byte[] connectPacket;
                        if (uri.Scheme == "obex-ftp")
                        {
                            connectPacket = new byte[] { 0x80, 0x00, 26, 0x10, 0x00, 0x20, 0x00, 0x46, 0x00, 19, 0xF9, 0xEC, 0x7B, 0xC4, 0x95, 0x3C, 0x11, 0xD2, 0x98, 0x4E, 0x52, 0x54, 0x00, 0xDC, 0x9E, 0x09 };
                        }
                        else
                        {
                            connectPacket = new byte[7] { 0x80, 0x00, 0x07, 0x10, 0x00, 0x20, 0x00 };
                        }
                        ns.Write(connectPacket, 0, connectPacket.Length);

                        byte[] receivePacket = new byte[3];

                        int bytesReceived = ns.Read(receivePacket, 0, 3);
                        
                        //failure
                        if (bytesReceived == 0)
                        {
                            throw new Exception("Connection Lost");
                        }

                        while (bytesReceived < 3)
                        {
                            bytesReceived += ns.Read(receivePacket, bytesReceived, 3 - bytesReceived);
                        }
                        if (receivePacket[0] == (byte)(ObexStatusCode.OK | ObexStatusCode.Final))
                        {
                            //get length
                            short len = (short)(IPAddress.NetworkToHostOrder(BitConverter.ToInt16(receivePacket, 1)) - 3);

                            byte[] receivePacket2 = new byte[3+len];
                            Buffer.BlockCopy(receivePacket, 0, receivePacket2, 0, 3);
                            int nextReceived = ns.Read(receivePacket2, 3, len);
                            if(nextReceived == 0)
                            {
                                throw new Exception("Connection Lost");
                            }
                            bytesReceived += nextReceived;
                            while (bytesReceived < len+3)
                            {
                                bytesReceived += ns.Read(receivePacket2, 3+bytesReceived, len - bytesReceived);
                            }
                            ObexParser.ParseHeaders(receivePacket2, ref remoteMaxPacket, null, headers);

                            if (headers["CONNECTIONID"] != null)
                            {
                                connectionId = int.Parse(headers["CONNECTIONID"]);
                            }
                            //ParseHeaders(receivePacket2, headers, null);
                        }
                        
                        return (ObexStatusCode)receivePacket[0];

                    }
					finally
					{
						if (s != null && !s.Connected)
						{
							s = null;
						}
					}
				}
			}
			return (ObexStatusCode)0;
		}
예제 #31
-2
 public void connectBluetoothDevice(BluetoothClient bc, BluetoothAddress addr, Guid serviceClass)
 {
     try
     {
         var ep = new BluetoothEndPoint(addr, serviceClass);
         bc.Connect(ep);
     }
     catch (SocketException ex)
     {
         // Try to give a explanation reason by checking what error-code.
         // http://32feet.codeplex.com/wikipage?title=Errors
         // Note the error codes used on MSFT+WM are not the same as on
         // MSFT+Win32 so don't expect much there, we try to use the
         // same error codes on the other platforms where possible.
         // e.g. Widcomm doesn't match well, Bluetopia does.
         // http://32feet.codeplex.com/wikipage?title=Feature%20support%20table
         string reason;
         switch (ex.ErrorCode)
         {
             case 10048: // SocketError.AddressAlreadyInUse
                 // RFCOMM only allow _one_ connection to a remote service from each device.
                 reason = "There is an existing connection to the remote Chat2 Service";
                 break;
             case 10049: // SocketError.AddressNotAvailable
                 reason = "Chat2 Service not running on remote device";
                 break;
             case 10064: // SocketError.HostDown
                 reason = "Chat2 Service not using RFCOMM (huh!!!)";
                 break;
             case 10013: // SocketError.AccessDenied:
                 reason = "Authentication required";
                 break;
             case 10060: // SocketError.TimedOut:
                 reason = "Timed-out";
                 break;
             default:
                 reason = null;
                 break;
         }
         reason += " (" + ex.ErrorCode.ToString() + ") -- ";
         //
         var msg = "Bluetooth connection failed: " + ex.Message;
         msg = reason + msg;
         msg += "Attempting to reconnect ....";
         log.dispatchLogMessage(msg);
         //MessageBox.Show(msg);
     }
     var mssg = "Bluetooh connection established with a PROTAG device ";
     log.dispatchLogMessage(mssg);
 }