public DeviceDataModel GetById(String Id)
        {
            DeviceDataModel deviceData = _deviceData.Find <DeviceDataModel>(dd => dd.Id == Id).FirstOrDefault();

            deviceData.Timestamp += TimeSpan.FromHours(8);
            return(deviceData);
        }
        public IHttpActionResult GetAlarmDetailData(DeviceDataModel model)
        {
            DeviceDataBLL data = new DeviceDataBLL();
            var           get  = data.GetCurrentData(model);

            return(InspurJson <RetDeviceTableData>(get));
        }
        public IHttpActionResult GetEquipmentReportListData(DeviceDataModel model)
        {
            DeviceDataBLL data = new DeviceDataBLL();
            var           get  = data.GetEquipmentReportListData(model);

            return(InspurJson <RetDeviceTableData>(get));
        }
예제 #4
0
        /*
         * 根据数据ID(数据库ID)获取数据
         *
         * 输入:
         * ID
         *
         * 输出:
         * 该ID的设备数据
         */
        public DeviceDataSerializer GetDeviceDataById(String Id)
        {
            DeviceDataModel      deviceData = this._deviceDataDao.GetById(Id);
            DeviceDataSerializer result     = new DeviceDataSerializer(deviceData);

            return(result);
        }
예제 #5
0
 public static DeviceModel MapToDeviceModel(this DeviceDataModel dataModel)
 {
     return(new DeviceModel()
     {
         Id = dataModel.Id.ToString(),
         Name = dataModel.Name,
         FunctionCollection = dataModel.FunctionCollection?.Select(x => x.MapToFunctionModel()).ToList()
     });
 }
        public override Task <DeviceDataArray> GetProgramResults(ProgramPageRequest request, ServerCallContext context)
        {
            List <DeviceDataModel> modelList = new List <DeviceDataModel>();

            var    response = new DeviceDataArray();
            string filename = request.RunAccelerometer ? AccelerometerOnly.FileName : GyroscopeOnly.FileName;

            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                _logger.LogInformation($"Request: {request}");
                long startIndex = request.DataSetStart * request.SegmentSize;
                long endIndex   = startIndex + (request.Rows * request.SegmentSize);
                long rows       = request.Rows;

                _logger.LogInformation($"FileStream size: {fs.Length}. Start Index: {startIndex}. End Index: {endIndex}");
                if (startIndex > fs.Length)
                {
                    throw new IndexOutOfRangeException("Requested starting index is larger than the file's size.");
                }

                if (endIndex > fs.Length)
                {
                    long bytesLeft = fs.Length - startIndex;
                    rows = (bytesLeft / request.SegmentSize);
                }

                fs.Seek(startIndex, SeekOrigin.Begin);

                for (long i = 0; i < rows; i++)
                {
                    byte[] bytes = new byte[request.SegmentSize];

                    fs.Read(bytes, 0, request.SegmentSize);

                    DeviceDataModel model = new DeviceDataModel();

                    if (request.RunAccelerometer)
                    {
                        int[] accelData = System.Runtime.InteropServices.MemoryMarshal.Cast <byte, int>(bytes).ToArray();

                        model.AccelData.Add(accelData);
                    }
                    else if (request.RunGyroscope)
                    {
                        int[] gyroData = System.Runtime.InteropServices.MemoryMarshal.Cast <byte, int>(bytes).ToArray();

                        model.GyroData.Add(gyroData);
                    }

                    modelList.Add(model);
                }
            }

            response.Items.AddRange(modelList);

            return(Task.FromResult(response));
        }
        public String Update(String id, DeviceDataModel deviceDataModel)
        {
            var filter = Builders <DeviceDataModel> .Filter.Eq("_id", new ObjectId(id));

            var update = Builders <DeviceDataModel> .Update.Set("IndexValue", deviceDataModel.IndexValue.ToString());

            var result = _deviceData.UpdateOne(filter, update);

            return(result.ModifiedCount == 1 ? "success" : "error");
        }
 public DeviceDataSerializer(DeviceDataModel deviceDataModel)
 {
     this.id         = deviceDataModel.Id;
     this.deviceId   = deviceDataModel.DeviceId;
     this.indexName  = deviceDataModel.IndexName;
     this.indexId    = deviceDataModel.IndexId;
     this.indexUnit  = deviceDataModel.IndexUnit;
     this.indexType  = deviceDataModel.IndexType;
     this.indexValue = deviceDataModel.IndexValue;
     this.timestamp  = deviceDataModel.Timestamp
                       .ToString(Constant.getDateFormatString());
 }
        /// <summary>
        /// Is the device in the system. If it is, return true. Otherwise false
        /// </summary>
        /// <param name="deviceId">The device id of the device being checked.</param>
        /// <returns>Returns true if the device already registered. </returns>
        public bool IsDeviceRegistered(string deviceId)
        {
            DeviceDataModel ddm = this.dds.SelectByDeviceId(deviceId);

            if (ddm == null)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
예제 #10
0
        /*
         * 更新设备数据
         */
        public String UpdateDeviceData(String id, DeviceDataSerializer deviceDataSerializer)
        {
            DeviceDataModel deviceDataModel = new DeviceDataModel();

            deviceDataModel.Id         = deviceDataSerializer.id;
            deviceDataModel.DeviceId   = deviceDataSerializer.deviceId;
            deviceDataModel.IndexName  = deviceDataSerializer.indexName;
            deviceDataModel.IndexId    = deviceDataSerializer.indexId;
            deviceDataModel.IndexUnit  = deviceDataSerializer.indexUnit;
            deviceDataModel.IndexType  = deviceDataSerializer.indexType;
            deviceDataModel.IndexValue = deviceDataSerializer.indexValue;
            return(this._deviceDataDao.Update(id, deviceDataModel));
        }
 /// <summary>
 /// Enque either a common or iPhone message type to be sent to APNS. Get message components and enque it for the device
 /// </summary>
 /// <param name="device">Device to send the message to</param>
 /// <param name="msg">Message to send</param>
 public override void EnqueMessage(DeviceDataModel device, PushMessage msg)
 {
     if (msg.MessageType == (short)PushMessageType.Iphone)
     {
         string        msgStr    = ToString(msg);
         iPhoneMessage iPhoneMsg = FromString(msgStr, typeof(iPhoneMessage)) as iPhoneMessage;
         this.EnqueiOSMessage(device, iPhoneMsg);
     }
     else if (msg.MessageType == (short)PushMessageType.Common)
     {
         string        msgStr    = ToString(msg);
         iPhoneMessage iPhoneMsg = FromString(msgStr, typeof(iPhoneMessage)) as iPhoneMessage;
         this.EnqueiOSMessage(device, iPhoneMsg);
     }
 }
 /// <summary>
 /// Enques all types of WP7 message to each device URI in the subscription.
 /// </summary>
 /// <param name="ddm">Device to send message to.</param>
 /// <param name="messageBytes">Message bytes of the message to send.</param>
 /// <param name="type">Type of message to send.</param>
 private void EnqueWP7Notification(DeviceDataModel ddm, byte[] messageBytes, WP7NotificationType type)
 {
     // Get the all devices that have signed up for the subscription
     // Send the message to each device addrress or URI
     if (Uri.IsWellFormedUriString(ddm.Address, UriKind.Absolute))
     {
         this.SendWP7Message(new Uri(ddm.Address), messageBytes, type);
     }
     else
     {
         if (this.DeviceIdFormatError != null)
         {
             this.DeviceIdFormatError(this, new NotificationEventArgs(new DeviceIdFormatException(ddm.Address)));
         }
     }
 }
예제 #13
0
        public async Task <ResultCode> AddDataAsync(DeviceDataModel data)
        {
            if (!await _deviceStorage.ExistAsync(data.Seria))
            {
                return(ResultCode.NotFound);
            }

            var deviceId = await _deviceStorage.GetIdBySeriaAsync(data.Seria);

            data.DeviceId = deviceId;

            var entity = _mapper.Map <DeviceDataModel, ReadingEntity>(data);

            await _deviceStorage.AddReadingAsync(entity);

            return(ResultCode.Success);
        }
예제 #14
0
        /// <summary>
        /// Gets the list details of devices that have signed up for the subscriptions.
        /// </summary>
        /// <param name="subId">Subscription name</param>
        /// <returns>Returns the list of device details.</returns>
        public Collection <DeviceInfo> GetDevices(string subId)
        {
            IEnumerable <SubscriptionDataModel> isdm    = this.sds.SelectBySubscription(subId);
            Collection <DeviceInfo>             devList = new Collection <DeviceInfo>();

            foreach (SubscriptionDataModel sdm in isdm)
            {
                DeviceInfo devInfo = new DeviceInfo();
                devInfo.DeviceId = sdm.DeviceId;
                DeviceDataModel ddm = this.deviceMgr.GetDevice(sdm.DeviceId);
                devInfo.DeviceType = ddm.DeviceType;
                devInfo.DeviceUri  = ddm.Address;
                devList.Add(devInfo);
            }

            return(devList);
        }
예제 #15
0
 public DeviceDataSerializer(DeviceDataModel deviceDataModel)
 {
     this.id         = deviceDataModel.Id;
     this.deviceId   = deviceDataModel.DeviceId;
     this.indexName  = deviceDataModel.IndexName;
     this.indexId    = deviceDataModel.IndexId;
     this.indexUnit  = deviceDataModel.IndexUnit;
     this.indexType  = deviceDataModel.IndexType;
     this.indexValue = deviceDataModel.IndexValue;
     this.timestamp  = DateTime.Parse(deviceDataModel.Timestamp.ToString())
                       .ToLocalTime().ToString(Constant.getDateFormatString());
     this.gatewayId  = deviceDataModel.GatewayId;
     this.deviceType = deviceDataModel.DeviceType;
     this.mark       = deviceDataModel.Mark;
     this.isCheck    = deviceDataModel.IsCheck;
     this.deviceName = deviceDataModel.DeviceName;
 }
        /// <summary>
        /// Delete device from the d/b
        /// </summary>
        /// <param name="deviceId">The device id of the device delete.</param>
        /// <returns>Returns either success or error.</returns>
        public PushMessageError DeleteDevice(string deviceId)
        {
            if (string.IsNullOrEmpty(deviceId))
            {
                return(PushMessageError.ErrorIllegalDeviceId);
            }

            DeviceDataModel ddm = this.dds.SelectByDeviceId(deviceId);

            if (ddm == null)
            {
                return(PushMessageError.ErrorDeviceNotFound);
            }

            this.dds.Delete(ddm);
            return(PushMessageError.Success);
        }
        public DeviceDataModel GetSingleReading()
        {
            _status = ResultStatus.None;

            DeviceDataModel model = new DeviceDataModel();

            model.AccelData.Add(GetAccelerometerResults() ?? new int[0]);
            model.GyroData.Add(GetGyroscopeResults() ?? new int[0]);
            model.TransactionTime = GetRTCResults();
            model.CpuTemp         = GetCPUTemperatureResults();

            //Remove None flag
            _status &= ResultStatus.None;

            model.ResultStatus = (int)_status;

            return(model);
        }
 /// <summary>
 /// Enque either a common or WP7 message to be sent to MPNS. Get message components and send it to the device
 /// </summary>
 /// <param name="device">Device to send the message to</param>
 /// <param name="msg">Message to send</param>
 public override void EnqueMessage(DeviceDataModel device, PushMessage msg)
 {
     if (msg.MessageType == (short)PushMessageType.Toast)
     {
         this.EnqueWP7ToastNotification(device, msg.Message["toast"]);
     }
     else if (msg.MessageType == (short)PushMessageType.Raw)
     {
         this.EnqueWP7RawNotification(device, msg.Message["message"]);
     }
     else if (msg.MessageType == (short)PushMessageType.Tile || msg.MessageType == (short)PushMessageType.Common)
     {
         this.EnqueWP7TileNotification(device, msg.Message["title"], int.Parse(msg.Message["count"], CultureInfo.InvariantCulture), msg.Message["url"]);
     }
     else
     {
         return;
     }
 }
예제 #19
0
        public async Task <ActionResult> AddOrUpdate(DeviceDataModel d)
        {
            using (var db = new EFWorkContext())
            {
                var dd = await db.DeviceData.AsNoTracking().Where(a => a.Name == d.Name).FirstOrDefaultAsync();//.FirstOrDefault();

                if (dd == null)
                {
                    dd = db.DeviceData.Add(d);
                }
                else
                {
                    dd.Message = d.Message;
                    dd.Dt      = DateTime.Now;
                    db.Entry <DeviceDataModel>(dd).State = EntityState.Modified;
                }
                db.SaveChanges();
                return(Json(new { dd.DeviceId }));
            }
        }
        /// <summary>
        /// Adds the device or updates it. For WP7, the URI will be updated frequently.
        /// deviceID is maintained as the index into the d/b
        /// </summary>
        /// <param name="devTypeName">The type of the device being added or updated.</param>
        /// <param name="deviceId">The device id of the device being added or updated.</param>
        /// <param name="deviceUri">The device uri. Used only for WP7 and empty string for others.</param>
        /// <returns>Returns success or an error.</returns>
        public PushMessageError AddOrUpdateDevice(string devTypeName, string deviceId, string deviceUri)
        {
            DeviceDataModel ddm = this.dds.SelectByDeviceIdAndType(deviceId, devTypeName);

            if (ddm == null)
            {
                // No such device, create it
                ddm         = new DeviceDataModel(devTypeName, deviceId);
                ddm.Address = deviceUri;
                this.dds.Insert(ddm);
                return(PushMessageError.Success);
            }
            else
            {
                // For WP7, we will update the URI with the new value
                ddm.Address = deviceUri;
                this.dds.Update(ddm);
                return(PushMessageError.Success);
            }
        }
        public override async Task StreamDeviceData(DeviceDataRequest request, IServerStreamWriter <DeviceDataModel> responseStream, ServerCallContext context)
        {
            try
            {
                while (!context.CancellationToken.IsCancellationRequested)
                {
                    DeviceDataModel resultReply = _dataService.GetSingleReading();

                    if (context.CancellationToken.IsCancellationRequested)
                    {
                        context.CancellationToken.ThrowIfCancellationRequested();
                    }
                    await responseStream.WriteAsync(resultReply);
                }
            }
            catch (OperationCanceledException)
            {
                _logger.LogInformation("Stream cancelled by user request.");
            }
        }
예제 #22
0
        public void TestInsertDeviceIfDeviceIsNotInDB()
        {
            string       medicalDeviceUrl = url + "/MedicalDevice";
            IRestClient  restClient       = new RestClient();
            IRestRequest restRequest      = new RestRequest()
            {
                Resource = medicalDeviceUrl
            };
            var deviceInfo = new DeviceDataModel()
            {
                DeviceName = "BloodPressure",
                MinValue   = 20,
                MaxValue   = 50
            };

            restRequest.AddHeader("Content-Type", "application/json");
            restRequest.AddJsonBody(deviceInfo);
            IRestResponse restResponse = restClient.Post(restRequest);

            Assert.AreEqual(restResponse.StatusCode, HttpStatusCode.OK);
        }
예제 #23
0
        public void TestInsertDeviceInvalidDataFormat()
        {
            string       medicalDeviceUrl = url + "/MedicalDevice";
            IRestClient  restClient       = new RestClient();
            IRestRequest restRequest      = new RestRequest()
            {
                Resource = medicalDeviceUrl
            };
            var deviceInfo = new DeviceDataModel()
            {
                DeviceName = "bp",
                MinValue   = 70,
                MaxValue   = 20
            };

            restRequest.AddHeader("Content-Type", "application/json");
            restRequest.AddJsonBody(deviceInfo);
            IRestResponse restResponse = restClient.Post(restRequest);

            Assert.AreEqual((int)restResponse.StatusCode, 400);
        }
예제 #24
0
        public static Vibe2020DataModel ConvertToDataModel(DeviceDataModel deviceData)
        {
            Vibe2020DataModel model = new Vibe2020DataModel();

            if (deviceData?.AccelData != null && deviceData.AccelData.Count > 0)
            {
                model.AccelData_Raw = new int[] { deviceData.AccelData[0], deviceData.AccelData[1], deviceData.AccelData[2] };

                model.AccelData = new double[] {
                    ScaleAccelerometer(deviceData.AccelData[0]),
                    ScaleAccelerometer(deviceData.AccelData[1]),
                    ScaleAccelerometer(deviceData.AccelData[2])
                };
            }

            if (deviceData?.GyroData != null && deviceData.GyroData.Count > 0)
            {
                Span <int> data = new int[4]
                {
                    deviceData.GyroData[0],
                    deviceData.GyroData[1],
                    deviceData.GyroData[2],
                    deviceData.GyroData[3]
                };

                Span <byte> bytes = MemoryMarshal.Cast <int, byte>(data);
                model.GyroData_Raw = GyroConversionHelper.CombineBytes(bytes).ToArray();

                model.GyroData = GyroConversionHelper.GetGyroscopeDetails(model.GyroData_Raw).ToArray();
            }

            model.ResultStatus = (ResultStatus)deviceData.ResultStatus;

            model.TransactionTime = new DateTime(deviceData.TransactionTime).ToLocalTime();

            model.CpuTemp = deviceData.CpuTemp;

            return(model);
        }
예제 #25
0
        public AlarmInfoModel AlarmInfoGenerator(DeviceDataModel deviceData, ThresholdModel threshold)
        {
            AlarmInfoModel alarmInfo = new AlarmInfoModel
            {
                AlarmInfo      = threshold.Description,
                DeviceId       = deviceData.DeviceId,
                IndexId        = deviceData.IndexId,
                IndexName      = deviceData.IndexName,
                IndexValue     = deviceData.IndexValue,
                ThresholdValue = threshold.ThresholdValue,
                Timestamp      = DateTime.Now,
                Severity       = threshold.Severity,
                Processed      = "No"
            };

            if (threshold.Operator == "equal")
            {
                if (deviceData.IndexValue != threshold.ThresholdValue)
                {
                    return(alarmInfo);
                }
            }
            else if (threshold.Operator == "less")
            {
                if (deviceData.IndexValue > threshold.ThresholdValue)
                {
                    return(alarmInfo);
                }
            }
            else
            {
                if (deviceData.IndexValue < threshold.ThresholdValue)
                {
                    return(alarmInfo);
                }
            }
            return(null);
        }
        public IHttpActionResult GetEnergyReportListData(EquipmentEnergyModel parameter)
        {
            RetDeviceTableData        info  = new RetDeviceTableData();
            List <RetDeviceTableList> table = new List <RetDeviceTableList>();

            if (parameter.Property != null)
            {
                int i = 0;
                for (; i < parameter.Property.Count; i++)
                {
                    DeviceDataModel model = new DeviceDataModel();
                    model.DeviceID            = parameter.Property[i].data[0];
                    model.DeviceItemID        = parameter.Property[i].data[1];
                    model.StartTime           = parameter.StartTime;
                    model.EndTime             = parameter.EndTime;
                    model.StatisticalInterval = parameter.StatisticalInterval;
                    model.IntervalUnit        = parameter.IntervalUnit;
                    model.GetTogetherType     = parameter.Type;
                    DeviceDataBLL data = new DeviceDataBLL();
                    var           get  = data.GetEnergyReportListData(model);
                    if (get.Data != null)
                    {
                        foreach (var item in get.Data.DeviceTableList)
                        {
                            table.Add(item);
                        }
                    }
                }
            }
            info.DeviceTableList = table.OrderByDescending(o => o.Time).ToList();
            ReturnItem <RetDeviceTableData> r = new ReturnItem <RetDeviceTableData>();

            r.Count = info.DeviceTableList.Count();
            r.Msg   = "设备数据获取成功";
            r.Code  = 0;
            r.Data  = info;
            return(InspurJson <RetDeviceTableData>(r));
        }
예제 #27
0
 /// <summary>
 ///  enques all types of WP7 message to each device URI in the subscription.
 /// </summary>
 /// <param name="subscription"></param>
 /// <param name="messageBytes"></param>
 /// <param name="type"></param>
 private void EnqueAndroidNotification(DeviceDataModel ddm, byte[] msgBytes)
 {
     try
     {
         // get the all devices that have signed up for the subscription
         // send the message to each device addrress or URI
         this.SendAndroidMessage(msgBytes);
     }
     catch (ObjectDisposedException e)
     {
         if (this.NotificationFailed != null)
         {
             this.NotificationFailed(this, new NotificationEventArgs(e));
         }
     }
     catch (System.IO.IOException e)
     {
         if (this.NotificationFailed != null)
         {
             this.NotificationFailed(this, new NotificationEventArgs(e));
         }
     }
 }
예제 #28
0
 /// <summary>
 /// Enque either a common or WP7 message to be sent to MPNS. Get message components and send it to the device
 /// </summary>
 /// <param name="device">Device to send the message to</param>
 /// <param name="msg">Message to send</param>
 public override void EnqueMessage(DeviceDataModel device, PushMessage msg)
 {
     if (msg.MessageType == (short)PushMessageType.Toast)
     {
         this.EnqueAndroidToastNotification(device, msg.Message["toast"]);
     }
     else if (msg.MessageType == (short)PushMessageType.Raw)
     {
         this.EnqueAndroidRawNotification(device, msg.Message["raw"]);
     }
     else if (msg.MessageType == (short)PushMessageType.Common)
     {
         this.EnqueAndroidCommonNotification(device, msg.Message["title"], int.Parse(msg.Message["count"], CultureInfo.InvariantCulture), msg.Message["sound"]);
     }
     else if (msg.MessageType == (short)PushMessageType.Iphone)
     {
         this.EnqueAndroidCommonNotification(device, msg.Message["title"], int.Parse(msg.Message["count"], CultureInfo.InvariantCulture), msg.Message["sound"]);
     }
     else
     {
         return;
     }
 }
        public DeviceDataModel[] GetReadings(int numReadings = 1000)
        {
            Span <DeviceDataModel> dataModels = new DeviceDataModel[numReadings];
            DateTime startTime = DateTime.Now;

            for (int i = 0; i < numReadings; i++)
            {
                _status = ResultStatus.None;

                DeviceDataModel model = new DeviceDataModel();

                model.AccelData.AddRange(GetAccelerometerResults() ?? new int[0]);
                model.GyroData.AddRange(GetGyroscopeResults() ?? new int[0]);
                model.TransactionTime = GetRTCResults();
                model.CpuTemp         = GetCPUTemperatureResults();
                model.ResultStatus    = (int)_status;

                dataModels[i] = model;
            }
            _logger.LogInformation($"Finished {numReadings} items in {(DateTime.Now - startTime).TotalSeconds} seconds!");

            return(dataModels.ToArray());
        }
 /// <summary>
 /// Formats a file message and enques it for sending it out to  dtheevices in the subscription.
 /// </summary>
 /// <param name="ddm">Devices to send the message to.</param>
 /// <param name="title">Title of the push notification.</param>
 /// <param name="count">Count to be shown on the tile.</param>
 /// <param name="image">Image to show on the tile.</param>
 private void EnqueWP7TileNotification(DeviceDataModel ddm, string title, int count, string image)
 {
     byte[] messageBytes = PackageTileNotification(title, count, image);
     this.EnqueWP7Notification(ddm, messageBytes, WP7NotificationType.Tile);
 }