Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
33 lines (30 loc) · 9.83 KB
/
Copy pathapp.js
File metadata and controls
33 lines (30 loc) · 9.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const DATA_URL = "https://code4fukui.github.io/fukui-spot/fuku-e-spot.csv";
const SDK_URL = "https://code4fukui.github.io/webglass-sdk/sabera.js";
const FALLBACK = [
{ name: "東尋坊", area: "坂井市 / 越前海岸", description: "柱状節理がつくる、日本海の大迫力の断崖。", url: "https://www.fuku-e.com/spot/detail_1471.html" },
{ name: "福井県立恐竜博物館", area: "勝山市 / 北谷町", description: "世界三大恐竜博物館のひとつ。太古の記憶に会いに行く。", url: "https://www.fuku-e.com/spot/detail_1663.html" },
{ name: "永平寺", area: "永平寺町 / 志比", description: "深い杉木立に包まれた、曹洞宗の大本山。", url: "https://www.fuku-e.com/spot/detail_1184.html" },
{ name: "三方五湖レインボーライン", area: "若狭町 / 気山", description: "五つの湖と若狭湾を一望する、天空のテラス。", url: "https://www.fuku-e.com/spot/detail_1352.html" },
{ name: "越前大野城", area: "大野市 / 城町", description: "雲海に浮かぶ「天空の城」。城下町の景色も美しい。", url: "https://www.fuku-e.com/spot/detail_1218.html" },
{ name: "一乗谷朝倉氏遺跡", area: "福井市 / 城戸ノ内町", description: "戦国時代の町並みが残る、歴史のタイムカプセル。", url: "https://www.fuku-e.com/spot/detail_1170.html" },
{ name: "越前海岸", area: "福井市・越前町", description: "奇岩と青い海が連なる、北陸のダイナミックな海岸線。", url: "https://www.fuku-e.com/spot/detail_1424.html" }
];
const $ = id => document.getElementById(id);
let spots = FALLBACK, current = null, timer = null, seconds = 15, sdkModule = null, sdkClient = null, connected = false, textModeReady = false;
// SDKはボタンを押す前にロードしておく。BluetoothのrequestDevice()は、
// クリック直後のユーザー操作コンテキストから呼び出す必要があるため。
try { sdkModule = await import(SDK_URL); } catch (error) { console.warn("SABERA SDKの読み込みに失敗しました", error); }
function notify(message) { const toast = $("toast"); toast.textContent = message; toast.classList.add("show"); setTimeout(() => toast.classList.remove("show"), 2600); }
function pick(obj, keys) { for (const key of keys) if (obj[key] != null && String(obj[key]).trim()) return String(obj[key]).trim(); return ""; }
function parseCSV(text) { const rows = []; let row = [], cell = "", quoted = false; for (let i = 0; i < text.length; i++) { const ch = text[i], next = text[i + 1]; if (ch === '"' && quoted && next === '"') { cell += '"'; i++; } else if (ch === '"') quoted = !quoted; else if (ch === ',' && !quoted) { row.push(cell); cell = ""; } else if ((ch === '\n' || ch === '\r') && !quoted) { if (ch === '\r' && next === '\n') i++; row.push(cell); if (row.some(v => v.trim())) rows.push(row); row = []; cell = ""; } else cell += ch; } if (cell || row.length) { row.push(cell); rows.push(row); } const headers = rows.shift()?.map(v => v.replace(/^\uFEFF/, '').trim()) || []; return rows.map(values => Object.fromEntries(headers.map((h, i) => [h, values[i] || ""]))); }
function normalize(row) { return { name: pick(row, ["名称", "name", "スポット名", "dc:title", "schema:name", "観光スポット名"]), area: pick(row, ["市町名", "エリア", "住所", "所在地", "area"]), description: pick(row, ["概要", "説明", "紹介文", "description", "dc:description"]), image: pick(row, ["画像", "画像URL", "ic:画像", "image", "schema:image"]), url: pick(row, ["参照", "URL", "url", "ic:参照", "schema:url"]) }; }
async function loadSpots() { try { const response = await fetch(DATA_URL); if (!response.ok) throw new Error("data"); const data = parseCSV(await response.text()).map(normalize).filter(d => d.name); if (data.length > 10) spots = data; $("dataStatus").textContent = `${spots.length}スポットを読み込み済み`; } catch { $("dataStatus").textContent = "サンプルデータで表示中"; } $("spotCount").textContent = spots.length; showNext(true); }
function showNext(first = false) { let next = spots[Math.floor(Math.random() * spots.length)]; if (spots.length > 1 && current) while (next.name === current.name) next = spots[Math.floor(Math.random() * spots.length)]; current = next; const number = String(spots.indexOf(current) + 1).padStart(3, "0"); $("glassTitle").textContent = current.name || "福井の旅先"; $("glassArea").textContent = current.area || "FUKUI PREFECTURE"; $("glassNumber").textContent = `#${number}`; $("saberaTitle").textContent = current.name || "福井の旅先"; $("saberaArea").textContent = current.area || "FUKUI"; $("saberaDescription").textContent = current.description || "次の旅先を見つけました。"; $("saberaProgress").textContent = `${String(spots.indexOf(current) + 1).padStart(2, "0")} / ${String(spots.length).padStart(2, "0")}`; [$("glassWindow"), $("saberaWindow")].forEach(el => { el.animate([{ opacity: .35, transform: "translateY(5px)" }, { opacity: 1, transform: "translateY(0)" }], { duration: 450, easing: "ease-out" }); }); seconds = 15; if (!first) pushToGlass(); }
function getSdkObject() { if (!sdkModule) throw new Error("SDKを読み込めませんでした"); if (sdkClient) return sdkClient; const Candidate = sdkModule.SaberaClient || sdkModule.SABERA || sdkModule.Sabera || sdkModule.sabera || sdkModule.default; if (typeof Candidate === "function") { try { sdkClient = new Candidate(); } catch { sdkClient = Candidate; } } else sdkClient = Candidate || sdkModule; return sdkClient; }
function findSdkMethod(client, names) { for (const target of [client, sdkModule, client?.constructor]) for (const name of names) if (typeof target?.[name] === "function") return { target, method: target[name], name }; return null; }
function getTextSender(client) { const exact = findSdkMethod(client, ["sendText", "sendNormalText", "sendGenericText", "sendDisplayText", "displayText", "displayNormalText", "sendTextToGlass", "showText", "setText", "updateText", "writeText", "send"]); if (exact) return exact; const proto = Object.getOwnPropertyNames(Object.getPrototypeOf(client || {})); const name = proto.find(key => /text/i.test(key) && /send|show|display|write|set|update/i.test(key) && typeof client[key] === "function"); return name ? { target: client, method: client[name], name } : null; }
async function enterTextMode(client) { if (textModeReady) return; const screen = findSdkMethod(client, ["showScreen"]); if (screen) { await screen.method.call(screen.target, 0x47); textModeReady = true; console.log("SABERA screen: generic text (0x47)"); return; } const mode = findSdkMethod(client, ["setMode", "setDisplayMode", "setScreenMode", "switchMode", "changeMode", "setPage", "openTextMode", "openText", "startTextMode", "showGenericText"]); if (!mode) { console.warn("SABERAのテキストモードAPIが見つかりません", Object.getOwnPropertyNames(Object.getPrototypeOf(client))); return; } const noArg = /^(open|start|show)/i.test(mode.name); await mode.method.call(mode.target, ...(noArg ? [] : ["generic_text"])); textModeReady = true; console.log("SABERA text mode:", mode.name); }
async function pushToGlass() { if (!sdkClient || !connected || !current) return; const message = `${current.name}\n${current.description || "福井県の観光スポット"}`; try { await enterTextMode(sdkClient); const sender = getTextSender(sdkClient); if (!sender) throw new Error(`text API unavailable: ${Object.getOwnPropertyNames(Object.getPrototypeOf(sdkClient)).join(", ")}`); console.log("SABERA text method:", sender.name); await sender.method.call(sender.target, message); $("saberaState").innerHTML = "<i></i> CONNECTED / SENT"; } catch (error) { console.error("SABERA文字送信エラー", error); $("saberaState").innerHTML = "<i></i> CONNECTED / SEND ERROR"; notify("接続しましたが、スポットの送信に失敗しました"); } }
async function connectGlass() { if (connected) { connected = false; textModeReady = false; const disconnect = findSdkMethod(sdkClient, ["disconnect", "close"]); if (disconnect) await disconnect.method.call(disconnect.target); $("connectButton").innerHTML = '<span class="bluetooth">⌁</span> SABERAに接続'; $("saberaState").innerHTML = "<i></i> STANDBY"; notify("SABERAとの接続を解除しました"); return; } try { if (!window.isSecureContext && location.hostname !== "localhost" && location.hostname !== "127.0.0.1") throw new Error("secure context required"); if (!navigator.bluetooth) throw new Error("Web Bluetooth unavailable"); const client = getSdkObject(); const connector = findSdkMethod(client, ["connect", "connectDevice", "connectSABERA", "connectSabera", "scanAndConnect", "requestDevice", "open", "start"]); if (!connector) throw new Error(`SDKに接続APIがありません: ${Object.keys(sdkModule).join(", ")}`); await connector.method.call(connector.target); sdkClient = client; connected = true; $("connectButton").textContent = "✓ 接続中"; $("saberaState").innerHTML = "<i></i> CONNECTED"; notify("SABERAに接続しました"); await pushToGlass(); } catch (error) { console.error("SABERA接続エラー", error); const message = error?.name === "NotFoundError" ? "接続するSABERAが選択されませんでした" : error?.message?.includes("secure") ? "localhostまたはHTTPSで開いてください" : !navigator.bluetooth ? "Web Bluetooth対応のChromium系ブラウザで開いてください" : error?.message?.includes("接続API") ? "SABERA SDKの接続APIを確認できませんでした" : "SABERA SDKを読み込めませんでした。ページを再読み込みしてください"; notify(message); } }
function startTimer() { clearInterval(timer); timer = setInterval(() => { seconds--; $("countdown").textContent = String(seconds).padStart(2, "0"); if (seconds <= 0) showNext(); }, 1000); }
$("nextButton").addEventListener("click", () => showNext()); $("connectButton").addEventListener("click", connectGlass); loadSpots(); startTimer();