Domanda

Sto cercando di utilizzare Symbol.WPAN.Bluetooth che viene fornito con l'EMDK per i dispositivi Symbol.

Qualcuno capita di avere un esempio di lavoro che trasferisce i dati?

L'esempio di Symbol solo coppie i dispositivi. (A quanto pare pensano che il trasferimento dei dati non è realmente necessario in un esempio personal area network).

In ogni caso, so che questo è un colpo lungo, ma se qualcuno ha ottenuto questo lavoro mi piacerebbe vedere qualche codice.

Questo è quello che ho provato. Ho un dispositivo di stampa button1 e un altro dispositivo stampa button2. Il valore letto è sempre un array di byte di lunghezza zero.

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

        }

    }
}
È stato utile?

Soluzione

ho rinunciato utilizzando il built in connessione della porta COM e aprii un oggetto SerialPort sulla connessione.

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

Ho anche scoperto che anche se i loro documenti ha detto che è stato LocalComPort auto assegnato, questo non è stato sempre la verità. E 'stato meglio usare la loro BTExplorer per impostarlo prima.

Come pure, ci OpenComPort avrebbe funzionato in situazioni in cui è non dovrebbe - con Reflector è abbastanza ovviamente sbagliato. Ci sono controllando il ritorno di ::CreateFile("COM" + port...) contro 0 anziché -1 (INVALID_HANDLE_VALUE)

Altri suggerimenti

Non so se questo possa mai serve a nessuno, ma qui è un vecchio pezzo di codice che ho scritto qualche anno fa.

Si dovrà pulire in modo che funziona per la vostra applicazione. La mia app ha avuto un controllo TextBox che leggere e registrati tutti gli errori di una classe globale. Cambiare la situazione a lavorare con quello che hai, e dovrebbe essere sostanzialmente buona.

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

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top