Exemple #1
0
        public async Task <Dictionary <Coordenates, Velocity> > GetCurrentPositionAsync()
        {
            Dictionary <Coordenates, Velocity> geoSpeed = new Dictionary <Coordenates, Velocity>();
            Coordenates geo = new Coordenates();
            Velocity    vel = new Velocity();

            var loc = await Geolocation.GetLastKnownLocationAsync();

            if (loc == null)
            {
                var request = new GeolocationRequest(GeolocationAccuracy.High);
                loc = await Geolocation.GetLocationAsync(request);
            }

            vel.speed = loc.Speed;

            geo.lat = loc.Latitude;
            geo.lng = loc.Longitude;

            geoSpeed.Add(geo, vel);

            return(geoSpeed);
        }
Exemple #2
0
 public Drone(string input)
 {
     Coordenates = new Coordenates(input);
 }
Exemple #3
0
        static void Main(string[] args)
        {
            /*** Tipos valor y tipos referencia ***/
            #region tipos valor
            bool value    = false;
            bool newValue = value;

            value = true;

            Console.WriteLine("value {0}", value);       //true
            Console.WriteLine("newValue {0}", newValue); //false
            #endregion

            #region tipos referencia
            Coordenates coordA = new Coordenates();
            coordA.x = 1;
            coordA.y = 50;

            Coordenates coordB = coordA;
            Console.WriteLine("coordB.x {0}", coordB.x); //1
            Console.WriteLine("coordB.y {0}", coordB.y); //50
            coordA.x = 100;
            Console.WriteLine("coordB.x {0}", coordB.x); //100 - se ha copiado la ref a coordA, por lo tanto el valor sera el mismo que coordA.x
            Console.WriteLine("coordB.y {0}", coordB.y); //50
            #endregion

            #region ref
            int myNumber = 10;
            AddTen(ref myNumber);                        //se tiene que incluir la palabra reserv. ref en donde se invoca el metodo y en la declaracion del metodo
            Console.WriteLine("myNumber {0}", myNumber); //20
            #endregion

            /*** Tipos genericos ***/
            #region tipos genericos
            var nameList = new List <string>(); //requiere using System.Collections.Generic;
            nameList.Add("Name");
            Console.WriteLine("nameList {0}", nameList[0].ToString());
            #endregion

            #region crear clase generica
            var str = new Concat <int>();
            str.Add(5);
            str.Add(9);
            Console.WriteLine("str {0}", str.result); //59

            var strBool = new Concat <bool>();
            strBool.Add(false);
            strBool.Add(true);
            Console.WriteLine("str {0}", strBool.result); //falsetrue
            #endregion

            /*** Tipos anonimos ***/
            #region anonimos
            var location = new { Country = "Austria", City = "Graz" };
            Console.WriteLine("cliente - Pais: {0}, Ciudad: {1}", location.Country, location.City); //Lectura permitida
            //client.Name = "Daniela"; //Solo lectura, no puede ser modificado.
            #endregion

            #region anidacion
            var client = new { Name     = "Noemi",
                               Surname  = "Leon",
                               Status   = false,
                               Location = location };
            Console.WriteLine("cliente - Nombre: {0}, Pais: {1}", client.Name, client.Location.Country);
            #endregion

            #region arreglos anonimos
            var locationb = new { Country = "Mexico", City = "CDMX" };
            var clients   = new[]
            {
                new { Name = "Clara", Surname = "Rdz", Status = true, Location = location },
                new { Name = "Raul", Surname = "Noel", Status = false, Location = locationb },
                client
            };
            int i = 0;
            foreach (var cl in clients)
            {
                Console.WriteLine("cliente {0} - Nombre: {1}, Pais: {2}, Cd: {3}",
                                  i, cl.Name, cl.Location.Country, cl.Location.City);
                i++;
            }
            #endregion

            /*** Tipo tupla ***/
            #region no type
            var provider = (Name : "Alberto", Surname : "Perez");
            Console.WriteLine($"Provider: {provider.Name}, {provider.Surname}");
            #endregion

            #region tipos especificados
            (string Name, string Surname, int Age)providerB = (Name : "Alberto", Surname : "Perez", Age : 40);
            Console.WriteLine($"ProviderB: {providerB.Name}, {providerB.Age}");
            #endregion

            #region modificar campo de tupla
            providerB.Age = 25;
            Console.WriteLine($"ProviderB Age: {providerB.Age}");
            #endregion
        }
Exemple #4
0
        public async void SetPosition()
        {
            if (Application.Current.Properties.ContainsKey("IdUnidadeRastreada"))
            {
                Int32 IdUnidadeRastreada = (Int32)Application.Current.Properties["IdUnidadeRastreada"];
                Int32 Tolerancia         = (Int32)Application.Current.Properties["CalculoDistancia"];

                try
                {
                    if (Application.Current.Properties["IdUnidadeRastreada"] != null && (Boolean)Application.Current.Properties["IsAdmin"] == false)
                    {
                        //Posição atual
                        Dictionary <Coordenates, Velocity> loc = new Dictionary <Coordenates, Velocity>();
                        Coordenates geoLoc = new Coordenates();

                        loc = await GetCurrentPositionAsync();

                        if (loc != null)
                        {
                            Double?speed = 0;

                            foreach (KeyValuePair <Coordenates, Velocity> dadosGeo in loc)
                            {
                                geoLoc.lat = dadosGeo.Key.lat;
                                geoLoc.lng = dadosGeo.Key.lng;

                                speed = dadosGeo.Value.speed;
                            }

                            String address = null;

                            await Task.Run(async() =>
                            {
                                //Reverser GeoCode para endereço
                                address = await GetAddressByReverseGeoCode(geoLoc.lat, geoLoc.lng);
                            });


                            //Posição anterior
                            DtoPosition lastPos = new DtoPosition();
                            lastPos = GetLastPosition(IdUnidadeRastreada).Result.FirstOrDefault();

                            Boolean gravaPosicao = true;

                            //Cálculo de distância

                            if (lastPos != null)
                            {
                                Coordenates lastLatLong = new Coordenates();
                                lastLatLong.lat = lastPos.Latitude;
                                lastLatLong.lng = lastPos.Longitude;

                                Double distance = await GetCalculateDistance(IdUnidadeRastreada, lastLatLong, geoLoc);

                                if (distance > Tolerancia || lastPos.DateEvent.Day != DateTime.Today.Day)
                                {
                                    gravaPosicao = true;
                                }
                                else
                                {
                                    gravaPosicao = false;
                                }
                            }

                            var level = Battery.ChargeLevel;

                            if (gravaPosicao)
                            {
                                using (var client = new HttpClient())
                                {
                                    var positionRequest = new DtoPosition
                                    {
                                        _id = null,
                                        IdUnidadeRastreada = (Int32)Application.Current.Properties["IdUnidadeRastreada"],
                                        Name         = Application.Current.Properties["Name"].ToString(),
                                        DateEvent    = DateTime.Now,
                                        Address      = address,
                                        Latitude     = geoLoc.lat,
                                        Longitude    = geoLoc.lng,
                                        IdRegra      = null,
                                        Avatar       = Application.Current.Properties["Avatar"].ToString(),
                                        LevelBattery = level,
                                        Velocity     = (double)speed
                                    };

                                    var jsonRequest = JsonConvert.SerializeObject(positionRequest);
                                    var httpContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json");

                                    string uri = "http://207.180.246.227:8095/admin/Position/SetLastPosition";

                                    var retorno = await client.PostAsync(uri, httpContent);

                                    var resultString = await retorno.Content.ReadAsStringAsync();

                                    DtoPosition pos = new DtoPosition();
                                    pos = JsonConvert.DeserializeObject <DtoPosition>(resultString);

                                    if (retorno.StatusCode == System.Net.HttpStatusCode.BadRequest)
                                    {
                                        //throw new Exception("Ocorrer um erro ao enviar posição!");
                                    }

                                    #region ViolacaoRegra

                                    RuleService rule    = new RuleService();
                                    Boolean     HasRule = await rule.HasViolationRule(pos.IdUnidadeRastreada, pos.Latitude, pos.Longitude, pos._id);

                                    #endregion


                                    //DtoPosition position = new DtoPosition();
                                    //position = JsonConvert.DeserializeObject<DtoPosition>(resultString);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Ocorreu um erro ao enviar posição. Erro: " + ex.Message);
                }

                await Application.Current.SavePropertiesAsync();
            }
        }
Exemple #5
0
        public async Task <Double> GetCalculateDistance(Int32 paramIdUnidadeRastreada, Coordenates latLongLastPos, Coordenates latLongCurrentePos)
        {
            Location lastPosition    = new Location(latLongLastPos.lat, latLongLastPos.lng);
            Location currentPosition = new Location(latLongCurrentePos.lat, latLongCurrentePos.lng);
            Double   metros          = Location.CalculateDistance(lastPosition, currentPosition, DistanceUnits.Kilometers);

            return(metros * 1000);
        }
        private async void MontaUltimaPosicao()
        {
            Int32 IdAdmin = (int)Application.Current.Properties["IdUser"];

            List <DtoPosition> itens = new List <DtoPosition>();

            try
            {
                using (var client = new HttpClient())
                {
                    string uri = "http://207.180.246.227:8095/admin/Position/GetLastPosition?paramIdAdmin=" + IdAdmin;

                    HttpResponseMessage retorno = await client.GetAsync(uri);

                    var resultString = await retorno.Content.ReadAsStringAsync();

                    if (retorno.StatusCode == System.Net.HttpStatusCode.BadRequest)
                    {
                        await DisplayAlert("Erro", "Ocorreu um erro ao retonar as posições", "Ok");

                        return;
                    }
                    if (resultString != "[]")
                    {
                        PositionService pos = new PositionService();

                        List <DtoPosition> listPosition = new List <DtoPosition>();

                        foreach (var item in JsonConvert.DeserializeObject <List <DtoPosition> >(resultString))
                        {
                            DtoPosition position = new DtoPosition()
                            {
                                Name            = item.Name,
                                DateEvent       = item.DateEvent,
                                DateAtualizacao = item.DateAtualizacao,
                                Avatar          = item.Avatar,
                                Address         = item.Address,
                                LatLong         = item.LatLong,
                                Latitude        = item.Latitude,
                                Longitude       = item.Longitude
                            };
                            listPosition.Add(position);
                        }

                        lvPosition.ItemsSource = listPosition;

                        //var polyline = new Polyline();

                        //foreach (DtoPosition x in lvPosition.DataSource.Items)
                        //{

                        //    polyline.Positions.Add(new Position(x.Latitude, x.Longitude));

                        //    polyline.StrokeColor = Color.Red;
                        //    polyline.StrokeWidth = 5f;
                        //    polyline.Tag = "POLYLINE"; // Can set any object

                        //    polyline.IsClickable = false;
                        //    polyline.Clicked += (s, e) =>
                        //    {
                        //        // handle click polyline
                        //    };


                        //    Pin pin = new Pin()
                        //    {
                        //        Icon = BitmapDescriptorFactory.FromBundle(x.Avatar),
                        //        Type = PinType.Place,
                        //        Label = x.Name,
                        //        Address = x.Address,
                        //        Position = new Position(x.Latitude, x.Longitude),
                        //        ZIndex = 5,
                        //    };

                        //    MyMap.Pins.Add(pin);
                        //}

                        //MyMap.Polylines.Add(polyline);
                        Dictionary <Coordenates, Velocity> geo = new Dictionary <Coordenates, Velocity>();

                        Coordenates geoLoc = new Coordenates();

                        geo = await pos.GetCurrentPositionAsync();

                        foreach (KeyValuePair <Coordenates, Velocity> dadosGeo in geo)
                        {
                            geoLoc.lat = dadosGeo.Key.lat;
                            geoLoc.lng = dadosGeo.Key.lng;
                        }

                        MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(geoLoc.lat, geoLoc.lng), Distance.FromKilometers(1)));


                        //waitActivityIndicator.IsVisible = false;
                        //waitActivityIndicator.IsRunning = false;
                    }
                    else
                    {
                        //waitActivityIndicator.IsVisible = false;
                        //waitActivityIndicator.IsRunning = false;
                    }
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Erro", ex.Message, "Erro ao listar Matérias...");

                return;
            }
        }
        private async void MontaHistoricoPosicao()
        {
            List <DtoPosition> itens = new List <DtoPosition>();

            try
            {
                using (var client = new HttpClient())
                {
                    //var dadosRequest = new DtoFiltro()
                    //{
                    //    Assunto = filtro.Assunto,
                    //    ChkImpresso = filtro.ChkImpresso,
                    //    ChkTv = filtro.ChkTv,
                    //    ChkRd = filtro.ChkRd,
                    //    ChkOnline = filtro.ChkOnline,
                    //    ChkInter = filtro.ChkInter,
                    //    ChkMSocial = filtro.ChkMSocial,
                    //    Palavra = filtro.Palavra,
                    //    DataIni = new DateTime(Convert.ToDateTime(filtro.DataIni).Year, Convert.ToDateTime(filtro.DataIni).Month, Convert.ToDateTime(filtro.DataIni).Day),
                    //    DataFim = new DateTime(Convert.ToDateTime(filtro.DataFim).Year, Convert.ToDateTime(filtro.DataFim).Month, Convert.ToDateTime(filtro.DataFim).Day),
                    //    NomeBanco = filtro.NomeBanco,
                    //    Cliente = filtro.Cliente
                    //};

                    //var jsonRequest = JsonConvert.SerializeObject(dadosRequest);
                    //var httpContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json");

                    waitActivityIndicator.IsVisible = true;
                    waitActivityIndicator.IsRunning = true;

                    string uri = "http://207.180.246.227:8095/admin/Position/GetHistoricPositionByData?paramDataIni=2020-04-01T08:00:00&paramDataFim=2020-12-31T12:00:00";

                    HttpResponseMessage retorno = await client.GetAsync(uri);

                    var resultString = await retorno.Content.ReadAsStringAsync();

                    if (retorno.StatusCode == System.Net.HttpStatusCode.BadRequest)
                    {
                        await DisplayAlert("Erro", "Ocorreu um erro ao retonar as posições", "Ok");

                        return;
                    }
                    if (resultString != "[]")
                    {
                        //noNews.IsVisible = false;
                        PositionService pos = new PositionService();
                        lvPosition.ItemsSource = JsonConvert.DeserializeObject <List <DtoPosition> >(resultString);
                        int countPos = JsonConvert.DeserializeObject <List <DtoPosition> >(resultString).Count();

                        Dictionary <Coordenates, Velocity> geo = new Dictionary <Coordenates, Velocity>();

                        Coordenates geoLoc = new Coordenates();

                        geo = await pos.GetCurrentPositionAsync();

                        foreach (KeyValuePair <Coordenates, Velocity> dadosGeo in geo)
                        {
                            geoLoc.lat = dadosGeo.Key.lat;
                            geoLoc.lng = dadosGeo.Key.lng;
                        }

                        MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(geoLoc.lat, geoLoc.lng), Distance.FromMeters(5000)));
                    }
                    else
                    {
                        waitActivityIndicator.IsVisible = false;
                        waitActivityIndicator.IsRunning = false;
                        //noNews.IsVisible = true;
                    }

                    waitActivityIndicator.IsVisible = false;
                    waitActivityIndicator.IsRunning = false;
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Erro", ex.Message, "Erro ao listar Matérias...");

                return;
            }
        }
 Coordenates IWeatherService.CreateManyCoordenates(Coordenates coords)
 {
     throw new NotImplementedException();
 }