public static Timelapse Get(int id) { var timelapse = new Timelapse(); try { const string sql = "Select * FROM Timelapses WHERE Id=@Id AND IsDeleted=0 ORDER BY CreatedDT DESC"; var p1 = new SqlParameter("@Id", id); var cmd = new SqlCommand { CommandText = sql, CommandType = CommandType.Text }; cmd.Parameters.Add(p1); cmd.Connection = Connection.DbConnection; Connection.OpenConnection(); var dr = GetListFromDataReader(cmd.ExecuteReader()); if (dr.Count > 0) timelapse = dr.FirstOrDefault(); Connection.CloseConnection(); return timelapse; } catch (Exception ex) { if (Connection.DbConnection.State == ConnectionState.Closed) Utils.FileLog("TimelapseDao Get(int id) " + ex.Message); else Utils.FileLog(string.Format("TimelapseDao Get(int id) Id={0}<br />{1}", id, ex.Message)); return timelapse; } finally { Connection.CloseConnection(); } }
public static int Insert(Timelapse timelapse) { string query = @"INSERT INTO [dbo].[Timelapses] " + "([UserId],[CameraId],[OauthToken],[Code],[Title],[Status],[Privacy],[FromDT],[ToDT],[DateAlways],[TimeAlways],[ServerIP],[TzId],[TimeZone],[SnapsInterval],[ModifiedDT],[EnableMD],[MDThreshold],[ExcludeDark],[DarkThreshold],[FPS],[IsRecording],[IsDeleted],[CreatedDT],[WatermarkImage],[WatermarkPosition]) " + "VALUES " + "(@UserId,@CameraId,@OauthToken,@Code,@Title,@Status,@Privacy,@FromDT,@ToDT,@DateAlways,@TimeAlways,@ServerIP,@TzId,@TimeZone,@SnapsInterval,@ModifiedDT,@EnableMD,@MDThreshold,@ExcludeDark,@DarkThreshold, @FPS,@IsRecording,@IsDeleted,@CreatedDT,@WatermarkImage,@WatermarkPosition) " + "SELECT CAST(scope_identity() AS int)"; try { var p1 = new SqlParameter("@CameraId", timelapse.CameraId); var p2 = new SqlParameter("@UserId", timelapse.UserId); var p3 = new SqlParameter("@Code", timelapse.Code); var p4 = new SqlParameter("@Title", timelapse.Title); var p5 = new SqlParameter("@Status", timelapse.Status); var p6 = new SqlParameter("@Privacy", timelapse.Privacy); var p7 = new SqlParameter("@FromDT", (timelapse.FromDT == null ? Utils.SQLMinDate : timelapse.FromDT)); var p8 = new SqlParameter("@ToDT", (timelapse.ToDT == null ? Utils.SQLMaxDate : timelapse.ToDT)); var p9 = new SqlParameter("@ServerIP", timelapse.ServerIP); var p10 = new SqlParameter("@EnableMD", timelapse.EnableMD); var p11 = new SqlParameter("@MDThreshold", timelapse.MDThreshold); var p12 = new SqlParameter("@ExcludeDark", timelapse.ExcludeDark); var p13 = new SqlParameter("@DarkThreshold", timelapse.DarkThreshold); var p14 = new SqlParameter("@IsRecording", timelapse.IsRecording); var p15 = new SqlParameter("@IsDeleted", timelapse.IsDeleted); var p16 = new SqlParameter("@ModifiedDT", Utils.ConvertFromUtc(DateTime.UtcNow, timelapse.TimeZone)); var p17 = new SqlParameter("@SnapsInterval", timelapse.SnapsInterval); var p18 = new SqlParameter("@TimeZone", timelapse.TimeZone); var p19 = new SqlParameter("@DateAlways", timelapse.DateAlways); var p20 = new SqlParameter("@TimeAlways", timelapse.TimeAlways); var p21 = new SqlParameter("@CreatedDT", Utils.ConvertFromUtc(DateTime.UtcNow, timelapse.TimeZone)); var p22 = new SqlParameter("@TzId", timelapse.TzId); var p23 = new SqlParameter("@FPS", timelapse.FPS); var p24 = new SqlParameter("@OauthToken", timelapse.OauthToken); var p25 = new SqlParameter("@WatermarkImage", (timelapse.WatermarkImage.Equals("-")? "" : timelapse.WatermarkImage)); var p26 = new SqlParameter("@WatermarkPosition", timelapse.WatermarkPosition); var list = new[] { p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26}; var cmd = new SqlCommand { CommandText = query, CommandType = CommandType.Text }; cmd.Parameters.AddRange(list); Connection.OpenConnection(); cmd.Connection = Connection.DbConnection; int result = (int)cmd.ExecuteScalar(); Connection.CloseConnection(); cmd.Dispose(); return result; } catch (Exception ex) { Utils.FileLog("TimelapseDao Insert(Timelapse timelapse) " + ex.Message); return 0; } finally { Connection.CloseConnection(); } }
protected bool isCreatedHls(Timelapse timelapse, string camera_exid) { FilePath = timelapse.TimelapsePath + Settings.BucketName; string downPath = Path.Combine(FilePath, camera_exid, timelapse.ID.ToString(), "images"); string tsPath = Path.Combine(FilePath, camera_exid, timelapse.ID.ToString(), "ts"); if (Directory.Exists(downPath) && Directory.Exists(tsPath)) { DirectoryInfo imagesDirectory = new DirectoryInfo(downPath); int imagesCount = imagesDirectory.GetFiles("*.jpg").Length; DirectoryInfo ts = new DirectoryInfo(tsPath); int hasTsFiles = ts.GetFiles("*.*").Length; if (hasTsFiles == 0 && imagesCount > 0) { return false; } } else if (Directory.Exists(downPath) && !Directory.Exists(tsPath)) { DirectoryInfo imagesDirectory = new DirectoryInfo(downPath); int imagesCount = imagesDirectory.GetFiles("*.jpg").Length; if (imagesCount > 0) { return false; } } return true; }
public static void TimelapseLog(Timelapse timelapse, string message, Exception x) { TimelapseLog(timelapse, message + Environment.NewLine + x.ToString()); }
public static void TimelapseLog(Timelapse timelapse, Exception x) { TimelapseLog(timelapse, x.ToString()); }
public static void TimelapseLog(Timelapse timelapse, string message) { TimelapseLog(timelapse.ID, message); }
private void RecordTimelapse() { int processId = Utils.TimelapseRunning(timelapse.ID); Utils.TimelapseLog(timelapse, "Recording Timelapse..."); Process p = Process.GetProcessById(processId); if (p.Id > 0 && p.Id != Process.GetCurrentProcess().Id && !p.HasExited && !p.Responding) { Utils.TimelapseLog(timelapse, "Killing previous halted process#" + p.Id); Utils.KillProcess(p.Id, timelapse.ID); } else if (p.Id > 0 && p.Id != Process.GetCurrentProcess().Id && !p.HasExited && p.Responding) { Utils.TimelapseLog(timelapse, "EXIT: Timelapse recorder already running process#" + p.Id); ExitProcess(); } while (true) { Stopwatch watch = Stopwatch.StartNew(); DateTime utcBefore = DateTime.UtcNow; try { //// GET THIS FROM API !!! timelapse = TimelapseDao.Get(timelapse.Code); if (timelapse.ID == 0) { Utils.TimelapseLog(timelapse, "EXIT: Timelapse.ID == 0"); ExitProcess(); } if (timelapse.RecreateHls) { Utils.TimelapseLog(timelapse, "EXIT: Because user request recreate HLS. Timelapse.ID == " + timelapse.ID); ExitProcess(); } if (timelapse.Status == (int)TimelapseStatus.Stopped && !timelapse.IsRecording) { Utils.TimelapseLog(timelapse, "EXIT: Timelapse.Status == Stopped"); ExitProcess(); } if (fileError) { Utils.TimelapseLog(timelapse, "EXIT: Error in creating video file"); ExitProcess(); } Program.WatermarkFile = timelapse.ID + ".png"; string mp4IdFileName = Path.Combine(Program.UpPath, timelapse.ID + ".mp4"); string mp4CodeFileName = Path.Combine(Program.UpPath, timelapse.Code + ".mp4"); string tempMp4FileName = Path.Combine(Program.TempPath, timelapse.Code + ".mp4"); string tempVideoFileName = Path.Combine(Program.TempPath, "temp" + timelapse.Code + ".mp4"); string baseMp4FileName = Path.Combine(Program.TempPath, "base" + timelapse.Code + ".mp4"); BashFile = Path.Combine(Program.UpPath, "build.sh"); DirectoryInfo imagesDirectory = new DirectoryInfo(Program.DownPath); if (Utils.StopTimelapse(timelapse)) { TimelapseDao.UpdateStatus(timelapse.Code, (TimelapseStatus)timelapse.Status, timelapse.StatusTag, timelapse.TimeZone); ExitProcess(); } Utils.TimelapseLog(timelapse, "Timelapser Initialized @ " + Utils.ConvertFromUtc(DateTime.UtcNow, timelapse.TimeZone) + " (" + timelapse.FromDT + "-" + timelapse.ToDT + ")"); int imagesCount = imagesDirectory.GetFiles("*.jpg").Length; index = imagesCount; string imageFile = DownloadSnapshot(); // timelapse recorder is just initializing if (!Program.Initialized) { Utils.TimelapseLog(timelapse, "<<< Initialized: images_count:" + imagesCount + ", Interval:" + timelapse.SnapsInterval + ", Snapshot Count:" + timelapse.SnapsCount); DirectoryInfo ts = new DirectoryInfo(Program.TsPath); int hasTsFiles = ts.GetFiles("*.*").Length; if (hasTsFiles == 0 && imagesCount > 25) { CreateVideoChunks(BashFile); Utils.TimelapseLog(timelapse, "Initial Stream <<< CreateVideoChunks"); } else if (hasTsFiles == 0 && imagesCount > 0 && imagesCount < 25) { string sourceFile = Path.Combine(Program.DownPath, (index - 1) + ".jpg"); for (int i = index; i < 24; i++) { File.Copy(sourceFile, Path.Combine(Program.DownPath, i + ".jpg"), true); } if (imagesCount == 24) { CreateVideoChunks(BashFile); imagesCount = imagesDirectory.GetFiles("*.jpg").Length; index = imagesCount; } else { CreateVideoChunks(BashFile, false); for (int i = index; i < 24; i++) { File.Delete(Path.Combine(Program.DownPath, i + ".jpg")); } } Utils.TimelapseLog(timelapse, "Initial Stream one repeated image<<< CreateVideoChunks"); } else if (CalculateChunckCreateTime(imagesCount, timelapse.SnapsInterval, timelapse.SnapsCount)) { chunkIndex = GetTsFileIndex(Program.TsPath); CreateNewVideoChunk(BashFile, timelapse.SnapsCount); Utils.TimelapseLog(timelapse, "<<< CreateNewVideoChunk"); } if (hasTsFiles > 0) { chunkIndex = GetTsFileIndex(Program.TsPath); timelapse = TimelapseDao.Get(timelapse.Code); Program.Initialized = true; } } if (!string.IsNullOrEmpty(imageFile)) { if (intervals_max.Contains(timelapse.SnapsInterval) && index > 0 && index < 25) { if (Directory.Exists(Program.TsPath)) Directory.Delete(Program.TsPath, true); Directory.CreateDirectory(Program.TsPath); string sourceFile = Path.Combine(Program.DownPath, (index - 1) + ".jpg"); for (int i = index; i < 24; i++) { File.Copy(sourceFile, Path.Combine(Program.DownPath, i + ".jpg"), true); } if (imagesCount == 24) { CreateVideoChunks(BashFile); imagesCount = imagesDirectory.GetFiles("*.jpg").Length; index = imagesCount; } else { CreateVideoChunks(BashFile, false); for (int i = index; i < 24; i++) { File.Delete(Path.Combine(Program.DownPath, i + ".jpg")); } } Utils.TimelapseLog(timelapse, "Add new image<<< CreateVideoChunks"); } else if (CalculateChunckCreateTime(imagesCount, timelapse.SnapsInterval, timelapse.SnapsCount)) { CreateNewVideoChunk(BashFile, timelapse.SnapsCount); Utils.TimelapseLog(timelapse, "<<< CreateNewVideoChunk"); } } else { //// could not get an image from camera so retry after 15 seconds if (timeOutCount >= timeOutLimit) { string log = "Camera not accessible (tried " + timeOutCount + " times) "; Utils.TimelapseLog(timelapse, log); TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, log, timelapse.TimeZone); ExitProcess(); } // wait for x seconds before next retry Utils.TimelapseLog(timelapse, "Retry after " + Settings.RetryInterval + " seconds"); Thread.Sleep(TimeSpan.FromMilliseconds(Settings.RetryInterval * 1000)); } DateTime utcAfter = utcBefore.AddMilliseconds(watch.ElapsedMilliseconds); if (timelapse.SnapsInterval == 1) { if (utcAfter.Hour == utcBefore.Hour && utcAfter.Minute == utcBefore.Minute) { int wait = 60 - utcAfter.Second; Utils.TimelapseLog(timelapse, "Wait for " + wait + " seconds"); Thread.Sleep(TimeSpan.FromMilliseconds(wait * 1000)); } } else { TimeSpan span = utcAfter.AddMinutes(timelapse.SnapsInterval).Subtract(utcAfter); Utils.TimelapseLog(timelapse, "Wait for " + span.TotalMinutes + " minutes"); Thread.Sleep(TimeSpan.FromMilliseconds(span.TotalMinutes * 60 * 1000)); } } catch (Exception x) { Utils.TimelapseLog(timelapse, "ERR: RecordTimelapse(): " + x); TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Failed with error - " + x.Message, timelapse.TimeZone); Console.WriteLine("RecordTimelapse Error: " + x.Message); } } }
private static List<Timelapse> GetListFromDataReader(SqlDataReader dr) { List<Timelapse> timelapses = new List<Timelapse>(); while (dr.Read()) { var timelapse = new Timelapse(); if (!dr.IsDBNull(dr.GetOrdinal("Id"))) timelapse.ID = dr.GetInt32(dr.GetOrdinal("Id")); if (!dr.IsDBNull(dr.GetOrdinal("UserId"))) timelapse.UserId = dr["UserId"].ToString(); if (!dr.IsDBNull(dr.GetOrdinal("CameraId"))) timelapse.CameraId = dr["CameraId"].ToString(); if (!dr.IsDBNull(dr.GetOrdinal("OauthToken"))) timelapse.OauthToken = dr["OauthToken"].ToString(); if (!dr.IsDBNull(dr.GetOrdinal("StatusTag"))) timelapse.StatusTag = dr["StatusTag"].ToString(); if (!dr.IsDBNull(dr.GetOrdinal("Code"))) timelapse.Code = dr["Code"].ToString(); if (!dr.IsDBNull(dr.GetOrdinal("Title"))) timelapse.Title = dr["Title"].ToString(); if (!dr.IsDBNull(dr.GetOrdinal("Status"))) timelapse.Status = dr.GetInt32(dr.GetOrdinal("Status")); if (!dr.IsDBNull(dr.GetOrdinal("Privacy"))) timelapse.Privacy = dr.GetInt32(dr.GetOrdinal("Privacy")); if (!dr.IsDBNull(dr.GetOrdinal("FromDT"))) timelapse.FromDT = dr.GetDateTime(dr.GetOrdinal("FromDT")); if (!dr.IsDBNull(dr.GetOrdinal("ToDT"))) timelapse.ToDT = dr.GetDateTime(dr.GetOrdinal("ToDT")); if (!dr.IsDBNull(dr.GetOrdinal("SnapsInterval"))) timelapse.SnapsInterval = dr.GetInt32(dr.GetOrdinal("SnapsInterval")); if (!dr.IsDBNull(dr.GetOrdinal("SnapsCount"))) timelapse.SnapsCount = dr.GetInt32(dr.GetOrdinal("SnapsCount")); if (!dr.IsDBNull(dr.GetOrdinal("FileSize"))) timelapse.FileSize = dr.GetInt64(dr.GetOrdinal("FileSize")); if (!dr.IsDBNull(dr.GetOrdinal("Duration"))) timelapse.Duration = dr["Duration"].ToString(); if (!dr.IsDBNull(dr.GetOrdinal("Resolution"))) timelapse.Resolution = dr["Resolution"].ToString(); if (!dr.IsDBNull(dr.GetOrdinal("MaxResolution"))) timelapse.MaxResolution = dr.GetBoolean(dr.GetOrdinal("MaxResolution")); if (!dr.IsDBNull(dr.GetOrdinal("ServerIP"))) timelapse.ServerIP = dr["ServerIP"].ToString(); if (!dr.IsDBNull(dr.GetOrdinal("TzId"))) timelapse.TzId = dr["TzId"].ToString(); if (!dr.IsDBNull(dr.GetOrdinal("TimeZone"))) timelapse.TimeZone = dr["TimeZone"].ToString(); if (!dr.IsDBNull(dr.GetOrdinal("EnableMD"))) timelapse.EnableMD = dr.GetBoolean(dr.GetOrdinal("EnableMD")); if (!dr.IsDBNull(dr.GetOrdinal("MDThreshold"))) timelapse.MDThreshold = dr.GetInt32(dr.GetOrdinal("MDThreshold")); if (!dr.IsDBNull(dr.GetOrdinal("ExcludeDark"))) timelapse.ExcludeDark = dr.GetBoolean(dr.GetOrdinal("ExcludeDark")); if (!dr.IsDBNull(dr.GetOrdinal("DarkThreshold"))) timelapse.DarkThreshold = dr.GetInt32(dr.GetOrdinal("DarkThreshold")); if (!dr.IsDBNull(dr.GetOrdinal("DateAlways"))) timelapse.DateAlways = dr.GetBoolean(dr.GetOrdinal("DateAlways")); if (!dr.IsDBNull(dr.GetOrdinal("TimeAlways"))) timelapse.TimeAlways = dr.GetBoolean(dr.GetOrdinal("TimeAlways")); if (!dr.IsDBNull(dr.GetOrdinal("FPS"))) timelapse.FPS = dr.GetInt32(dr.GetOrdinal("FPS")); if (!dr.IsDBNull(dr.GetOrdinal("WatermarkImage"))) timelapse.WatermarkImage = dr["WatermarkImage"].ToString(); if (!dr.IsDBNull(dr.GetOrdinal("WatermarkPosition"))) timelapse.WatermarkPosition = int.Parse(dr["WatermarkPosition"].ToString()); if (!dr.IsDBNull(dr.GetOrdinal("IsRecording"))) timelapse.IsRecording = dr.GetBoolean(dr.GetOrdinal("IsRecording")); if (!dr.IsDBNull(dr.GetOrdinal("IsDeleted"))) timelapse.IsDeleted = dr.GetBoolean(dr.GetOrdinal("IsDeleted")); if (!dr.IsDBNull(dr.GetOrdinal("LastSnapDT"))) timelapse.LastSnapDT = dr.GetDateTime(dr.GetOrdinal("LastSnapDT")); if (!dr.IsDBNull(dr.GetOrdinal("ModifiedDT"))) timelapse.ModifiedDT = dr.GetDateTime(dr.GetOrdinal("ModifiedDT")); if (!dr.IsDBNull(dr.GetOrdinal("CreatedDT"))) timelapse.CreatedDT = dr.GetDateTime(dr.GetOrdinal("CreatedDT")); timelapses.Add(timelapse); } dr.Close(); dr.Dispose(); return timelapses; }
static void Main(string[] args) { //Utils.UpdateTimelapsesOnAzure(); //Utils.CopyTimelapsesToAzure(); AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException; int tId = Convert.ToInt32(args[0]); // testing any timelapse //int tId = 398; Evercam.SANDBOX = Settings.EvercamSandboxMode; Evercam = new Evercam(Settings.EvercamClientID, Settings.EvercamClientSecret, Settings.EvercamClientUri); Timelapse timelapse = new Timelapse(); try { tl = timelapse = TimelapseDao.Get(tId); string cleanCameraId = BLL.Common.Utils.RemoveSymbols(timelapse.CameraId); if (timelapse.ID == 0) { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Timelapse details not found", timelapse.TimeZone); ExitProcess("Timelapse not found. ID = " + tId); } if (!timelapse.IsRecording) { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Stopped, "Recording stopped", timelapse.TimeZone); ExitProcess("Timelapse stopped. ID = " + tId); } if (string.IsNullOrEmpty(cleanCameraId)) { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone); ExitProcess("Invalid Camera ID. Timelapse ID = " + tId + ", Camera ID = " + timelapse.CameraId); } //// User AuthToken is Unauthorized to access certain cameras, e.g. wayra_office //// may be shared cameras ? if (!string.IsNullOrEmpty(timelapse.OauthToken)) Evercam = new Evercam(timelapse.OauthToken); for (int i = 1; i <= TRY_COUNT; i++) { //// tests x times if camera is available instantly otherwise exits try { var data = Evercam.GetLiveImage(timelapse.CameraId); break; } catch(Exception x) { Utils.TimelapseLog(timelapse, "Main Error (try#" + i + "): " + x.ToString()); if (i < TRY_COUNT) Thread.Sleep(RETRY_INTERVAL * 1000); // 7 seconds else { Snapshot snap = Evercam.GetLatestSnapshot(timelapse.CameraId, true); byte[] data = snap.ToBytes(); if (data != null && data.Length > 0) break; else { BLL.Common.Utils.AppLog("Main Error in Timelapse#" + tId + ". Camera recording not found."); TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera not accessible", timelapse.TimeZone); ExitProcess("Camera not accessible"); } } } } Camera = Evercam.GetCamera(timelapse.CameraId); if (Camera == null || string.IsNullOrEmpty(Camera.ID)) { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone); ExitProcess("Camera not found. ID = " + timelapse.CameraId); } if (!Camera.IsOnline) { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera went offline", timelapse.TimeZone); ExitProcess("Camera is offline. ID = " + timelapse.CameraId); } Console.Title = "Timelapse (#" + tId + ") - Camera (#" + cleanCameraId + ")"; Console.WriteLine("Running Timelapse (#" + tId + ") - Camera (#" + cleanCameraId + ")"); UpPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString()); DownPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString(), "images"); TempPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString(), "temp"); if (!Directory.Exists(FfmpegCopyPath)) Directory.CreateDirectory(FfmpegCopyPath); if (!Directory.Exists(FilePath)) Directory.CreateDirectory(FilePath); if (!Directory.Exists(UpPath)) Directory.CreateDirectory(UpPath); if (!Directory.Exists(DownPath)) Directory.CreateDirectory(DownPath); if (!Directory.Exists(TempPath)) Directory.CreateDirectory(TempPath); Recorder recorder = new Recorder(timelapse); recorder.Start(); } catch (Exception x) { if (x.Message.ToLower().Contains("not found")) TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone); else if (x.Message.ToLower().Contains("not exist")) TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone); else TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera not accessible", timelapse.TimeZone); BLL.Common.Utils.AppLog("Main Error in Timelapse#" + tId + ". ERR: " + x.Message); ExitProcess(x.Message); } }
static void Main(string[] args) { //Utils.UpdateTimelapsesOnAzure(); //Utils.CopyTimelapsesToAzure(); AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException; int tId = Convert.ToInt32(args[0]); Evercam.SANDBOX = Settings.EvercamSandboxMode; Evercam = new Evercam(Settings.EvercamClientID, Settings.EvercamClientSecret, Settings.EvercamClientUri); Timelapse timelapse = new Timelapse(); try { tl = timelapse = TimelapseDao.Get(tId); string cleanCameraId = BLL.Common.Utils.RemoveSymbols(timelapse.CameraId); if (timelapse.ID == 0) { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Timelapse details not found", timelapse.TimeZone); ExitProcess("Timelapse not found. ID = " + tId); } if (!timelapse.IsRecording) { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Stopped, "Recording stopped", timelapse.TimeZone); ExitProcess("Timelapse stopped. ID = " + tId); } if (string.IsNullOrEmpty(cleanCameraId)) { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone); ExitProcess("Invalid Camera ID. Timelapse ID = " + tId + ", Camera ID = " + timelapse.CameraId); } //// User AuthToken is Unauthorized to access certain cameras, e.g. wayra_office //// may be shared cameras ? if (!string.IsNullOrEmpty(timelapse.OauthToken)) { string[] cred = timelapse.OauthToken.Split(':'); if (cred.Length >= 2) Evercam = new Evercam(cred[0], cred[1]); else Evercam = new Evercam(timelapse.OauthToken); } for (int i = 1; i <= TRY_COUNT; i++) { //// tests x times if camera is available instantly otherwise exits try { var data = Evercam.GetLiveImage(timelapse.CameraId); break; } catch(Exception x) { Utils.TimelapseLog(timelapse, "Main Error (try#" + i + "): " + x.ToString()); if (i < TRY_COUNT) Thread.Sleep(RETRY_INTERVAL * 1000); // 7 seconds else { byte[] data = Evercam.GetThumbnail(timelapse.CameraId, true); if (data != null && data.Length > 0) break; else { BLL.Common.Utils.AppLog("Main Error in Timelapse#" + tId + ". Camera recording not found."); TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera not accessible", timelapse.TimeZone); ExitProcess("Camera not accessible"); } } } } FilePath = timelapse.TimelapsePath + Settings.BucketName; UpPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString()); DownPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString(), "images"); TsPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString(), "ts"); TempPath = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString(), "temp"); string hlsFileUrl = "http://timelapse.evercam.io/timelapses/" + cleanCameraId + "/" + timelapse.ID.ToString(); if (!Directory.Exists(FilePath)) Directory.CreateDirectory(FilePath); if (!Directory.Exists(UpPath)) Directory.CreateDirectory(UpPath); if (!Directory.Exists(DownPath)) Directory.CreateDirectory(DownPath); if (!Directory.Exists(TsPath)) Directory.CreateDirectory(TsPath); if (!Directory.Exists(TempPath)) Directory.CreateDirectory(TempPath); //if (!File.Exists(Path.Combine(UpPath, "timelapse.m3u8"))) CreateManifestFile(UpPath); CreateManifestFileForDownload(UpPath, hlsFileUrl); CreateBashFile(timelapse.FPS, DownPath, TsPath, chunkSize, timelapse.SnapsInterval); Recorder recorder = new Recorder(timelapse); string bashFile = Path.Combine(Program.UpPath, "build.sh"); if (timelapse.RecreateHls) { string old_ts_path = Path.Combine(FilePath, cleanCameraId, timelapse.ID.ToString(), "ts_old"); Directory.Move(TsPath, old_ts_path); if (!Directory.Exists(TsPath)) Directory.CreateDirectory(TsPath); recorder.CreateVideoChunks(bashFile); TimelapseDao.UpdateReCreateHlsParams(timelapse.Code, false, false); Directory.Delete(old_ts_path, true); Utils.TimelapseLog(timelapse, "Program <<< Recreate HLS stream"); } DirectoryInfo imagesDirectory = new DirectoryInfo(Program.DownPath); int imagesCount = imagesDirectory.GetFiles("*.jpg").Length; DirectoryInfo ts = new DirectoryInfo(TsPath); int hasTsFiles = ts.GetFiles("*.*").Length; if (imagesCount > timelapse.SnapsCount && (imagesCount - timelapse.SnapsCount) > 1000) { ExitProcess("Something went wrong with timelapse: " + timelapse.ID + ", imagesCount: " + imagesCount + ", SnapsCount: " + timelapse.SnapsCount); } if (hasTsFiles == 0 && imagesCount > 24) { recorder.CreateVideoChunks(bashFile); Utils.TimelapseLog(timelapse, "Program <<< CreateVideoChunks"); } Camera = Evercam.GetCamera(timelapse.CameraId); if (Camera == null || string.IsNullOrEmpty(Camera.ID)) { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone); ExitProcess("Camera not found. ID = " + timelapse.CameraId); } if (!Camera.IsOnline) { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera went offline", timelapse.TimeZone); ExitProcess("Camera is offline. ID = " + timelapse.CameraId); } Console.Title = "Timelapse (#" + tId + ") - Camera (#" + cleanCameraId + ")"; Console.WriteLine("Running Timelapse (#" + tId + ") - Camera (#" + cleanCameraId + ")"); recorder.Start(); } catch (Exception x) { if (x.Message.ToLower().Contains("not found")) TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone); else if (x.Message.ToLower().Contains("not exist")) TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details could not be retreived from Evercam", timelapse.TimeZone); else TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera not accessible", timelapse.TimeZone); BLL.Common.Utils.AppLog("Main Error in Timelapse#" + tId + ". ERR: " + x.Message); ExitProcess(x.Message); } }
public static TimelapseModel Convert(Timelapse timelapse, string tempImage) { TimelapseModel model = new TimelapseModel(); model.id = timelapse.ID; model.camera_id = timelapse.CameraId; model.user_id = timelapse.UserId; model.code = timelapse.Code; model.title = timelapse.Title; model.jpg_url = Common.Utility.GetTimelapseResourceUrl(timelapse) + timelapse.Code + ".jpg"; //model.jpg_url = tempImage; model.status_tag = timelapse.StatusTag; model.mp4_url = Common.Utility.GetTimelapseResourceUrl(timelapse) + timelapse.Code + ".mp4"; model.status = timelapse.Status; model.time_zone = timelapse.TimeZone; model.snaps_count = timelapse.SnapsCount; model.file_size = Utils.GetSpace(timelapse.FileSize); model.duration = timelapse.Duration; model.resolution = timelapse.Resolution; model.privacy = timelapse.Privacy; model.from_date = Utils.ConvertFromUtc(timelapse.FromDT, timelapse.TimeZone).ToString(); model.to_date = Utils.ConvertFromUtc(timelapse.ToDT, timelapse.TimeZone).ToString(); model.is_date_always = timelapse.DateAlways; model.is_time_always = timelapse.TimeAlways; model.enable_md = timelapse.EnableMD; model.md_thrushold = timelapse.MDThreshold; model.exclude_dark = timelapse.ExcludeDark; model.darkness_thrushold = timelapse.DarkThreshold; model.is_recording = timelapse.IsRecording; model.interval = timelapse.SnapsInterval; model.last_snap_date = (timelapse.LastSnapDT == Utils.SQLMinDate ? "" : Utils.ConvertFromUtc(timelapse.LastSnapDT, timelapse.TimeZone).ToString("f")); model.modified_date = timelapse.ModifiedDT.ToString("f"); model.created_date = timelapse.CreatedDT.ToString("f"); model.fps = timelapse.FPS; model.watermark_file = timelapse.WatermarkImage; model.watermark_position = (int)timelapse.WatermarkPosition; model.access_token = timelapse.OauthToken; return model; }
public static Timelapse Convert(TimelapseModel model, string userId) { Timelapse timelapse = new Timelapse(); timelapse.ID = model.id; timelapse.UserId = userId; timelapse.CameraId = model.camera_id; timelapse.Code = model.code; timelapse.Title = model.title; timelapse.Status = model.status; timelapse.Privacy = model.privacy; timelapse.DateAlways = model.is_date_always; timelapse.TimeAlways = model.is_time_always; timelapse.FromDT = DateTime.Parse(model.from_date); timelapse.ToDT = DateTime.Parse(model.to_date); timelapse.EnableMD = model.enable_md; timelapse.MDThreshold = model.md_thrushold; timelapse.ExcludeDark = model.exclude_dark; timelapse.DarkThreshold = model.darkness_thrushold; timelapse.IsRecording = model.is_recording; timelapse.SnapsInterval = model.interval; timelapse.TimeZone = model.time_zone; timelapse.CreatedDT = DateTime.Parse(model.created_date); timelapse.FPS = model.fps; timelapse.WatermarkImage = model.watermark_file; timelapse.WatermarkPosition = model.watermark_position; timelapse.OauthToken = model.access_token; return timelapse; }
public static Timelapse Convert(TimelapseInfoModel model, string evercamId, int id, string code, int status) { Timelapse timelapse = new Timelapse(); timelapse.ID = id; if (!string.IsNullOrEmpty(code)) timelapse.Code = code; timelapse.Status = status; timelapse.UserId = evercamId; timelapse.CameraId = model.camera_eid; timelapse.OauthToken = model.access_token; timelapse.Title = model.title; timelapse.LastSnapDT = Utils.SQLMinDate; timelapse.Privacy = model.privacy; timelapse.DateAlways = model.is_date_always; timelapse.TimeAlways = model.is_time_always; DateTime from = new DateTime(Utils.SQLMinDate.Year, Utils.SQLMinDate.Month, Utils.SQLMinDate.Day, 0, 0, 0, 0); DateTime to = new DateTime(Utils.SQLMaxDate.Year, Utils.SQLMaxDate.Month, Utils.SQLMaxDate.Day, 23, 59, 59, 000); DateTime f = from; DateTime t = to; if (!model.is_date_always) { f = DateTime.Parse(model.from_date); t = DateTime.Parse(model.to_date); from = new DateTime(f.Year, f.Month, f.Day, 0, 0, 0, 0); to = new DateTime(t.Year, t.Month, t.Day, 23, 59, 59, 000); } if (!model.is_time_always) { f = DateTime.Parse(model.from_time); t = DateTime.Parse(model.to_time); from = new DateTime(from.Year, from.Month, from.Day, f.Hour, f.Minute, f.Second, f.Millisecond); to = new DateTime(to.Year, to.Month, to.Day, t.Hour, t.Minute, t.Second, t.Millisecond); } timelapse.TzId = model.time_zone; timelapse.TimeZone = Common.Utility.GetTimezone(model.time_zone); if (string.IsNullOrEmpty(timelapse.TimeZone)) timelapse.TimeZone = Common.DEFAULT_TIMEZONE; timelapse.FromDT = Utils.ConvertToUtc(from, timelapse.TimeZone); timelapse.ToDT = Utils.ConvertToUtc(to, timelapse.TimeZone); timelapse.EnableMD = model.enable_md; timelapse.MDThreshold = model.md_thrushold; timelapse.ExcludeDark = model.exclude_dark; timelapse.DarkThreshold = model.darkness_thrushold; timelapse.SnapsInterval = model.interval; timelapse.IsRecording = model.is_recording; timelapse.FPS = model.fps; timelapse.WatermarkImage = model.watermark_file; timelapse.WatermarkPosition = model.watermark_position; return timelapse; }
private void RecordTimelapse() { int processId = Utils.TimelapseRunning(timelapse.ID); Utils.TimelapseLog(timelapse, "Recording Timelapse..."); Process p = Process.GetProcessById(processId); if (p.Id > 0 && p.Id != Process.GetCurrentProcess().Id && !p.HasExited && !p.Responding) { Utils.TimelapseLog(timelapse, "Killing previous halted process#" + p.Id); Utils.KillProcess(p.Id, timelapse.ID); } else if (p.Id > 0 && p.Id != Process.GetCurrentProcess().Id && !p.HasExited && p.Responding) { Utils.TimelapseLog(timelapse, "EXIT: Timelapse recorder already running process#" + p.Id); ExitProcess(); } while (true) { Stopwatch watch = Stopwatch.StartNew(); DateTime utcBefore = DateTime.UtcNow; try { //// GET THIS FROM API !!! timelapse = TimelapseDao.Get(timelapse.Code); if (timelapse.ID == 0) { Utils.TimelapseLog(timelapse, "EXIT: Timelapse.ID == 0"); ExitProcess(); } if (timelapse.Status == (int)TimelapseStatus.Stopped && !timelapse.IsRecording) { Utils.TimelapseLog(timelapse, "EXIT: Timelapse.Status == Stopped"); ExitProcess(); } if (fileError) { Utils.TimelapseLog(timelapse, "EXIT: Error in creating video file"); ExitProcess(); } Program.WatermarkFile = timelapse.ID + ".png"; string mp4IdFileName = Path.Combine(Program.UpPath, timelapse.ID + ".mp4"); string mp4CodeFileName = Path.Combine(Program.UpPath, timelapse.Code + ".mp4"); string tempMp4FileName = Path.Combine(Program.TempPath, timelapse.Code + ".mp4"); string tempVideoFileName = Path.Combine(Program.TempPath, "temp" + timelapse.Code + ".mp4"); string baseMp4FileName = Path.Combine(Program.TempPath, "base" + timelapse.Code + ".mp4"); if (!string.IsNullOrEmpty(timelapse.WatermarkImage)) { Utils.DoDownload(timelapse.WatermarkImage, Path.Combine(Program.TimelapseExePath, Program.WatermarkFile)); if (File.Exists(Path.Combine(Program.TimelapseExePath, Program.WatermarkFile))) File.Copy(Path.Combine(Program.TimelapseExePath, Program.WatermarkFile), Path.Combine(Program.UpPath, Program.WatermarkFileName), true); } //// timelapse recorder is just initializing if (!Program.Initialized) { DirectoryInfo d = new DirectoryInfo(Program.DownPath); int fileCount = d.GetFiles("*.jpg").Length; index = fileCount; if (fileCount > 0 && fileCount != timelapse.SnapsCount) { Utils.TimelapseLog(timelapse, ">>> CreateVideoFromImages(" + fileCount + " != " + timelapse.SnapsCount + ") index=" + index); string lastImage = Path.Combine(Program.DownPath, index + ".jpg"); if (fileCount == (timelapse.SnapsCount-1) && File.Exists(lastImage)) { ConcatenateVideoSingleImage(mp4IdFileName, tempMp4FileName, baseMp4FileName, tempVideoFileName, lastImage); Utils.TimelapseLog(timelapse, "<<< AddedLastImageToVideo"); } else { CreateVideoFromImages(mp4IdFileName, baseMp4FileName); Utils.TimelapseLog(timelapse, "<<< CreatedVideoFromImages"); } File.Copy(mp4IdFileName, mp4CodeFileName, true); } Program.Initialized = true; Utils.TimelapseLog(timelapse, "Timelapser Initialized @ " + Utils.ConvertFromUtc(DateTime.UtcNow, timelapse.TimeZone) + " (" + timelapse.FromDT + "-" + timelapse.ToDT + ")"); } string imageFile = DownloadSnapshot(); if (Utils.StopTimelapse(timelapse)) { TimelapseDao.UpdateStatus(timelapse.Code, (TimelapseStatus)timelapse.Status, timelapse.StatusTag, timelapse.TimeZone); ExitProcess(); } if (!string.IsNullOrEmpty(imageFile)) { //// generates video source file and updates timelapse status to Processing if (!File.Exists(mp4IdFileName)) GenerateVideoSingleImage(mp4IdFileName, baseMp4FileName, imageFile); else ConcatenateVideoSingleImage(mp4IdFileName, tempMp4FileName, baseMp4FileName, tempVideoFileName, imageFile); File.Copy(mp4IdFileName, mp4CodeFileName, true); } else { //// could not get an image from camera so retry after 15 seconds if (timeOutCount >= timeOutLimit) { string log = "Camera not accessible (tried " + timeOutCount + " times) "; Utils.TimelapseLog(timelapse, log); TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, log, timelapse.TimeZone); ExitProcess(); } // wait for x seconds before next retry Utils.TimelapseLog(timelapse, "Retry after " + Settings.RetryInterval + " seconds"); Thread.Sleep(TimeSpan.FromMilliseconds(Settings.RetryInterval * 1000)); } DateTime utcAfter = utcBefore.AddMilliseconds(watch.ElapsedMilliseconds); if (timelapse.SnapsInterval == 1) { if (utcAfter.Hour == utcBefore.Hour && utcAfter.Minute == utcBefore.Minute) { int wait = 60 - utcAfter.Second; Utils.TimelapseLog(timelapse, "Wait for " + wait + " seconds"); Thread.Sleep(TimeSpan.FromMilliseconds(wait * 1000)); } } else { TimeSpan span = utcAfter.AddMinutes(timelapse.SnapsInterval).Subtract(utcAfter); Utils.TimelapseLog(timelapse, "Wait for " + span.TotalMinutes + " minutes"); Thread.Sleep(TimeSpan.FromMilliseconds(span.TotalMinutes * 60 * 1000)); } } catch (Exception x) { Utils.TimelapseLog(timelapse, "ERR: RecordTimelapse(): " + x); TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Failed with error - " + x.Message, timelapse.TimeZone); Console.WriteLine("RecordTimelapse Error: " + x.Message); } } }
public Recorder(Timelapse timelapse) { this.timelapse = timelapse; }
public static bool Update(Timelapse timelapse) { string query = @"UPDATE [dbo].[Timelapses] " + "SET [OauthToken]=@OauthToken,[Title]=@Title, [Privacy]=@Privacy, [SnapsInterval]=@SnapsInterval, [FromDT]=@FromDT, [ToDT]=@ToDT,[DateAlways]=@DateAlways,[TimeAlways]=@TimeAlways,[TzId]=@TzId,[Timezone]=@Timezone, [EnableMD]=@EnableMD, [MDThreshold]=@MDThreshold, [ExcludeDark]=@ExcludeDark, [DarkThreshold]=@DarkThreshold, [IsRecording]=@IsRecording, [FPS]=@FPS, [WatermarkImage]=@WatermarkImage, [WatermarkPosition]=@WatermarkPosition " + "WHERE (Code = '" + timelapse.Code + "')"; try { var p3 = new SqlParameter("@OauthToken", timelapse.OauthToken); var p4 = new SqlParameter("@Title", timelapse.Title); var p6 = new SqlParameter("@Privacy", timelapse.Privacy); var p7 = new SqlParameter("@FromDT", (timelapse.FromDT == null) ? Utils.SQLMinDate : timelapse.FromDT); var p8 = new SqlParameter("@ToDT", (timelapse.ToDT == null) ? Utils.SQLMinDate : timelapse.ToDT); var p9 = new SqlParameter("@SnapsInterval", timelapse.SnapsInterval); var p10 = new SqlParameter("@EnableMD", timelapse.EnableMD); var p11 = new SqlParameter("@MDThreshold", timelapse.MDThreshold); var p12 = new SqlParameter("@ExcludeDark", timelapse.ExcludeDark); var p13 = new SqlParameter("@DarkThreshold", timelapse.DarkThreshold); var p14 = new SqlParameter("@IsRecording", timelapse.IsRecording); var p15 = new SqlParameter("@DateAlways", timelapse.DateAlways); var p16 = new SqlParameter("@TimeAlways", timelapse.TimeAlways); var p17 = new SqlParameter("@Timezone", timelapse.TimeZone); var p18 = new SqlParameter("@TzId", timelapse.TzId); var p19 = new SqlParameter("@FPS", timelapse.FPS); var p20 = new SqlParameter("@WatermarkImage", (timelapse.WatermarkImage.Equals("-") ? "" : timelapse.WatermarkImage)); var p21 = new SqlParameter("@WatermarkPosition", timelapse.WatermarkPosition); var list = new[] { p3, p4, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21 }; var cmd = new SqlCommand { CommandText = query, CommandType = CommandType.Text }; cmd.Parameters.AddRange(list); Connection.OpenConnection(); cmd.Connection = Connection.DbConnection; bool result = (cmd.ExecuteNonQuery() > 0); Connection.CloseConnection(); cmd.Dispose(); return result; } catch (Exception ex) { Utils.FileLog("TimelapseDao Update(Timelapse timelapse) " + ex.Message); return false; } finally { Connection.CloseConnection(); } }
/// <summary> /// Checks if given timelapse needs to be started /// </summary> /// <param name="timelapse"></param> /// <returns></returns> public static bool StartTimelapse(Timelapse timelapse) { if (timelapse.Status == (int)TimelapseStatus.Failed) { timelapse.StatusTag = "Camera not accessible"; FileLog("Utils.StartTimelapse#" + timelapse.ID + " - Start Failed"); return true; } if (timelapse.Status == (int)TimelapseStatus.Stopped && timelapse.IsRecording) { timelapse.Status = (int)TimelapseStatus.Processing; timelapse.StatusTag = "Now recording..."; FileLog("Utils.StartTimelapse#" + timelapse.ID + " - Start Stopped"); return true; } // otherwise if new, processing, scheduled or expired if (timelapse.DateAlways && timelapse.TimeAlways) { timelapse.Status = (int)TimelapseStatus.Processing; timelapse.StatusTag = "Now recording..."; FileLog("Utils.StartTimelapse#" + timelapse.ID + " - Start Recording Always"); return true; } else if (timelapse.DateAlways && !timelapse.TimeAlways) { if (timelapse.FromDT.Hour >= timelapse.ToDT.Hour) { DateTime nextDay = DateTime.UtcNow.AddDays(1); if (DateTime.UtcNow >= new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, timelapse.FromDT.Hour, timelapse.FromDT.Minute, 0) && DateTime.UtcNow < new DateTime(nextDay.Year, nextDay.Month, nextDay.Day, timelapse.ToDT.Hour, timelapse.ToDT.Minute, 59)) { timelapse.Status = (int)TimelapseStatus.Scheduled; timelapse.StatusTag = "Recording on schedule..."; FileLog("Utils.StartTimelapse#" + timelapse.ID + " - Start Recording Everyday Next"); return true; } } else if (DateTime.UtcNow >= new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, timelapse.FromDT.Hour, timelapse.FromDT.Minute, 0) && DateTime.UtcNow < new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, timelapse.ToDT.Hour, timelapse.ToDT.Minute, 59)) { timelapse.Status = (int)TimelapseStatus.Scheduled; timelapse.StatusTag = "Recording on schedule..."; FileLog("Utils.StartTimelapse#" + timelapse.ID + " - Start Recording Everyday"); return true; } } else if (!timelapse.DateAlways && timelapse.TimeAlways) { if (DateTime.UtcNow >= new DateTime(timelapse.FromDT.Year, timelapse.FromDT.Month, timelapse.FromDT.Day, 0, 0, 0) && DateTime.UtcNow < new DateTime(timelapse.ToDT.Year, timelapse.ToDT.Month, timelapse.ToDT.Day, 23, 59, 59)) { timelapse.Status = (int)TimelapseStatus.Scheduled; timelapse.StatusTag = "Recording on schedule..."; FileLog("Utils.StartTimelapse#" + timelapse.ID + " - Start Recording Anytime"); return true; } } else if (!timelapse.DateAlways && !timelapse.TimeAlways) { if (DateTime.UtcNow >= new DateTime(timelapse.FromDT.Year, timelapse.FromDT.Month, timelapse.FromDT.Day, timelapse.FromDT.Hour, timelapse.FromDT.Minute, 0) && DateTime.UtcNow < new DateTime(timelapse.ToDT.Year, timelapse.ToDT.Month, timelapse.ToDT.Day, timelapse.ToDT.Hour, timelapse.ToDT.Minute, 59)) { timelapse.Status = (int)TimelapseStatus.Scheduled; timelapse.StatusTag = "Recording on schedule..."; FileLog("Utils.StartTimelapse#" + timelapse.ID + " - Start Recording Range"); return true; } } FileLog("Utils.StartTimelapse#" + timelapse.ID + " - NoStart Recording"); return false; }
/// <summary> /// Checks if given timelapse needs to be stopped /// </summary> /// <param name="timelapse"></param> /// <returns></returns> public static bool StopTimelapse(Timelapse timelapse) { if (timelapse.Status == (int)TimelapseStatus.NotFound) { timelapse.StatusTag = "Camera details not found"; FileLog("Utils.StopTimelapse#" + timelapse.ID + " - Stop Recording Not Found"); return true; } //if (timelapse.Status == (int)TimelapseStatus.Failed) //{ // timelapse.StatusTag = "Camera not accessible"; // FileLog("Utils.StopTimelapse#" + timelapse.ID + " - Stop Recording Failed"); // return true; //} if (timelapse.Status == (int)TimelapseStatus.Stopped) { timelapse.StatusTag = "Recording stopped"; FileLog("Utils.StopTimelapse#" + timelapse.ID + " - Stop Recording Stopped"); return true; } //if (timelapse.Status == (int)TimelapseStatus.Expired) //{ // timelapse.StatusTag = "Out of schedule"; // FileLog("Utils.StopTimelapse#" + timelapse.ID + " - Stop Recording Expired"); // return true; //} // otherwise if new, processing or scheduled if (timelapse.DateAlways && !timelapse.TimeAlways) { if (timelapse.FromDT.Hour >= timelapse.ToDT.Hour) { DateTime nextDay = DateTime.UtcNow.AddDays(1); if (DateTime.UtcNow >= new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, timelapse.ToDT.Hour, timelapse.ToDT.Minute, 59) && DateTime.UtcNow < new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, timelapse.FromDT.Hour, timelapse.FromDT.Minute, 00)) { timelapse.Status = (int)TimelapseStatus.Scheduled; timelapse.StatusTag = "Recording on schedule"; FileLog("Utils.StopTimelapse#" + timelapse.ID + " - NoStop Recording Everyday Next"); return false; } } else if (DateTime.UtcNow < new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, timelapse.FromDT.Hour, timelapse.FromDT.Minute, 0) || DateTime.UtcNow > new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, timelapse.ToDT.Hour, timelapse.ToDT.Minute, 59)) { timelapse.Status = (int)TimelapseStatus.Scheduled; timelapse.StatusTag = "Recording on schedule"; FileLog("Utils.StopTimelapse#" + timelapse.ID + " - NoStop Recording Everyday"); return false; } } else if (!timelapse.DateAlways && timelapse.TimeAlways) { if (DateTime.UtcNow < new DateTime(timelapse.FromDT.Year, timelapse.FromDT.Month, timelapse.FromDT.Day, 0, 0, 0) || DateTime.UtcNow >= new DateTime(timelapse.ToDT.Year, timelapse.ToDT.Month, timelapse.ToDT.Day, 23, 59, 59)) { timelapse.Status = (int)TimelapseStatus.Expired; timelapse.StatusTag = "Out of schedule"; FileLog("Utils.StopTimelapse#" + timelapse.ID + " - Stop Recording Anytime - Expired"); return true; } } else if (!timelapse.DateAlways && !timelapse.TimeAlways) { if (DateTime.UtcNow.Date >= timelapse.FromDT.Date && DateTime.UtcNow.Date <= timelapse.ToDT.Date) { timelapse.Status = (int)TimelapseStatus.Scheduled; timelapse.StatusTag = "Recording on schedule"; FileLog("Utils.StopTimelapse#" + timelapse.ID + " - NoStop Recording Range"); return false; } else { timelapse.Status = (int)TimelapseStatus.Expired; timelapse.StatusTag = "Out of schedule"; FileLog("Utils.StopTimelapse#" + timelapse.ID + " - Stop Recording Range - Expired"); return true; } } FileLog("Utils.StopTimelapse#" + timelapse.ID + " - NoStop Recording"); return false; }
private void StartTimelapser(Timelapse timelapse) { try { // tests if camera details are available from Evercam before starting its recorder Evercam.SANDBOX = Settings.EvercamSandboxMode; Evercam evercam = new Evercam(Settings.EvercamClientID, Settings.EvercamClientSecret, Settings.EvercamClientUri); if (!string.IsNullOrEmpty(timelapse.OauthToken)) evercam = new Evercam(timelapse.OauthToken); Camera camera = evercam.GetCamera(timelapse.CameraId); // if camera found then start its process if (camera.IsOnline) { ProcessStartInfo process = new ProcessStartInfo(TimelapserExePath, timelapse.ID.ToString()); process.UseShellExecute = true; process.WindowStyle = ProcessWindowStyle.Hidden; //ProcessWindowStyle.Normal; Process currentProcess = Process.Start(process); //currentProcess.PriorityClass = ProcessPriorityClass.Idle; //currentProcess.Refresh(); TimelapseProcessInfo tpi = new TimelapseProcessInfo(); tpi.ProcessId = currentProcess.Id; tpi.IsResponding = true; tpi.NextRun = Utils.SQLMinDate; tpi.Interval = timelapse.SnapsInterval; if (_timelapseInfos.ContainsKey(timelapse.ID)) _timelapseInfos[timelapse.ID] = tpi; else _timelapseInfos.Add(timelapse.ID, tpi); } else { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera not accessible", timelapse.TimeZone); Utils.FileLog("Executor.StartTimelapser(" + timelapse.ID + ") Camera (" + camera.ID + ") is Offline at Evercam (" + timelapse.Title + ")"); } } catch (Exception x) { if (x.Message.ToLower().Contains("not found")) { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details Could not be retrieved from Evercam", timelapse.TimeZone); Utils.FileLog("Executor.StartTimelapser(" + timelapse.ID + ") Error: Could not get camera (" + timelapse.CameraId + ") details from Evercam (" + timelapse.Title + ")"); } else if (x.Message.ToLower().Contains("not exist")) { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.NotFound, "Camera details Could not be retrieved from Evercam", timelapse.TimeZone); Utils.FileLog("Executor.StartTimelapser(" + timelapse.ID + ") Error: Camera (" + timelapse.CameraId + ") does not exist at Evercam (" + timelapse.Title + ")"); } else { TimelapseDao.UpdateStatus(timelapse.Code, TimelapseStatus.Failed, "Camera not accessible", timelapse.TimeZone); Utils.FileLog("Executor.StartTimelapser(" + timelapse.ID + ") (" + timelapse.Title + ") Error: " + x.Message); } } }
public static string GetTimelapseResourceUrl(Timelapse timelapse) { return Common.TRANSFER_PROTOCOL + timelapse.ServerIP + "/" + Settings.BucketName + "/" + Utils.RemoveSymbols(timelapse.CameraId) + "/" + timelapse.ID + "/"; }