Example #1
0
        // 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);
            }
        }
        public async Task Report(double temperature)
        {
            var reading = new
            {
                Date        = DateTime.Now,
                Temperature = temperature
            };

            var readingDoc = new Document <dynamic>
            {
                Id      = Guid.NewGuid().ToString(),
                Content = reading
                          // Expiry = DateTime.Now.AddMinutes(10)
            };

            var result = await _bucket.InsertAsync(readingDoc);

            await _temperatureHub.SendMessage(JsonConvert.SerializeObject(reading));
        }