-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathSensor.cs
More file actions
203 lines (176 loc) · 7.02 KB
/
Sensor.cs
File metadata and controls
203 lines (176 loc) · 7.02 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Cassandra; // DataStax Cassandra C# driver
using Microsoft.Extensions.Logging;
using CarePet.Model;
using System.CommandLine;
using System.CommandLine.Invocation;
namespace CarePet
{
public class Sensor
{
private static readonly ILogger<Sensor> LOG;
private readonly SensorConfig _config;
private readonly Model.Owner _owner;
private readonly Model.Pet _pet;
private readonly Model.Sensor[] _sensors;
static Sensor()
{
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole();
});
LOG = loggerFactory.CreateLogger<Sensor>();
}
public Sensor(SensorConfig config)
{
_config = config;
_owner = Owner.Random();
_pet = Pet.Random(_owner.OwnerId);
_sensors = new CarePet.Model.Sensor[Enum.GetValues(typeof(SensorType)).Length];
var sensorTypes = Enum.GetValues(typeof(SensorType)).Cast<SensorType>().ToArray();
for (int i = 0; i < _sensors.Length; i++)
{
_sensors[i] = new CarePet.Model.Sensor(_pet.PetId, Guid.NewGuid(), SensorTypeExtensions.GetTypeCode(sensorTypes[i]));
}
}
public static void Main(string[] args)
{
var config = SensorConfig.Parse(args);
var client = new Sensor(config);
client.Save();
client.Run();
}
/// <summary>
/// Initiates a connection with the configured keyspace.
/// </summary>
public ISession Keyspace()
{
var session = _config.Builder(Config.Keyspace).Build().Connect();
session.ChangeKeyspace(Config.Keyspace);
return session;
}
/// <summary>
/// Save owner, pet, and sensors to the database.
/// </summary>
private void Save()
{
using (var session = Keyspace())
{
var mapper = new Mapper(session);
LOG.LogInformation($"owner = {_owner}");
LOG.LogInformation($"pet = {_pet}");
mapper.Owner().Create(_owner);
mapper.Pet().Create(_pet);
foreach (var s in _sensors)
{
LOG.LogInformation($"sensor = {s}");
mapper.Sensor().Create(s);
}
}
}
/// <summary>
/// Generate random sensor data and push it to the database.
/// </summary>
private void Run()
{
using (var session = Keyspace())
{
var prepared = session.Prepare("INSERT INTO measurement (sensor_id, ts, value) VALUES (?, ?, ?)");
var ms = new List<Measure>();
var prev = DateTimeOffset.UtcNow;
while (true)
{
while ((DateTimeOffset.UtcNow - prev) < _config.BufferInterval)
{
if (!Sleep(_config.Measurement))
return;
foreach (var s in _sensors)
{
var m = ReadSensorData(s);
ms.Add(m);
LOG.LogInformation(m.ToString());
}
}
var elapsed = DateTimeOffset.UtcNow - prev;
var intervals = elapsed.Ticks / _config.BufferInterval.Ticks;
prev = prev.AddTicks(intervals * _config.BufferInterval.Ticks);
LOG.LogInformation("pushing data");
var batch = new BatchStatement();
foreach (var m in ms)
{
batch.Add(prepared.Bind(m.SensorId, m.Ts.UtcDateTime, m.Value));
}
session.Execute(batch);
ms.Clear();
}
}
}
private bool Sleep(TimeSpan interval)
{
try
{
Thread.Sleep(interval);
return true;
}
catch (ThreadInterruptedException)
{
return false;
}
}
private Measure ReadSensorData(CarePet.Model.Sensor s)
{
return new Measure(s.SensorId, DateTimeOffset.UtcNow, s.RandomData());
}
public class SensorConfig : Config
{
public TimeSpan BufferInterval { get; set; } = TimeSpan.FromHours(1);
public TimeSpan Measurement { get; set; } = TimeSpan.FromMinutes(1);
public static SensorConfig Parse(string[] args)
{
var config = new SensorConfig();
// Base options from Config
var hostsOption = new Option<string[]>("--hosts", "Database contact points");
var dcOption = new Option<string>(new[] { "-dc", "--datacenter" }, "Local datacenter name");
var usernameOption = new Option<string>(new[] { "-u", "--username" }, "Authentication username");
var passwordOption = new Option<string>(new[] { "-p", "--password" }, "Authentication password");
var helpOption = new Option<bool>(new[] { "-h", "--help" }, "Display help message");
var bufferInterval = new Option<TimeSpan>(
"--buffer-interval",
"Buffer interval to accumulate measures");
var measure = new Option<TimeSpan>(
"--measure",
"Sensors measurement interval");
var rootCommand = new RootCommand
{
hostsOption,
dcOption,
usernameOption,
passwordOption,
helpOption,
bufferInterval,
measure
};
rootCommand.SetHandler((InvocationContext context) =>
{
config.Hosts = context.ParseResult.GetValueForOption(hostsOption);
config.Datacenter = context.ParseResult.GetValueForOption(dcOption);
config.Username = context.ParseResult.GetValueForOption(usernameOption);
config.Password = context.ParseResult.GetValueForOption(passwordOption);
config.Help = context.ParseResult.GetValueForOption(helpOption);
config.BufferInterval = context.ParseResult.GetValueForOption(bufferInterval);
config.Measurement = context.ParseResult.GetValueForOption(measure);
});
rootCommand.InvokeAsync(args);
if (config.Help == true)
{
rootCommand.InvokeAsync("-h");
Environment.Exit(1);
}
return config;
}
}
}
}