private void OnBeaconArrived(Beacon beacon)
 {
     //		GUILayout.Label ("find");
     //		status = "find";
     Application.OpenURL(string.Format("http://210.163.187.34:3070?major={0}&minor={1}", beacon.major, beacon.minor));
     Debug.Log ("Beacon arrived: "+beacon.ToString());
 }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            Tuple<Beacon, Region> stuff = this.GetBeaconAndRegion();
            _beacon = stuff.Item1;
            _region = stuff.Item2;

            ActionBar.SetDisplayHomeAsUpEnabled(true);
            SetContentView(Resource.Layout.distance_view);
            _dotView = FindViewById(Resource.Id.dot);

            _sonar = FindViewById(Resource.Id.sonar);
            _sonar.ViewTreeObserver.AddOnGlobalLayoutListener(this);

            _findBeacon = new FindSpecificBeacon(this);
            _findBeacon.BeaconFound += (sender, e) => RunOnUiThread(() =>{
                                                                        Log.Debug(Tag, "Found the beacon!");
                                                                        if (_segmentLength == -1)
                                                                        {
                                                                            return;
                                                                        }
                                                                        _dotView.Animate().TranslationY(ComputeDotPosY(e.FoundBeacon)).Start();
                                                                    });
        }
 public void BeaconExtension_GetApproximateIosRange()
 {
     var beacon = new Beacon("", 0, 0, -39) { Rssi = -52 };
     Assert.AreEqual(8.3781601753285457d, beacon.GetApproximateIosRange());
     beacon.Rssi = 0;
     Assert.AreEqual(-1d, beacon.GetApproximateIosRange());
 }
    private void DisplayBeacon(Beacon beacon)
    {
        Vector3 screenPos = Camera.main.WorldToScreenPoint(beacon.avatarTransform.position);

        GUI.color = beacon.color;
        float scale = maxScale*beacon.scale;
        GUI.DrawTexture(new Rect(screenPos.x - scale, Screen.height -screenPos.y -scale, scale*2, scale*2), beaconTex);
    }
 public void Display(Beacon beacon)
 {
     _macTextView.Text = string.Format("MAC: {0} ({1:N2})", beacon.MacAddress, Utils.ComputeAccuracy(beacon));
     _majorTextView.Text = string.Format("Major: {0}", beacon.Major);
     _minorTextView.Text = string.Format("Minor: {0}", beacon.Minor);
     _measuredPowerTextView.Text = string.Format("MPower: {0}", beacon.MeasuredPower);
     _rssiTextView.Text = string.Format("RSSI: {0}", beacon.Rssi);
 }
 float ComputeDotPosY(Beacon foundBeacon)
 {
     // Put the dot at the end of the scale when it's further than 6m.
     double x = Utils.ComputeAccuracy(foundBeacon);
     Log.Debug(Tag, "Beacon is approx. {0:N1} metres away", x);
     double distance = Math.Min(x, 6.0);
     return _startY + (int)(_segmentLength * (distance / 6.0));
 }
Example #7
0
 public void Setup()
 {
     beacon = new Beacon("4fe5d5f6-abce-ddfe-1587-123d1a4b567f", 1234, 5678, -48, 0xAABB) { Rssi = -52 };
     data = new byte[] {
         0x02, 0x01, 0x1A, 0x1A, 0xFF, 0xAA, 0xBB, 0x02, 0x15, 0x4F, 0xE5, 0xD5, 0xF6, 0xAB, 0xCE,
         0xDD, 0xFE, 0x15, 0x87, 0x12, 0x3D, 0x1A, 0x4B, 0x56, 0x7F, 0x04, 0xD2, 0x16, 0x2E, 0xD0
     };
 }
Example #8
0
 private void serverButton_Click(object sender, RoutedEventArgs e)
 {
     // We need a random port number otherwise all beacons will be the same
     var b = new Beacon("beaconDemo", (ushort) r.Next(2048, 60000))
     {
         BeaconData = "Beacon at " + DateTime.Now + " on " + Dns.GetHostName()
     };
     b.Start();
     beacons.Add(b);
 }
 public override void Stop()
 {
     if (_isSearching)
     {
         BeaconManager.StopRanging(_region);
         base.Stop();
         _region = null;
         _beacon = null;
         _isSearching = false;
     }
 }
Example #10
0
 void InitializeListView()
 {
     _adapter = new LeDevicesListAdapter(this);
     ListView list = FindViewById<ListView>(Resource.Id.device_list);
     list.Adapter = _adapter;
     list.ItemClick += (sender, e) =>{
                           _selectedBeacon = _adapter[e.Position];
                           View imgView = e.View.FindViewWithTag("beacon_image");
                           _quickAction.Show(imgView);
                       };
 }
Example #11
0
        public Beacon ConvertDtoToBeacon(BeaconDto beaconDto)
        {
            var beacon = new Beacon
            {
                Guid        = Guid.NewGuid(),
                Name        = beaconDto.Name,
                Description = beaconDto.Description,
                Status      = true
            };

            return(beacon);
        }
        void RemoveBeacon(Beacon beacon)
        {
            if (beacon == null)
            {
                return;
            }

            Self.World.AddFrameEndTask(w =>
            {
                w.Remove(beacon);
            });
        }
Example #13
0
    public override void _Pressed()
    {
        base._Pressed();
        counter++;
        BeaconControl beaconControlInstance = (BeaconControl)beaconControlScene.Instance();
        Beacon        beacon = (Beacon)beaconScene.Instance();

        sliders.AddChild(beaconControlInstance);
        beaconTrack.AddChild(beacon);
        beacon.BeaconId = counter;
        beaconControlInstance.Link(beacon);
    }
Example #14
0
        public static Beacon GetBeacon(this Activity activity)
        {
            Beacon beacon = activity.Intent.GetParcelableExtra(EXTRAS_BEACON) as Beacon;

            if (beacon == null)
            {
                Toast.MakeText(activity, "Beacon not found in intent extras.", ToastLength.Long).Show();
                activity.Finish();
                return(null);
            }
            return(beacon);
        }
Example #15
0
        public IHttpActionResult PostBeacon(Beacon beacon)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.Beacons.Add(beacon);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = beacon.Id }, beacon));
        }
Example #16
0
        private void Delete_Button_Click(object sender, RoutedEventArgs e)
        {
            if (sender != null)
            {
                System.Windows.Controls.Button btn = (System.Windows.Controls.Button)sender;
                Beacon p = btn.DataContext as Beacon;
                beacons.Remove(p);
                listBox.Items.Refresh();

                File.WriteAllLines(SPEC_FILE_PATH, new string[] { JsonConvert.SerializeObject(beacons) });
            }
        }
Example #17
0
        public PermissionResult CheckBeaconPermission(int userId, Beacon beacon)
        {
            if (!beacon.FKHotel.HasValue || RootRepository.HotelRepository.CheckHotelPermission(userId, beacon.FKHotel.Value).Result == PermissionResults.Authorized)
            {
                return(new PermissionResult {
                    Result = PermissionResults.Authorized
                });
            }

            return(new PermissionResult(PermissionResults.Unauthorized, "You are unauthorized to access this beacon.",
                                        new[] { new KeyValuePair <string, object>("userId", userId), new KeyValuePair <string, object>("beaconId", beacon.PKID), }));
        }
Example #18
0
        /// <summary>
        /// Method demonstrating how to handle individual new beacons found by the manager.
        /// This event will only be invoked once, the very first time a beacon is discovered.
        /// For more fine-grained status updates, subscribe to changes of the ObservableCollection in
        /// BeaconManager.BluetoothBeacons (_beaconManager).
        /// To handle all individual received Bluetooth packets in your main app and outside of the
        /// library, subscribe to AdvertisementPacketReceived event of the IBluetoothPacketProvider
        /// (_provider).
        /// </summary>
        /// <param name="sender">Reference to the sender instance of the event.</param>
        /// <param name="beacon">Beacon class instance containing all known and parsed information about
        /// the Bluetooth beacon.</param>
        private void BeaconManagerOnBeaconAdded(object sender, Beacon beacon)
        {
            Debug.WriteLine("\nBeacon: " + beacon.BluetoothAddressAsString);
            Debug.WriteLine("Type: " + beacon.BeaconType);
            Debug.WriteLine("Last Update: " + beacon.Timestamp);
            Debug.WriteLine("RSSI: " + beacon.Rssi);

            Analytics.TrackEvent("Added Beacon", new Dictionary <string, string> {
                { "Beacon", "Error:" + beacon.BluetoothAddressAsString },
                { "Function", "BeaconManagerOnBeaconAdded" }
            });

            foreach (var beaconFrame in beacon.BeaconFrames.ToList())
            {
                // Print a small sample of the available data parsed by the library
                if (beaconFrame is UidEddystoneFrame)
                {
                    Debug.WriteLine("Eddystone UID Frame");
                    Debug.WriteLine("ID: " + ((UidEddystoneFrame)beaconFrame).NamespaceIdAsNumber.ToString("X") + " / " +
                                    ((UidEddystoneFrame)beaconFrame).InstanceIdAsNumber.ToString("X"));
                }
                else if (beaconFrame is UrlEddystoneFrame)
                {
                    Debug.WriteLine("Eddystone URL Frame");
                    Debug.WriteLine("URL: " + ((UrlEddystoneFrame)beaconFrame).CompleteUrl);
                }
                else if (beaconFrame is TlmEddystoneFrame)
                {
                    Debug.WriteLine("Eddystone Telemetry Frame");
                    Debug.WriteLine("Temperature [°C]: " + ((TlmEddystoneFrame)beaconFrame).TemperatureInC);
                    Debug.WriteLine("Battery [mV]: " + ((TlmEddystoneFrame)beaconFrame).BatteryInMilliV);
                }
                else if (beaconFrame is EidEddystoneFrame)
                {
                    Debug.WriteLine("Eddystone EID Frame");
                    Debug.WriteLine("Ranging Data: " + ((EidEddystoneFrame)beaconFrame).RangingData);
                    Debug.WriteLine("Ephemeral Identifier: " + BitConverter.ToString(((EidEddystoneFrame)beaconFrame).EphemeralIdentifier));
                }
                else if (beaconFrame is ProximityBeaconFrame)
                {
                    Debug.WriteLine("Proximity Beacon Frame (iBeacon compatible)");
                    Debug.WriteLine("Uuid: " + ((ProximityBeaconFrame)beaconFrame).UuidAsString);
                    Debug.WriteLine("Major: " + ((ProximityBeaconFrame)beaconFrame).MajorAsString);
                    Debug.WriteLine("Major: " + ((ProximityBeaconFrame)beaconFrame).MinorAsString);
                }
                else
                {
                    Debug.WriteLine("Unknown frame - not parsed by the library, write your own derived beacon frame type!");
                    Debug.WriteLine("Payload: " + BitConverter.ToString(((UnknownBeaconFrame)beaconFrame).Payload));
                }
            }
        }
        private async void OnRanging(object sender, BeaconManager.RangingEventArgs e)
        {
            Log.Debug("demo", "IN Ranging " + e.Beacons.Count);
            if (e.Beacons.Count > 0)
            {
                Log.Debug("demo", "List > 0");

                foreach (Beacon beacon in e.Beacons)
                {
                    _proximity = ComputeProximity(beacon);

                    if (_proximity != Proximity.Unknown)
                    {
                        _distance = ComputeAccuracy(beacon);

                        //If distance is valid and (less than current distance or current beacon is null) update current beacon
                        if (_distance > -1 && ((_distance < _currentBeaconDistance) || _currentBeacon == null))
                        {
                            _currentBeaconDistance = _distance;

                            _currentBeacon = beacon;

                            switch (beacon.Major)
                            {
                            case 1564:
                                _lastActiveTimeRegion1 = DateTime.Now.Ticks;
                                break;

                            case 15212:
                                _lastActiveTimeRegion2 = DateTime.Now.Ticks;
                                break;

                            case 26535:
                                _lastActiveTimeRegion3 = DateTime.Now.Ticks;
                                break;
                            }
                        }
                        //If distance is valid and beacon major is same as current beacon's major, update current beacon distance
                        if (_distance > -1 && (beacon.Major == _currentBeacon.Major))
                        {
                            _currentBeaconDistance = _distance;
                            Log.Debug(Constants.TAG, "updating current beacon");

                            if (!isUnlockInProgress)
                            {
                                await UnLockMessagesAsync(_currentBeacon.Major).ConfigureAwait(false);
                            }
                        }
                    }
                }
            }
        }
Example #20
0
        public async Task EventHistory_FlushHistory()
        {
            var beacon = new Beacon();

            beacon.Id1       = "7367672374000000ffff0000ffff0007";
            beacon.Id2       = 8008;
            beacon.Id3       = 5;
            beacon.Timestamp = DateTimeOffset.Now;
            var args = new BeaconEventArgs();

            args.Beacon    = beacon;
            args.EventType = BeaconEventType.Exit;
            var resolvedActionEventArgs = new ResolvedActionsEventArgs()
            {
                BeaconPid = beacon.Pid, BeaconEventType = BeaconEventType.Enter
            };

            BeaconAction beaconaction1 = new BeaconAction()
            {
                Body = "body", Url = "http://www.com", Uuid = "1223"
            };
            BeaconAction beaconaction2 = new BeaconAction()
            {
                Body = "body", Url = "http://www.com", Uuid = "5678"
            };
            BeaconAction beaconaction3 = new BeaconAction()
            {
                Body = "body", Url = "http://www.com", Uuid = "9678"
            };
            ResolvedAction res1 = new ResolvedAction()
            {
                SuppressionTime = 100, SendOnlyOnce = true, BeaconAction = beaconaction1
            };
            ResolvedAction res2 = new ResolvedAction()
            {
                SuppressionTime = 100, SendOnlyOnce = true, BeaconAction = beaconaction2
            };
            ResolvedAction res3 = new ResolvedAction()
            {
                SuppressionTime = 1, SendOnlyOnce = true, BeaconAction = beaconaction3
            };

            EventHistory eventHistory = new EventHistory();

            await eventHistory.SaveBeaconEventAsync(args, null);

            await eventHistory.SaveExecutedResolvedActionAsync(resolvedActionEventArgs, beaconaction1);

            await eventHistory.SaveExecutedResolvedActionAsync(resolvedActionEventArgs, beaconaction3);

            await eventHistory.FlushHistoryAsync();
        }
Example #21
0
        void HandleDidRangeBeacons(object sender, CLRegionBeaconsRangedEventArgs e)
        {
            Unknowns.Clear();
            Immediates.Clear();
            Nears.Clear();
            Fars.Clear();

            SystemLogger.Log(SystemLogger.Module.PLATFORM, "************************** HandleDidRangeBeacons Identifier: " + e.Region.Identifier);
            int i = 0;

            foreach (CLBeacon beacon in e.Beacons)
            {
                switch (beacon.Proximity)
                {
                case CLProximity.Immediate:
                    Immediates.Add(beacon);
                    break;

                case CLProximity.Near:
                    Nears.Add(beacon);
                    break;

                case CLProximity.Far:
                    Fars.Add(beacon);
                    break;

                case CLProximity.Unknown:
                    Unknowns.Add(beacon);
                    break;
                }
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "************************** HandleDidRangeBeacons Accuracy: " + beacon.Accuracy);
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "************************** HandleDidRangeBeacons Proximity: " + beacon.Proximity);
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "************************** HandleDidRangeBeacons Description: " + beacon.Description);
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "************************** HandleDidRangeBeacons Major: " + beacon.Major);
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "************************** HandleDidRangeBeacons Minor: " + beacon.Minor);
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "************************** HandleDidRangeBeacons Rssi: " + beacon.Rssi);
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "************************** HandleDidRangeBeacons ProximityUuid: " + beacon.ProximityUuid);


                Beacon AppverseBeacon = FromCLBeacon(beacon);
                String id             = uniqueIDForBeacon(AppverseBeacon);
                if (!rangingBeacons.ContainsKey(id))
                {
                    SystemLogger.Log(SystemLogger.Module.PLATFORM, "************************** ADDED LOCATION: " + AppverseBeacon.Distance.ToString());
                    rangingBeacons.Add(id, AppverseBeacon);
                }
                else
                {
                    rangingBeacons[id] = AppverseBeacon;
                }
            }
        }
Example #22
0
        public override void Activate(Actor self, Order order, SupportPowerManager manager)
        {
            base.Activate(self, order, manager);
            PlayLaunchSounds();

            foreach (var launchpad in self.TraitsImplementing <INotifyNuke>())
            {
                launchpad.Launching(self);
            }

            var targetPosition = self.World.Map.CenterOfCell(order.TargetLocation);
            var palette        = info.IsPlayerPalette ? info.MissilePalette + self.Owner.InternalName : info.MissilePalette;
            var missile        = new NukeLaunch(self.Owner, info.MissileWeapon, info.WeaponInfo, palette, info.MissileUp, info.MissileDown,
                                                self.CenterPosition + body.LocalToWorld(info.SpawnOffset),
                                                targetPosition,
                                                info.FlightVelocity, info.FlightDelay, info.SkipAscent,
                                                info.FlashType);

            self.World.AddFrameEndTask(w => w.Add(new DelayedAction(info.MissileDelay, () => self.World.Add(missile))));

            if (info.CameraRange != WDist.Zero)
            {
                var type = info.RevealGeneratedShroud ? Shroud.SourceType.Visibility
                                        : Shroud.SourceType.PassiveVisibility;

                self.World.AddFrameEndTask(w => w.Add(new RevealShroudEffect(targetPosition, info.CameraRange, type, self.Owner, info.CameraStances,
                                                                             info.FlightDelay - info.CameraSpawnAdvance, info.CameraSpawnAdvance + info.CameraRemoveDelay)));
            }

            if (Info.DisplayBeacon)
            {
                var beacon = new Beacon(
                    order.Player,
                    targetPosition,
                    Info.BeaconPaletteIsPlayerPalette,
                    Info.BeaconPalette,
                    Info.BeaconImage,
                    Info.BeaconPoster,
                    Info.BeaconPosterPalette,
                    Info.ArrowSequence,
                    Info.CircleSequence,
                    Info.ClockSequence,
                    () => missile.FractionComplete,
                    Info.BeaconDelay,
                    info.FlightDelay - info.BeaconRemoveAdvance);

                self.World.AddFrameEndTask(w =>
                {
                    w.Add(beacon);
                });
            }
        }
Example #23
0
        private static bool IsRayIntersectWithBeaconAccuracy(PointF ray, Beacon beacon)
        {
            if (beacon == null)
            {
                return(false);
            }

            var x = beacon.X;
            var y = beacon.Y;
            var r = beacon.Accuracy;

            return(r > Math.Sqrt((ray.X - x) * (ray.X - x) + (ray.Y - y) * (ray.Y - y)));
        }
Example #24
0
        public async void Remove(Beacon beacon)
        {
            int index = 0;

            for (index = 0; index < BeaconDetailsCollection.Count; ++index)
            {
                if (BeaconDetailsCollection[index].Matches(beacon))
                {
                    BeaconDetailsCollection.RemoveAt(index);
                    break;
                }
            }
        }
Example #25
0
        private bool IsValidEnterEvent(BackgroundEvent history, Beacon beacon, int outOfRangeDb)
        {
            if (history == null)
            {
                return(true);
            }

            if (!SuppressBurst)
            {
                return(history.LastEvent == BeaconEventType.Exit || !IsOutOfRange(outOfRangeDb, beacon) && history.EventTime.AddMilliseconds(AppSettings.BeaconExitTimeout) < DateTimeOffset.Now);
            }
            return(!IsOutOfRange(outOfRangeDb, beacon) && history.EventTime.AddMilliseconds(AppSettings.BeaconExitTimeout) < DateTimeOffset.Now);
        }
Example #26
0
        public void SetUp()
        {
            logger = Substitute.For <ILogger>();
            logger.IsDebugEnabled.Returns(true);

            beaconSendingContext = Substitute.For <IBeaconSendingContext>();
            beaconSender         = new BeaconSender(beaconSendingContext);

            mockTimingProvider = Substitute.For <ITimingProvider>();
            var configuration = new TestConfiguration();

            beacon = new Beacon(logger, new Caching.BeaconCache(), configuration, "127.0.0.1", Substitute.For <IThreadIDProvider>(), mockTimingProvider);
        }
        /// <summary>
        /// Handles the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        public async Task <BeaconViewModel> Handle(BeaconQuery message)
        {
            Beacon beacon = await beaconsRepository.FindBy(m => m.BeaconId == message.Id.ToString());

            //TODO: add auto mapper
            var viewModel = new BeaconViewModel
            {
                Id     = Guid.Parse(beacon.BeaconId),
                Number = beacon.Title
            };

            return(await Task.FromResult(viewModel));
        }
        public void multiFrameBeaconProgramaticParserAssociationDifferentServiceUUIDFieldsGetUpdated()
        {
            Beacon beacon                  = getMultiFrameBeacon();
            Beacon beaconUpdate            = getMultiFrameBeaconUpdateDifferentServiceUUID();
            ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker(false);

            tracker.Track(beacon);
            tracker.Track(beaconUpdate);
            Beacon trackedBeacon = tracker.Track(beacon);

            AssertEx.AreEqual("rssi should be updated", beaconUpdate.Rssi, trackedBeacon.Rssi);
            AssertEx.AreEqual("data fields should be updated", beaconUpdate.DataFields, trackedBeacon.ExtraDataFields);
        }
        public void multiFrameBeaconDifferentServiceUUIDFieldsNotUpdated()
        {
            Beacon beacon                  = getMultiFrameBeacon();
            Beacon beaconUpdate            = getMultiFrameBeaconUpdateDifferentServiceUUID();
            ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker();

            tracker.Track(beacon);
            tracker.Track(beaconUpdate);
            Beacon trackedBeacon = tracker.Track(beacon);

            AssertEx.AreNotEqual("rssi should NOT be updated", beaconUpdate.Rssi, trackedBeacon.Rssi);
            AssertEx.AreNotEqual("data fields should NOT be updated", beaconUpdate.DataFields, trackedBeacon.ExtraDataFields);
        }
        public void gattBeaconFieldsGetUpdated()
        {
            Beacon beacon                  = getGattBeacon();
            Beacon beaconUpdate            = getGattBeaconUpdate();
            Beacon extraDataBeacon         = getGattBeaconExtraData();
            ExtraDataBeaconTracker tracker = new ExtraDataBeaconTracker();

            tracker.Track(beacon);
            Beacon trackedBeacon = tracker.Track(beaconUpdate);

            AssertEx.AreEqual("rssi should be updated", beaconUpdate.Rssi, trackedBeacon.Rssi);
            AssertEx.AreEqual("data fields should be updated", beaconUpdate.DataFields, trackedBeacon.DataFields);
        }
 public BeaconEventType ResolveBeaconState(Beacon b)
 {
     lock (KnownBeacons)
     {
         if (KnownBeacons.ContainsKey(b))
         {
             KnownBeacons[b] = DateTimeOffset.Now;
             return BeaconEventType.None;
         }
         KnownBeacons[b] = DateTimeOffset.Now;
     }
     return BeaconEventType.Enter;
 }
 public BeaconEventType ResolveBeaconState(Beacon b)
 {
     lock (KnownBeacons)
     {
         if (KnownBeacons.ContainsKey(b))
         {
             KnownBeacons[b] = DateTimeOffset.Now;
             return(BeaconEventType.None);
         }
         KnownBeacons[b] = DateTimeOffset.Now;
     }
     return(BeaconEventType.Enter);
 }
Example #33
0
        /* Updates the beacon that is provided as json */
        private void UpdateBeacon(string data)
        {
            /* we are triming data below, splitting it by blank chars is not a valid way.
             * because blank char can become in the json object as well */
            string command = "update beacon ";
            string json    = data.Substring(command.Length);

            Beacon    beacon    = JsonConvert.DeserializeObject <Beacon>(json);
            BeaconDao beaconDao = new BeaconDao();

            beaconDao.UpdateBeacon(beacon);
            ServiceClient.Send(OK);
        }
Example #34
0
 public BeaconGetModel(Beacon beacon)
 {
     this.Beacon_id                = beacon.Beacon_id;
     this.Beacon_major             = beacon.Beacon_major;
     this.Beacon_message           = beacon.Beacon_message;
     this.Beacon_minor             = beacon.Beacon_minor;
     this.Beacon_rssi              = beacon.Beacon_rssi;
     this.Beacon_title             = beacon.Beacon_title;
     this.Beacon_trigger_interval  = beacon.Beacon_trigger_interval;
     this.Beacon_trigger_proximity = beacon.Beacon_trigger_proximity;
     this.Beacon_uuid              = beacon.Beacon_uuid;
     this.IsDeleted                = beacon.IsDeleted;
 }
        // *** constructors ***

        public WebRequestTracerBase(ILogger logger, Beacon beacon, Action action)
        {
            this.logger = logger;
            this.beacon = beacon;
            this.action = action;

            // creating start sequence number has to be done here, because it's needed for the creation of the tag
            startSequenceNo = beacon.NextSequenceNumber;

            tag = beacon.CreateTag(action, startSequenceNo);

            startTime = beacon.CurrentTimestamp;
        }
Example #36
0
        void InitializeListView()
        {
            _adapter = new LeDevicesListAdapter(this);
            var list = FindViewById <ListView>(Resource.Id.device_list);

            list.Adapter    = _adapter;
            list.ItemClick += (sender, e) =>
            {
                _selectedBeacon = _adapter[e.Position];
                var imgView = e.View.FindViewWithTag("beacon_image");
                _quickAction.Show(imgView);
            };
        }
        // *** constructors ***

        public WebRequestTracerBase(ILogger logger, Beacon beacon, int parentActionID)
        {
            this.logger         = logger;
            this.beacon         = beacon;
            this.parentActionID = parentActionID;

            // creating start sequence number has to be done here, because it's needed for the creation of the tag
            StartSequenceNo = beacon.NextSequenceNumber;

            tag = beacon.CreateTag(parentActionID, StartSequenceNo);

            StartTime = beacon.CurrentTimestamp;
        }
Example #38
0
        internal Action(Beacon beacon, string name, Action parentAction, SynchronizedQueue <IAction> thisLevelActions)
        {
            this.beacon       = beacon;
            this.parentAction = parentAction;

            this.startTime       = beacon.CurrentTimestamp;
            this.startSequenceNo = beacon.NextSequenceNumber;
            this.id   = beacon.NextID;
            this.name = name;

            this.thisLevelActions = thisLevelActions;
            this.thisLevelActions.Put(this);
        }
        public ActionResult Save(Beacon beacon)
        {
            if (!IsUserLoggedIn())
            {
                TempData["RedirectMessage"] = "Access denied. Please login.";
                return(RedirectToAction("Index", "Home"));
            }

            if (String.IsNullOrWhiteSpace(beacon.uuid))
            {
                ModelState.AddModelError("uuid", "Please fill this field.");
                return(View("Edit", beacon));
            }

            try
            {
                new Guid(beacon.uuid);
            }
            catch (Exception e)
            {
                ModelState.AddModelError("uuid", "UUID must have 32 characters, separated by 4 dashes.");
                beacon.uuid = null;
                return(View("Edit", beacon));
            }

            if (String.IsNullOrWhiteSpace(beacon.Name))
            {
                ModelState.AddModelError("Name", "Please fill this field.");
                return(View("Edit", beacon));
            }

            if (String.IsNullOrWhiteSpace(beacon.Location))
            {
                ModelState.AddModelError("Localization", "Please fill this field.");
                return(View("Edit", beacon));
            }

            using (BeaconDBContext db = new BeaconDBContext())
            {
                bool success;

                if (Request.Params["typeofedit"].ToString().Equals("new")) // hiddenfield can be 2 values: new, exists
                {
                    success = db.AddNewBeacon(beacon);
                    return(RedirectToAction("Index", new { result = success ? 1 : 0, add = 1 }));
                }

                success = db.EditBeacon(beacon);
                return(RedirectToAction("Index", new { result = success ? 1 : 0, add = 0 }));
            }
        }
Example #40
0
        public ActionResult SetFilter(string BeaconId,
                                      string FilterIn,
                                      string FilterOut
                                      )
        {
            if (FilterIn == null)
            {
                // Add BeaconId list
                if (beaconList.Count == 0)
                {
                    foreach (var beacon in db.Beacons.OrderByDescending(data => data.Id))
                    {
                        beaconList.Add(new SelectListItem {
                            Text = beacon.BeaconId, Value = beacon.BeaconId
                        });
                    }
                }

                ViewBag.BeaconId = beaconList;

                ViewBag.FilterIn  = ProcessAdvertisement.GetFilter(beaconList[curSelectedIndex].Text, true);
                ViewBag.FilterOut = ProcessAdvertisement.GetFilter(beaconList[curSelectedIndex].Text, false);

                return(View());
            }

            int valueIn = 0, valueOut = 0;

            if (!int.TryParse(FilterIn, out valueIn))
            {
                return(View());
            }

            if (!int.TryParse(FilterOut, out valueOut))
            {
                return(View());
            }
            ProcessAdvertisement.SetFilter(BeaconId, valueIn, valueOut);


            Beacon result = db.Beacons.Where(data => data.BeaconId == BeaconId).FirstOrDefault();

            result.InFilter  = valueIn;
            result.OutFilter = valueOut;

            db.Entry(result).State = EntityState.Modified;
            db.SaveChanges();

            //return View();
            return(RedirectToAction("Index"));
        }
Example #41
0
        public async Task <IActionResult> BeaconCreate(
            [HttpTrigger(AuthorizationLevel.User, "post", Route = "beacons")]
            [RequestBodyType(typeof(BeaconBody), "The beacon to create")] HttpRequest req,
            [SwaggerIgnore] ClaimsPrincipal userClaim)
        {
            // only admin can update beacon
            if (!userClaim.IsInRole(UserType.Admin.ToString()))
            {
                return(ForbiddenObjectResult.Create(new ErrorResponse(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS)));
            }

            // deserialize request
            BeaconBody beaconBody;

            try
            {
                beaconBody = await SerializationUtil.Deserialize <BeaconBody>(req.Body);
            }
            catch (JsonException e)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, e.Message)));
            }

            // check for required fields
            if (beaconBody.Name == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "Name is required")));
            }
            if (beaconBody.LocationId == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "LocationId is required")));
            }
            if (beaconBody.Lat == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "Latitude is required")));
            }
            if (beaconBody.Lng == null)
            {
                return(new BadRequestObjectResult(new ErrorResponse(400, "Longitude is required")));
            }

            if (!await locationService.Exists((int)beaconBody.LocationId))
            {
                return(new NotFoundObjectResult(new ErrorResponse(ErrorCode.LOCATION_NOT_FOUND)));
            }

            // create user
            Beacon createdBeacon = await this.beaconService.CreateBeacon(beaconBody);

            return(new OkObjectResult(createdBeacon));
        }
Example #42
0
    // Use this for initialization
    void Start()
    {
        beacons=new ArrayList();
        foreach(GameObject zone in GameObject.FindGameObjectsWithTag("zone")){
            Beacon b=new Beacon(zone);
            beacons.Add (b);
        }
        for(int count=0;count<bugCount;count++){
            GameObject bug=(GameObject)Instantiate(bugPrefab,new Vector3(0f,.5f,1.25f) ,Quaternion.identity);
            bugScript script=(bugScript)bug.GetComponent("bugScript");
            script.setBeacons(beacons);
            bugs.Add (bug);

        }
    }
Example #43
0
        public void EqualsTest()
        {
            try
            {
                iBeaconServer beacon1 = new iBeaconServer("test", 10, 10);
                Beacon beacon2 = new Beacon("test", 10, 10, 10, 10, 20.00, 10);

                Assert.IsNotNull(beacon1);
                Assert.IsNotNull(beacon2);
                Assert.True(beacon1.Equals(beacon2));
            }
            catch (SecurityException e)
            {
                Console.WriteLine("Security Exception:\n\n{0}", e.Message);
            }
        }
Example #44
0
 void HandleActionItemClicked(object sender, ActionItemClickEventArgs e)
 {
     switch (e.ActionItem.ActionId)
     {
         case QUICKACTION_DISTANCEDEMO:
             this.StartActivityForBeacon<DistanceBeaconActivity>(_selectedBeacon);
             break;
         case QUICKACTION_NOTIFYDEMO:
             this.StartActivityForBeacon<NotifyDemoActivity>(_selectedBeacon);
             break;
         default:
             Log.Wtf(Tag, "Don't know how to handle the ActionItem {0}.", e.ActionItem.Title);
             break;
     }
     _selectedBeacon = null;
 }
 public static MeetingRoom GetByBeacon(IDbConnection db, Beacon beacon)
 {
     using (IDbCommand command = db.CreateCommand())
     {
         command.CommandText = "select id,name,capacity, beacon, timezone from meetingroom where id = @Beacon";
         IDbDataParameter p = command.CreateParameter();
         p.ParameterName = "@Beacon";
         p.Value = string.Format("{0}:{1}:{2}", beacon.Uuid, beacon.Major, beacon.Minor);
         command.Parameters.Add(p);
         using(IDataReader reader = command.ExecuteReader())
         {
             if (!reader.Read())
                 return null;
             return new MeetingRoom(reader);
         }
     }
 }
        /// <param name="beacon"></param>
        /// <returns>True, if the given beacon matches an existing one in this container.</returns>
        public bool Contains(Beacon beacon)
        {
            bool found = false;

            lock (_beaconListLock)
            {
                foreach (Beacon existingBeacon in _beacons)
                {
                    if (beacon.Matches(existingBeacon))
                    {
                        found = true;
                        break;
                    }
                }
            }

            return found;
        }
    private IEnumerator beaconAnimation(byte id)
    {
        Beacon newBeacon = new Beacon(avatarManager.GetAvatarTransform(id), 0, Time.time, avatarManager.GetAvatarColor(id));

        beacons.Add(newBeacon);

        //yield return new WaitForSeconds(timeForBeacon);

        while(newBeacon.startTime + timeForBeacon > Time.time)
        {
            print(newBeacon.startTime);
            newBeacon.scale += scalePerSecond*Time.deltaTime;
            yield return 0;
        }

        beacons.Remove(newBeacon);
        print("what");
    }
    GameObject createNewBeaconUi(Beacon beacon)
    {
        Vector3 position = this.nextBeaconPosition();

        GameObject beaconObj = (GameObject) Instantiate(beaconPrefab);
        beaconObj.transform.parent = this.transform;
        beaconObj.transform.localPosition = position;

        Quaternion rotation = new Quaternion(0, 0, 0, 0);
        beaconObj.transform.rotation = rotation;

        BtnJoinBehaviour behaviour = beaconObj.GetComponentInChildren<BtnJoinBehaviour>();
        if (null != behaviour){
            behaviour.resetName(beacon.name, beacon.ip);
        }

        return beaconObj;
    }
Example #49
0
        static void Main(string[] args)
        {
            // On-site version
            //var beacon = new Beacon("my-web-site", "http://localhost:6053/1.0.0");

            // Cloud version
            var beacon = new Beacon("my-api-key", "my-secret-key-or-null-if-auth-disabled", "http://api.beaconpush.com/1.0.0");

            Console.WriteLine("Number of online users: {0}", beacon.OnlineUserCount());

            Console.Write("Sending message to channel...");
            beacon.Channel("my-channel").Send(new { message = "Test message sent to channel" });
            Console.WriteLine("done.");

            foreach (var user in beacon.Channel("my-channel").Users())
            {
                Console.Write("Sending message to user '{0}'...", user.Username);
                user.Send(new { message = "Test message sent directly to user." });
                Console.WriteLine("done.");
            }

            Console.ReadKey();
        }
 /// <summary>
 /// Adds the given beacon to this container.
 /// </summary>
 /// <param name="beacon">The beacon to add.</param>
 /// <param name="overwrite">If true, will update a matching beacon.</param>
 public void Add(Beacon beacon, bool overwrite = false)
 {
     if (beacon != null)
     {
         if (overwrite)
         {
             if (!Update(beacon))
             {
                 lock (_beaconListLock)
                 {
                     _beacons.Add(beacon);
                 }
             }
         }
         else
         {
             lock (_beaconListLock)
             {
                 _beacons.Add(beacon);
             }
         }
     }
 }
Example #51
0
 public void RangeBeacons(string beacons)
 {
     if (!string.IsNullOrEmpty(beacons)) {
         string beaconsClean = beacons.Remove(beacons.Length-1); // Get rid of last ;
         string[] beaconsArr = beaconsClean.Split(';');
         List<Beacon> tempbeacons = new List<Beacon>();
         foreach (string beacon in beaconsArr) {
             string[] beaconArr = beacon.Split(',');
             string uuid = beaconArr[0];
             int major = int.Parse(beaconArr[1]);
             int minor = int.Parse(beaconArr[2]);
             int range = int.Parse(beaconArr[3]);
             int strenght = int.Parse(beaconArr[4]);
             double accuracy = double.Parse(beaconArr[5]);
             int rssi = int.Parse(beaconArr[6]);
             Beacon bTmp = new Beacon(uuid,major,minor,range,strenght,accuracy,rssi);
             tempbeacons.Add(bTmp);
         }
         if (BeaconRangeChangedEvent != null)
             BeaconRangeChangedEvent(tempbeacons);
     }
 }
    public static void UserInReach(IDbConnection db, UserDetails userDetails, Beacon beacon, string Proximity)
    {
        MeetingRoom mr = MeetingRoom.GetByBeacon(db, beacon);
        if (mr == null)
            return;

        TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
        long today = (long)t.TotalSeconds;
        string UserEmail = userDetails.Email;
        if (!MeetingRoomCheckin.DidAlreadyCheckin(db, UserEmail, today))
        {
            SendRequest Request = new SendRequest();
            Request.Members.Add(UserEmail);
            Request.Flags = MessageFlag.ALLOW_DISMISS.Value;
            Request.Text = "Welcome at TP Office. \nHave a nice working day!";

            Api api = new Api();
            api.ApiKey = "ak56ba7f5d4285bb685ba8ddf1ad25c8245245dccef6e127724d4743a6cebb1dcd";
            try
            {
                api.Send(Request);
            }
            catch (Com.Mobicage.Rogerthat.ApiException e)
            {

            }
        }

        List<MeetingRoomBooking> bookings = MeetingRoomBooking.list(db, mr, today);
        MeetingRoomBooking booking = null;
        foreach (MeetingRoomBooking meetingRoomBooking in bookings)
        {
            long Start = today + (meetingRoomBooking.From * 3600);
            long End = today + (meetingRoomBooking.Till * 3600);
            if((Start - 5 * 60)<today && today<(End-5*60))
            {
                booking = meetingRoomBooking;
                break;
            }
        }
    }
 public BeaconFoundEventArgs(Beacon beacon)
 {
     FoundBeacon = beacon;
 }
 private void OnBeaconOutOfRange(Beacon beacon)
 {
     //		GUILayout.Label ("not find");
     //		status = "not found";
     Debug.Log ("Beacon out of range: "+beacon.ToString());
 }
 private void AddBeaconArgs(Beacon beacon, BeaconEventType eventType)
 {
     var args = new BeaconEventArgs();
     args.Beacon = beacon;
     args.EventType = eventType;
     _beaconArgs.Add(args);
 }
 private static bool IsOutOfRange(int outOfRangeDb, Beacon beacon)
 {
     return beacon.RawSignalStrengthInDBm == outOfRangeDb;
 }
        private bool IsValidEnterEvent(BackgroundEvent history, Beacon beacon, int outOfRangeDb)
        {
            if (history == null)
            {
                return true;
            }

            if(!SuppressBurst)
            {
                return history.LastEvent == BeaconEventType.Exit || !IsOutOfRange(outOfRangeDb, beacon) && history.EventTime.AddMilliseconds(AppSettings.BeaconExitTimeout) < DateTimeOffset.Now;
            }
            return !IsOutOfRange(outOfRangeDb, beacon) && history.EventTime.AddMilliseconds(AppSettings.BeaconExitTimeout) < DateTimeOffset.Now;
        }
Example #58
0
 protected override void OnPause()
 {
     _selectedBeacon = null;
     base.OnPause();
 }
        /// <summary>
        /// Creates the second part of the beacon advertizing packet.
        /// Uses the beacon IDs 1, 2, 3 and measured power to create the data section.
        /// </summary>
        /// <param name="beacon">A beacon instance.</param>
        /// <param name="includeAuxByte">Defines whether we should add the additional byte or not.</param>
        /// <returns>A newly created data section.</returns>
        public static BluetoothLEAdvertisementDataSection BeaconToSecondDataSection(
            Beacon beacon, bool includeAuxByte = false)
        {
            string[] temp = beacon.Id1.Split(HexStringSeparator);
            string beaconId1 = string.Join(string.Empty, temp);

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(ManufacturerIdToString(beacon.ManufacturerId));
            stringBuilder.Append(BeaconCodeToString(beacon.Code));
            stringBuilder.Append(beaconId1.ToUpper());

            byte[] beginning = HexStringToByteArray(stringBuilder.ToString());

            byte[] data = includeAuxByte
                ? new byte[SecondBeaconDataSectionMinimumLengthInBytes + 1]
                : new byte[SecondBeaconDataSectionMinimumLengthInBytes];
            
            beginning.CopyTo(data, 0);
            ChangeInt16ArrayEndianess(BitConverter.GetBytes(beacon.Id2)).CopyTo(data, 20);
            ChangeInt16ArrayEndianess(BitConverter.GetBytes(beacon.Id3)).CopyTo(data, 22);
            data[24] = (byte)Convert.ToSByte(beacon.MeasuredPower);
            
            if (includeAuxByte)
            {
                data[25] = beacon.Aux;
            }

            BluetoothLEAdvertisementDataSection dataSection = new BluetoothLEAdvertisementDataSection();
            dataSection.DataType = SecondBeaconDataSectionDataType;
            dataSection.Data = data.AsBuffer();

            return dataSection;
        }
 private void Deserialize(JSONNode node)
 {
     rssi = node["RSSI"].AsInt;
     beacon = new Beacon(node["beacon"]);
     date = Gimbal.ConvertJsonDate(node["date"].Value);
 }