public HubitatClient(HubitatOptions options, ILogger logger) { _options = options; _logger = logger; var socketOptions = new PureWebSocketOptions() { DebugMode = true, SendDelay = 100, IgnoreCertErrors = true, MyReconnectStrategy = new ReconnectStrategy(options.MinReconnectInterval, options.MaxReconnectInterval, options.MaxReconnectAttempts) }; _webSocket = new PureWebSocket(_options.WebSocketURL, socketOptions); _webSocket.OnOpened += (sender) => SocketOpen(); _webSocket.OnStateChanged += (sender, newState, previousState) => SocketStateChanged(newState, previousState); _webSocket.OnMessage += (sender, message) => MessageReceived(message); _webSocket.OnClosed += (sender, reason) => SocketClosed(reason); _webSocket.OnSendFailed += (sender, data, ex) => SocketSendFailed(data, ex); _webSocket.OnError += (sender, e) => SocketError(e); _collector = Metrics.Collector = new CollectorConfiguration() .Batch.AtInterval(TimeSpan.FromSeconds(options.BatchInterval)) .WriteTo.InfluxDB(options.InfluxDbURL, options.InfluxDbDatabase, options.InfluxDbUsername, options.InfluxDbPassword) .CreateCollector(); CollectorLog.RegisterErrorHandler((string message, Exception ex) => { _logger.Error(ex, "Failed to write metrics to InfluxDB: {Message}", message); }); }
static async Task Main(string[] args) { IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile(APPLICATION_SETTINGS_FILE_NAME, optional: false, reloadOnChange: true) .AddUserSecrets(typeof(Program).GetTypeInfo().Assembly) .Build(); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); Log.Information("Starting Hubitat Influx Logger"); var hubitatOptions = new HubitatOptions(); configuration.Bind("Hubitat", hubitatOptions); Log.Information("Configured to receive data from {WebSocketURL}", hubitatOptions.WebSocketURL); Log.Information("Configured to write data to {InfluxDbDatabase} at {InfluxDbURL}", hubitatOptions.InfluxDbDatabase, hubitatOptions.InfluxDbURL); _hubitat = new HubitatClient(hubitatOptions, Log.ForContext <HubitatClient>()); using (var shutdownCts = new CancellationTokenSource()) { try { var myTask = Task.Factory.StartNew(() => Worker(shutdownCts.Token), shutdownCts.Token); Console.CancelKeyPress += (sender, eventArgs) => { Shutdown(shutdownCts); eventArgs.Cancel = true; }; AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => Shutdown(shutdownCts); await _hubitat.Start(); Log.Information("Started Hubitat Client"); Console.WriteLine("Application is running. Press Ctrl+C to shut down."); while (!shutdownCts.IsCancellationRequested) { await Task.Delay(TimeSpan.FromSeconds(1)); } Log.Information("Application is shutting down..."); await _hubitat.Stop(); } catch (Exception ex) { Log.Logger.Error(ex, "Error whilst shutting down"); } } }