/// <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); }*/ }
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); } }
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); } }
/// <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; } }
private async void button2_Click(object sender, EventArgs e) { BluetoothDevicePicker picker = new BluetoothDevicePicker(); var device = await picker.PickSingleDeviceAsync(); listBox1.Items.Clear(); listBox2.Items.Clear(); client = new InTheHand.Net.Sockets.BluetoothClient(); client.Connect(device.DeviceAddress, new Guid("fa87c0d0-afac-11de-8a39-0800200c9a66")); stream = client.GetStream(); label3.Text = "Status: Connected " + device.DeviceName; //var AvilableDevices = client.DiscoverDevices(); //foreach (var item in AvilableDevices) //{ // listBox1.Items.Add(item.DeviceName); //} //var PairDevices = client.PairedDevices; //foreach (var item in PairDevices) //{ // listBox2.Items.Add(item.DeviceName); //} btnConnect.Enabled = !client.Connected; btnDisconnect.Enabled = client.Connected; btnSend.Enabled = client.Connected; }
public void readInfoClient() { bluetoothClient = bluetoothListener.AcceptBluetoothClient(); Console.WriteLine("Cliente Conectado!"); Stream stream = bluetoothClient.GetStream(); while (bluetoothClient.Connected) { try { byte[] byteReceived = new byte[1024]; int read = stream.Read(byteReceived, 0, byteReceived.Length); if (read > 0) { Console.WriteLine("Messagem Recebida: " + Encoding.ASCII.GetString(byteReceived) + System.Environment.NewLine); } stream.Flush(); } catch (Exception e) { Console.WriteLine("Erro: " + e.ToString()); } } stream.Close(); }
private async void MainWindow_Activated(object sender, EventArgs e) { BluetoothDevicePicker picker = new BluetoothDevicePicker(); //picker.ClassOfDevices.Add(new ClassOfDevice(DeviceClass.SmartPhone, 0)); var device = await picker.PickSingleDeviceAsync(); InTheHand.Net.Sockets.BluetoothClient client = new InTheHand.Net.Sockets.BluetoothClient(); System.Diagnostics.Debug.WriteLine("Unknown"); foreach (BluetoothDeviceInfo bdi in client.DiscoverDevices()) { System.Diagnostics.Debug.WriteLine(bdi.DeviceName + " " + bdi.DeviceAddress); } System.Diagnostics.Debug.WriteLine("Paired"); foreach (BluetoothDeviceInfo bdi in client.PairedDevices) { System.Diagnostics.Debug.WriteLine(bdi.DeviceName + " " + bdi.DeviceAddress); } //System.Diagnostics.Debug.WriteLine(client.RemoteMachineName); client.Connect(device.DeviceAddress, BluetoothService.SerialPort); var stream = client.GetStream(); stream.Write(System.Text.Encoding.ASCII.GetBytes("Hello World\r\n\r\n"), 0, 15); stream.Close(); }
public void ServerConnectThread() { updateUI("Server started, waiting for client"); bluetoothListener = new BluetoothListener(mUUID); bluetoothListener.Start(); conn = bluetoothListener.AcceptBluetoothClient(); updateUI("Client has connected"); connected = true; //Stream mStream = conn.GetStream(); mStream = conn.GetStream(); while (connected) { try { byte[] received = new byte[1024]; mStream.Read(received, 0, received.Length); string receivedString = Encoding.ASCII.GetString(received); //updateUI("Received: " + receivedString); handleBluetoothInput(receivedString); //byte[] send = Encoding.ASCII.GetBytes("Hello world"); //mStream.Write(send, 0, send.Length); } catch (IOException e) { connected = false; updateUI("Client disconnected"); disconnectBluetooth(); } } }
public Task OpenAsync() { return Task.Run( () => { _tokenSource = new CancellationTokenSource(); _client = new BluetoothClient(); _client.Connect( _deviceInfo.DeviceAddress, BluetoothService.SerialPort ); _networkStream = _client.GetStream(); Task.Factory.StartNew( CheckForData, _tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default ); } ); }
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(); }
void ServerWorker_DoWork(object sender, DoWorkEventArgs e) { try { client = serverSocket.AcceptBluetoothClient(); Stream peerStream = client.GetStream(); bWriter = new BinaryWriter(peerStream, Encoding.ASCII); bReader = new BinaryReader(peerStream, Encoding.ASCII); e.Result = true; } catch (Exception exception) { e.Result = false; Console.WriteLine(exception.Message); } }
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(); }
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); } }
/*public static void md5(string source) { byte[] data = System.Text.Encoding.UTF8.GetBytes(source); MD5 md = MD5.Create(); byte [] cryptoData = md.ComputeHash(data); Console.WriteLine(System.Text.Encoding.UTF8.GetString(cryptoData)); md.Clear(); } */ public void Listen() { try { new BluetoothClient(); } catch (Exception ex) { var msg = "Bluetooth init failed: " + ex; MessageBox.Show(msg); throw new InvalidOperationException(msg, ex); } Bluetoothlistener = new BluetoothListener(OurServiceClassId); Bluetoothlistener.ServiceName = OurServiceName; Bluetoothlistener.Start(); Bluetoothclient = Bluetoothlistener.AcceptBluetoothClient(); byte[] data = new byte[1024]; Ns = Bluetoothclient.GetStream(); Ns.BeginRead(data, 0, data.Length, new AsyncCallback(ReadCallBack), data); DataAvailable(this, "Begin to read"); }
void BluetoothConnect() { string androidTabletMAC = "68:05:71:AA:2B:C7"; // The MAC address of my phone, lets assume we know it BluetoothAddress addr = BluetoothAddress.Parse(androidTabletMAC); //var btEndpoint = new BluetoothEndPoint(addr, 1600); var btClient = new BluetoothClient(); //btClient.Connect(btEndpoint); Stream peerStream = btClient.GetStream(); StreamWriter sw = new StreamWriter(peerStream); sw.WriteLine("Hello World"); sw.Flush(); sw.Close(); btClient.Close(); btClient.Dispose(); // btEndpoint = null; }
private void acceptBluetoothClient(IAsyncResult ar) { if (client != null) Stop(false); if (listener == null) { Stop(true); return; } client = listener.EndAcceptBluetoothClient(ar); stream = client.GetStream(); ReadAsync(stream); Invoke(new MethodInvoker(delegate { status.Text = string.Format("Connected to {0}.", client.RemoteMachineName); sendButton.Enabled = true; })); listener.BeginAcceptBluetoothClient(acceptBluetoothClient, null); }
public override void Initialize() { var cli = new BluetoothClient(); BluetoothDeviceInfo[] peers = cli.DiscoverDevices(); BluetoothDeviceInfo device; if (string.IsNullOrEmpty(_address)) device = peers.FirstOrDefault(); else { device = peers.FirstOrDefault((d) => d.DeviceAddress.ToString() == _address); } if (device != null) { BluetoothAddress addr = device.DeviceAddress; Guid service = device.InstalledServices.FirstOrDefault(); cli.Connect(addr, service); var stream = cli.GetStream(); _bwriter = new StreamWriter(stream); } Initialized = true; }
private void detector_DoWork(object sender, DoWorkEventArgs e) { try { if (_bluetoothStream != null) _bluetoothStream.Close(); _client = new BluetoothClient(); BluetoothDeviceInfo gadgeteerDevice = null; while (gadgeteerDevice == null) { gadgeteerDevice = _client.DiscoverDevices().Where(d => d.DeviceName == "Gadgeteer") .FirstOrDefault(); UpdateStatus("Still looking..."); } if (gadgeteerDevice != null) { _client.SetPin(gadgeteerDevice.DeviceAddress, "1234"); _client.Connect(gadgeteerDevice.DeviceAddress, BluetoothService.SerialPort); _bluetoothStream = _client.GetStream(); e.Result = true; } else { e.Result = false; } } catch (Exception) { e.Result = false; } }
private void ListenLoop() { while (listening) { try { client = listener.AcceptBluetoothClient(); stream = client.GetStream(); SIGN_STREAMSETUP = true; listening = false; // 远程连接后,启动发送文件进程 // 远程设备连接后,启动recieve程序 receiving = true; receiveThread.Start(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); continue; } } }
private bool connect() { using (SelectBluetoothDeviceDialog bldialog = new SelectBluetoothDeviceDialog()) { bldialog.ShowRemembered = false; if (bldialog.ShowDialog() == DialogResult.OK) { if (bldialog.SelectedDevice == null) { MessageBox.Show("No device selected"); return false; } BluetoothDeviceInfo selecteddevice = bldialog.SelectedDevice; if (!selecteddevice.Authenticated) { if (!BluetoothSecurity.PairRequest(selecteddevice.DeviceAddress, "0000")) { MessageBox.Show("PairRequest Error"); return false; } } try { client = new BluetoothClient(); client.Connect(selecteddevice.DeviceAddress, BluetoothService.SerialPort); } catch { return false; } stream = client.GetStream(); // 标记stream已经接受对象实例化 SIGN_STREAMSETUP = true; // 启动接收图片的进程 receiving = true; receiveThread = new System.Threading.Thread(Receiveloop); receiveThread.Start(); // sendDataThread = new System.Threading.Thread(SendData); closeSendData(); sendDataThread.Start(); return true; } return false; } }
private void bgWorkerListen_DoWork(object sender, DoWorkEventArgs e) { running = true; bl.Start(); try { bc = bl.AcceptBluetoothClient(); ns = bc.GetStream(); Console.WriteLine("connected"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } BluetoothStreamHandler BSH = new BluetoothStreamHandler(bc, this); while (running) { } }
public BluetoothStreamHandler(BluetoothClient bc, BluetoothCommForm fm) { bcFm = fm; try { BluetoothStream = bc.GetStream(); BluetoothStream.BeginRead(buffer, 0, buffer.Length, AsyncReceiveCallback, this); } catch (Exception e) { Console.WriteLine(e.Message); } }
// 监听线程函数,用来监听来自手机端的请求并且分配各个用户的权限。 private void ListenLoop() { while (listening) { try { System.IO.Stream tempStream; client = listener.AcceptBluetoothClient(); clientList.Add(client); // 获取客户端信息(学生或者老师) tempStream = client.GetStream(); byte[] mark; int length; mark = new byte[20]; length = tempStream.Read(mark, 0, mark.Length); string right = System.Text.Encoding.ASCII.GetString(mark, 0, length); if (right == "teacher") { stream = tempStream; sendfileList.Add("tom.jpg"); WriteMessage("tom"); sendfileList.Add("jake.jpg"); WriteMessage("jake"); sendfileList.Add("sherry.jpg"); WriteMessage("sherry"); } if (right.StartsWith("student")) { // 提取right中的学生名称并加进去listBox里面 string studentName = right.Substring(7, right.Length - 7); WriteMessage(studentName); } SIGN_STREAMSETUP = true; // 远程设备连接后,启动recieve程序 receiving = true; new System.Threading.Thread(ReceiveLoop).Start((Object)client); } catch (Exception ex) { MessageBox.Show(ex.ToString()); continue; } } listener.Stop(); }
protected override void OpenConnection() { btEndpoint = new BluetoothEndPoint(addr, g); btClient = new BluetoothClient(); btClient.Connect(btEndpoint); peerStream = btClient.GetStream(); }
/// <summary> /// 连接函数 /// </summary> /// <returns></连接失败返回false> private bool connect() { // 创建选择框选择要连接的设备 using (SelectBluetoothDeviceDialog bldialog = new SelectBluetoothDeviceDialog()) { bldialog.ShowRemembered = false; if (bldialog.ShowDialog() == DialogResult.OK) { if (bldialog.SelectedDevice == null) { MessageBox.Show("No device selected"); return false; } BluetoothDeviceInfo selecteddevice = bldialog.SelectedDevice; if (!selecteddevice.Authenticated) { if (!BluetoothSecurity.PairRequest(selecteddevice.DeviceAddress, "0000")) { MessageBox.Show("PairRequest Error"); return false; } } try { // 对指定的目标进行蓝牙连接请求 client = new BluetoothClient(); client.Connect(selecteddevice.DeviceAddress, BluetoothService.SerialPort); stream = client.GetStream(); stream.Write(System.Text.Encoding.ASCII.GetBytes("teacher"), 0, 7); } catch { return false; } StateOfRunning(); stream = client.GetStream(); // 标记stream已经接受对象实例化 SIGN_STREAMSETUP = true; // 启动接收图片的线程 receiving = true; ReceiveThread = new System.Threading.Thread(ReceiveLoop); ReceiveThread.Start(); // 启动信息发送线程 sendDataThread = new System.Threading.Thread(SendDataLoop); closeSendData(); sendDataThread.Start(); sendfileThread = new System.Threading.Thread(SendFileLoop); return true; } return false; } }
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; } } }
// 连接电脑端蓝牙 private bool connect() { using (SelectBluetoothDeviceDialog bldialog = new SelectBluetoothDeviceDialog()) { bldialog.ShowRemembered = false; if (bldialog.ShowDialog() == DialogResult.OK) { if (bldialog.SelectedDevice == null) { MessageBox.Show("No device selected"); return false; } BluetoothDeviceInfo selecteddevice = bldialog.SelectedDevice; if (!selecteddevice.Authenticated) { if (!BluetoothSecurity.PairRequest(selecteddevice.DeviceAddress, "0000")) { MessageBox.Show("PairRequest Error"); return false; } } try { client = new BluetoothClient(); client.Connect(selecteddevice.DeviceAddress, BluetoothService.SerialPort); stream = client.GetStream(); stream.Write(System.Text.Encoding.ASCII.GetBytes("student" + LOCALBLUETOOTHNAME), 0, 7 + LOCALBLUETOOTHNAME.Length); } catch { return false; } StateOfRunning(); stream = client.GetStream(); // 标记stream已经接受对象实例化 SIGN_STREAMSETUP = true; // 启动接收图片的进程 receiving = true; // sendfileThread = new System.Threading.Thread(SendFileLoop); return true; } return false; } }
private void DiscoveryDeviceConnectCallback(IAsyncResult result) { client = (BluetoothClient)result.AsyncState; if (client.Connected) { peerStream = client.GetStream(); CommonConnectionSetup(); SendTweetsRequest(); } else { ErrorMessage("Couldn't connect to client!"); } }
/// <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; }
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"); }
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 } } }
public SocketClientAdapter(BluetoothClient cli) : base(cli.GetStream()) { cli1B = cli; }
/// <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); } }