示例#1
0
        static bool PlatformPairRequest(BluetoothAddress device, string pin)
        {
            BluetoothDevice bluetoothDevice = null;
            var             t = Task <bool> .Run(async() =>
            {
                bluetoothDevice = await BluetoothDevice.FromBluetoothAddressAsync(device.ToUInt64());
                DevicePairingResultStatus status = DevicePairingResultStatus.NotPaired;

                if (string.IsNullOrEmpty(pin))
                {
                    var result = await bluetoothDevice.DeviceInformation.Pairing.PairAsync();
                    status     = result.Status;
                }
                else
                {
                    pinMappings.Add(bluetoothDevice.DeviceId, pin);
                    bluetoothDevice.DeviceInformation.Pairing.Custom.PairingRequested += Custom_PairingRequested;
                    var result = await bluetoothDevice.DeviceInformation.Pairing.Custom.PairAsync(DevicePairingKinds.ProvidePin);
                    status     = result.Status;
                }

                return(status == DevicePairingResultStatus.Paired);
            });

            t.Wait();
            return(t.Result);
        }
示例#2
0
        private async Task Connect(JObject parameters)
        {
            //if (_connectedSocket?.Information.RemoteHostName != null)
            //{
            //    throw JsonRpcException.InvalidRequest("Already connected");
            //}
            var id              = parameters["peripheralId"]?.ToObject <string>();
            var address         = Convert.ToUInt64(id, 16);
            var bluetoothDevice = await BluetoothDevice.FromBluetoothAddressAsync(address);

            if (!bluetoothDevice.DeviceInformation.Pairing.IsPaired)
            {
                if (parameters.TryGetValue("pin", out var pin))
                {
                    _pairingCode = (string)pin;
                }
                var pairingResult = await Pair(bluetoothDevice);

                if (pairingResult != DevicePairingResultStatus.Paired &&
                    pairingResult != DevicePairingResultStatus.AlreadyPaired)
                {
                    throw JsonRpcException.ApplicationError("Could not automatically pair with peripheral");
                }
            }
            s_currentSession = this;
            if (s_connectMap.ContainsKey(id))
            {
                // ListenForMessages(id);
                return;
            }

            var services = await bluetoothDevice.GetRfcommServicesForIdAsync(RfcommServiceId.SerialPort,
                                                                             BluetoothCacheMode.Uncached);

            if (services.Services.Count > 0)
            {
                StreamSocket _connectedSocket = new StreamSocket();
                await _connectedSocket.ConnectAsync(services.Services[0].ConnectionHostName,
                                                    services.Services[0].ConnectionServiceName);

                DataWriter _socketWriter = new DataWriter(_connectedSocket.OutputStream);
                DataReader _socketReader = new DataReader(_connectedSocket.InputStream)
                {
                    ByteOrder = ByteOrder.LittleEndian
                };
                s_readerMap.Add(id, _socketReader);
                s_writerMap.Add(id, _socketWriter);
                s_connectMap.Add(id, _connectedSocket);
                ListenForMessages(id);
            }
            else
            {
                throw JsonRpcException.ApplicationError("Cannot read services from peripheral");
            }
        }
示例#3
0
        static bool PlatformRemoveDevice(BluetoothAddress device)
        {
            BluetoothDevice bluetoothDevice = null;
            var             t = Task <bool> .Run(async() =>
            {
                bluetoothDevice = await BluetoothDevice.FromBluetoothAddressAsync(device.ToUInt64());
                var result      = await bluetoothDevice.DeviceInformation.Pairing.UnpairAsync();

                return(result.Status == DeviceUnpairingResultStatus.Unpaired);
            });

            t.Wait();

            return(t.Result);
        }
示例#4
0
        private static async Task <RfcommDeviceService> FromIdAsyncImpl(string deviceId)
        {
            if (deviceId.StartsWith("BLUETOOTH#"))
            {
                var parts  = deviceId.Split('#');
                var addr   = parts[1];
                var uuid   = parts[2];
                var device = await BluetoothDevice.FromBluetoothAddressAsync(ulong.Parse(addr, NumberStyles.HexNumber));

                var service = RfcommServiceId.FromUuid(new Guid(uuid));

                return(new RfcommDeviceService(device, service));
            }

            return(null);
        }
示例#5
0
        public async void Setup()
        {
            foreach (var i in json.Devices)
            {
                if (i.DeviceType == "Bluetooth")
                {
                    BluetoothDevice bd;

                    if (i.DeviceAddress.StartsWith("Bluetooth"))
                    {
                        bd = await BluetoothDevice.FromIdAsync(i.DeviceAddress);
                    }
                    else
                    {
                        bd = await BluetoothDevice.FromBluetoothAddressAsync(ulong.Parse(i.DeviceAddress));
                    }

                    bd.ConnectionStatusChanged += Bd_ConnectionStatusChanged;
                }
            }
        }
        public override async Task <List <IBluetoothDevice> > GetPairedDevices()
        {
            var devices = new List <IBluetoothDevice>();

            var bluetoothDevices = await GetBluetoothPairedDevices();

            var serialPortDevices = await GetSerialPortDevices();

            foreach (var deviceInfo in bluetoothDevices)
            {
                var address = GetAddress(deviceInfo);

                if (!string.IsNullOrEmpty(address))
                {
                    var bluetoothDevice = new UWPBluetoothDevice()
                    {
                        Name    = deviceInfo.Name,
                        Address = address
                    };

                    var   trimmedAddress = address.Replace(":", "");
                    ulong t = Convert.ToUInt64(trimmedAddress, 16);

                    var bluetoothDeviceQuery = await BluetoothDevice.FromBluetoothAddressAsync(t);

                    bluetoothDevice.BluetoothDeviceReference = bluetoothDeviceQuery;

                    var serialQuery = serialPortDevices.FirstOrDefault(x => x.Id.Contains(deviceInfo.Id));
                    if (serialQuery != null)
                    {
                        var identifiers = GetUniqueIdentifiers(serialQuery);
                        bluetoothDevice.UniqueIdentifiers.AddRange(identifiers);
                    }

                    devices.Add(bluetoothDevice);
                }
            }

            return(devices);
        }
示例#7
0
        async Task Connect(string address)
        {
            // TODO: Add error handling
            var rawAddress = Convert.ToUInt64(address.Replace(":", ""), 16);
            var device     = await BluetoothDevice.FromBluetoothAddressAsync(rawAddress);

            var service = await device.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(Guid.Parse(BTBulldozer.MainPage.SPP_UUID)));

            var spp = service.Services[0];

            socket = new StreamSocket();
            await socket.ConnectAsync(spp.ConnectionHostName, spp.ConnectionServiceName);

            ChangeStatus();

            var timer = new Timer(async(object _) =>
            {
                if (socket is null)
                {
                    return;
                }

                var writer = new DataWriter(socket.OutputStream);
                writer.WriteBytes(Command.VOLTAGE);
                await writer.StoreAsync();

                var reader = new DataReader(socket.InputStream);
                await reader.LoadAsync(4);

                var buffer = new byte[4];
                reader.ReadBytes(buffer);
                var voltage = BitConverter.ToInt32(buffer, 0);
                var status  = new BTBulldozer.MainPage.Status()
                {
                    Voltage = voltage
                };

                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => mainPage.OnStatusUpdate(status));
            }, null, 0, 1000);
        }
示例#8
0
        /// <summary>
        /// Connect the client to a remote bluetooth host using PenInformation instance
        /// </summary>
        /// <param name="penInformation">The instance of PenInformation class</param>
        /// <returns>When this method completes successfully, it returns a boolean result</returns>
        public async Task <bool> Connect(PenInformation penInformation)
        {
            try
            {
                // lock try 블럭 안으로 이동
                await semaphreSlime.WaitAsync();

                if (Alive)
                {
                    return(false);
                }

                bool ret = await Pairing(penInformation);

                if (ret == false)
                {
                    return(false);
                }

                // 소켓을 멤버 변수로 가지고 있게끔
                streamSocket = new StreamSocket();

                //BluetoothDevice bluetoothDevice = await BluetoothDevice.FromIdAsync(penInformation.deviceInformation.Id);
                // le의 deviceinformation id를 이용해 BluetoothDevice를 가져올 수 없기 때문에 이런식으로 우회함
                BluetoothDevice bluetoothDevice = await BluetoothDevice.FromBluetoothAddressAsync(penInformation.BluetoothAddress);

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

                //var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync(RfcommServiceId.SerialPort, BluetoothCacheMode.Uncached);
                var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(RfcommServiceId.SerialPort.Uuid), BluetoothCacheMode.Uncached);

                RfcommDeviceService chatService = null;

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

                await streamSocket.ConnectAsync(bluetoothDevice.HostName, chatService.ConnectionServiceName);

                // 여기가 좀 지저분함
                PenController.Protocol = penInformation.Protocol == Protocols.V2 || bluetoothDevice.ClassOfDevice.RawValue == ClassOfDeviceV2 ? Protocols.V2 : Protocols.V1;

                await Task.Delay(200);

                Bind(streamSocket);
            }
            catch (Exception ex)
            {
                switch ((uint)ex.HResult)
                {
                case (0x80070490):                         // ERROR_ELEMENT_NOT_FOUND
                    return(false);

                case (0x800710DF):                         // ERROR_DEVICE_NOT_AVAILABLE
                    return(false);

                default:
                    Debug.WriteLine($"Exception : {ex.Message}");
                    Debug.WriteLine($"Exception : {ex.StackTrace}");
                    return(false);
                }
            }
            finally
            {
                semaphreSlime.Release();
            }

            return(true);
        }
示例#9
0
        static async Task MainLoop()
        {
            List <BluetoothDevice> btDevices = new List <BluetoothDevice>();

            foreach (var i in devices.Devices)
            {
                if (i.DeviceType == "Bluetooth")
                {
                    BluetoothDevice bd = await BluetoothDevice.FromBluetoothAddressAsync((ulong)long.Parse(i.DeviceAddress));

                    bd.ConnectionStatusChanged += Bd_ConnectionStatusChanged;
                    btDevices.Add(bd);
                    BTtemplateLocations.Add(i.TemplateLocation);
                    BTdeviceNames.Add(i.DeviceName);
                    BTAddresses.Add(bd.BluetoothAddress);
                }
            }

            USBdevicesOLD = GetUSBDevices();
            USBdevicesNEW = GetUSBDevices();

            while (true)
            {
                USBdevicesNEW = GetUSBDevices();

                Console.WriteLine("Checking if a new USB device is connected...");

                if (USBdevicesOLD != USBdevicesNEW)
                {
                    if (USBdevicesOLD.Count > USBdevicesNEW.Count)
                    {
                        Console.WriteLine("Device disconnected");
                    }
                    else if (USBdevicesOLD.Count < USBdevicesNEW.Count)
                    {
                        Console.WriteLine("Device Connected");
                        int index = 0;
                        for (int i = 0; i < USBdevicesNEW.Count; i++)
                        {
                            if (i == USBdevicesNEW.Count - 1)
                            {
                                index = i;
                                break;
                            }
                            else if (USBdevicesNEW[i].DeviceID == USBdevicesOLD[i].DeviceID)
                            {
                                Console.WriteLine("No difference in this interation...");
                            }
                            else
                            {
                                index = i;
                                Console.WriteLine("DIFFERENCE, index is " + i);
                                break;
                            }
                        }
                        int deviceIndex = 0;
                        for (int i = 0; i < devices.Devices.Count; i++)
                        {
                            if (USBdevicesNEW[index].DeviceID == devices.Devices[i].DeviceAddress)
                            {
                                deviceIndex = i;
                            }
                        }
                        StartProcess(devices.Devices[deviceIndex].DeviceName, devices.Devices[deviceIndex].TemplateLocation);
                    }
                }

                USBdevicesOLD = Copy(USBdevicesNEW);

                await Task.Delay(500);
            }
        }