66 lines
1.3 KiB
TypeScript
66 lines
1.3 KiB
TypeScript
import { browser } from '$app/environment';
|
|
import { readable } from 'svelte/store';
|
|
|
|
const url = 'http://192.168.116.72';
|
|
|
|
export type SensorData = {
|
|
temp: number;
|
|
hum: number;
|
|
out1: boolean;
|
|
out2: boolean;
|
|
};
|
|
|
|
const defaultData: SensorData = {
|
|
temp: 0,
|
|
hum: 0,
|
|
out1: false,
|
|
out2: false,
|
|
};
|
|
|
|
export const sensor = readable<SensorData>(defaultData, (set) => {
|
|
if (browser) {
|
|
const source = new EventSource(`${url}/events`);
|
|
|
|
source.addEventListener('open', () => {
|
|
console.log('Connected');
|
|
});
|
|
|
|
source.addEventListener('message', (e) => {
|
|
set(JSON.parse(e.data));
|
|
});
|
|
}
|
|
});
|
|
|
|
export async function setOutput(pin: number, value: boolean) {
|
|
await fetch(`${url}/set`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Accept: 'application/json',
|
|
},
|
|
body: JSON.stringify({ pin, value }),
|
|
});
|
|
}
|
|
|
|
export async function setOnTemp(temp: number) {
|
|
await fetch(`${url}/settings`, {
|
|
method: 'PATCH',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Accept: 'application/json',
|
|
},
|
|
body: JSON.stringify({ onTemp: temp }),
|
|
});
|
|
}
|
|
|
|
export async function setOnHum(hum: number) {
|
|
await fetch(`${url}/settings`, {
|
|
method: 'PATCH',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Accept: 'application/json',
|
|
},
|
|
body: JSON.stringify({ onHum: hum }),
|
|
});
|
|
}
|