Beispiel #1
0
        public void Run()
        {
            thread = new Thread(() => {
                try
                {
                    var ep     = new IPEndPoint(IPAddress.Any, Port);
                    var client = new UdpClient(ep);
                    while (true)
                    {
                        try
                        {
                            var r         = client.Receive(ref ep);
                            var eventArgs = Parse(r);

                            // If the discovery packet is from a different app, then ignore it.
                            if (!string.Equals(eventArgs.App, App, StringComparison.OrdinalIgnoreCase))
                            {
                                continue;
                            }

                            Discovered?.Invoke(eventArgs);
                        }
                        catch (Exception e)
                        {
                            Log.Warn(TAG, $"Failed to handle udp message with error {e}");
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Error(TAG, $"Failed to listen for udp on port {Port} with error {e}");
                }
            });
            thread.Start();
        }
Beispiel #2
0
        private void OnScanResponse(object sender, ScanResponseEventArgs e)
        {
            var type      = (DiscoveryType)e.PacketType;
            var mac       = new MAC(e.Sender);
            var macType   = (MacType)e.AddressType;
            var eventArgs = new DiscoveryEventArgs(type, mac, macType, e.Data, e.RSSI);

            Discovered?.Invoke(this, eventArgs);
        }
Beispiel #3
0
        public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI)
        {
            Console.WriteLine("Discovered {0}, data {1}, RSSI {2}", peripheral.Name, advertisementData, RSSI);

            if (!string.IsNullOrEmpty(peripheral.Name))
            {
                Discovered?.Invoke(new RomeRemoteSystem(peripheral)
                {
                    DisplayName = peripheral.Name,
                    Id          = peripheral.Identifier.ToString()
                });
            }
        }
        public override void OnEvent(Payload e)
        {
            lock (m_Lock)
            {
                var Location   = e.Pairs.FirstOrDefault(P => string.Equals(P.Type, "location", StringComparison.OrdinalIgnoreCase));
                var MACAddress = e.Pairs.FirstOrDefault(P => string.Equals(P.Type, "SerialNumber", StringComparison.OrdinalIgnoreCase));

                if (Location != null && MACAddress != null)
                {
                    string IpAddress = Location.Value.Substring(7);

                    IpAddress = IpAddress.Substring(0, IpAddress.IndexOf(':'));
                    Discovered?.Invoke(null, new BBDeviceFound {
                        MAC = MACAddress.Value, IPAddress = IpAddress
                    });
                }
            }
        }
Beispiel #5
0
        private async void OnBroadcast(CancellationTokenSource cancellationToken)
        {
            try
            {
                var parameter = new RemoteParameter()
                {
                    Command = RemoteCommands.MiriotDiscovery
                };

                while (!cancellationToken.IsCancellationRequested)
                {
                    var udpClient   = new UdpClient();
                    var requestData = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(parameter));
                    var serverEp    = new IPEndPoint(IPAddress.Any, 0);

                    udpClient.EnableBroadcast = true;
                    udpClient.Send(requestData, requestData.Length, new IPEndPoint(IPAddress.Broadcast, _port));

                    var serverResponseData = udpClient.Receive(ref serverEp);
                    var serverResponse     = Encoding.ASCII.GetString(serverResponseData);

                    var system = JsonConvert.DeserializeObject <RomeRemoteSystem>(serverResponse);
                    system.EndPoint = serverEp;

                    Debug.WriteLine("Received {0} from {1}", system.DisplayName, system.EndPoint.Address + ":" + system.EndPoint.Port);

                    Discovered?.Invoke(system);

                    udpClient.Close();

                    await Task.Delay(1000);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }
Beispiel #6
0
        // Called by manager

        private static bool RaiseDiscovered(BluetoothDeviceInfo bt, HIDDeviceInfo hid)
        {
            if (bt?.IsInvalid ?? true)
            {
                Debug.WriteLine($"{hid} Discovered");
            }
            else
            {
                Debug.WriteLine($"{bt} Discovered");
            }
            WiimoteDeviceInfo device;

            //FIXME: Quick fix to support both Bluetooth and DolphinBar connections.
            if (bt?.IsInvalid ?? true)            // && DolphinBarMode)
            {
                device = new WiimoteDeviceInfo(hid, true);
            }
            else
            {
                device = new WiimoteDeviceInfo(bt, hid);
            }
            WiimoteDiscoveredEventArgs e = new WiimoteDiscoveredEventArgs(device);

            Discovered?.Invoke(null, e);
            if (e.AddDevice)
            {
                try {
                    Connect(e.Device);
                }
                catch (Exception ex) {
                    RaiseConnectionFailed(e.Device, ex);
                    return(true);
                }
            }
            return(e.KeepSearching);
        }
Beispiel #7
0
        public void UdpListener_Received(byte[] data, IPEndPoint endPoint)
        {
            try
            {
                var dhcpData = new DhcpData(data)
                {
                    RelatedServer = this
                };
                var msgType = dhcpData.GetCurrentMessageType();
                var client  = dhcpData.GetClientInfo();
                switch (msgType)
                {
                case DhcpMessgeType.DHCP_DISCOVER:
                    MessageRaised?.Invoke(this, new MessageEventArgs {
                        Message = "DHCPDISCOVER received."
                    });
                    Discovered?.Invoke(client);
                    var newIp = ownedIpAddressPool.Find(x => (x.AuthorizedClientMac == client.MacAddress) || (x.IsAllocated == false && x.AuthorizedClientMac == null));
                    if (newIp.Ip == null)
                    {
                        MessageRaised?.Invoke(this, new MessageEventArgs {
                            Message = "No ip is available to allocate."
                        });
                        return;
                    }
                    MessageRaised?.Invoke(this, new MessageEventArgs {
                        Message = "DHCPOFFER sent."
                    });
                    // MUST be unicast over raw socket (unimplemented)
                    // broadcast used
                    SendDhcpMessage(DhcpMessgeType.DHCP_OFFER, dhcpData, newIp);
                    break;

                case DhcpMessgeType.DHCP_REQUEST:
                    MessageRaised?.Invoke(this, new MessageEventArgs {
                        Message = "DHCPREQUEST received."
                    });
                    Requested?.Invoke(client);
                    switch (GetDhcpRequestType(client, endPoint))
                    {
                    // respond to client which has responded to DHCPOFFER message from this server
                    case DhcpRequestType.Selecting:
                        MessageRaised?.Invoke(this, new MessageEventArgs {
                            Message = "Response to DHCPREQUEST generated during SELECTING state."
                        });
                        if (_settings.ServerIp.Equals(client.ServerAddress))
                        {
                            var allocatedIp = ownedIpAddressPool.Find(x => x.Ip.Equals(client.RequestAddress));
                            if (allocatedIp.Ip != null && !allocatedIp.IsAllocated)
                            {
                                allocatedIp.IsAllocated         = true;
                                allocatedIp.AuthorizedClientMac = client.MacAddress;
                                MessageRaised?.Invoke(this, new MessageEventArgs {
                                    Message = "DHCPACK sent."
                                });
                                // broadcast
                                SendDhcpMessage(DhcpMessgeType.DHCP_ACK, dhcpData, allocatedIp);
                            }
                        }
                        break;

                    case DhcpRequestType.InitReboot:
                        MessageRaised?.Invoke(this, new MessageEventArgs {
                            Message = "Response to DHCPREQUEST generated during INIT-REBOOT state."
                        });
                        if (!client.RelayAgentAddress.Equals(IPAddress.Any))
                        {
                            MessageRaised?.Invoke(this, new MessageEventArgs {
                                Message = "Relay agent is not supported in this version."
                            });
                        }
                        var rebootIp = ownedIpAddressPool.Find(x => x.Ip.Equals(client.RequestAddress));
                        if (rebootIp.Ip != null && rebootIp.AuthorizedClientMac == client.MacAddress)
                        {
                            // broadcast
                            SendDhcpMessage(DhcpMessgeType.DHCP_ACK, dhcpData, rebootIp);
                            MessageRaised?.Invoke(this, new MessageEventArgs {
                                Message = "DHCPACK sent."
                            });
                        }
                        break;

                    case DhcpRequestType.ReNewing:
                        MessageRaised?.Invoke(this, new MessageEventArgs {
                            Message = "Response to DHCPREQUEST generated during RENEWING state."
                        });
                        var reNewIp = ownedIpAddressPool.Find(x => x.Ip.Equals(client.ClientAddress));
                        if (reNewIp.Ip != null && reNewIp.AuthorizedClientMac == client.MacAddress)
                        {
                            // unicast
                            SendDhcpMessage(client.ClientAddress.ToString(), DhcpMessgeType.DHCP_ACK, dhcpData, reNewIp);
                            MessageRaised?.Invoke(this, new MessageEventArgs {
                                Message = "DHCPACK sent."
                            });
                        }
                        break;

                    case DhcpRequestType.ReBinding:
                        MessageRaised?.Invoke(this, new MessageEventArgs {
                            Message = "Response to DHCPREQUEST generated during REBINDING state."
                        });
                        var reBindIp = ownedIpAddressPool.Find(x => x.IsAllocated == false);
                        if (reBindIp.Ip != null)
                        {
                            reBindIp.IsAllocated         = true;
                            reBindIp.AuthorizedClientMac = client.MacAddress;
                            // broadcast
                            SendDhcpMessage(DhcpMessgeType.DHCP_ACK, dhcpData, reBindIp);
                            MessageRaised?.Invoke(this, new MessageEventArgs {
                                Message = "DHCPACK sent."
                            });
                        }
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    break;

                case DhcpMessgeType.DHCP_DECLINE:
                    MessageRaised?.Invoke(this, new MessageEventArgs {
                        Message = "DHCPDECLINE received."
                    });
                    var declinedIp = ownedIpAddressPool.Find(x => x.Ip.Equals(client.ClientAddress));
                    if (declinedIp.Ip != null)
                    {
                        ownedIpAddressPool.Remove(declinedIp);
                    }
                    break;

                case DhcpMessgeType.DHCP_RELEASE:
                    MessageRaised?.Invoke(this, new MessageEventArgs {
                        Message = "DHCPRELESE received."
                    });
                    var releasedIp = ownedIpAddressPool.Find(x => x.Ip.Equals(client.ClientAddress));
                    if (releasedIp.Ip != null)
                    {
                        releasedIp.IsAllocated = false;
                    }
                    break;

                case DhcpMessgeType.DHCP_INFORM:
                    MessageRaised?.Invoke(this, new MessageEventArgs {
                        Message = "DHCPINFORM received."
                    });
                    // unicast
                    SendDhcpMessage(client.ClientAddress.ToString(), DhcpMessgeType.DHCP_ACK, dhcpData, null);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch (Exception e)
            {
                ErrorRaised?.Invoke(this, new ErrorMessageEventArgs {
                    Message = e.Message
                });
                Terminate();
                throw e;
            }
        }
Beispiel #8
0
        private async void StartUnpairedDeviceWatcher()
        {
            // Request additional properties
            string[] requestedProperties = new string[] { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };

            _deviceWatcher = DeviceInformation.CreateWatcher(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
                                                             requestedProperties,
                                                             DeviceInformationKind.AssociationEndpoint);

            // Hook up handlers for the watcher events before starting the watcher
            _deviceWatcher.Added += new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, deviceInfo) =>
            {
                // Make sure device name isn't blank
                if (deviceInfo.Name != "")
                {
                    try
                    {
                        var service = await GattDeviceService.FromIdAsync(deviceInfo.Id);
                        if (service != null)
                        {
                        }
                    }
                    catch (Exception)
                    {
                    }
                    //if (service != null)
                    //{
                    //    var rfcommServices = await service?.GetRfcommServicesForIdAsync(
                    //RfcommServiceId.FromUuid(Constants.SERVICE_UUID), BluetoothCacheMode.Uncached);

                    //    if (rfcommServices?.Services.Count > 0)
                    //    {
                    //if (service.Uuid == Constants.SERVICE_UUID)
                    Discovered?.Invoke(new RomeRemoteSystem(deviceInfo)
                    {
                        Id          = deviceInfo.Id,
                        DisplayName = deviceInfo.Name,
                    });
                    //    }
                    //}
                }
            });

            _deviceWatcher.Updated += new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                var temp = _devices.ToList();
                foreach (var device in temp)
                {
                    if (device.Id == deviceInfoUpdate.Id)
                    {
                        (device.NativeObject as DeviceInformation).Update(deviceInfoUpdate);

                        var d = _devices.Single(df => df.Id == device.Id);
                        d     = new RomeRemoteSystem(device);

                        Updated?.Invoke(d);
                        break;
                    }
                }
            });

            _deviceWatcher.EnumerationCompleted += new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
            });

            _deviceWatcher.Removed += new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) =>
            {
                Removed?.Invoke(deviceInfoUpdate.Id);
            });

            _deviceWatcher.Stopped += new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) =>
            {
            });

            _deviceWatcher.Start();
        }
Beispiel #9
0
 protected void OnDiscovered(IAnalyzer analyzer, EventArgs args)
 {
     Discovered?.Invoke(analyzer, args);
 }