-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTelematicsDataRepository.cs
89 lines (79 loc) · 2.26 KB
/
TelematicsDataRepository.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using TeltonikaDataServer.Services;
using TeltonikaDataServer.Models;
using TeltonikaDataServer.Config;
using Dapper;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
namespace TeltonikaDataServer;
public class TelematicsDataRepository
{
private readonly Database _db;
private readonly MemoryCache _cache;
public TelematicsDataRepository(Database db, IOptions<DatabaseOptions> options)
{
_db = db;
_cache = new MemoryCache(new MemoryCacheOptions { SizeLimit = options.Value.DbCacheSize });
}
public async Task StoreGpsPosition(GpsPositionIn gpsPositionIn)
{
const string query = @"
INSERT INTO telematics.gps_position (
gps_latitude,
gps_longitude,
gps_altitude,
gps_heading,
gps_speed,
gps_timestamp_utc,
gps_dev_id
) VALUES (
@Latitude,
@Longitude,
@Altitude,
@Heading,
@Speed,
@TimeStampUtc,
@DevId
)";
using (var conn = _db.GetConnection())
{
await conn.ExecuteAsync(query, gpsPositionIn);
}
}
public async Task StoreExternalVoltage(ExternalVoltageIn externalVoltageIn)
{
const string query = @"
INSERT INTO telematics.external_voltage (
exv_value,
exv_timestamp_utc,
exv_dev_id
) VALUES (
@Value,
@TimestampUtc,
@DevId
)";
using (var conn = _db.GetConnection())
{
await conn.ExecuteAsync(query, externalVoltageIn);
}
}
public async Task<int?> GetDeviceId(string imei)
{
const string query = @"
SELECT dev_id
FROM telematics.device
WHERE dev_imei = @imei
LIMIT 1";
using (var conn = _db.GetConnection())
{
return await conn.QuerySingleOrDefaultAsync<int?>(query, new { imei });
}
}
public async Task<int?> GetDeviceIdFromCache(string imei)
{
string key = $"devId_{imei}";
return await _cache.GetOrCreateAsync<int?>(key, cacheEntry => {
cacheEntry.Size = 1;
return GetDeviceId(imei);
});
}
}