Ejemplo n.º 1
0
        public void Start(TracingInformation tracingInformation)
        {
            if (tracingInformation == null || _enabled)
            {
                return;
            }

            _tracingInformation = tracingInformation;
            _peripheralManager.RemoveAllServices();
            CBUUID uuidService        = CBUUID.FromString(tracingInformation.ServiceId);
            CBUUID uuidCharacteristic = CBUUID.FromString(tracingInformation.CharacteristicId);
            var    data           = NSData.FromArray(PayloadFormatter.GetBytesToSend(new PackageData(tracingInformation.DeviceId)));
            var    characteristic = new CBMutableCharacteristic(uuidCharacteristic, CBCharacteristicProperties.Read, data, CBAttributePermissions.Readable);
            var    service        = new CBMutableService(uuidService, true);

            service.Characteristics = new CBCharacteristic[] { characteristic };
            _peripheralManager.AddService(service);
            StartAdvertisingOptions advData = new StartAdvertisingOptions {
                ServicesUUID = new CBUUID[] { uuidService }
            };

            _peripheralManager.StartAdvertising(advData);
            TracingState.Instance.SetAdvertisingState(true);
            _enabled = true;
            _logger.LogDebug("Advertising starting. DeviceId: " + _tracingInformation.DeviceId);
        }
        public void StartAdvertising(CBPeripheralManager peripheralManager)
        {
            var userSettings = new UserSettings();
            var advertisingData = CreateAdvertisementData(userSettings.Name, BluetoothServiceUuid.ChatServiceUuid);

            peripheralManager.StartAdvertising(advertisingData);
        }
Ejemplo n.º 3
0
        public async Task StartAdvertising(string localName, List <IService> services)
        {
            if (_peripheralManager.State != CBPeripheralManagerState.PoweredOn)
            {
                throw new InvalidStateException((ManagerState)_peripheralManager.State);
            }

            var cbuuIdArray = new NSMutableArray();
            var optionsDict = new NSMutableDictionary();

            if (services != null)
            {
                foreach (Service service in services)
                {
                    cbuuIdArray.Add(CBUUID.FromString(service.Uuid));
                    //_peripheralManager.AddService((CBMutableService) service.NativeService);
                }
                optionsDict[CBAdvertisement.DataServiceUUIDsKey] = cbuuIdArray;
            }


            if (localName != null)
            {
                optionsDict[CBAdvertisement.DataLocalNameKey] = new NSString(localName);
            }

            _peripheralManager.StartAdvertising(optionsDict);
        }
Ejemplo n.º 4
0
        public void StartBroadcasting()
        {
            CLBeaconRegion region = Helpers.CreateRegion(new NSUuid("8E6DBFBB-489D-418A-9560-1BA1CE6301AA"), new NSNumber(5050), new NSNumber(1234));

            if (region != null)
            {
                peripheralManager.StartAdvertising(region.GetPeripheralData(new NSNumber(50)));
            }
        }
Ejemplo n.º 5
0
        public void Start(BleDevice device, BleCharacteristic[] characteristics)
        {
            string dataServiceUUIDsKey               = "71DA3FD1-7E10-41C1-B16F-4430B5060000";
            string customBeaconServiceUUIDsKey       = "71DA3FD1-7E10-41C1-B16F-4430B5060001";
            string customBeaconCharacteristicUUIDKey = "71DA3FD1-7E10-41C1-B16F-4430B5060002";
            string identifier = "71DA3FD1-7E10-41C1-B16F-4430B5060003";

            peripheralManager = new CBPeripheralManager(this, DispatchQueue.DefaultGlobalQueue);
            peripheralManager.AdvertisingStarted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("*** BleServer -> Advertising error: {0}", e.Error.Description));
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("*** BleServer -> We are advertising.");
                }
            };


            var customBeaconServiceUUID        = CBUUID.FromString(customBeaconServiceUUIDsKey);
            var customBeaconCharacteristicUUID = CBUUID.FromString(customBeaconCharacteristicUUIDKey);

            var service  = new CBMutableService(customBeaconServiceUUID, true);
            var dataUUID = NSData.FromString(identifier, NSStringEncoding.UTF8);

            var characteristic = new CBMutableCharacteristic(
                customBeaconCharacteristicUUID,
                CBCharacteristicProperties.Read,
                dataUUID,
                CBAttributePermissions.Readable);

            service.Characteristics = new CBCharacteristic[] { characteristic };
            peripheralManager.AddService(service);

            var localName = new NSString("CustomBeacon");

            //var advertisingData = new NSDictionary( CBAdvertisement.DataLocalNameKey, localName,
            //    CBAdvertisement.IsConnectable, false,
            //    CBAdvertisement.DataManufacturerDataKey, CBUUID.FromString(dataServiceUUIDsKey),
            //    CBAdvertisement.DataServiceUUIDsKey, CBUUID.FromString(dataServiceUUIDsKey));

            //peripheralManager.StartAdvertising(advertisingData);



            var UUI = new CBUUID[] { CBUUID.FromString("71DA3FD1-7E10-41C1-B16F-4430B5060000") };

            NSArray arry = NSArray.FromObjects(UUI);
            var     test = NSObject.FromObject(arry);
            var     ad   = new NSDictionary(CBAdvertisement.DataServiceUUIDsKey, test);

            peripheralManager.StartAdvertising(ad);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// iBeacon発信開始処理(UUID、Major、Minorを直指定して発信)
        /// </summary>
        /// <param name="uuid">UUID</param>
        /// <param name="major">Major</param>
        /// <param name="minor">Minor</param>
        public void StartTransmission(Guid uuid, ushort major, ushort minor, sbyte txPower)
        {
            // BLE発信制御クラスに渡すためのiBeacon定義を作成する。
            NSUuid         nsUuid         = new NSUuid(uuid.ToString());
            CLBeaconRegion region         = new CLBeaconRegion(nsUuid, major, minor, uuid.ToString());
            NSNumber       nsnumTxPower   = new NSNumber(txPower);
            NSDictionary   peripheralData = region.GetPeripheralData(nsnumTxPower);

            // iBeaconの発信を開始する。
            _peripheralManager.StartAdvertising(peripheralData);
        }
Ejemplo n.º 7
0
        public void speak()
        {
            var monkeyUUID    = new NSUuid(uuid_person);
            var beaconRegion2 = new CLBeaconRegion(monkeyUUID, "Person");

            //power - the received signal strength indicator (RSSI) value (measured in decibels) of the beacon from one meter away
            var power = new NSNumber(-59);
            NSMutableDictionary peripheralData = beaconRegion2.GetPeripheralData(power);

            peripheralDelegate = new BTPeripheralDelegate();
            peripheralMgr      = new CBPeripheralManager(peripheralDelegate, DispatchQueue.DefaultGlobalQueue);

            peripheralMgr.StartAdvertising(peripheralData);
        }
Ejemplo n.º 8
0
 internal void PeripheralManagerDidUpdateState()
 {
     if (peripheralManager.state == CBPeripheralManagerState.PoweredOn)
     {
         Log("Powered ON.");
         Dictionary <object, object> data = beaconRegion.PeripheralData(-50);
         peripheralManager.StartAdvertising(data);
         Log("Advertising.");
     }
     else if (peripheralManager.state == CBPeripheralManagerState.PoweredOff)
     {
         Log("Powered OFF.");
         peripheralManager.StopAdvertising();
     }
 }
Ejemplo n.º 9
0
        public void StartAdvertisingBeacons(UserDataModel userData)
        {
            _userData = userData;

            if (_beaconTransmitter.State < CBPeripheralManagerState.PoweredOn)
            {
                System.Diagnostics.Debug.WriteLine("Bluetooth must be enabled");
                // new UIAlertView("Bluetooth must be enabled", "To configure your device as a beacon", null, "OK", null).Show();
                return;
            }

            CLBeaconRegion region  = new CLBeaconRegion(new NSUuid(AppConstants.iBeaconAppUuid), ushort.Parse(_userData.Major), ushort.Parse(_userData.Minor), _userData.UserUuid);
            NSNumber       txPower = new NSNumber(-59);

            _beaconTransmitter.StartAdvertising(region.GetPeripheralData(txPower));
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			beaconUUID = new NSUuid (uuid);
			beaconRegion = new CLBeaconRegion (beaconUUID, beaconMajor, beaconMinor, beaconId);



			//power - the received signal strength indicator (RSSI) value (measured in decibels) of the beacon from one meter away
			var power = new NSNumber (-59);

			NSMutableDictionary peripheralData = beaconRegion.GetPeripheralData (power);
			peripheralDelegate = new BTPeripheralDelegate ();
			peripheralMgr = new CBPeripheralManager (peripheralDelegate, DispatchQueue.DefaultGlobalQueue);

			peripheralMgr.StartAdvertising (peripheralData);
		}
Ejemplo n.º 11
0
        public RemoteXServerForIos()
        {
            CBUUID[] cBUUIDs = new CBUUID[1];
            CBUUID   cBUUID  = CBUUID.FromString("AD86E9A5-AB95-4D75-A4BC-2A969F26E028");

            cBPeripheralManager = new CBPeripheralManager();
            remoteService       = new CBMutableService(cBUUID, true);
            cBPeripheralManager.AddService(remoteService);
            cBUUIDs.Append(cBUUID);
            var advertisingOption = new StartAdvertisingOptions
            {
                LocalName = "RemoteX Controller"
            };

            advertisingOption.ServicesUUID = cBUUIDs;
            cBPeripheralManager.StartAdvertising(advertisingOption);
        }
 public override void StateUpdated(CBPeripheralManager peripheral)
 {
     if (peripheral.State == CBPeripheralManagerState.PoweredOn)
     {
         Console.WriteLine("powered on");
         peripheral.StartAdvertising(beaconPeripheralRegion);
     }
     else if (peripheral.State == CBPeripheralManagerState.PoweredOff)
     {
         Console.WriteLine("powered off");
         peripheral.StopAdvertising();
     }
     else if (peripheral.State == CBPeripheralManagerState.Unsupported)
     {
         Console.WriteLine("unsupported");
     }
 }
Ejemplo n.º 13
0
        void HandleTouchDown(object sender, EventArgs e)
        {
            if (segBeacon.SelectedSegment == 0) {
                var power = new NSNumber (-59);
                NSMutableDictionary peripheralData = bRegion.GetPeripheralData (power);
                pDelegate = new BTPDelegate ();
                pManager = new CBPeripheralManager (pDelegate, DispatchQueue.DefaultGlobalQueue);

                pManager.StartAdvertising (peripheralData);
            } else {

                locManager = new CLLocationManager ();

                locManager.RegionEntered += (object s, CLRegionEventArgs ea) => {
                    if (ea.Region.Identifier == "beacon") {
                        UILocalNotification notification = new UILocalNotification () { AlertBody = "Entering beacon region!" };
                        UIApplication.SharedApplication.PresentLocationNotificationNow (notification);
                    }
                };

                locManager.DidRangeBeacons += (object s, CLRegionBeaconsRangedEventArgs ea) => {
                    if (ea.Beacons.Length > 0) {

                        CLBeacon beacon = ea.Beacons [0];
                        switch (beacon.Proximity) {
                        case CLProximity.Immediate:
                            this.View.BackgroundColor = UIColor.Green;
                            break;
                        case CLProximity.Near:
                            this.View.BackgroundColor = UIColor.Yellow;
                            break;
                        case CLProximity.Far:
                            this.View.BackgroundColor = UIColor.Red;
                            break;
                        case CLProximity.Unknown:
                            this.View.BackgroundColor = UIColor.Black;
                            break;
                        }
                    }
                };

                locManager.StartMonitoring (bRegion);
                locManager.StartRangingBeacons (bRegion);
            }
        }
Ejemplo n.º 14
0
        public void Start_old(BleDevice device, BleCharacteristic[] characteristics)
        {
            try
            {
                if (device == null)
                {
                    throw new Exception("Could not initialize server without a service description.");
                }
                if ((characteristics == null) || (characteristics.Length == 0))
                {
                    throw new Exception("Could not initialize server without characteristic descriptions.");
                }

                //  setup a peripheral manager
                _PeripheralManager = new CBPeripheralManager();
                var uuid = CBUUID.FromPartial(device.GuidValue);
                System.Diagnostics.Debug.WriteLine(string.Format("*** BleServer.Start - Device Guid: {0}", uuid.Uuid));
                _Service                 = new CBMutableService(uuid, true);
                _Characteristics         = characteristics.Select(ch => new CBMutableCharacteristic(CBUUID.FromPartial(ch.GuidValue), CBCharacteristicProperties.Read, null, CBAttributePermissions.Readable)).ToList();
                _Service.Characteristics = _Characteristics.ToArray();

                //  register services
                _PeripheralManager.AddService(_Service);
                _PeripheralManager.AdvertisingStarted += (sender, e) =>
                {
                    if (e.Error != null)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("*** BleServer -> Advertising error: {0}", e.Error.Description));
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("*** BleServer -> We are advertising.");
                    }
                };

                //  advertise services
                var opt = new StartAdvertisingOptions();
                opt.ServicesUUID = new CBUUID[] { _Service.UUID };
                _PeripheralManager.StartAdvertising(opt);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("*** BleServer.Start - Exception: {0}", ex));
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            var uuid = new NSUuid ("A1F30FF0-0A9F-4DE0-90DA-95F88164942E");
            var beaconId = "iOSBeacon";
            var beaconRegion = new CLBeaconRegion (uuid, beaconId) {
                NotifyEntryStateOnDisplay = true,
                NotifyOnEntry = true,
                NotifyOnExit = true
            };

            var peripheralData = beaconRegion.GetPeripheralData (new NSNumber (-59));

            peripheralDelegate = new BTPeripheralDelegate ();
            peripheralMgr = new CBPeripheralManager (peripheralDelegate, DispatchQueue.DefaultGlobalQueue);
            peripheralMgr.StartAdvertising (peripheralData);
        }
Ejemplo n.º 16
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            beaconUUID   = new NSUuid(uuid);
            beaconRegion = new CLBeaconRegion(beaconUUID, beaconMajor, beaconMinor, beaconId);



            //power - the received signal strength indicator (RSSI) value (measured in decibels) of the beacon from one meter away
            var power = new NSNumber(-59);

            NSMutableDictionary peripheralData = beaconRegion.GetPeripheralData(power);

            peripheralDelegate = new BTPeripheralDelegate();
            peripheralMgr      = new CBPeripheralManager(peripheralDelegate, DispatchQueue.DefaultGlobalQueue);

            peripheralMgr.StartAdvertising(peripheralData);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var uuid         = new NSUuid("A1F30FF0-0A9F-4DE0-90DA-95F88164942E");
            var beaconId     = "iOSBeacon";
            var beaconRegion = new CLBeaconRegion(uuid, beaconId)
            {
                NotifyEntryStateOnDisplay = true,
                NotifyOnEntry             = true,
                NotifyOnExit = true
            };

            var peripheralData = beaconRegion.GetPeripheralData(new NSNumber(-59));

            peripheralDelegate = new BTPeripheralDelegate();
            peripheralMgr      = new CBPeripheralManager(peripheralDelegate, DispatchQueue.DefaultGlobalQueue);
            peripheralMgr.StartAdvertising(peripheralData);
        }
        public override void ServiceAdded(CBPeripheralManager peripheral, CBService service, NSError error)
        {
            if (error == null)
            {
                SensusServiceHelper.Get().Logger.Log("Added service.", LoggingLevel.Normal, GetType());

                try
                {
                    peripheral.StartAdvertising(new NSDictionary(CBAdvertisement.DataServiceUUIDsKey, NSArray.FromObjects(_probe.DeviceIdService.UUID)));
                }
                catch (Exception ex)
                {
                    SensusServiceHelper.Get().Logger.Log("Exception while starting advertising:  " + ex.Message, LoggingLevel.Normal, GetType());
                }
            }
            else
            {
                SensusServiceHelper.Get().Logger.Log("Error adding service:  " + error, LoggingLevel.Normal, GetType());
            }
        }
Ejemplo n.º 19
0
        public void AdvertiseData()
        {
            var uui      = new CBUUID[] { CBUUID.FromString("E20A39F4-73F5-4BC4-A12F-17D1AD07A961") };
            var nsArray  = NSArray.FromObjects(uui);
            var nsObject = NSObject.FromObject(nsArray);

            var manufacturerDataBytes = new byte[6] {
                5, 255, 76, 0, 25, 35
            };

            var advertisementData = new NSDictionary(
                CBAdvertisement.DataLocalNameKey, "id1",
                CBAdvertisement.DataServiceUUIDsKey, nsObject,
                CBAdvertisement.DataManufacturerDataKey, NSData.FromArray(manufacturerDataBytes),
                CBAdvertisement.DataServiceDataKey, "Sent data");

            if (cbPeriphMang.Advertising)
            {
                cbPeriphMang.StopAdvertising();
            }

            cbPeriphMang.StartAdvertising(advertisementData);
        }
Ejemplo n.º 20
0
        private void DidStateUpdated(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("DidStateUpdated");
            CBPeripheralManager trasmitter = sender as CBPeripheralManager;

            if (trasmitter.State < CBPeripheralManagerState.PoweredOn)
            {
                System.Diagnostics.Debug.WriteLine("Bluetooth must be enabled");
                // new UIAlertView("Bluetooth must be enabled", "To configure your device as a beacon", null, "OK", null).Show();
                return;
            }

            if (_transmitterFlg)
            {
                CLBeaconRegion region  = new CLBeaconRegion(new NSUuid(AppConstants.iBeaconAppUuid), ushort.Parse(_userData.Major), ushort.Parse(_userData.Minor), _userData.UserUuid);
                NSNumber       txPower = new NSNumber(-59);
                trasmitter.StartAdvertising(region.GetPeripheralData(txPower));
            }
            else
            {
                trasmitter.StopAdvertising();
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            if (!UserInterfaceIdiomIsPhone)
            {
                openMultipeerBrowser.TouchUpInside += (sender, e) => {
                    StartMultipeerBrowser();
                };
            }
            else
            {
                StartMultipeerAdvertiser();
            }

            var monkeyUUID   = new NSUuid(uuid);
            var beaconRegion = new CLBeaconRegion(monkeyUUID, monkeyId);

            beaconRegion.NotifyEntryStateOnDisplay = true;
            beaconRegion.NotifyOnEntry             = true;
            beaconRegion.NotifyOnExit = true;

            if (!UserInterfaceIdiomIsPhone)
            {
                //power - the received signal strength indicator (RSSI) value (measured in decibels) of the beacon from one meter away
                var power = new NSNumber(-59);
                NSMutableDictionary peripheralData = beaconRegion.GetPeripheralData(power);
                peripheralDelegate = new BTPeripheralDelegate();
                peripheralMgr      = new CBPeripheralManager(peripheralDelegate, DispatchQueue.DefaultGlobalQueue);

                peripheralMgr.StartAdvertising(peripheralData);
            }
            else
            {
                InitPitchAndVolume();

                locationMgr = new CLLocationManager();

                locationMgr.RegionEntered += (object sender, CLRegionEventArgs e) => {
                    if (e.Region.Identifier == monkeyId)
                    {
                        UILocalNotification notification = new UILocalNotification()
                        {
                            AlertBody = "There's a monkey hiding nearby!"
                        };
                        UIApplication.SharedApplication.PresentLocationNotificationNow(notification);
                    }
                };

                locationMgr.DidRangeBeacons += (object sender, CLRegionBeaconsRangedEventArgs e) => {
                    if (e.Beacons.Length > 0)
                    {
                        CLBeacon beacon  = e.Beacons [0];
                        string   message = "";

                        switch (beacon.Proximity)
                        {
                        case CLProximity.Immediate:
                            message = "You found the monkey!";
                            monkeyStatusLabel.Text = message;
                            View.BackgroundColor   = UIColor.Green;
                            break;

                        case CLProximity.Near:
                            message = "You're getting warmer";
                            monkeyStatusLabel.Text = message;
                            View.BackgroundColor   = UIColor.Yellow;
                            break;

                        case CLProximity.Far:
                            message = "You're freezing cold";
                            monkeyStatusLabel.Text = message;
                            View.BackgroundColor   = UIColor.Blue;
                            break;

                        case CLProximity.Unknown:
                            message = "I'm not sure how close you are to the monkey";
                            monkeyStatusLabel.Text = message;
                            View.BackgroundColor   = UIColor.Gray;
                            break;
                        }

                        if (previousProximity != beacon.Proximity)
                        {
                            Speak(message);

                            // demo send message using multipeer connectivity
                            if (beacon.Proximity == CLProximity.Immediate)
                            {
                                SendMessage();
                            }
                        }
                        previousProximity = beacon.Proximity;
                    }
                };

                locationMgr.StartMonitoring(beaconRegion);
                locationMgr.StartRangingBeacons(beaconRegion);
            }
        }
Ejemplo n.º 22
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            this.Title = "Configure";

            enabledSwitch.ValueChanged += (sender, e) => {
                enabled = enabledSwitch.On;
            };

            uuidTextField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            uuidTextField.InputView        = new UuidPickerView(uuidTextField);
            uuidTextField.EditingDidBegin += HandleEditingDidBegin;
            uuidTextField.EditingDidEnd   += (sender, e) => {
                uuid = new NSUuid(uuidTextField.Text);
                NavigationItem.RightBarButtonItem = saveButton;
            };
            uuidTextField.Text = uuid.AsString();

            majorTextField.KeyboardType     = UIKeyboardType.NumberPad;
            majorTextField.ReturnKeyType    = UIReturnKeyType.Done;
            majorTextField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            majorTextField.EditingDidBegin += HandleEditingDidBegin;
            majorTextField.EditingDidEnd   += (sender, e) => {
                major = numberFormatter.NumberFromString(majorTextField.Text);
                NavigationItem.RightBarButtonItem = saveButton;
            };

            minorTextField.KeyboardType     = UIKeyboardType.NumberPad;
            minorTextField.ReturnKeyType    = UIReturnKeyType.Done;
            minorTextField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            minorTextField.EditingDidBegin += HandleEditingDidBegin;
            minorTextField.EditingDidEnd   += (sender, e) => {
                minor = numberFormatter.NumberFromString(minorTextField.Text);
                NavigationItem.RightBarButtonItem = saveButton;
            };

            measuredPowerTextField.KeyboardType     = UIKeyboardType.NumberPad;
            measuredPowerTextField.ReturnKeyType    = UIReturnKeyType.Done;
            measuredPowerTextField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            measuredPowerTextField.EditingDidBegin += HandleEditingDidBegin;
            measuredPowerTextField.EditingDidEnd   += (sender, e) => {
                power = numberFormatter.NumberFromString(measuredPowerTextField.Text);
                NavigationItem.RightBarButtonItem = saveButton;
            };

            doneButton = new UIBarButtonItem(UIBarButtonSystemItem.Done, (sender, e) => {
                uuidTextField.ResignFirstResponder();
                majorTextField.ResignFirstResponder();
                minorTextField.ResignFirstResponder();
                measuredPowerTextField.ResignFirstResponder();
                TableView.ReloadData();
            });

            saveButton = new UIBarButtonItem(UIBarButtonSystemItem.Save, (sender, e) => {
                if (peripheralManager.State < CBPeripheralManagerState.PoweredOn)
                {
                    new UIAlertView("Bluetooth must be enabled", "To configure your device as a beacon", null, "OK", null).Show();
                    return;
                }

                if (enabled)
                {
                    CLBeaconRegion region = Helpers.CreateRegion(uuid, major, minor);
                    if (region != null)
                    {
                        peripheralManager.StartAdvertising(region.GetPeripheralData(power));
                    }
                }
                else
                {
                    peripheralManager.StopAdvertising();
                }

                NavigationController.PopViewControllerAnimated(true);
            });

            NavigationItem.RightBarButtonItem = saveButton;
        }
Ejemplo n.º 23
0
 public void StartAdvertising()
 {
     _peripheralMgr.StartAdvertising(_peripheralData);
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            var monkeyUUID = new NSUuid (uuid);
            var beaconRegion = new CLBeaconRegion (monkeyUUID, monkeyId);

            beaconRegion.NotifyEntryStateOnDisplay = true;
            beaconRegion.NotifyOnEntry = true;
            beaconRegion.NotifyOnExit = true;

            if (!UserInterfaceIdiomIsPhone) {

                //power - the received signal strength indicator (RSSI) value (measured in decibels) of the beacon from one meter away
                var power = new NSNumber (-59);
                NSMutableDictionary peripheralData = beaconRegion.GetPeripheralData (power);
                peripheralDelegate = new BTPeripheralDelegate ();
                peripheralMgr = new CBPeripheralManager (peripheralDelegate, DispatchQueue.DefaultGlobalQueue);

                peripheralMgr.StartAdvertising (peripheralData);

            } else {

                InitPitchAndVolume ();

                locationMgr = new CLLocationManager ();

                locationMgr.RegionEntered += (object sender, CLRegionEventArgs e) => {
                    if (e.Region.Identifier == monkeyId) {
                        UILocalNotification notification = new UILocalNotification () { AlertBody = "There's a monkey hiding nearby!" };
                        UIApplication.SharedApplication.PresentLocationNotificationNow (notification);
                    }
                };

                locationMgr.DidRangeBeacons += (object sender, CLRegionBeaconsRangedEventArgs e) => {
                    if (e.Beacons.Length > 0) {

                        CLBeacon beacon = e.Beacons [0];
                        string message = "";

                        switch (beacon.Proximity) {
                        case CLProximity.Immediate:
                            message = "You found the monkey!";
                            monkeyStatusLabel.Text = message;
                            View.BackgroundColor = UIColor.Green;
                            break;
                        case CLProximity.Near:
                            message = "You're getting warmer";
                            monkeyStatusLabel.Text = message;
                            View.BackgroundColor = UIColor.Yellow;
                            break;
                        case CLProximity.Far:
                            message = "You're freezing cold";
                            monkeyStatusLabel.Text = message;
                            View.BackgroundColor = UIColor.Blue;
                            break;
                        case CLProximity.Unknown:
                            message = "I'm not sure how close you are to the monkey";;
                            monkeyStatusLabel.Text = message;
                            View.BackgroundColor = UIColor.Gray;
                            break;
                        }

                        if(previousProximity != beacon.Proximity){
                            Speak (message);
                        }
                        previousProximity = beacon.Proximity;
                    }
                };

                locationMgr.StartMonitoring (beaconRegion);
                locationMgr.StartRangingBeacons (beaconRegion);
            }
        }