public static async Task <ThingSpeakData> ReadThingspeak() { var client = new ThingSpeakClient(sslRequired: b_requiredSSL); ThingSpeakData feeds = await client.ReadAllFeedsAsync(s_readAPIKey, i_channelID); return(feeds); }
public override async Task StartAsync() { if (string.IsNullOrWhiteSpace(ApiKey)) { await Log.ReportWarningFormatAsync(CancellationToken, "Could not start {0}, missing API key ", Name); return; } ThingSpeakClient = new ThingSpeakClient(ApiKey); NotifyEntityChangeContext.ChangeNotifications <DeviceValue> .OnEntityUpdated += ChangeNotificationsOnOnEntityUpdated; await Log.ReportInfoFormatAsync(CancellationToken, "{0} started", Name); }
void ReadAndSendMeasurements(IFileSystem fileSystem, IConfiguration config) { try { logger_.Info("Starting another measurement"); var conn_sensors_enumerable = new ConnectedDS18B20Enumerable(fileSystem); List <SensorDS18B20> connected_sensors = conn_sensors_enumerable.ToList(); var measurements = new List <Measurement>(); foreach (var sensor in connected_sensors) { List <Measurement> sensor_measurements = sensor.ReadMeasurements(); measurements.AddRange(sensor_measurements); foreach (var measurement in sensor_measurements) { logger_.Info(String.Format("Retrieved measurement from sensor ID {0}: temperature {1} °C", sensor.LinuxFolderName, measurement.Value)); } } logger_.Info("Measurements are ready to be sent"); try { ThingSpeakFeed feed = ConverterMeasurement2ThingSpeakFeed.Convert(measurements, config); var thingspeak_conn = new ThingSpeakClient(sslRequired: true); thingspeak_conn.UpdateFeedAsync(config.APIKey, feed).Wait(); logger_.Info("Measurement is finished"); } catch (System.Net.WebException ex) { logger_.Error("Failed to send measurements to server: " + ex.ToString()); } } catch (OneWireModuleNotLoadedException e) { logger_.Error("1-Wire module is not loaded. Unfortunately, author of this app is lazy and did not implement feature to load required modules."); throw; } catch (Exception e) { logger_.Error("Reading measurement failed, caught exception: " + e.ToString()); //throw; //TODO really we should let app die since we may have memory or stack corruption or other horrible things going // But since it's complicated to restart the app without systemd, that line is commented for now. // It will be uncommented when systemd service is implememted } }
static void Main(string[] args) { var thingSpeakConnection = new ThingSpeakClient(sslRequired: true); Int32 channelId = 108891; List <DateTime> last_30days = GenerateLast30DaysList(); // Unfortunately, ThingSpeak limits amount of data in one request to 8000, so we can't get all data in one huge request, // so we have to get data for each day in separate request (however, they can be parallelized) //TODO: parallelize calculation for different days for (var dt = last_30days.First(); dt < last_30days.Last(); dt = dt.AddDays(1)) { // Step 1: retrieve data // TODO include other fields when data are available for them ThingSpeakData allDataForDay = thingSpeakConnection.ReadFieldsAsync( String.Empty, channelId, fieldId: 1, start_date: dt, end_date: dt.AddDays(1)).Result; var dataForDay = allDataForDay.Feeds; Console.WriteLine("Retrieved {0} feeds for day {1}.", dataForDay.Count(), dt.ToString()); Double workingTimeInPercents = 0.0; if (dataForDay.Count() >= 5) { // We have enough data to calculate interval // Step 2: find average interval between measurements TimeSpan interval = GetManualIntervalForDay(dt); Console.WriteLine("Found interval for day {0}, it is {1} minutes", dt.ToString(), interval.TotalMinutes); Double intervalInSeconds = interval.TotalSeconds; workingTimeInPercents = (dataForDay.Count() * intervalInSeconds / TimeSpan.FromDays(1).TotalSeconds) * 100.0; } Int32 roundedWorkingTimeInPercents = (Int32)Math.Round(workingTimeInPercents); Console.WriteLine("Working time percentage for day {0} is {1} %", dt.ToString(), roundedWorkingTimeInPercents); } Console.WriteLine("================================ Application finished. Press any key to exit ============================="); Console.ReadKey(true); }
private void ChangeNotificationsOnOnEntityUpdated(object sender, NotifyEntityChangeContext.ChangeNotifications <DeviceValue> .EntityUpdatedArgs entityUpdatedArgs) { var bw = new BackgroundWorker(); bw.DoWork += async(s, a) => { try { await Log.ReportInfoFormatAsync(CancellationToken, "{0} working!", Name); using (var context = new ZvsContext(EntityContextConnection)) { var dv = await context.DeviceValues .FirstOrDefaultAsync(v => v.Id == entityUpdatedArgs.NewEntity.Id, CancellationToken); await Log.ReportInfoFormatAsync(CancellationToken, "DeviceValueId : {1}, new:{2}, old:{3}, dv.Value:{4}", (dv != null && dv.Value != null), entityUpdatedArgs.NewEntity.Id, entityUpdatedArgs.NewEntity.Value, entityUpdatedArgs.OldEntity.Value); if (dv == null || dv.Value == null) { return; } var name = dv.Device.Name; await Log.ReportInfoFormatAsync(CancellationToken, "[{0}] value name: [{1}], Value: [{2}]", Name, name, dv.Value); if (name == Field1) { await Log.ReportInfoFormatAsync(CancellationToken, "Sending {0} to ThingSpeak as Field1, Value={1}", name, dv.Value); short response; var success = ThingSpeakClient.SendDataToThingSpeak(out response, dv.Value); await Log.ReportInfoFormatAsync(CancellationToken, "ThingSpeak results ({0}): success:{1}, response:{2}", name, success, response); } if (name == Field2) { await Log.ReportInfoFormatAsync(CancellationToken, "Sending {0} to ThingSpeak as Field2, Value={1}", name, dv.Value); short response; var success = ThingSpeakClient.SendDataToThingSpeak(out response, null, dv.Value); await Log.ReportInfoFormatAsync(CancellationToken, "ThingSpeak results ({0}): success:{1}, response:{2}", name, success, response); } if (name == Field3) { await Log.ReportInfoFormatAsync(CancellationToken, "Sending {0} to ThingSpeak as Field3, Value={1}", name, dv.Value); short response; var success = ThingSpeakClient.SendDataToThingSpeak(out response, null, null, dv.Value); await Log.ReportInfoFormatAsync(CancellationToken, "ThingSpeak results ({0}): success:{1}, response:{2}", name, success, response); } if (name == Field4) { await Log.ReportInfoFormatAsync(CancellationToken, "Sending {0} to ThingSpeak as Field4, Value={1}", name, dv.Value); short response; var success = ThingSpeakClient.SendDataToThingSpeak(out response, null, null, null, dv.Value); await Log.ReportInfoFormatAsync(CancellationToken, "ThingSpeak results ({0}): success:{1}, response:{2}", name, success, response); } if (name == Field5) { await Log.ReportInfoFormatAsync(CancellationToken, "Sending {0} to ThingSpeak as Field5, Value={1}", name, dv.Value); short response; var success = ThingSpeakClient.SendDataToThingSpeak(out response, null, null, null, null, dv.Value); await Log.ReportInfoFormatAsync(CancellationToken, "ThingSpeak results ({0}): success:{1}, response:{2}", name, success, response); } if (name == Field6) { await Log.ReportInfoFormatAsync(CancellationToken, "Sending {0} to ThingSpeak as Field6, Value={1}", name, dv.Value); short response; var success = ThingSpeakClient.SendDataToThingSpeak(out response, null, null, null, null, null, dv.Value); await Log.ReportInfoFormatAsync(CancellationToken, "ThingSpeak results ({0}): success:{1}, response:{2}", name, success, response); } if (name == Field7) { await Log.ReportInfoFormatAsync(CancellationToken, "Sending {0} to ThingSpeak as Field7, Value={1}", name, dv.Value); short response; var success = ThingSpeakClient.SendDataToThingSpeak(out response, null, null, null, null, null, null, dv.Value); await Log.ReportInfoFormatAsync(CancellationToken, "ThingSpeak results ({0}): success:{1}, response:{2}", name, success, response); } if (name == Field8) { await Log.ReportInfoFormatAsync(CancellationToken, "Sending {0} to ThingSpeak as Field8, Value={1}", name, dv.Value); short response; var success = ThingSpeakClient.SendDataToThingSpeak(out response, null, null, null, null, null, null, null, dv.Value); await Log.ReportInfoFormatAsync(CancellationToken, "ThingSpeak results ({0}): success:{1}, response:{2}", name, success, response); } } } catch (Exception e) { Log.ReportErrorAsync(e.Message, CancellationToken).Wait(); } }; bw.RunWorkerAsync(); }