private void AddCoordinate_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         var newPoint = new Geopoint(new BasicGeoposition()
         {
             Latitude = double.Parse(LatitudeText.Text),
             Longitude = double.Parse(LongitudeText.Text)
         });
         var geofence = new Geofence(NameText.Text, new Geocircle(newPoint.Position, double.Parse(RadiusText.Text)),
             MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited,
             false, TimeSpan.FromSeconds(10));
         GeofenceMonitor.Current.Geofences.Add(geofence);
     }
     catch (Exception ex)
     {
         new MessageDialog("Exception thrown: " + ex.Message).ShowAsync();
     }
 }
        public void AddFence()
        {
            // Replace if it already exists for this maneuver key
            var oldFence = GeofenceMonitor.Current.Geofences.Where(p => p.Id == soort.ToString()).FirstOrDefault();
            if (oldFence != null)
            {
                GeofenceMonitor.Current.Geofences.Remove(oldFence);
            }

            Geocircle geocircle = new Geocircle(Position, 25);

            bool singleUse = true;

            MonitoredGeofenceStates mask = 0;

            mask |= MonitoredGeofenceStates.Entered;
            mask |= MonitoredGeofenceStates.Exited;

            var geofence = new Geofence(soort.ToString(), geocircle, mask, singleUse, TimeSpan.FromSeconds(1));
            GeofenceMonitor.Current.Geofences.Add(geofence);
            fence = geofence;
        }
        public async Task AddGeofence(string id, double latitude, double longitude, int radius)
        {
            try
            {
                await _uiThreadProvider.RunInUIThread(() =>
                {
                    var geoCircle = new Geocircle(new BasicGeoposition
                    {
                        Latitude = latitude,
                        Longitude = longitude
                    }, radius);

                    var geofence = new Geofence(id, geoCircle, MonitoredGeofenceStates.Entered, false);
                    GeofenceMonitor.Current.Geofences.Add(geofence);
                });
            }
            catch (Exception e)
            {
                _logService.Log(Tag, e);
                throw;
            }
        }
Пример #4
1
        void OnAddGeofence(object sender, RoutedEventArgs e)
        {
            double lat = double.Parse(this.txtLatitude.Text);
            double lon = double.Parse(this.txtLongitude.Text);
            string identifier = this.txtIdentifier.Text;

            Geofence fence = new Geofence(
                identifier,
                  new Geocircle(
                      new BasicGeoposition()
                      {
                          Latitude = lat,
                          Longitude = lon
                      },
                      500),
                  MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited,
                  false,
                  TimeSpan.FromSeconds(5));

            GeofenceMonitor.Current.Geofences.Add(fence);

            RebuildListOfFences();
        }
Пример #5
1
        /// <summary>
        /// Crea un geofence.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="latitude"></param>
        /// <param name="longitude"></param>
        /// <param name="radius"></param>
        private void NewGeofence(string id, double latitude, double longitude, double radius)
        {
            // Establecemos la posición del Geofence.
            var position = new BasicGeoposition
            {
                Latitude = latitude,
                Longitude = longitude
            };

            // El Geofence es un círculo centrado en el punto dado por la latitud y la longitud con el radio asignado en la propiedad radius.
            var geocircle = new Geocircle(position, radius);

            // Queremos gestionar los eventos al entrar en la zona.
            const MonitoredGeofenceStates mask = MonitoredGeofenceStates.Entered;

            // Tiempo que el usuario debe estar en el área para recibir la notificación.
            var dwellTime = TimeSpan.FromSeconds(5);

            // Añadimos el Geofence al GeofenceMonitor.
            var geofence = new Geofence(id, geocircle, mask, false, dwellTime);

            if (!GeofenceMonitor.Current.Geofences.Contains(geofence))
                GeofenceMonitor.Current.Geofences.Add(geofence);
        }
Пример #6
1
        private void SetupGeofence()
        {
            //Set up a unique key for the geofence
            string GeofenceKey = "My Home Geofence";
            BasicGeoposition GeoFenceRootPosition = GetMyHomeLocation();

            double Georadius = 500;

            // the geocircle is the circular region that defines the geofence
            Geocircle geocircle = new Geocircle(GeoFenceRootPosition, Georadius);

            bool singleUse = (bool)SingleUse.IsChecked;

            //Selecting a subset of the events we need to interact with the geofence
            MonitoredGeofenceStates GeoFenceStates = 0;

            GeoFenceStates |= MonitoredGeofenceStates.Entered;
            GeoFenceStates |= MonitoredGeofenceStates.Exited;

            // setting up how long you need to be in geofence for enter event to fire
            TimeSpan dwellTime;

            dwellTime = DwellTime.Text!=""? ParseTimeSpan(DwellTime.Text) : TimeSpan.FromSeconds(DefaultDwellTimeInSeconds);

            // setting up how long the geofence should be active
            TimeSpan GeoFenceDuration;
            GeoFenceDuration = TimeSpan.FromDays(10);

            // setting up the start time of the geofence
            DateTimeOffset GeoFenceStartTime = DateTimeOffset.Now;

            geofence = new Geofence(GeofenceKey, geocircle, GeoFenceStates, singleUse, dwellTime, GeoFenceStartTime, GeoFenceDuration);
            
            //Add the geofence to the GeofenceMonitor
            GeofenceMonitor.Current.Geofences.Add(geofence);

            //GeofenceMonitor.Current.GeofenceStateChanged += Current_GeofenceStateChanged;

        }
Пример #7
1
private async Task Init_Geofence(double lati, double longi)
{
    var geofenceMonitor = GeofenceMonitor.Current;
    var loc = await new Geolocator().GetGeopositionAsync(
        TimeSpan.FromMinutes(2),
        TimeSpan.FromSeconds(5));

    geofenceMonitor.Geofences.Clear();

    geofenceMonitor.GeofenceStateChanged += (sender, args) =>
    {
        var geoReports = geofenceMonitor.ReadReports();
        foreach (var geofenceStateChangeReport in geoReports)
        {
            
                var id = geofenceStateChangeReport.Geofence.Id;
                var newState = geofenceStateChangeReport.NewState;

                switch (newState)
                {
                    case GeofenceState.Entered:
                        Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                      new MessageDialog("Kevin Ricardo Sejin this will be your favorite place :)", "Welcome")
                      .ShowAsync());
                        break;
                    case GeofenceState.Exited:
                        Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                      new MessageDialog("Please come back soon", "GoodBye")
                      .ShowAsync());
                        break;
                    case GeofenceState.None:
                        break;
                    case GeofenceState.Removed:
                        break;
                    default:
                        break;
                }
            }
        
    };
 
    var jayway = new Geopoint(new BasicGeoposition()
    {
        Latitude = lati, Longitude = longi
    });
    var geofence = new Geofence("has llegado", new Geocircle(jayway.Position, 400),
        MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited,
        false, TimeSpan.FromSeconds(10));
    geofenceMonitor.Geofences.Add(geofence);
}
Пример #8
1
        public void GeofenceMark(double lati, double longi)
        {
            _monitor.GeofenceStateChanged += _monitor_GeofenceStateChanged;
            _monitor.Geofences.Clear();
            //Ruta N, Medellin building
            BasicGeoposition pos = new BasicGeoposition { Latitude = lati, Longitude = longi };
            Geofence fence = new Geofence("Building 9", new Geocircle(pos, 100));

            try
            {
                _monitor.Geofences.Add(fence);
            }
            catch (Exception)
            {
                
                throw;
            }
        }
        public void changeDoor()
        {
            if (Player.Level != null)
            {
                int radius = 0;
                int timeGiven = 10;
                if(this.Difficult.Equals(KnockingDoors.Difficulties.First_Time)){
                    radius = 100;
                    timeGiven = 360;
                }
                else if (this.Difficult.Equals(KnockingDoors.Difficulties.Been_Here))
                {
                    radius = 250;
                    timeGiven = 480;
                }
                else if (this.Difficult.Equals(KnockingDoors.Difficulties.Born_Here))
                {
                    radius = 500;
                    timeGiven = 600;
                }

                BasicGeoposition basGeo = mc.getRandomGeoposition(Player.Level.Longitude, Player.Level.Latitude, radius);
                Player.currentDoor = new Door() { Latitude = basGeo.Latitude, Longitude = basGeo.Longitude, TimeLeft = timeGiven, Address = mc.ReverseGeoLoc(basGeo.Latitude, basGeo.Longitude) };

            }

            if (Player.currentDoor != null)
            {
                Geofence gf = new Geofence("Door"+DateTime.Now.Millisecond, new Geocircle(new BasicGeoposition{ Latitude = Player.currentDoor.Latitude, Longitude = Player.currentDoor.Longitude}, 15));
                GeofenceMonitor.Current.Geofences.Clear();

                GeofenceMonitor.Current.Geofences.Add(gf);

                this.ImageStreet = mc.getImageUrlFromGeoPoint(Player.currentDoor.Address);
            }
        }
Пример #10
1
        public void fillGeofences (Company company) {
            ConcurrentQueue<Geofence> geofences = new ConcurrentQueue<Geofence>();

            try {
                mysqlConnection = new MySqlConnection(database.getConnectionString());
                mysqlConnection.Open();

                string sql =
                     "SELECT * " +
                     "FROM cmp_" + company.DatabaseName + ".gf";

                MySqlCommand mySqlCommand = new MySqlCommand(sql, mysqlConnection);
                MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();

                if (!mySqlDataReader.HasRows) {
                    mySqlDataReader.Dispose();
                } else {
                    while (mySqlDataReader.Read()) {
                        Geofence geofence = new Geofence();
                        geofence.Id = mySqlDataReader.GetInt32("gf_id");
                        geofence.Name = mySqlDataReader.GetString("gf_name");
                        geofence.Tracks = mySqlDataReader.GetString("gf_trks");

                        string geofenceData = (string)mySqlDataReader["gf_data"];
                        geofenceData = geofenceData.Replace("),( ", "|");
                        geofenceData = geofenceData.Replace(")", string.Empty);
                        geofenceData = geofenceData.Replace("(", string.Empty);
                        geofenceData = geofenceData.Replace(" ", string.Empty);


                        List<string> points = geofenceData.Split('|').ToList();
                        foreach (string point in points) {
                            string[] coordinates = point.Split(',');
                            double latitude = double.Parse(coordinates[0]);
                            double longitude = double.Parse(coordinates[1]);
                            Coordinate location = new Coordinate(latitude, longitude);
                            geofence.addPoint(location);
                        }
                        geofences.Enqueue(geofence);
                    }
                    company.Geofences = geofences;
                    mySqlDataReader.Dispose();
                }
            } catch (MySqlException mySqlException) {
                throw new QueryException(1, mySqlException.Message);
            } catch (QueryException queryException) {
                throw queryException;
            } catch (Exception exception) {
                throw new QueryException(1, exception.Message);
            } finally {
                mysqlConnection.Close();
            }
        }
Пример #11
1
 public Geofence createGeofence(Bing.Maps.Location l,String name)
 {
     Geofence fence = new Geofence(name, new Geocircle(new BasicGeoposition { Altitude = 0.0, Latitude = l.Latitude, Longitude = l.Longitude }, 10));
     return fence;
 }
        // add geofence to listbox
        private void AddGeofenceToRegisteredGeofenceListBox(Geofence geofence)
        {
            GeofenceItem item = new GeofenceItem(geofence);

            // the registered geofence listbox is data bound
            // to the collection stored in the root page
            geofenceCollection.Insert(0, item);
        }
Пример #13
1
        public void RefreshTriggerFence(BasicGeoposition location)
        {
            // The partition size on the server is a rectangle with sides of 0.01 degree, 
            // so draw a circle to the closest edge of the rectangle           
           
            double closestLat = Math.Round(location.Latitude, 2);
            double distanceToClosestLat = Math.Abs(closestLat - location.Latitude);
            double closestLon = Math.Round(location.Longitude, 2);
            double distanceToClosestLon =  Math.Abs(closestLon - location.Longitude);

            BasicGeoposition closestEdge = new BasicGeoposition();
            if(distanceToClosestLon < distanceToClosestLat){
                closestEdge.Latitude = location.Latitude;
                closestEdge.Longitude = closestLon;
            }
            else
            {
                closestEdge.Longitude = location.Longitude;
                closestEdge.Latitude = closestLat;
            }

            var distance = Distance(location, closestEdge);
            // Disallow distance of 0 meters, default to 1 meter
            if (distance == 0)
            {
                distance = 1;
            }

            TriggerFence = new Geofence(
                    "WindowsAzure.TriggerFence",
                    new Geocircle(
                        new BasicGeoposition
                        {
                            Altitude = 0,
                            Latitude = location.Latitude,
                            Longitude = location.Longitude
                        },
                        distance
                    ), 
                    MonitoredGeofenceStates.Exited,
                    false,
                    TimeSpan.FromSeconds(1));
        }
Пример #14
1
 /// <summary>
 /// Create geo fence around certain geopoint with a given radius
 /// </summary>
 /// <param name="fenceKey">The key of the fence</param>
 /// <param name="latitude">Latitude of the geo fence</param>
 /// <param name="longitude">Longitude of the geo fence</param>
 /// <param name="radius">Radius of the geo fence</param>
 /// <param name="fenceColor">UI color of the geo fence</param>
 private void CreateGeofence( string fenceKey, double latitude, double longitude, double radius, Color fenceColor )
 {
     if( GeofenceMonitor.Current.Geofences.All( v => v.Id != fenceKey ) )
     {
         var position = new BasicGeoposition { Latitude = latitude, Longitude = longitude, Altitude = 0.0 };
         CreateCircle( position, radius, fenceColor );
         // The geofence is a circular region
         var geocircle = new Geocircle( position, radius );
         // Listen for enter geofence and exit geofence events
         MonitoredGeofenceStates mask = 0;
         mask |= MonitoredGeofenceStates.Entered;
         mask |= MonitoredGeofenceStates.Exited;
         var geofence = new Geofence( fenceKey, geocircle, mask, false );
         GeofenceMonitor.Current.Geofences.Add( geofence );
         GeofenceMonitor.Current.StatusChanged += GeoFence_StatusChanged;
     }
     else
     {
         foreach( var f in GeofenceMonitor.Current.Geofences.Where( f => f.Id == fenceKey ) )
         {
             var x = f.Geoshape as Geocircle;
             if( x != null )
             {
                 CreateCircle( x.Center, x.Radius, fenceColor );
             }
             break;
         }
     }
 }
        /// <summary>
        /// This method removes the geofence from the client side geofences collection
        /// </summary>
        /// <param name="geofence"></param>
        private void Remove(Geofence geofence)
        {
            try
            {
                if (!geofences.Remove(geofence))
                {
                    var strMsg = "Could not find Geofence " + geofence.Id + " in the geofences collection";

                    rootPage.NotifyUser(strMsg, NotifyType.StatusMessage);
                }
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
Пример #16
1
        private void AddPushpin(Waypoint poi, int ID)
        {
            Pushpin pp = null;
            if (poi is PointOfInterest)
            {
                PointOfInterest poii = poi as PointOfInterest;
                pp = new Pushpin()
                {
                    Tag = new InfoBoxData() { Title = poii.Name, Description = poii.Information, ImagePath = poii.ImagePath }
                };
                pp.Background = new SolidColorBrush(Windows.UI.Colors.Red);
            }
            else
            {
                pp = new Pushpin();
                pp.Background = new SolidColorBrush(Windows.UI.Colors.Blue);
            }

            MapLayer.SetPosition(pp, new Location(poi.Latitude, poi.Longitude));
            pp.Tapped += PinTapped;
            layer.Children.Add(pp);

            Geocircle circle = new Geocircle(new BasicGeoposition() { Latitude = poi.Latitude, Longitude = poi.Longitude, Altitude=0 }, 15);
            Geofence fence = new Geofence(""+ID, circle, MonitoredGeofenceStates.Entered, false, new TimeSpan(10));
            
            GeofenceMonitor.Current.Geofences.Add(fence);
        }
Пример #17
0
        //围栏被触发委托
        private async void Current_GeofenceStateChanged(GeofenceMonitor sender, object args)
        {
            var reports = sender.ReadReports();

            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                foreach (GeofenceStateChangeReport report in reports)
                {
                    GeofenceState state = report.NewState;

                    Geofence geofence = report.Geofence;

                    if (state == GeofenceState.Removed)
                    {
                        // Remove the geofence from the geofences collection.
                        GeofenceMonitor.Current.Geofences.Remove(geofence);
                    }
                    else if (state == GeofenceState.Entered)
                    {
                        // Your app takes action based on the entered event.

                        // NOTE: You might want to write your app to take a particular
                        // action based on whether the app has internet connectivity.
                    }
                    else if (state == GeofenceState.Exited)
                    {
                        // Your app takes action based on the exited event.

                        // NOTE: You might want to write your app to take a particular
                        // action based on whether the app has internet connectivity.
                    }
                }
            });
        }
Пример #18
0
        public static void CreateGeofence(string id, double lat, double lon, double radius)
        {
            if (GeofenceMonitor.Current.Geofences.SingleOrDefault(g => g.Id == id) != null)
            {
                return;
            }

            var position = new BasicGeoposition();

            position.Latitude  = lat;
            position.Longitude = lon;

            var geocircle = new Geocircle(position, radius);

            MonitoredGeofenceStates mask = 0;

            mask |= MonitoredGeofenceStates.Entered;
            // Uncomment these to monitor other states
            mask |= MonitoredGeofenceStates.Exited;
            mask |= MonitoredGeofenceStates.Removed;

            // Create Geofence with the supplied id, geocircle and mask, not for single use
            // and with a dwell time of 5 seconds

            //MessageBox.Show(string.Format("Geofence {0} created!", id.ToString()));
            var geofence = new Geofence(id, geocircle, mask, false, new TimeSpan(0, 0, 5));

            GeofenceMonitor.Current.Geofences.Add(geofence);
        }
Пример #19
0
        private void Add_Click(object sender, RoutedEventArgs e)
        {
            Geofence geofence;

            string id = this.tBoxName.Text;

            BasicGeoposition position;

            position.Latitude  = Double.Parse(this.tBoxLatitude.Text);
            position.Longitude = Double.Parse(this.tBoxLongitude.Text);
            position.Altitude  = 0.0;
            double radius = Double.Parse(this.tBoxRadius.Text);

            // the geofence is a circular region
            Geocircle geocircle = new Geocircle(position, radius);

            // want to listen for enter geofence, exit geofence and remove geofence events
            // you can select a subset of these event states
            MonitoredGeofenceStates mask = 0;

            mask |= MonitoredGeofenceStates.Entered;
            mask |= MonitoredGeofenceStates.Exited;
            mask |= MonitoredGeofenceStates.Removed;

            TimeSpan dwellTime = new TimeSpan(0);

            geofence = new Geofence(id, geocircle, mask, false, dwellTime);

            this.geoservice.AddGeofence(geofence);
        }
Пример #20
0
        private async Task <int> CreateGeofence(Geofence geofence, Geofence existing)
        {
            Log.LogDebug($"GeofenceRepository/CreateGeofence: geofence={JsonConvert.SerializeObject(geofence)}");

            if (existing == null)
            {
                Log.LogDebug($"GeofenceRepository/CreateGeofence: going to create geofence={geofence.GeofenceUID}");

                var formattedPolygon = RepositoryHelper.WKTToSpatial(geofence.GeometryWKT);

                var insert =
                    "INSERT Geofence " +
                    "     (GeofenceUID, Name, Description, PolygonST, FillColor, IsTransparent, IsDeleted, fk_CustomerUID, UserUID, LastActionedUTC, fk_GeofenceTypeID, AreaSqMeters) " +
                    " VALUES " +
                    $"     (@GeofenceUID, @Name, @Description, {formattedPolygon}, @FillColor, @IsTransparent, @IsDeleted, @CustomerUID, @UserUID, @LastActionedUTC, @GeofenceType, @AreaSqMeters)";

                var upsertedCount = await ExecuteWithAsyncPolicy(insert, geofence);

                Log.LogDebug(
                    $"GeofenceRepository/CreateGeofence upserted {upsertedCount} rows for: geofenceUid:{geofence.GeofenceUID}");
                return(upsertedCount);
            }

            Log.LogDebug(
                $"GeofenceRepository/CreateGeofence: can't create as already exists geofence={geofence.GeofenceUID}, going to update it");
            return(await UpdateGeofence(geofence, existing));
        }
Пример #21
0
        public void bboxesFromGeoPolygon()
        {
            List <GeoCoord> verts =
                new List <GeoCoord>
            {
                new GeoCoord(0.8, 0.3),
                new GeoCoord(0.7, 0.6),
                new GeoCoord(1.1, 0.7),
                new GeoCoord(1.0, 0.2)
            };
            Geofence geofence = new Geofence {
                numVerts = 4, verts = verts.ToArray()
            };
            GeoPolygon polygon = new GeoPolygon {
                Geofence = geofence, numHoles = 0
            };

            BBox expected = new BBox {
                north = 1.1, south = 0.7, east = 0.7, west = 0.2
            };

            List <BBox> result = new List <BBox>();

            result.Add(new BBox());
            Polygon.bboxesFromGeoPolygon(polygon, ref result);
            Assert.True(BBox.bboxEquals(result[0], expected), "Got expected bbox");
        }
Пример #22
0
        public void polyfillExact()
        {
            GeoCoord    somewhere = new GeoCoord(1, 2);
            H3Index     origin    = H3Index.geoToH3(ref somewhere, 9);
            GeoBoundary boundary  = new GeoBoundary();

            H3Index.h3ToGeoBoundary(origin, ref boundary);

            List <GeoCoord> verts = new GeoCoord [boundary.numVerts + 1].ToList();

            for (int i = 0; i < boundary.numVerts; i++)
            {
                verts[i] = boundary.verts[i];
            }
            verts[boundary.numVerts] = boundary.verts[0];

            Geofence someGeofence = new Geofence();

            someGeofence.numVerts = boundary.numVerts + 1;
            someGeofence.verts    = verts.ToArray();
            GeoPolygon someHexagon = new GeoPolygon();

            someHexagon.Geofence = someGeofence;
            someHexagon.numHoles = 0;

            int numHexagons = Algos.maxPolyfillSize(ref someHexagon, 9);
            var hexagons    = new ulong[numHexagons].Select(cell => new H3Index(cell)).ToList();

            Algos.polyfill(someHexagon, 9, hexagons);
            int actualNumHexagons = countActualHexagons(hexagons, numHexagons);

            Assert.True(actualNumHexagons == 1, "got expected polyfill size (1)");
        }
Пример #23
0
        readonly GeofenceMonitor _monitor = GeofenceMonitor.Current;                                //Maak klasse aan

        public MainPage()                                                                           //Constructor
        {
            InitializeComponent();

            AppInfo appinfo = new AppInfo();                                                        //Binding appinfo

            appinfo.AppNaam        = "GeoTrackerUCLL";                                              //Binding appinfo
            TitlePanel.DataContext = appinfo;                                                       //Binding appinfo

            var dwellTimes = TimeSpan.FromSeconds(2);                                               //Verplicht aantal miliseconds dat men binnen de geolocatie moet zijn vooraleer code verder gaat
            var mask       = MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited;      //mask meegeven, binnen de zone of buiten de zone

            geolocator.MovementThreshold = 10;

            var pos = new BasicGeoposition {
                Latitude = 50.929125, Longitude = 5.395183
            };                                                                                      //Geef longitude en latitude van positie mee (Zone UCLL in diepenbeek)

            Geofence fence = new Geofence("UCLL", new Geocircle(pos, 50), mask, false, dwellTimes); //Maak nieuwe geofence met behulp van de meegegeven variabelen

            _monitor.GeofenceStateChanged += MonitorOnGeofenceStateChanged;                         //ga naar functie (MonitorOnGeofenceStateChanged)

            try
            {
                _monitor.Geofences.Clear();                                                         //Verwijder eerdere toegevoegde geofences
                _monitor.Geofences.Add(fence);
            }
            catch (Exception)
            {
                //geofence is al aan het systeem toegevoegd
            }
        }
Пример #24
0
        private static void OnGeofenceStateChanged(System.Collections.Generic.IReadOnlyList <GeofenceStateChangeReport> reports)
        {
            foreach (GeofenceStateChangeReport report in reports)
            {
                GeofenceState state = report.NewState;

                Geofence geofence = report.Geofence;

                if (state == GeofenceState.Removed)
                {
                    // remove the geofence from the geofences collection
                    GeofenceMonitor.Current.Geofences.Remove(geofence);
                    MessageBox.Show(string.Format("Geofence Id: {0}, was removed.", geofence.Id));
                }
                else if (state == GeofenceState.Entered)
                {
                    // Your app takes action based on the entered event

                    // NOTE: You might want to write your app to take particular
                    // action based on whether the app has internet connectivity.
                    MessageBox.Show(string.Format("Geofence Id: {0}, just entered.", geofence.Id));
                }
                else if (state == GeofenceState.Exited)
                {
                    // Your app takes action based on the exited event

                    // NOTE: You might want to write your app to take particular
                    // action based on whether the app has internet connectivity.
                    MessageBox.Show(string.Format("Geofence Id: {0}, just exited.", geofence.Id));
                }
            }
        }
Пример #25
0
        public async Task HydrateJsonWithBoundary_HappyPath_Custom(FilterType filterType)
        {
            var log          = serviceProvider.GetRequiredService <ILoggerFactory>().CreateLogger <ValidationTests>();
            var geofenceRepo = new Mock <IGeofenceRepository>();
            var geofence     = new Geofence {
                GeofenceUID = boundaryUid, Name = Name, GeometryWKT = GeometryWKT, GeofenceType = GeofenceType.Filter
            };

            geofenceRepo.Setup(g => g.GetGeofence(It.IsAny <string>())).ReturnsAsync(geofence);
            //var geofenceProxy = new Mock<IGeofenceProxy>();
            var request = FilterRequestFull.Create(null, custUid, false, userUid, new ProjectData {
                ProjectUID = projectUid
            },
                                                   new FilterRequest
            {
                FilterUid  = filterUid,
                Name       = "a filter",
                FilterType = filterType,
                FilterJson = "{\"designUid\": \"id\", \"vibeStateOn\": true, \"polygonUid\": \"" + geofence.GeofenceUID +
                             "\"}"
            });

            var result = await ValidationUtil
                         .HydrateJsonWithBoundary(/*geofenceProxy.Object,*/ geofenceRepo.Object, log, serviceExceptionHandler, request).ConfigureAwait(false);

            var expectedResult =
                "{\"designUid\":\"id\",\"vibeStateOn\":true,\"polygonUid\":\"" + geofence.GeofenceUID +
                "\",\"polygonName\":\"" + geofence.Name +
                "\",\"polygonLL\":[{\"Lat\":12.677856,\"Lon\":80.257874},{\"Lat\":13.039345,\"Lon\":79.856873},{\"Lat\":13.443052,\"Lon\":80.375977}]," +
                "\"polygonType\":" + (int)geofence.GeofenceType + "}";

            Assert.Equal(expectedResult, result);
        }
Пример #26
0
        public async Task HydrateJsonWithBoundary_InvalidBoundary2(FilterType filterType)
        {
            var log          = serviceProvider.GetRequiredService <ILoggerFactory>().CreateLogger <ValidationTests>();
            var geofenceRepo = new Mock <IGeofenceRepository>();
            var geofence     = new Geofence
            {
                GeofenceType = GeofenceType.Filter,
                GeometryWKT  =
                    "POLYGON((-115.0200886019198 36.20745605916501,-115.02005976817289 36.20734622441246,-115.01992699882665 36.2073559634608,-115.0198176988093 36.207342978062755,-115.01973320922532 36.20734027277125,-115.01974729082266 36.20738950906242,-115.01975466689743 36.2074300884,-115.01996052643932 36.20746201079744))"
            };

            // var geofence = new Geofence { GeometryWKT = "POLYGON((-115.02022874734084 36.20751287018342,-115.02025556943099 36.207300775504265,-115.02001953503766 36.20729428280093,-115.01966816565673 36.20726506562927,-115.01945493004004 36.20714170411769,-115.0192846097676 36.20734189594616,-115.01962927362601 36.20748581732266,-115.02022874734084 36.20751287018342))" };
            geofenceRepo.Setup(g => g.GetGeofence(It.IsAny <string>())).ReturnsAsync(geofence);
            //var geofenceProxy = new Mock<IGeofenceProxy>();
            //var geofenceData = new GeofenceData { GeofenceType = GeofenceType.Generic.ToString(), GeometryWKT = geofence.GeometryWKT };
            //geofenceProxy.Setup(g => g.GetGeofenceForCustomer(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<HeaderDictionary>())).ReturnsAsync(geofenceData);

            var request = FilterRequestFull.Create(null, custUid, false, userUid, new ProjectData {
                ProjectUID = projectUid
            },
                                                   new FilterRequest
            {
                FilterUid  = filterUid,
                Name       = "a filter",
                FilterType = filterType,
                FilterJson = "{\"designUID\": \"id\", \"vibeStateOn\": true, \"polygonUID\": \"" + boundaryUid + "\"}"
            });

            var ex = await Assert.ThrowsAsync <ServiceException>(async() => await ValidationUtil
                                                                 .HydrateJsonWithBoundary(/*geofenceProxy.Object,*/ geofenceRepo.Object, log, serviceExceptionHandler, request).ConfigureAwait(false));

            Assert.Contains("2045", ex.GetContent);
            Assert.Contains("Invalid spatial filter boundary. One or more polygon components are missing.", ex.GetContent);
        }
Пример #27
0
        public async Task HydrateJsonWithBoundary_InvalidBoundary(FilterType filterType)
        {
            var log          = serviceProvider.GetRequiredService <ILoggerFactory>().CreateLogger <ValidationTests>();
            var geofenceRepo = new Mock <IGeofenceRepository>();
            var geofence     = new Geofence {
                GeometryWKT = "This is not a valid polygon WKT", GeofenceType = GeofenceType.Filter
            };

            geofenceRepo.Setup(g => g.GetGeofence(It.IsAny <string>())).ReturnsAsync(geofence);
            //var geofenceProxy = new Mock<IGeofenceProxy>();
            var geofenceData = new GeofenceData {
                GeometryWKT = geofence.GeometryWKT, GeofenceType = GeofenceType.Generic.ToString()
            };
            //geofenceProxy.Setup(g => g.GetGeofenceForCustomer(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<HeaderDictionary>())).ReturnsAsync(geofenceData);

            var request = FilterRequestFull.Create(null, custUid, false, userUid, new ProjectData {
                ProjectUID = projectUid
            },
                                                   new FilterRequest
            {
                FilterUid  = filterUid,
                Name       = "a filter",
                FilterType = filterType,
                FilterJson = "{\"designUID\": \"id\", \"vibeStateOn\": true, \"polygonUID\": \"" + boundaryUid + "\"}"
            });

            var ex = await Assert.ThrowsAsync <ServiceException>(async() => await ValidationUtil
                                                                 .HydrateJsonWithBoundary(/*geofenceProxy.Object,*/ geofenceRepo.Object, log, serviceExceptionHandler, request).ConfigureAwait(false));

            Assert.Contains("2045", ex.GetContent);
            Assert.Contains("Invalid spatial filter boundary. One or more polygon components are missing.", ex.GetContent);
        }
Пример #28
0
        public async void OnGeofenceStateChangedHandler(GeofenceMonitor sender, object e)
        {
            bool tagsChanged = false;
            var  reports     = sender.ReadReports();


            foreach (GeofenceStateChangeReport report in reports)
            {
                GeofenceState state = report.NewState;

                Geofence geofence = report.Geofence;

                if (!String.Equals(geofence.Id, triggerFenceName))
                {
                    if (state == GeofenceState.Removed)
                    {
                    }
                    else if (state == GeofenceState.Entered)
                    {
                        tags.Add(geofence.Id);
                        tagsChanged = true;
                    }
                    else if (state == GeofenceState.Exited)
                    {
                        tags.RemoveAll(x => String.Equals(x, geofence.Id));
                        tagsChanged = true;
                    }
                }
            }

            if (tagsChanged)
            {
                await hub.RegisterAsync(GenerateRegistration());
            }
        }
Пример #29
0
        public Geofence CreateGeofence(string fenceID, double latitude, double longitude, double altitude, double radius, bool singleUse, int dwellTime, int duration)
        {
            _fenceId = fenceID;
                        // Define the fence location and radius.
                        BasicGeoposition position;

            position.Latitude  = latitude;
            position.Longitude = longitude;
            position.Altitude  = altitude;
            _radius            = radius; // in meters

            // Set the circular region for geofence.
            _geocircle = new Geocircle(position, radius);

            // Remove the geofence after the first trigger.
            _singleUse = singleUse;

            // Set the monitored states.
            _monitoredStates = MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited | MonitoredGeofenceStates.Removed;

            // Set how long you need to be in geofence for the enter event to fire.
            _dwellTime = TimeSpan.FromSeconds(dwellTime);

            // Set how long the geofence should be active.
            _duration = TimeSpan.FromDays(duration);

            // Set up the start time of the geofence.
            _startTime = DateTime.Now;

            // Create the geofence.
            _geofence = new Geofence(_fenceId, _geocircle, _monitoredStates, _singleUse, _dwellTime, _startTime, _duration);
            return(_geofence);
        }
Пример #30
0
            static async Task RegisterFenceAsync(double fenceRadius,
                                                 MonitoredGeofenceStates monitoredStates,
                                                 TimeSpan dwellTime)
            {
                // Where are we?
                BasicGeoposition position = await GetCurrentLocationAsync();

                Geofence fence = null;

                // Get rid of any existing geofences. This is a bit of a TBD. The fence I'm
                // creating is meant to be a single-use fence so my understanding would be
                // that the system gets rid of it for me. Maybe the system will do that
                // "later" but, right now, it's still there so if I try and add a fence
                // with the same ID I'll get an error so I remove the original fence
                // myself.
                if (IsFenceRegistered)
                {
                    fence = GeofenceMonitor.Current.Geofences.First(
                        f => f.Id == FENCE_ID);

                    GeofenceMonitor.Current.Geofences.Remove(fence);
                }
                fence = new Geofence(
                    FENCE_ID,
                    new Geocircle(position, fenceRadius),
                    monitoredStates,
                    false, // means it's not a single-use event
                    dwellTime);

                GeofenceMonitor.Current.Geofences.Add(fence);
            }
        public HttpResponseMessage Put(Geofence geofence, int id)
        {
            ModelState.Remove("geofence.Geography");
            if (!ModelState.IsValid)
            {
                return(this.ModelStateResult());
            }

            Geofence item = this.repository.GetById(id);

            if (item == null || item.User.Id != CurrentUser.Id)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            item.Name    = geofence.Name;
            item.GroupId = geofence.GroupId;
            if (item.BufferRadius != geofence.BufferRadius)
            {
                item.BufferRadius    = geofence.BufferRadius;
                item.GeoJSON         = item.Geography.ToGeoJSON();
                item.GeoJSONBuffered = item.Geography.Buffer(item.BufferRadius).ToGeoJSON();
            }

            this.repository.Save(item);

            return(Request.CreateResponse(HttpStatusCode.Accepted, item));
        }
Пример #32
0
        private void AddGeofenceToMap([NotNull] Geofence fence)
        {
            if (fence == null)
            {
                throw new ArgumentNullException("fence");
            }

            var geocircle = (Geocircle)fence.Geoshape;
            var circle    = new MapPolygon
            {
                FillColor = Color.FromArgb(128, 0, 0, 255),
                Locations = GetCircleLocations(geocircle.Center, geocircle.Radius)
            };

            // Get the first shape layer for the circles, or add a new one to accomodate
            var shapeLayer = ExampleMap.ShapeLayers.FirstOrDefault();

            if (shapeLayer == null)
            {
                shapeLayer = new MapShapeLayer();
                ExampleMap.ShapeLayers.Add(shapeLayer);
            }
            shapeLayer.Shapes.Add(circle);

            var pushpin = new Pushpin();

            pushpin.Tapped += (sender, args) => ShowPinMessage(fence);

            MapLayer.SetPosition(pushpin, new Location(geocircle.Center.Latitude, geocircle.Center.Longitude));
            ExampleMap.Children.Add(pushpin);

            _mapFenceElements.Add(fence.Id, new MapElements {
                Circle = circle, Pin = pushpin
            });
        }
Пример #33
0
        public void bboxFromGeofenceTransmeridian()
        {
            List <GeoCoord> verts =
                new List <GeoCoord>
            {
                new GeoCoord(0.1, -Constants.M_PI + 0.1),
                new GeoCoord(0.1, Constants.M_PI - 0.1),
                new GeoCoord(0.05, Constants.M_PI - 0.2),
                new GeoCoord(-0.1, Constants.M_PI - 0.1),
                new GeoCoord(-0.1, -Constants.M_PI + 0.1),
                new GeoCoord(-0.05, -Constants.M_PI + 0.2)
            };
            Geofence geofence = new Geofence {
                numVerts = 6, verts = verts.ToArray()
            };

            BBox expected = new BBox
            {
                north = 0.1, south = -0.1, east = -Constants.M_PI + 0.2,
                west  = Constants.M_PI - 0.2
            };

            BBox result = new BBox();

            Polygon.bboxFromGeofence(ref geofence, ref result);
            Assert.True
            (
                BBox.bboxEquals(result, expected),
                "Got expected transmeridian bbox"
            );
        }
Пример #34
0
        /// <summary>
        /// Create a geo-fence around certain geopoint with a given radius
        /// </summary>
        /// <param name="fenceKey"></param>
        /// <param name="latitude"></param>
        /// <param name="longitude"></param>
        /// <param name="radius"></param>
        private void CreateGeofence(string fenceKey, double latitude, double longitude, double radius, Color fenceColor)
        {
            if (GeofenceMonitor.Current.Geofences.All(v => v.Id != fenceKey))
            {
                var position = new BasicGeoposition {
                    Latitude = latitude, Longitude = longitude, Altitude = 0.0
                };
                CreateCircle(position, radius, fenceColor);

                // the geofence is a circular region
                var geocircle = new Geocircle(position, radius);

                // Listen for enter geofence and exit geofence events
                MonitoredGeofenceStates mask = 0;

                mask |= MonitoredGeofenceStates.Entered;
                mask |= MonitoredGeofenceStates.Exited;

                var geofence = new Geofence(fenceKey, geocircle, mask, false);
                GeofenceMonitor.Current.Geofences.Add(geofence);
                GeofenceMonitor.Current.StatusChanged += EnterFence;
            }
            else
            {
                foreach (var f in GeofenceMonitor.Current.Geofences.Where(f => f.Id == fenceKey))
                {
                    var x = f.Geoshape as Geocircle;
                    if (x != null)
                    {
                        CreateCircle(x.Center, x.Radius, fenceColor);
                    }
                    break;
                }
            }
        }
Пример #35
0
        public void pointInsideGeofence()
        {
            Geofence geofence = new Geofence {
                numVerts = 6, verts = sfVerts.ToArray()
            };

            GeoCoord inside    = new GeoCoord(0.659, -2.136);
            GeoCoord somewhere = new GeoCoord(1, 2);

            BBox bbox = new BBox();

            BBox.bboxFromGeofence(geofence, ref bbox);

            var v0 = sfVerts[0];

            Assert.True(!Polygon.pointInsideGeofence(ref geofence, ref bbox, ref v0),
                        "contains exact");
            var v4 = sfVerts[4];

            Assert.True(Polygon.pointInsideGeofence(ref geofence, ref bbox, ref v4),
                        "contains exact 4");
            Assert.True(Polygon.pointInsideGeofence(ref geofence, ref bbox, ref inside),
                        "contains point inside");
            Assert.True(!Polygon.pointInsideGeofence(ref geofence, ref bbox, ref somewhere),
                        "contains somewhere else");
        }
Пример #36
0
        /// <summary>
        ///     All detail-related columns can be inserted,
        ///     but only certain columns can be updated.
        ///     on deletion, a flag will be set.
        /// </summary>
        /// <param name="geofence"></param>
        /// <param name="eventType"></param>
        /// <returns></returns>
        private async Task <int> UpsertGeofenceDetail(Geofence geofence, string eventType)
        {
            var upsertedCount = 0;
            var existing      = (await QueryWithAsyncPolicy <Geofence>
                                     (@"SELECT 
              GeofenceUID, Name, fk_GeofenceTypeID AS GeofenceType, ST_ASWKT(PolygonST) AS GeometryWKT, FillColor, IsTransparent,
              IsDeleted, Description, fk_CustomerUID AS CustomerUID, UserUID, AreaSqMeters,
              LastActionedUTC   
            FROM Geofence
            WHERE GeofenceUID = @GeofenceUID",
                                     new { geofence.GeofenceUID }
                                     )).FirstOrDefault();

            if (eventType == "CreateGeofenceEvent")
            {
                upsertedCount = await CreateGeofence(geofence, existing);
            }

            if (eventType == "UpdateGeofenceEvent")
            {
                upsertedCount = await UpdateGeofence(geofence, existing);
            }

            if (eventType == "DeleteGeofenceEvent")
            {
                upsertedCount = await DeleteGeofence(geofence, existing);
            }

            return(upsertedCount);
        }
Пример #37
0
        public override void onReceive(Context arg0, Intent arg1)
        {
            TestTip.Inst.ShowText("GeoFenceBroadcast success");
            GeofenceData geofenceData = GeofenceData.getDataFromIntent(arg1);
            string       s            = "receive\n";

            if (geofenceData != null)
            {
                int      errorCode  = geofenceData.getErrorCode();
                int      conversion = geofenceData.getConversion();
                List     list       = geofenceData.getConvertingGeofenceList();
                Location mLocation  = geofenceData.getConvertingLocation();
                bool     status     = geofenceData.isSuccess();
                s += "errorcode: " + errorCode.ToString() + "\n";
                s += "conversion: " + conversion.ToString() + "\n";
                for (int i = 0; i < list.toArray().Length; i++)
                {
                    Geofence g = HmsUtil.GetHmsBase <Geofence>(list.toArray()[i]);
                    s += ("geoFence id :" + g.getUniqueId() + "\n");
                }
                s += ("location is :" + mLocation.getLongitude() + " " + mLocation.getLatitude() + "\n");
                s += ("is successful :" + status);
            }
            TestTip.Inst.ShowText(s);
        }
Пример #38
0
        private void AddPushpin(Waypoint poi, int ID)
        {
            Pushpin pp = null;

            if (poi is PointOfInterest)
            {
                PointOfInterest poii = poi as PointOfInterest;
                pp = new Pushpin()
                {
                    Tag = new InfoBoxData()
                    {
                        Title = poii.Name, Description = poii.Information, ImagePath = poii.ImagePath
                    }
                };
                pp.Background = new SolidColorBrush(Windows.UI.Colors.Red);
            }
            else
            {
                pp            = new Pushpin();
                pp.Background = new SolidColorBrush(Windows.UI.Colors.Blue);
            }

            MapLayer.SetPosition(pp, new Location(poi.Latitude, poi.Longitude));
            pp.Tapped += PinTapped;
            layer.Children.Add(pp);

            Geocircle circle = new Geocircle(new BasicGeoposition()
            {
                Latitude = poi.Latitude, Longitude = poi.Longitude, Altitude = 0
            }, 15);
            Geofence fence = new Geofence("" + ID, circle, MonitoredGeofenceStates.Entered, false, new TimeSpan(10));

            GeofenceMonitor.Current.Geofences.Add(fence);
        }
Пример #39
0
        /// <summary>
        /// This is the click handler for the 'Create Geofence' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnCreateGeofence(object sender, RoutedEventArgs e)
        {
            try
            {
                // get lat/long/radius, the fence name (fenceKey),
                // and other properties from controls,
                // depending on data in controls for activation time
                // and duration the appropriate
                // constructor will be used.
                Geofence geofence = GenerateGeofence();

                // Add the geofence to the GeofenceMonitor's
                // collection of fences
                geofences.Add(geofence);

                // add geofence to listbox
                AddGeofenceToRegisteredGeofenceListBox(geofence);
            }
            catch (TaskCanceledException)
            {
                _rootPage.NotifyUser("Canceled", NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                // GeofenceMonitor failed in adding a geofence
                // exceptions could be from out of memory, lat/long out of range,
                // too long a name, not a unique name, specifying an activation
                // time + duration that is still in the past
                _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
        private void CreateGeofence()
        {
            Geofence geofence = null;

            string fenceKey = "Test";

            BasicGeoposition position;

            position.Latitude  = 35.246166;
            position.Longitude = 33.035971;
            position.Altitude  = 0.0;
            //            35.246166, 33.035971


            // the geofence is a circular region
            Geocircle geocircle = new Geocircle(position, 50);


            // want to listen for enter geofence, exit geofence and remove geofence events
            // you can select a subset of these event states
            MonitoredGeofenceStates mask = 0;

            mask |= MonitoredGeofenceStates.Entered;
            mask |= MonitoredGeofenceStates.Exited;
            mask |= MonitoredGeofenceStates.Removed;



            geofence = new Geofence(fenceKey, geocircle, mask, false);
            GeofenceMonitor.Current.Geofences.Add(geofence);
        }
Пример #41
0
        private Geofence CreatGeofence(BasicGeoposition position)
        {
            string fenceId = "fence";
            // Define the fence location and radius.
            //BasicGeoposition position;
            //position.Latitude = 47.6510;
            //position.Longitude = -122.3473;
            //position.Altitude = 0.0;
            double radius = 100000; // in meters
            // Set the circular region for geofence.
            Geocircle geocircle = new Geocircle(position, radius);
            // Remove the geofence after the first trigger.
            bool singleUse = true;
            // Set the monitored states.
            MonitoredGeofenceStates monitoredStates =
                MonitoredGeofenceStates.Entered |
                MonitoredGeofenceStates.Exited |
                MonitoredGeofenceStates.Removed;
            // Set how long you need to be in geofence for the enter event to fire.
            TimeSpan dwellTime = TimeSpan.FromMinutes(1);

            // Set how long the geofence should be active.
            TimeSpan duration = TimeSpan.FromDays(1);

            // Set up the start time of the geofence.
            DateTimeOffset startTime = DateTime.Now;

            // Create the geofence.
            Geofence geofence = new Geofence(fenceId, geocircle, monitoredStates, singleUse, dwellTime, startTime, duration);

            return(geofence);
        }
Пример #42
0
        /// <summary>
        /// This method creates a Geofence for a given Shoppinglist.
        /// </summary>
        /// <param name="shop">Object for which a Geofence should be created.</param>
        private Geofence CreateGeofence(Shop shop)
        {
            Geocircle circle = new Geocircle((BasicGeoposition)shop.Location, (shop.Radius * 1000));

            //Selecting a subset of the events we need to interact with the geofence
            const MonitoredGeofenceStates geoFenceStates = MonitoredGeofenceStates.Entered;

            // Setting up how long you need to be in geofence for enter event to fire
            TimeSpan dwellTime = TimeSpan.FromSeconds(1);

            // Setting up how long the geofence should be active
            TimeSpan geoFenceDuration = TimeSpan.FromSeconds(0);

            // Setting up the start time of the geofence
            DateTimeOffset geoFenceStartTime = DateTimeOffset.Now;

            // Create object
            Geofence fence = new Geofence
                                 (shop.ID,
                                 circle,
                                 geoFenceStates,
                                 false,
                                 dwellTime,
                                 geoFenceStartTime,
                                 geoFenceDuration);

            return(fence);
        }
Пример #43
0
        private async void weilan_Click(object sender, RoutedEventArgs e)
        {
            var accessStatus = await Geolocator.RequestAccessAsync();

            switch (accessStatus)
            {
            case GeolocationAccessStatus.Allowed:
                Geofence         geofence = CreatGeofence(OwnLocation.Position);
                IList <Geofence> geos     = GeofenceMonitor.Current.Geofences;
                geos.Clear();
                geos.Add(geofence);
                //  FillRegisteredGeofenceListBoxWithExistingGeofences();
                // FillEventListBoxWithExistingEvents();
                // Register for state change events.
                //围栏触发事件
                // GeofenceMonitor.Current.GeofenceStateChanged += Current_GeofenceStateChanged;

                //位置权限更改
                //  GeofenceMonitor.Current.StatusChanged += Current_StatusChanged;
                break;

            case GeolocationAccessStatus.Denied:
                // _rootPage.NotifyUser("Access denied.", NotifyType.ErrorMessage);
                break;

            case GeolocationAccessStatus.Unspecified:
                //_rootPage.NotifyUser("Unspecified error.", NotifyType.ErrorMessage);
                break;
            }
        }
        //创建Geofence
        public bool CreateGeofence(string id, double lat, double lon, double radius, GeofenceStateChangedCallback callback)
        {
            if (GeofenceMonitor.Current.Geofences.SingleOrDefault(g => g.Id == id) != null)
            {
                return(false);
            }

            var position = new BasicGeoposition();

            position.Latitude  = lat;
            position.Longitude = lon;
            var geocircle = new Geocircle(position, radius);

            MonitoredGeofenceStates mask = MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited;

            // Create Geofence with the supplied id, geocircle and mask, not for single use
            // and with a dwell time of 1 seconds
            var geofence = new Geofence(id, geocircle, mask, false, new TimeSpan(0, 0, 1));

            GeofenceMonitor.Current.Geofences.Add(geofence);
            //将回调函数存入geofencesStateChangedCallback
            if (callbacks.ContainsKey(GetGeofenceIndex(geofence)))
            {
                callbacks.Remove(GetGeofenceIndex(geofence));
            }
            callbacks.Add(GetGeofenceIndex(geofence), callback);
            //注册Geofence状态改变回调事件
            GeofenceMonitor.Current.GeofenceStateChanged -= Current_GeofenceStateChanged;
            GeofenceMonitor.Current.GeofenceStateChanged += Current_GeofenceStateChanged;

            return(true);
        }
        /// <summary>
        /// This is the click handler for the 'Create Geofence' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnCreateGeofence(object sender, RoutedEventArgs e)
        {
            Geofence geofence = GenerateGeofence();

            if (geofence != null)
            {
                try
                {
                    // add geofence to GeofenceMonitor
                    geofenceMonitor.Geofences.Add(geofence);
                }
                catch (Exception ex)
                {
                    // GeofenceMonitor failed to add the geofence. Possible reasons include
                    // duplicate or invalid name, invalid position, having a limited-duration
                    // geofence that doesn't leave enough time for the DwellTime to trigger the geofence.
                    _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                    geofence = null;
                }
            }

            if (geofence != null)
            {
                // Update UI after geofence successfully added to GeofenceMonitor.
                AddGeofenceToRegisteredGeofenceListBox(geofence);
            }
        }
        private void AddGeofenceHere_Click(object sender, RoutedEventArgs e)
        {
            ClearStatus();

            try
            {
                double radiusInMeters = Settings.GeofenceRadiusMeters;
                ShowStatus("Adding geofence...");

                var geofences = GeofenceMonitor.Current.Geofences;

                var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff");
                BasicGeoposition position;
                position.Altitude  = 0;
                position.Latitude  = _geoposition.Coordinate.Point.Position.Latitude;
                position.Longitude = _geoposition.Coordinate.Point.Position.Longitude;

                var geocircle = new Geocircle(position, radiusInMeters);
                var geofence  = new Geofence(timestamp, geocircle);
                geofences.Add(geofence);
                Logger.Trace(TraceLevel.Info, String.Format("Added geofence for current location: {0} radius: {1} meters, id {2}",
                                                            Logger.FormatLatLong(position.Latitude, position.Longitude), radiusInMeters, timestamp));

                // Re-center the map since the user wanted a geofence at the current location
                Map.SetView(new Bing.Maps.Location(position.Latitude, position.Longitude));

                GetGeofences_Click(this, null);
            }
            catch (Exception ex)
            {
                Logger.Trace(TraceLevel.Error, "Error adding geofence for current location: " + Logger.FormatException(ex));
                ShowStatus("Could not add geofence for current location: " + ex.Message);
            }
        }
Пример #47
0
 public void MakeNewGeofence(int radius)
 {
     Geocircle circle = new Geocircle(position, radius);
     MonitoredGeofenceStates monitoredStates =
         MonitoredGeofenceStates.Entered |
         MonitoredGeofenceStates.Exited |
         MonitoredGeofenceStates.Removed;
     TimeSpan dwellTime = TimeSpan.FromSeconds(1);
     geofenceRadius = radius;
     geofence = new Geofence(name, circle, monitoredStates, false, dwellTime);
 }
Пример #48
0
        public async Task SetupGeofencesAsync(SetupGeofencingMessage message)
        {
            foreach (var mapFriendViewModel in message.MapFriendViewModel.Where(f => f.Location != null))
            {
                var geofence = new Geofence(mapFriendViewModel.Id, new Geocircle(mapFriendViewModel.Location.Position, 2000), MonitoredGeofenceStates.Entered, false);
                if (geofences.SingleOrDefault(g => g.Id == geofence.Id) == null)
                    geofences.Add(geofence);
            }

            var settings = ApplicationData.Current.LocalSettings;
            var jsonsString = settings.Values["BackgroundGeofenceEventCollection"];

            await RegisterBackgroundTask();
        }
Пример #49
0
        private void UpdateGeofence(string fenceId, double latitude, double longitude)
        {
            var geofence = GeofenceMonitor.Current.Geofences.SingleOrDefault(f => f.Id == fenceId);
            if (geofence != null)
                GeofenceMonitor.Current.Geofences.Remove(geofence);

            var position = new BasicGeoposition();
            position.Latitude = latitude;
            position.Longitude = longitude;

            var area = new Geocircle(position, HomeRadiusInMeters);
            geofence = new Geofence(fenceId, area);

            GeofenceMonitor.Current.Geofences.Add(geofence);
        }
Пример #50
0
        public void loadGeofence(WebBrowser webBrowser, Geofence geofence) {
            if (webBrowser != null) {
                try {
                    htmlDocument = (mshtml.IHTMLDocument3)webBrowser.Document;

                    mshtml.IHTMLElementCollection collection = htmlDocument.getElementsByName("formGeofence");

                    foreach (mshtml.HTMLInputElement element in collection.item(name: "formGeofence")) {

                        if (element.id == "geofenceId") {
                            element.value = geofence.Id.ToString();
                        }

                        if (element.id == "geofenceCoordinates") {
                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.Append("[");
                            foreach (Coordinate coordinate in geofence.getPoints()) {
                                stringBuilder.Append("{\"Latitude\":\"");
                                stringBuilder.Append(coordinate.latitude.ToString());
                                stringBuilder.Append("\",\"Longitude\":\"");
                                stringBuilder.Append(coordinate.longitude.ToString());
                                stringBuilder.Append("\"},");
                            }
                            stringBuilder.Remove(stringBuilder.Length - 1, 1);
                            stringBuilder.Append("]");

                            element.value = stringBuilder.ToString();

                        }
                        if (element.id == "geofenceName") {
                            element.value = geofence.Name;
                        }

                        if (element.id == "geofenceSubmit") {
                            mshtml.HTMLInputElement btnSubmit = element;
                            btnSubmit.click();
                        }

                    }
                } catch {

                }
            }
        }
        public static async Task TryCreateGeofence()
        {
            await Initialize();

            string fenceKey = "TIG.Todo";

            Geofence geofence = null;

            BasicGeoposition position;
            position.Latitude = currentLocation.Coordinate.Point.Position.Latitude;
            position.Longitude = currentLocation.Coordinate.Point.Position.Longitude;
            position.Altitude = 0.0;
            double radius = 100; //Suggested >50

            // the geofence is a circular region
            Geocircle geocircle = new Geocircle(position, radius);

            bool singleUse = true;

            // want to listen for enter geofence, exit geofence and remove geofence events
            // you can select a subset of these event states
            MonitoredGeofenceStates mask = 0;

            mask |= MonitoredGeofenceStates.Entered;
            mask |= MonitoredGeofenceStates.Exited;
            mask |= MonitoredGeofenceStates.Removed;

            // setting up how long you need to be in geofence for enter event to fire
            //TimeSpan dwellTime = TimeSpan.FromMinutes(1);
            TimeSpan dwellTime = TimeSpan.FromSeconds(1);

            // setting up how long the geofence should be active
            //TimeSpan duration = TimeSpan.FromHours(24);
            TimeSpan duration = TimeSpan.FromMinutes(2);

            // setting up the start time of the geofence
            DateTimeOffset startTime = DateTimeOffset.Now;

            geofence = new Geofence(fenceKey, geocircle, mask, singleUse, dwellTime, startTime, duration);
            GeofenceMonitor.Current.Geofences.Add(geofence);

        }
Пример #52
0
        private async void CreateGeofence()
        {
            GeofenceMonitor.Current.Geofences.Clear();

            BasicGeoposition basicGeoposition = new BasicGeoposition();
            Geoposition geoposition = await geolocator.GetGeopositionAsync();
            Geofence geofence;

            basicGeoposition.Latitude = geoposition.Coordinate.Latitude;
            basicGeoposition.Longitude = geoposition.Coordinate.Longitude;
            basicGeoposition.Altitude = (double) geoposition.Coordinate.Altitude;
            double radius = 10.0;

            Geocircle geocircle = new Geocircle(basicGeoposition, radius);

            // want to listen for enter geofence, exit geofence and remove geofence events
            // you can select a subset of these event states
            MonitoredGeofenceStates mask = 0;

            mask |= MonitoredGeofenceStates.Entered;
            mask |= MonitoredGeofenceStates.Exited;
            mask |= MonitoredGeofenceStates.Removed;

            // setting up how long you need to be in geofence for enter event to fire
            TimeSpan dwellTime = new TimeSpan(1, 0, 0);

            // setting up how long the geofence should be active
            TimeSpan duration = new TimeSpan(0,10,0);

            // setting up the start time of the geofence
            DateTimeOffset startTime = DateTimeOffset.Now;
            
            geofence = new Geofence("Test", geocircle, mask, true);

            GeofenceMonitor.Current.Geofences.Add(geofence);

        }
        private Geofence GenerateGeofence()
        {
            Geofence geofence = null;

            string fenceKey = new string(Id.Text.ToCharArray());

            BasicGeoposition position;
            position.Latitude = Double.Parse(Latitude.Text);
            position.Longitude = Double.Parse(Longitude.Text);
            position.Altitude = 0.0;
            double radius = Double.Parse(Radius.Text);

            // the geofence is a circular region
            Geocircle geocircle = new Geocircle(position, radius);

            bool singleUse = (bool)SingleUse.IsChecked;

            // want to listen for enter geofence, exit geofence and remove geofence events
            // you can select a subset of these event states
            MonitoredGeofenceStates mask = 0;

            mask |= MonitoredGeofenceStates.Entered;
            mask |= MonitoredGeofenceStates.Exited;
            mask |= MonitoredGeofenceStates.Removed;

            // setting up how long you need to be in geofence for enter event to fire
            TimeSpan dwellTime;

            if ("" != DwellTime.Text)
            {
                dwellTime = new TimeSpan(ParseTimeSpan(DwellTime.Text, defaultDwellTimeSeconds));
            }
            else
            {
                dwellTime = new TimeSpan(ParseTimeSpan("0", defaultDwellTimeSeconds));
            }

            // setting up how long the geofence should be active
            TimeSpan duration;

            if ("" != Duration.Text)
            {
                duration = new TimeSpan(ParseTimeSpan(Duration.Text, 0));
            }
            else
            {
                duration = new TimeSpan(ParseTimeSpan("0", 0));
            }

            // setting up the start time of the geofence
            DateTimeOffset startTime;

            try
            {
                if ("" != StartTime.Text)
                {
                    startTime = DateTimeOffset.Parse(StartTime.Text); 
                }
                else
                {
                    // if you don't set start time in C# the start time defaults to 1/1/1601
                    calendar.SetToNow();

                    startTime = calendar.GetDateTime();
                }
            }
            catch (ArgumentNullException)
            {
            }
            catch (FormatException)
            {
                rootPage.NotifyUser("Start Time is not a valid string representation of a date and time", NotifyType.ErrorMessage);
            }
            catch (ArgumentException)
            {
                rootPage.NotifyUser("The offset is greater than 14 hours or less than -14 hours.", NotifyType.ErrorMessage);
            }

            geofence = new Geofence(fenceKey, geocircle, mask, singleUse, dwellTime, startTime, duration);

            return geofence;
        }