Esempio n. 1
0
        private void ConnectToDevice()
        {
            if (curDeviceAddress == null)
            {
                DataGridViewRow selectedRow = dgvDeviceDiscovery.SelectedRows[0];
                selectedDevice   = (BtDevice)dgvDeviceDiscovery.CurrentCell.Value;
                curDeviceAddress = selectedDevice.DeviceAddress;
            }
            BtConnectionParameters cxParam = new BtConnectionParameters();

            cxParam.ConnectionIntervalMs = 30;
            //cxParam.SlaveLatency = 0;
            //cxParam.SupervisionTimeoutMs = 10000;
            try
            {
                if (false && isBonded)
                {
                    masterEmulator.Connect(curDeviceAddress, cxParam);
                }
                else
                {
                    if (masterEmulator.Connect(curDeviceAddress, cxParam))
                    {
                        //masterEmulator.Bond();
                        DiscoverPipes();
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Check if a device has the advertising data we are looking for.
        /// </summary>
        bool IsEligibleForConnection(BtDevice device)
        {
            IDictionary <DeviceInfoType, string> deviceInfo = device.DeviceInfo;

            bool hasServicesCompleteAdField =
                deviceInfo.ContainsKey(DeviceInfoType.ServicesCompleteListUuid128);

            if (!hasServicesCompleteAdField)
            {
                return(false);
            }

            const string bleUartUuid       = "6E400001B5A3F393E0A9E50E24DCCA9E";
            bool         hasHidServiceUuid =
                deviceInfo[DeviceInfoType.ServicesCompleteListUuid128].Contains(
                    bleUartUuid);

            if (!hasHidServiceUuid)
            {
                return(false);
            }

            /* If we have reached here it means all the criterias have passed. */
            return(true);
        }
Esempio n. 3
0
        void OnDeviceDiscovered(object sender, ValueEventArgs <BtDevice> e)
        {
            this.BeginInvoke((MethodInvoker) delegate()
            {
                dgvDeviceDiscovery.Enabled = true;
                dgvDeviceDiscovery.Visible = true;

                BtDevice dev      = e.Value;
                string deviceName = "";
                IDictionary <DeviceInfoType, string> deviceInfo = dev.DeviceInfo;

                if (deviceInfo.ContainsKey(DeviceInfoType.CompleteLocalName))
                {
                    deviceName = deviceInfo[DeviceInfoType.CompleteLocalName];
                }
                else if (deviceInfo.ContainsKey(DeviceInfoType.ShortenedLocalName))
                {
                    deviceName = deviceInfo[DeviceInfoType.ShortenedLocalName];
                }
                else
                {
                    deviceName = "Default";
                }

                string key = deviceName + " (adr: " + dev.DeviceAddress + ")";
                discoveredDevicesList[key]  = dev;
                dgvDeviceDiscovery.RowCount = discoveredDevicesList.Count;
            });
        }
Esempio n. 4
0
 public BtGattConnectCallback(BtDevice btDevice, DeviceDescriptor descriptor, IDeviceManager deviceManager, TracingInformation tracingInformation)
 {
     _btDevice           = btDevice;
     _descriptor         = descriptor;
     _deviceManager      = deviceManager;
     _tracingInformation = tracingInformation;
 }
Esempio n. 5
0
        public async Task <ObservableCollection <BtDevice> > GetBondedDevices()
        {
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;

            if (adapter == null)
            {
                Log("No Bluetooth adapter found.");
            }
            else if (!adapter.IsEnabled)
            {
                Log("Bluetooth adapter is not enabled.");
            }

            ObservableCollection <BtDevice> L = new ObservableCollection <BtDevice>();

            foreach (BluetoothDevice d in adapter.BondedDevices)
            {
                var device = new BtDevice();
                device.Name    = d.Name;
                device.Address = d.Address;
                Log("D: " + d.Name + " " + d.Address + " " + d.BondState.ToString());
                L.Add(device);
            }
            return(L);
        }
 public void pair()
 {
     BtDevice.PairingRequest().Subscribe(x =>
     {
         string txt = x ? "Device Paired Successfully" : "Device Pairing Failed";
         Console.WriteLine(txt);
     });
 }
Esempio n. 7
0
 private void DeviceDiscovered(object sender, BtDevice dev)
 {
     BeginInvoke((MethodInvoker) delegate()
     {
         logBox.AppendText("New device found.\n");
         deviceBox.Items.Add(dev);
     });
 }
Esempio n. 8
0
 private void Connected(object sender, BtDevice dev)
 {
     BeginInvoke((MethodInvoker) delegate()
     {
         logBox.AppendText("Connected.\n");
         startButton.Enabled = true;
         connectButton.Enabled = true;
         connectButton.Text = "Disconnect";
     });
 }
Esempio n. 9
0
 //----------------------------------------------------------
 // DeviceFound handler
 //----------------------------------------------------------
 public void OnDevFound(BtDevice device)
 {
     // add device to list if not already contained
     if (DeviceNames.Contains(device.DeviceName))
     {
         return;
     }
     AddResult(String.Format("Adding '{0}' to list", device.DeviceName));
     Devices.Enqueue(device);
     DeviceNames.Enqueue(device.DeviceName);
 }
Esempio n. 10
0
 internal void ReleaseBtDevice()
 {
     if (BtDevice != null)
     {
         BtDevice.ConnectionStatusChanged -= ConnectionStatusChanged;
         BtDevice.NameChanged             -= NameChanged;
         BtDevice.SdpRecordsChanged       -= ServiceChanged;
         BtDevice.Dispose();
         BtDevice = null;
     }
 }
Esempio n. 11
0
 public void connect()
 {
     // don't cleanup connection - force user to d/c
     if (BtDevice.Status == ConnectionStatus.Disconnected)
     {
         BtDevice.Connect();
     }
     else
     {
         BtDevice.CancelConnection();
     }
 }
Esempio n. 12
0
        void OnDeviceDiscovered(object sender, ValueEventArgs <BtDevice> arguments)
        {
            /* Avoid call after a connect procedure is being started,
            * and the discovery procedure hasn't yet been stopped. */
            if (connectionInProgress)
            {
                return;
            }
            //device1 = arguments.Value;
            //while ( (GetDeviceName(device1.DeviceInfo).Equals("MDZB")) == false)
            {
                device1 = arguments.Value;

                if (!IsEligibleForConnection(device1))
                {
                    return;
                }

                connectionInProgress = true;
            }


            /* Start the connection procedure in a background task to avoid
             * blocking the event caller. */

            conn1();

            /*
             * Task.Factory.StartNew(() =>
             * {
             *  try
             *  {
             *      //if (GetDeviceName(device.DeviceInfo).Equals("MDZB"))
             *      {
             *          Connecting(this, EventArgs.Empty);
             *
             *          bool success = Connect(device1);
             *          if (!success)
             *          {
             *              ConnectionCanceled(this, EventArgs.Empty);
             *              return;
             *          }
             *      }
             *  }
             *  catch (Exception ex)
             *  {
             *      LogErrorMessage(string.Format("Exception in OnDeviceDiscovered: {0}",
             *          ex.Message), ex.StackTrace);
             *      ConnectionCanceled(this, EventArgs.Empty);
             *  }
             * });
             * */
        }
Esempio n. 13
0
 private void ProcessResult(ScanResult result)
 {
     System.Threading.Tasks.Task.Run(() =>
     {
         BtDevice btDevice = new BtDevice(result.Device.Address, result.TimestampNanos);
         var descriptor    = result.ToDeviceDescriptor();
         _deviceManager.HandleDeviceDiscovered(descriptor, (d) =>
         {
             result.Device.ConnectGatt(
                 _context,
                 false,
                 new BtGattConnectCallback(btDevice, descriptor, _deviceManager, _tracingInformation));
         });
     }).FireAndForget();
 }
Esempio n. 14
0
        void OnDgvDeviceDiscoveryClick(object sender, EventArgs e)
        {
            if (isConnected)
            {
                return;
            }

            if (dgvDeviceDiscovery.CurrentCell != null)
            {
                string deviceKey = (string)(dgvDeviceDiscovery.CurrentCell.Value);
                selectedDevice     = discoveredDevicesList[deviceKey];
                curDeviceAddress   = selectedDevice.DeviceAddress;
                btnConnect.Enabled = true;
            }
        }
        /// <summary>
        /// Event handler for DeviceDiscovered. This handler will be called when devices
        /// are discovered during asynchronous device discovery.
        /// </summary>
        void OnDeviceDiscovered(object sender, ValueEventArgs <BtDevice> arguments)
        {
            /* Avoid call after a connect procedure is being started,
            * and the discovery procedure hasn't yet been stopped. */
            if (connectionInProgress)
            {
                return;
            }

            BtDevice device = arguments.Value;

            if (!IsEligibleForConnection(device))
            {
                return;
            }

            connectionInProgress = true;

            /* Start the connection procedure in a background task to avoid
             * blocking the event caller. */
            Task.Factory.StartNew(() =>
            {
                try
                {
                    Connecting(this, EventArgs.Empty);

                    bool success = Connect(device);
                    if (!success)
                    {
                        ConnectionCanceled(this, EventArgs.Empty);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    LogErrorMessage(string.Format("Exception in OnDeviceDiscovered: {0}",
                                                  ex.Message), ex.StackTrace);
                    ConnectionCanceled(this, EventArgs.Empty);
                }
            });
        }
Esempio n. 16
0
        bool Connect(BtDevice device)
        {
            if (masterEmulator.IsDeviceDiscoveryOngoing)
            {
                masterEmulator.StopDeviceDiscovery();
            }

            deviceName = GetDeviceName(device.DeviceInfo);
            AddToLog(string.Format("Connecting to {0}, Device name: {1}",
                                   device.DeviceAddress.ToString(), deviceName));


            BtConnectionParameters connectionParams = new BtConnectionParameters();

            connectionParams.ConnectionIntervalMs = 11.25;
            connectionParams.ScanIntervalMs       = 250;
            connectionParams.ScanWindowMs         = 200;
            bool connectSuccess = masterEmulator.Connect(device.DeviceAddress, connectionParams);

            return(connectSuccess);
        }
Esempio n. 17
0
        internal async Task <bool> ObtainBtDevice()
        {
            if (BtDevice != null)
            {
                return(true);
            }

            try
            {
                BtDevice = await BluetoothDevice.FromIdAsync(BtID);
            }
            catch (Exception)
            {
                if (BtDevice != null)
                {
                    BtDevice.Dispose();
                }

                BtDevice = null;
            }

            if (BtDevice == null)
            {
                return(false);
            }

            BtDevice.ConnectionStatusChanged += ConnectionStatusChanged;
            BtDevice.NameChanged             += NameChanged;
            BtDevice.SdpRecordsChanged       += ServiceChanged;

            if (BtDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                BtConnectionStateChangedObservers?.Invoke(this, BtDevice, BtDevice.ConnectionStatus);
            }

            return(true);
        }
Esempio n. 18
0
        // Function to send file to all devices in the queue
        public void SendFiles(string filename)
        {
            if (Devices.Count < 1)
            {
                return;
            }

            BtDevice curDevice;

            while (Devices.Count > 0)
            {
                curDevice = Devices.Dequeue();
                DeviceNames.Dequeue();
                SendComplete = false;
                AddResult(String.Format("Sending '{0}'", filename));
                ShowFcnResult("SendFile", curDevice.SendFile(filename));
                while (!SendComplete)
                {
                    Application.DoEvents();
                }
            }

            AddResult("Done sending files.");
        }
 private void onConnected(object sender, BtDevice dev)
 {
     onResponseReceived(this, (byte) 0x00);
     this.mec.Connected -= onConnected;
 }
        public void Connect(BtDevice device)
        {
            if (masterEmulator.IsDeviceDiscoveryOngoing)
                masterEmulator.StopDeviceDiscovery();

            BtConnectionParameters connParams = new BtConnectionParameters();
            connParams.ConnectionIntervalMs = 7.5;
            connParams.SlaveLatency = 0;
            connParams.SupervisionTimeoutMs = 100;

            connectedDevice = device;

            masterEmulator.Connect(device.DeviceAddress, connParams);
        }
Esempio n. 21
0
        /// <summary>
        /// Check if a device has the advertising data we are looking for.
        /// </summary>
        bool IsEligibleForConnection(BtDevice device)
        {
            IDictionary<DeviceInfoType, string> deviceInfo = device.DeviceInfo;

            karelDumpDevice(device);
            /*
            bool hasServicesCompleteAdField =
                deviceInfo.ContainsKey(DeviceInfoType.ServicesCompleteListUuid128);

            if (!hasServicesCompleteAdField)
            {
                return false;
            }
            */
            bool hasHidServiceUuid;
            try
            {
                //#define NUS_BASE_UUID  {{0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, 0x93, 0xF3, 0xA3, 0xB5, 0x00, 0x00, 0x40, 0x6E}} /**< Used vendor specific UUID. */
                //const string bleUartUuid = "6E400001B5A3F393E0A9E50E24DCCA9E";
                const string bleUartUuid = "6E400001B5A3F393E0A9E50E24DCCA42"; // ... 42 == T&D
                hasHidServiceUuid = deviceInfo[DeviceInfoType.ServicesCompleteListUuid128].Contains(bleUartUuid);
            }
            catch //(Exception ex)
            {
                hasHidServiceUuid = false;
            }
            if (!hasHidServiceUuid)
            {
                return false;
            }

            /* If we have reached here it means all the criterias have passed. */
            return true;
        }
Esempio n. 22
0
        void karelDumpDevice(BtDevice device)
        {
            IDictionary<DeviceInfoType, string> deviceInfo;
            BtDeviceAddress deviceAddress;
            string str = string.Empty;
            //string deviceName = string.Empty;
            //bool hasNameField;

            /*
             * $$$$ karelDumpDevice $$$$
             * --Device Address: 3C2DB785F142
             * $$$$ karelDumpDevice $$$$
             * --Flags: GeneralDiscoverable, BrEdrNotSupported
             * --ServicesCompleteListUuid128: 0xD0D0D0D00000000000000000DEADF154
             * --CompleteLocalName: SimpleBLEPeripheral
             * --TxPowerLevel: 0dBm
             * --SlaveConnectionIntervalRange: 10-00-20-00
             * --RandomTargetAddress: A0-A1-A2-A3-A4-A5
             * --Rssi: -65
             * $$$$ karelDumpDevice $$$$ [END]
             *
             * $$$$ karelDumpDevice $$$$
             * --Device Address: DCB326B6E893
             * $$$$ karelDumpDevice $$$$
             * --Flags: LimitedDiscoverable, BrEdrNotSupported
             * --ServicesCompleteListUuid128: 0x6E400001B5A3F393E0A9E50E24DCCA9E
             * --CompleteLocalName: Nondick_UART
             * --Rssi: -45
             * $$$$ karelDumpDevice $$$$ [END]
             *
             */
            deviceInfo = device.DeviceInfo;

            deviceAddress = device.DeviceAddress;

            karelLog("$$$$ karelDumpDevice $$$$");

            str = string.Format("--Device Address: {0}", deviceAddress.Value);
            karelLog(str);

            karelLog("$$$$ karelDumpDevice $$$$");

            //http://stackoverflow.com/questions/972307/can-you-loop-through-all-enum-values
            //var Avalues = Enum.GetValues(typeof(DeviceInfoType));
            var Bvalues = Enum.GetValues(typeof(DeviceInfoType)).Cast<DeviceInfoType>();

            foreach (var p in Bvalues)
            {
                if (deviceInfo.ContainsKey(p))
                {
                    str = string.Format("--{0}: {1}", p, deviceInfo[p]);
                    karelLog(str);
                }
            }

            karelLog("$$$$ karelDumpDevice $$$$ [END]");
        }
Esempio n. 23
0
        //=====================================================================
        //=====================================================================
        //=====================================================================
        //=====================================================================
        //=====================================================================
        public bool Connect_to_device(BtDevice device)
        {
            bool bStatus;

            //if (masterEmulator.IsDeviceDiscoveryOngoing)
            while (masterEmulator.IsDeviceDiscoveryOngoing) // TODO (maybe need this during debug run
            {
                masterEmulator.StopDeviceDiscovery();
            }

            karelDumpDevice(device); //karel

            string deviceName = GetDeviceName(device.DeviceInfo);
            AddToLog(string.Format("Connecting to {0}, Device name: {1}",
                device.DeviceAddress.ToString(), deviceName));

            BtConnectionParameters connectionParams = new BtConnectionParameters();
            //TODO _nRFTD1 connection parameters may be different than for _nRFUart
            connectionParams.ConnectionIntervalMs = 11.25;
            connectionParams.ScanIntervalMs = 250;
            connectionParams.ScanWindowMs = 200;
            //TODO _nRFTD1 connection parameters may be different than for _nRFUart

            FLAG_connectionInProgress = true;
            bStatus = masterEmulator.Connect(device.DeviceAddress, connectionParams);
            if (bStatus == false)
            {
                FLAG_connectionInProgress = false;
            }
            return (bStatus);
        }
Esempio n. 24
0
        /// <summary>
        /// Connecting to the given device, and with the given connection parameters.
        /// </summary>
        /// <param name="device">Device to connect to.</param>
        /// <returns>Returns success indication.</returns>
        //bool Connect(BtDevice device)
        bool Connect_nRFUart(BtDevice device)
        {
            if (masterEmulator.IsDeviceDiscoveryOngoing)
            {
                masterEmulator.StopDeviceDiscovery();
            }

            karelDumpDevice(device); //karel

            /* NG here*/
            //karel - from Documentation
            karelLog("\r\n");
            karelLog("\r\n");
            karelLog("========== TESTING masterEmulator.DiscoverServices() ================\r\n");
            karelLog("\r\n");

            var attributes = masterEmulator.DiscoverServices();
            foreach (var item in attributes)
            {
                Trace.WriteLine(item.ToString());
                karelLog("-----> " + item.ToString());
            }
            /**/

            string deviceName = GetDeviceName(device.DeviceInfo);
            AddToLog(string.Format("Connecting to {0}, Device name: {1}",
                device.DeviceAddress.ToString(), deviceName));

            BtConnectionParameters connectionParams = new BtConnectionParameters();
            connectionParams.ConnectionIntervalMs = 11.25;
            connectionParams.ScanIntervalMs = 250;
            connectionParams.ScanWindowMs = 200;
            bool connectSuccess = masterEmulator.Connect(device.DeviceAddress, connectionParams);
            return connectSuccess;
        }

        #endif
    }

    public class udPacketEventArgs : EventArgs
    {
        #region Constructors

        public udPacketEventArgs(Byte[] packet, Int32 length)
        {
            Packet = packet;
            Length = length;
        }

        #endregion Constructors

        #region Properties

        public Int32 Length
        {
            get; set;
        }

        public Byte[] Packet
        {
            get; set;
        }

        #endregion Properties
    }

    public class UpDnEngine
    {
        #region Fields

        public Nordicsemi.MasterEmulator masterEmulator;

        //=====================================================================
        //=====================================================================
        //===== UP ============================================================
        //=====================================================================
        //=====================================================================
        int BLK_DN_COUNT;
        Int32 DN_CHK_CHKSUM_NG = 3;
        Int32 DN_CHK_OK = 0;
        UInt16 m_blkDn_blkCnt;

        /*
        #define BLK_DN_COUNT 128

        Byte m_blkDn_buf[ 16 * BLK_DN_COUNT ]; // 2048 @ BLK_DN_COUNT = 128
        Byte m_blkDn_chk[  1 * BLK_DN_COUNT ]; //  128 @ BLK_DN_COUNT = 128
        */
        /*array<Byte,1>*/
        byte[] m_blkDn_buf;

        /*array<Byte,1>*/
        byte[] m_blkDn_chk;
        UInt16 m_blkDn_len;
        UInt16 m_blkDn_rxBlkCnt;

        //static Byte  m_Dcfm_buf[20];
        //static UInt16 m_Dcfm_len;
        /*array<Byte,1>*/
        byte[] m_Dcfm_buf;
        UInt16 m_Dcfm_len;

        //PPP PipeSetup pipeSetup;
        PipeSetup_UpDn pipeSetup;
        L6_OnDataRxCallback_DEL rxCallback = L6_OnDataRxCallback_DUMMY;
Esempio n. 25
0
 private void Disconnected(object sender, BtDevice dev)
 {
     BeginInvoke((MethodInvoker)delegate()
     {
         startButton.Enabled = false;
         connectButton.Enabled = true;
         connectButton.Text = "Connect";
     });
 }
Esempio n. 26
0
 //----------------------------------------------------------
 // DeviceFound handler
 //----------------------------------------------------------
 public void OnDevFound(BtDevice device)
 {
     // add device to list if not already contained
     if (DeviceNames.Contains(device.DeviceName))
         return;
     AddResult(String.Format("Adding '{0}' to list", device.DeviceName));
     Devices.Enqueue(device);
     DeviceNames.Enqueue(device.DeviceName);
 }
Esempio n. 27
0
        public bool scan_and_connect(String emulator_filter="")
        {
            System.Collections.ObjectModel.Collection<string> emulator_devices;

            //""" Function for doing discovery of the peer device, connect and
            //discover pipes. The function will also open the Master Emulator. """
            try
            {
                this.master = new Nordicsemi.MasterEmulator();

                this.master.LogMessage += this.log_message_handler;
                this.master.DataReceived += this.data_received_handler;
                this.master.Connected += this.connected_handler;
                this.master.Disconnected += this.disconnected_handler;
                this.master.PipeError += this.pipe_error_handler;
                this.master.ConnectionUpdateRequest += this.connection_update_handler;

                emulator_devices = this.master.EnumerateUsb(Nordicsemi.UsbDeviceType.AnyDevice);

                String emulator_device = this.filter_emulator_device(emulator_devices, emulator_filter);

                if( emulator_device == null )
                {
                    //raise Exception("Could not find emulator device");
                    throw new System.Exception("Could not find emulator device");
                }

                this.master.SerialPortBaudRate = this.baud_rate;

                this.master.Open(emulator_device); //void Open(string usbSerialNumber);

                this.setup_service();

                //# Start Master Emulator
                this.master.Run();

                this.set_local_data();

                if( this.own_address != "" )
                {
                    String byte_endianess_transformed_address = this.change_byte_endianess(this.own_address);
                    BtDeviceAddress bt_device_address = new Nordicsemi.BtDeviceAddress(byte_endianess_transformed_address);
                    this.master.SetBDAddress(bt_device_address);
                }
                this.restore_bond_info();

                //# Run discovery procedure
                this.myPeerDevice = this._discover_peer_device();
                logger.log("Found peer device");

                //# Connect and bond to peer device
                Nordicsemi.BtConnectionParameters conn_params = new Nordicsemi.BtConnectionParameters();
                conn_params.ConnectionIntervalMs = 15;
                if( this.master.Connect(this.myPeerDevice.DeviceAddress) )
                {
                    logger.log("--- Connected ---");
                } else {
                    //raise(Exception("Connection failed"));
                    throw new System.Exception("Connection failed");
                }

                if( this.service_setup_done == true )
                {
                    //# Service discovery
                    bool found_pipes = this.master.DiscoverPipes();

                    //print "PIPES RETURN VALUE: %s" % found_pipes

                    if( !found_pipes )
                    {
                        return false;
                    }

                    logger.log("--- Pipes discovered ---");
                }
            }
            catch( Exception ex)
            {
                logger.log(String.Format("[EXCEPTION] {0}", ex));
                logger.log("Call stack:");
                //tb = traceback.extract_tb(sys.exc_info()[2])
                //for f in reversed(tb):
                //logger.log(String.Format("  File {0}, line {1}",os.path.basename(f[0]), f[1]));
                this.num_of_errors += 1;
                logger.log(String.Format("number of errors: {0}", this.num_of_errors));
                return false;
            }
            return true;

            /*
            """ Function for doing discovery of the peer device, connect and
                discover pipes. The function will also open the Master Emulator. """
            try:
                this.master = None
                this.master = Nordicsemi.MasterEmulator()

                this.master.LogMessage += this.log_message_handler
                this.master.DataReceived += this.data_received_handler
                this.master.Connected += this.connected_handler
                this.master.Disconnected += this.disconnected_handler
                this.master.PipeError += this.pipe_error_handler
                this.master.ConnectionUpdateRequest += this.connection_update_handler

                emulator_devices = this.master.EnumerateUsb(Nordicsemi.UsbDeviceType.AnyDevice)

                emulator_device = this.filter_emulator_device(emulator_devices, emulator_filter)

                if emulator_device is None:
                    raise Exception("Could not find emulator device")

                this.master.SerialPortBaudRate = this.baud_rate

                this.master.Open(emulator_device)

                this.setup_service()

                # Start Master Emulator
                this.master.Run()

                this.set_local_data()

                if this.own_address:
                    byte_endianess_transformed_address = this.change_byte_endianess(this.own_address)
                    bt_device_address = Nordicsemi.BtDeviceAddress(byte_endianess_transformed_address)
                    this.master.SetBDAddress(bt_device_address)

                this.restore_bond_info()

                # Run discovery procedure
                this.myPeerDevice = this._discover_peer_device()
                logger.log("Found peer device")

                # Connect and bond to peer device
                conn_params = Nordicsemi.BtConnectionParameters()
                conn_params.ConnectionIntervalMs = 15
                if this.master.Connect(this.myPeerDevice.DeviceAddress):
                    logger.log("--- Connected ---")
                else:
                    raise(Exception("Connection failed"))

                if this.service_setup_done:
                    # Service discovery
                    found_pipes = this.master.DiscoverPipes()

                    print "PIPES RETURN VALUE: %s" % found_pipes

                    if not found_pipes:
                        return false

                    logger.log("--- Pipes discovered ---")

            except Exception, ex:
                logger.log("[EXCEPTION] %s" % ex)
                logger.log("Call stack:")
                tb = traceback.extract_tb(sys.exc_info()[2])
                for f in reversed(tb):
                    logger.log("  File {0}, line {1}".format(os.path.basename(f[0]), f[1]))
                this.num_of_errors += 1
                logger.log("number of errors: %i" % this.num_of_errors)
                return false

            return true
            */
        }
Esempio n. 28
0
        public async Task <bool> ConnectSpp()
        {
            bool result = await ObtainBtDevice();

            Log($"ConnectSpp({BleID}, ObtainBtDevice={result})");

            if (BtDevice == null)
            {
                return(false);
            }

            if (BtDevice.DeviceAccessInformation.CurrentStatus == DeviceAccessStatus.DeniedByUser)
            {
                return(false);
            }

            // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call

            RfcommDeviceServicesResult rfcommServices =
                await BtDevice.GetRfcommServicesForIdAsync(
                    RfcommServiceId.SerialPort,
                    BluetoothCacheMode.Uncached);

            Log($"{rfcommServices.Services.Count} Services found");

            foreach (RfcommDeviceService service in rfcommServices.Services)
            {
                Log($"{service.ConnectionServiceName}");
                Log($"\tHostName: {service.ConnectionHostName}");
                Log($"\tServiceId: {service.ServiceId.AsString()}");
                Log($"\tProtectionLevel: {service.ProtectionLevel}");
                Log($"\tDeviceAccessInformation: {service.DeviceAccessInformation.CurrentStatus}");
            }

            if (rfcommServices.Services.Count > 0)
            {
                SppService = rfcommServices.Services[0];
            }
            else
            {
                return(false);
            }

            Log($"Connecting to {SppService.ServiceId.AsString()}");

            // Do various checks of the SDP record to make sure you are talking to a device that actually supports the Bluetooth Rfcomm Chat Service

            lock (this)
            {
                SppServiceSocket = new StreamSocket();
            }
            try
            {
                await SppServiceSocket.ConnectAsync(SppService.ConnectionHostName, SppService.ConnectionServiceName);

                SppServiceWriter = new DataWriter(SppServiceSocket.OutputStream);
                SppServiceReader = new DataReader(SppServiceSocket.InputStream);
                SppServiceReader.InputStreamOptions = InputStreamOptions.ReadAhead;
            }
            catch (Exception ex)
            {
                Log($"{ex.Message}");
                Log($"{ex.StackTrace}");
                return(false);
            }

            return(true);
        }
Esempio n. 29
0
        // Function to send file to all devices in the queue
        public void SendFiles(string filename)
        {
            if (Devices.Count < 1)
                return;

            BtDevice curDevice;
            while (Devices.Count > 0)
            {
                curDevice = Devices.Dequeue();
                DeviceNames.Dequeue();
                SendComplete = false;
                AddResult(String.Format("Sending '{0}'", filename));
                ShowFcnResult("SendFile", curDevice.SendFile(filename));
                while (!SendComplete)
                    Application.DoEvents();

            }

            AddResult("Done sending files.");
        }
 private void onDisconnected(object sender, BtDevice dev)
 {
     mec.Connect(dev);
 }
Esempio n. 31
0
        /// <summary>
        /// Connecting to the given device, and with the given connection parameters.
        /// </summary>
        /// <param name="device">Device to connect to.</param>
        /// <returns>Returns success indication.</returns>
        //bool Connect(BtDevice device)
        bool Connect_nRFUart(BtDevice device)
        {
            if (masterEmulator.IsDeviceDiscoveryOngoing)
            {
                masterEmulator.StopDeviceDiscovery();
            }

            karelDumpDevice(device); //karel

            /* NG here*/
            //karel - from Documentation
            karelLog("\r\n");
            karelLog("\r\n");
            karelLog("========== TESTING masterEmulator.DiscoverServices() ================\r\n");
            karelLog("\r\n");

            var attributes = masterEmulator.DiscoverServices();
            foreach (var item in attributes)
            {
                Trace.WriteLine(item.ToString());
                karelLog("-----> " + item.ToString());
            }
            /**/

            string deviceName = GetDeviceName(device.DeviceInfo);
            AddToLog(string.Format("Connecting to {0}, Device name: {1}",
                device.DeviceAddress.ToString(), deviceName));

            BtConnectionParameters connectionParams = new BtConnectionParameters();
            connectionParams.ConnectionIntervalMs = 11.25;
            connectionParams.ScanIntervalMs = 250;
            connectionParams.ScanWindowMs = 200;
            bool connectSuccess = masterEmulator.Connect(device.DeviceAddress, connectionParams);
            return connectSuccess;
        }

        #endif

        #if true

        /*_nRFTD1*/
        bool Connect(BtDevice device)
        {
            //if (masterEmulator.IsDeviceDiscoveryOngoing)
            while (masterEmulator.IsDeviceDiscoveryOngoing) // TODO (maybe need this during debug run
            {
                masterEmulator.StopDeviceDiscovery();
            }

            karelDumpDevice(device); //karel

            string deviceName = GetDeviceName(device.DeviceInfo);
            AddToLog(string.Format("Connecting to {0}, Device name: {1}",
                device.DeviceAddress.ToString(), deviceName));

            BtConnectionParameters connectionParams = new BtConnectionParameters();
            //TODO _nRFTD1 connection parameters may be different than for _nRFUart
            connectionParams.ConnectionIntervalMs = 11.25;
            connectionParams.ScanIntervalMs = 250;
            connectionParams.ScanWindowMs = 200;
            //TODO _nRFTD1 connection parameters may be different than for _nRFUart
            bool connectSuccess;
            connectSuccess = masterEmulator.Connect(device.DeviceAddress, connectionParams);
            return connectSuccess;
        }

        #endif
    }