Skip to content

Commit

Permalink
Merge pull request #46 from CropWatchDevelopment/change-device-names
Browse files Browse the repository at this point in the history
Change device names
  • Loading branch information
CropWatchDevelopment authored May 9, 2024
2 parents 65bf939 + 5c75641 commit 977fcbe
Show file tree
Hide file tree
Showing 10 changed files with 266 additions and 49 deletions.
12 changes: 12 additions & 0 deletions Database DDL/cw_locations-RLS.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
CREATE POLICY "update_if_user_owns_table"
ON cw_locations
FOR UPDATE
USING (
EXISTS (
SELECT 1
FROM cw_location_owners
WHERE cw_location_owners.user_id = auth.uid()
AND cw_location_owners.location_id = cw_locations.location_id
AND cw_location_owners.is_active = true -- Assuming you have a similar condition
)
);
9 changes: 9 additions & 0 deletions src/app.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@
<link rel="icon" type="image/png" sizes="16x16" href="%sveltekit.assets%/icons/logo_16.png?v=1">
<link rel="icon" type="image/png" sizes="512x512" href="%sveltekit.assets%/icons/logo_512.png?v=1">
<link rel="manifest" href="%sveltekit.assets%/manifest.json">
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-1C791PBK6E"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());

gtag('config', 'G-1C791PBK6E');
</script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="google" content="notranslate">
%sveltekit.head%
Expand Down
80 changes: 80 additions & 0 deletions src/lib/components/ui/EditSensorNameDialog.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<script lang="ts">
import { enhance } from '$app/forms';
import { mdiClose, mdiFloppy, mdiPencil } from '@mdi/js';
import { toast } from '@zerodevx/svelte-toast';
import { Button, Dialog, TextField } from 'svelte-ux';
import { _ } from 'svelte-i18n';
export let currentSensorName: string = '';
export let dev_eui: string = -1;
let currentSensorNameStatic = currentSensorName;
let open = false;
const handleSubmit = () => {
fetch(`/api/v1/devices/${dev_eui}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: currentSensorName })
})
.then((res) => {
if (res.ok) {
toast.push(`Sensor name updated successfully`, {
theme: {
'--toastBackground': 'green',
'--toastColor': 'black'
}
});
currentSensorNameStatic = currentSensorName;
} else {
toast.push(`Sensor name updated FAILED`, {
theme: {
'--toastBackground': 'red',
'--toastColor': 'black'
}
});
currentSensorName = currentSensorNameStatic;
open = false;
}
return res.json();
})
.then((data) => {
console.log(data);
currentSensorName = data.name;
open = false;
})
.catch((err) => {
console.error(err);
currentSensorName = currentSensorNameStatic;
open = false;
});
};
const closing = () => {
currentSensorName = currentSensorNameStatic;
open = false;
};
</script>

<Button on:click={() => (open = true)} icon={mdiPencil} size="sm" />

<form action={`/api/v1/sensors/${dev_eui}`} method="PUT">
<Dialog bind:open on:close={() => closing()}>
<div slot="title">{$_('rename_dialog.rename')} {currentSensorNameStatic} {$_('rename_dialog.to_what')}</div>
<div class="m-4">
<TextField name="newName" label={$_('rename_dialog.new_name')} bind:value={currentSensorName} />
</div>
<div class="flex flex-row mt-1 p-2">
<Button variant="fill" icon={mdiClose} on:click={() => (open = false)} color="danger">{$_('close')}</Button>
<span class="flex-grow" />
<Button
variant="fill"
type="button"
icon={mdiFloppy}
on:click={() => handleSubmit()}
color="success">{$_('save')}</Button
>
</div>
</Dialog>
</form>
16 changes: 12 additions & 4 deletions src/lib/components/ui/sensors/CW_SS_TME.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
import { HighChartsTimeSeriesChart } from '$lib/charts/highcharts/timeseries';
import Highcharts from '$lib/actions/highcharts.action';
import { _ } from 'svelte-i18n';
import EditSensorNameDialog from '../EditSensorNameDialog.svelte';
export let data;
export let sensorName = 'NS';
export let permissions = 0;
let dev_eui = data.at(0).dev_eui;
let temperature = data.at(0).soil_temperatureC;
let moisture = data.at(0).soil_moisture;
let soil_ec = data.at(0).soil_EC;
Expand Down Expand Up @@ -45,7 +47,7 @@
}
},
opposite: false
},
}
],
$_('soil_temperature')
);
Expand Down Expand Up @@ -89,9 +91,15 @@
alt={isActiveRecently ? 'Active Image' : 'in-active Image'}
class="w-14 h-14 mr-4"
/>
<div class="flex flex-col">
<p class="text-surface-100 text-4xl">{sensorName}</p>
<p class="text-slate-500">{$_('lastSeen')}: <Duration start={lastSeen} totalUnits={1} /> {$_('ago')}</p>
<div class="flex flex-col justify-center">
<div class="flex flex-row text-neutral-content">
<p class="text-surface-100 text-4xl mr-2">{sensorName}</p>
<EditSensorNameDialog {dev_eui} bind:currentSensorName={sensorName} />
</div>
<p class="text-slate-500">
{$_('lastSeen')}: <Duration start={lastSeen} totalUnits={1} />
{$_('ago')}
</p>
</div>
</div>
<DarkCard title={$_('soil_temperature')} value={temperature} optimalValue={20} unit={'ºC'}>
Expand Down
9 changes: 7 additions & 2 deletions src/lib/components/ui/sensors/CW_SS_TMEPNPK.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
import { curveLinearClosed } from 'd3-shape';
import { Chart, Svg, Group, Axis, Spline, Points } from 'layerchart';
import { _ } from 'svelte-i18n';
import EditSensorNameDialog from '../EditSensorNameDialog.svelte';
export let data;
export let sensorName = 'NS';
export let permissions = 0;
let dev_eui = data.at(0).dev_eui;
let temperature = data.at(0).soil_temperatureC;
let moisture = data.at(0).soil_moisture;
let soil_ec = data.at(0).soil_EC;
Expand Down Expand Up @@ -102,7 +104,10 @@
class="w-14 h-14 mr-4"
/>
<div class="flex flex-col">
<p class="text-surface-100 text-4xl">{sensorName}</p>
<div class="flex flex-row text-neutral-content">
<p class="text-surface-100 text-4xl mr-2">{sensorName}</p>
<EditSensorNameDialog {dev_eui} bind:currentSensorName={sensorName} />
</div>
<p class="text-slate-500">
{$_('lastSeen')}: <Duration start={lastSeen} totalUnits={1} />
{$_('ago')}
Expand Down
7 changes: 6 additions & 1 deletion src/lib/components/ui/sensors/SEEED_2120.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
import ActiveImage from '$lib/images/UI/cw-10.svg';
import inActiveImage from '$lib/images/UI/cw_sensor_status_inactive.svg';
import EditSensorNameDialog from '../EditSensorNameDialog.svelte';
export let data;
export let sensorName = 'NS';
let dev_eui = data.at(0).dev_eui;
let lastSeen = data.at(0).created_at;
let isActiveRecently = moment().diff(moment(lastSeen), 'minutes') < 31;
</script>
Expand All @@ -21,7 +23,10 @@
class="w-14 h-14 mr-4"
/>
<div class="flex flex-col">
<p class="text-surface-100 text-4xl">{sensorName}</p>
<div class="flex flex-row text-neutral-content">
<p class="text-surface-100 text-4xl mr-2">{sensorName}</p>
<EditSensorNameDialog {dev_eui} bind:currentSensorName={sensorName} />
</div>
<p class="text-slate-500">
{$_('lastSeen')}: <Duration start={lastSeen} totalUnits={1} />
{$_('ago')}
Expand Down
7 changes: 6 additions & 1 deletion src/lib/components/ui/sensors/SEEED_S2103.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@
import { curveLinearClosed } from 'd3-shape';
import { _ } from 'svelte-i18n';
import { HighChartsGuageChart } from '$lib/charts/highcharts/guage';
import EditSensorNameDialog from '../EditSensorNameDialog.svelte';
export let data;
export let sensorName = 'NS';
export let permissions = 0;
let dev_eui = data.at(0).dev_eui;
let temperature = data.at(0).temperature;
let humidity = data.at(0).humidity;
let co2_level = data.at(0).co2_level;
Expand Down Expand Up @@ -88,7 +90,10 @@
class="w-14 h-14 mr-4"
/>
<div class="flex flex-col">
<p class="text-surface-100 text-4xl">{sensorName}</p>
<div class="flex flex-row text-neutral-content">
<p class="text-surface-100 text-4xl mr-2">{sensorName}</p>
<EditSensorNameDialog {dev_eui} bind:currentSensorName={sensorName} />
</div>
<p class="text-slate-500">{$_('lastSeen')}: <Duration start={lastSeen} totalUnits={1} /> {$_('ago')}</p>
</div>
</div>
Expand Down
7 changes: 6 additions & 1 deletion src/lib/components/ui/sensors/Sensor1.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
import { Duration } from 'svelte-ux';
import SensorFooterControls from '../SensorFooterControls.svelte';
import { _ } from 'svelte-i18n';
import EditSensorNameDialog from '../EditSensorNameDialog.svelte';
export let data;
export let sensorName = 'NS';
export let permissions = 0;
let dev_eui = data.at(0).dev_eui;
const temperature = data.at(0).temperatureC;
const humidity = data.at(0).humidity;
const dewPoint = data.at(0).dewPointC;
Expand Down Expand Up @@ -112,7 +114,10 @@
class="w-14 h-14 mr-4"
/>
<div class="flex flex-col">
<p class="text-surface-100 text-4xl">{sensorName}</p>
<div class="flex flex-row text-neutral-content">
<p class="text-surface-100 text-4xl mr-2">{sensorName}</p>
<EditSensorNameDialog {dev_eui} bind:currentSensorName={sensorName} />
</div>
<p class="text-slate-500">{$_('lastSeen')}: <Duration start={lastSeen} totalUnits={1} /> {$_('ago')}</p>
</div>
</div>
Expand Down
65 changes: 65 additions & 0 deletions src/routes/(api)/api/v1/devices/[dev_eui]/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,69 @@ export const GET: RequestHandler = async ({ url, params, locals: { supabase, saf
{
status: error ? 500 : 200,
});
}


export const PUT: RequestHandler = async ({ params, request, locals: { supabase, safeGetSession } }) => {
const { session } = await safeGetSession();
if (!session) {
throw redirect(303, '/auth/unauthorized');
}

const body = new URLSearchParams(await request.json());
const name = body.get('name');


if (!name) {
return new Response(
JSON.stringify({ error: 'name is required' }),
{
status: 400,
});
}

const dev_eui = params.dev_eui;
if (!dev_eui) {
return new Response(
JSON.stringify({ error: 'location_id is required' }),
{
status: 400,
});
}
const { data, error } = await supabase
.from('cw_device_owners')
.select('*, cw_devices(*)')
.eq('dev_eui', dev_eui)
.eq('user_id', session.user.id)
.limit(1)
.single();

if (error) {
return new Response(
JSON.stringify(error),
{
status: 500,
headers: {
'Content-Type': 'application/json',
}
});
}

const { data: updatedData, error: updateError } = await supabase
.from('cw_devices')
.update({ 'name': name })
.eq('dev_eui', data.cw_devices.dev_eui)
.select()
.single();

return new Response(
JSON.stringify(updatedData) ||
JSON.stringify(updateError),
{
status: updatedData ? 200 : 500,
statusText: updatedData ? 'OK' : updateError,
headers: {
'Content-Type': 'application/json',
}
});
}
Loading

0 comments on commit 977fcbe

Please sign in to comment.