示例#1
0
        public ActionResult Image(long id = 0)
        {
            DeviceLog devicelog = logdb.DeviceLogs.Find(id);

            if (devicelog == null)
            {
                return(HttpNotFound());
            }
            byte[] data     = System.Convert.FromBase64String(devicelog.Message);
            string filePath = Request.MapPath("~/Content/tmp.png");

            System.IO.File.WriteAllBytes(filePath, data);

            string testPathSource = Request.MapPath("~/Content/test.png");
            string testPathTarge  = Request.MapPath("~/Content/test.png.txt");
            //byte[] testContent = System.IO.File.ReadAllBytes(testPathSource);
            //System.IO.File.WriteAllText(testPathTarge, System.Convert.ToBase64String(testContent));
            string        testContent = System.IO.File.ReadAllText(testPathTarge);
            Base64Decoder decoder     = new Base64Decoder(testContent.ToCharArray());

            System.IO.File.WriteAllBytes(testPathSource, decoder.GetDecoded());
            //System.IO.File.WriteAllText(testPathTarge, System.Convert.ToBase64String(testContent));

            return(File(filePath, "image/png"));
        }
示例#2
0
        public DeviceLog Save(DeviceLog deviceLog)
        {
            var updatedAt = Convert.ToString(deviceLog.UpdatedAt);

            _eventHubService.ALogWasGeneratedEvent(this, new PayloadUpdateLog(deviceLog.Message, deviceLog.DeviceSerial, updatedAt, deviceLog.LogLevel));
            return(_deviceLogRepository.Save(deviceLog));
        }
示例#3
0
        private double CalculateEnergyUsage(string timePeriod, DeviceLog log)
        {
            DateTime dtOn  = new DateTime();
            DateTime dtOff = new DateTime();
            double   sum   = 0;

            if (log.State == "on")
            {
                dtOn = log.DateTime;
                System.Diagnostics.Debug.WriteLine("Datetime on: " + dtOn);
            }
            else if (log.State == "off")
            {
                dtOff = log.DateTime;

                if (dtOn != null)
                {
                    TimeSpan span = dtOff.Subtract(dtOn);
                    sum += log.KWh * span.TotalHours;
                }

                // clear
                dtOn  = new DateTime();
                dtOff = new DateTime();
            }

            return(sum);
        }
        public CollectionWithLogsTests()
        {
            _log = new DeviceLog {
                DateStamp = DateTime.Now, PluginName = "SamsungDPlugin"
            };
            var options = Options
                          .Create(new ServerSettings
            {
                DataStoragePlugin = new ServerSettingViewModel
                {
                    Name        = "DataStoragePlugin",
                    Value       = "MSSQLDSPlugin",
                    DisplayName = "Data storage plugin",
                    IsEditable  = false
                },
                CapacityOfCollectionToInsert = new ServerSettingViewModel
                {
                    Name        = "BulkInsertCapacity",
                    DisplayName = "Bulk insert capacity",
                    Value       = 100.ToString(),
                    IsEditable  = true
                },
                IntervalForWritingIntoDb = new ServerSettingViewModel
                {
                    Name        = "BulkInsertInterval",
                    DisplayName = "Bulk insert interval",
                    Value       = 100.ToString(),
                    IsEditable  = true
                }
            });

            _appSettingsModifier = new AppSettingsAccessor(options);

            _helperCollection = new CollectionOfLogs(_appSettingsModifier);
        }
        public List <DeviceLog> GetLogsToInsert()
        {
            try
            {
                lock (_locker)
                {
                    if (_helperQueue.Any() && ((AreUserSettingsUpdated) || (_helperQueue.Peek().Count == _serverSettings.CapacityOfCollectionToInsert.Value.ConvertToInt())))
                    {
                        AreUserSettingsUpdated = false;

                        var collectionToInsert = _helperQueue.Peek();
                        var temporaryObj       = new DeviceLog[collectionToInsert.Count];

                        collectionToInsert.CopyTo(temporaryObj);

                        collectionToInsert.Clear();

                        RemoveCollectionFromQueue();

                        return(temporaryObj.Where(x => x != null).ToList());
                    }
                }
            }
            catch (Exception ex)
            {
                //Debugger.Break();
                Console.WriteLine(ex.Message);
            }

            return(new List <DeviceLog>());
        }
示例#6
0
        public async Task GetForDateRangeAsync()
        {
            var timeStamp = new DateTime(2018, 10, 1, 1, 0, 0);
            var logEntry  = new DeviceLog
            {
                DateStamp = DateTime.UtcNow.ToJSONString(),
                DeviceId  = Guid.NewGuid().ToId(),
                Entry     = "entry",
                EntryType = "entrytype",
                MetaData  = "meta",
                RowKey    = Guid.NewGuid().ToId(),
                Source    = "source"
            };
            await DataFactory.DeviceLogRepo.AddLogEntryAsync(DataFactory.DeviceRepo, logEntry);

            timeStamp          = new DateTime(2018, 10, 1, 2, 0, 0);
            logEntry.DateStamp = timeStamp.ToJSONString();
            logEntry.RowKey    = Guid.NewGuid().ToId();
            await DataFactory.DeviceLogRepo.AddLogEntryAsync(DataFactory.DeviceRepo, logEntry);

            var listRequest = new ListRequest
            {
                PageIndex = 1,
                PageSize  = 25,
                StartDate = timeStamp.AddDays(-2).ToJSONString()
            };
            var response = await DataFactory.DeviceLogRepo.GetForDateRangeAsync(DataFactory.DeviceRepo, logEntry.DeviceId, listRequest);

            Assert.IsTrue(response.Successful);
            Assert.IsTrue(response.Model.Count() > 0);
        }
        public void InMemoryStorage_After1000CallsFromApi_ContainsElementsInTheSameOrderAsTheyCameFromApi()
        {
            // Arrange
            var repo         = new DeviceLogsRepoMock();
            var countOfCalls = 1000;

            new LogsStorageWriter(_helperCollection, repo, _appSettingsModifier).RunLogsChecker(CancellationToken.None);
            var copyOfHelperCollectionAsList = new List <DeviceLog>();

            // Act

            var taskWriters = Enumerable.Range(1, countOfCalls).Select(x =>
            {
                return(Task.Run(() =>
                {
                    var log = new DeviceLog {
                        DateStamp = DateTime.Now, PluginName = "SamsungDPlugin", Id = x
                    };

                    lock (_locker)
                    {
                        _helperCollection.AddLog(log);
                        copyOfHelperCollectionAsList.Add(log);
                    }
                }));
            }).ToArray();

            Task.WaitAll(taskWriters); // full the collection of collections
            Thread.Sleep(3000);

            var isEqual = Enumerable.SequenceEqual(repo.logsInMemory, copyOfHelperCollectionAsList);

            //Assert
            Assert.True(isEqual);
        }
示例#8
0
        //命令执行后调用
        public override void OnCommandExecuted(CommandExecutingContext commandContext)
        {
            SZSLNoiseSession session = (SZSLNoiseSession)commandContext.Session;

            BLL.DeviceLog       bllLog    = new DeviceLog();
            BLL.Device          bllDevice = new Device();
            Model.DeviceLogInfo log       = new Model.DeviceLogInfo();
            log.DEVICE_ID   = Convert.ToInt32(bllDevice.getDeviceIdByCode(session.MacID));
            log.OPERATETYPE = "下发";
            log.LOGTIME     = DateTime.Now;

            if (session.Conf != null)
            {
                //记录实际下发信息
                string   content  = session.Conf.FrameContent;
                string[] items    = content.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
                byte[]   sendData = new byte[items.Length];
                for (int i = 0; i < items.Length; i++)
                {
                    sendData[i] = byte.Parse(items[i], System.Globalization.NumberStyles.HexNumber);
                }
                log.MESSAGE = "更新渗漏配置:密集开始时间:" + sendData[4] + ":" + sendData[5] +
                              "样本间隔:" + sendData[6] + "采集个数:" + sendData[7];
            }
            else
            {
                //记录默认配置信息
                byte[] set = ApplicationContext.getInstance().getDefaultSLConfig();
                log.MESSAGE = "更新渗漏配置:密集开始时间:" + set[4] + ":" + set[5] +
                              "样本间隔:" + set[6] + "采集个数:" + set[7];
            }
            bllLog.insert(log);
        }
        public int CreateDeviceLog(DeviceLogDto deviceLogDto)
        {
            Mapper.CreateMap <DeviceLogDto, DeviceLog>();
            DeviceLog tblDeviceLog = Mapper.Map <DeviceLogDto, DeviceLog>(deviceLogDto);

            _deviceLogRepository.CreateDeviceLog(tblDeviceLog, _dbContext);
            return(_dbContext.SaveChanges());
        }
示例#10
0
        public ActionResult DeleteConfirmed(long id)
        {
            DeviceLog devicelog = logdb.DeviceLogs.Find(id);

            logdb.DeviceLogs.Remove(devicelog);
            logdb.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public override void OnCommandExecuting(SuperSocket.SocketBase.CommandExecutingContext commandContext)
        {
            BLL.DeviceLog bllLog    = new DeviceLog();
            BLL.Device    bllDevice = new Device();

            DGNSZSession  session = (DGNSZSession)commandContext.Session;
            DeviceLogInfo log     = null;

            //如果没有设备id,则进行了校时操作。
            if (string.IsNullOrEmpty(session.MacID))
            {
                session.Logger.Info("多功能漏损监测仪校时成功!");

                byte[] sectionClose = Utility.ApplicationContext.getInstance().getLSSectionCloseConfig();
                session.Send(sectionClose, 0, sectionClose.Length);
                session.Logger.Info("LSSECTION结束帧已经发送!" + BitConverter.ToString(sectionClose));
                commandContext.Cancel = true;
                return;
            }

            //设备下发了噪声的默认配置
            if (session.NoiseConf == null)
            {
                session.Logger.Info("多功能漏损监测仪噪声(" + session.MacID + ")默认配置成功!");

                log             = new DeviceLogInfo();
                log.DEVICE_ID   = Convert.ToInt32(bllDevice.getDeviceIdByCode(session.MacID));
                log.MESSAGE     = "噪声初始化!";
                log.OPERATETYPE = "下发";
                log.LOGTIME     = DateTime.Now;
                bllLog.insert(log);
                return;
            }

            //设备配置下发
            session.Logger.Info("多功能漏损监测仪噪声(" + session.MacID + ")配置成功:" + session.NoiseConf.FrameContent);

            session.NoiseConf.Status = true;
            new DeviceConfig().Update(session.NoiseConf);

            string[] config    = session.NoiseConf.FrameContent.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
            string   hour1     = byte.Parse(config[9], System.Globalization.NumberStyles.HexNumber).ToString();
            string   second1   = byte.Parse(config[10], System.Globalization.NumberStyles.HexNumber).ToString();
            string   interval1 = byte.Parse(config[11], System.Globalization.NumberStyles.HexNumber).ToString();
            string   count1    = byte.Parse(config[12], System.Globalization.NumberStyles.HexNumber).ToString();

            string hour2     = byte.Parse(config[17], System.Globalization.NumberStyles.HexNumber).ToString();
            string second2   = byte.Parse(config[18], System.Globalization.NumberStyles.HexNumber).ToString();
            string interval2 = byte.Parse(config[19], System.Globalization.NumberStyles.HexNumber).ToString();

            log           = new DeviceLogInfo();
            log.DEVICE_ID = Convert.ToInt32(bllDevice.getDeviceIdByCode(session.MacID));
            log.MESSAGE   = "噪声配置下发。密集开始时间" + hour1 + ":" + second1 + ";密集间隔" + interval1 + ";密集样本数:"
                            + count1 + ";松散开始时间" + hour2 + ":" + second2 + ";松散间隔:" + interval2;
            log.OPERATETYPE = "下发";
            log.LOGTIME     = DateTime.Now;
            bllLog.insert(log);
        }
示例#12
0
        private void ArchiveTextFile(long id = 0)
        {
            DeviceLog devicelog = logdb.DeviceLogs.Find(id);

            if (devicelog != null)
            {
                ArchiveTextFile(devicelog);
            }
        }
示例#13
0
        public void SaveLog(String log, String deviceId)
        {
            DeviceLog newlog = new DeviceLog();

            newlog.DeviceId = deviceId;
            newlog.Date     = GlobalWebData.ToUniversalTime();
            newlog.Log      = log;
            earthquakeRepository.DbContext.DevicesLogs.Add(newlog);
            earthquakeRepository.Save();
        }
示例#14
0
        public ActionResult Delete(long id = 0)
        {
            DeviceLog devicelog = logdb.DeviceLogs.Find(id);

            if (devicelog == null)
            {
                return(HttpNotFound());
            }
            return(View(devicelog));
        }
        public bool AddLog(DeviceLog log)
        {
            lock (_locker)
            {
                var workingCollection = GetWorkingCollection();

                workingCollection.Add(log);
            }

            return(true);
        }
示例#16
0
    public void WriteLog(string str)
    {
        var log = new DeviceLog()
        {
            s    = str,
            date = DateTime.Now
        };

        Logs.Add(log);
        RecvDeviceLog?.Invoke(log);
    }
示例#17
0
 private static uint GetPartition(DeviceLog deviceLog, uint partitionCount)
 {
     if (!Guid.TryParse(deviceLog.InstallId, out var installId))
     {
         return(0);
     }
     unchecked
     {
         var hash = (uint)GetMurmurHash(installId);
         return(hash % partitionCount);
     }
 }
        public override void OnCommandExecuting(SuperSocket.SocketBase.CommandExecutingContext commandContext)
        {
            BLL.DeviceLog bllLog    = new DeviceLog();
            BLL.Device    bllDevice = new Device();
            DGNSZSession  session   = (DGNSZSession)commandContext.Session;

            Model.DeviceLogInfo log = new Model.DeviceLogInfo();
            log.DEVICE_ID   = Convert.ToInt32(bllDevice.getDeviceIdByCode(session.MacID));
            log.MESSAGE     = "压力数据上报";
            log.OPERATETYPE = "上报";
            log.LOGTIME     = DateTime.Now;
            bllLog.insert(log);
        }
示例#19
0
        static void HandleV114Message(V114Message message, DeviceClient client, LisconDbEntities db)
        {
            var log = new DeviceLog()
            {
                DevIDNO   = client.DevIDNO,
                LogType   = (int)LogTypes.Gps,
                LogTime   = client.Runtime.GpsTime,
                Latitude  = client.Runtime.Latitude,
                Longitude = client.Runtime.Longitude
            };

            DeviceLogBL.Add(log, db);
        }
        public IHttpActionResult Post(DeviceLogInputModel model)
        {
            if (String.IsNullOrWhiteSpace(model.FileName)) 
            {
                return BadRequest();
            }

            var logFile = new DeviceLog(model.FileName);
            var fileId = DeviceLogRepository.CreateDeviceLog(logFile);
            var response = DeviceLogResponseModel.From(fileId);

            return Ok(response);
        }
示例#21
0
 public async Task AddLogEntryAsync()
 {
     var logEntry = new DeviceLog
     {
         DateStamp = DateTime.UtcNow.ToJSONString(),
         DeviceId  = Guid.NewGuid().ToId(),
         Entry     = "entry",
         EntryType = "entrytype",
         MetaData  = "meta",
         RowKey    = Guid.NewGuid().ToId(),
         Source    = "source"
     };
     await DataFactory.DeviceLogRepo.AddLogEntryAsync(DataFactory.DeviceRepo, logEntry);
 }
示例#22
0
        // Mark Processed Image
        public string MPI(string d, string p, long id)
        {
            string message = string.Empty;

            if (AuthenticateAdminDevice(d, p))
            {
                DeviceLog devicelog = logdb.DeviceLogs.Find(id);
                devicelog.Processed          = 100;
                logdb.Entry(devicelog).State = EntityState.Modified;
                logdb.SaveChanges();
            }

            return(message);
        }
        //命令执行后调用
        public override void OnCommandExecuted(CommandExecutingContext commandContext)
        {
            SZSLNoiseSession session = (SZSLNoiseSession)commandContext.Session;

            BLL.DeviceLog bllLog    = new DeviceLog();
            BLL.Device    bllDevice = new Device();

            Model.DeviceLogInfo log = new Model.DeviceLogInfo();
            log.DEVICE_ID   = Convert.ToInt32(bllDevice.getDeviceIdByCode(session.MacID));
            log.MESSAGE     = "渗漏噪声服务器地址配置:" + ApplicationContext.getInstance().getSLIpConfig();
            log.OPERATETYPE = "下发";
            log.LOGTIME     = DateTime.Now;

            bllLog.insert(log);
        }
示例#24
0
        public void CreateLog(DeviceLog deviceLog)
        {
            string query = "INSERT INTO DeviceLog (deviceId, userId, logtime) " +
                           "VALUES (@deviceId, @userId, @logtime) ";

            using (SqlCommand cmd = new SqlCommand(query, connection))
            {
                cmd.Parameters.Add("@deviceId", SqlDbType.VarChar, 50).Value = deviceLog.DeviceId;
                cmd.Parameters.Add("@userId", SqlDbType.VarChar, 50).Value   = deviceLog.UserId;
                cmd.Parameters.Add("@logtime", SqlDbType.DateTime).Value     = DateTime.Now;
                connection.Open();
                cmd.ExecuteNonQuery();
                //connection.Close();
            }
        }
示例#25
0
        private ActionResult SaveTextFile(long id = 0, string file = null)
        {
            DeviceLog devicelog = logdb.DeviceLogs.Find(id);

            if (devicelog == null)
            {
                return(HttpNotFound());
            }

            string decoded        = Server.UrlDecode(devicelog.Message);
            string testPathSource = Request.MapPath(file);

            System.IO.File.WriteAllText(testPathSource, decoded);

            return(File(testPathSource, "Text/plain"));
        }
示例#26
0
        private void ArchiveTextFile(DeviceLog devicelog)
        {
            string decoded = Server.UrlDecode(devicelog.Message);

            string file     = string.Format("~/App_Data/Archive/{0}-{1}-{2}/{3}/{4}-{5}.txt", devicelog.CreationDate.Year, devicelog.CreationDate.Month, devicelog.CreationDate.Day, devicelog.CreationDate.Hour, devicelog.DeviceID, devicelog.ID);
            string filePath = Request.MapPath(file);

            System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath));
            System.IO.File.WriteAllText(filePath, decoded);

            devicelog.Message   = file;
            devicelog.Processed = 900; // Archived

            logdb.Entry(devicelog).State = EntityState.Modified;
            logdb.SaveChanges();
        }
    public async Task <IActionResult> PostLog([FromBody] DeviceLog log)
    {
        log.Time = DateTime.Now;
        if (ModelState.IsValid)
        {
            var checkIfExist = _dbcontext.Devices.Where(x => x.DeviceId == log.DeviceId).Count() > 0;
            if (!checkIfExist)
            {
                return(BadRequest("Unable to find device id " + log.DeviceId));
            }
            await _dbcontext.AddAsync(log);

            _dbcontext.SaveChanges();
            return(new ObjectResult(log));
        }
        return(BadRequest(ModelState));
    }
        //命令执行后调用
        public override void OnCommandExecuted(CommandExecutingContext commandContext)
        {
            BLL.DeviceLog    bllLog    = new DeviceLog();
            BLL.Device       bllDevice = new Device();
            SZSLNoiseSession session   = (SZSLNoiseSession)commandContext.Session;

            try
            {
                Model.DeviceLogInfo log = new Model.DeviceLogInfo();
                log.DEVICE_ID   = Convert.ToInt32(bllDevice.getDeviceIdByCode(session.MacID));
                log.MESSAGE     = "渗漏噪声数据上传";
                log.OPERATETYPE = "上报";
                log.LOGTIME     = DateTime.Now;
                bllLog.insert(log);
            }
            catch (Exception e)
            {
                commandContext.Session.Logger.Error("设备重启记录保存异常" + e.ToString());
            }
        }
示例#29
0
        public async Task WriteDeviceLog(DeviceLog log, bool purgeBeforeWrite = false)
        {
            var connection = _context.OpenConn();

            using (var transaction = connection.BeginTransaction())
            {
                if (purgeBeforeWrite)
                {
                    await connection.ExecuteAsync(
                        "delete from ApplicationLogs where DeviceId = @deviceId",
                        new { deviceId = log.DeviceId }, transaction);
                }

                const string sql = @"
                    insert into ApplicationLogs(Id, DeviceId, Type, Message, CreatedLocal, CreatedUtc) 
                    values (@Id, @DeviceId, @Type, @Message, @CreatedLocal, @CreatedUtc)";


                await connection.ExecuteAsync(sql, log.Entries, transaction);
            }
        }
示例#30
0
        public override void OnCommandExecuting(SuperSocket.SocketBase.CommandExecutingContext commandContext)
        {
            DeviceLog bllLog    = new DeviceLog();
            Device    bllDevice = new Device();

            DGNSZSession  session = (DGNSZSession)commandContext.Session;
            DeviceLogInfo log     = null;

            if (session.PressConf != null)
            {
                session.Logger.Info("多功能漏损监测仪压力(" + session.MacID + ")配置成功!");

                session.PressConf.Status = true;
                new DeviceConfig().Update(session.PressConf);

                string[] config    = session.PressConf.FrameContent.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
                string   interval1 = Int16.Parse(config[8] + config[9], System.Globalization.NumberStyles.HexNumber).ToString();
                string   interval2 = Int16.Parse(config[10] + config[11], System.Globalization.NumberStyles.HexNumber).ToString();

                log             = new Model.DeviceLogInfo();
                log.DEVICE_ID   = Convert.ToInt32(bllDevice.getDeviceIdByCode(session.MacID));
                log.MESSAGE     = "压力配置下发.采集间隔" + interval1 + ";发送间隔" + interval2;
                log.OPERATETYPE = "add";
                log.LOGTIME     = DateTime.Now;
                bllLog.insert(log);
            }
            else
            {
                session.Logger.Info("多功能漏损监测仪压力(" + session.MacID + ")默认配置成功!");

                log             = new Model.DeviceLogInfo();
                log.DEVICE_ID   = Convert.ToInt32(bllDevice.getDeviceIdByCode(session.MacID));
                log.MESSAGE     = "压力初始化!";
                log.OPERATETYPE = "add";
                log.LOGTIME     = DateTime.Now;
                bllLog.insert(log);
            }
        }
示例#31
0
        public async Task When(LogEventReceived command)
        {
            // Create a new device log domain entity from received command.
            var deviceLog = DeviceLog.ForExistingDevice(command.DeviceId);

            foreach (LogEventModel model in command.LogEvents)
            {
                var logEvent = new ApplicationLog {
                    Type         = model.Type,
                    Message      = model.Content,
                    CreatedLocal = model.TimestampLocal,
                    CreatedUtc   = model.TimestampUtc
                };

                deviceLog.AddLog(logEvent);
            }

            // Save the device log and optionally delete any prior entries.
            using (_repoContext)
            {
                await _deviceRepository.WriteDeviceLog(deviceLog, command.PurgeExisting);
            }
        }