using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using InTheHand.Net.Ports;
using System.IO;
Guid muuid = new Guid("00001101-0000-1000-8000-00805F9B34FB");
private void scan()
{
UpdateUI("Starting Scan...");
BluetoothClient client = new BluetoothClient();
Devices = client.DiscoverDevicesInRange();
UpdateUI("Scan Complete");
foreach (BluetoothDeviceInfo d in Devices)
{
items.Add(d.DeviceName);
}
UpdateDeviceList();
}
private void StartScan()
{
lb_BT.DataSource = null;
lb_BT.Items.Clear();
items.Clear();
Thread bluetoothScanThread = new Thread(new ThreadStart(scan));
bluetoothScanThread.Start();
}
BluetoothDeviceInfo[] Devices;
private void UpdateDeviceList()
{
Func<int> del = delegate()
{
lb_BT.DataSource = items;
return 0;
};
Invoke(del);
}
BluetoothDeviceInfo deviceInfo;
private void ClientConnectThread()
{
BluetoothClient client = new BluetoothClient();
UpdateUI("Attempting connect");
client.BeginConnect(deviceInfo.DeviceAddress, muuid, this.BluetoothClientConnectCallback, client);
}
Stream stream = null;
public void BluetoothClientConnectCallback(IAsyncResult res)
{
{
BluetoothClient client = (BluetoothClient)res.AsyncState;
client.EndConnect(res);
stream = client.GetStream();
else
{
SetupObj.bInitialize(stream);
}
//fpcresp[0] = (byte)stream.ReadByte();
}
}
private void writeCmd(byte[] buffer)
{
try
{
stream.Flush();
stream.Write(buffer, 0, buffer.Length);
retCode = SUCCESS;
}
catch (Exception ex)
{
retCode = FAILURE;
Debug.WriteLine("Write IO Exception " + ex.Message);
}
}
private byte[] ReadCmd()
{
if( stream!= null)
{
byte[] BytesRead = new byte[100];
int BytesReadCnt = 0;
stream.Read(BytesRead, 0, 3);
return BytesRead;
}
else
{
return null;
}
}
首先我会调用writeCmd,然后调用ReadCmd。有时会发生什么,我在ReadCmd中获取未读数据。(因为上次writeCmd)所以我使用了stream.Flush();在每个writeCmd之前。那么流上的数据也不是法拉盛。