poe-svelte-ui-lib 3.15.0 → 3.15.2
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/LICENSE.md +3 -1
- package/README.md +8 -0
- package/dist/Button/Button.svelte +33 -1
- package/dist/GUIRenderer/GUIRenderer.svelte +0 -1
- package/dist/SectionHead.svelte +1 -1
- package/dist/WidgetFOC/README.md +2 -1
- package/dist/WidgetFOC/WidgetFOC.svelte +80 -68
- package/dist/WidgetHoming/README.md +2 -3
- package/dist/WidgetHoming/WidgetHoming.svelte +20 -25
- package/dist/WidgetHoming/WidgetHomingProps.svelte +1 -1
- package/dist/WidgetMap/README.md +5 -3
- package/dist/WidgetMap/mission/MapAgro.svelte +26 -5
- package/dist/WidgetMap/mission/MissionLayers.svelte +2 -1
- package/dist/WidgetMap/mission/coverage.d.ts +7 -1
- package/dist/WidgetMap/mission/coverage.js +86 -15
- package/dist/WidgetMap/mission/plan.d.ts +1 -0
- package/dist/WidgetMap/mission/plan.js +1 -0
- package/dist/locales/translations.d.ts +17 -7
- package/dist/locales/translations.js +27 -21
- package/dist/types.d.ts +0 -1
- package/package.json +1 -1
package/LICENSE.md
CHANGED
|
@@ -4,7 +4,9 @@ Version 1.0.0
|
|
|
4
4
|
© 2025 Oleg Perevyshin - All Rights Reserved
|
|
5
5
|
© 2025 Олег Перевышин - Все права защищены
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Автор и правообладатель - Олег Перевышин. Контакты - oleg.perevyshin@gmail.com, +375 (29) 352-18-40.
|
|
8
|
+
|
|
9
|
+
Author and copyright holder - Oleg Perevyshin. Contacts - oleg.perevyshin@gmail.com, +375 (29) 352-18-40.
|
|
8
10
|
|
|
9
11
|
---
|
|
10
12
|
|
package/README.md
CHANGED
|
@@ -481,6 +481,14 @@ const bridge = UI.createBusBridge(channel, {
|
|
|
481
481
|
- 🔍 В конструкторе иконку выбирают в окне с поиском по имени или категории.
|
|
482
482
|
- 👀 Весь каталог с именами виден на вкладке «Иконки» на главной витрины, клик по иконке копирует её SVG.
|
|
483
483
|
|
|
484
|
+
Служебные иконки кнопок, шапок и разделов лежат в `src/lib/libIcons` и экспортируются из `icons.ts` (`IconDelete`, `IconInfo`, `IconRestart` и другие); иконки приложений, например `DevCloud/src/lib/icons`, живут по тем же правилам.
|
|
485
|
+
|
|
486
|
+
- 📐 Плотность: viewBox 24, размер 1em. Контурные глифы и иконки разделов вписаны в оптическую коробку 20/24, метки (крест, плюс, стрелки, точки, грипы, галочки, гамбургер, стоп-квадрат) - в 14/24. Линия контура 1,7 после компенсации масштаба; залитые глифы только масштабируются.
|
|
487
|
+
- 🎨 Цвет только `currentColor`, вторичные элементы через `opacity`; жёстких цветов нет, исключение - брендовый Logo с градиентом.
|
|
488
|
+
- 🧩 Один смысл - один глиф на весь стек: информация - `IconInfo`, свои залитые копии в приложениях не заводят. Пары состояний и зеркала (Eye/EyeSlash, Plug/Unplug, стрелки вправо/влево) дублями не считаются.
|
|
489
|
+
- 🔍 Плотность новой иконки проверяют рендером и bbox глифа: вышла за коробку класса - правят масштаб обёртки, а не рисуют глиф заново.
|
|
490
|
+
- 🧪 Инструмент: `node scripts/icon-density/density.mjs audit | normalize | refine | sheet <png>` (sharp берётся из DevCloud). Порядок: audit, normalize, audit, refine, audit, sheet; листы до и после смотрят глазами, затем тесты, svelte-check, Sync и перезапуск dev-сервера потребителя.
|
|
491
|
+
|
|
484
492
|
<details>
|
|
485
493
|
<summary>🛡️ Безопасный вывод SVG и HTML</summary>
|
|
486
494
|
|
|
@@ -35,6 +35,25 @@
|
|
|
35
35
|
onClick?.()
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
/* Текст подтверждения: строки-пункты («- » или «• ») и **жирный**; всё экранируется до подстановки */
|
|
39
|
+
const confirmLines = $derived(
|
|
40
|
+
(confirm ?? "")
|
|
41
|
+
.split("\n")
|
|
42
|
+
.map((line) => line.trim())
|
|
43
|
+
.filter(Boolean)
|
|
44
|
+
.map((line) => {
|
|
45
|
+
const bullet = /^[-•]\s+/.test(line)
|
|
46
|
+
const warning = /^!\s*/.test(line)
|
|
47
|
+
const text = line.replace(/^[-•!]\s*/, "")
|
|
48
|
+
const html = text
|
|
49
|
+
.replace(/&/g, "&")
|
|
50
|
+
.replace(/</g, "<")
|
|
51
|
+
.replace(/>/g, ">")
|
|
52
|
+
.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
|
|
53
|
+
return { bullet, warning, html }
|
|
54
|
+
}),
|
|
55
|
+
)
|
|
56
|
+
|
|
38
57
|
let showInfo = $state(false)
|
|
39
58
|
const isIconOnly = $derived(!!content?.icon && !content.name?.trim())
|
|
40
59
|
/* Ширина в wrapperClass (w-8, size-10...) - кнопка-значок заполняет обёртку кругом, иначе она размером с поле (32px); w-auto/w-fit/w-max/w-min/w-full ширины не задают */
|
|
@@ -129,7 +148,20 @@
|
|
|
129
148
|
{#if confirm?.trim()}
|
|
130
149
|
<Modal title={content.name || content.info?.text || $T("widget.common.confirm")} bind:isOpen={asking} wrapperClass="w-md max-w-[95vw]">
|
|
131
150
|
{#snippet main()}
|
|
132
|
-
<
|
|
151
|
+
<div class="flex flex-col gap-2 text-left text-[14px]">
|
|
152
|
+
{#each confirmLines as line, i (i)}
|
|
153
|
+
{#if line.warning}
|
|
154
|
+
<p class="font-semibold text-(--orange-text)">{@html line.html}</p>
|
|
155
|
+
{:else if line.bullet}
|
|
156
|
+
<div class="flex gap-2">
|
|
157
|
+
<span class="shrink-0 text-(--muted-color)">•</span>
|
|
158
|
+
<span class="min-w-0">{@html line.html}</span>
|
|
159
|
+
</div>
|
|
160
|
+
{:else}
|
|
161
|
+
<p>{@html line.html}</p>
|
|
162
|
+
{/if}
|
|
163
|
+
{/each}
|
|
164
|
+
</div>
|
|
133
165
|
{/snippet}
|
|
134
166
|
{#snippet footer()}
|
|
135
167
|
<Self variant="primary" {accent} content={{ name: $T("widget.common.confirm") }} onClick={accept} />
|
|
@@ -610,7 +610,6 @@
|
|
|
610
610
|
value={fields(component, prefix, WIDGET_FIELDS.WidgetHoming) as never}
|
|
611
611
|
persistKey={persist(component)}
|
|
612
612
|
onSearch={locked ? undefined : () => send("SET", "MotionHome", { Search: 1 })}
|
|
613
|
-
onHome={locked ? undefined : () => send("SET", "MotionHome", {})}
|
|
614
613
|
onSave={locked ? undefined : (values) => saveFields(prefix, Object.keys(values) as (keyof typeof values)[], values, props.keys)}
|
|
615
614
|
onRefresh={() => send("GET", "ModuleConfig", { CfgGroup: prefix })}
|
|
616
615
|
/>
|
package/dist/SectionHead.svelte
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
{title}
|
|
17
17
|
</span>
|
|
18
18
|
{#if summary}
|
|
19
|
-
<span class="text-[12px] text-(--muted-color) tabular-nums
|
|
19
|
+
<span class="text-[12px] text-(--muted-color) tabular-nums">{summary}</span>
|
|
20
20
|
{/if}
|
|
21
21
|
</span>
|
|
22
22
|
<ExpandIcon
|
package/dist/WidgetFOC/README.md
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
|
|
7
7
|
- 🚦 Показывает, включён ли мотор, и флаги оси: ноль известен, выход в угол, калибровка нуля, занят процедурой, поток уставок прервался.
|
|
8
8
|
- 📐 Показывает угол вала, °, скорость, °/с, ток момента Iq, А, и напряжение Uq, В. Пока виджет раскрыт, данные обновляются раз в секунду.
|
|
9
|
-
- 🔌
|
|
9
|
+
- 🔌 Свич включения мотора с подписью положения «Включить» (клик по подписи тоже переключает) и чипы флагов стоят в главной шапке виджета и видны даже в свёрнутом виде; цвет свича берёт мастер-цвет компонента (пропс `accent`, переменные `--accent-*` на корне). Чип нуля («ноль известен»/«ноль не известен») живёт в разделе «Мотор» рядом с кнопкой поиска нуля. Без управления (`onEnable` не передан) шапка показывает точку и надпись состояния. Строка автонастройки одной высоты: подпись полосы, поле и кнопка «Автонастройка».
|
|
10
|
+
- 📋 Шапка каждого раздела показывает все доступные параметры группы без обрезки; в узкой колонке сводка переносится по строкам.
|
|
10
11
|
- 🧲 «Запустить поиск» рядом с полем «Ноль, эл. °» в разделе «Мотор» находит и сохраняет электрический ноль и направление датчика. Подтверждение показывает расчётный ход по числу пар полюсов, которое вернул привод. «Автонастройка» подбирает регуляторы на выбранную полосу. Обе команды требуют подтверждения, поскольку вал будет двигаться.
|
|
11
12
|
- ⚙️ Разделы настроек: мотор, пределы и режимы, контуры тока, скорости и угла, датчик тока и фильтры. Изменения сохраняются кнопкой «Сохранить», «Заводские» возвращают заводские настройки.
|
|
12
13
|
- 📏 Всё в градусах: угол, °, скорость, °/с, коэффициенты регулятора скорости - на °/с.
|
|
@@ -52,11 +52,12 @@
|
|
|
52
52
|
const flag = (bit: number) => flags !== undefined && (flags & bit) !== 0
|
|
53
53
|
const enabled = $derived(flag(0x01))
|
|
54
54
|
const busy = $derived(flag(0x04) || flag(0x20))
|
|
55
|
+
/* Чип нуля живёт в разделе «Мотор» рядом с поиском нуля, остальные - в шапке */
|
|
56
|
+
const zeroChip = $derived(flags === undefined ? null : flag(0x10) ? { key: "zero", color: "var(--green-text)" } : { key: "noZero", color: "var(--red-text)" })
|
|
55
57
|
const chips = $derived(
|
|
56
58
|
flags === undefined
|
|
57
59
|
? []
|
|
58
60
|
: [
|
|
59
|
-
flag(0x10) ? { key: "zero", color: "var(--green-text)" } : { key: "noZero", color: "var(--red-text)" },
|
|
60
61
|
...(flag(0x02) ? [{ key: "moving", color: "var(--blue-text)" }] : []),
|
|
61
62
|
...(flag(0x04) ? [{ key: "calibrating", color: "var(--purple-text)" }] : []),
|
|
62
63
|
...(flag(0x20) ? [{ key: "busy", color: "var(--purple-text)" }] : []),
|
|
@@ -154,7 +155,6 @@
|
|
|
154
155
|
const summaryOf = (fields: Field[]) =>
|
|
155
156
|
fields
|
|
156
157
|
.filter(available)
|
|
157
|
-
.slice(0, 4)
|
|
158
158
|
.map((f) => `${f.key} ${optionText(f, shown(f))}`)
|
|
159
159
|
.join(" · ")
|
|
160
160
|
|
|
@@ -211,7 +211,8 @@
|
|
|
211
211
|
</script>
|
|
212
212
|
|
|
213
213
|
{#snippet fieldCell(title: string, samples: string[], inset: string, content: Snippet)}
|
|
214
|
-
|
|
214
|
+
<!-- Колонка занимает всю ячейку сетки: все поля виджета одной ширины -->
|
|
215
|
+
<div class="w-full min-w-0">
|
|
215
216
|
<!-- Ширина строки зависит от подписи и текста поля, без стандартной ширины input браузера -->
|
|
216
217
|
<div class="pointer-events-none invisible h-0 overflow-hidden whitespace-nowrap" aria-hidden="true">
|
|
217
218
|
<div class="text-[12px] font-semibold">{title}</div>
|
|
@@ -226,7 +227,8 @@
|
|
|
226
227
|
{/snippet}
|
|
227
228
|
|
|
228
229
|
{#snippet numberField(f: Field)}
|
|
229
|
-
|
|
230
|
+
<!-- Запас по ширине под знак, дроби и стрелки: содержимое не упирается в край поля -->
|
|
231
|
+
{@render fieldCell(fieldName(f), [String(shown(f) ?? "0"), "-0000.00"], "1.5rem", input)}
|
|
230
232
|
{#snippet input()}
|
|
231
233
|
<UI.Input
|
|
232
234
|
type="number"
|
|
@@ -281,7 +283,8 @@
|
|
|
281
283
|
/>
|
|
282
284
|
</div>
|
|
283
285
|
{#if open[key]}
|
|
284
|
-
|
|
286
|
+
<!-- Равные колонки не уже 8rem: подписи и значения со стрелками помещаются, ряды выглядят ровно -->
|
|
287
|
+
<div class="grid items-end gap-x-3 gap-y-2 border-t border-(--hairline-color) p-3" style="grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr))">
|
|
285
288
|
{#each fields as f (f.key)}
|
|
286
289
|
{@render field(f)}
|
|
287
290
|
{/each}
|
|
@@ -297,61 +300,63 @@
|
|
|
297
300
|
class={twMerge("@container relative flex w-full flex-col gap-4 rounded-2xl border border-(--hairline-color) bg-(--container-color) p-4", wrapperClass)}
|
|
298
301
|
style={rootStyle}
|
|
299
302
|
>
|
|
300
|
-
<WidgetHeader icon={FOCIcon} label={label?.name || $T("widget.foc.title")} bind:collapsed {hints}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
<div class="flex flex-wrap items-center justify-between gap-2">
|
|
303
|
+
<WidgetHeader icon={FOCIcon} label={label?.name || $T("widget.foc.title")} bind:collapsed {hints}>
|
|
304
|
+
{#snippet right(narrow)}
|
|
305
|
+
<!-- Свич состояния и чипы флагов живут в шапке: видны и в свёрнутом виджете; цвет свича - мастер-цвет компонента (пропс accent) -->
|
|
306
|
+
<div class="flex flex-wrap items-center justify-end gap-2">
|
|
305
307
|
<div class="flex flex-wrap items-center gap-1.5 text-[12px]" use:hint={{ text: $T("widget.foc.hint.state"), enabled: $hints }}>
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
<
|
|
309
|
-
|
|
308
|
+
{#if onEnable}
|
|
309
|
+
<!-- Одна подпись положения «Включить», а не заголовок: шапка остаётся низкой; клик по подписи тоже переключает -->
|
|
310
|
+
<UI.Switch
|
|
311
|
+
wrapperClass="w-fit shrink-0"
|
|
312
|
+
label={{ captionRight: $T("widget.foc.enable") }}
|
|
313
|
+
value={enabled ? 1 : 0}
|
|
314
|
+
disabled={flags === undefined || (busy && !enabled)}
|
|
315
|
+
onUpdate={(v) => onEnable(!!v)}
|
|
316
|
+
/>
|
|
317
|
+
{:else}
|
|
318
|
+
<span class="flex items-center gap-2 text-[13px]">
|
|
319
|
+
<span class="size-2 rounded-full {busy ? 'animate-pulse' : ''}" style="background: {enabled ? 'var(--green-text)' : 'var(--faint-color)'}"></span>
|
|
320
|
+
{#if !narrow}
|
|
321
|
+
<span class="font-semibold">{flags === undefined ? "-" : $T(enabled ? "widget.foc.on" : "widget.foc.off")}</span>
|
|
322
|
+
{/if}
|
|
323
|
+
</span>
|
|
324
|
+
{/if}
|
|
310
325
|
{#each chips as chip (chip.key)}
|
|
311
326
|
<span class="rounded-full border border-(--hairline-color) px-2 py-0.5 whitespace-nowrap" style="color: {chip.color}">
|
|
312
327
|
{$T(`widget.foc.flag.${chip.key}`)}
|
|
313
328
|
</span>
|
|
314
329
|
{/each}
|
|
315
330
|
</div>
|
|
316
|
-
{#if onTune}
|
|
317
|
-
{@const tuneLabel = `${$T("widget.foc.field.TuneHz")}, ${$T("widget.foc.unit.hz")}`}
|
|
318
|
-
<div class="flex flex-wrap items-center gap-2" use:hint={{ text: $T("widget.foc.hint.tune"), enabled: $hints }}>
|
|
319
|
-
<div class="w-24 shrink-0">
|
|
320
|
-
{@render fieldCell(tuneLabel, [String(tuneShown)], "1.5rem", bandwidth)}
|
|
321
|
-
</div>
|
|
322
|
-
{#snippet bandwidth()}
|
|
323
|
-
<UI.Input
|
|
324
|
-
wrapperClass="w-24"
|
|
325
|
-
type="number"
|
|
326
|
-
label={{ name: tuneLabel }}
|
|
327
|
-
value={tuneShown}
|
|
328
|
-
number={{ minNum: 5, maxNum: 60, step: 1 }}
|
|
329
|
-
disabled={busy || tuneWait}
|
|
330
|
-
onUpdate={(v) => (tuneHz = Number(v))}
|
|
331
|
-
/>
|
|
332
|
-
{/snippet}
|
|
333
|
-
<UI.Button
|
|
334
|
-
wrapperClass="w-40"
|
|
335
|
-
variant="primary"
|
|
336
|
-
content={{ name: $T("widget.foc.tune") }}
|
|
337
|
-
disabled={!enabled || busy || tuneWait}
|
|
338
|
-
confirm={$T("widget.foc.tune.confirm")}
|
|
339
|
-
onClick={tune}
|
|
340
|
-
/>
|
|
341
|
-
</div>
|
|
342
|
-
{/if}
|
|
343
|
-
{#if onEnable}
|
|
344
|
-
<div use:hint={{ text: $T("widget.foc.hint.enable"), enabled: $hints }}>
|
|
345
|
-
<UI.Button
|
|
346
|
-
wrapperClass="w-32"
|
|
347
|
-
variant="primary"
|
|
348
|
-
content={{ name: $T(enabled ? "widget.foc.disable" : "widget.foc.enable") }}
|
|
349
|
-
disabled={flags === undefined || (busy && !enabled)}
|
|
350
|
-
onClick={() => onEnable(!enabled)}
|
|
351
|
-
/>
|
|
352
|
-
</div>
|
|
353
|
-
{/if}
|
|
354
331
|
</div>
|
|
332
|
+
{/snippet}
|
|
333
|
+
</WidgetHeader>
|
|
334
|
+
|
|
335
|
+
{#if !collapsed}
|
|
336
|
+
<div class="flex flex-col gap-4" transition:slide={{ duration: 150 }}>
|
|
337
|
+
{#if onTune}
|
|
338
|
+
{@const tuneLabel = `${$T("widget.foc.field.TuneHz")}, ${$T("widget.foc.unit.hz")}`}
|
|
339
|
+
<!-- Подпись полосы в строку с полем: вся строка одной высоты, центры совпадают -->
|
|
340
|
+
<div class="flex flex-wrap items-center gap-2" use:hint={{ text: $T("widget.foc.hint.tune"), enabled: $hints }}>
|
|
341
|
+
<span class="text-[12px] font-semibold whitespace-nowrap text-(--muted-color)">{tuneLabel}</span>
|
|
342
|
+
<UI.Input
|
|
343
|
+
wrapperClass="w-24"
|
|
344
|
+
type="number"
|
|
345
|
+
value={tuneShown}
|
|
346
|
+
number={{ minNum: 5, maxNum: 60, step: 1 }}
|
|
347
|
+
disabled={busy || tuneWait}
|
|
348
|
+
onUpdate={(v) => (tuneHz = Number(v))}
|
|
349
|
+
/>
|
|
350
|
+
<UI.Button
|
|
351
|
+
wrapperClass="w-40"
|
|
352
|
+
variant="primary"
|
|
353
|
+
content={{ name: $T("widget.foc.tune") }}
|
|
354
|
+
disabled={!enabled || busy || tuneWait}
|
|
355
|
+
confirm={$T("widget.foc.tune.confirm")}
|
|
356
|
+
onClick={tune}
|
|
357
|
+
/>
|
|
358
|
+
</div>
|
|
359
|
+
{/if}
|
|
355
360
|
|
|
356
361
|
<div class="grid grid-cols-2 gap-1.5 @[340px]:grid-cols-4" use:hint={{ text: $T("widget.foc.hint.readout"), enabled: $hints }}>
|
|
357
362
|
<SensorReadout label={$T("widget.foc.angle")} value={value.Ang} digits={1} unit="°" />
|
|
@@ -369,22 +374,29 @@
|
|
|
369
374
|
{/if}
|
|
370
375
|
|
|
371
376
|
{#snippet motorExtra()}
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
377
|
+
<!-- Ноль, поиск и чип - такие же ячейки сетки, как и остальные поля -->
|
|
378
|
+
{@render numberField({ key: "ZEA", unit: "edeg", readonly: true })}
|
|
379
|
+
{#if onZero}
|
|
380
|
+
<div use:hint={{ text: $T("widget.foc.hint.zero"), enabled: $hints }}>
|
|
381
|
+
<UI.Button
|
|
382
|
+
wrapperClass="w-full"
|
|
383
|
+
componentClass="px-3 whitespace-nowrap"
|
|
384
|
+
variant="primary"
|
|
385
|
+
content={{ name: $T("widget.foc.zero") }}
|
|
386
|
+
disabled={!enabled || busy}
|
|
387
|
+
confirm={`${$T("widget.foc.zero.confirm")}\n\n${zeroTravel}`}
|
|
388
|
+
onClick={onZero}
|
|
389
|
+
/>
|
|
390
|
+
</div>
|
|
391
|
+
{/if}
|
|
392
|
+
{#if zeroChip}
|
|
393
|
+
<!-- Обёртка высотой с кнопку: чип нуля стоит на одной центральной линии с поиском нуля и полем -->
|
|
394
|
+
<span class="flex h-8 items-center">
|
|
395
|
+
<span class="rounded-full border border-(--hairline-color) px-2 py-0.5 text-[12px] whitespace-nowrap" style="color: {zeroChip.color}">
|
|
396
|
+
{$T(`widget.foc.flag.${zeroChip.key}`)}
|
|
397
|
+
</span>
|
|
398
|
+
</span>
|
|
399
|
+
{/if}
|
|
388
400
|
{/snippet}
|
|
389
401
|
|
|
390
402
|
{@render section("motor", motorFields, motorExtra)}
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
# 🧱 WidgetHoming
|
|
2
2
|
|
|
3
|
-
База оси привода: как ищется база, нашлась ли она, где края и где вал сейчас.
|
|
3
|
+
База оси привода: как ищется база, нашлась ли она, где края и где вал сейчас. Кнопка «Домой» заново ищет базу и выводит ось домой, ниже - настройки поиска.
|
|
4
4
|
|
|
5
5
|
## ✨ Что умеет
|
|
6
6
|
|
|
7
|
-
-
|
|
8
|
-
- 🏠 Кнопка «Домой» отправляет отдельную команду движения в домашнюю точку. Для двух краёв дом - середина хода плюс смещение.
|
|
7
|
+
- 🏠 Одна кнопка «Домой» в главной шапке виджета (видна и в свёрнутом виде): всегда заново ищет базу выбранным способом (по двум упорам, одной метке датчика или датчикам) и выводит ось домой с учётом смещения - независимо от того, была ли база найдена раньше. Подтверждение сразу по сути: поиск только при включённом моторе, как пойдёт ось, и для упоров - усилие «Force, %» из настроек. Для двух краёв дом - середина хода плюс смещение.
|
|
9
8
|
- 📏 Для двух краёв виджет показывает полосу хода, рабочую зону, дом и текущее положение оси. Для одного датчика видны его координата и состояние.
|
|
10
9
|
- 🚦 Показывает способ поиска и состояние: не искали, идёт поиск, база найдена или отказ с причиной текстом.
|
|
11
10
|
- ⏳ Пока идёт поиск, раз в секунду перечитывает настройки устройства и кончает ожидание по ответу прошивки.
|
|
@@ -26,7 +26,6 @@
|
|
|
26
26
|
collapsed = $bindable(false),
|
|
27
27
|
persistKey,
|
|
28
28
|
onSearch,
|
|
29
|
-
onHome,
|
|
30
29
|
onSave,
|
|
31
30
|
onRefresh,
|
|
32
31
|
}: IWidgetHomingProps = $props()
|
|
@@ -186,7 +185,26 @@
|
|
|
186
185
|
class={twMerge("@container relative flex w-full flex-col gap-4 rounded-2xl border border-(--hairline-color) bg-(--container-color) p-4", wrapperClass)}
|
|
187
186
|
style={rootStyle}
|
|
188
187
|
>
|
|
189
|
-
<WidgetHeader icon={HomingIcon} label={label?.name || $T("widget.home.title")} bind:collapsed {hints}
|
|
188
|
+
<WidgetHeader icon={HomingIcon} label={label?.name || $T("widget.home.title")} bind:collapsed {hints}>
|
|
189
|
+
{#snippet right(narrow)}
|
|
190
|
+
<!-- Команда оси в главной шапке: видна и в свёрнутом виджете -->
|
|
191
|
+
<div class="flex flex-wrap items-center justify-end gap-2">
|
|
192
|
+
{#if onSearch}
|
|
193
|
+
<!-- «Домой» всегда заново ищет базу выбранным способом и выводит ось домой с учётом смещения -->
|
|
194
|
+
<div use:hint={{ text: $T("widget.home.hint.search"), enabled: $hints }}>
|
|
195
|
+
<UI.Button
|
|
196
|
+
wrapperClass="w-40"
|
|
197
|
+
variant="primary"
|
|
198
|
+
content={{ name: $T("widget.home.goHome") }}
|
|
199
|
+
disabled={busy || !onSearch || (!singleSensor && !hasBase)}
|
|
200
|
+
confirm={$T(`widget.home.search.confirm.${mode}`, { 0: shown("Force") ?? 100 })}
|
|
201
|
+
onClick={search}
|
|
202
|
+
/>
|
|
203
|
+
</div>
|
|
204
|
+
{/if}
|
|
205
|
+
</div>
|
|
206
|
+
{/snippet}
|
|
207
|
+
</WidgetHeader>
|
|
190
208
|
|
|
191
209
|
{#if !collapsed}
|
|
192
210
|
<div class="flex flex-col gap-4" transition:slide={{ duration: 150 }}>
|
|
@@ -205,10 +223,6 @@
|
|
|
205
223
|
<SensorReadout label={$T("widget.home.sensorPos")} value={value.SensorPos} {unit} />
|
|
206
224
|
</div>
|
|
207
225
|
<span>{$T("widget.home.sensor")}: {value.Sensor === undefined ? "-" : $T(value.Sensor ? "widget.home.active" : "widget.home.free")}</span>
|
|
208
|
-
<div class="flex flex-wrap gap-2">
|
|
209
|
-
{#if onSearch}<UI.Button content={{ name: $T("widget.home.search") }} disabled={busy} onClick={search} />{/if}
|
|
210
|
-
{#if onHome}<UI.Button content={{ name: $T("widget.home.goHome") }} disabled={!found || busy} onClick={onHome} />{/if}
|
|
211
|
-
</div>
|
|
212
226
|
{#if errText}<span class="text-(--red-text)">{errText}</span>{/if}
|
|
213
227
|
{:else}
|
|
214
228
|
<div class="flex flex-wrap items-center justify-between gap-2" use:hint={{ text: $T("widget.home.hint.state"), enabled: $hints }}>
|
|
@@ -234,25 +248,6 @@
|
|
|
234
248
|
: "-"}
|
|
235
249
|
</span>
|
|
236
250
|
</span>
|
|
237
|
-
<div class="flex flex-wrap gap-2">
|
|
238
|
-
{#if onHome}
|
|
239
|
-
<div use:hint={{ text: $T("widget.home.hint.home"), enabled: $hints }}>
|
|
240
|
-
<UI.Button wrapperClass="w-32" variant="secondary" content={{ name: $T("widget.home.goHome") }} disabled={busy} onClick={onHome} />
|
|
241
|
-
</div>
|
|
242
|
-
{/if}
|
|
243
|
-
{#if onSearch && hasBase}
|
|
244
|
-
<div use:hint={{ text: $T("widget.home.hint.search"), enabled: $hints }}>
|
|
245
|
-
<UI.Button
|
|
246
|
-
wrapperClass="w-40"
|
|
247
|
-
variant="primary"
|
|
248
|
-
content={{ name: $T("widget.home.search") }}
|
|
249
|
-
disabled={busy}
|
|
250
|
-
confirm={$T(`widget.home.search.confirm.${!twoSensors && method?.key === "stall" ? "stall" : "other"}`)}
|
|
251
|
-
onClick={search}
|
|
252
|
-
/>
|
|
253
|
-
</div>
|
|
254
|
-
{/if}
|
|
255
|
-
</div>
|
|
256
251
|
</div>
|
|
257
252
|
{#if errText}
|
|
258
253
|
<span class="text-[12px] text-(--red-text)">{errText}</span>
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
<UI.Select
|
|
28
28
|
type="buttons"
|
|
29
29
|
label={{ name: $T("widget.home.mode") }}
|
|
30
|
-
options={(["
|
|
30
|
+
options={(["rotarySensor", "rotary", "linear", "linearSensors"] as const).map((mode) => ({
|
|
31
31
|
id: mode,
|
|
32
32
|
value: mode,
|
|
33
33
|
name: $T(`widget.home.mode.${mode}`),
|
package/dist/WidgetMap/README.md
CHANGED
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
|
|
48
48
|
- 🌐 Для карты нужен интернет. Без него видна заглушка «Карта не загружена».
|
|
49
49
|
- 📡 Карта только показывает и ничего не отправляет на устройство. Исключение - кнопка «Отправить» в режимах миссии.
|
|
50
|
-
- 🎨 Цвет виджета красит кнопки, линию маршрута, точки, точку взлёта, переходы и аппарат в имитации. Цвета со смыслом не меняются: поля зелёные, запретные зоны красные, развороты оранжевые, удаление и ошибки красные.
|
|
50
|
+
- 🎨 Цвет виджета красит кнопки, линию маршрута, точки, точку взлёта, переходы и аппарат в имитации. Цвета со смыслом не меняются: поля зелёные, проходы - мастер-цвет, запретные зоны красные, развороты оранжевые, удаление и ошибки красные.
|
|
51
51
|
- 📐 Ширина карты равна ширине контейнера. В сетке конструктора виджет занимает одну строку.
|
|
52
52
|
- 📦 Сворачивание и кнопка «?» с подсказками работают как у других смарт-виджетов.
|
|
53
53
|
- 🤝 Имена полей общие с пилотажным дисплеем `WidgetPFD` и `WidgetDeviceInfo`: одна отправка телеметрии кормит все три.
|
|
@@ -131,7 +131,7 @@ configureMapLibre({ module: "/maplibre-gl.mjs", css: "/maplibre-gl.css", styles:
|
|
|
131
131
|
|
|
132
132
|
- **Подложка.** Стили CARTO (Voyager для светлой темы, Dark Matter для тёмной) на данных OpenStreetMap. Указывать источник обязательно, подпись свёрнута в кнопку «i» в углу карты.
|
|
133
133
|
- Сворачивание, мастер-цвет и кнопка «?» с подсказками работают как у `WidgetWiFi`.
|
|
134
|
-
- Мастер-цвет (`accent`) красит весь виджет: кнопки, линию маршрута, точки, точку взлёта, переходы и аппарат в имитации. Цвета со смыслом не меняются: поля зелёные, запретные зоны красные, развороты оранжевые, «Очистить», удаление и ошибка отправки красные.
|
|
134
|
+
- Мастер-цвет (`accent`) красит весь виджет: кнопки, линию маршрута, точки, точку взлёта, переходы и аппарат в имитации. Цвета со смыслом не меняются: поля зелёные, проходы - мастер-цвет, запретные зоны красные, развороты оранжевые, «Очистить», удаление и ошибка отправки красные.
|
|
135
135
|
|
|
136
136
|
</details>
|
|
137
137
|
|
|
@@ -226,7 +226,7 @@ configureMapLibre({ module: "/maplibre-gl.mjs", css: "/maplibre-gl.css", styles:
|
|
|
226
226
|
<details>
|
|
227
227
|
<summary>🔬 Как устроено: «Авторасчёт»</summary>
|
|
228
228
|
|
|
229
|
-
У каждого поля свой угол проходов. Новое поле сразу получает лучший угол по быстрой оценке. «Авторасчёт» пересчитывает углы всех полей приближениями по полному расчёту траектории: шаг 5° по всем направлениям и вдоль сторон поля, затем 1° около трёх лучших, затем 0,1° около победителя. Лучший угол даёт наименьшую цену:
|
|
229
|
+
У каждого поля свой угол проходов. Новое поле сразу получает лучший угол по быстрой оценке. «Авторасчёт» пересчитывает углы всех полей приближениями по полному расчёту траектории: шаг 5° по всем направлениям и вдоль сторон поля, затем 1° около трёх лучших, затем 0,1° около победителя. Лучший угол даёт наименьшую цену: проходы и развороты на скорости распыления, переходы на скорости переходов, разворот ≈ захват/скорость + 2 с, плюс штраф за недолив (метр недолитого прохода стоит как три метра полёта); переход от взлёта и возврат домой входят в цену.
|
|
230
230
|
|
|
231
231
|
Пока идёт расчёт, на карте видно колесо ожидания «Расчёт оптимального маршрута» с полосой и процентом (на большом поле это несколько секунд). Кнопка «i» справа от «Авторасчёта» открывает подробное описание алгоритма: проходы, ячейки, порядок облёта, штрафы и поиск угла приближениями. Текст лежит в словаре под ключом `widget.mission.autoInfo`.
|
|
232
232
|
|
|
@@ -246,6 +246,8 @@ configureMapLibre({ module: "/maplibre-gl.mjs", css: "/maplibre-gl.css", styles:
|
|
|
246
246
|
- 🔀 Части и поля облетаются в таком порядке, чтобы пустых перелётов было как можно меньше.
|
|
247
247
|
- 🌳 Развороты и перелёты огибают запретные зоны.
|
|
248
248
|
- 💧 Распылитель работает только на проходах. На разворотах и перелётах он выключен.
|
|
249
|
+
- 🛫 Первый проход идёт вдоль линии поля со стороны взлёта (без взлёта - со стороны длинной стороны); порядок остальных ячеек оптимизируется от него.
|
|
250
|
+
- ⏩ Скорость переходов задаётся отдельно от скорости распыления и попадает в миссию QGC командами DO_CHANGE_SPEED; в оценке времени переходы считаются на своей скорости.
|
|
249
251
|
- 🧭 Направление проходов у каждого поля своё. Карта подбирает его сама, чтобы поле обрабатывалось быстрее и полнее.
|
|
250
252
|
|
|
251
253
|
Маршрут пересчитывается сразу, как только вы что-то меняете: двигаете точку, меняете ширину захвата или угол.
|
|
@@ -210,7 +210,12 @@
|
|
|
210
210
|
searching = 0
|
|
211
211
|
try {
|
|
212
212
|
for (const [k, contour] of contours.entries()) {
|
|
213
|
-
const angle = await searchFieldAngle(contour, plan.holes, plan.spacing, plan.margin, plan.speed,
|
|
213
|
+
const angle = await searchFieldAngle(contour, plan.holes, plan.spacing, plan.margin, plan.speed, {
|
|
214
|
+
start: plan.start,
|
|
215
|
+
returnHome: plan.returnHome,
|
|
216
|
+
transitSpeed: plan.transitSpeed,
|
|
217
|
+
onProgress: (f) => (searching = (k + f) / contours.length),
|
|
218
|
+
})
|
|
214
219
|
/* Контур могли изменить или удалить, пока шёл подбор - тогда угол не ставится */
|
|
215
220
|
if (fieldList.some((f) => f.contour === contour)) update({ fields: fieldList.map((f) => (f.contour === contour ? { ...f, angle } : f)) })
|
|
216
221
|
}
|
|
@@ -228,7 +233,15 @@
|
|
|
228
233
|
)
|
|
229
234
|
if (!result) return null
|
|
230
235
|
const total = result.sprayLength + result.turnLength + result.transitLength
|
|
231
|
-
|
|
236
|
+
/* Время: проходы и развороты на скорости распыления, переходы - на своей; разворот ≈ захват/скорость + 2 с */
|
|
237
|
+
const vTransit = plan.transitSpeed ?? plan.speed
|
|
238
|
+
const timeMin =
|
|
239
|
+
plan.speed > 0
|
|
240
|
+
? ((result.sprayLength + result.turnLength) / plan.speed +
|
|
241
|
+
result.transitLength / Math.max(0.1, vTransit) +
|
|
242
|
+
result.turns * (plan.spacing / plan.speed + 2)) /
|
|
243
|
+
60
|
|
244
|
+
: 0
|
|
232
245
|
const liquid = (area / 10000) * plan.rate
|
|
233
246
|
const coverage = area > 0 ? Math.min(100, ((result.sprayLength * plan.spacing) / area) * 100) : 0
|
|
234
247
|
return {
|
|
@@ -254,12 +267,13 @@
|
|
|
254
267
|
$effect(() => sim.setPath(simPath))
|
|
255
268
|
let simPath = $derived.by(() => {
|
|
256
269
|
if (!result?.waypoints.length) return []
|
|
257
|
-
const
|
|
270
|
+
const vTransit = plan.transitSpeed ?? plan.speed
|
|
271
|
+
const out = [{ point: result.waypoints[0].point, alt: plan.alt, speed: vTransit, spray: false }]
|
|
258
272
|
for (const seg of result.segments)
|
|
259
273
|
seg.points.forEach((pt, i) => {
|
|
260
274
|
const prev = out[out.length - 1].point
|
|
261
275
|
if (i === 0 && Math.abs(prev[0] - pt[0]) < 1e-9 && Math.abs(prev[1] - pt[1]) < 1e-9) return
|
|
262
|
-
out.push({ point: pt, alt: plan.alt, speed: plan.speed, spray: seg.kind === "spray" && i > 0 })
|
|
276
|
+
out.push({ point: pt, alt: plan.alt, speed: seg.kind === "spray" ? plan.speed : vTransit, spray: seg.kind === "spray" && i > 0 })
|
|
263
277
|
})
|
|
264
278
|
return out
|
|
265
279
|
})
|
|
@@ -339,6 +353,7 @@
|
|
|
339
353
|
? toMission(result, plan.start ?? fields[0][0], {
|
|
340
354
|
alt: plan.alt,
|
|
341
355
|
speed: plan.speed,
|
|
356
|
+
transitSpeed: plan.transitSpeed,
|
|
342
357
|
spray: plan.sprayControl,
|
|
343
358
|
servo: { channel: plan.servoChannel, on: plan.servoOn, off: plan.servoOff },
|
|
344
359
|
returnHome: plan.returnHome,
|
|
@@ -578,6 +593,12 @@
|
|
|
578
593
|
</div>
|
|
579
594
|
<Input type="number" label={{ name: $T("widget.mission.alt") }} {...numField("alt", 1, 200, 0.5)} />
|
|
580
595
|
<Input type="number" label={{ name: $T("widget.mission.speed") }} {...numField("speed", 0.5, 30, 0.5)} />
|
|
596
|
+
<Input
|
|
597
|
+
type="number"
|
|
598
|
+
label={{ name: $T("widget.mission.transitSpeed") }}
|
|
599
|
+
{...numField("transitSpeed", 0.5, 30, 0.5)}
|
|
600
|
+
value={plan.transitSpeed ?? plan.speed}
|
|
601
|
+
/>
|
|
581
602
|
</div>
|
|
582
603
|
<label class="flex items-center gap-2 text-[13px]">
|
|
583
604
|
<input type="checkbox" checked={plan.returnHome} onchange={(e) => update({ returnHome: e.currentTarget.checked })} />
|
|
@@ -750,7 +771,7 @@
|
|
|
750
771
|
<span class="text-(--muted-color)">{$T("widget.mission.waypoints")}</span><span class="text-right font-semibold">{stats.waypoints}</span>
|
|
751
772
|
</div>
|
|
752
773
|
<div class="flex flex-wrap gap-3 text-[11px] text-(--muted-color)">
|
|
753
|
-
<span class="flex items-center gap-1"><span class="h-0.5 w-4 bg-(--
|
|
774
|
+
<span class="flex items-center gap-1"><span class="h-0.5 w-4 bg-(--accent-color)"></span>{$T("widget.mission.legendSpray")}</span>
|
|
754
775
|
<span class="flex items-center gap-1"><span class="h-0.5 w-4 bg-(--orange-mark)"></span>{$T("widget.mission.legendTurn")}</span>
|
|
755
776
|
<span class="flex items-center gap-1">
|
|
756
777
|
<span class="h-0.5 w-4 border-t-2 border-dashed border-(--accent-text)"></span>{$T("widget.mission.legendTransit")}
|
|
@@ -31,7 +31,8 @@
|
|
|
31
31
|
"msn-zones-line": { "line-color": byKind },
|
|
32
32
|
"msn-path-transit": { "line-color": c.line },
|
|
33
33
|
"msn-path-turn": { "line-color": c.orange },
|
|
34
|
-
|
|
34
|
+
/* Проходы - мастер-цвет: контур поля остаётся зелёным, траектория читается отдельно */
|
|
35
|
+
"msn-path-spray": { "line-color": c.accent },
|
|
35
36
|
"msn-path-route": { "line-color": c.line },
|
|
36
37
|
"msn-draft-line": { "line-color": byKind },
|
|
37
38
|
"msn-highlight-fill": { "fill-color": byKind },
|
|
@@ -44,11 +44,17 @@ export declare const holesOf: (field: LngLat[], holes: LngLat[][]) => LngLat[][]
|
|
|
44
44
|
export declare const fieldsArea: (fields: LngLat[][], holes: LngLat[][]) => number;
|
|
45
45
|
export declare const planFields: (input: IFieldsInput) => ICoverageResult | null;
|
|
46
46
|
export declare const bestFieldAngle: (contour: LngLat[], holes: LngLat[][], spacing: number, margin: number) => number;
|
|
47
|
-
export declare const searchFieldAngle: (contour: LngLat[], holes: LngLat[][], spacing: number, margin: number, speed: number,
|
|
47
|
+
export declare const searchFieldAngle: (contour: LngLat[], holes: LngLat[][], spacing: number, margin: number, speed: number, opts?: {
|
|
48
|
+
start?: LngLat;
|
|
49
|
+
returnHome?: boolean;
|
|
50
|
+
transitSpeed?: number;
|
|
51
|
+
onProgress?: (fraction: number) => void;
|
|
52
|
+
}) => Promise<number>;
|
|
48
53
|
export type SprayControl = "none" | "sprayer" | "servo";
|
|
49
54
|
export interface IMissionExport {
|
|
50
55
|
alt: number;
|
|
51
56
|
speed: number;
|
|
57
|
+
transitSpeed?: number;
|
|
52
58
|
spray: SprayControl;
|
|
53
59
|
servo?: {
|
|
54
60
|
channel: number;
|
|
@@ -414,10 +414,11 @@ const exitOf = (cell, v) => {
|
|
|
414
414
|
return [p.x1, p.y];
|
|
415
415
|
};
|
|
416
416
|
/* Порядок ячеек: точный перебор (Хелд-Карп) до 10 ячеек, иначе жадный выбор с улучшением 2-opt */
|
|
417
|
-
const orderCells = (cells, cost, start) => {
|
|
417
|
+
const orderCells = (cells, cost, start, forceFirst) => {
|
|
418
418
|
const n = cells.length;
|
|
419
419
|
if (!n)
|
|
420
420
|
return [];
|
|
421
|
+
const vIdx = (v) => (v.fromTop ? 2 : 0) + (v.fromRight ? 1 : 0);
|
|
421
422
|
const variants = cells.map((_, i) => [false, true].flatMap((fromTop) => [false, true].map((fromRight) => ({ cell: i, fromTop, fromRight }))));
|
|
422
423
|
const entries = variants.map((vs) => vs.map((v) => entryOf(cells[v.cell], v)));
|
|
423
424
|
const exits = variants.map((vs) => vs.map((v) => exitOf(cells[v.cell], v)));
|
|
@@ -427,9 +428,14 @@ const orderCells = (cells, cost, start) => {
|
|
|
427
428
|
const dp = new Float64Array(full * n * 4).fill(Infinity);
|
|
428
429
|
const par = new Int32Array(full * n * 4).fill(-1);
|
|
429
430
|
const at = (mask, i, k) => (mask * n + i) * 4 + k;
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
431
|
+
/* Первый проход закреплён за линией поля: перебор стартует только с разрешённых вариантов */
|
|
432
|
+
if (forceFirst?.length)
|
|
433
|
+
for (const f of forceFirst)
|
|
434
|
+
dp[at(1 << f.cell, f.cell, vIdx(f))] = startCost(f.cell, vIdx(f));
|
|
435
|
+
else
|
|
436
|
+
for (let i = 0; i < n; i++)
|
|
437
|
+
for (let k = 0; k < 4; k++)
|
|
438
|
+
dp[at(1 << i, i, k)] = startCost(i, k);
|
|
433
439
|
/* Стоимости всех переходов «выход варианта k ячейки i - вход варианта l ячейки j» заранее, числами: перебор обращается к ним сотни тысяч раз */
|
|
434
440
|
const m = n * 4;
|
|
435
441
|
const trans = new Float64Array(m * m);
|
|
@@ -484,15 +490,25 @@ const orderCells = (cells, cost, start) => {
|
|
|
484
490
|
let pos = start;
|
|
485
491
|
for (let step = 0; step < n; step++) {
|
|
486
492
|
let best = null;
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
for (let k = 0; k < 4; k++) {
|
|
493
|
+
const cands = step === 0 && forceFirst?.length ? forceFirst.map((f) => ({ i: f.cell, k: vIdx(f) })) : null;
|
|
494
|
+
if (cands) {
|
|
495
|
+
for (const { i, k } of cands) {
|
|
491
496
|
const c = pos ? cost(pos, entries[i][k]) : 0;
|
|
492
497
|
if (!best || c < best.c)
|
|
493
498
|
best = { i, k, c };
|
|
494
499
|
}
|
|
495
500
|
}
|
|
501
|
+
else {
|
|
502
|
+
for (let i = 0; i < n; i++) {
|
|
503
|
+
if (used[i])
|
|
504
|
+
continue;
|
|
505
|
+
for (let k = 0; k < 4; k++) {
|
|
506
|
+
const c = pos ? cost(pos, entries[i][k]) : 0;
|
|
507
|
+
if (!best || c < best.c)
|
|
508
|
+
best = { i, k, c };
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
496
512
|
used[best.i] = true;
|
|
497
513
|
order.push(variants[best.i][best.k]);
|
|
498
514
|
pos = exits[best.i][best.k];
|
|
@@ -514,7 +530,8 @@ const orderCells = (cells, cost, start) => {
|
|
|
514
530
|
let bestCost = tourCost(order);
|
|
515
531
|
for (let improved = true, guard = 0; improved && guard < 50; guard++) {
|
|
516
532
|
improved = false;
|
|
517
|
-
|
|
533
|
+
/* Первый проход закреплён за линией поля: 2-opt не трогает первую ячейку */
|
|
534
|
+
for (let i = forceFirst?.length ? 1 : 0; i < order.length - 1; i++) {
|
|
518
535
|
for (let j = i + 1; j < order.length; j++) {
|
|
519
536
|
const cand = [
|
|
520
537
|
...order.slice(0, i),
|
|
@@ -693,7 +710,40 @@ export const planCoverage = (input) => {
|
|
|
693
710
|
const r = router.route(a, b);
|
|
694
711
|
return r.len === Infinity ? 1e9 + dist(a, b) : r.len;
|
|
695
712
|
};
|
|
696
|
-
|
|
713
|
+
/* Первый проход - вдоль линии поля: крайний ряд со стороны взлёта, без взлёта - со стороны длинной стороны */
|
|
714
|
+
let forceFirst;
|
|
715
|
+
if (rows.length) {
|
|
716
|
+
const ys = field.map((p) => p[1]);
|
|
717
|
+
const lo = Math.min(...ys);
|
|
718
|
+
const hi = Math.max(...ys);
|
|
719
|
+
let sideTop;
|
|
720
|
+
if (startP)
|
|
721
|
+
sideTop = startP[1] >= (lo + hi) / 2;
|
|
722
|
+
else {
|
|
723
|
+
let bestLen = -1;
|
|
724
|
+
let midY = (lo + hi) / 2;
|
|
725
|
+
for (let i = 0; i < field.length; i++) {
|
|
726
|
+
const a = field[i];
|
|
727
|
+
const b = field[(i + 1) % field.length];
|
|
728
|
+
const l = dist(a, b);
|
|
729
|
+
if (l > bestLen) {
|
|
730
|
+
bestLen = l;
|
|
731
|
+
midY = (a[1] + b[1]) / 2;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
sideTop = midY >= (lo + hi) / 2;
|
|
735
|
+
}
|
|
736
|
+
const extremeY = sideTop ? rows[rows.length - 1].y : rows[0].y;
|
|
737
|
+
const forced = cells.flatMap((c, i) => c.lines.some((l) => l.y === extremeY)
|
|
738
|
+
? [
|
|
739
|
+
{ cell: i, fromTop: sideTop, fromRight: false },
|
|
740
|
+
{ cell: i, fromTop: sideTop, fromRight: true },
|
|
741
|
+
]
|
|
742
|
+
: []);
|
|
743
|
+
if (forced.length)
|
|
744
|
+
forceFirst = forced;
|
|
745
|
+
}
|
|
746
|
+
const order = orderCells(cells, routeCost, startP, forceFirst);
|
|
697
747
|
const segments = [];
|
|
698
748
|
const toLL = (ps) => ps.map(proj.inv);
|
|
699
749
|
let sprayLength = 0;
|
|
@@ -844,20 +894,33 @@ export const planFields = (input) => {
|
|
|
844
894
|
/* Лучший угол для одного поля с учётом его зон, округлён до 0.5° */
|
|
845
895
|
export const bestFieldAngle = (contour, holes, spacing, margin) => Math.round(optimizeAngle({ field: contour, holes: holesOf(contour, holes), angle: 0, spacing, margin }) * 2) / 2;
|
|
846
896
|
/* Подбор угла поля приближениями по полному расчёту траектории: шаг 5° по всем 180° и направления сторон поля, затем шаг 1° около трёх лучших, затем 0.1° около победителя. Мерило - время облёта: путь со скоростью плюс около 4 с на разворот, недопокрытая площадь штрафуется. Считается частями, чтобы интерфейс не замирал */
|
|
847
|
-
export const searchFieldAngle = async (contour, holes, spacing, margin, speed,
|
|
897
|
+
export const searchFieldAngle = async (contour, holes, spacing, margin, speed, opts) => {
|
|
848
898
|
const own = holesOf(contour, holes);
|
|
849
899
|
const area = fieldArea(contour, own);
|
|
850
900
|
const norm = (a) => Math.round((((a % 180) + 180) % 180) * 10) / 10;
|
|
851
901
|
const cache = new Map();
|
|
902
|
+
const vSpray = Math.max(0.1, speed);
|
|
903
|
+
const vTransit = Math.max(0.1, opts?.transitSpeed ?? speed);
|
|
904
|
+
/* Разворот тем дольше, чем шире захват: пролёт поперёк полосы плюс остановка и разворот на месте */
|
|
905
|
+
const turnTime = spacing / vSpray + 2;
|
|
852
906
|
const cost = (a) => {
|
|
853
907
|
const key = norm(a);
|
|
854
908
|
const hit = cache.get(key);
|
|
855
909
|
if (hit !== undefined)
|
|
856
910
|
return hit;
|
|
857
|
-
const r = planCoverage({
|
|
911
|
+
const r = planCoverage({
|
|
912
|
+
field: contour,
|
|
913
|
+
holes: own,
|
|
914
|
+
angle: key,
|
|
915
|
+
spacing,
|
|
916
|
+
margin,
|
|
917
|
+
start: opts?.start,
|
|
918
|
+
returnHome: opts?.returnHome,
|
|
919
|
+
home: opts?.start,
|
|
920
|
+
});
|
|
858
921
|
/* Недопокрытая площадь штрафуется: недолитый метр прохода стоит как трёхкратный полёт по нему - за ним пришлось бы возвращаться */
|
|
859
922
|
const missed = r ? Math.max(0, area / spacing - r.sprayLength) : 0;
|
|
860
|
-
const c = r ? (r.sprayLength + r.turnLength +
|
|
923
|
+
const c = r ? (r.sprayLength + r.turnLength + missed * 3) / vSpray + r.transitLength / vTransit + r.turns * turnTime + r.unreachable * 1e6 : Infinity;
|
|
861
924
|
cache.set(key, c);
|
|
862
925
|
return c;
|
|
863
926
|
};
|
|
@@ -882,7 +945,7 @@ export const searchFieldAngle = async (contour, holes, spacing, margin, speed, o
|
|
|
882
945
|
for (const a of angles) {
|
|
883
946
|
cost(a);
|
|
884
947
|
done++;
|
|
885
|
-
onProgress?.(Math.min(1, done / stages));
|
|
948
|
+
opts?.onProgress?.(Math.min(1, done / stages));
|
|
886
949
|
await yieldUi();
|
|
887
950
|
}
|
|
888
951
|
};
|
|
@@ -900,7 +963,7 @@ export const searchFieldAngle = async (contour, holes, spacing, margin, speed, o
|
|
|
900
963
|
let best = [...cache.entries()].reduce((m, e) => (e[1] < m[1] ? e : m))[0];
|
|
901
964
|
await run(Array.from({ length: 11 }, (_, i) => norm(best - 0.5 + i * 0.1)));
|
|
902
965
|
best = [...cache.entries()].reduce((m, e) => (e[1] < m[1] ? e : m))[0];
|
|
903
|
-
onProgress?.(1);
|
|
966
|
+
opts?.onProgress?.(1);
|
|
904
967
|
return best;
|
|
905
968
|
};
|
|
906
969
|
/* Миссия и номера команд её точек маршрута: по ним прогресс считается из WPNum телеметрии */
|
|
@@ -923,9 +986,17 @@ export const toMission = (res, home, opt) => {
|
|
|
923
986
|
sprayRow(false);
|
|
924
987
|
let spraying = false;
|
|
925
988
|
let sprayOnLeg = false;
|
|
989
|
+
/* Переходы без распыления летятся своей скоростью: смена скорости перед точкой начала отрезка */
|
|
990
|
+
const vTransit = opt.transitSpeed ?? opt.speed;
|
|
991
|
+
let legSpeed = opt.speed;
|
|
926
992
|
for (const wp of res.waypoints) {
|
|
927
993
|
nav.push({ point: wp.point, seq, spray: sprayOnLeg });
|
|
928
994
|
sprayOnLeg = wp.spray;
|
|
995
|
+
const want = wp.spray ? opt.speed : vTransit;
|
|
996
|
+
if (want !== legSpeed) {
|
|
997
|
+
legSpeed = want;
|
|
998
|
+
row(0, 3, 178, [1, legSpeed, -1, 0], [0, 0], 0);
|
|
999
|
+
}
|
|
929
1000
|
row(0, 3, 16, [0, 0, 0, 0], wp.point, opt.alt);
|
|
930
1001
|
if (wp.spray !== spraying) {
|
|
931
1002
|
spraying = wp.spray;
|
|
@@ -2224,12 +2224,22 @@ declare const translations: {
|
|
|
2224
2224
|
en: string;
|
|
2225
2225
|
zh: string;
|
|
2226
2226
|
};
|
|
2227
|
-
"widget.home.search.confirm.
|
|
2227
|
+
"widget.home.search.confirm.rotary": {
|
|
2228
2228
|
ru: string;
|
|
2229
2229
|
en: string;
|
|
2230
2230
|
zh: string;
|
|
2231
2231
|
};
|
|
2232
|
-
"widget.home.search.confirm.
|
|
2232
|
+
"widget.home.search.confirm.rotarySensor": {
|
|
2233
|
+
ru: string;
|
|
2234
|
+
en: string;
|
|
2235
|
+
zh: string;
|
|
2236
|
+
};
|
|
2237
|
+
"widget.home.search.confirm.linear": {
|
|
2238
|
+
ru: string;
|
|
2239
|
+
en: string;
|
|
2240
|
+
zh: string;
|
|
2241
|
+
};
|
|
2242
|
+
"widget.home.search.confirm.linearSensors": {
|
|
2233
2243
|
ru: string;
|
|
2234
2244
|
en: string;
|
|
2235
2245
|
zh: string;
|
|
@@ -2449,11 +2459,6 @@ declare const translations: {
|
|
|
2449
2459
|
en: string;
|
|
2450
2460
|
zh: string;
|
|
2451
2461
|
};
|
|
2452
|
-
"widget.home.hint.home": {
|
|
2453
|
-
ru: string;
|
|
2454
|
-
en: string;
|
|
2455
|
-
zh: string;
|
|
2456
|
-
};
|
|
2457
2462
|
"widget.home.hint.range": {
|
|
2458
2463
|
ru: string;
|
|
2459
2464
|
en: string;
|
|
@@ -2889,6 +2894,11 @@ declare const translations: {
|
|
|
2889
2894
|
en: string;
|
|
2890
2895
|
zh: string;
|
|
2891
2896
|
};
|
|
2897
|
+
"widget.mission.transitSpeed": {
|
|
2898
|
+
ru: string;
|
|
2899
|
+
en: string;
|
|
2900
|
+
zh: string;
|
|
2901
|
+
};
|
|
2892
2902
|
"widget.mission.returnHome": {
|
|
2893
2903
|
ru: string;
|
|
2894
2904
|
en: string;
|
|
@@ -953,15 +953,25 @@ const translations = {
|
|
|
953
953
|
"widget.home.st.failed": { ru: "отказ", en: "failed", zh: "失败" },
|
|
954
954
|
"widget.home.search": { ru: "Найти базу", en: "Find home", zh: "查找基准" },
|
|
955
955
|
"widget.home.goHome": { ru: "Домой", en: "Go home", zh: "回原点" },
|
|
956
|
-
"widget.home.search.confirm.
|
|
957
|
-
ru: "Поиск
|
|
958
|
-
en: "
|
|
959
|
-
zh: "
|
|
960
|
-
},
|
|
961
|
-
"widget.home.search.confirm.
|
|
962
|
-
ru: "Поиск
|
|
963
|
-
en: "
|
|
964
|
-
zh: "
|
|
956
|
+
"widget.home.search.confirm.rotary": {
|
|
957
|
+
ru: "Поиск идёт только при включённом моторе.\n- Ось идёт в минус до упора, потом в плюс до упора.\n- Дом - центр между упорами плюс смещение.\n- Усилие в упоре - **{0}%** от полного.\n!Проверьте посторонние предметы на пути и натяжение проводов.",
|
|
958
|
+
en: "Search runs only with the motor enabled.\n- The axis goes minus to a stop, then plus to a stop.\n- Home is the center between the stops plus the offset.\n- Push force at the stop is **{0}%** of full.\n!Check for foreign objects on the path and cable tension.",
|
|
959
|
+
zh: "搜索仅在电机启用时进行。\n- 轴向负向运动到限位,再向正向到限位。\n- 原点为两限位中心加偏移。\n- 顶住限位的力为满力矩的 **{0}%**。\n!检查路径上的异物和线缆张紧情况。",
|
|
960
|
+
},
|
|
961
|
+
"widget.home.search.confirm.rotarySensor": {
|
|
962
|
+
ru: "Поиск идёт только при включённом моторе.\n- Ось крутится в заданную сторону до метки датчика.\n- Отъезд и повторный подход на малой скорости.\n- Дом - метка плюс смещение.\n!Проверьте посторонние предметы на пути и натяжение проводов.",
|
|
963
|
+
en: "Search runs only with the motor enabled.\n- The axis turns in the set direction until the sensor index.\n- Back off and re-approach at fine speed.\n- Home is the index plus the offset.\n!Check for foreign objects on the path and cable tension.",
|
|
964
|
+
zh: "搜索仅在电机启用时进行。\n- 轴沿设定方向旋转直到传感器标记。\n- 退回并以慢速重新接近。\n- 原点为标记加偏移。\n!检查路径上的异物和线缆张紧情况。",
|
|
965
|
+
},
|
|
966
|
+
"widget.home.search.confirm.linear": {
|
|
967
|
+
ru: "Поиск идёт только при включённом моторе.\n- Ось идёт в заданную сторону до датчика.\n- Отъезд и повторный подход на малой скорости.\n- Дом - координата датчика плюс смещение.\n!Проверьте посторонние предметы на пути и натяжение проводов.",
|
|
968
|
+
en: "Search runs only with the motor enabled.\n- The axis moves in the set direction until the sensor.\n- Back off and re-approach at fine speed.\n- Home is the sensor coordinate plus the offset.\n!Check for foreign objects on the path and cable tension.",
|
|
969
|
+
zh: "搜索仅在电机启用时进行。\n- 轴沿设定方向运动直到传感器。\n- 退回并以慢速重新接近。\n- 原点为传感器坐标加偏移。\n!检查路径上的异物和线缆张紧情况。",
|
|
970
|
+
},
|
|
971
|
+
"widget.home.search.confirm.linearSensors": {
|
|
972
|
+
ru: "Поиск идёт только при включённом моторе.\n- Ось по очереди находит оба датчика с отъездом и повторным подходом.\n- Дом - середина между датчиками плюс смещение.\n!Проверьте посторонние предметы на пути и натяжение проводов.",
|
|
973
|
+
en: "Search runs only with the motor enabled.\n- The axis finds both sensors in turn, with back off and re-approach.\n- Home is the midpoint between the sensors plus the offset.\n!Check for foreign objects on the path and cable tension.",
|
|
974
|
+
zh: "搜索仅在电机启用时进行。\n- 轴依次查找两个传感器,均退回并重新接近。\n- 原点为两传感器中点加偏移。\n!检查路径上的异物和线缆张紧情况。",
|
|
965
975
|
},
|
|
966
976
|
"widget.home.err.noStop": {
|
|
967
977
|
ru: "Край не найден: ось прошла больше оборота",
|
|
@@ -985,9 +995,9 @@ const translations = {
|
|
|
985
995
|
},
|
|
986
996
|
"widget.home.homePoint": { ru: "Дом", en: "Home", zh: "原点" },
|
|
987
997
|
"widget.home.mode": { ru: "Режим базирования", en: "Homing mode", zh: "回原点模式" },
|
|
988
|
-
"widget.home.mode.rotary": { ru: "Поворотная · два упора", en: "Rotary · two stops", zh: "旋转轴 · 双限位" },
|
|
989
|
-
"widget.home.mode.rotarySensor": { ru: "Поворотная · одна метка", en: "Rotary · one index", zh: "旋转轴 ·
|
|
990
|
-
"widget.home.mode.linearSensors": { ru: "Линейная · два датчика", en: "Linear · two sensors", zh: "直线轴 · 双传感器" },
|
|
998
|
+
"widget.home.mode.rotary": { ru: "Поворотная ось · два упора", en: "Rotary axis · two stops", zh: "旋转轴 · 双限位" },
|
|
999
|
+
"widget.home.mode.rotarySensor": { ru: "Поворотная ось · одна метка датчика", en: "Rotary axis · one sensor index", zh: "旋转轴 · 单传感器标记" },
|
|
1000
|
+
"widget.home.mode.linearSensors": { ru: "Линейная ось · два датчика", en: "Linear axis · two sensors", zh: "直线轴 · 双传感器" },
|
|
991
1001
|
"widget.home.hint.twoSensors": {
|
|
992
1002
|
ru: "Направление задаёт первый датчик. Скорость используется при поиске, отъезд освобождает каждый датчик, доводка задаёт скорость повторного подхода. После повторного срабатывания обоих датчиков ось выходит в середину между их координатами с учётом смещения дома. Расстояния в миллиметрах.",
|
|
993
1003
|
en: "The axis finds both sensors and moves to their midpoint plus the home offset. Distances are in millimeters.",
|
|
@@ -998,7 +1008,7 @@ const translations = {
|
|
|
998
1008
|
en: "Search for the index in the selected direction, back off and approach again at fine speed. Angles are in degrees.",
|
|
999
1009
|
zh: "轴沿指定方向查找标记,退回后再慢速接近。角度单位为度。",
|
|
1000
1010
|
},
|
|
1001
|
-
"widget.home.mode.linear": { ru: "Линейная · один датчик", en: "Linear · one sensor", zh: "直线轴 · 单传感器" },
|
|
1011
|
+
"widget.home.mode.linear": { ru: "Линейная ось · один датчик", en: "Linear axis · one sensor", zh: "直线轴 · 单传感器" },
|
|
1002
1012
|
"widget.home.axisPos": { ru: "Положение оси", en: "Axis position", zh: "轴位置" },
|
|
1003
1013
|
"widget.home.sensorPos": { ru: "Координата датчика", en: "Sensor position", zh: "传感器位置" },
|
|
1004
1014
|
"widget.home.sensor": { ru: "Датчик", en: "Sensor", zh: "传感器" },
|
|
@@ -1042,11 +1052,6 @@ const translations = {
|
|
|
1042
1052
|
en: "**Find home** - the axis finds both ends by itself and smoothly goes home\n**When needed** - once at assembly and after the axis is rebuilt: the ends are saved in the device\n**While searching** - motion commands from the bus are not executed",
|
|
1043
1053
|
zh: "**查找基准** - 轴自行找到两个端点并平稳回到原点\n**何时需要** - 装配时和轴重新装配后一次:端点保存在设备中\n**搜索期间** - 不执行总线上的运动命令",
|
|
1044
1054
|
},
|
|
1045
|
-
"widget.home.hint.home": {
|
|
1046
|
-
ru: "**Домой** - ось плавно едет в центр между краями плюс «Дом от центра»\n**Без базы** - в угол «Дом от центра» от нуля датчика",
|
|
1047
|
-
en: '**Go home** - the axis smoothly moves to the center between the ends plus "Home from center"\n**Without a home** - to the "Home from center" angle from the sensor zero',
|
|
1048
|
-
zh: "**回原点** - 轴平稳移动到两端点中心加「原点偏移」\n**无基准时** - 移动到距传感器零点「原点偏移」角度处",
|
|
1049
|
-
},
|
|
1050
1055
|
"widget.home.hint.range": {
|
|
1051
1056
|
ru: "**Полоса** - разрешённый ход от края Lo до края Hi\n**Зелёное** - где ось работает, без отступов от краёв\n**Синяя черта** - дом\n**Кружок** - вал сейчас, красный - за краем\n**Центр** - середина хода между упорами. Смещение «Дом от центра» учитывается отдельно синей меткой\n**От центра** - кратчайшая угловая разность между положением вала и центром. Знак плюс означает поворот в сторону увеличения угла датчика",
|
|
1052
1057
|
en: "**Bar** - allowed travel from end Lo to end Hi\n**Green** - where the axis works, without the margins\n**Blue line** - home\n**Circle** - the shaft now, red - beyond an end\n**Center** - midpoint of travel between the stops. The blue home marker includes the home offset\n**From center** - shortest signed angle from center to shaft. Positive follows increasing sensor angle",
|
|
@@ -1233,9 +1238,9 @@ const translations = {
|
|
|
1233
1238
|
"widget.mission.showOnMap": { ru: "Показать на карте", en: "Show on the map", zh: "在地图上显示" },
|
|
1234
1239
|
"widget.mission.autoInfoTitle": { ru: "Как работает авторасчёт", en: "How auto-calculate works", zh: "自动计算的原理" },
|
|
1235
1240
|
"widget.mission.autoInfo": {
|
|
1236
|
-
ru: "Авторасчёт подбирает для каждого поля направление проходов, при котором поле обрабатывается быстрее всего и как можно полнее. Ниже по шагам, как это устроено.\n\n## 🗺️ 1. Подготовка\n- Карта вокруг поля переводится в плоскость в метрах. Для полей размером в несколько километров ошибка такого перевода незаметна.\n- Поле поворачивается так, чтобы проходы шли слева направо. Дальше всё считается в этой повёрнутой системе.\n- Запретная зона может лежать внутри поля, выходить за его край или стоять вне полей. Полю она мешает, если задевает его, а перелётам мешает всегда.\n\n## 🚜 2. Проходы\n- Проходы идут параллельно с шагом не больше ширины захвата.\n- Первый и последний проходы стоят на расстоянии отступа от края поля. Остальные распределяются между ними поровну, поэтому соседние проходы могут слегка перекрываться, но не оставляют просветов.\n- Проход должен быть свободен по всей своей ширине: от его оси в обе стороны на величину отступа не должно быть ни края поля, ни запретной зоны.\n- Концы прохода укорачиваются на отступ от границы. Куски короче четверти захвата отбрасываются, но порог не меньше 1 м.\n- 💧 Распылитель работает только на проходах. На разворотах и переходах он выключен.\n\n## 🧩 3. Ячейки\n- Если запретная зона или вырез разрезает проходы на части, поле делится на ячейки. Внутри ячейки проходы идут подряд змейкой и соединяются один к одному.\n- Ячейку можно начать четырьмя способами: с первого или последнего прохода и с левого или правого конца.\n\n## 🔀 4. Порядок облёта\n- Ищется порядок ячеек и способ входа в каждую, при котором путь между ними самый короткий.\n- До 10 ячеек перебираются все варианты (точный метод Хелда-Карпа), так что порядок гарантированно лучший.\n- Больше 10 ячеек: сначала каждый раз берётся ближайшая ячейка, потом порядок улучшается перестановками участков (2-opt), до 50 кругов.\n- ✈️ Переходы и развороты прокладываются в обход препятствий. Вокруг углов поля и зон ставятся опорные точки чуть дальше отступа, и по ним ищется кратчайший путь (алгоритм Дейкстры). Путь не подходит к границам ближе отступа.\n- Если точка взлёта стоит за полем, путь к полю обходит только запретные зоны.\n- ⚠️ Перелёты от точки взлёта к полю, между полями и домой обходят все запретные зоны, в том числе стоящие вне полей. Поэтому опоры ЛЭП, вышки, деревья и постройки между полями обязательно обведите запретными зонами, иначе аппарат полетит напрямую и может в них врезаться.\n- Несколько полей облетаются по очереди: каждый раз следующее ближайшее к текущему положению. У каждого поля свой угол.\n\n## ⚖️ 5. Как сравниваются углы\nДля каждого угла строится полная траектория и считается её «цена» в секундах:\n- ⏱️
|
|
1237
|
-
en: 'Auto-calculate picks a pass direction for each field so that the field is sprayed as fast and as completely as possible. Here is how it works, step by step.\n\n## 🗺️ 1. Preparation\n- The map around the field is converted to a flat plane in meters. For fields a few kilometers across the error of this conversion is negligible.\n- The field is rotated so that passes run left to right. Everything else is computed in this rotated frame.\n- A no-fly zone can lie inside a field, stick out over its edge or stand outside fields. It affects a field if it touches it, and it always affects transits.\n\n## 🚜 2. Passes\n- Passes run in parallel, spaced no wider than the swath.\n- The first and last passes sit one margin away from the field edge. The rest are spread evenly between them, so neighboring passes may overlap slightly but never leave gaps.\n- A pass must be clear across its whole width: within one margin on both sides of its axis there must be neither the field edge nor a no-fly zone.\n- Pass ends are shortened by the margin from the boundary. Pieces shorter than a quarter of the swath are dropped, with a threshold of at least 1 m.\n- 💧 The sprayer works only on passes. It is off on turns and transits.\n\n## 🧩 3. Cells\n- If a no-fly zone or a notch cuts passes into pieces, the field is split into cells. Inside a cell passes follow each other in a zigzag and connect one to one.\n- A cell can be started in four ways: from the first or the last pass, from the left or the right end.\n\n## 🔀 4. Flight order\n- The search looks for the order of cells and the way into each one that makes the path between them the shortest.\n- Up to 10 cells all options are checked (exact Held-Karp method), so the order is guaranteed to be the best.\n- Over 10 cells: first the nearest cell is taken each time, then the order is improved by reversing parts of it (2-opt), up to 50 rounds.\n- ✈️ Transits and turns go around obstacles. Anchor points are placed near the corners of the field and zones slightly beyond the margin, and the shortest path is found through them (Dijkstra\'s algorithm). The path never comes closer to a boundary than the margin.\n- If the takeoff point is outside the field, the path to the field only avoids no-fly zones.\n- ⚠️ Transits from takeoff to a field, between fields and back home avoid all no-fly zones, including those outside fields. So be sure to outline power line poles, towers, trees and buildings between fields as no-fly zones, otherwise the vehicle flies straight and may crash into them.\n- Several fields are flown one by one: each time the one nearest to the current position. Each field has its own angle.\n\n## ⚖️ 5. How angles are compared\nFor each angle the full path is built and its "cost" in seconds is calculated:\n- ⏱️
|
|
1238
|
-
zh: "自动计算为每个田块选择作业行方向,使田块喷洒最快、覆盖尽可能完整。下面逐步说明其原理。\n\n## 🗺️ 1. 准备\n- 田块周围的地图被转换为以米为单位的平面。对于几公里大小的田块,这种转换的误差可以忽略。\n- 田块被旋转,使作业行从左到右。之后的计算都在这个旋转后的坐标系中进行。\n- 禁飞区可以位于田块内、跨出田块边缘或位于田块外。只要与田块接触就影响该田块,并且始终影响转场。\n\n## 🚜 2. 作业行\n- 作业行相互平行,间距不大于喷幅。\n- 第一行和最后一行距田块边缘一个边距。其余各行在两者之间均匀分布,因此相邻作业行可能略有重叠,但不会留下空隙。\n- 作业行在整个宽度上必须畅通:轴线两侧一个边距内不能有田块边缘或禁飞区。\n- 作业行两端从边界缩短一个边距。短于四分之一喷幅的片段会被舍弃,阈值不小于 1 m。\n- 💧 喷洒器只在作业行上工作,转弯和转场时关闭。\n\n## 🧩 3. 单元\n- 如果禁飞区或缺口把作业行切成几段,田块会被分成若干单元。单元内作业行呈之字形依次相连,一一对应。\n- 每个单元有四种开始方式:从第一行或最后一行开始,从左端或右端开始。\n\n## 🔀 4. 飞行顺序\n- 寻找单元顺序和每个单元的进入方式,使单元之间的路径最短。\n- 不超过 10 个单元时检查所有方案(精确的 Held-Karp 方法),保证顺序最优。\n- 超过 10 个单元时:先每次选择最近的单元,再通过翻转部分顺序 (2-opt) 改进,最多 50 轮。\n- ✈️ 转场和转弯绕开障碍物。在田块和禁飞区的角附近、略大于边距的位置设置支点,并通过它们寻找最短路径(Dijkstra 算法)。路径与边界的距离不小于边距。\n- 如果起飞点在田块外,前往田块的路径只绕开禁飞区。\n- ⚠️ 从起飞点到田块、田块之间以及返航的转场会绕开所有禁飞区,包括田块外的禁飞区。因此务必把田块之间的电力线杆、塔、树木和建筑圈为禁飞区,否则飞行器会直线飞行并可能撞上它们。\n- 多个田块依次作业:每次选择离当前位置最近的田块。每个田块有自己的角度。\n\n## ⚖️ 5. 如何比较角度\n对每个角度构建完整航线,并以秒为单位计算其“代价”:\n- ⏱️
|
|
1241
|
+
ru: "Авторасчёт подбирает для каждого поля направление проходов, при котором поле обрабатывается быстрее всего и как можно полнее. Ниже по шагам, как это устроено.\n\n## 🗺️ 1. Подготовка\n- Карта вокруг поля переводится в плоскость в метрах. Для полей размером в несколько километров ошибка такого перевода незаметна.\n- Поле поворачивается так, чтобы проходы шли слева направо. Дальше всё считается в этой повёрнутой системе.\n- Запретная зона может лежать внутри поля, выходить за его край или стоять вне полей. Полю она мешает, если задевает его, а перелётам мешает всегда.\n\n## 🚜 2. Проходы\n- Проходы идут параллельно с шагом не больше ширины захвата.\n- Первый и последний проходы стоят на расстоянии отступа от края поля. Остальные распределяются между ними поровну, поэтому соседние проходы могут слегка перекрываться, но не оставляют просветов.\n- Проход должен быть свободен по всей своей ширине: от его оси в обе стороны на величину отступа не должно быть ни края поля, ни запретной зоны.\n- Концы прохода укорачиваются на отступ от границы. Куски короче четверти захвата отбрасываются, но порог не меньше 1 м.\n- 💧 Распылитель работает только на проходах. На разворотах и переходах он выключен.\n\n## 🧩 3. Ячейки\n- Если запретная зона или вырез разрезает проходы на части, поле делится на ячейки. Внутри ячейки проходы идут подряд змейкой и соединяются один к одному.\n- Ячейку можно начать четырьмя способами: с первого или последнего прохода и с левого или правого конца.\n\n## 🔀 4. Порядок облёта\n- Ищется порядок ячеек и способ входа в каждую, при котором путь между ними самый короткий.\n- 🛫 Первый проход закреплён за линией поля: крайний ряд со стороны точки взлёта (без взлёта - со стороны длинной стороны); порядок остальных ячеек оптимизируется от него.\n- До 10 ячеек перебираются все варианты (точный метод Хелда-Карпа), так что порядок гарантированно лучший.\n- Больше 10 ячеек: сначала каждый раз берётся ближайшая ячейка, потом порядок улучшается перестановками участков (2-opt), до 50 кругов.\n- ✈️ Переходы и развороты прокладываются в обход препятствий. Вокруг углов поля и зон ставятся опорные точки чуть дальше отступа, и по ним ищется кратчайший путь (алгоритм Дейкстры). Путь не подходит к границам ближе отступа.\n- Если точка взлёта стоит за полем, путь к полю обходит только запретные зоны.\n- ⚠️ Перелёты от точки взлёта к полю, между полями и домой обходят все запретные зоны, в том числе стоящие вне полей. Поэтому опоры ЛЭП, вышки, деревья и постройки между полями обязательно обведите запретными зонами, иначе аппарат полетит напрямую и может в них врезаться.\n- Несколько полей облетаются по очереди: каждый раз следующее ближайшее к текущему положению. У каждого поля свой угол.\n\n## ⚖️ 5. Как сравниваются углы\nДля каждого угла строится полная траектория и считается её «цена» в секундах:\n- ⏱️ проходы и развороты на скорости распыления, переходы - на скорости переходов;\n- 🔄 плюс время разворота: захват/скорость плюс 2 с на остановку и разворот;\n- 🚫 плюс штраф за недолив. Площадь поля, делённая на ширину захвата, даёт длину проходов при идеальном покрытии. Каждый метр, которого не хватает до неё, считается как три метра полёта: за пропущенным куском пришлось бы возвращаться;\n- ⛔ если к какой-то ячейке нет пути, угол фактически отбрасывается.\nПобеждает угол с наименьшей ценой.\n\n## 🔍 6. Поиск угла приближениями\nЦена меняется скачками: на полградуса больше, и появляется или пропадает целый проход. Поэтому угол ищется в три захода:\n- 1️⃣ все направления с шагом 5° (36 углов) плюс направления каждой стороны поля;\n- 2️⃣ около трёх лучших вариантов, разнесённых минимум на 5°, шаг 1° на ±4°. Три кандидата нужны, чтобы не застрять в ложном минимуме;\n- 3️⃣ около победителя шаг 0,1° на ±0,5°.\nВсего около 75 полных расчётов на поле. Расчёт идёт частями, чтобы интерфейс не замирал. Прогресс виден на карте.\n\nКогда поле только замкнули, ему сразу ставится быстрая оценка без прокладки путей (перебор через 3°, затем через 0,5°), а потом её уточняет полный поиск.\n\n## 🤔 Почему проходы не вдоль стороны поля\nНаправления сторон всегда есть среди кандидатов, но выигрывают они не всегда.\n- Если вести проходы вдоль одной стороны, они идут наискось к другим сторонам и к краям выреза. Каждый проход обрывается за отступ до наклонной границы, и вдоль неё остаются необработанные клинья.\n- Пример с малого восточного демо-поля: вдоль левой стороны (5,6°) покрытие 78,6 %, а угол 8,9°, выбранный подбором, даёт 84,6 % и на один разворот меньше почти за то же время. Это компромисс между левой стороной и правыми сторонами (около 14-15°).\n- Если все длинные стороны поля параллельны, подбор выберет угол вдоль них.\n\n## 💡 Советы\n- Покрытие меньше 100 % в основном из-за отступа от границ и зон. Чтобы обработать больше, уменьшите отступ.\n- Угол можно задать вручную: общим ползунком или у каждого поля в блоке «Итог».\n- После правки контура нажмите «Авторасчёт» ещё раз.\n- Время облёта в «Итоге» считается так же: проходы и развороты на скорости распыления, переходы - на скорости переходов, разворот ≈ захват/скорость + 2 с.\n- Скорость переходов задаётся отдельно: переходы без распыления летятся быстрее, в миссии QGC скорость меняется командами DO_CHANGE_SPEED.",
|
|
1242
|
+
en: 'Auto-calculate picks a pass direction for each field so that the field is sprayed as fast and as completely as possible. Here is how it works, step by step.\n\n## 🗺️ 1. Preparation\n- The map around the field is converted to a flat plane in meters. For fields a few kilometers across the error of this conversion is negligible.\n- The field is rotated so that passes run left to right. Everything else is computed in this rotated frame.\n- A no-fly zone can lie inside a field, stick out over its edge or stand outside fields. It affects a field if it touches it, and it always affects transits.\n\n## 🚜 2. Passes\n- Passes run in parallel, spaced no wider than the swath.\n- The first and last passes sit one margin away from the field edge. The rest are spread evenly between them, so neighboring passes may overlap slightly but never leave gaps.\n- A pass must be clear across its whole width: within one margin on both sides of its axis there must be neither the field edge nor a no-fly zone.\n- Pass ends are shortened by the margin from the boundary. Pieces shorter than a quarter of the swath are dropped, with a threshold of at least 1 m.\n- 💧 The sprayer works only on passes. It is off on turns and transits.\n\n## 🧩 3. Cells\n- If a no-fly zone or a notch cuts passes into pieces, the field is split into cells. Inside a cell passes follow each other in a zigzag and connect one to one.\n- A cell can be started in four ways: from the first or the last pass, from the left or the right end.\n\n## 🔀 4. Flight order\n- The search looks for the order of cells and the way into each one that makes the path between them the shortest.\n- 🛫 The first pass is pinned to a field line: the extreme row on the takeoff side (without takeoff, on the longest side); the rest of the order is optimized from it.\n- Up to 10 cells all options are checked (exact Held-Karp method), so the order is guaranteed to be the best.\n- Over 10 cells: first the nearest cell is taken each time, then the order is improved by reversing parts of it (2-opt), up to 50 rounds.\n- ✈️ Transits and turns go around obstacles. Anchor points are placed near the corners of the field and zones slightly beyond the margin, and the shortest path is found through them (Dijkstra\'s algorithm). The path never comes closer to a boundary than the margin.\n- If the takeoff point is outside the field, the path to the field only avoids no-fly zones.\n- ⚠️ Transits from takeoff to a field, between fields and back home avoid all no-fly zones, including those outside fields. So be sure to outline power line poles, towers, trees and buildings between fields as no-fly zones, otherwise the vehicle flies straight and may crash into them.\n- Several fields are flown one by one: each time the one nearest to the current position. Each field has its own angle.\n\n## ⚖️ 5. How angles are compared\nFor each angle the full path is built and its "cost" in seconds is calculated:\n- ⏱️ passes and turns at the spray speed, transits at the transit speed;\n- 🔄 plus turn time: swath/speed plus 2 s to stop and turn;\n- 🚫 plus a penalty for missed spraying. The field area divided by the swath gives the pass length for perfect coverage. Each meter short of it counts as three meters of flight: the vehicle would have to come back for the missed piece;\n- ⛔ if some cell cannot be reached, the angle is effectively rejected.\nThe angle with the lowest cost wins.\n\n## 🔍 6. Searching the angle step by step\nThe cost changes in jumps: half a degree more, and a whole pass appears or disappears. So the angle is searched in three rounds:\n- 1️⃣ all directions in 5° steps (36 angles) plus the direction of every field side;\n- 2️⃣ around the three best options, at least 5° apart, 1° steps over ±4°. Three candidates are needed so the search does not get stuck in a false minimum;\n- 3️⃣ around the winner, 0.1° steps over ±0.5°.\nThat is about 75 full calculations per field. The work is split into chunks so the interface does not freeze. Progress is shown on the map.\n\nWhen a field has just been closed, it immediately gets a quick estimate without path routing (3° steps, then 0.5°), and the full search refines it afterwards.\n\n## 🤔 Why passes do not follow a field side\nSide directions are always among the candidates, but they do not always win.\n- If passes follow one side, they cross the other sides and the notch edges at an angle. Each pass stops one margin before the slanted boundary, and untreated wedges remain along it.\n- Example from the small eastern demo field: along the left side (5.6°) the coverage is 78.6 %, while 8.9° chosen by the search gives 84.6 % and one turn less in almost the same time. It is a compromise between the left side and the right sides (about 14-15°).\n- If all long sides of a field are parallel, the search picks the angle along them.\n\n## 💡 Tips\n- Coverage below 100 % is mostly due to the margin from boundaries and zones. To treat more area, reduce the margin.\n- The angle can be set by hand: with the common slider or for each field in the Summary block.\n- After editing an outline, press "Auto-calculate" again.\n- The flight time in the Summary is computed the same way: passes and turns at the spray speed, transits at the transit speed, turn ≈ swath/speed + 2 s.\n- Transit speed is set separately: legs without spraying fly faster; the QGC mission changes speed with DO_CHANGE_SPEED commands.',
|
|
1243
|
+
zh: "自动计算为每个田块选择作业行方向,使田块喷洒最快、覆盖尽可能完整。下面逐步说明其原理。\n\n## 🗺️ 1. 准备\n- 田块周围的地图被转换为以米为单位的平面。对于几公里大小的田块,这种转换的误差可以忽略。\n- 田块被旋转,使作业行从左到右。之后的计算都在这个旋转后的坐标系中进行。\n- 禁飞区可以位于田块内、跨出田块边缘或位于田块外。只要与田块接触就影响该田块,并且始终影响转场。\n\n## 🚜 2. 作业行\n- 作业行相互平行,间距不大于喷幅。\n- 第一行和最后一行距田块边缘一个边距。其余各行在两者之间均匀分布,因此相邻作业行可能略有重叠,但不会留下空隙。\n- 作业行在整个宽度上必须畅通:轴线两侧一个边距内不能有田块边缘或禁飞区。\n- 作业行两端从边界缩短一个边距。短于四分之一喷幅的片段会被舍弃,阈值不小于 1 m。\n- 💧 喷洒器只在作业行上工作,转弯和转场时关闭。\n\n## 🧩 3. 单元\n- 如果禁飞区或缺口把作业行切成几段,田块会被分成若干单元。单元内作业行呈之字形依次相连,一一对应。\n- 每个单元有四种开始方式:从第一行或最后一行开始,从左端或右端开始。\n\n## 🔀 4. 飞行顺序\n- 寻找单元顺序和每个单元的进入方式,使单元之间的路径最短。\n- 🛫 第一行固定在田块边线上:靠起飞点一侧的最外行(无起飞点时为长边一侧);其余顺序由其优化。\n- 不超过 10 个单元时检查所有方案(精确的 Held-Karp 方法),保证顺序最优。\n- 超过 10 个单元时:先每次选择最近的单元,再通过翻转部分顺序 (2-opt) 改进,最多 50 轮。\n- ✈️ 转场和转弯绕开障碍物。在田块和禁飞区的角附近、略大于边距的位置设置支点,并通过它们寻找最短路径(Dijkstra 算法)。路径与边界的距离不小于边距。\n- 如果起飞点在田块外,前往田块的路径只绕开禁飞区。\n- ⚠️ 从起飞点到田块、田块之间以及返航的转场会绕开所有禁飞区,包括田块外的禁飞区。因此务必把田块之间的电力线杆、塔、树木和建筑圈为禁飞区,否则飞行器会直线飞行并可能撞上它们。\n- 多个田块依次作业:每次选择离当前位置最近的田块。每个田块有自己的角度。\n\n## ⚖️ 5. 如何比较角度\n对每个角度构建完整航线,并以秒为单位计算其“代价”:\n- ⏱️ 作业行和转弯按喷洒速度、转场按转移速度计算;\n- 🔄 加上转弯时间:喷幅/速度再加 2 s 停止与转弯;\n- 🚫 加上漏喷惩罚。田块面积除以喷幅得到完全覆盖时的作业行长度。每缺少一米按三米飞行计算:漏掉的部分需要返回补喷;\n- ⛔ 如果某个单元无法到达,该角度实际上被排除。\n代价最低的角度胜出。\n\n## 🔍 6. 逐步逼近搜索角度\n代价是跳跃变化的:角度多半度,就可能多出或少掉一整行。因此角度分三轮搜索:\n- 1️⃣ 以 5° 步长遍历所有方向(36 个角度),并加上田块每条边的方向;\n- 2️⃣ 在三个最佳方案附近(彼此至少相距 5°),以 1° 步长搜索 ±4°。需要三个候选,避免陷入假的最小值;\n- 3️⃣ 在胜出角度附近,以 0.1° 步长搜索 ±0.5°。\n每个田块大约需要 75 次完整计算。计算分批进行,界面不会卡住。进度显示在地图上。\n\n田块刚闭合时,会立即得到一个不规划路径的快速估算(先 3° 步长,再 0.5°),随后由完整搜索进一步精确。\n\n## 🤔 为什么作业行不沿田块的边\n各边的方向总在候选之中,但并不总是最优。\n- 如果作业行沿一条边,就会与其他边和缺口边缘斜交。每行在斜边界前一个边距处中断,沿边界留下未作业的楔形区域。\n- 东侧小演示田块的例子:沿左边 (5.6°) 覆盖率为 78.6 %,而搜索选出的 8.9° 覆盖率为 84.6 %,转弯少一次,时间几乎相同。这是左边与右侧各边(约 14-15°)之间的折中。\n- 如果田块所有长边都平行,搜索会选择沿这些边的角度。\n\n## 💡 提示\n- 覆盖率低于 100 % 主要是由于与边界和禁飞区的边距。要作业更多面积,请减小边距。\n- 角度可以手动设置:使用公共滑块,或在“汇总”中为每个田块单独设置。\n- 修改轮廓后,请再次点击“自动计算”。\n- “汇总”中的飞行时间按同样方式计算:作业行和转弯按喷洒速度、转场按转移速度,转弯≈喷幅/速度+2 s。\n- 转移速度单独设置:不喷洒的航段飞得更快;QGC 任务用 DO_CHANGE_SPEED 命令切换速度。",
|
|
1239
1244
|
},
|
|
1240
1245
|
"widget.mission.autoHint": {
|
|
1241
1246
|
ru: "Для каждого поля перебираются углы полным расчётом траектории: шаг 5°, затем 1° и 0,1°. Лучший - с наименьшим временем облёта, где учитываются путь и развороты",
|
|
@@ -1246,6 +1251,7 @@ const translations = {
|
|
|
1246
1251
|
"widget.mission.margin": { ru: "Отступ от границ, м", en: "Edge margin, m", zh: "边界距离,米" },
|
|
1247
1252
|
"widget.mission.alt": { ru: "Высота, м", en: "Altitude, m", zh: "高度,米" },
|
|
1248
1253
|
"widget.mission.speed": { ru: "Скорость, м/с", en: "Speed, m/s", zh: "速度,米/秒" },
|
|
1254
|
+
"widget.mission.transitSpeed": { ru: "Скорость переходов, м/с", en: "Transit speed, m/s", zh: "转移速度,米/秒" },
|
|
1249
1255
|
"widget.mission.returnHome": { ru: "Вернуться к точке взлёта", en: "Return to takeoff point", zh: "返回起飞点" },
|
|
1250
1256
|
"widget.mission.spraying": { ru: "Внесение", en: "Application", zh: "喷洒" },
|
|
1251
1257
|
"widget.mission.rate": { ru: "Норма, л/га", en: "Rate, l/ha", zh: "用量,升/公顷" },
|
package/dist/types.d.ts
CHANGED
|
@@ -932,7 +932,6 @@ export interface IWidgetHomingProps {
|
|
|
932
932
|
collapsed?: boolean;
|
|
933
933
|
persistKey?: string;
|
|
934
934
|
onSearch?: () => void;
|
|
935
|
-
onHome?: () => void;
|
|
936
935
|
onSave?: (values: Partial<Record<keyof IWidgetHomingData, number>>) => void;
|
|
937
936
|
onRefresh?: () => void;
|
|
938
937
|
}
|