private async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct) { var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow); while (true) { if (ct.IsCancellationRequested) { break; } EventData eventData = await eventHubReceiver.ReceiveAsync(); if (eventData == null) { continue; } var data = Encoding.UTF8.GetString(eventData.GetBytes()); Debug.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data); var temperature = JsonConvert.DeserializeObject <TemperatureData>(data); temperature.PartitionId = partition; var hub = new TemperatureHub(); await hub.NotifyClient(temperature); } }
public TemperatureController(IOptions <CouchbaseOptions> couchbaseOptions, TemperatureHub temperatureHub) { _temperatureHub = temperatureHub; _bucket = ClusterHelper.GetBucket(couchbaseOptions.Value.CouchbaseBucket); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, JsonSerializerOptions serializerOptions, IHttpClientFactory clientFactory, TemperatureHub temperatureHub) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseRouting(); app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod()); // app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseEndpoints(endpoints => { endpoints.MapHub <TemperatureHub>("/temperatureHub"); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapSubscribeHandler(); endpoints.MapPost("readings-input", Readings).WithTopic("readings"); }); async Task Readings(HttpContext context) { var tempReading = await JsonSerializer.DeserializeAsync <dynamic>(context.Request.Body, serializerOptions); var reading = new { Date = DateTime.Now, Temperature = tempReading.Data.Temperature }; await temperatureHub.SendMessage(JsonSerializer.Serialize(reading)); context.Response.ContentType = "application/json"; await JsonSerializer.SerializeAsync(context.Response.Body, string.Empty, serializerOptions); } }