private void BluetoothConnect(BluetoothAddress addr)
 {
     BluetoothClient btClient = new BluetoothClient();
       try
       {
     btClient.Connect(addr, OurServiceClassId);
     var peer = btClient.GetStream();
     SetConnection(peer, true, btClient.RemoteEndPoint);
     ThreadPool.QueueUserWorkItem(ReadMessagesToEnd_Runner, peer);
       }
       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;
     msg = reason + msg;
     AddMessage(MessageSource.Error, msg);
     System.Windows.MessageBox.Show(msg);
       }
       catch (Exception ex)
       {
     var msg = "Bluetooth connection failed: " + ex;
     AddMessage(MessageSource.Error, msg);
     System.Windows.MessageBox.Show(msg);
       }
 }
Exemplo n.º 2
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;
            }
        }
Exemplo n.º 3
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());
            }
        }
        public static void MakeConnection(BluetoothAddress btAddress)
        {
            var serviceClass = BluetoothService.SerialPort;
            if (_cli != null)
            {
                _cli.Close();
            }

            _cli = new BluetoothClient();
            var bluetoothDeviceInfos = _cli.DiscoverDevices();
            var deviceInfos = bluetoothDeviceInfos.ToList();
            BluetoothDeviceInfo device = null;
            foreach (var bluetoothDeviceInfo in deviceInfos)
            {
                var scannedDeviceAddress = bluetoothDeviceInfo.DeviceAddress;

                if (scannedDeviceAddress == btAddress)
                {
                    device = bluetoothDeviceInfo;
                }
            }

            if (device == null)
            {
                return;
            }

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

            try
            {
                if (!device.Connected)
                {
                    _cli.Connect(ep);
                }
            }
            catch(System.Net.Sockets.SocketException e)
            {
                _cli.Close();
                _isConnected = false;
                return;
            }

            _isConnected = true;
        }
Exemplo n.º 5
1
        public static ObexStatusCode SendFile(BluetoothAddress address, string file_path)
        {
            
            Uri uri = new Uri("obex://" + address.ToString() + "/" + file_path);
            ObexWebResponse response;
            try
            {
                ObexWebRequest request = new ObexWebRequest(uri);
                request.ReadFile(file_path);
                response = (ObexWebResponse)request.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                return ObexStatusCode.InternalServerError;
            }

            return response.StatusCode;
        }
 private void OnNfc(object sender, RoutedEventArgs e)
 {
     BluetoothAddress btAddress = new BluetoothAddress(new byte[]{252, 27, 32, 49, 211, 152, 0, 0});
     BluetoothHandler.MakeConnection(btAddress);
     bluetoothIndicator.Fill = !BluetoothHandler.IsConnected() ? new SolidColorBrush( Colors.Red) : new SolidColorBrush(Colors.Green);
 }
        private void OnLaser(object sender, RoutedEventArgs e)
        {
            BluetoothAddress btAddress = new BluetoothAddress(new byte[] { 17, 71, 48, 49, 211, 152, 0, 0 });
            BluetoothHandler.MakeConnection(btAddress);

            if (!BluetoothHandler.IsConnected())
            {
                bluetoothIndicator.Fill = new SolidColorBrush(Colors.Red);
            }
            else
            {
                bluetoothIndicator.Fill = new SolidColorBrush(Colors.Green);
            }
        }
Exemplo n.º 8
1
 internal BluetoothDevice(BluetoothAddress ba)
 {
     bdi = new BluetoothDeviceInfo(ba);
 }
Exemplo n.º 9
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);
            }
        }
Exemplo n.º 10
1
        /// <summary>
        /// Hook into the native message loop for the application to process WM_DEVICECHANGE messages.
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="msg"></param>
        /// <param name="wParam"></param>
        /// <param name="lParam"></param>
        /// <param name="handled"></param>
        /// <returns></returns>
        IntPtr HwndBluetoothHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            // Handle async notifications from the Bluetooth radio here
            if (msg == WM_DEVICECHANGE)
            {
                BluetoothMonitor.DEV_BROADCAST_HANDLE dbh = (BluetoothMonitor.DEV_BROADCAST_HANDLE)Marshal.PtrToStructure(lParam, typeof(BluetoothMonitor.DEV_BROADCAST_HANDLE));
                IntPtr offset = new IntPtr(lParam.ToInt32() + 40);

                if (dbh.dbch_eventguid == BluetoothMonitor.GUID_BLUETOOTH_RADIO_IN_RANGE)
                {

                    BTH_RADIO_IN_RANGE rir = (BTH_RADIO_IN_RANGE)Marshal.PtrToStructure(offset, typeof(BTH_RADIO_IN_RANGE));

                    BluetoothDevice bd = new BluetoothDevice(new InTheHand.Net.BluetoothAddress(rir.deviceInfo.address));

                    // Item is newly discovered - should not exist but check just in case
                    if (!devices.Contains(bd))
                    {
                        DeviceClass dc = (DeviceClass)(rir.deviceInfo.classOfDevice & 0x001ffc);
                        ServiceClass sc = (ServiceClass)(rir.deviceInfo.classOfDevice >> 13);
                        // Either the device advertises support for object transfer or is a smart phone
                        // The latter may introduce false positives for devices which don't support OBEX but is necessary because android supports OBEX but doesn't include the relevant ServiceClass flag.
                        if (((sc & ServiceClass.ObjectTransfer) == ServiceClass.ObjectTransfer) || ((dc & DeviceClass.SmartPhone) == DeviceClass.SmartPhone))
                        {
                            System.Diagnostics.Debug.Write("Radio In Range");
                            System.Diagnostics.Debug.WriteLine(" " + rir.deviceInfo.address.ToString("X"));
                            System.Diagnostics.Debug.WriteLine("Flags " + rir.deviceInfo.flags.ToString());

                            devices.Add(bd);

                            if (deviceArrived != null)
                            {
                                System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(OnDeviceArrived), new InTheHand.Net.Sockets.BluetoothDeviceInfo(new InTheHand.Net.BluetoothAddress(rir.deviceInfo.address)));
                            }
                        }
                    }
                    else
                    {
                        // Only act if this event indicates a change
                        // New devices will have previousDeviceFlags = 0
                        // Other cases can include adding the BDIF_NAME flag when a remote name is queried
                        if (rir.previousDeviceFlags != rir.deviceInfo.flags)
                        {
                            System.Diagnostics.Debug.Write("Radio Updated");
                            System.Diagnostics.Debug.WriteLine(" " + rir.deviceInfo.address.ToString("X"));
                            System.Diagnostics.Debug.WriteLine("New Flags " + (rir.deviceInfo.flags ^ rir.previousDeviceFlags).ToString());

                            // Item is updated - refresh the information
                            devices[devices.IndexOf(bd)].Refresh(rir.deviceInfo.flags ^ rir.previousDeviceFlags);
                        }
                    }
                }
                else if (dbh.dbch_eventguid == BluetoothMonitor.GUID_BLUETOOTH_RADIO_OUT_OF_RANGE)
                {
                    // Read the numeric Bluetooth address.
                    long addr = System.Runtime.InteropServices.Marshal.ReadInt64(offset);
                    InTheHand.Net.BluetoothAddress ba = new InTheHand.Net.BluetoothAddress(addr);
                    // Get device information
                    BluetoothDevice bd = new BluetoothDevice(ba);

                    System.Diagnostics.Debug.Write("Radio Out Of Range");
                    System.Diagnostics.Debug.WriteLine(" " + addr.ToString("X"));

                    if (devices.Contains(bd))
                    {
                        // Handles device going out of range
                        // Remove device pairing if present
                        if (bd.Authenticated)
                        {
                            BluetoothSecurity.RemoveDevice(bd.DeviceAddress);
                        }
                        devices.Remove(bd);
                    }

                    if (deviceLeft != null)
                    {
                        System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(OnDeviceLeft), new InTheHand.Net.Sockets.BluetoothDeviceInfo(ba));
                    }
                }

            }

            handled = false;
            return IntPtr.Zero;
        }
Exemplo n.º 11
1
        /// <summary>
		/// Initializes a new instance of the <see cref="BluetoothEndPoint"/> class with the specified address and service.
		/// </summary>
		/// <param name="address">The Bluetooth address of the device. A six byte array.</param>
		/// <param name="service">The Bluetooth service to use.</param>
		public BluetoothEndPoint(BluetoothAddress address, Guid service) : this(address, service, defaultPort)
		{
		}
Exemplo n.º 12
0
		/// <summary>
		/// Initializes a new instance of the <see cref="BluetoothEndPoint"/> class with the specified address, service and port number.
		/// </summary>
		/// <param name="address">The Bluetooth address of the device. A six byte array.</param>
		/// <param name="service">The Bluetooth service to use.</param>
		/// <param name="port">Radio channel to use, -1 for any.</param>
		public BluetoothEndPoint(BluetoothAddress address, Guid service, int port)
		{
			
			m_id = address;
			m_service = service;
			m_port = port;
        }
Exemplo n.º 13
0
 public static string FormatBtAddress(string s, BluetoothAddress btA, string format)
 {
     if (s != null && (s.Length == 12 || s.Length == 17))
     {
         try
         {
             return BluetoothAddress.Parse(s).ToString(format).ToLower();
         }
         catch
         {
             DebugLog.write("BTUtils.BtAddress Failed on " + s);
             return "";
         }
     }
     else if (btA != null)
     {
         try
         {
             return btA.ToString(format).ToLower();
         }
         catch
         {
             DebugLog.write("BTUtils.BtAddress Failed with unknown btA");
             return "";
         }
     }
     else
     {
         DebugLog.write("BTUtils.BtAddress : Invalid Parameters");
         return "";
     }
 }
        public Client()
        {
            UUID = new Guid("00000000-0000-0000-0000-000000000000");
                    PIN = "1234";

            bluetoothAddress = getMacAddress();
        }
Exemplo n.º 15
0
        public static ObexStatusCode SendFile(BluetoothAddress address, string file_path)
        {
            string FileName = file_path.Substring(file_path.LastIndexOf("\\"));
            Uri uri = new Uri("obex://" + address.ToString() + "/" + file_path);

            ObexWebRequest request = new ObexWebRequest(uri);
            request.ReadFile(file_path);
            ObexWebResponse response = (ObexWebResponse)request.GetResponse();
            response.Close();

            return response.StatusCode;
        }
 private void buttonSelectBluetooth_Click(object sender, EventArgs e)//选择远程蓝牙设备
 {
     InTheHand.Windows.Forms.SelectBluetoothDeviceDialog dialog = new InTheHand.Windows.Forms.SelectBluetoothDeviceDialog();
     dialog.ShowRemembered    = true; //显示已经记住的蓝牙设备
     dialog.ShowAuthenticated = true; //显示认证过的蓝牙设备
     dialog.ShowUnknown       = true; //显示位置蓝牙设备
     if (dialog.ShowDialog() == DialogResult.OK)
     {
         sendAddress       = dialog.SelectedDevice.DeviceAddress;//获取选择的远程蓝牙地址
         labelAddress.Text = "地址:" + sendAddress.ToString() + "  设备名:" + dialog.SelectedDevice.DeviceName;
     }
 }
        public IstemciDinleyici(BluetoothClient istemci, AnaPencere pencere)
        {
            this.istemci = istemci;
            this.anaPencere = pencere;

            istemciAdi = this.istemci.RemoteMachineName;
            istemciAdresi = ((BluetoothEndPoint)(this.istemci.Client.RemoteEndPoint)).Address; // :D

            anaPencere.SunucuUyariGoster("Ýstemci baðlandý: " + istemciAdi);

            istemciKanali = new Thread(new ThreadStart(Kanal));
            istemciKanali.Start();
        }
Exemplo n.º 18
0
        private void sendfile()
        {
            int index = selected;

            InTheHand.Net.BluetoothAddress address = devices[index].DeviceAddress;
            System.Uri     uri     = new Uri("obex://" + address.ToString() + "/" + "sample.txt"); //Change it to your file name
            ObexWebRequest request = new ObexWebRequest(uri);

            request.ReadFile("c:\\users\\chinmay\\sample.txt"); // Chnage it to your File Path
            ObexWebResponse response = (ObexWebResponse)request.GetResponse();

            response.Close();
        }
Exemplo n.º 19
0
        /// <summary>
        /// Converts the string representation of an address to it's <see cref="BluetoothAddress"/> equivalent.
        /// A return value indicates whether the operation succeeded.
        /// </summary>
        /// <param name="s">A string containing an address to convert.</param>
        /// <param name="result">When this method returns, contains the <see cref="BluetoothAddress"/> equivalent to the address contained in s, if the conversion succeeded, or null (Nothing in Visual Basic) if the conversion failed.
        /// The conversion fails if the s parameter is null or is not of the correct format.</param>
        /// <returns>true if s is a valid Bluetooth address; otherwise, false.</returns>
        public static bool TryParse(string s, out BluetoothAddress result)
        {

            try
            {
                result = Parse(s);
                return true;
            }
            catch
            {
                result = null;
                return false;
            }
        }
Exemplo n.º 20
0
        /* These properties are not needed . They may be enabled later if needed . 
        public bool Authenticated { get; set; }
        public bool Connected { get; set; }
        public ushort Nap { get; set; }
        public uint Sap { get; set; }
        public DateTime LastSeen { get; set; }
        public DateTime LastUsed { get; set; }
        public bool Remembered { get; set; }
         */

        public Device(BluetoothDeviceInfo device_info)
        {

            this.DeviceName = device_info.DeviceName;
            this.DeviceAddress = device_info.DeviceAddress;

            /* These properties are not needed . They may be enabled later if needed . 
            this.Authenticated = device_info.Authenticated;
            this.Connected = device_info.Connected;
            this.LastSeen = device_info.LastSeen;
            this.LastUsed = device_info.LastUsed;
            this.Nap = device_info.DeviceAddress.Nap;
            this.Sap = device_info.DeviceAddress.Sap;
            this.Remembered = device_info.Remembered;
             */
        }
        private void sendfile()
        {
            var filepath = FileDialogue();

            foreach (var x in filepath)
            {
                string filename = Path.GetFileName(x);
                int    index    = Selected;
                InTheHand.Net.BluetoothAddress address = this.address_array[index];
                System.Uri     uri     = new Uri("obex://" + address.ToString() + "/" + filename);
                ObexWebRequest request = new ObexWebRequest(uri);
                request.ReadFile(x);
                ObexWebResponse response = (ObexWebResponse)request.GetResponse();
                response.Close();
            }
        }
        public void PairDevice()
        {
            BluetoothClient client = new BluetoothClient();

            BluetoothDeviceInfo[] devices = client.DiscoverDevices();

            InTheHand.Net.BluetoothAddress address = this.address_array[this.lstDevices.SelectedIndex];
            foreach (BluetoothDeviceInfo Device in devices)
            {
                if (Device.DeviceAddress.Equals(address)) // item from ComboBox
                {
                    bool paired = BluetoothSecurity.PairRequest(Device.DeviceAddress, "123456");
                    if (paired)
                    {
                        MessageBox.Show("Paired!");
                    }
                    else
                    {
                        MessageBox.Show("There was a problem pairing.");
                    }
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="BluetoothEndPoint"/> class with the specified address and service.
 /// </summary>
 /// <param name="address">The Bluetooth address of the device. A six byte array.</param>
 /// <param name="service">The Bluetooth service to use.</param>
 public BluetoothEndPoint(BluetoothAddress address, Guid service)
     : this(address, service, defaultPort)
 {
 }
Exemplo n.º 24
0
 public void IstemciSayisiAzalt(BluetoothAddress istemciAdresi, String istemciAdi) 
 {
     int index = IstemciAdresleri.IndexOf(istemciAdresi);
     IstemciAdresleri.Remove(istemciAdresi);
     IstemciCikar(index);
     IstemciSayisiGoster("Sunucuya Baðlý Ýstemciler: " + IstemciAdresleri.Count);
     SunucuUyariGoster(istemciAdi + " ile baðlantý sona erdi.");
 }
Exemplo n.º 25
-1
 public void AdresEkle(BluetoothAddress adres)
 {
     try
     {
         SunucuAdresleri.Add(adres);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
 }
Exemplo n.º 26
-1
        /// <summary> 
        /// Connect to the device via Bluetooth.
        /// </summary>
        public override void Connect(Brick brick)
        {
            Initialize();
            if (!IsConnected)
            {
                lock (commLock)
                {
                    BluetoothAddress adr = new BluetoothAddress(brick.brickinfo.address);
                    BluetoothDeviceInfo device = new BluetoothDeviceInfo(adr);
                    BluetoothSecurity.PairRequest(adr, "1234");

                    client.Connect(adr, NXT_GUID);

                    //BluetoothSecurity.RevokePin(adr);
                    //BluetoothSecurity.RemoveDevice(adr);

                }
                if (!IsConnected) { throw new NXTNotConnected(); }
            }
            return;
        }
Exemplo n.º 27
-1
        /// <summary>
        /// Send Members profile to another bluetooth device
        /// </summary>
        /// <param name="address">The address object for the remote Member</param>
        /// <param name="gotTheirProfile">1 if this Member has the remote Members profile</param>
		private void SendBluetoothProfile(BluetoothAddress address, int gotTheirProfile)
		{		
			try
			{
                // Create a BluetoothClient object
				BluetoothClient btSend = new BluetoothClient();

                // Connect to the remote member with the serviceGUID for service identification
				btSend.Connect(new BluetoothEndPoint(address, serviceGUID)); 

                // get the stream from the connetion
				System.IO.Stream s = btSend.GetStream();

                // serialise the this Members profile into a string
				string header = "";

				header += this.MajorVersion+",";
				header += this.MinorVersion+",";
				header += Member.Age+",";
				header += ((int)Member.Gender).ToString()+",";
				header += Member.SeekAge+",";
				header += ((int)Member.SeekGender).ToString()+",";
				header += MainForm.member.MemberID+",";
				header += this.MACAddress+",";
				header += gotTheirProfile.ToString();

                // convert the header string into a byte array for transmission
				byte[] bs = System.Text.Encoding.Unicode.GetBytes(header);

                // write the byte array to the steam object
				s.Write(bs, 0, bs.Length);

                // Flush the buffer and transmit the profile
				s.Flush();

                // close the BluetoothClient connection
				btSend.Close();

			}
			catch(Exception ex)
			{
                throw ex;
			}
		}
        public override void send_file(String devicename, String bluid, int not)
        {
            try
            {
                _stopwatch.Start();

                _bluetooth_client = new BluetoothClient();

                BluetoothDeviceInfo[] devinfos = _bluetooth_client.DiscoverDevices();

                foreach (var device in devinfos)
                {
                    if (device.DeviceName == devicename)
                    {
                        _bluetooth_address = device.DeviceAddress;
                        break;
                    }
                }

                _bluetooth_guid = Guid.Parse(bluid);

                _bluetooth_client.Connect(_bluetooth_address, _bluetooth_guid);

                _netstream = _bluetooth_client.GetStream();

                byte[] dataToSend = File.ReadAllBytes(this.filepath);

                _netstream.Write(dataToSend, 0, dataToSend.Length);
                _netstream.Flush();

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

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

                _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);

                _stopwatch.Stop();
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, devicename);
            }
        }
Exemplo n.º 29
-2
        public Mesajlasma(BluetoothAddress adres, AnaPencere pencere, String ad)
        {
            this.sunucuAdresi = adres;
            this.anaPencere = pencere;
            this.sunucuAdi = ad;

            servisAdi = new Guid(Sabitler.SERVIS_GUID); // Sunucu servisi.

            try
            {
                baglantiKanali = new Thread(new ThreadStart(Baglan));
                baglantiKanali.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 30
-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);
 }
Exemplo n.º 31
-2
        /*
        private static void readingLoop()
        {
            List<BluetoothStream> streamsToRemove = new List<BluetoothStream>();
            while (true)
            {

                foreach (BluetoothStream stream in openStreams)
                {
                    if (usingWidcomm)
                    {
                        //TODO FIXME
                    }
                    else
                    {
                        if (stream.btClient.Connected)
                        {
                            int bytesReceived;
                            try
                            {
                                bytesReceived = stream.btSocket.Receive(stream.singleReadBuffer);
                            }
                            catch (Exception e)
                            {
                                throw e;
                            }

                            //this is a timeout. If we get too many of them, we classify that
                            //as a socket that has been disconnected
                            if (bytesReceived == 0)
                            {
                                List<DateTime> newTimeouts = stream.timeoutTimestamps.FindAll(oldEnoughPredicate);
                                newTimeouts.Add(DateTime.Now);
                                if (newTimeouts.Count > MAX_TIMEOUTS)
                                {
                                    stream.socketDead = true;
                                    streamsToRemove.Add(stream);
                                }
                                stream.timeoutTimestamps = newTimeouts;
                            }

                            lock (stream)
                            {
                                int currentBytes = stream.tail - stream.head;
                                if (currentBytes < 0)
                                    currentBytes = DEFAULT_BUFFER_SIZE + currentBytes;
                                int ii;
                                for (ii = 0; ii < bytesReceived && ii < (DEFAULT_BUFFER_SIZE - currentBytes); ii++)
                                {
                                    stream.localBuffer[stream.tail++] = stream.singleReadBuffer[ii];
                                    stream.tail %= DEFAULT_BUFFER_SIZE;
                                }
                                if (ii == DEFAULT_BUFFER_SIZE - currentBytes && ii < bytesReceived)
                                {
                                    while (ii < bytesReceived)
                                    {
                                        stream.localBuffer[stream.tail++] = stream.singleReadBuffer[ii++];
                                        stream.head++;
                                        stream.tail %= DEFAULT_BUFFER_SIZE;
                                        stream.head %= DEFAULT_BUFFER_SIZE;
                                    }
                                    stream.head++;
                                    stream.head %= DEFAULT_BUFFER_SIZE;
                                }
                            }
                        }
                    }
                    
                }

                foreach (BluetoothStream stream in streamsToRemove)
                {
                    openStreams.Remove(stream);
                }
                streamsToRemove.Clear();

            }
        }
        */

        /// <summary>
        /// Opens a Bluetooth connection with the specified address and returns
        /// a BluetoothStream object which can be used to communicate over that
        /// connection
        /// </summary>
        /// <param name="addr">The MAC address of the remote bluetooth device. 
        /// It <b>MUST</b> be in most-significant-byte first
        /// order (i.e. the bluetooth address 00:f1:ad:34:3d:f3 would be
        /// { 0x00, 0xf1, ...} and NOT {0xf3, 0x3d, ...})</param>
        /// <param name="pin">An optional pin for the bluetooth device</param>
        /// <returns></returns>
        public static BluetoothStream OpenConnection(byte[] addr, string pin)
        {
            BluetoothStream newStream = new BluetoothStream();
            try
            {
                if (usingWidcomm)
                {
                    bool canStart = initializeWidcommBluetooth();
                    if (!canStart)
                        throw new Exception("Couldn't instantiate the Widcomm object in C++");
                    IntPtr stringPtr = prepareCOMportWidcomm(addr);
                    if (stringPtr != IntPtr.Zero)
                        newStream.comPortName = Marshal.PtrToStringUni(stringPtr);
                    else
                        throw new Exception("Got a null pointer from the WIDCOMM code");

                    //now open the port
                    newStream.comPort = new SerialPort(newStream.comPortName);
                    newStream.comPort.Open();
                }
                else
                {
                    newStream.btClient = new BluetoothClient();
                    byte[] reverseAddr = new byte[addr.Length];
                    for (int ii = 0; ii < addr.Length; ii++)
                    {
                        reverseAddr[reverseAddr.Length - 1 - ii] = addr[ii];
                    }

                    newStream.timeoutTimestamps = new List<DateTime>();
                    newStream.localBuffer = new byte[DEFAULT_BUFFER_SIZE];
                    newStream.singleReadBuffer = new byte[DEFAULT_BUFFER_SIZE];
                    lock (lockObject)
                    {
                        BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
                        BluetoothAddress bt_addr = new BluetoothAddress(reverseAddr);
                        if (pin != null)
                            BluetoothSecurity.SetPin(bt_addr, pin);

                        newStream.btClient.Connect(bt_addr, BluetoothService.SerialPort);
                        newStream.btSocket = newStream.btClient.Client;
                        newStream.btSocket.Blocking = true;

                    }
                }

               // if (newStream.readingThread != null)
               //     newStream.readingThread.Abort();
               // newStream.readingThread = new Thread(new ThreadStart(newStream.readingFunction));
                //newStream.readingThread.Start();
            }
            catch
            {
                newStream.disposed = true;
                throw;
            }
            return newStream;
        }
Exemplo n.º 32
-2
 // Constructor
 public ObexBluetoothDevice(BluetoothDeviceInfo info)
 {
     this.name = info.DeviceName;
     this.address = info.DeviceAddress;
 }
Exemplo n.º 33
-2
 public void IstemciSayisiArtir(String istemciAdi, BluetoothAddress istemciAdresi) 
 {
     IstemciAdresleri.Add(istemciAdresi);
     IstemciEkle(istemciAdi);
     IstemciSayisiGoster("Sunucuya Baðlý Ýstemciler: " + IstemciAdresleri.Count);
 }
Exemplo n.º 34
-2
        /// <summary>
		/// Converts the string representation of a Bluetooth address to a new <see cref="BluetoothAddress"/> instance.
		/// </summary>
        /// <param name="bluetoothString">A string containing an address to convert.</param>
		/// <returns>New <see cref="BluetoothAddress"/> instance.</returns>
		/// <remarks>Address must be specified in hex format optionally separated by the colon or period character e.g. 000000000000, 00:00:00:00:00:00 or 00.00.00.00.00.00.</remarks>
        /// <exception cref="ArgumentNullException">bluetoothString is null.</exception>
        /// <exception cref="FormatException">bluetoothString is not a valid Bluetooth address.</exception>
        public static BluetoothAddress Parse(string bluetoothString)
		{
            if (bluetoothString == null)
			{
                throw new ArgumentNullException("bluetoothString");
			}

			BluetoothAddress ba;

            if (bluetoothString.IndexOf(":") > -1)
			{
				//assume address in standard hex format 00:00:00:00:00:00

                //check length
                if (bluetoothString.Length != 17)
                {
                    throw new FormatException("bluetoothString is not a valid Bluetooth address.");
                }

				ba = new BluetoothAddress();
				byte[] babytes = ba.ToByteArray();
				//split on colons
                string[] sbytes = bluetoothString.Split(':');
				for(int ibyte = 0; ibyte < 6; ibyte++)
				{
					//parse hex byte in reverse order
					babytes[ibyte] = byte.Parse(sbytes[5 - ibyte],System.Globalization.NumberStyles.HexNumber);
				}
			}
            else if (bluetoothString.IndexOf(".") > -1)
			{
				//assume address in uri hex format 00.00.00.00.00.00
                //check length
                if (bluetoothString.Length != 17)
                {
                    throw new FormatException("bluetoothString is not a valid Bluetooth address.");
                }

				ba = new BluetoothAddress();
				byte[] babytes = ba.ToByteArray();
				//split on periods
                string[] sbytes = bluetoothString.Split('.');
				for(int ibyte = 0; ibyte < 6; ibyte++)
				{
					//parse hex byte in reverse order
					babytes[ibyte] = byte.Parse(sbytes[5 - ibyte],System.Globalization.NumberStyles.HexNumber);
				}
			}
			else
			{
				//assume specified as long integer
                if ((bluetoothString.Length < 12) | (bluetoothString.Length > 16))
                {
                    throw new FormatException("bluetoothString is not a valid Bluetooth address.");
                }

                ba = new BluetoothAddress(long.Parse(bluetoothString, System.Globalization.NumberStyles.HexNumber));
			}

			return ba;
        }
Exemplo n.º 35
-2
 public void SetAddress(String add)
 {
     addr = BluetoothAddress.Parse(add);
 }