문제

기호 장치 용 EMDK와 함께 제공되는 Symbol.wpan.bluetooth를 사용하려고합니다.

데이터를 전송하는 작업 예제가 있습니까?

Symbol의 예제는 단지 장치를 짝을 이룹니다. (개인 영역 네트워크 예에서는 데이터 전송이 실제로 필요하지 않다고 생각합니다.)

어쨌든, 나는 이것이 긴 샷이라는 것을 알고 있지만, 누군가가 이것을 일하기 위해 얻었다면 나는 몇 가지 코드를보고 싶습니다.

이것이 제가 시도한 것입니다. 하나의 장치 누르기 버튼을 누르고 다른 장치를 누릅니다. 버튼을 누릅니다. 읽기 값은 항상 제로 길이 바이트 배열입니다.

using System.Text;
using System.Windows.Forms;
using Symbol.WPAN;
using Symbol.WPAN.Bluetooth;

namespace SmartDeviceProject1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Bluetooth bluetooth = new Bluetooth();
            if (bluetooth.IsEnabled != true)
            {
                bluetooth.Enable();
                bluetooth.RadioMode = BTH_RADIO_MODE.BTH_DISCOVERABLE_AND_CONNECTABLE;
            }

            RemoteDevice connectedDevice = null;
            foreach (RemoteDevice remoteDevice in MakeEnumerable(bluetooth.RemoteDevices))
            {
                if ((remoteDevice.Name == "WM_Dan")  && (remoteDevice.IsPaired == false))
                {
                    remoteDevice.Pair();
                    connectedDevice = remoteDevice;
                }
            }

            string test;
            test = "Testing this out";
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] encTest = encoding.GetBytes(test);


            if (connectedDevice != null)
            {
                connectedDevice.WriteTimeout = 20000;
                connectedDevice.Write(encTest);
            }


        }

        public static IEnumerable<RemoteDevice> MakeEnumerable(RemoteDevices devices)
        {
            for (var i = 0; i < devices.Length; i++)
            {
                yield return devices[i];
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Bluetooth bluetooth = new Bluetooth();

            if (bluetooth.IsEnabled != true)
            {
                bluetooth.Enable();
                bluetooth.RadioMode = BTH_RADIO_MODE.BTH_DISCOVERABLE_AND_CONNECTABLE;
            }

            RemoteDevice connectedDevice = null;
            foreach (RemoteDevice remoteDevice in MakeEnumerable(bluetooth.RemoteDevices))
            {
                if ((remoteDevice.Name == "WM_Dan2") && (remoteDevice.IsPaired == false))
                {
                    remoteDevice.Pair();
                    connectedDevice = remoteDevice;
                }
            }

            string test;
            test = "Testing this out";
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] encTest = encoding.GetBytes(test);
            byte[] encTest2;
            string test2;

            if (connectedDevice != null)
            {
                connectedDevice.ReadTimeout = 20000;
                encTest2 = connectedDevice.Read(encTest.Length);
                test2 = encoding.GetString(encTest2, 0, encTest2.Length);
                MessageBox.Show(test2);
            }

        }

    }
}
도움이 되었습니까?

해결책

내장 된 COM 포트 연결 사용을 포기하고 연결에 시리얼 포트 객체를 열었습니다.

SerialPort sp = new SerialPort();
sp.PortName = "COM" + connectedDevice.LocalComPort.ToString();
sp.BaudRate = 9600;
sp.DataBits = 8;
sp.Parity = Parity.None;
sp.StopBits = StopBits.One;

sp.Open();
sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
sp.ErrorReceived += new SerialErrorReceivedEventHandler(sp_ErrorReceived);
sp.WriteLine(textBoxSend.Text);

또한 그들의 문서가 LocalComport가 자동 할당되었다고 말했지만 이것이 항상 진실이 아니라는 것을 알았습니다. BtexPlorer를 사용하여 먼저 설정하는 것이 가장 좋습니다.

또한, OpenComport는 반사기를 사용하는 것이 매우 잘못된 것입니다. 반환을 점검하고 있습니다 ::CreateFile("COM" + port...) -1 대신 0에 대해INVALID_HANDLE_VALUE)

다른 팁

이것이 누군가를 도울 수 있는지 모르겠지만 여기에 몇 년 전에 쓴 오래된 코드가 있습니다.

응용 프로그램에서 작동하도록 정리해야합니다. 내 앱에는 글로벌 클래스에 오류를 읽고 로그인 한 텍스트 상자 컨트롤이 있습니다. 당신이 가진 것과 함께 일하기 위해 그것을 바꾸면 기본적으로 좋을 것입니다.

static class Scanner {

  const string _CODEFILE = "Scanner.cs - Scanner::";
  static int _baud = 9600;
  static int _bits = 8;
  static string _dataIn = null;
  static string _port = "COM1";
  static Parity _parity = Parity.None;
  static StopBits _stop = StopBits.One;
  static SerialPort _com1 = null;
  static TextBox _textbox = null;
  public enum ControlType { None, BadgeID, PartNumber, SerialNumber, WorkOrder };
  static ControlType _control;

  public static bool Available { get { return ((_com1 != null) && (_com1.IsOpen)); } }

  public static bool Close {
    get {
      if (_com1 == null) return true;
      try {
        if (_com1.IsOpen) {
          _com1.Close();
        }
        return (!_com1.IsOpen);
      } catch { }
      return false;
    }
  }

  public static string Open() {
    const string na = "Not Available";
    if (_com1 == null) {
      string reset = Reset();
      if (!String.IsNullOrEmpty(reset)) return reset;
    }
    try {
      _com1.Open();
      return (_com1.IsOpen) ? null : na;
    } catch (Exception err) {
      return err.Message;
    }
  }

  static void ProcessData(string incoming) {
    _dataIn += incoming;
    if ((_control != ControlType.None) && (_textbox != null)) {
      bool ok = false;
      string testData = _dataIn.Trim();
      switch (_control) {
        case ControlType.BadgeID:
          if (testData.Length == 6) {
            if (testData != BarCode.LOGOFF) {
              Regex pattern = new Regex(@"[0-9]{6}");
              ok = (pattern.Matches(testData).Count == 1);
            } else {
              ok = true;
            }
          }
          break;
        case ControlType.PartNumber:
          if (testData.Length == 7) {
            Regex pattern = new Regex(@"[BCX][P057][0-9]{5}");
            ok = (pattern.Matches(testData).Count == 1);
          }
          break;
        case ControlType.SerialNumber:
          if (testData.Length == 15) {
            Regex pattern = new Regex(@"[BCX][P057][0-9]{5} [0-9]{4} [0-9]{2}");
            ok = (pattern.Matches(testData).Count == 1);
          }
          break;
        case ControlType.WorkOrder:
          if (testData.Length == 6) {
            Regex pattern = new Regex(@"[0-9]{6}");
            ok = (pattern.Matches(testData).Count == 1);
          }
          break;
      }
      if (ok) {
        _textbox.Text = testData;
        _textbox.ScrollToCaret();
        _dataIn = null;
      }
    }
  }

  static string Reset() {
    if (_com1 != null) {
      try {
        if (_com1.IsOpen) {
          _com1.DiscardInBuffer();
          _com1.Close();
        }
      } catch (Exception err) {
        return err.Message;
      }
      Global.Dispose(_com1);
      _com1 = null;
    }
    try {
      _com1 = new SerialPort(_port, _baud, _parity, _bits, _stop);
      _com1.DataReceived += new SerialDataReceivedEventHandler(Serial_DataReceived);
      _com1.Open();
    } catch (Exception err) {
      return err.Message;
    }
    return null;
  }

  public static void ScanSource(ref TextBox objTextBox, ControlType objType) {
    _textbox = objTextBox;
    _control = objType;
    _dataIn = null;
  }

  static void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e) {
    ProcessData(_com1.ReadExisting());
  }

  public static void Settings(string ComPort, int BaudRate, Parity ParityValue, int Bits, StopBits StopBit) {
    _port = ComPort;
    _baud = BaudRate;
    _parity = ParityValue;
    _bits = Bits;
    _stop = StopBit;
  }

  /// <summary>
  /// Closes the COM Port
  /// COM Port routines are ready to add as soon as I am
  /// </summary>
  static bool ComPortClose {
    get {
      if (_com1 == null) ComPortReset();
      return ((_com1 == null) ? true : _com1.IsOpen ? false : true);
    }
    set {
      if (_com1 == null) ComPortReset();
      else if (_com1.IsOpen) {
        _com1.DiscardInBuffer();
        _com1.Close();
      }
    }
  }
  /// <summary>
  /// Opens the COM Port
  /// </summary>
  static bool ComPortOpen {
    get {
      if (_com1 == null) ComPortReset();
      return (_com1 == null) ? false : _com1.IsOpen;
    }
    set {
      if (_com1 == null) ComPortReset();
      if ((_com1 != null) && (!_com1.IsOpen)) _com1.Open();
    }
  }
  /// <summary>
  /// Initialized the Serial Port on COM1
  /// </summary>
  static void ComPortReset() {
    if ((_com1 != null) && (_com1.IsOpen)) {
      _com1.Close();
      _com1 = null;
    }
    try {
      _com1 = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
    } catch (IOException err) {
      Global.LogError(_CODEFILE + "ComPortReset", err);
    }
  }

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top