Exemplo n.º 1
0
        /// <summary>
        /// Añade la posición de un vehículo dada la referencia de este
        /// </summary>
        /// <param name="reference"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public async Task <bool> AddVehiclePosition(string reference, PositionAPI value)
        {
            // Si ni es un vehiculo ni administrador no podemos añadir la posición
            if (!IsVehicle() && !IsAdmin())
            {
                return(false);
            }

            // Buscamos el vehículo
            var vehicle = await _vehicleRepository.Find(reference);

            if (vehicle == null)
            {
                return(false);
            }
            // Si el usuario no es administrador vemos si es el usuario asociado al vehículo
            if (!IsAdmin() && vehicle.UserId != GetUserId())
            {
                return(false);
            }
            if (value.SetDate == DateTime.MinValue)
            {
                value.SetDate = DateTime.Now;
            }
            // Añadimos la posición
            bool retValue = await _vehicleRepository.AddVehiclePosition(vehicle.Id, value);

            // Notificamos la posicion
            _notifyService.NotifyPosition(vehicle.Id, value);
            return(retValue);
        }
        /// <summary>
        /// Añade una posición a un vehiculo dado el id de este y los datos de posición
        /// </summary>
        /// <param name="vehicleId"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public async Task <bool> AddVehiclePosition(Guid vehicleId, PositionAPI value)
        {
            if (value == null || vehicleId == Guid.Empty)
            {
                return(false);
            }

            try
            {
                var position = await _context.VehiclePositions.AddAsync(new VehiclePosition
                {
                    VehicleId      = vehicleId,
                    SetDate        = value.SetDate,
                    PositionFormat = value.PositionFormat,
                    Latitude       = value.Latitude,
                    Longitude      = value.Longitude,
                    Precision      = value.Precision,
                    ExtendedInfo   = value.ExtendedInfo
                });

                return(await _context.SaveChangesAsync() > 0);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error añadiendo posición del vehiculo. {@value}", value);
            }

            return(false);
        }
        /// <summary>
        /// Notificamos la posición de un vehículo
        /// </summary>
        /// <param name="vehicleId"></param>
        /// <param name="position"></param>
        public void NotifyPosition(Guid vehicleId, PositionAPI position)
        {
            List <NotifyElement> lstNotify = null;

            lock (LockDictionary)
            {
                if (!notifications.ContainsKey(vehicleId))
                {
                    return;
                }
                var list = notifications[vehicleId];
                if (list == null || !list.Any())
                {
                    return;
                }

                lstNotify = list.GetRange(0, list.Count);
            }
            // Lanzamos un hilo para las notificaciones
            new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;
                // Llamamos a lanzar las notificaciones
                LaunchNotifyList(lstNotify, position);
            }).Start();
        }
Exemplo n.º 4
0
 public void DeleteDown()
 {
     PositionAPI.DeletePosition((bool flag) => {
         if (flag)
         {
             Debug.Log("Delete PositionData!");
         }
         else
         {
             Debug.Log("Delete failed...");
         }
     });
 }
Exemplo n.º 5
0
 public void AddDown()
 {
     PositionAPI.AddPosition((bool flag) => {
         if (flag)
         {
             Debug.Log("Add PositionData!");
         }
         else
         {
             Debug.Log("Add failed...");
         }
     });
 }
        public async Task <IActionResult> SetVehiclePosition(string reference, [FromBody] PositionAPI value)
        {
            if (String.IsNullOrEmpty(reference) || value == null)
            {
                return(BadRequest());
            }

            if (!await _vehicleService.AddVehiclePosition(reference, value))
            {
                return(BadRequest());
            }
            return(Ok());
        }
 /// <summary>
 ///  Lanzamos una notificación Webhook
 /// </summary>
 /// <param name="notify"></param>
 /// <param name="position"></param>
 private void LaunchWebhook(NotifyElement notify, PositionAPI position)
 {
     try
     {
         // Enviamos la notificación al webhook sin esperar la respuesta
         using (HttpClient client = new HttpClient())
         {
             client.PostAsJsonAsync(notify.Data, new NotifyWebhook
             {
                 Position         = position,
                 VehicleReference = notify.VehicleReference,
                 UserName         = notify.UserName
             });
         }
     }catch (Exception)
     {
     }
 }
        /// <summary>
        /// Metodo generado para lanzarse en un hilo y notificar la posicion
        /// </summary>
        /// <param name="lstCalls"></param>
        /// <param name="position"></param>
        private void LaunchNotifyList(List <NotifyElement> lstCalls, PositionAPI position)
        {
            if (lstCalls == null || position == null)
            {
                return;
            }
            // Enviamos las notificaciones
            foreach (var call in lstCalls)
            {
                try
                {
                    switch (call.NotifyType)
                    {
                    case NotifyType.Webhook: LaunchWebhook(call, position); break;

                    case NotifyType.MQTT: LaunchMQTT(call, position); break;
                    }
                }
                catch (Exception)
                {
                    // No dejaremos que cualquier excepción aqui evite el resto de notificaciones
                }
            }
        }
 /// <summary>
 /// Lanzamos una notificación MQTT
 /// </summary>
 /// <param name="notify"></param>
 /// <param name="position"></param>
 private void LaunchMQTT(NotifyElement notify, PositionAPI position)
 {
     //TODO: Por hacer
     /// Se llamará al cliente MQTT para añadir una notificación en el servidor
     /// con ruta el Usuario/Referencia del Vehículo.
 }