private void Awake()
    {
        if (m_instance != null && m_instance != this)
        {
#if UNITY_EDITOR
            DestroyImmediate(this);
#else
            Destroy(this);
#endif
            return;
        }
        m_instance  = this;
        name        = NAME;
        initialized = false;
#if UNITY_EDITOR
        #if UNITY_ANDROID
        CheckManifest();
        #endif
        #if UNITY_IOS
        if (string.IsNullOrEmpty(bluetoothPeripheralUsageDescription))
        {
            bluetoothPeripheralUsageDescription = _bluetoothPeripheralUsageDescription;
        }
        else
        {
            _bluetoothPeripheralUsageDescription = bluetoothPeripheralUsageDescription;
        }
        CheckDescriptions();
        #endif
#endif
    }
Example #2
0
        public MainPage()
        {
            InitializeComponent();
            devices = new ObservableCollection <VDevice>();
            ble     = CrossBluetoothLE.Current;
            adapter = CrossBluetoothLE.Current.Adapter;
            state   = ble.State;
            DevicesListView.ItemsSource = devices;
            DeviceType = new List <string>()
            {
                "TV",
                "PC",
                "Labtop",
                "MacBook",
                "[AV] Samsung",
                "Charger",
                "JBL",
                "Mi"
            };

            notificationManager = DependencyService.Get <INotificationManager>();
            notificationManager.NotificationReceived += (sender, eventArgs) =>
            {
                var evtData = (NotificationEventArgs)eventArgs;
            };
            LbStatus.Text = "Setup";
            BluetoothStatusChecker();
            ScanAndCheckAsync();
            CheckForAnyNewDevice();
        }
Example #3
0
 private void ClientFindInformationEvent(object sender, FindInformationFoundEventArgs e)
 {
     Console.WriteLine(String.Format("UUID = {0} and Charactaristic Handle = {1}", ByteArrayToHexString(e.uuid), e.chrhandle));
     //TODO if we do things right we will get the tool charactaristiic handle here
     ToolCharactaristic = e.chrhandle;
     connState          = BluetoothState.STATE_FINDING_ATTRIBUTES;
 }
Example #4
0
    private static void SetDialogs(bool skip)
    {
        BluetoothState.CheckManifest();

        var          manifest        = XDocument.Load(Application.dataPath + BluetoothState.MANIFEST_PATH + BluetoothState.MANIFEST_FILE);
        XNamespace   android         = BluetoothState.ANDROID_NAMESPACE;
        const string metadataElement = "meta-data";
        const string metadataName    = "unityplayer.SkipPermissionsDialog";

        var metadata = manifest.Descendants(metadataElement).Where(e => (string)e.Attribute(android + "name") == metadataName).Select(e => e).FirstOrDefault();

        if (metadata == null)
        {
            var application = manifest.Root.Element("application");
            application.Add(new XComment("iBeacon"));
            application.Add(new XElement(metadataElement, new XAttribute(android + "name", metadataName), new XAttribute(android + "value", skip ? "true" : "false")));
        }
        else
        {
            metadata.SetAttributeValue(android + "value", skip ? "true" : "false");
        }

        using (var writer = new StreamWriter(Application.dataPath + BluetoothState.MANIFEST_PATH + BluetoothState.MANIFEST_FILE, false, Encoding.UTF8)) {
            manifest.Save(writer);
        }
    }
Example #5
0
        private string GetStateText(BluetoothState state)
        {
            switch (state)
            {
            case BluetoothState.Unknown:
                return("Unknown BLE state.");

            case BluetoothState.Unavailable:
                return("BLE is not available on this device.");

            case BluetoothState.Unauthorized:
                return("You are not allowed to use BLE.");

            case BluetoothState.TurningOn:
                return("BLE is warming up, please wait.");

            case BluetoothState.On:
                return("BLE is on.");

            case BluetoothState.TurningOff:
                return("BLE is turning off. That's sad!");

            case BluetoothState.Off:
                return("BLE is off. Turn it on!");

            default:
                return("Unknown BLE state.");
            }
        }
 private void OnDestroy()
 {
     if (m_instance == this)
     {
         m_instance = null;
     }
 }
    public static void Init(bool shouldLog)
    {
        if (initialized)
        {
            return;
        }
        if (m_instance == null)
        {
            m_instance = FindObjectOfType <BluetoothState>();
            if (m_instance == null)
            {
                var obj = GameObject.Find(NAME);
                if (obj == null)
                {
                    obj = new GameObject(NAME);
                }
                m_instance = obj.AddComponent <BluetoothState>();
            }
        }
#if !UNITY_EDITOR
        #if UNITY_IOS
        InitBluetoothState(shouldLog);
        #elif UNITY_ANDROID
        GetPlugin().Call("Init", shouldLog);
        #endif
#endif
        initialized = true;
        if (BluetoothStateChangedEvent != null)
        {
            BluetoothStateChangedEvent(GetBluetoothLEStatus());
        }
    }
Example #8
0
        private void Connected(BluetoothSocket bluetoothSocket)
        {
            Log.Debug(Name, $"create ConnectedThread");

            Socket = bluetoothSocket;

            try
            {
                InStream  = bluetoothSocket.InputStream;
                OutStream = bluetoothSocket.OutputStream;
            }
            catch (Java.IO.IOException e)
            {
                Log.Error(Name, "temp sockets not created", e);
                ConnectionLost();
            }

            State = BluetoothState.Connected;

            Log.Info(Name, "BEGIN mConnectedThread");

            CallbackObject callback = new CallbackObject
            {
                Buffer = new byte[1024]
            };

            InStream.BeginRead(callback.Buffer, 0, callback.Length, ReadCallback, callback);
        }
        void OnStateChanged(BluetoothStateChangedArgs args)
        {
            switch (args.NewState)
            {
            case BluetoothState.On:
                _bluetoothState = BluetoothState.On;

                AnimationView.Animation         = "loader.json";
                AnimationView.IsVisible         = true;
                labelStatus.Text                = "En cours...";
                labelStatusDescription.Text     = "Votre Find Me est en cours de connexion";
                successConnectedImage.IsVisible = false;

                // Start scan
                _bleService.TryStartScanning(true);
                return;

            case BluetoothState.Off:
                _bleService.StopScan();

                _bluetoothState = BluetoothState.Off;

                AnimationView.Animation         = "cloud.json";
                AnimationView.IsVisible         = true;
                labelStatus.Text                = "Erreur";
                labelStatusDescription.Text     = "Le bluetooth de cet appareil semble désactivé.";
                successConnectedImage.IsVisible = false;
                buttonRetry.IsVisible           = false;
                buttonStart.IsEnabled           = false;
                return;

            default:
                return;
            }
        }
Example #10
0
        /*******************
         * Tool response events
         *///////////////////
        private void ProcedureCompleteEvent(object sender, ProcedureCompletedEventArgs e)
        {
            Console.WriteLine(String.Format("Got response from tool {0}", e.result));
            //
            //TODO remove the 1,5. I just made that up
            //2,3 doesn't error
            //We can track globally for getting shit done, or per tool
            //use e.connection. That is the key for the dictionary
            if (connState == BluetoothState.STATE_FINDING_SERVICES)
            {
                Byte[] cmd = bglib.BLECommandATTClientFindInformation(e.connection, 2, 3);

                bglib.SendCommand(serialAPI, cmd);

                Console.WriteLine("getting attributes");
            }


            if (connState == BluetoothState.STATE_FINDING_ATTRIBUTES)
            {
                //TODO replace e.connection with the tool connection. pull tool out based on e.connection
                //Also the payload has to mean something, like identify tool
                Byte[] payload = { 0x01, 0x01, 0x01, 0xA0, 0x23, 0x01, 0x00, 0xc7 };
                Byte[] cmd     = bglib.BLECommandATTClientAttributeWrite(e.connection, 0x000F, payload);
                bglib.SendCommand(serialAPI, cmd);
                Console.WriteLine("Wrote data to attribute");
                connState = BluetoothState.STATE_SENDING_COMMAND;
            }
        }
Example #11
0
    private void Start()
    {
        setBeaconPropertiesAtStart();         // please keep here!

        _bluetoothButton.onClick.AddListener(delegate() {
            BluetoothState.EnableBluetooth();
        });
        _bluetoothText = _bluetoothButton.GetComponentInChildren <Text>();
        BluetoothState.BluetoothStateChangedEvent += delegate(BluetoothLowEnergyState state) {
            switch (state)
            {
            case BluetoothLowEnergyState.TURNING_OFF:
            case BluetoothLowEnergyState.TURNING_ON:
                break;

            case BluetoothLowEnergyState.UNKNOWN:
            case BluetoothLowEnergyState.RESETTING:
                SwitchToStatus();
                _statusText.text = "Checking Device…";
                break;

            case BluetoothLowEnergyState.UNAUTHORIZED:
                SwitchToStatus();
                _statusText.text = "You don't have the permission to use beacons.";
                break;

            case BluetoothLowEnergyState.UNSUPPORTED:
                SwitchToStatus();
                _statusText.text = "Your device doesn't support beacons.";
                break;

            case BluetoothLowEnergyState.POWERED_OFF:
                SwitchToMenu();
                _bluetoothButton.interactable = true;
                _bluetoothText.text           = "Enable Bluetooth";
                break;

            case BluetoothLowEnergyState.POWERED_ON:
                SwitchToMenu();
                _bluetoothButton.interactable = false;
                _bluetoothText.text           = "Bluetooth already enabled";
                break;

            case BluetoothLowEnergyState.IBEACON_ONLY:
                SwitchToMenu();
                _bluetoothButton.interactable = false;
                _bluetoothText.text           = "iBeacon only";
                break;

            default:
                SwitchToStatus();
                _statusText.text = "Unknown Error";
                break;
            }
        };
        f_ScrollViewContentRectWidth  = ((RectTransform)go_FoundBeacon.transform).rect.width;
        f_ScrollViewContentRectHeight = ((RectTransform)go_FoundBeacon.transform).rect.height;
        BluetoothState.Init();
    }
Example #12
0
 /// <summary>Raises the <see cref="BluetoothStateChanged" /> event.</summary>
 /// <param name="sender">The object that raised the event.</param>
 /// <param name="btState">Current state of the Bluetooth module</param>
 protected virtual void OnBluetoothStateChanged(Bluetooth sender, BluetoothState btState)
 {
     if (_onBluetoothStateChanged == null)
     {
         _onBluetoothStateChanged = OnBluetoothStateChanged;
     }
     BluetoothStateChanged?.Invoke(sender, btState);
 }
Example #13
0
    private static void InternInit(bool shouldLog)
    {
        if (initialized)
        {
            Scan();
            return;
        }
        if (m_instance == null)
        {
            m_instance = FindObjectOfType <iBeaconReceiver>();
            if (m_instance == null)
            {
                BluetoothState.Init();
                m_instance = GameObject.Find(BluetoothState.NAME).AddComponent <iBeaconReceiver>();
            }
        }
        Stop();
        var state = BluetoothState.GetBluetoothLEStatus();

        if (state == BluetoothLowEnergyState.IBEACON_ONLY)
        {
            if (regions.Any(region => region.beacon.type == BeaconType.iBeacon))
            {
                Debug.LogWarning(MessageiBeaconOnly);
            }
            else
            {
                throw new iBeaconException(MessageiBeaconOnly);
            }
        }
        else if (state != BluetoothLowEnergyState.POWERED_ON)
        {
            BluetoothState.EnableBluetooth();
            if (BluetoothState.GetBluetoothLEStatus() != BluetoothLowEnergyState.POWERED_ON)
            {
                throw new iBeaconException("Bluetooth is off and could not be enabled.");
            }
        }
#if !UNITY_EDITOR
        #if UNITY_IOS
        if (!InitReceiver(iBeaconRegion.regionsToString(m_instance._regions), shouldLog))
        {
            throw new iBeaconException("Receiver initialization failed.");
        }
        #elif UNITY_ANDROID
        GetPlugin().Call(
            "Init",
            iBeaconRegion.regionsToString(m_instance._regions),
            Mathf.FloorToInt(m_instance._detectionTimespan * 1000),
            Mathf.FloorToInt(m_instance._scanPeriod * 1000),
            Mathf.FloorToInt(m_instance._betweenScanPeriod * 1000),
            shouldLog);
        #endif
#endif
        initialized = true;
        Scan();
    }
    private void Start()
    {
        _bluetoothButton.onClick.AddListener(delegate() {
            BluetoothState.EnableBluetooth();
        });
        _bluetoothText = _bluetoothButton.GetComponentInChildren <Text> ();
        BluetoothState.BluetoothStateChangedEvent += delegate(BluetoothLowEnergyState state) {
            switch (state)
            {
            case BluetoothLowEnergyState.TURNING_OFF:
            case BluetoothLowEnergyState.TURNING_ON:
                break;

            case BluetoothLowEnergyState.UNKNOWN:
            case BluetoothLowEnergyState.RESETTING:
                break;

            case BluetoothLowEnergyState.UNAUTHORIZED:
                break;

            case BluetoothLowEnergyState.UNSUPPORTED:
                break;

            case BluetoothLowEnergyState.POWERED_OFF:
                _bluetoothButton.interactable = true;
                break;

            case BluetoothLowEnergyState.POWERED_ON:
                _bluetoothButton.interactable = false;
                break;

            default:
                break;
            }
        };
        BluetoothState.Init();

        _camera   = GameObject.FindGameObjectWithTag("MainCamera");//
        posCamera = new Vector3(0, 0, -9);
        MapImage  = GameObject.Find("Map").transform.Find("Map_Image").gameObject;
        btnGetYokai.transform.GetChild(0).GetComponent <Text>().text     = ApplicationData.GetLocaleText(LocaleType.ButtonToSeal);
        btnGetYokai.transform.GetChild(0).GetComponent <Text>().fontSize = ApplicationData.SetFontSize(LocaleType.ButtonToSeal);
        btnSuccess.transform.GetChild(0).GetComponent <Text>().text      = ApplicationData.GetLocaleText(LocaleType.ButtonGetSuccessful);
        btnSuccess.transform.GetChild(0).GetComponent <Text>().fontSize  = ApplicationData.SetFontSize(LocaleType.ButtonGetSuccessful);

        if (ApplicationData.SelectedLanguage == LanguageType.Thai)
        {
            btnGetYokai.transform.GetChild(0).GetComponent <Text> ().font = ApplicationData.GetFont(4);
            btnSuccess.transform.GetChild(0).GetComponent <Text>().font   = ApplicationData.GetFont(4);
        }
        else
        {
            btnGetYokai.transform.GetChild(0).GetComponent <Text> ().font = ApplicationData.GetFont(2);
            btnSuccess.transform.GetChild(0).GetComponent <Text>().font   = ApplicationData.GetFont(2);
        }
    }
Example #15
0
 /// <summary>
 /// Raises the <see cref="BluetoothStateChanged"/> event.
 /// </summary>
 /// <param name="sender">The object that raised the event.</param>
 /// <param name="btState">Current state of the Bluetooth module</param>
 protected virtual void OnBluetoothStateChanged(Bluetooth sender, BluetoothState btState)
 {
     if (onBluetoothStateChanged == null)
     {
         onBluetoothStateChanged = new BluetoothStateChangedHandler(OnBluetoothStateChanged);
     }
     if (Program.CheckAndInvoke(BluetoothStateChanged, onBluetoothStateChanged, sender, btState))
     {
         BluetoothStateChanged(sender, btState);
     }
 }
Example #16
0
    private static void InternInit(bool shouldLog)
    {
        if (initialized)
        {
            Transmit();
            return;
        }
        if (m_instance == null)
        {
            m_instance = FindObjectOfType <iBeaconServer>();
            if (m_instance == null)
            {
                BluetoothState.Init();
                m_instance = GameObject.Find(BluetoothState.NAME).AddComponent <iBeaconServer>();
            }
        }
        StopTransmit();
        if (BluetoothState.GetBluetoothLEStatus() != BluetoothLowEnergyState.POWERED_ON)
        {
            BluetoothState.EnableBluetooth();
            if (BluetoothState.GetBluetoothLEStatus() != BluetoothLowEnergyState.POWERED_ON)
            {
                throw new iBeaconException("Bluetooth is off and could not be enabled.");
            }
        }
        if (!checkTransmissionSupported(shouldLog))
        {
            throw new iBeaconException("This device does not support transmitting as a beacon.");
        }
#if !UNITY_EDITOR
        var sb = new StringBuilder(JsonUtility.ToJson(m_instance._region));
        sb.Insert(sb.Length - 1, ",\"_txPower\":");
        sb.Insert(sb.Length - 1, m_instance._txPower);
#if UNITY_IOS
        if (!InitBeaconServer(sb.ToString(), shouldLog))
        {
            throw new iBeaconException("Server initialization failed.");
        }
#elif UNITY_ANDROID
        sb.Insert(sb.Length - 1, ",\"_powerLevel\":");
        sb.Insert(sb.Length - 1, (int)m_instance._powerLevel);
        sb.Insert(sb.Length - 1, ",\"_mode\":");
        sb.Insert(sb.Length - 1, (int)m_instance._mode);
        if (!GetPlugin().Call <bool>("Init", sb.ToString(), shouldLog))
        {
            throw new iBeaconException("Server initialization failed.");
        }
#endif
#endif
        initialized = true;
        Transmit();
    }
Example #17
0
        public BluetoothDevice(DeviceCreationInfo creationInfo)
            : base(new BluetoothState(), creationInfo)
        {
            BluetoothState state = (BluetoothState)mState;

            state.BtName = creationInfo.Configuration.btname;

            mService = (BluetoothService)creationInfo.ServiceManager.GetService(typeof(BluetoothService));
            if (mService != null)
            {
                mService.AddDevice(this);
            }
        }
Example #18
0
        private void BglibOnBleEventAttClientGroupFound(object sender, GroupFoundEventArgs e)
        {
            String log = String.Format("ble_evt_attclient_group_found: connection={0}, start={1}, end={2}, uuid=[ {3}]" + Environment.NewLine,
                                       e.connection,
                                       e.start,
                                       e.end,
                                       ByteArrayToHexString(e.uuid)
                                       );

            Console.WriteLine(log);
            //TODO capture start and end for finding the attribute
            Console.WriteLine(String.Format("Services start {0} and end {1}", e.start, e.end));
            connState = BluetoothState.STATE_FINDING_SERVICES;
        }
Example #19
0
        public App()
        {
            InitializeComponent();

            ble                         = CrossBluetoothLE.Current;
            adapter                     = ble.Adapter;
            bleState                    = ble.State;
            adapter.ScanTimeout         = 30000;
            ble.StateChanged           += Ble_StateChanged;
            adapter.DeviceDiscovered   += Adapter_DeviceDiscovered;
            adapter.ScanTimeoutElapsed += Adapter_ScanTimeoutElapsed;
            App.bleInit();
            DependencyService.Register <MockDataStore>();
            MainPage = new MainPage();
        }
Example #20
0
        public void OnStatusUpdate(bool inRange, bool initialState = false)
        {
            BluetoothState state = (BluetoothState)mState;

            state.InRange = inRange;

            if (initialState)
            {
                return;
            }

            if (OnDeviceEvent != null)
            {
                OnDeviceEvent(this, new BluetoothDeviceEvent(this, state.InRange));
            }
        }
Example #21
0
    void Start()
    {
        // Enable Bluetooth
        BluetoothState.Init();
        BluetoothState.EnableBluetooth();

        //Init Pop Up
        PopUpDetected.active = false;
        PopUpLoading.active  = false;

        // Auto Region
        s_Region = "Indonesia";

        // Button Listener
        ScanBtn.onClick.AddListener(startScan);
    }
Example #22
0
    private void Start()
    {
        BluetoothState.BluetoothStateChangedEvent += delegate(BluetoothLowEnergyState state) {
            switch (state)
            {
            case BluetoothLowEnergyState.TURNING_OFF:
            case BluetoothLowEnergyState.TURNING_ON:
                break;

            case BluetoothLowEnergyState.UNKNOWN:
            case BluetoothLowEnergyState.RESETTING:
//				SwitchToStatus();
//				_statusText.text = "Checking Device…";
                break;

            case BluetoothLowEnergyState.UNAUTHORIZED:
//				SwitchToStatus();
//				_statusText.text = "You don't have the permission to use beacons.";
                break;

            case BluetoothLowEnergyState.UNSUPPORTED:
//				SwitchToStatus();
//				_statusText.text = "Your device doesn't support beacons.";
                break;

            case BluetoothLowEnergyState.POWERED_OFF:
//				SwitchToMenu();
//				_bluetoothButton.interactable = true;
//				_bluetoothText.text = "Enable Bluetooth";
                break;

            case BluetoothLowEnergyState.POWERED_ON:
//				SwitchToMenu();
//				_bluetoothButton.interactable = false;
//				_bluetoothText.text = "Bluetooth already enabled";
                break;

            default:
//				SwitchToStatus();
//				_statusText.text = "Unknown Error";
                break;
            }
        };

        BluetoothState.Init();
    }
Example #23
0
        private void RegisterStateChangedEvent()
        {
            _stateChangedCallback = (int result, int state, IntPtr userData) =>
            {
                if (_stateChanged != null)
                {
                    BluetoothState st  = (BluetoothState)state;
                    BluetoothError res = (BluetoothError)result;
                    _stateChanged(null, new StateChangedEventArgs(res, st));
                }
            };
            int ret = Interop.Bluetooth.SetStateChangedCallback(_stateChangedCallback, IntPtr.Zero);

            if (ret != (int)BluetoothError.None)
            {
                Log.Error(Globals.LogTag, "Failed to set state changed callback, Error - " + (BluetoothError)ret);
            }
        }
        void OnScanTimeoutElapsed()
        {
            _bluetoothState = _bleService._bleInstance.State;

            // Check state because task not canceled when desactivate ble on scan
            if (_bluetoothState == BluetoothState.On && _isConnected == false)
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    AnimationView.Animation         = "cloud.json";
                    AnimationView.IsVisible         = true;
                    labelStatus.Text                = "Non détecté";
                    labelStatusDescription.Text     = "Votre Find Me n'a pas pu être détecté...";
                    successConnectedImage.IsVisible = false;
                    buttonRetry.IsVisible           = true;
                });
            }
        }
Example #25
0
    private void Awake()
    {
        if (m_instance != null && m_instance != this)
        {
#if UNITY_EDITOR
            DestroyImmediate(this);
#else
            Destroy(this);
#endif
            return;
        }
        m_instance  = this;
        name        = NAME;
        initialized = false;
#if UNITY_EDITOR
        CheckManifest();
#endif
    }
Example #26
0
        /// <summary>
        /// Detects current Bluetooth requestedState
        /// </summary>
        private async void DetectBluetoothState(Action <BluetoothState> action)
        {
            BluetoothState state = BluetoothState.Enabled;

            try
            {
                PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
                var peers = await PeerFinder.FindAllPeersAsync();
            }
            catch (Exception ex)
            {
                if ((uint)ex.HResult == 0x8007048F)
                {
                    state = BluetoothState.Disabled;
                }
            }

            action(state);
        }
    /* Internal Functions */
    internal static BluetoothState RemoteManagerBluetoothState()
    {
        if (Application.platform != RuntimePlatform.IPhonePlayer && Application.platform != RuntimePlatform.OSXPlayer)
        {
            return(BluetoothState.Unknown);
        }

        string identifier = Guid.NewGuid().ToString();

        BluetoothState bluetoothState = BluetoothState.Unknown;

        intActions[identifier] = (state) => {
            bluetoothState = (BluetoothState)state;
        };

        MRRemoteManagerBluetoothState(identifier, IntCallback);

        return(bluetoothState);
    }
Example #28
0
        private bool Connect(BluetoothDevice device)
        {
            BluetoothSocket bluetoothSocket = null;

            try
            {
                bluetoothSocket = device.CreateRfcommSocketToServiceRecord(UUID);
            }
            catch (Java.IO.IOException e)
            {
                Log.Error(Name, "create() failed", e);
                Functions.ShowToast($"BLINK와의 연결에 실패했습니다.");
                return(false);
            }
            State = BluetoothState.Connecting;

            adapter.CancelDiscovery();

            try
            {
                bluetoothSocket.Connect();
            }
            catch (Java.IO.IOException)
            {
                try
                {
                    bluetoothSocket.Close();
                }
                catch (Java.IO.IOException e)
                {
                    Log.Error(Name, $"unable to close() socket during connection failure.", e);
                    Functions.ShowToast($"BLINK와의 연결에 실패했습니다.");
                    return(false);
                }
                ConnectionFailed();
                Functions.ShowToast($"BLINK와의 연결에 실패했습니다.");
                return(false);
            }

            Connected(bluetoothSocket);
            return(true);
        }
Example #29
0
    private static void InternInit(bool shouldLog)
    {
        if (initialized)
        {
            Scan();
            return;
        }
        if (m_instance == null)
        {
            m_instance = FindObjectOfType <iBeaconReceiver>();
            if (m_instance == null)
            {
                BluetoothState.Init();
                m_instance = GameObject.Find(BluetoothState.NAME).AddComponent <iBeaconReceiver>();
            }
        }
        Stop();
        if (BluetoothState.GetBluetoothLEStatus() != BluetoothLowEnergyState.POWERED_ON)
        {
            BluetoothState.EnableBluetooth();
            if (BluetoothState.GetBluetoothLEStatus() != BluetoothLowEnergyState.POWERED_ON)
            {
                throw new iBeaconException("Bluetooth is off and could not be enabled.");
            }
        }
#if !UNITY_EDITOR
        #if UNITY_IOS
        if (!InitReceiver(iBeaconRegion.regionsToString(m_instance._regions), shouldLog))
        {
            throw new iBeaconException("Receiver initialization failed.");
        }
        #elif UNITY_ANDROID
        GetPlugin().Call(
            "Init",
            iBeaconRegion.regionsToString(m_instance._regions),
            Mathf.FloorToInt(m_instance._androidDetectionTimespan * 1000),
            shouldLog);
        #endif
#endif
        initialized = true;
        Scan();
    }
Example #30
0
 public void checkBLStatus(BluetoothState bluetoothState)
 {
     if (bluetoothState == BluetoothState.TurningOff || bluetoothState == BluetoothState.Off)
     {
         pnlActivarBL.IsVisible = true;
         pnlGeneral.IsVisible   = false;
         pnlCarga.IsVisible     = false;
         lblStatusBL.Text       = "Bluetooth DESACTIVADO";
     }
     else if (bluetoothState == BluetoothState.Unauthorized || bluetoothState == BluetoothState.Unavailable || bluetoothState == BluetoothState.Unknown)
     {
         pnlActivarBL.IsVisible = true;
         pnlGeneral.IsVisible   = false;
         pnlCarga.IsVisible     = false;
         lblStatusBL.Text       = "La aplicación no tiene permisos para acceder al bluetooth o el bluetooth no está disponible";
     }
     else if (bluetoothState == BluetoothState.On)
     {
         pnlActivarBL.IsVisible = false;
         pnlGeneral.IsVisible   = true;
         pnlCarga.IsVisible     = false;
     }
 }
 public void Initialize()
 {
     InitializeNative();
     State = GetInitialStateNative();
 }
Example #32
0
 /// <summary>
 /// Disables Bluetooth adapter
 /// </summary>
 /// <param name="options"></param>
 public void disable(string options)
 {
     this.requestedState = BluetoothState.Disabled;
     this.ChangeBluetoothState();            
 }     
 private void UpdateState(BluetoothState state)
 {
     State = state;
 }
Example #34
0
 public BluetoothState(BluetoothState state)
     : base(state)
 {
     BtName = state.BtName;
     InRange = state.InRange;
 }
 /// <summary>
 /// Raises the <see cref="BluetoothStateChanged"/> event.
 /// </summary>
 /// <param name="sender">The object that raised the event.</param>  
 /// <param name="btState">Current state of the Bluetooth module</param>
 protected virtual void OnBluetoothStateChanged(Bluetooth sender, BluetoothState btState)
 {
     if (onBluetoothStateChanged == null) onBluetoothStateChanged = new BluetoothStateChangedHandler(OnBluetoothStateChanged);
     if (Program.CheckAndInvoke(BluetoothStateChanged, onBluetoothStateChanged, sender, btState))
     {
         BluetoothStateChanged(sender, btState);
     }
 }
 public BluetoothStateChangedArgs(BluetoothState oldState, BluetoothState newState)
 {
     OldState = oldState;
     NewState = newState;
 }