poe-svelte-ui-lib 3.2.0 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/GUIRenderer/GUIRenderer.svelte +1 -0
- package/dist/Select/Select.svelte +10 -6
- package/dist/SensorReadout.svelte +4 -4
- package/dist/SensorSettings.svelte +250 -0
- package/dist/SensorSettings.svelte.d.ts +10 -0
- package/dist/WidgetAHRS/Horizon.svelte +7 -6
- package/dist/WidgetAHRS/WidgetAHRS.svelte +37 -31
- package/dist/WidgetAHRS/ahrs.d.ts +2 -0
- package/dist/WidgetAHRS/ahrs.js +17 -12
- package/dist/WidgetIMU/AccelPoses.svelte +80 -0
- package/dist/WidgetIMU/AccelPoses.svelte.d.ts +10 -0
- package/dist/WidgetIMU/README.md +20 -14
- package/dist/WidgetIMU/WidgetIMU.svelte +27 -12
- package/dist/WidgetIMU/WidgetIMUProps.svelte +9 -0
- package/dist/WidgetMag/README.md +12 -9
- package/dist/WidgetMag/WidgetMag.svelte +16 -6
- package/dist/WidgetMag/WidgetMagProps.svelte +9 -0
- package/dist/WidgetPFD/WidgetPFD.svelte +5 -4
- package/dist/WidgetPFD/pfdColors.d.ts +6 -0
- package/dist/WidgetPFD/pfdColors.js +7 -0
- package/dist/defaults.js +3 -3
- package/dist/dictionaries/firmware/poe_msg.h +8 -2
- package/dist/dictionaries/generated/poe_msg.js +14 -2
- package/dist/dictionaries/poe_msg.yaml +8 -2
- package/dist/gui.d.ts +1 -0
- package/dist/gui.js +3 -2
- package/dist/locales/translations.d.ts +215 -0
- package/dist/locales/translations.js +355 -236
- package/dist/sensorChips.d.ts +47 -0
- package/dist/sensorChips.js +253 -0
- package/dist/types.d.ts +4 -0
- package/package.json +2 -2
|
@@ -593,6 +593,7 @@
|
|
|
593
593
|
value={fields(component, prefix, component.type === "WidgetIMU" ? WIDGET_FIELDS.WidgetIMU : WIDGET_FIELDS.WidgetMag) as never}
|
|
594
594
|
persistKey={persist(component)}
|
|
595
595
|
onCalibrate={locked ? undefined : (cfg: number) => saveFields(prefix, ["Cfg"], { Cfg: cfg }, props.keys)}
|
|
596
|
+
onSaveCfg={locked ? undefined : (cfg: number) => saveFields(prefix, ["Cfg"], { Cfg: cfg }, props.keys)}
|
|
596
597
|
onRefresh={() => send("GET", "ModuleConfig", { CfgGroup: prefix })}
|
|
597
598
|
/>
|
|
598
599
|
{/if}
|
|
@@ -56,14 +56,18 @@
|
|
|
56
56
|
const measure = () => {
|
|
57
57
|
if (!alive) return
|
|
58
58
|
const widest = Math.max(0, ...[...element.children].map((child) => child.getBoundingClientRect().width))
|
|
59
|
-
/* сегменты равной ширины: самый широкий текст + отступы 2×12 (сжатые - 2×4), разделители и
|
|
60
|
-
buttonsNeed = options.length * (widest +
|
|
61
|
-
compactNeed = options.length * (widest +
|
|
59
|
+
/* сегменты равной ширины: самый широкий текст + отступы 2×12 (сжатые - 2×4), разделители и рамка; +2 на сегмент - запас на дробные пиксели (ширина места округляется до целых) */
|
|
60
|
+
buttonsNeed = options.length * (Math.ceil(widest) + 26) + options.length + 1
|
|
61
|
+
compactNeed = options.length * (Math.ceil(widest) + 10) + options.length + 1
|
|
62
62
|
}
|
|
63
63
|
measure()
|
|
64
|
-
/*
|
|
65
|
-
|
|
66
|
-
|
|
64
|
+
/* Шрифт подписей (полужирный) может догрузиться уже после замера, и document.fonts.ready к тому времени давно выполнен: перемер по изменению ширины блока замера */
|
|
65
|
+
const observer = typeof ResizeObserver === "undefined" ? undefined : new ResizeObserver(measure)
|
|
66
|
+
observer?.observe(element)
|
|
67
|
+
return () => {
|
|
68
|
+
alive = false
|
|
69
|
+
observer?.disconnect()
|
|
70
|
+
}
|
|
67
71
|
})
|
|
68
72
|
/* fitContent: ширину задают сами кнопки, сворачивать нечего */
|
|
69
73
|
const shownType = $derived(type === "buttons" && !fitContent && anchorWidth < compactNeed ? "select" : type)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!-- $lib/SensorReadout.svelte - показание датчика надписью: подпись мелко, число крупно моноширинными цифрами, единица рядом. Нет числа - дефис. Общее для WidgetAHRS, WidgetIMU, WidgetMag -->
|
|
1
|
+
<!-- $lib/SensorReadout.svelte - показание датчика надписью: подпись мелко, число крупно моноширинными цифрами, единица рядом. Нет числа - дефис. Общее для WidgetAHRS, WidgetIMU, WidgetMag; в виджете уже 384 px (контейнер) обычное число мельче и отступы меньше, чтобы длинные значения помещались -->
|
|
2
2
|
<script lang="ts">
|
|
3
3
|
let {
|
|
4
4
|
label,
|
|
@@ -21,11 +21,11 @@
|
|
|
21
21
|
|
|
22
22
|
const number = $derived(value === undefined || value === null || value === "" ? NaN : Number(value))
|
|
23
23
|
const text = $derived(Number.isFinite(number) ? number.toFixed(digits) : "-")
|
|
24
|
-
const valueClass = $derived(size === "lg" ? "text-[22px]" : size === "sm" ? "text-[13px]" : "text-[16px]")
|
|
24
|
+
const valueClass = $derived(size === "lg" ? "text-[22px]" : size === "sm" ? "text-[13px]" : "text-[16px] @max-sm:text-[14px]")
|
|
25
25
|
</script>
|
|
26
26
|
|
|
27
|
-
<div class="flex
|
|
28
|
-
<span class="w-full
|
|
27
|
+
<div class="flex flex-col items-center gap-0.5 rounded-[10px] border border-(--hairline-color) bg-(--back-color) px-2 py-1.5 @max-sm:px-1">
|
|
28
|
+
<span class="w-full text-center text-[11px] whitespace-nowrap text-(--muted-color)">{label}</span>
|
|
29
29
|
<span class="flex items-baseline gap-1 leading-tight">
|
|
30
30
|
<span class="font-semibold tabular-nums {valueClass}" style={color ? `color: ${color}` : undefined}>{text}</span>
|
|
31
31
|
{#if unit}<span class="text-[11px] text-(--muted-color)">{unit}</span>{/if}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
<!-- $lib/SensorSettings.svelte - настройки микросхемы датчика в WidgetIMU и WidgetMag: поля слова Cfg по описанию из sensorChips.ts (списки и переключатели), сворачиваемый раздел со сводкой в шапке. Раздел common идёт без заголовка, режим узла (gate) - первым полем строки узла, выключен - остальные поля скрыты; раздел из одних переключателей (оси) - одна группа кнопок рядом с полями предыдущего раздела. Правки локальные до «Сохранить»; биты, которых нет в описании, и режим (биты 0-1) не меняются. «По умолчанию» - заводское слово микросхемы с текущим режимом -->
|
|
2
|
+
<script lang="ts">
|
|
3
|
+
import { untrack } from "svelte"
|
|
4
|
+
import * as UI from "."
|
|
5
|
+
import { T } from "./locales/i18n"
|
|
6
|
+
import SectionHead from "./SectionHead.svelte"
|
|
7
|
+
import { hint } from "./hints"
|
|
8
|
+
import { bitFieldGet, bitFieldSet } from "./bitField"
|
|
9
|
+
import type { SensorChipField, SensorChipPart, SensorChipRead, SensorChipSection } from "./sensorChips"
|
|
10
|
+
|
|
11
|
+
type Switch = Extract<SensorChipField, { type: "switch" }>
|
|
12
|
+
/* Элемент сетки: одно поле (id - ключ в списке, label - ключ перевода подписи) или группа переключателей кнопками */
|
|
13
|
+
type Item =
|
|
14
|
+
{ kind: "field"; id: string; label: string; field: SensorChipField; section: SensorChipSection } | { kind: "flags"; name: string; fields: Switch[] }
|
|
15
|
+
|
|
16
|
+
let {
|
|
17
|
+
part,
|
|
18
|
+
cfg,
|
|
19
|
+
onSave,
|
|
20
|
+
hints = false,
|
|
21
|
+
}: {
|
|
22
|
+
part: SensorChipPart
|
|
23
|
+
cfg: unknown
|
|
24
|
+
/* Новое слово Cfg; без колбэка - только просмотр */
|
|
25
|
+
onSave?: (cfg: number) => void
|
|
26
|
+
/* Подсказки виджета включены кнопкой «?» */
|
|
27
|
+
hints?: boolean
|
|
28
|
+
} = $props()
|
|
29
|
+
|
|
30
|
+
let open = $state(false)
|
|
31
|
+
const incoming = $derived(cfg === undefined || cfg === null || cfg === "" ? undefined : Number(cfg) >>> 0)
|
|
32
|
+
/* Правки локальные: новое слово с устройства подхватывается, только пока правок нет */
|
|
33
|
+
let word = $state(untrack(() => incoming))
|
|
34
|
+
let saved = $state(untrack(() => incoming))
|
|
35
|
+
const isDirty = $derived(word !== saved)
|
|
36
|
+
$effect(() => {
|
|
37
|
+
const next = incoming
|
|
38
|
+
if (untrack(() => isDirty)) return
|
|
39
|
+
word = next
|
|
40
|
+
saved = next
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
const readOnly = $derived(!onSave || word === undefined)
|
|
44
|
+
const get = (field: SensorChipField) => (word === undefined ? undefined : bitFieldGet(word, field.start, field.end))
|
|
45
|
+
const set = (field: SensorChipField, value: unknown) => {
|
|
46
|
+
const number = Number(value)
|
|
47
|
+
if (word === undefined || !Number.isFinite(number)) return
|
|
48
|
+
word = normalize(bitFieldSet(word, field.start, field.end, number))
|
|
49
|
+
}
|
|
50
|
+
/* Чтение другого поля из слова: сначала свой раздел, потом остальные */
|
|
51
|
+
const readerOf =
|
|
52
|
+
(section: SensorChipSection, from: () => number | undefined = () => word): SensorChipRead =>
|
|
53
|
+
(key) => {
|
|
54
|
+
const source = from()
|
|
55
|
+
const other = section.fields.find((f) => f.key === key) ?? part.sections.flatMap((s) => s.fields).find((f) => f.key === key)
|
|
56
|
+
return other && source !== undefined ? bitFieldGet(source, other.start, other.end) : undefined
|
|
57
|
+
}
|
|
58
|
+
/* Недопустимый по даташиту выбор (available) заменяется ближайшим допустимым вариантом списка; два прохода - поля зависят друг от друга */
|
|
59
|
+
const normalize = (value: number) => {
|
|
60
|
+
let next = value
|
|
61
|
+
for (let pass = 0; pass < 2; pass++)
|
|
62
|
+
for (const section of part.sections)
|
|
63
|
+
for (const field of section.fields) {
|
|
64
|
+
if (field.type !== "select" || !field.available) continue
|
|
65
|
+
const read = readerOf(section, () => next)
|
|
66
|
+
const current = bitFieldGet(next, field.start, field.end)
|
|
67
|
+
if (field.available(current, read)) continue
|
|
68
|
+
const index = Math.max(
|
|
69
|
+
0,
|
|
70
|
+
field.options.findIndex((o) => o.value === current),
|
|
71
|
+
)
|
|
72
|
+
const nearest = field.options
|
|
73
|
+
.map((o, i) => ({ o, d: Math.abs(i - index) }))
|
|
74
|
+
.filter(({ o }) => field.available!(o.value, read))
|
|
75
|
+
.sort((a, b) => a.d - b.d)[0]
|
|
76
|
+
if (nearest) next = bitFieldSet(next, field.start, field.end, nearest.o.value)
|
|
77
|
+
}
|
|
78
|
+
return next
|
|
79
|
+
}
|
|
80
|
+
/* Поле показывается, если visible не запрещает */
|
|
81
|
+
const shown = (item: Item) => item.kind === "flags" || !item.field.visible || item.field.visible(readerOf(item.section))
|
|
82
|
+
/* Варианты списка, допустимые при текущих значениях других полей */
|
|
83
|
+
const choices = (field: Extract<SensorChipField, { type: "select" }>, section: SensorChipSection) =>
|
|
84
|
+
field.available ? field.options.filter((o) => field.available!(o.value, readerOf(section))) : field.options
|
|
85
|
+
/* Подпись варианта: @имя - перевод sensor.opt.<имя>, иначе как есть (числа с единицами) */
|
|
86
|
+
const optionName = (name: string) => (name.startsWith("@") ? $T(`sensor.opt.${name.slice(1)}`) : name)
|
|
87
|
+
type Select = Extract<SensorChipField, { type: "select" }>
|
|
88
|
+
const field = (section: SensorChipSection, field: SensorChipField): Item => ({
|
|
89
|
+
kind: "field",
|
|
90
|
+
id: `${section.name}-${field.key}`,
|
|
91
|
+
label: `sensor.field.${field.key}`,
|
|
92
|
+
field,
|
|
93
|
+
section,
|
|
94
|
+
})
|
|
95
|
+
/* Подпись варианта списка: format по другим полям или имя варианта; @имя - перевод */
|
|
96
|
+
const choiceName = (field: Select, section: SensorChipSection, value: number) =>
|
|
97
|
+
optionName(field.format ? field.format(value, readerOf(section)) : (field.options.find((o) => o.value === value)?.name ?? String(value)))
|
|
98
|
+
/* Группы сетки: заголовок - имя раздела (у common нет); gate - режим узла (gate: true), выключен - видно только его; раздел из одних переключателей - кнопки в группе предыдущего раздела */
|
|
99
|
+
const groups = $derived.by(() => {
|
|
100
|
+
const out: { title?: string; gate?: Select; items: Item[] }[] = []
|
|
101
|
+
for (const section of part.sections) {
|
|
102
|
+
const switches = section.fields.filter((field): field is Switch => field.type === "switch")
|
|
103
|
+
if (section.fields.length > 1 && switches.length === section.fields.length) {
|
|
104
|
+
const item: Item = { kind: "flags", name: section.name, fields: switches }
|
|
105
|
+
if (out.length) out[out.length - 1].items.push(item)
|
|
106
|
+
else out.push({ items: [item] })
|
|
107
|
+
continue
|
|
108
|
+
}
|
|
109
|
+
const title = section.name === "common" ? undefined : section.name
|
|
110
|
+
const gate = section.fields.find((f): f is Select => f.type === "select" && !!f.gate)
|
|
111
|
+
const items = section.fields.map((item) => field(section, item))
|
|
112
|
+
/* Раздел без заголовка после группы без заголовка (оси, потом общие) - в ту же группу */
|
|
113
|
+
const last = out[out.length - 1]
|
|
114
|
+
if (!title && !gate && last && !last.title && !last.gate) last.items.push(...items)
|
|
115
|
+
else out.push({ title, gate, items })
|
|
116
|
+
}
|
|
117
|
+
return out
|
|
118
|
+
})
|
|
119
|
+
/* Узел выключен: режим (gate) равен 0 */
|
|
120
|
+
const isOff = (group: { gate?: Select }) => !!group.gate && get(group.gate) === 0
|
|
121
|
+
/* Поля группы на экране: у выключенного узла - только режим */
|
|
122
|
+
const visibleItems = (group: { gate?: Select; items: Item[] }) =>
|
|
123
|
+
group.items.filter((item) => shown(item) && (!isOff(group) || (item.kind === "field" && item.field === group.gate)))
|
|
124
|
+
/* Подсказка поля: группа кнопок - по имени раздела, остальное - по ключу поля */
|
|
125
|
+
const hintText = (item: Item) => $T(item.kind === "flags" ? `sensor.hint.${item.name}` : `sensor.hint.${item.field.key}`)
|
|
126
|
+
/* Ширина ячейки поля: списки постоянной ширины, кнопки - шире, но не шире виджета (на узком месте сжимаются или становятся списком), переключатель по подписи */
|
|
127
|
+
const cellClass = (item: Item) =>
|
|
128
|
+
item.kind === "flags"
|
|
129
|
+
? "w-28 shrink-0"
|
|
130
|
+
: item.field.type === "switch"
|
|
131
|
+
? "shrink-0"
|
|
132
|
+
: item.field.type === "select" && item.field.buttons
|
|
133
|
+
? "w-72 max-w-full shrink-0"
|
|
134
|
+
: item.field.type === "select" && item.field.wide
|
|
135
|
+
? "w-40 shrink-0"
|
|
136
|
+
: "w-28 shrink-0"
|
|
137
|
+
const flagsOn = (fields: Switch[]) => fields.filter((field) => get(field) === 1).map((field) => field.key)
|
|
138
|
+
const flagsSet = (fields: Switch[], keys: string[]) => fields.forEach((field) => set(field, keys.includes(field.key) ? 1 : 0))
|
|
139
|
+
/* Сводка в шапке: поля brief (нет ни одного - все списки и числа с единицей) и группы кнопок; раздел с заголовком - короткое имя и значения, выключенный - «выкл.» */
|
|
140
|
+
const anyBrief = $derived(part.sections.some((section) => section.fields.some((field) => field.type !== "switch" && field.brief)))
|
|
141
|
+
const itemText = (item: Item) => {
|
|
142
|
+
if (item.kind === "flags") {
|
|
143
|
+
const on = item.fields.filter((field) => get(field) === 1).map((field) => field.short ?? field.key)
|
|
144
|
+
return `${$T(`sensor.section.${item.name}`)} ${on.length ? on.join(" ") : "-"}`
|
|
145
|
+
}
|
|
146
|
+
const { field } = item
|
|
147
|
+
const value = get(field)
|
|
148
|
+
if (value === undefined || field.type === "switch" || (anyBrief && !field.brief)) return undefined
|
|
149
|
+
return field.unit ? `${value} ${$T(`sensor.unit.${field.key}`)}` : choiceName(field, item.section, value)
|
|
150
|
+
}
|
|
151
|
+
const summary = $derived(
|
|
152
|
+
groups
|
|
153
|
+
.flatMap((group) => {
|
|
154
|
+
const short = group.title ? $T(`sensor.short.${group.title}`) : ""
|
|
155
|
+
if (isOff(group)) return [`${short} ${$T("sensor.off")}`]
|
|
156
|
+
const texts = visibleItems(group)
|
|
157
|
+
.map(itemText)
|
|
158
|
+
.filter((text): text is string => !!text)
|
|
159
|
+
return group.title && texts.length ? [`${short} ${texts.join(", ")}`] : texts
|
|
160
|
+
})
|
|
161
|
+
.join(" · "),
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
const save = () => {
|
|
165
|
+
if (!onSave || word === undefined) return
|
|
166
|
+
onSave(word)
|
|
167
|
+
saved = word
|
|
168
|
+
}
|
|
169
|
+
/* Заводское слово с текущим режимом: «По умолчанию» не останавливает и не запускает измерение */
|
|
170
|
+
const reset = () => {
|
|
171
|
+
if (word !== undefined) word = bitFieldSet(part.factory, 0, 1, bitFieldGet(word, 0, 1))
|
|
172
|
+
}
|
|
173
|
+
</script>
|
|
174
|
+
|
|
175
|
+
<div class="flex flex-col rounded-[10px] border border-(--hairline-color) bg-(--back-color)">
|
|
176
|
+
<div class="px-3 py-2" use:hint={{ text: $T("sensor.hint.settings"), enabled: hints }}><SectionHead title={$T("sensor.settings")} {summary} bind:open /></div>
|
|
177
|
+
{#if open}
|
|
178
|
+
<div class="flex flex-col gap-3 border-t border-(--hairline-color) p-3">
|
|
179
|
+
{#each groups as group, index (index)}
|
|
180
|
+
<div class="flex flex-col gap-2">
|
|
181
|
+
<!-- Поля плотно слева постоянной ширины (подпись целиком в одну строку), лишние уходят в следующий ряд; у выключенного узла - только режим -->
|
|
182
|
+
{#if group.title}<span class="text-[12px] font-semibold text-(--muted-color)">{$T(`sensor.section.${group.title}`)}</span>{/if}
|
|
183
|
+
<div class="flex flex-wrap items-end gap-x-3 gap-y-2">
|
|
184
|
+
{#each visibleItems(group) as item (item.kind === "flags" ? `flags-${item.name}` : item.id)}
|
|
185
|
+
<div class={cellClass(item)} use:hint={{ text: hintText(item), enabled: hints }}>
|
|
186
|
+
{#if item.kind === "flags"}
|
|
187
|
+
<UI.Select
|
|
188
|
+
type="buttons"
|
|
189
|
+
multiSelect
|
|
190
|
+
label={{ name: $T(`sensor.section.${item.name}`) }}
|
|
191
|
+
options={item.fields.map((field) => ({ id: `${item.name}-${field.key}`, name: field.short ?? field.key, value: field.key }))}
|
|
192
|
+
value={flagsOn(item.fields)}
|
|
193
|
+
disabled={readOnly}
|
|
194
|
+
onUpdate={(value) => flagsSet(item.fields, value as string[])}
|
|
195
|
+
/>
|
|
196
|
+
{:else if item.field.type === "switch"}
|
|
197
|
+
{@const field = item.field}
|
|
198
|
+
<UI.Switch
|
|
199
|
+
type="horizontal"
|
|
200
|
+
label={{ name: $T(item.label) }}
|
|
201
|
+
value={get(field) ?? 0}
|
|
202
|
+
disabled={readOnly}
|
|
203
|
+
onUpdate={(value) => set(field, value ? 1 : 0)}
|
|
204
|
+
/>
|
|
205
|
+
{:else if item.field.type === "select"}
|
|
206
|
+
{@const field = item.field}
|
|
207
|
+
<UI.Select
|
|
208
|
+
type={field.buttons ? "buttons" : "select"}
|
|
209
|
+
label={{ name: $T(item.label) }}
|
|
210
|
+
options={choices(field, item.section).map((o) => ({
|
|
211
|
+
id: `${field.key}-${o.value}`,
|
|
212
|
+
name: choiceName(field, item.section, o.value),
|
|
213
|
+
value: o.value,
|
|
214
|
+
}))}
|
|
215
|
+
value={get(field)}
|
|
216
|
+
disabled={readOnly || !!field.locked?.(readerOf(item.section))}
|
|
217
|
+
onUpdate={(value) => set(field, value)}
|
|
218
|
+
/>
|
|
219
|
+
{/if}
|
|
220
|
+
</div>
|
|
221
|
+
{/each}
|
|
222
|
+
</div>
|
|
223
|
+
</div>
|
|
224
|
+
{/each}
|
|
225
|
+
|
|
226
|
+
{#if onSave}
|
|
227
|
+
<div class="flex flex-col items-center gap-2">
|
|
228
|
+
<span class="text-[12px] text-(--muted-color) {isDirty ? '' : 'invisible'}">{$T("widget.common.unsaved")}</span>
|
|
229
|
+
<div class="flex w-full max-w-80 flex-wrap gap-2">
|
|
230
|
+
<UI.Button
|
|
231
|
+
wrapperClass="min-w-fit flex-1"
|
|
232
|
+
componentClass="px-2 whitespace-nowrap"
|
|
233
|
+
content={{ name: $T("sensor.default") }}
|
|
234
|
+
disabled={word === undefined}
|
|
235
|
+
onClick={reset}
|
|
236
|
+
/>
|
|
237
|
+
<UI.Button
|
|
238
|
+
wrapperClass="min-w-fit flex-1"
|
|
239
|
+
componentClass="px-2 whitespace-nowrap"
|
|
240
|
+
variant="primary"
|
|
241
|
+
content={{ name: $T("widget.common.save") }}
|
|
242
|
+
disabled={!isDirty}
|
|
243
|
+
onClick={save}
|
|
244
|
+
/>
|
|
245
|
+
</div>
|
|
246
|
+
</div>
|
|
247
|
+
{/if}
|
|
248
|
+
</div>
|
|
249
|
+
{/if}
|
|
250
|
+
</div>
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { SensorChipPart } from "./sensorChips";
|
|
2
|
+
type $$ComponentProps = {
|
|
3
|
+
part: SensorChipPart;
|
|
4
|
+
cfg: unknown;
|
|
5
|
+
onSave?: (cfg: number) => void;
|
|
6
|
+
hints?: boolean;
|
|
7
|
+
};
|
|
8
|
+
declare const SensorSettings: import("svelte").Component<$$ComponentProps, {}, "">;
|
|
9
|
+
type SensorSettings = ReturnType<typeof SensorSettings>;
|
|
10
|
+
export default SensorSettings;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
<!-- $lib/WidgetAHRS/Horizon.svelte - круглый авиагоризонт: небо и земля поворачиваются на крен и сдвигаются на тангаж, неподвижный силуэт в центре; шкала тангажа через 10°. Нет углов - серый круг -->
|
|
2
2
|
<script lang="ts">
|
|
3
|
+
import { PFD_COLORS } from "../WidgetPFD/pfdColors"
|
|
3
4
|
let { roll, pitch, size = 112 }: { roll: number | undefined; pitch: number | undefined; size?: number } = $props()
|
|
4
5
|
|
|
5
6
|
/* Сдвиг горизонта: 45° тангажа - радиус круга */
|
|
@@ -17,16 +18,16 @@
|
|
|
17
18
|
<g clip-path="url(#{id})">
|
|
18
19
|
{#if ok}
|
|
19
20
|
<g transform="rotate({-r}) translate(0 {p * PX_PER_DEG})" style="transition: transform 120ms linear">
|
|
20
|
-
<rect x="-150" y="-150" width="300" height="150" fill=
|
|
21
|
-
<rect x="-150" y="0" width="300" height="150" fill=
|
|
22
|
-
<line x1="-150" x2="150" y1="0" y2="0" stroke=
|
|
21
|
+
<rect x="-150" y="-150" width="300" height="150" fill={PFD_COLORS.sky} />
|
|
22
|
+
<rect x="-150" y="0" width="300" height="150" fill={PFD_COLORS.ground} />
|
|
23
|
+
<line x1="-150" x2="150" y1="0" y2="0" stroke={PFD_COLORS.mark} stroke-width="0.8" />
|
|
23
24
|
{#each [-30, -20, -10, 10, 20, 30] as deg (deg)}
|
|
24
25
|
<line
|
|
25
26
|
x1={deg % 20 === 0 ? -12 : -7}
|
|
26
27
|
x2={deg % 20 === 0 ? 12 : 7}
|
|
27
28
|
y1={-deg * PX_PER_DEG}
|
|
28
29
|
y2={-deg * PX_PER_DEG}
|
|
29
|
-
stroke=
|
|
30
|
+
stroke={PFD_COLORS.mark}
|
|
30
31
|
stroke-width="0.6"
|
|
31
32
|
opacity="0.8"
|
|
32
33
|
/>
|
|
@@ -37,6 +38,6 @@
|
|
|
37
38
|
{/if}
|
|
38
39
|
</g>
|
|
39
40
|
<circle r="48" fill="none" stroke="var(--hairline-color)" stroke-width="1.5" />
|
|
40
|
-
<path d="M-26 0H-9l3 4M26 0H9l-3 4" fill="none" stroke=
|
|
41
|
-
<circle r="1.8" fill=
|
|
41
|
+
<path d="M-26 0H-9l3 4M26 0H9l-3 4" fill="none" stroke={PFD_COLORS.symbol} stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" />
|
|
42
|
+
<circle r="1.8" fill={PFD_COLORS.symbol} />
|
|
42
43
|
</svg>
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
import SensorReadout from "../SensorReadout.svelte"
|
|
11
11
|
import AhrsIcon from "./AhrsIcon.svelte"
|
|
12
12
|
import Horizon from "./Horizon.svelte"
|
|
13
|
-
import { AHRS_ALGORITHMS, AHRS_PARAM_RANGES, ahrsAlgorithm, type AHRSParam } from "./ahrs"
|
|
13
|
+
import { AHRS_ALGORITHMS, AHRS_PARAM_RANGES, ahrsAlgorithm, roundToStep, type AHRSParam } from "./ahrs"
|
|
14
14
|
import { hint, hintsSetting } from "../hints"
|
|
15
15
|
import { accentStyle } from "../accent"
|
|
16
16
|
import { readPersistedCollapsed, writePersistedCollapsed } from "../widgetCollapse"
|
|
@@ -30,8 +30,15 @@
|
|
|
30
30
|
|
|
31
31
|
type Settings = Partial<Record<"Mode" | "MU" | AHRSParam, number>>
|
|
32
32
|
const SETTING_KEYS = ["Mode", "MU", ...(Object.keys(AHRS_PARAM_RANGES) as AHRSParam[])] as const
|
|
33
|
+
/* Параметры - с точностью шага поля: прошивка шлёт float32 */
|
|
33
34
|
const pickSettings = (data: Partial<IWidgetAHRSData>): Settings =>
|
|
34
|
-
Object.fromEntries(
|
|
35
|
+
Object.fromEntries(
|
|
36
|
+
SETTING_KEYS.filter((key) => data[key] !== undefined).map((key) => {
|
|
37
|
+
const number = Number(data[key])
|
|
38
|
+
const range = AHRS_PARAM_RANGES[key as AHRSParam]
|
|
39
|
+
return [key, range && Number.isFinite(number) ? roundToStep(number, range.step) : number]
|
|
40
|
+
}),
|
|
41
|
+
)
|
|
35
42
|
|
|
36
43
|
/* Правки локальные до «Сохранить»; новые значения с устройства подхватываются, только пока правок нет (углы идут потоком и не мешают) */
|
|
37
44
|
const incoming = $derived(pickSettings(value))
|
|
@@ -52,8 +59,8 @@
|
|
|
52
59
|
const num = (v: unknown) => (v === undefined || v === null || v === "" ? undefined : Number(v))
|
|
53
60
|
const roll = $derived(num(value.R))
|
|
54
61
|
const pitch = $derived(num(value.P))
|
|
55
|
-
/* Оценка ошибки есть только у ESKF
|
|
56
|
-
const
|
|
62
|
+
/* Оценка ошибки есть только у ESKF: у остальных алгоритмов в ряду дефисы (прошивка шлёт нули), ряд не пропадает и блок не прыгает */
|
|
63
|
+
const sigma = (v: unknown) => (algorithm?.sigma ? v : undefined)
|
|
57
64
|
|
|
58
65
|
const set = (key: keyof Settings, input: unknown) => {
|
|
59
66
|
const number = Number(input)
|
|
@@ -91,13 +98,11 @@
|
|
|
91
98
|
<SensorReadout label={$T("widget.ahrs.bias", { axis: "Y" })} value={value.BY} digits={3} unit="°/s" size="sm" />
|
|
92
99
|
<SensorReadout label={$T("widget.ahrs.bias", { axis: "Z" })} value={value.BZ} digits={3} unit="°/s" size="sm" />
|
|
93
100
|
</div>
|
|
94
|
-
{
|
|
95
|
-
<
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
</div>
|
|
100
|
-
{/if}
|
|
101
|
+
<div class="grid grid-cols-3 gap-1.5" use:hint={{ text: $T("widget.ahrs.hint.sigma"), enabled: $hints }}>
|
|
102
|
+
<SensorReadout label={$T("widget.ahrs.sigma", { angle: $T("widget.ahrs.roll") })} value={sigma(value.SR)} digits={2} unit="°" size="sm" />
|
|
103
|
+
<SensorReadout label={$T("widget.ahrs.sigma", { angle: $T("widget.ahrs.pitch") })} value={sigma(value.SP)} digits={2} unit="°" size="sm" />
|
|
104
|
+
<SensorReadout label={$T("widget.ahrs.sigma", { angle: $T("widget.ahrs.yaw") })} value={sigma(value.SY)} digits={2} unit="°" size="sm" />
|
|
105
|
+
</div>
|
|
101
106
|
</div>
|
|
102
107
|
</div>
|
|
103
108
|
|
|
@@ -126,23 +131,25 @@
|
|
|
126
131
|
</div>
|
|
127
132
|
|
|
128
133
|
{#if algorithm}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
134
|
+
<!-- Подпись поля - одна строка целиком (имя и единица мелко справа, пояснение - в подсказке): колонка не уже подписи, лишние поля уходят в следующий ряд, поля в ряду на одной высоте -->
|
|
135
|
+
<div class="grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2">
|
|
136
|
+
{#each algorithm.params as param (param)}
|
|
137
|
+
{@const range = AHRS_PARAM_RANGES[param]}
|
|
138
|
+
<div class="flex min-w-0 flex-col gap-1" use:hint={{ text: $T(`widget.ahrs.hint.${param}`), enabled: $hints }}>
|
|
139
|
+
<span class="flex min-w-0 items-baseline justify-center gap-1 px-1 text-[12px] leading-4 font-semibold">
|
|
140
|
+
<span class="whitespace-nowrap">{$T(`widget.ahrs.${param}`)}</span>
|
|
141
|
+
{#if range.unit}<span class="shrink-0 text-[11px] font-normal text-(--muted-color)">{range.unit}</span>{/if}
|
|
142
|
+
</span>
|
|
143
|
+
<UI.Input
|
|
144
|
+
type="number"
|
|
145
|
+
value={settings[param] ?? ""}
|
|
146
|
+
readonly={readOnly}
|
|
147
|
+
number={{ minNum: range.min, maxNum: range.max, step: range.step }}
|
|
148
|
+
onUpdate={(input) => set(param, input)}
|
|
149
|
+
/>
|
|
150
|
+
</div>
|
|
151
|
+
{/each}
|
|
152
|
+
</div>
|
|
146
153
|
{:else if settings.Mode !== undefined}
|
|
147
154
|
<span class="text-center text-[13px] text-(--muted-color)">{$T("widget.ahrs.unknown_mode", { mode: settings.Mode })}</span>
|
|
148
155
|
{/if}
|
|
@@ -150,9 +157,8 @@
|
|
|
150
157
|
|
|
151
158
|
{#if !readOnly}
|
|
152
159
|
<div class="flex flex-col items-center gap-2">
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
{/if}
|
|
160
|
+
<!-- Место под строку есть всегда: без правок она невидима, кнопка не прыгает -->
|
|
161
|
+
<span class="text-[12px] text-(--muted-color) {isDirty ? '' : 'invisible'}">{$T("widget.common.unsaved")}</span>
|
|
156
162
|
<UI.Button wrapperClass="w-40" variant="primary" content={{ name: $T("widget.common.save") }} disabled={!isDirty} onClick={save} />
|
|
157
163
|
</div>
|
|
158
164
|
{/if}
|
|
@@ -10,5 +10,7 @@ export declare const AHRS_PARAM_RANGES: Record<AHRSParam, {
|
|
|
10
10
|
min: number;
|
|
11
11
|
max: number;
|
|
12
12
|
step: number;
|
|
13
|
+
unit: string;
|
|
13
14
|
}>;
|
|
15
|
+
export declare const roundToStep: (value: number, step: number) => number;
|
|
14
16
|
export declare const ahrsAlgorithm: (mode: unknown) => IAHRSAlgorithm | undefined;
|
package/dist/WidgetAHRS/ahrs.js
CHANGED
|
@@ -5,19 +5,24 @@ export const AHRS_ALGORITHMS = [
|
|
|
5
5
|
{ mode: 2, name: "Mahony", params: ["KP", "KI", "AN", "AG", "KM"] },
|
|
6
6
|
{ mode: 3, name: "Madgwick", params: ["KB", "AN", "AG", "KM"] },
|
|
7
7
|
];
|
|
8
|
-
/* Диапазоны как в
|
|
8
|
+
/* Диапазоны как в прошивке (значение вне них устройство отклоняет) и единица - мелко рядом с подписью поля */
|
|
9
9
|
export const AHRS_PARAM_RANGES = {
|
|
10
|
-
TA: { min: 0.1, max: 30, step: 0.1 },
|
|
11
|
-
TM: { min: 0.1, max: 120, step: 0.1 },
|
|
12
|
-
GN: { min: 0.0001, max: 1, step: 0.0001 },
|
|
13
|
-
GB: { min: 0.00001, max: 1, step: 0.00001 },
|
|
14
|
-
AN: { min: 0.001, max: 1, step: 0.001 },
|
|
15
|
-
AG: { min: 0.01, max: 2, step: 0.01 },
|
|
16
|
-
MN: { min: 0.1, max: 180, step: 0.1 },
|
|
17
|
-
KP: { min: 0, max: 10, step: 0.01 },
|
|
18
|
-
KI: { min: 0, max: 1, step: 0.0001 },
|
|
19
|
-
KB: { min: 0, max: 1, step: 0.001 },
|
|
20
|
-
KM: { min: 0, max: 1, step: 0.0001 },
|
|
10
|
+
TA: { min: 0.1, max: 30, step: 0.1, unit: "s" },
|
|
11
|
+
TM: { min: 0.1, max: 120, step: 0.1, unit: "s" },
|
|
12
|
+
GN: { min: 0.0001, max: 1, step: 0.0001, unit: "°/s/√Hz" },
|
|
13
|
+
GB: { min: 0.00001, max: 1, step: 0.00001, unit: "°/s/√s" },
|
|
14
|
+
AN: { min: 0.001, max: 1, step: 0.001, unit: "g" },
|
|
15
|
+
AG: { min: 0.01, max: 2, step: 0.01, unit: "g" },
|
|
16
|
+
MN: { min: 0.1, max: 180, step: 0.1, unit: "°" },
|
|
17
|
+
KP: { min: 0, max: 10, step: 0.01, unit: "" },
|
|
18
|
+
KI: { min: 0, max: 1, step: 0.0001, unit: "" },
|
|
19
|
+
KB: { min: 0, max: 1, step: 0.001, unit: "" },
|
|
20
|
+
KM: { min: 0, max: 1, step: 0.0001, unit: "" },
|
|
21
|
+
};
|
|
22
|
+
/* Значение с устройства (float32) с точностью шага поля: 0.004999999888 - 0.005 */
|
|
23
|
+
export const roundToStep = (value, step) => {
|
|
24
|
+
const decimals = Math.max(0, Math.ceil(-Math.log10(step) - 1e-9));
|
|
25
|
+
return Number(value.toFixed(decimals));
|
|
21
26
|
};
|
|
22
27
|
/* Алгоритм по Mode; неизвестный - undefined (виджет показывает только выбор и углы) */
|
|
23
28
|
export const ahrsAlgorithm = (mode) => AHRS_ALGORITHMS.find((a) => a.mode === Number(mode));
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
<!-- $lib/WidgetIMU/AccelPoses.svelte - калибровка акселерометра по 6 положениям в WidgetIMU: какие положения записаны (биты ACP: +X, -X, +Y, -Y, +Z, -Z), кнопка «Записать положение» - слово Cfg с режимом 3; ось вверх или вниз прошивка определяет сама, после шестого положения сохраняет смещения и масштаб и сбрасывает ACP. Сворачиваемый раздел -->
|
|
2
|
+
<script lang="ts">
|
|
3
|
+
import * as UI from ".."
|
|
4
|
+
import { T } from "../locales/i18n"
|
|
5
|
+
import SectionHead from "../SectionHead.svelte"
|
|
6
|
+
import { hint } from "../hints"
|
|
7
|
+
import { bitFieldSet } from "../bitField"
|
|
8
|
+
|
|
9
|
+
let {
|
|
10
|
+
poses,
|
|
11
|
+
cfg,
|
|
12
|
+
onRecord,
|
|
13
|
+
onRefresh,
|
|
14
|
+
hints = false,
|
|
15
|
+
}: {
|
|
16
|
+
/* Биты записанных положений из прошивки (ACP) */
|
|
17
|
+
poses: unknown
|
|
18
|
+
cfg: unknown
|
|
19
|
+
/* Слово Cfg с режимом «записать положение»; без колбэка - только просмотр */
|
|
20
|
+
onRecord?: (cfg: number) => void
|
|
21
|
+
/* Перечитать настройки: прошивка присылает ACP только по запросу */
|
|
22
|
+
onRefresh?: () => void
|
|
23
|
+
hints?: boolean
|
|
24
|
+
} = $props()
|
|
25
|
+
|
|
26
|
+
/* Режим задачи драйвера «записать положение» (биты 0-1 Cfg) */
|
|
27
|
+
const POSE_MODE = 3
|
|
28
|
+
/* Запись: 0.5 с успокоения и 1 с отсчётов, перечитываем с запасом */
|
|
29
|
+
const RECORD_MS = 2500
|
|
30
|
+
const NAMES = ["+X", "-X", "+Y", "-Y", "+Z", "-Z"]
|
|
31
|
+
|
|
32
|
+
let open = $state(false)
|
|
33
|
+
let busy = $state(false)
|
|
34
|
+
const bits = $derived(Number(poses) || 0)
|
|
35
|
+
const done = $derived(NAMES.filter((_, i) => (bits >> i) & 1).length)
|
|
36
|
+
|
|
37
|
+
const record = () => {
|
|
38
|
+
if (!onRecord || busy || cfg === undefined || cfg === null || cfg === "") return
|
|
39
|
+
onRecord(bitFieldSet(Number(cfg) >>> 0, 0, 1, POSE_MODE))
|
|
40
|
+
busy = true
|
|
41
|
+
setTimeout(() => {
|
|
42
|
+
busy = false
|
|
43
|
+
onRefresh?.()
|
|
44
|
+
}, RECORD_MS)
|
|
45
|
+
}
|
|
46
|
+
</script>
|
|
47
|
+
|
|
48
|
+
<div class="flex flex-col rounded-[10px] border border-(--hairline-color) bg-(--back-color)">
|
|
49
|
+
<div class="px-3 py-2" use:hint={{ text: $T("widget.imu.hint.pose"), enabled: hints }}>
|
|
50
|
+
<SectionHead title={$T("widget.imu.pose.title")} summary={`${done} / 6`} bind:open />
|
|
51
|
+
</div>
|
|
52
|
+
{#if open}
|
|
53
|
+
<div class="flex flex-col gap-3 border-t border-(--hairline-color) p-3">
|
|
54
|
+
<span class="text-[12px] text-(--muted-color)">{$T("widget.imu.pose.howto")}</span>
|
|
55
|
+
<!-- Записанные положения залиты цветом виджета -->
|
|
56
|
+
<div class="grid grid-cols-6 gap-1.5">
|
|
57
|
+
{#each NAMES as name, index (name)}
|
|
58
|
+
{@const on = ((bits >> index) & 1) === 1}
|
|
59
|
+
<span
|
|
60
|
+
class="flex h-7 min-w-0 items-center justify-center rounded-[8px] border text-[13px] font-semibold tabular-nums {on
|
|
61
|
+
? 'border-transparent bg-(--accent-color) text-(--on-accent)'
|
|
62
|
+
: 'border-(--border-color) text-(--muted-color)'}"
|
|
63
|
+
>
|
|
64
|
+
{name}
|
|
65
|
+
</span>
|
|
66
|
+
{/each}
|
|
67
|
+
</div>
|
|
68
|
+
{#if onRecord}
|
|
69
|
+
<UI.Button
|
|
70
|
+
wrapperClass="w-full max-w-80 self-center"
|
|
71
|
+
componentClass="whitespace-nowrap"
|
|
72
|
+
variant="primary"
|
|
73
|
+
content={{ name: $T(busy ? "widget.imu.pose.recording" : "widget.imu.pose.record") }}
|
|
74
|
+
disabled={busy}
|
|
75
|
+
onClick={record}
|
|
76
|
+
/>
|
|
77
|
+
{/if}
|
|
78
|
+
</div>
|
|
79
|
+
{/if}
|
|
80
|
+
</div>
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
type $$ComponentProps = {
|
|
2
|
+
poses: unknown;
|
|
3
|
+
cfg: unknown;
|
|
4
|
+
onRecord?: (cfg: number) => void;
|
|
5
|
+
onRefresh?: () => void;
|
|
6
|
+
hints?: boolean;
|
|
7
|
+
};
|
|
8
|
+
declare const AccelPoses: import("svelte").Component<$$ComponentProps, {}, "">;
|
|
9
|
+
type AccelPoses = ReturnType<typeof AccelPoses>;
|
|
10
|
+
export default AccelPoses;
|