Example #1
0
        //----
        internal List <ServiceRecord> DoSdpQueryWithConnect(
            BluetoothAddress addr, Guid svcClass, bool rfcommOnly)
        {
            var svcUuid = new Structs.uuid_t(svcClass);

            //:TestUuids();

            // Connect
            byte[] target = BluezUtils.FromBluetoothAddress(addr);
            Console.WriteLine("Gonna sdp_connect (SafeHandle)...");
            NativeMethods.SdpSessionSafeHandle session = NativeMethods.sdp_connect(StackConsts.BDADDR_ANY,
                                                                                   target, StackConsts.SdpConnectFlags.SDP_RETRY_IF_BUSY);
            if (session.IsInvalid)
            {
                //BluezUtils.Throw((BluezError)(-1), "sdp_connect");
                const int WSASERVICE_NOT_FOUND = 10108;
                throw new SocketException(WSASERVICE_NOT_FOUND);
            }
            try {
                // Query
                return(DoSdpQuery(session, svcUuid, rfcommOnly));
            } finally {
                session.Close();
            }
        }
Example #2
0
        void InitRadios()
        {
            if (_radioPrimary != null)
            {
                return;
            }
            //
            int idPrimary = NativeMethods.hci_get_route(IntPtr.Zero);
            /////////////////////////////// BluezUtils.CheckAndThrow((BluezError)idPrimary, "hci_get_route");
            var dd = NativeMethods.hci_open_dev(idPrimary);

            Console.WriteLine("InitRadios idPrimary: {0}, dd: {1}", idPrimary, dd);
            _radioPrimary = new BluezRadio(this, dd);
            //
            int maxToTry = 10;
            var list     = new List <IBluetoothRadio>();

            for (int curId = 0; curId < maxToTry; ++curId)
            {
                var curDd = NativeMethods.hci_open_dev(curId);
                var ret   = (BluezError)curDd;
                if (BluezUtils.IsSuccess(ret))
                {
                    Console.WriteLine("InitRadios curDd: {0}", curDd);
                    var curR = new BluezRadio(this, curDd);
                    list.Add(curR);
                }
            }
            _radioList = list;
            Debug.Assert(_radioList.Count >= 1);
        }
Example #3
0
        IBluetoothDeviceInfo[] DoDiscoverDevices(
            int maxDevices, bool authenticated, bool remembered, bool unknown, bool discoverableOnly,
            BluetoothClient.LiveDiscoveryCallback liveDiscoHandler, object liveDiscoState)
        {
            Console.WriteLine("DoDiscoverDevices");
            var discoTime = DateTime.UtcNow;
            List <IBluetoothDeviceInfo> known = new List <IBluetoothDeviceInfo>(); // hack often GC fodder
            var bus = _fcty.BluezDbus;

            known = bus.GetDeviceList_OnDefaultAdapter();
            //
            List <IBluetoothDeviceInfo> inquired = null;

            if (discoverableOnly || unknown)
            {
                inquired = new List <IBluetoothDeviceInfo>();
                double       td         = InquiryLength.TotalSeconds;
                const double Multiplier = 1.25d;
                td /= Multiplier;
                int t = (int)td;
                StackConsts.IREQ_int flags = StackConsts.IREQ_int.IREQ_CACHE_FLUSH;
                //
                var    TypeofItem = typeof(Structs.inquiry_info);
                var    SizeofItem = Marshal.SizeOf(TypeofItem);
                IntPtr pii        = BluezUtils.malloc(maxDevices * SizeofItem);
                try {
                    Console.WriteLine("Gonna hci_inquiry num_rsp: {0}, t: {1} ({2} was {3}) ", maxDevices, t, td, InquiryLength);
                    // TO-DO LAP/IAC: var lap = InquiryAccessCode;
                    //var stackTrace = new StackTrace();
                    //var msg = "Gonna hci_inquiry at: " + stackTrace;
                    //Debug.WriteLine(msg);
                    //Console.WriteLine(msg);
                    int num = NativeMethods.hci_inquiry(_fcty.DevId, t, maxDevices, IntPtr.Zero, ref pii, flags);
                    Console.WriteLine("inquiry num=" + num);
                    //BluezUtils.CheckAndThrow((BluezError)num, "hci_inquiry");
                    BluezUtils.Assert((BluezError)num, "hci_inquiry");
                    //
                    IntPtr pCur = pii;
                    for (int i = 0; i < num; i++)
                    {
                        var cur = (Structs.inquiry_info)Marshal.PtrToStructure(pCur, TypeofItem);
                        var bdi = BluezDeviceInfo.CreateFromInquiry(_fcty, cur);
                        inquired.Add(bdi);
                        pCur = PointerAdd(pCur, SizeofItem);
                    }//for
                } finally {
                    BluezUtils.free(pii);
                }
            }
            //
            var merged = BluetoothClient.DiscoverDevicesMerge(
                authenticated, remembered, unknown,
                known, inquired, discoverableOnly, discoTime);

            return(merged.ToArray());
        }
Example #4
0
 void CloseStack()
 {
     lock (_lock) {
         var hDevD = _hDevDescr;
         if (hDevD != null)
         {
             BluezUtils.close(hDevD.Value);
         }
     }
 }
Example #5
0
        internal static BluezDeviceInfo CreateFromInquiry(BluezFactory fcty, Structs.inquiry_info cur)
        {
            var addr = BluezUtils.ToBluetoothAddress(cur.bdaddr);
            var bdi  = new BluezDeviceInfo(fcty, addr);

            bdi._cod = BluezUtils.ToClassOfDevice(cur.dev_class);
            // Note the devices here aren't 'created' by BlueZ so no ObjectPath.
            // We'll lookup/create the device later if required.
            //
            return(bdi);
        }
        void adapter_DeviceFound(string address, IDictionary <string, object> properties)
        {
            Console.WriteLine("xAdapter_DeviceFound addr: {0}, prop.Count: {1}",
                              address, properties.Count);
            if (!_livePropDumped)
            {
                _livePropDumped = true;
                BluezUtils.DumpKeys(properties);
                // "keys: Address, Class, Icon, RSSI, Name, Alias, LegacyPairing, Paired"
            }
            var bdi = BluezDeviceInfo.CreateFromInquiryLive(_fcty, properties);

            LiveDisco(bdi);
        }
Example #7
0
        internal static NativeMethods.SdpSessionSafeHandle AddRecord(IntPtr rec)
        {
            //Console.Write("Hit return to AddRecord> ");
            //Console.ReadLine();
            //
            BluezError ret;
            var        session = NativeMethods.sdp_connect(
                StackConsts.BDADDR_ANY, StackConsts.BDADDR_LOCAL,
                StackConsts.SdpConnectFlags.SDP_RETRY_IF_BUSY);

            //
            ret = NativeMethods.sdp_record_register(session, rec, 0);
            BluezUtils.CheckAndThrow(ret, "sdp_record_register");

            return(session);
        }
Example #8
0
        internal static BluezDeviceInfo CreateFromStored(BluezFactory fcty,
                                                         ObjectPath objectPath,
                                                         BluetoothAddress address,
                                                         IDictionary <string, object> dbusDeviceDict)
        {
            var bdi = new BluezDeviceInfo(fcty, address);

            if (!_propDumped)
            {
                _propDumped = true;
                BluezUtils.DumpKeys(dbusDeviceDict);
                // "keys: Address, Name, Alias, Class, Icon, Paired, Trusted, Connected, UUIDs, Adapter"
            }
            SetProperties(objectPath, bdi, dbusDeviceDict);
            return(bdi);
        }
Example #9
0
        internal static IntPtr Malloc <T>(ref T val, List <IntPtr> listAllocs) where T : struct
        {
            int    size = Marshal.SizeOf(val);
            IntPtr p    = BluezUtils.malloc(size);

            //Console.WriteLine("Malloc size: {0}, p: {1}", size, p);
            if (p == IntPtr.Zero)
            {
                throw new InvalidOperationException("malloc");
            }
            listAllocs.Add(p);
            Marshal.StructureToPtr(val, p, false);
            var data = Marshal.ReadInt64(p);

            //Console.WriteLine("Malloc data as u64: {0:X}", data);
            return(p);
        }
Example #10
0
        List <ServiceRecord> DoSdpQuery(NativeMethods.SdpSessionSafeHandle session,
                                        Structs.uuid_t svcUuid, bool rfcommOnly)
        {
            var    listAllocs = new List <IntPtr>();
            IntPtr searchList = BluezUtils.sdp_list_append(IntPtr.Zero, svcUuid, listAllocs);

            // Attribute pattern
            IntPtr attridList;

            StackConsts.sdp_attrreq_type_t reqType;
            Console.WriteLine("rfcommOnly: " + rfcommOnly);
            if (rfcommOnly)
            {
                const UInt16 ClassListId  = (ushort)UniversalAttributeId.ServiceClassIdList;     //=1
                const UInt16 ProtoDListId = (ushort)UniversalAttributeId.ProtocolDescriptorList; //=4
                reqType    = StackConsts.sdp_attrreq_type_t.SDP_ATTR_REQ_INDIVIDUAL;
                attridList = BluezUtils.sdp_list_append(IntPtr.Zero, ClassListId, listAllocs);
                attridList = BluezUtils.sdp_list_append(attridList, ProtoDListId, listAllocs);
            }
            else
            {
                const UInt32 allAttributes = 0x0000ffff;
                reqType    = StackConsts.sdp_attrreq_type_t.SDP_ATTR_REQ_RANGE;
                attridList = BluezUtils.sdp_list_append(IntPtr.Zero, allAttributes, listAllocs);
            }

            // Query
            Console.WriteLine("sdp_service_search_attr_req in:"
                              + " {0}, attrid_list: {1}",
                              searchList, attridList);
            IntPtr     pResponseList;
            BluezError ret = NativeMethods.sdp_service_search_attr_req(session,
                                                                       searchList,
                                                                       reqType, attridList,
                                                                       out pResponseList);

            Console.WriteLine("sdp_service_search_attr_req ret: {0}, result: {1}",
                              ret, pResponseList);
            BluezUtils.CheckAndThrow(ret, "sdp_service_search_attr_req");
            //
            var rList = BuildRecordList(pResponseList);

            return(rList);
        }
Example #11
0
        //----
        internal BluezRadio(BluezFactory fcty, int dd)
        {
            _dd = dd;
            Debug.Assert(fcty != null, "ArgNull");
            _fcty = fcty;
            BluezError ret;
            var        bdaddr = BluezUtils.FromBluetoothAddress(BluetoothAddress.None);

            ret = NativeMethods.hci_read_bd_addr(_dd, bdaddr, _fcty.StackTimeout);
            //TODO BluezUtils.CheckAndThrow(ret, "hci_read_bd_addr");
            BluezUtils.Assert(ret, "hci_read_bd_addr");
            if (BluezUtils.IsSuccess(ret))
            {
                _addr = BluezUtils.ToBluetoothAddress(bdaddr);
                Console.WriteLine("Radio SUCCESS, addr: " + _addr);
            }
            else
            {
                // NEVER used EXCEPT in the debugger if we skip the CheckandThrow above.
                _addr = BluetoothAddress.None;
                Console.WriteLine("Radio FAIL, addr: " + _addr);
            }
            _nameTmp = new byte[250];
            //
            // First find _objectPath. In the future we'll be passed this.
            var ax = _fcty.BluezDbus.FindAdapter(_addr, out _objectPath);

            Debug.Assert(_objectPath != null, "BluezRadio..ctor NOT _objectPath!=null");
            //--
            // Set Adapter.
            _adapter = GetAdapter(_objectPath);
            Console.WriteLine("Got adapter at .ctor.3.");
            //
            var    prop   = GetProperties();
            string addrDt = (string)prop[PropertyName.Address];
            var    addrD  = BluetoothAddress.Parse(addrDt);

            Utils.MiscUtils.AssertEquals(addrD, _addr);
            Console.WriteLine("Check DONE Radio..ctor. " + addrD + " vs " + _addr);
        }
Example #12
0
 private void OpenStack()
 {
     lock (_lock) {
         if (_hDevDescr == null)
         {
             BluezError ret;
             int        hDevId = NativeMethods.hci_get_route(IntPtr.Zero); // TODO (BlueZ: open specific interface)
             ret = (BluezError)hDevId;
             BluezUtils.CheckAndThrow(ret, "hci_get_route");
             int hDevDescr = NativeMethods.hci_open_dev(hDevId);
             ret = (BluezError)hDevDescr;
             BluezUtils.CheckAndThrow(ret, "hci_open_dev");
             if (hDevId < 0 || hDevDescr < 0)
             {
                 Debug.Fail("should have been detected above");
                 BluezUtils.Throw(ret, "opening socket");
             }
             _hDevId    = hDevId;
             _hDevDescr = hDevDescr;
             Console.WriteLine("Id: {0}, DD: {1}", DevId, DevDescr);
         }
     }
 }
Example #13
0
        private static void EnsureHasObjectPath(BluezDeviceInfo bdi)
        {
            // A device from discovery (D-Bus or HCI) isn't 'created' by BlueZ
            // so no ObjectPath. So we have to lookup/create the device now.
            if (bdi._dbusPath != null)
            {
                return;
            }
            var pd = bdi._fcty.BluezDbus.FindDeviceProperties_OnDefaultAdapter(bdi._addr, out bdi._dbusPath);

            Debug.Assert((pd == null) == (bdi._dbusPath == null), "Xor! "
                         + Utils.MiscUtils.ToStringQuotedOrNull(pd) + " vs "
                         + Utils.MiscUtils.ToStringQuotedOrNull(bdi._dbusPath));
            if (pd == null)
            {
                // Doesn't exist, so have to create the device now.
                var a = bdi._fcty.BluezDbus.GetDefaultAdapter();
                bdi._dbusPath = a.CreateDevice(BluezUtils.FromBluetoothAddressToDbus(bdi._addr));
            }
            Debug.Assert(bdi._dbusPath != null, "NOT _dbusPath!=null after EnsureHasObjectPath.");
            Console.WriteLine("EnsureHasObjectPath after: "
                              + Utils.MiscUtils.ToStringQuotedOrNull(bdi._dbusPath));
        }
Example #14
0
        //--
        void ReadVersions()
        {
            if (_doneVersions)
            {
                return;
            }
            var vers = new Structs.hci_version(HciVersion.Unknown);
            var ret  = NativeMethods.hci_read_local_version(_dd, ref vers, _fcty.StackTimeout);

            BluezUtils.Assert(ret, "hci_read_local_version");
            if (BluezUtils.IsSuccess(ret))
            {
                _versions = vers;
            }
            _doneVersions = true; // Always set, as unlikely to work second time if failed first time.
            //
            var arr = new byte[8];

            ret = NativeMethods.hci_read_local_features(_dd, arr, _fcty.StackTimeout);
            if (BluezUtils.IsSuccess(ret))
            {
                _lmpFeatures = (LmpFeatures)BitConverter.ToInt64(arr, 0);
            }
        }
Example #15
0
        private static void SetProperties(ObjectPath objectPath,
                                          BluezDeviceInfo bdi, IDictionary <string, object> dbusDeviceDict)
        {
            // Stored:
            //   "keys: Address, Name, Alias, Class, Icon, Paired, Trusted, Connected, UUIDs, Adapter"
            // D-Bus Inquiry event:
            //   "keys: Address, Name, Alias, Class, Icon, Paired; RSSI, LegacyPairing"
            //   ("keys: Address, Class, Icon, RSSI, Name, Alias, LegacyPairing, Paired")
#if DEBUG
            var checkAddr = BluetoothAddress.Parse((string)dbusDeviceDict["Address"]);
            Debug.Assert(bdi._addr == checkAddr, "NOT EQUAL address: " + bdi._addr + " checkAddr: " + checkAddr);
#endif
            bdi._rmbd     = true;
            bdi._dbusPath = objectPath;
            BluezUtils.DebugKeyExists(dbusDeviceDict, "Paired");
            bdi._authd = (bool)dbusDeviceDict["Paired"];
            BluezUtils.DebugKeyExists(dbusDeviceDict, "Connected");
            object value;
            if (dbusDeviceDict.TryGetValue("Connected", out value))
            {
                bdi._connd = (bool)value;
            }
            BluezUtils.DebugKeyExists(dbusDeviceDict, "Alias");
            bdi._name = (string)dbusDeviceDict["Alias"];
            // Seen not present when callled from CreateFromGivenAddress from BtCli.GetRemoteMachineName.
            BluezUtils.DebugKeyExists(dbusDeviceDict, "Class");
            if (dbusDeviceDict.ContainsKey("Class"))
            {
                bdi._cod = new ClassOfDevice((UInt32)dbusDeviceDict["Class"]);
            }
            else
            {
                bdi._cod = new ClassOfDevice(0);
            }
            Console.WriteLine("After SetProperties, _name: " + bdi._name);
        }
 //--------
 static string FromBluetoothAddress(BluetoothAddress address)
 {
     return(BluezUtils.FromBluetoothAddressToDbus(address));
 }