Call /api/state after relay is switched

This commit is contained in:
2023-08-27 13:44:03 +02:00
parent f5f759ca0a
commit c1953517e7
3 changed files with 30 additions and 16 deletions

View File

@@ -1,37 +1,39 @@
<script lang="ts">
// import { toggleRelay } from '$lib/server/relayToggle'
import { createEventDispatcher } from 'svelte';
import Switch from './Switch.svelte';
import type { IRelaysDTO } from '../interfaces/IRelaysDTO';
export let relays = [];
export let relays: IRelaysDTO[] = [];
const dispatch = createEventDispatcher();
function toggleRelay(location) {
const url = `/api/relay/${location}`;
function toggleRelay(controls: string) {
const url = `/api/relay/${controls}`;
const options = {
method: 'POST'
};
fetch(url, options)
.then((resp) => resp.json())
.then(console.log);
}
.then((response) => {
const changedRelay = relays.findIndex((relay) => relay.pin === response.pin);
relays[changedRelay] = response;
});
function handleChange(event) {
let isChecked = event.detail.checked;
// Perform any desired actions based on the new value
console.log('New value:', isChecked);
dispatch('relaySwitched');
}
</script>
<div class="card">
<h1>Manual relay controls</h1>
<h1>Manual fridge controls</h1>
<div class="vertical-sensor-display">
{#each relays as relay}
<div>
<h2>{relay.location} relay</h2>
<h2>{relay.controls} relay</h2>
<div class="sensor-reading">
<Switch checked="{relay.state}" on:change="{() => toggleRelay(relay.location)}" />
<Switch checked="{relay.state}" on:change="{() => toggleRelay(relay.controls)}" />
</div>
</div>
{/each}

View File

@@ -7,7 +7,12 @@
import type { IStateDTO } from '../lib/interfaces/IStateDTO';
export let data: PageData;
const { inside, outside, relays } = data;
const { inside, outside } = data;
let { relays, state } = data;
const updateState = () => setTimeout(() => fetch('/api/state')
.then((resp) => resp.json())
.then((response: IStateDTO) => state = response), 100)
</script>
<Logo />
@@ -17,9 +22,7 @@
<VerticalSensorDisplay {inside} {outside} {relays} {state} />
<RelayControls relays="{relays}" />
<!-- <Livestream /> -->
<RelayControls bind:relays="{relays}" on:relaySwitched={updateState} />
</div>
<style lang="scss">

View File

@@ -0,0 +1,9 @@
import { json, RequestEvent } from '@sveltejs/kit';
import { BREWLOGGER_HOST } from '$env/static/private';
import type { RequestHandler } from './$types';
export const GET = (async (event: RequestEvent) => {
return fetch(BREWLOGGER_HOST + '/api/regulator')
.then((resp) => resp.json())
.then((response) => json(response));
}) satisfies RequestHandler;