diff options
| author | Adam Malczewski <[email protected]> | 2026-04-09 15:46:54 +0900 |
|---|---|---|
| committer | Adam Malczewski <[email protected]> | 2026-04-09 15:46:54 +0900 |
| commit | a4b619ff1229b226da3e7228c167aad4289e1784 (patch) | |
| tree | 6a92b7f71dec96f70d4d1e6b9aafe6ce28b596b6 /src | |
| download | flashair-speedsync-a4b619ff1229b226da3e7228c167aad4289e1784.tar.gz flashair-speedsync-a4b619ff1229b226da3e7228c167aad4289e1784.zip | |
inital app skeleton
Diffstat (limited to 'src')
| -rw-r--r-- | src/App.svelte | 145 | ||||
| -rw-r--r-- | src/app.css | 4 | ||||
| -rw-r--r-- | src/lib/flashair/client.ts | 198 | ||||
| -rw-r--r-- | src/lib/flashair/index.ts | 2 | ||||
| -rw-r--r-- | src/lib/flashair/types.ts | 37 | ||||
| -rw-r--r-- | src/main.ts | 9 |
6 files changed, 395 insertions, 0 deletions
diff --git a/src/App.svelte b/src/App.svelte new file mode 100644 index 0000000..bcac7cb --- /dev/null +++ b/src/App.svelte @@ -0,0 +1,145 @@ +<script lang="ts"> + import { flashair } from './lib/flashair'; + import type { FlashAirFileEntry } from './lib/flashair'; + + let files = $state<FlashAirFileEntry[]>([]); + let currentDir = $state('/DCIM'); + let loading = $state(false); + let error = $state<string | undefined>(undefined); + let isDark = $state(false); + + $effect(() => { + document.documentElement.setAttribute('data-theme', isDark ? 'black' : 'cmyk'); + }); + + async function loadFiles(dir: string) { + loading = true; + error = undefined; + try { + currentDir = dir; + files = await flashair.listFiles(dir); + } catch (e) { + error = e instanceof Error ? e.message : String(e); + files = []; + } finally { + loading = false; + } + } + + const imageFiles = $derived( + files.filter((f) => !f.isDirectory && /\.(jpe?g|png|bmp|gif)$/i.test(f.filename)), + ); + + const directories = $derived(files.filter((f) => f.isDirectory)); +</script> + +<div class="min-h-screen bg-base-200"> + <div class="navbar bg-base-100 shadow-sm"> + <div class="flex-1"> + <span class="text-xl font-bold px-4">SpeedSync</span> + </div> + <div class="flex-none gap-2"> + <button class="btn btn-ghost btn-sm" onclick={() => loadFiles(currentDir)}> + Refresh + </button> + <label class="swap swap-rotate btn btn-ghost btn-sm"> + <input type="checkbox" bind:checked={isDark} /> + <!-- sun icon --> + <svg class="swap-off fill-current w-5 h-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> + <path d="M5.64,17l-.71.71a1,1,0,0,0,0,1.41,1,1,0,0,0,1.41,0l.71-.71A1,1,0,0,0,5.64,17ZM5,12a1,1,0,0,0-1-1H3a1,1,0,0,0,0,2H4A1,1,0,0,0,5,12Zm7-7a1,1,0,0,0,1-1V3a1,1,0,0,0-2,0V4A1,1,0,0,0,12,5ZM5.64,7.05a1,1,0,0,0,.7.29,1,1,0,0,0,.71-.29,1,1,0,0,0,0-1.41l-.71-.71A1,1,0,0,0,4.93,6.34Zm12,.29a1,1,0,0,0,.7-.29l.71-.71a1,1,0,1,0-1.41-1.41L17,5.64a1,1,0,0,0,0,1.41A1,1,0,0,0,17.66,7.34ZM21,11H20a1,1,0,0,0,0,2h1a1,1,0,0,0,0-2Zm-9,8a1,1,0,0,0-1,1v1a1,1,0,0,0,2,0V20A1,1,0,0,0,12,19ZM18.36,17A1,1,0,0,0,17,18.36l.71.71a1,1,0,0,0,1.41,0,1,1,0,0,0,0-1.41ZM12,6.5A5.5,5.5,0,1,0,17.5,12,5.51,5.51,0,0,0,12,6.5Zm0,9A3.5,3.5,0,1,1,15.5,12,3.5,3.5,0,0,1,12,15.5Z"/> + </svg> + <!-- moon icon --> + <svg class="swap-on fill-current w-5 h-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> + <path d="M21.64,13a1,1,0,0,0-1.05-.14,8.05,8.05,0,0,1-3.37.73A8.15,8.15,0,0,1,9.08,5.49a8.59,8.59,0,0,1,.25-2A1,1,0,0,0,8,2.36,10.14,10.14,0,1,0,22,14.05,1,1,0,0,0,21.64,13Zm-9.5,6.69A8.14,8.14,0,0,1,7.08,5.22v.27A10.15,10.15,0,0,0,17.22,15.63a9.79,9.79,0,0,0,2.1-.22A8.11,8.11,0,0,1,12.14,19.73Z"/> + </svg> + </label> + </div> + </div> + + <div class="container mx-auto p-4"> + <div class="breadcrumbs text-sm mb-4"> + <ul> + <li> + <button class="link" onclick={() => loadFiles('/')}>/</button> + </li> + {#each currentDir.split('/').filter(Boolean) as segment, i} + <li> + <button + class="link" + onclick={() => + loadFiles( + '/' + + currentDir + .split('/') + .filter(Boolean) + .slice(0, i + 1) + .join('/'), + )} + > + {segment} + </button> + </li> + {/each} + </ul> + </div> + + {#if loading} + <div class="flex justify-center py-12"> + <span class="loading loading-spinner loading-lg"></span> + </div> + {:else if error} + <div role="alert" class="alert alert-error"> + <span>{error}</span> + <button class="btn btn-sm" onclick={() => loadFiles(currentDir)}>Retry</button> + </div> + {:else if files.length === 0} + <div class="text-center py-12 text-base-content/60"> + <p>No files found. Connect to the FlashAir WiFi and tap Refresh.</p> + <button class="btn btn-primary mt-4" onclick={() => loadFiles(currentDir)}> + Load Files + </button> + </div> + {:else} + {#if directories.length > 0} + <div class="mb-4"> + <h3 class="font-semibold mb-2">Folders</h3> + <div class="flex flex-wrap gap-2"> + {#each directories as dir} + <button class="btn btn-outline btn-sm" onclick={() => loadFiles(dir.path)}> + 📁 {dir.filename} + </button> + {/each} + </div> + </div> + {/if} + + {#if imageFiles.length > 0} + <h3 class="font-semibold mb-2">Photos ({imageFiles.length})</h3> + <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-2"> + {#each imageFiles as file (file.path)} + {@const thumbUrl = flashair.thumbnailUrl(file.path)} + <div class="card bg-base-100 shadow-sm"> + {#if thumbUrl} + <figure class="aspect-square overflow-hidden"> + <img + src={thumbUrl} + alt={file.filename} + class="object-cover w-full h-full" + loading="lazy" + /> + </figure> + {:else} + <figure class="aspect-square bg-base-300 flex items-center justify-center"> + <span class="text-3xl">🖼️</span> + </figure> + {/if} + <div class="card-body p-2"> + <p class="text-xs truncate">{file.filename}</p> + </div> + </div> + {/each} + </div> + {/if} + {/if} + </div> +</div> diff --git a/src/app.css b/src/app.css new file mode 100644 index 0000000..147bcf3 --- /dev/null +++ b/src/app.css @@ -0,0 +1,4 @@ +@import "tailwindcss"; +@plugin "daisyui" { + themes: cmyk --default, black; +} diff --git a/src/lib/flashair/client.ts b/src/lib/flashair/client.ts new file mode 100644 index 0000000..4e3a567 --- /dev/null +++ b/src/lib/flashair/client.ts @@ -0,0 +1,198 @@ +import type { FlashAirFileEntry, ThumbnailMeta } from './types'; + +/** Parse a 16-bit FAT date + time into a JS Date. */ +function parseFatDateTime(fatDate: number, fatTime: number): Date { + const year = ((fatDate >> 9) & 0x7f) + 1980; + const month = (fatDate >> 5) & 0x0f; + const day = fatDate & 0x1f; + const hour = (fatTime >> 11) & 0x1f; + const minute = (fatTime >> 5) & 0x3f; + const second = (fatTime & 0x1f) * 2; + return new Date(year, month - 1, day, hour, minute, second); +} + +/** Attribute bit 4 indicates a directory. */ +function isDirectory(attribute: number): boolean { + return (attribute & 0x10) !== 0; +} + +/** + * Resolve the base URL for FlashAir API requests. + * + * In production (served from the card), all requests go to the same origin. + * In development, we use the Vite dev server origin (which can proxy if configured). + */ +function getBaseUrl(): string { + return ''; +} + +/** + * Parse the text response from command.cgi op=100 into structured entries. + * + * First line is the header "WLANSD_FILELIST" and is skipped. + * Each subsequent line: <directory>,<filename>,<size>,<attribute>,<date>,<time> + * Note: filenames may contain commas, so we split from the right for the numeric fields. + */ +function parseFileList(text: string): FlashAirFileEntry[] { + const lines = text.trim().split('\n'); + const entries: FlashAirFileEntry[] = []; + + for (let i = 1; i < lines.length; i++) { + const line = lines[i]; + if (line === undefined || line.trim() === '') continue; + + // Split from the right: the last 4 fields are always numeric (size, attribute, date, time). + // The first field is directory, and everything between is the filename (which may contain commas). + const parts = line.split(','); + if (parts.length < 6) continue; + + const rawTime = Number(parts[parts.length - 1]); + const rawDate = Number(parts[parts.length - 2]); + const attribute = Number(parts[parts.length - 3]); + const size = Number(parts[parts.length - 4]); + const directory = parts[0] ?? ''; + // Filename is everything between the first and last 4 fields + const filename = parts.slice(1, parts.length - 4).join(','); + + const date = parseFatDateTime(rawDate, rawTime); + const dir = isDirectory(attribute); + const path = directory === '' ? `/${filename}` : `${directory}/${filename}`; + + entries.push({ + directory, + filename, + size, + attribute, + rawDate, + rawTime, + date, + isDirectory: dir, + path, + }); + } + + return entries; +} + +/** Known image extensions the FlashAir thumbnail.cgi supports (JPEG only). */ +const JPEG_EXTENSIONS = new Set(['.jpg', '.jpeg']); + +function isJpeg(filename: string): boolean { + const ext = filename.slice(filename.lastIndexOf('.')).toLowerCase(); + return JPEG_EXTENSIONS.has(ext); +} + +/** + * FlashAir API client. + * + * All methods return promises and throw on network/HTTP errors. + */ +export const flashair = { + /** + * List files in a directory. + * @param dir - Absolute path on the card, e.g. "/DCIM" + */ + async listFiles(dir: string): Promise<FlashAirFileEntry[]> { + const base = getBaseUrl(); + const res = await fetch(`${base}/command.cgi?op=100&DIR=${encodeURIComponent(dir)}`); + if (!res.ok) throw new Error(`listFiles failed: ${res.status} ${res.statusText}`); + const text = await res.text(); + return parseFileList(text); + }, + + /** + * Get the number of files in a directory. + */ + async getFileCount(dir: string): Promise<number> { + const base = getBaseUrl(); + const res = await fetch(`${base}/command.cgi?op=101&DIR=${encodeURIComponent(dir)}`); + if (!res.ok) throw new Error(`getFileCount failed: ${res.status} ${res.statusText}`); + const text = await res.text(); + return Number(text.trim()); + }, + + /** + * Check if the card memory has been updated since last check. + * Returns true if updated. Calling this clears the flag. + */ + async hasUpdated(): Promise<boolean> { + const base = getBaseUrl(); + const res = await fetch(`${base}/command.cgi?op=102`); + if (!res.ok) throw new Error(`hasUpdated failed: ${res.status} ${res.statusText}`); + const text = await res.text(); + return text.trim() === '1'; + }, + + /** + * Get the firmware version string. + */ + async getFirmwareVersion(): Promise<string> { + const base = getBaseUrl(); + const res = await fetch(`${base}/command.cgi?op=108`); + if (!res.ok) throw new Error(`getFirmwareVersion failed: ${res.status} ${res.statusText}`); + return (await res.text()).trim(); + }, + + /** + * Get SSID of the FlashAir. + */ + async getSSID(): Promise<string> { + const base = getBaseUrl(); + const res = await fetch(`${base}/command.cgi?op=104`); + if (!res.ok) throw new Error(`getSSID failed: ${res.status} ${res.statusText}`); + return (await res.text()).trim(); + }, + + /** + * Get the number of free sectors on the card. + */ + async getFreeSectors(): Promise<number> { + const base = getBaseUrl(); + const res = await fetch(`${base}/command.cgi?op=140`); + if (!res.ok) throw new Error(`getFreeSectors failed: ${res.status} ${res.statusText}`); + return Number((await res.text()).trim()); + }, + + /** + * Get the URL for a file on the card. + */ + fileUrl(path: string): string { + return `${getBaseUrl()}${path}`; + }, + + /** + * Get the thumbnail URL for a JPEG file. + * Returns undefined if the file is not a JPEG (thumbnails only work for JPEGs). + */ + thumbnailUrl(path: string): string | undefined { + const filename = path.slice(path.lastIndexOf('/') + 1); + if (!isJpeg(filename)) return undefined; + return `${getBaseUrl()}/thumbnail.cgi?${path}`; + }, + + /** + * Fetch a thumbnail and its EXIF metadata. + * Returns the blob and optional EXIF dimensions/orientation. + */ + async fetchThumbnail(path: string): Promise<{ blob: Blob; meta: ThumbnailMeta }> { + const url = flashair.thumbnailUrl(path); + if (url === undefined) throw new Error(`Not a JPEG file: ${path}`); + const res = await fetch(url); + if (!res.ok) throw new Error(`fetchThumbnail failed: ${res.status} ${res.statusText}`); + const blob = await res.blob(); + + const widthStr = res.headers.get('X-exif-WIDTH'); + const heightStr = res.headers.get('X-exif-HEIGHT'); + const orientStr = res.headers.get('X-exif-ORIENTATION'); + + const meta: ThumbnailMeta = { + width: widthStr !== null ? Number(widthStr) : undefined, + height: heightStr !== null ? Number(heightStr) : undefined, + orientation: orientStr !== null ? Number(orientStr) : undefined, + }; + + return { blob, meta }; + }, +} as const; + +export type { FlashAirFileEntry, ThumbnailMeta } from './types'; diff --git a/src/lib/flashair/index.ts b/src/lib/flashair/index.ts new file mode 100644 index 0000000..e7ff8af --- /dev/null +++ b/src/lib/flashair/index.ts @@ -0,0 +1,2 @@ +export { flashair } from './client'; +export type { FlashAirFileEntry, ThumbnailMeta } from './types'; diff --git a/src/lib/flashair/types.ts b/src/lib/flashair/types.ts new file mode 100644 index 0000000..1cee47d --- /dev/null +++ b/src/lib/flashair/types.ts @@ -0,0 +1,37 @@ +/** + * A single file entry returned by command.cgi op=100. + * + * Raw response format per line: + * <directory>,<filename>,<size>,<attribute>,<date>,<time> + * + * Date is a 16-bit FAT date: bits 15-9 = year (since 1980), 8-5 = month, 4-0 = day. + * Time is a 16-bit FAT time: bits 15-11 = hour, 10-5 = minute, 4-0 = second/2. + * Attribute is a 16-bit field: bit5=archive, bit4=directory, bit3=volume, bit2=system, bit1=hidden, bit0=readonly. + */ +export interface FlashAirFileEntry { + /** Parent directory path, e.g. "/DCIM/100__TSB" */ + readonly directory: string; + /** File name, e.g. "DSC_0001.JPG" */ + readonly filename: string; + /** File size in bytes */ + readonly size: number; + /** Raw FAT attribute value */ + readonly attribute: number; + /** Raw FAT date value */ + readonly rawDate: number; + /** Raw FAT time value */ + readonly rawTime: number; + /** Parsed JS Date */ + readonly date: Date; + /** Whether this entry is a directory */ + readonly isDirectory: boolean; + /** Full path to the file, e.g. "/DCIM/100__TSB/DSC_0001.JPG" */ + readonly path: string; +} + +/** Thumbnail response metadata from X-exif-* headers (FW 3.00.00+). */ +export interface ThumbnailMeta { + readonly width: number | undefined; + readonly height: number | undefined; + readonly orientation: number | undefined; +} diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 0000000..664a057 --- /dev/null +++ b/src/main.ts @@ -0,0 +1,9 @@ +import { mount } from 'svelte' +import './app.css' +import App from './App.svelte' + +const app = mount(App, { + target: document.getElementById('app')!, +}) + +export default app |
