public void AddCapture(IImage image, CaptureSource source, GateState state = GateState.Open, DateTime?timestamp = null) { if (!IsEnabled) { return; } var dateTime = timestamp ?? DateTime.UtcNow; DateTime lastTimestamp; if (_lastTimestamps.TryGetValue(source, out lastTimestamp) && (dateTime - lastTimestamp).TotalMilliseconds < minCaptureInterval) { return; } var capture = new CaptureEntry() { Timestamp = dateTime, GateState = state, Source = source, FilePath = SaveImage(image, source.ToString()), }; var command = _db.CreateCommand(); command.CommandText = string.Format( "INSERT INTO CaptureEntries (Timestamp, GateState, Source, FilePath) VALUES ('{0}Z', {1}, {2}, '{3}')", capture.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fffffff"), (int)capture.GateState, (int)capture.Source, capture.FilePath); try { lock (_dbLock) { command.ExecuteNonQuery(); } _lastTimestamps[source] = dateTime; } catch (Exception e) { TryDeleteImage(capture.FilePath); throw new CaptureStorageException("Failed to add a capture to DB", e); } finally { command.Dispose(); } }
public CaptureEntry[] GetCaptures(DateTime time, int msMargin) { var from = time.ToUniversalTime(); var to = from.AddMilliseconds(msMargin); List <CaptureEntry> captures = new List <CaptureEntry>(); var command = _db.CreateCommand(); command.CommandText = string.Format( "SELECT Id, Timestamp, GateState, Source, FilePath FROM CaptureEntries WHERE Timestamp >= '{0}Z' AND Timestamp < '{1}Z'", from.ToString("yyyy-MM-dd HH:mm:ss.fffffff"), to.ToString("yyyy-MM-dd HH:mm:ss.fffffff")); try { lock (_dbLock) { using (var reader = command.ExecuteReader()) { while (reader.Read()) { var capture = new CaptureEntry() { Id = reader.GetInt64(0), Timestamp = reader.GetDateTime(1), GateState = (GateState)reader.GetInt32(2), Source = (CaptureSource)reader.GetInt32(3), FilePath = reader.GetString(4) }; captures.Add(capture); } } } } catch (Exception e) { throw new CaptureStorageException("Failed to retrive captures from DB", e); } finally { command.Dispose(); } return(captures.GroupBy(x => x.Source, (source, entries) => entries.FirstOrDefault()).ToArray()); }