private void AxLEDeviceAdvertised(object sender, IDevice device)
        {
            Console.WriteLine($"ADVERTISED: {device.Name} <{device.MacAddress}> {device.Rssi} ({RssiFilter})");
            if (RssiFilter != 0 && device.Rssi < RssiFilter)
            {
                return;
            }

            if (!_lastSeen.ContainsKey(device.Id))
            {
                Console.WriteLine($"...New!");
                if (_devices.Any(d => d.Value.Id == device.Id))
                {
                    Console.WriteLine($"...Found");
                    var devicePair = _devices.Single(d => d.Value.Id == device.Id);
                    DeviceFound?.Invoke(this, devicePair.Key);
                }
                else
                {
                    Console.WriteLine($"...Discovered");
                    ProcessDeviceDiscovered(device);
                }
            }

            _lastSeen[device.Id] = DateTime.Now;
        }
Пример #2
0
        private void Close()
        {
            lock (this)
            {
                if (Port != null)
                {
                    try
                    {
                        Flush(Port);
                    }
                    catch (Exception ex)
                    {
                    }

                    try
                    {
                        Port.Close();
                    }
                    catch (Exception ex)
                    {
                    }
                    Port.Dispose();
                    Port        = null;
                    CurrentPort = null;
                }
                Connected = false;
                DeviceFound?.Invoke(this, CurrentPort);
            }
        }
Пример #3
0
 public void StartScan(BleDevice device)
 {
     _CentralManager = new CBCentralManager(this, null);
     if (device == null)
     {
         throw new Exception("Could not start client without a service type to scan for.");
     }
     _CentralManager.DiscoveredPeripheral += (o, e) =>
     {
         DeviceFound?.Invoke(this, new DeviceEventArgs {
             Device = new BleDevice {
                 Guid = e.Peripheral.UUID.Uuid
             }
         });
     };
     _CentralManager.ConnectedPeripheral += (o, e) =>
     {
         DeviceConnected?.Invoke(this, new DeviceEventArgs {
             Device = new BleDevice {
                 Guid = e.Peripheral.UUID.Uuid
             }
         });
     };
     //_CentralManager.ScanForPeripherals(CBUUID.FromPartial(device.GuidValue));
     _CentralManager.ScanForPeripherals(CBUUID.FromString(device.Guid));
 }
        private void SendProbe(IPAddress address, int port)
        {
            try
            {
                var uri = new UriBuilder("http", address.ToString(), port);

                var probe = new MTConnectClients.Probe(uri.ToString());
                probe.UserObject = new ProbeSender(address, port);
                probe.Timeout    = Timeout;
                probe.Error     += Probe_Error;

                // Notify that a new Probe request has been sent
                ProbeSent?.Invoke(this, address, port);

                var document = probe.Execute();
                if (document != null)
                {
                    // Get the MAC Address of the sender
                    var macAddress = GetMacAddress(address);

                    foreach (var device in document.Devices)
                    {
                        // Notify that a Device was found
                        DeviceFound?.Invoke(this, new MTConnectDevice(address, port, macAddress, device.Name));
                    }

                    // Notify that the Probe reqeuest was successful
                    ProbeSuccessful?.Invoke(this, address, port);
                }
            }
            catch { }
        }
Пример #5
0
        private async Task OnDevicesChangedAsync()
        {
            List <ObservableBluetoothLEDevice> devices = new List <ObservableBluetoothLEDevice>(BLE_HELPER.BluetoothLeDevices);

            foreach (ObservableBluetoothLEDevice device in devices)
            {
                if (string.Equals(device.BluetoothAddressAsString.ToLowerInvariant(), targetMac))
                {
                    BLEDevice bleDevice = await BLEDevice.FromIdAsync(device.DeviceInfo.Id);

                    if (!(bleDevice is null))
                    {
                        // Try to connect to the device:
                        if (await bleDevice.ConnectAsync())
                        {
                            // Execute the challenge response mechanism:
                            if (await bleDevice.UnlockAsync())
                            {
                                // Invoke event:
                                DeviceFound?.Invoke(this, new BLEDeviceEventArgs(bleDevice));
                                return;
                            }
                        }
                    }
                }
            }
        }
Пример #6
0
        private async Task OnDevicesChangedAsync()
        {
            List <ObservableBluetoothLEDevice> devices = new List <ObservableBluetoothLEDevice>(BLE_HELPER.BluetoothLeDevices);

            foreach (ObservableBluetoothLEDevice device in devices)
            {
                if (string.Equals(device.BluetoothAddressAsString.ToLowerInvariant(), targetMac))
                {
                    SetState(BLEScannerState.CONNECTING);
                    BLEDevice bleDevice = await BLEDevice.FromIdAsync(device.DeviceInfo.Id);

                    if (!(bleDevice is null))
                    {
                        // Try to connect to the device:
                        if (await bleDevice.ConnectAsync())
                        {
                            // Invoke event:
                            DeviceFound?.Invoke(this, new BLEDeviceEventArgs(bleDevice));
                            return;
                        }
                    }
                    SetState(BLEScannerState.SCANNING);
                }
            }
        }
Пример #7
0
        public override void OnReceive(Context context, Intent intent)
        {
            switch (intent.Action)
            {
            case BluetoothAdapter.ActionDiscoveryStarted:
                System.Diagnostics.Debug.WriteLine("DiscoveryStarted");
                break;

            case BluetoothAdapter.ActionDiscoveryFinished:
                System.Diagnostics.Debug.WriteLine("DiscoveryFinished");
                DiscoveryComplete?.Invoke(this, EventArgs.Empty);
                break;

            case BluetoothDevice.ActionFound:
                var device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                if (device.Type != BluetoothDeviceType.Le)
                {
                    System.Diagnostics.Debug.WriteLine($"Found {device.Name} {device.Address} {device.BondState}");
                    DeviceFound?.Invoke(this, device);
                }
                break;

            case BluetoothDevice.ActionNameChanged:
                var device2 = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                System.Diagnostics.Debug.WriteLine($"Name Changed {device2.Name} {device2.Address}");
                break;

            case BluetoothDevice.ActionAclConnected:
                break;

            case BluetoothDevice.ActionAclDisconnected:
                break;
            }
        }
Пример #8
0
        /// <inheritdoc />
        public IEnumerable <string> Discover()
        {
            lock (_discoveryLock)
            {
                UsbDeviceCollection?usbDeviceCollection = _context.List();
                _context.SetDebugLevel(LibUsbDotNet.LogLevel.Debug);

                // Filter out all but Concept2 Vendor
                var discoveredDevices = usbDeviceCollection.Where(d => d.VendorId == VendorId);

                // Discover disconnected device based on location
                foreach (UsbDevice detachedDevice in _devices.Values.Except(discoveredDevices, new IUsbDeviceComparer()))
                {
                    Location location = new (detachedDevice.BusNumber, detachedDevice.Address);

                    // If events are enabled, fire one for the device being lost
                    EventArgs args = new DeviceEventArgs(location);

                    DeviceLost?.Invoke(this, args);

                    // Clean up device
                    Destroy(detachedDevice);

                    // Remove from devices
                    _devices.Remove(location, out _);
                }

                // Discover new devices using Location as the comparer
                foreach (UsbDevice foundDevice in discoveredDevices.Except(_devices.Values, new IUsbDeviceComparer()))
                {
                    if (!IsValidDevice(foundDevice))
                    {
                        _logger.LogWarning("Invalid device encountered. Not being added to the device list.");
                    }

                    Location location = new (foundDevice.BusNumber, foundDevice.Address);

                    if (!foundDevice.IsOpen)
                    {
                        Initialize(foundDevice);
                    }

                    string serialNumber = foundDevice.Info.SerialNumber;

                    // If events are enabled, fire one for the device being found
                    EventArgs args = new DeviceEventArgs(location)
                    {
                        SerialNumber = serialNumber
                    };

                    DeviceFound?.Invoke(this, args);

                    // Add to devices
                    _devices.TryAdd(location, serialNumber, foundDevice);
                }

                return(_devices.SerialNumbers);
            }
        }
Пример #9
0
        public void Stop()
        {
            StopThread();

            Close();

            DeviceFound?.Invoke(this, null);
        }
Пример #10
0
 static NatUtility()
 {
     foreach (var searcher in new ISearcher [] { UpnpSearcher.Instance, PmpSearcher.Instance })
     {
         searcher.DeviceFound += (o, e) => DeviceFound?.Invoke(o, e);
         searcher.DeviceLost  += (o, e) => DeviceLost?.Invoke(o, e);
     }
 }
Пример #11
0
        public override void OnReceive(Context context, Intent intent)
        {
            string action = intent.Action;

            if (action.Equals(BluetoothDevice.ActionFound))
            {
                var device = intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                DeviceFound?.Invoke(device, new EventArgs());
            }
        }
Пример #12
0
 private void OnDeviceStateChanged(DeviceState state)
 {
     if (state == DeviceState.Connected)
     {
         DeviceFound?.Invoke(this, Device);
     }
     else
     {
         DeviceLost?.Invoke(this, null);
     }
 }
Пример #13
0
 private void OnDeviceFound(IntPtr devicePtr)
 {
     try
     {
         var device = new Device(devicePtr);
         DeviceFound?.Invoke(this, device);
     }
     catch (Exception e)
     {
         //TODO log or something else...
     }
 }
Пример #14
0
        private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
        {
            var exists = _Discovered.FirstOrDefault(d => d.Id.Equals(args.Id));

            if (exists == null)
            {
                return;
            }
            DeviceFound?.Invoke(this, new DeviceEventArgs {
                Device = new BleDevice {
                    Guid = args.Id, Name = exists.Name
                }
            });
        }
Пример #15
0
 private void OnDeviceFound(IntPtr scaner, IntPtr devicePtr, IntPtr userData)
 {
     if (scaner != _scannerPtr)
     {
         return;
     }
     try
     {
         var device = new Device(devicePtr);
         DeviceFound?.Invoke(this, device);
     }
     catch (Exception e)
     {
         //TODO log or something else...
     }
 }
        private void AxLEDeviceAdvertised(object sender, IDevice device)
        {
            if (!_lastSeen.ContainsKey(device.Id))
            {
                if (_devices.Any(d => d.Value.Id == device.Id))
                {
                    var devicePair = _devices.Single(d => d.Value.Id == device.Id);
                    DeviceFound?.Invoke(this, devicePair.Key);
                }
                else
                {
                    ProcessDeviceDiscovered(device);
                }
            }

            _lastSeen[device.Id] = DateTime.Now;
        }
Пример #17
0
        private void Probe_Successful(MTConnect.MTConnectDevices.Document document)
        {
            IncrementProbeRequests();

            if (document.UserObject != null)
            {
                var sender = document.UserObject as ProbeSender;
                if (sender != null)
                {
                    // Get the MAC Address of the sender
                    var macAddress = GetMacAddress(sender.Address);

                    foreach (var device in document.Devices)
                    {
                        DeviceFound?.Invoke(new MTConnectDevice(sender.Address, sender.Port, macAddress, device.Name));
                    }
                }
            }
        }
        private void ProcessDeviceDiscovered(IDevice device)
        {
            if (_devices.Any(d => d.Value.Id == device.Id))
            {
                return;
            }

            if (string.IsNullOrEmpty(device.MacAddress))
            {
                if (!_interrogateQueue.Contains(device))
                {
                    _interrogateQueue.Enqueue(device);
                }
            }
            else
            {
                _devices[device.MacAddress] = device;
                DeviceFound?.Invoke(this, device.MacAddress);
            }
        }
Пример #19
0
        protected void RaiseDeviceFound(NatDevice device)
        {
            NatDevice actualDevice;

            lock (Devices) {
                if (Devices.TryGetValue(device, out actualDevice))
                {
                    actualDevice.LastSeen = DateTime.UtcNow;
                }
                else
                {
                    Devices[device] = device;
                }
            }
            // If we did not find the device in the dictionary, raise an event as it's the first time
            // we've encountered it!
            if (actualDevice == null)
            {
                DeviceFound?.Invoke(this, new DeviceEventArgs(device));
            }
        }
        private async void OnDeviceAdded(DeviceWatcher sender, DeviceInformation args)
        {
            var device  = new RemoteBluetoothDevice(args);
            var success = await device.TryAndConnectToDevice();

            if (success)
            {
                var id = RfcommServiceId.FromUuid(BluetoothMessageOrchestrator.ServiceUuid);
                success = await device.HasService(id, BluetoothMessageOrchestrator.SdpServiceNameAttributeId);
            }

            if (success)
            {
                lock (RemoteDevices)
                {
                    RemoteDevices.Add(device);
                }

                DeviceFound.Invoke(this, device);
                RaisePropertyChanged(new PropertyChangedEventArgs(nameof(RemoteDevices)));
            }
        }
        private async void ProcessInterrogationStack(object sender, ElapsedEventArgs e)
        {
            if (!_interrogating)
            {
                _interrogating = true;

                while (_interrogateQueue.Any())
                {
                    if (_interrogateQueue.TryDequeue(out IDevice device))
                    {
                        var serial = await InterrogateForSerial(device);

                        if (!string.IsNullOrEmpty(serial))
                        {
                            _devices[serial] = device;
                            DeviceFound?.Invoke(this, serial);
                        }
                    }
                }

                _interrogating = false;
            }
        }
Пример #22
0
        private bool TryOpen(string port)
        {
            SerialPort p = null;

            try
            {
                p             = new SerialPort(port, 115200);
                p.ReadTimeout = 500;

                p.Open();
                Flush(p);

                /* read version */
                Pm3UsbCommand cmdDevInfo = new Pm3UsbCommand(0);
                cmdDevInfo.Write(p);
                Pm3UsbResponse resDevInfo = new Pm3UsbResponse(p);
                if (resDevInfo.Cmd != Pm3UsbResponse.eResponseType.DeviceInfo)
                {
                    LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3] TryOpen: " + port + " did not reply to a device info");
                    p.Close();
                    return(false);
                }

                DeviceInfo = (eDeviceInfo)resDevInfo.data.arg[0];

                LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3] Device info: ");
                LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3]   BOOTROM_PRESENT         " + ((DeviceInfo & eDeviceInfo.BootromPresent) != 0 ? "Y" : "N"));
                LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3]   OSIMAGE_PRESENT         " + ((DeviceInfo & eDeviceInfo.OsImagePresent) != 0 ? "Y" : "N"));
                LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3]   MODE_BOOTROM            " + ((DeviceInfo & eDeviceInfo.ModeBootrom) != 0 ? "Y" : "N"));
                LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3]   MODE_OS                 " + ((DeviceInfo & eDeviceInfo.ModeOs) != 0 ? "Y" : "N"));
                LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3]   UNDERSTANDS_START_FLASH " + ((DeviceInfo & eDeviceInfo.UnderstandStartFlash) != 0 ? "Y" : "N"));

                if ((DeviceInfo & eDeviceInfo.ModeBootrom) != 0 && (DeviceInfo & eDeviceInfo.ModeBootrom) != 0)
                {
                    Pm3UsbCommand cmdReset = new Pm3UsbCommand((ulong)Pm3UsbCommand.eCommandType.HardwareReset);
                    CurrentPort = port;
                    Port        = p;

                    if (!File.Exists(Flashfile))
                    {
                        LogWindow.Log(LogWindow.eLogLevel.Error, "[PM3] Device started in bootloader mode, but I cannot find flash file " + Flashfile + ". Reset device.");
                    }
                    else
                    {
                        bool bootloader = false;
                        var  segs       = ReadFlash(Flashfile, out bootloader);

                        FlashRequestContext ctx = new FlashRequestContext();

                        ctx.Bootloader = bootloader;
                        ctx.FlashFile  = Flashfile;
                        ctx.Proceed    = false;

                        FlashRequest?.Invoke(this, ctx);

                        if (ctx.Proceed)
                        {
                            bool success = Flash(segs, bootloader);
                            FlashResult?.Invoke(this, success);
                        }
                    }

                    cmdReset.Write(p);
                    p.Close();

                    return(false);
                }

                Pm3UsbCommand cmdPing = new Pm3UsbCommand(0x109);
                cmdPing.Write(p);
                Pm3UsbResponse resPing = new Pm3UsbResponse(p);

                if (resPing.Cmd != Pm3UsbResponse.eResponseType.ACK)
                {
                    LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3] TryOpen: " + port + " did not reply to a ping");
                    p.Close();
                    return(false);
                }

                /* read version */
                Pm3UsbCommand cmdVers = new Pm3UsbCommand(0x107);
                cmdVers.Write(p);
                Pm3UsbResponse resVers = new Pm3UsbResponse(p);
                if (resVers.Cmd != Pm3UsbResponse.eResponseType.ACK)
                {
                    LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3] TryOpen: " + port + " did not reply to a version info");
                    p.Close();
                    return(false);
                }
                Thread.Sleep(500);
                Flush(p);

                LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3] Chip ID: 0x" + resVers.data.arg[0].ToString("X8"));
                LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3] Flash:   0x" + resVers.data.arg[1].ToString("X8"));
                LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3] Caps:    0x" + resVers.data.arg[2].ToString("X8"));
                string versionString = Encoding.UTF8.GetString(resVers.data.d, 0, resVers.data.dataLen - 1);
                LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3] Version:");
                foreach (string line in versionString.Split('\n'))
                {
                    LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3]     " + line);
                }

                CurrentPort = port;
                Port        = p;

                /* does it support the unlock command? */
                int reason = 0;
                UnlockSupported = true;
                UnlockTag(0xDEADBEEF, ref reason);

                /* if not supported, the command will simply time out */
                UnlockSupported = reason > 0;
                LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3] Device does " + (UnlockSupported ? "" : "*NOT*") + " support SLIX-L unlock command");

                DeviceFound?.Invoke(this, CurrentPort);
                LogWindow.Log(LogWindow.eLogLevel.Debug, "[PM3] TryOpen: " + port + " successfully opened");


                Connected = true;
                return(true);
            }
            catch (Exception ex)
            {
                try
                {
                    if (p != null && p.IsOpen)
                    {
                        p.Close();
                    }
                }
                catch (Exception e)
                {
                }
            }

            return(false);
        }
Пример #23
0
        public event EventHandler ScanComplete; // TODO: Implement

        protected virtual void OnDeviceFound(Device device)
        {
            DeviceFound?.Invoke(device, null);
        }
Пример #24
0
 protected virtual void OnDeviceFound(Launch device)
 {
     DeviceFound?.Invoke(this, device);
 }
Пример #25
0
 private void OnDeviceFound(TPLinkSmartDevice device)
 {
     DeviceFound?.Invoke(this, new DeviceFoundEventArgs(device));
 }
Пример #26
0
 protected virtual void OnDeviceFound(Device e)
 {
     DeviceFound?.Invoke(this, e);
 }
Пример #27
0
 private void Sniffer_DeviceFound(MTConnectDevice device)
 {
     DeviceFound.Invoke(device);
 }
 public int DeviceAdded(int lFindData, IUPnPDevice pDevice)
 {
     DeviceFound?.Invoke(lFindData, pDevice);
     return(default(int));
 }
 private void OnDeviceFound(SonosDevice e)
 {
     DeviceFound?.Invoke(this, e);
 }
Пример #30
0
 static void HandleDeviceFound(object sender, DeviceEventArgs e)
 {
     DeviceFound?.Invoke(sender, e);
 }