Exemplo n.º 1
0
        /// <summary>
        ///     Registers the device location.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        /// <param name="latitude">The latitude.</param>
        /// <param name="longitude">The longitude.</param>
        /// <param name="altitude">The altitude.</param>
        /// <param name="bearing">The bearing.</param>
        /// <param name="speed">The speed.</param>
        /// <returns>DeviceLocation.</returns>
        public DeviceLocation RegisterDeviceLocation(string deviceId, double latitude, double longitude, double altitude,
                                                     float bearing, float speed)
        {
            DeviceLocation loc = null;

            try
            {
                loc = new DeviceLocation
                {
                    Device           = deviceId,
                    Accuracy         = (float)0.0,
                    Altitude         = altitude,
                    Bearing          = bearing,
                    Speed            = speed,
                    Latitude         = latitude,
                    Longitude        = longitude,
                    DisplayAltitude  = String.Format("{0:n0}m", altitude),
                    DisplayBearing   = GeoAngle.FromDouble(bearing).ToString(),
                    DisplayGrid      = CalculateGrid(latitude, longitude),
                    DisplayLatitude  = GeoAngle.FromDouble(latitude).ToString(LocationFormat.Latitude),
                    DisplayLongitude = GeoAngle.FromDouble(longitude).ToString(LocationFormat.Longtitude),
                    DisplaySpeed     = String.Format("{0:n1}m/s", speed)
                };
                LocationLog locLog = loc.ToLocationLog();
                locLog = LatiPortal
                         .Latis
                         .RegisterLocation(locLog);
                return(loc);
            }
            catch (Exception exception)
            {
                _logger.Error(exception.GetCombinedMessages());
                return(loc);
            }
        }
Exemplo n.º 2
0
//		[Obsolete]
//		public override void UpdatedLocation (CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation)
//		{
//			// if one of the coordinates has changed, the address has to be reset
//			if (thisDeviceLat != newLocation.Coordinate.Latitude || thisDeviceLng != newLocation.Coordinate.Longitude)
//			{
//				Interlocked.Exchange<string>(ref thisDeviceAddress, string.Empty);
//			}
//
//			thisDeviceLat = newLocation.Coordinate.Latitude;
//			thisDeviceLng = newLocation.Coordinate.Longitude;
//
//			if ( (DateTime.Now - LastCoordsRecordedTimeStamp).TotalMinutes >= 1 )
//			{
//				// string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
//				// string time = (DateTime.SpecifyKind (newLocation.Timestamp, DateTimeKind.Unspecified)).ToString("yyyy-MM-dd HH:mm:ss");
//				string anotherTime = (new DateTime(2001,1,1,0,0,0)).AddSeconds(newLocation.Timestamp.SecondsSinceReferenceDate).ToLocalTime().ToString ("yyyy-MM-dd HH:mm:ss");
//				AddLocationToBuffer (thisDeviceLng, thisDeviceLat, anotherTime, thisDeviceAddress, -1, -1);
//				LastCoordsRecordedTimeStamp = DateTime.Now;
//
//			}
//		}

        public void AddLocationToBuffer(double lng, double lat, string timeStamp, string address, long customer, long job)
        {
            lock (locationsBufferLock)
            {
                var locBuffer = this.thisManager.thisApp.LocationsBuffer;
                var loc       = new DeviceLocation();
                loc.Address   = address;
                loc.Timestamp = timeStamp;
                loc.Lat       = lat;
                loc.Lng       = lng;

                long jrtCustomer = (MyConstants._jrt.CurrentCustomer == null)? 0 : MyConstants._jrt.CurrentCustomer.CustomerNumber;
                loc.CustomerID = (customer != -1)? customer : jrtCustomer;
                loc.JobID      = job;

                locBuffer.Add(loc);

                // throwing out excess values if more than 300 were saved between buffer flushes
                int k = 0;
                while (locBuffer.Count > 300)
                {
                    if (locBuffer[k].Address == String.Empty)                     // making sure to only throw out ones where no address has been saved
                    {
                        locBuffer.RemoveAt(k);
                    }
                    else
                    {
                        k++;
                    }
                }

                LastCoordsRecordedTimeStamp = DateTime.Now;
            }
        }
Exemplo n.º 3
0
        public ActionResult <BaseResponse> UpdateLocation(DeviceLocation location)
        {
            try
            {
                _locationService.AddOrUpdate(location);

                if (location.Id != 0)
                {
                    var oldLocation = _locationService.Get(location.Id);
                    var newLocation = _locationService.Get(location.Name);
                    _deviceService.UpdateLocations(newLocation, oldLocation);
                }

                return(new BaseResponse()
                {
                    Message = $"Updated/Added location: {location.Name}"
                });
            }
            catch (Exception ex)
            {
                return(new BaseResponse()
                {
                    Error = ErrorCode.InternalError,
                    Message = ex.Message
                });
            }
        }
Exemplo n.º 4
0
        public void StartLocationUpdates()
        {
            // We need the user's permission for our app to use the GPS in iOS. This is done either by the user accepting
            // the popover when the app is first launched, or by changing the permissions for the app in Settings
            if (CLLocationManager.LocationServicesEnabled)
            {
                //set the desired accuracy, in meters
                LocMgr.DesiredAccuracy = 1;

                LocMgr.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
                    // fire our custom Location Updated event

                    var location = e.Locations[e.Locations.Length - 1];

                    var deviceLocation = new DeviceLocation
                    {
                        Altitude  = location.Altitude,
                        Longitude = location.Coordinate.Longitude,
                        Latitude  = location.Coordinate.Latitude,
                        Course    = location.Course,
                        Speed     = location.Speed
                    };

                    LocationUpdated(this, new LocationUpdatedEventArgs(deviceLocation));
                };

                LocMgr.StartUpdatingLocation();
            }
        }
    /// <summary>
    /// Invokes GetTerminal Location method of SDK and displays the result
    /// </summary>
    private void GetDeviceLocation()
    {
        try
        {
            int[] definedReqAccuracy = new int[3] {
                100, 1000, 10000
            };
            int requestedAccuracy, acceptableAccuracy;

            acceptableAccuracy = definedReqAccuracy[Radio_AcceptedAccuracy.SelectedIndex];
            requestedAccuracy  = definedReqAccuracy[Radio_RequestedAccuracy.SelectedIndex];

            TerminalLocationTolerance tolerance = TerminalLocationTolerance.DelayTolerant;
            switch (Radio_DelayTolerance.SelectedIndex)
            {
            case 0:
                tolerance = TerminalLocationTolerance.NoDelay;
                break;

            case 1:
                tolerance = TerminalLocationTolerance.LowDelay;
                break;

            default:
                tolerance = TerminalLocationTolerance.DelayTolerant;
                break;
            }

            DeviceLocation deviceLocationRequest = this.requestFactory.GetTerminalLocation(requestedAccuracy, tolerance, acceptableAccuracy);

            DateTime endTime  = DateTime.Now;
            TimeSpan timeSpan = endTime - this.startTime;

            this.DrawPanelForGetLocationResult(string.Empty, string.Empty, true);
            this.DrawPanelForGetLocationResult("Accuracy:", deviceLocationRequest.Accuracy.ToString(), false);
            this.DrawPanelForGetLocationResult("Latitude:", deviceLocationRequest.Latitude.ToString(), false);
            this.DrawPanelForGetLocationResult("Longitude:", deviceLocationRequest.Longitude.ToString(), false);
            this.DrawPanelForGetLocationResult("TimeStamp:", deviceLocationRequest.TimeStamp.ToString(), false);
            this.DrawPanelForGetLocationResult("Response Time:", timeSpan.Seconds.ToString() + "seconds", false);

            MapTerminalLocation.Visible = true;
            map_canvas.Visible          = true;
            StringBuilder googleString = new StringBuilder();
            googleString.Append("http://maps.google.com/?q=" + deviceLocationRequest.Latitude.ToString() + "+" + deviceLocationRequest.Longitude.ToString() + "&output=embed");
            MapTerminalLocation.Attributes["src"] = googleString.ToString();
        }
        catch (ArgumentException ex)
        {
            this.DrawPanelForFailure(tlPanel, ex.ToString());
        }
        catch (InvalidResponseException ex)
        {
            this.DrawPanelForFailure(tlPanel, ex.Body);
        }
        catch (Exception ex)
        {
            this.DrawPanelForFailure(tlPanel, ex.ToString());
        }
    }
Exemplo n.º 6
0
        public ActionResult DeleteConfirmed(int id)
        {
            DeviceLocation deviceLocation = db.DeviceLocations.Find(id);

            db.DeviceLocations.Remove(deviceLocation);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public async Task <IActionResult> PostDeviceLocation([FromBody] DeviceLocation deviceLocation)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.DeviceLocations.Add(deviceLocation);
            await _context.SaveChangesAsync();

            return(Created("", deviceLocation));
        }
    /// <summary>
    ///To Update the Device Location status to admin
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage updateDeviceLocation(DeviceLocation DL)
    {
        ar = new WebApiResponse();
        try
        {
            string qry = "select * from MDM_DeviceMaster where DeviceID='" + DL.uuid + "'";
            dr = databaseHelper.getDataReader(qry);

            if (dr.Read())
            {
                if (!dr.IsClosed)
                {
                    dr.Close();
                }

                DeviceTrackingDetail DT = new DeviceTrackingDetail();

                var list = DL.locations;
                foreach (var c in list)
                {
                    qry  = "insert into MDM_DeviceTrackingDetail(DeviceId,latitude,longitude,CreatedDate)values('" + DL.uuid + "','" + c.latitude + "','" + c.longitude + "','" + c.timestamp.ToString("yyyy-MM-dd HH:mm:ss") + "')";
                    rcnt = databaseHelper.ExecuteQuery(qry);
                }
                ar.response = true;
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, ar);

                qry  = "delete from MDM_PushNotification where DeviceID='" + DL.uuid + "' and Command='GetDeviceLocation'";
                rcnt = databaseHelper.ExecuteQuery(qry);

                return(response);
            }
            else
            {
                ar.errorCode = "Authentication Failed";
                ar.response  = false;
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return(response);
            }
        }
        catch (Exception ex)
        {
            linfo.LogFile(enLogType.EXCEPTION, ex.Message, null);
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
            {
                dr.Close();
            }
        }
        return(null);
    }
 public static LocationLog ToLocationLog(this DeviceLocation item)
 {
     return(new LocationLog
     {
         Bearing = item.Bearing,
         Accuracy = item.Accuracy,
         Altitude = item.Altitude,
         Latitude = item.Latitude,
         Longitude = item.Longitude,
         Speed = item.Speed,
         PoIId = item.Device
     });
 }
    private void SendOutLogoRecognisedEvent(string mTargetName, string mTargetMetadata)
    {
        var location = DeviceLocation.GetInstance().GetLocation();
        var args     = new LogoRecognisedEventArgs
        {
            microsite = mTargetName,
            metadata  = mTargetMetadata,
            latitude  = location.latitude,
            longitude = location.longitude
        };

        OnLogoRecognised(args);
    }
Exemplo n.º 11
0
        public static DLocation ToDirectedLocation(this DeviceLocation deviceLocation)
        {
            if (deviceLocation == null)
            {
                throw new ArgumentNullException(nameof(deviceLocation));
            }

            return(new DLocation(deviceLocation.Latitude,
                                 deviceLocation.Longitude,
                                 deviceLocation.Speed,
                                 deviceLocation.Heading,
                                 deviceLocation.Timestamp));
        }
Exemplo n.º 12
0
        // GET: DeviceLocations/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            DeviceLocation deviceLocation = db.DeviceLocations.Find(id);

            if (deviceLocation == null)
            {
                return(HttpNotFound());
            }
            return(View(deviceLocation));
        }
        public void Save()
        {
            IDeviceLocationRepository iDeviceLocationRepository =
                new DeviceLocationRepository(this.connectionString);

            DeviceLocation deviceLocation =
                new DeviceLocation
                (
                    1,
                    222.222333m,
                    399.220393m
                );

            iDeviceLocationRepository.Save(this.Application.Id, this.Device.Id, deviceLocation);
        }
        public void ShouldBuildLocationConstraintWithDefaultValues()
        {
            Extension <LocationConstraintContent> extension = new LocationConstraintExtensionBuilder()
                                                              .WithLatitude(_someLatitude)
                                                              .WithLongitude(_someLongitude)
                                                              .Build();

            Assert.AreEqual(Constants.Extension.LocationConstraint, extension.ExtensionType);
            DeviceLocation deviceLocation = extension.Content.ExpectedDeviceLocation;

            Assert.AreEqual(_someLatitude, deviceLocation.Latitude);
            Assert.AreEqual(_someLongitude, deviceLocation.Longitude);
            Assert.AreEqual(150d, deviceLocation.Radius);
            Assert.AreEqual(150d, deviceLocation.MaxUncertainty);
        }
        public void Save()
        {
            IDeviceLocationRepository iDeviceLocationRepository =
                new DeviceLocationRepository(this.client, this.database);

            DeviceLocation deviceLocation =
                new DeviceLocation
                (
                    this.Device.Id,
                    222.222333m,
                    399.220393m
                );

            iDeviceLocationRepository.Save(deviceLocation);
        }
        public void Save()
        {
            IDeviceLocationRepository iDeviceLocationRepository =
                new DeviceLocationRepository(this.connectionString);

            DeviceLocation deviceLocation =
                new DeviceLocation
                (
                    1,
                    222.222333m,
                    399.220393m
                );

            iDeviceLocationRepository.Save(this.Application.Id, this.Device.Id, deviceLocation);
        }
        public void Save()
        {
            IDeviceLocationRepository iDeviceLocationRepository =
                new DeviceLocationRepository(this.client, this.database);

            DeviceLocation deviceLocation =
                new DeviceLocation
                (
                    this.Device.Id,
                    222.222333m,
                    399.220393m
                );

            iDeviceLocationRepository.Save(deviceLocation);
        }
Exemplo n.º 18
0
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            DeviceLocation _model     = db.DeviceLocations.Find(id);
            var            _viewModel = DeviceLocationViewModel.GetViewModelDatas(_model);

            if (_model == null)
            {
                return(HttpNotFound());
            }
            ViewBag.DeviceID = new SelectList(db.Devices, "DeviceID", "InventoryNumber", _model.DeviceID);
            return(View(_viewModel));
        }
Exemplo n.º 19
0
        DeviceLocation GetModelDatas(DeviceLocationViewModel _viewModel)
        {
            DeviceLocation _model = new DeviceLocation()
            {
                LocationID     = _viewModel.LocationID,
                DeviceID       = _viewModel.DeviceID,
                DepartmentLoc  = _viewModel.DepartmentLoc.ToString(),
                CorpLoc        = _viewModel.CorpLoc.ToString(),
                FloorLoc       = _viewModel.FloorLoc.ToString(),
                RoomLoc        = _viewModel.RoomLoc,
                NoteDevLoc     = _viewModel.NoteDevLoc,
                CreateDateTime = _viewModel.CreateDateTime,
                ChangeDateTime = _viewModel.ChangeDateTime
            };

            return(_model);
        }
        public void Try_RegiserDeviceLocation()
        {
            try
            {
                //var res = HamdroidProvider
                //    .Hamdroids
                //    .RegisterDeviceLocation("iPhone", 50.125123, 5.212335, 54.253, (float)125.265265, (float)12.548);
                DeviceLocation res = HamdroidPortal
                                     .Agent
                                     .RegisterDeviceLocation("iPhone", 50.125123, 5.212335, 54.253, (float)125.265265, (float)12.548);
                Console.WriteLine("Grid:{0}, Lat:{1}, Lon:{2}", res.DisplayGrid, res.DisplayLatitude,
                                  res.DisplayLongitude);
            }
            catch (Exception exception)
            {
                Assert.Fail(exception.Message);

                throw;
            }
        }
Exemplo n.º 21
0
        public void Log(DeviceLocation deviceLocation, ApplicationInfo applicationInfo)
        {
            Application application = this.applicationRepository.Find(applicationInfo.ApplicationId);

            if (application != null)
            {
                DeviceInfo device = this.deviceRepository.Find(deviceLocation.DeviceId);

                if (device != null)
                {
                    this.deviceRepository.Save(deviceLocation);
                }
                else
                {
                    throw new NoDeviceException(deviceLocation.DeviceId);
                }
            }
            else
            {
                throw new InactiveApplicationException(applicationInfo.ApplicationId);
            }
        }
Exemplo n.º 22
0
        private DashboardViewModels CreateDashboard_Pack22_23ViewModel(Models.Message deviceMessageType22, Models.Message deviceMessageType23)
        {
            DashboardViewModels dashboard = new DashboardViewModels();

            dashboard.DeviceId           = deviceMessageType22.DeviceId;
            dashboard.Name               = deviceMessageType22.Device.Name;
            dashboard.Package            = $"{deviceMessageType22.Data};{deviceMessageType23.Data}";
            dashboard.TypePackage        = $"{deviceMessageType22.TypePackage};{deviceMessageType23.TypePackage}";
            dashboard.Date               = deviceMessageType22.Date;
            dashboard.Country            = deviceMessageType22.Country;
            dashboard.Lqi                = deviceMessageType22.Lqi;
            dashboard.Bits               = deviceMessageType22.Bits;
            dashboard.Level              = deviceMessageType22.Level;
            dashboard.Light              = deviceMessageType22.Light;
            dashboard.Temperature        = deviceMessageType22.Temperature;
            dashboard.Moisture           = deviceMessageType22.Moisture;
            dashboard.OxigenioDissolvido = deviceMessageType22.OxigenioDissolvido;
            dashboard.Ph                 = deviceMessageType23.Ph;
            dashboard.Condutividade      = deviceMessageType23.Condutividade;
            dashboard.PeriodoTransmissao = deviceMessageType23.PeriodoTransmissao;
            dashboard.BaseT              = deviceMessageType23.BaseT;

            // set location on dashboard of device
            DeviceLocation deviceLocation = GetDeviceLocationByDeviceId(dashboard.DeviceId);

            if (deviceLocation != null)
            {
                dashboard.Latitude  = deviceLocation.Latitude.ToString();
                dashboard.Longitude = deviceLocation.Longitude.ToString();
                dashboard.Radius    = deviceLocation.Radius;

                dashboard.LatitudeConverted  = LocationDecimalToDegrees((decimal)deviceLocation.Latitude, "S");
                dashboard.LongitudeConverted = LocationDecimalToDegrees((decimal)deviceLocation.Longitude, "W");
                dashboard.RadiusConverted    = RadiusFormated(deviceLocation.Radius);
            }

            return(dashboard);
        }
        private async void GetClassifications()
        {
            Locations    = new ObservableCollection <DeviceLocation>();
            AllLocations = new List <DeviceLocation>();

            var service = ServicesManager.SelfService;

            try
            {
                var locationsResponse = await service.GetLocations(Token);

                if (locationsResponse == null || locationsResponse.Error != ErrorCode.OK)
                {
                    MainWindow.Instance.AddNotification(locationsResponse ?? new BaseResponse()
                    {
                        Error = ErrorCode.InternalError, Message = "Failed to receive response from host."
                    });
                }
                else
                {
                    AllLocations.AddRange(locationsResponse.Locations);
                    foreach (var classific in locationsResponse.Locations)
                    {
                        Locations.Add(classific);
                    }

                    if (Locations.Count > 0)
                    {
                        CurrentLocation = Locations[0];
                    }
                }
            }
            catch (ServiceException ex)
            {
                //TODO: HIGH Add logging
                MainWindow.Instance.AddNotification(ex);
            }
        }
Exemplo n.º 24
0
        private DashboardViewModels CreateDashboard_Pack10ViewModel(Models.Message deviceMessage)
        {
            DashboardViewModels dashboard = new DashboardViewModels();

            dashboard.DeviceId    = deviceMessage.DeviceId;
            dashboard.Name        = deviceMessage.Device.Name;
            dashboard.Package     = deviceMessage.Data;
            dashboard.TypePackage = deviceMessage.TypePackage;
            dashboard.Date        = deviceMessage.Date;
            dashboard.Country     = deviceMessage.Country;
            dashboard.Lqi         = deviceMessage.Lqi;
            dashboard.Bits        = deviceMessage.Bits;

            // set location on dashboard of device
            DeviceLocation deviceLocation = GetDeviceLocationByDeviceId(dashboard.DeviceId);

            if (deviceLocation != null)
            {
                dashboard.Latitude  = deviceLocation.Latitude.ToString();
                dashboard.Longitude = deviceLocation.Longitude.ToString();
                dashboard.Radius    = deviceLocation.Radius;

                dashboard.LatitudeConverted  = LocationDecimalToDegrees((decimal)deviceLocation.Latitude, "S");
                dashboard.LongitudeConverted = LocationDecimalToDegrees((decimal)deviceLocation.Longitude, "W");
                dashboard.RadiusConverted    = RadiusFormated(deviceLocation.Radius);
            }

            dashboard.Temperature        = (decimal.Parse(deviceMessage.Temperature) * 100).ToString();
            dashboard.Temperature        = dashboard.Temperature.ToString().Substring(0, dashboard.Temperature.Length - 2);
            dashboard.Envio              = deviceMessage.Envio;
            dashboard.PeriodoTransmissao = deviceMessage.PeriodoTransmissao;
            dashboard.Alimentacao        = $"{deviceMessage.Alimentacao},0";
            dashboard.AlimentacaoMinima  = $"{deviceMessage.AlimentacaoMinima},0";

            return(dashboard);
        }
Exemplo n.º 25
0
 public async Task <BaseResponse> UpdateLocation(string token, DeviceLocation location)
 {
     return(await RequestHandler.ProcessPostRequest <BaseResponse, DeviceLocation>(POST_UPDATELOCATIONS, location, token));
 }
 public void Save(DeviceLocation location)
 {
     this.deviceMapper.Save(location);
 }
Exemplo n.º 27
0
        private DashboardViewModels CreateDashboard_Pack12ViewModel(Models.Message deviceMessage_12, Models.Message deviceMessage_13, DeviceRegistration deviceRegistration)
        {
            DashboardViewModels dashboard = new DashboardViewModels();

            dashboard.DeviceId    = deviceMessage_12.DeviceId;
            dashboard.Name        = deviceMessage_12.Device.Name;
            dashboard.Package     = deviceMessage_12.Data;
            dashboard.TypePackage = deviceMessage_12.TypePackage;
            dashboard.Date        = deviceMessage_12.Date;
            dashboard.Country     = deviceMessage_12.Country;
            dashboard.Lqi         = deviceMessage_12.Lqi;
            dashboard.Bits        = deviceMessage_12.Bits;

            // set location on dashboard of device
            DeviceLocation deviceLocation = GetDeviceLocationByDeviceId(dashboard.DeviceId);

            if (deviceLocation != null)
            {
                dashboard.Latitude  = deviceLocation.Latitude.ToString();
                dashboard.Longitude = deviceLocation.Longitude.ToString();
                dashboard.Radius    = deviceLocation.Radius;

                dashboard.LatitudeConverted  = LocationDecimalToDegrees((decimal)deviceLocation.Latitude, "S");
                dashboard.LongitudeConverted = LocationDecimalToDegrees((decimal)deviceLocation.Longitude, "W");
                dashboard.RadiusConverted    = RadiusFormated(deviceLocation.Radius);
            }

            // converter os bits deste
            dashboard.EstadoDetector     = deviceMessage_12.EstadoDetector;
            dashboard.PeriodoTransmissao = deviceMessage_12.PeriodoTransmissao;
            dashboard.AlertaFonteBaixa   = deviceMessage_12.AlertaFonteBaixa;

            dashboard.ContadorCarencias = deviceMessage_12.ContadorCarencias;
            dashboard.ContadorBloqueios = deviceMessage_12.ContadorBloqueios;

            var firstCaracter = deviceMessage_13.Temperature.Substring(0, deviceMessage_13.Temperature.Length - 1);
            var lastCaracter  = deviceMessage_13.Temperature.Substring(deviceMessage_13.Temperature.Length - 1, 1);

            dashboard.Temperature = $"{firstCaracter},{lastCaracter}";

            // dashboard.Alimentacao = deviceMessage_13.Alimentacao;
            if (deviceMessage_13.Alimentacao == "0")
            {
                if (deviceMessage_13.AlimentacaoH != "0")
                {
                    dashboard.Alimentacao = $"{deviceMessage_13.AlimentacaoL}{deviceMessage_13.AlimentacaoH}";
                }
                else
                {
                    dashboard.Alimentacao = deviceMessage_13.AlimentacaoL.Contains(",") ? $"{deviceMessage_13.AlimentacaoL}" : $"{deviceMessage_13.AlimentacaoL},0";
                }
            }
            else
            {
                dashboard.Alimentacao = deviceMessage_13.Alimentacao.Contains(",") ? $"{deviceMessage_13.Alimentacao}" : $"{deviceMessage_13.Alimentacao},0";
            }

            if (deviceRegistration.DataDownloadLink != null)
            {
                dashboard.Envio = deviceRegistration.Envio;
                dashboard.PeriodoTransmissao   = deviceRegistration.PeriodoTransmissao;
                dashboard.Bits.BaseTempoUpLink = deviceRegistration.BaseTempoUpLink;
                dashboard.TensaoMinima         = deviceRegistration.TensaoMinima;
            }

            return(dashboard);
        }
Exemplo n.º 28
0
 public LocationUpdatedEventArgs(DeviceLocation location)
 {
     this.location = location;
 }
    /// <summary>
    ///To Update the Device Location status to admin
    /// </summary>
    /// <param name="Ar"></param>
    /// <returns></returns>
    public HttpResponseMessage updateDeviceLocation(DeviceLocation DL)
    {
        ar = new WebApiResponse();        
        try
        {
            string qry = "select * from MDM_DeviceMaster where DeviceID='" + DL.uuid + "'";
            dr = databaseHelper.getDataReader(qry);

            if (dr.Read())
            {
                if (!dr.IsClosed)
                    dr.Close();

                DeviceTrackingDetail DT = new DeviceTrackingDetail();

                var list = DL.locations;
                foreach (var c in list)
                {
                    qry = "insert into MDM_DeviceTrackingDetail(DeviceId,latitude,longitude,CreatedDate)values('" + DL.uuid + "','" + c.latitude + "','" + c.longitude + "','" + c.timestamp.ToString("yyyy-MM-dd HH:mm:ss") + "')";
                    rcnt = databaseHelper.ExecuteQuery(qry);
                }
                ar.response = true;
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, ar);

                qry = "delete from MDM_PushNotification where DeviceID='" + DL.uuid + "' and Command='GetDeviceLocation'";
                rcnt = databaseHelper.ExecuteQuery(qry);

                return response;
            }
            else
            {
                ar.errorCode = "Authentication Failed";
                ar.response = false;
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, ar);
                return response;
            }
        }
        catch(Exception ex)
        {
            linfo.LogFile(enLogType.EXCEPTION, ex.Message,null);            
        }
        finally
        {
            if (dr != null && !dr.IsClosed)
                dr.Close();
        }
        return null;
    }
 public void Save(DeviceLocation location)
 {
     base.Save(location);
 }
Exemplo n.º 31
0
 private void Awake()
 {
     _instance = this;
 }
        private async Task GenerateDataAsync()
        {
            var random     = new Random();
            var collection = Enumerable.Range(_from, _to);
            var tasks      = new List <Task>();

            var stopwatch = Stopwatch.StartNew();

            foreach (var item in collection)
            {
                var id           = item.ToString();
                var partitionKey = new PartitionKey(id);
                var device       = new Device()
                {
                    ID      = id,
                    Name    = $"Device {item}",
                    Current = new Location()
                    {
                        Latitude  = 55,
                        Longitude = 44,
                        Timestamp = DateTimeOffset.UtcNow
                    }
                };
                var stream = new MemoryStream();
                await JsonSerializer.SerializeAsync(stream, device);

                tasks.Add(_devicesContainer.CreateItemStreamAsync(stream, partitionKey));

                if (tasks.Count() > _batch)
                {
                    Console.Write("+");
                    await Task.WhenAll(tasks);

                    tasks.Clear();
                }
            }

            Console.WriteLine("*");
            await Task.WhenAll(tasks);

            stopwatch.Stop();
            tasks.Clear();

            Console.WriteLine($"Device import took: {stopwatch.Elapsed}. Documents/s: {(_to - _from) * 1000 / stopwatch.ElapsedMilliseconds}");

            stopwatch.Restart();
            foreach (var item in collection)
            {
                var id           = item.ToString();
                var partitionKey = new PartitionKey(id);

                for (int i = 1; i < _locationsPerDevice + 1; i++)
                {
                    var deviceLocation = new DeviceLocation()
                    {
                        DeviceID = id,
                        Location = new Location()
                        {
                            Latitude  = 56,
                            Longitude = 45,
                            Timestamp = DateTimeOffset.UtcNow
                        }
                    };
                    var stream = new MemoryStream();
                    await JsonSerializer.SerializeAsync(stream, deviceLocation);

                    tasks.Add(_deviceLocationsContainer.CreateItemStreamAsync(stream, partitionKey));
                }

                if (tasks.Count() > _batch)
                {
                    Console.Write("+");
                    await Task.WhenAll(tasks);

                    tasks.Clear();
                }
            }

            Console.WriteLine("*");
            await Task.WhenAll(tasks);

            stopwatch.Stop();

            Console.WriteLine($"Device location import took: {stopwatch.Elapsed}. Documents/s: {(_to - _from) * _locationsPerDevice * 1000 / stopwatch.ElapsedMilliseconds}");

            //stopwatch.Restart();
            //foreach (var item in collection)
            //{
            //    var id = item.ToString();
            //    var partitionKey = new PartitionKey(id);

            //    var deviceLocation = new DeviceLocation()
            //    {
            //        DeviceID = id,
            //        Location = new Location()
            //        {
            //            Latitude = 56,
            //            Longitude = 45,
            //            Timestamp = DateTimeOffset.UtcNow
            //        }
            //    };

            //    await _deviceLocationsContainer.Scripts.ExecuteStoredProcedureAsync<string>(BulkImport, partitionKey, new dynamic[] { deviceLocation, random.Next(1200, 2500) });
            //    Console.Write("+");
            //}

            //stopwatch.Stop();
            //Console.WriteLine($"Device location import took: {stopwatch.Elapsed}.");
        }
Exemplo n.º 33
0
 public void TestDeviceLocationException()
 {
     DeviceLocation location = new DeviceLocation("");
 }