notes from a passionate developer





This is a personal blog. The opinions expressed here represent my own and not those of my employer, nor current or previous. All content is published "as is", without warranty of any kind and I don't take any responsibility and can't be liable for any claims, damages or other liabilities that might be caused by the content.

Sampling messages from NATS using my C# client for NATS

I'm currently in the process of building a solution for controlling parts of my home, based on my current mood. The first source of sensor data is my own heart rate. I'm using it as input for controlling lights. Like changing colors etc. For dispatching the received heart rate to a light controller as well as a health indexer, I'm using NATS. The heart rate sensor gives me several readings each second and for the indexer I'm writing it down to a time series optimized database, InfluxDB. The data in turn is visualized in Grafana. The lamps are controlled by a separate application/service that also listens to the heart rates being published over NATS. The client I've built for NATS is based around IObservable<T>, hence it is RX friendly and we can therefore make use of Observable.Sample. This becomes really useful when controlling the lamps, as I don't want to react on each individual reading for setting new colors etc. I can instead make use of sampling and be picking one value over the period of lets say five seconds.

For simplicity of getting RX setup, install the convenience package that brings that in:

install-package MyNatsClient.RX

Now just setup a subscription to a subject, in my case: "heartratereceived"; and start sampling messages:

var samplingFreq = TimeSpan.FromSeconds(5);

var cnInfo = new ConnectionInfo("LightsController", "");

var client = new NatsClient(cnInfo);
  msgOps => msgOps
    .Select(msgOp => HearRateDataReceived.Parse(msgOp.GetPayloadAsString()))
    .Where(ev => _lastKnownBpm != ev.BeatPerMinute)
    .Subscribe(ev => AdjustColors(ev)));

Done! Happy sampling



View Comments