Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
673dea62e8 | ||
|
|
947c0a3127 |
@@ -84,7 +84,7 @@ class Braco:
|
|||||||
try:
|
try:
|
||||||
for channel,pulse in pulses.items():
|
for channel,pulse in pulses.items():
|
||||||
self.servos.hw.pulse(channel,pulse)
|
self.servos.hw.pulse(channel,pulse)
|
||||||
self.servos.active[channel]=prazo
|
self.servos.ligar([(channel,prazo) for channel in pulses])
|
||||||
except OSError:
|
except OSError:
|
||||||
self.alvo=None; self.servos.stop()
|
self.alvo=None; self.servos.stop()
|
||||||
raise
|
raise
|
||||||
@@ -102,7 +102,13 @@ class Braco:
|
|||||||
self.escrever(pulses,prazo)
|
self.escrever(pulses,prazo)
|
||||||
self.atual=[float(a) for a in pose]
|
self.atual=[float(a) for a in pose]
|
||||||
return dict(ok=True,pulsos=pulses,movendo=False)
|
return dict(ok=True,pulsos=pulses,movendo=False)
|
||||||
self.alvo=[float(a) for a in pose]; self.velocidade=velocidade; self.lease=prazo
|
alvo=[float(a) for a in pose]
|
||||||
|
if all(abs(a-t)<.01 for a,t in zip(self.atual,alvo)):
|
||||||
|
# Já no alvo: só renova o prazo (e reenergiza canais que tenham desligado).
|
||||||
|
self.alvo=None
|
||||||
|
self.escrever(pulses,prazo)
|
||||||
|
return dict(ok=True,pulsos=pulses,movendo=False)
|
||||||
|
self.alvo=alvo; self.velocidade=velocidade; self.lease=prazo
|
||||||
for channel in list(self.servos.active): self.servos.active[channel]=prazo
|
for channel in list(self.servos.active): self.servos.active[channel]=prazo
|
||||||
return dict(ok=True,pulsos=pulses,movendo=True)
|
return dict(ok=True,pulsos=pulses,movendo=True)
|
||||||
def cancelar(self):
|
def cancelar(self):
|
||||||
@@ -142,7 +148,7 @@ class Braco:
|
|||||||
self.servos.reservar('braco'); self.alvo=None; self.atual=None
|
self.servos.reservar('braco'); self.alvo=None; self.atual=None
|
||||||
for ch,us in outputs.items():
|
for ch,us in outputs.items():
|
||||||
self.servos.hw.pulse(ch,us)
|
self.servos.hw.pulse(ch,us)
|
||||||
self.servos.active[ch]=time.monotonic()+2
|
self.servos.ligar([(ch,time.monotonic()+2) for ch in outputs])
|
||||||
return dict(ok=True,pulsos=outputs)
|
return dict(ok=True,pulsos=outputs)
|
||||||
def rotas(self,h,method):
|
def rotas(self,h,method):
|
||||||
route=h.path.split('?',1)[0]
|
route=h.path.split('?',1)[0]
|
||||||
|
|||||||
@@ -88,6 +88,15 @@ class ControleServos:
|
|||||||
with self.lock:
|
with self.lock:
|
||||||
return dict(disponivel=self.hw is not None, erro=self.error, ativos=sorted(self.active),
|
return dict(disponivel=self.hw is not None, erro=self.error, ativos=sorted(self.active),
|
||||||
dono=self.dono, travado=self.travado)
|
dono=self.dono, travado=self.travado)
|
||||||
|
def ligar(self, canais_prazos):
|
||||||
|
"""Registra canais energizados até o prazo; avisa o painel quando algum canal liga."""
|
||||||
|
with self.lock:
|
||||||
|
novos = False
|
||||||
|
for canal, prazo in canais_prazos:
|
||||||
|
novos = novos or canal not in self.active
|
||||||
|
self.active[canal] = prazo
|
||||||
|
if novos:
|
||||||
|
self.publicar('motores', self.motores())
|
||||||
def reservar(self, nome):
|
def reservar(self, nome):
|
||||||
"""Braço e diagnóstico usam o mesmo PCA9685 com limites diferentes: um de cada vez."""
|
"""Braço e diagnóstico usam o mesmo PCA9685 com limites diferentes: um de cada vez."""
|
||||||
with self.lock:
|
with self.lock:
|
||||||
@@ -110,7 +119,7 @@ class ControleServos:
|
|||||||
if self.hw is None: raise OSError('PCA9685 indisponível neste servidor')
|
if self.hw is None: raise OSError('PCA9685 indisponível neste servidor')
|
||||||
self.reservar('diagnostico')
|
self.reservar('diagnostico')
|
||||||
self.hw.pulse(row['canal'], pulse)
|
self.hw.pulse(row['canal'], pulse)
|
||||||
self.active[row['canal']] = time.monotonic() + 2
|
self.ligar([(row['canal'], time.monotonic() + 2)])
|
||||||
return self.status()
|
return self.status()
|
||||||
def expire(self, now):
|
def expire(self, now):
|
||||||
with self.lock:
|
with self.lock:
|
||||||
|
|||||||
@@ -17,7 +17,10 @@ spec = importlib.util.spec_from_file_location('kiosk_web', ROOT / 'kiosk-server.
|
|||||||
kiosk = importlib.util.module_from_spec(spec)
|
kiosk = importlib.util.module_from_spec(spec)
|
||||||
spec.loader.exec_module(kiosk)
|
spec.loader.exec_module(kiosk)
|
||||||
from braco import Braco
|
from braco import Braco
|
||||||
|
from cerebro import Cerebro
|
||||||
|
from conversa import Conversa
|
||||||
from servos import ControleServos
|
from servos import ControleServos
|
||||||
|
from treinamento import Treinamento
|
||||||
|
|
||||||
TOKEN = 'token-de-teste-123'
|
TOKEN = 'token-de-teste-123'
|
||||||
|
|
||||||
@@ -38,6 +41,10 @@ def main(capturas=None):
|
|||||||
server.controle = kiosk.ControlePC(tmp / 'app.json')
|
server.controle = kiosk.ControlePC(tmp / 'app.json')
|
||||||
server.servos = ControleServos(tmp / 'servos.json', HW())
|
server.servos = ControleServos(tmp / 'servos.json', HW())
|
||||||
server.braco = Braco(tmp / 'braco.json', server.servos)
|
server.braco = Braco(tmp / 'braco.json', server.servos)
|
||||||
|
server.cerebro = Cerebro(tmp / 'ia.json', server.controle, kiosk.enfileirar)
|
||||||
|
server.conversa = Conversa(tmp / 'memoria.db', server.cerebro)
|
||||||
|
server.treinamento = Treinamento(tmp / 'treinamento.db', iniciar=False)
|
||||||
|
server.conversa.treinamento = server.treinamento
|
||||||
kiosk.ligar_eventos(server)
|
kiosk.ligar_eventos(server)
|
||||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||||
thread.start()
|
thread.start()
|
||||||
@@ -109,6 +116,66 @@ def testar(base, server, capturas):
|
|||||||
page.get_by_label('Buscar ajuste').fill('')
|
page.get_by_label('Buscar ajuste').fill('')
|
||||||
page.screenshot(path=str(Path(capturas) / 'ajustes.png'), full_page=True)
|
page.screenshot(path=str(Path(capturas) / 'ajustes.png'), full_page=True)
|
||||||
|
|
||||||
|
# 6b. conversa: pergunta de hora é respondida pelo relógio (sem IA) e chega por SSE
|
||||||
|
page.get_by_role('link', name='Conversa').first.click()
|
||||||
|
page.get_by_label('Mensagem').fill('Que horas são?')
|
||||||
|
page.get_by_role('button', name='Enviar').click()
|
||||||
|
expect(page.get_by_text('no horário de São Paulo')).to_be_visible(timeout=5000)
|
||||||
|
page.get_by_label('Nova lembrança').fill('Meu nome é Júlio')
|
||||||
|
page.get_by_role('button', name='Adicionar').click()
|
||||||
|
expect(page.get_by_text('Meu nome é Júlio')).to_be_visible(timeout=5000)
|
||||||
|
page.get_by_role('tab', name='Rotina e preferências').click()
|
||||||
|
page.get_by_label('Nova rotina').fill('Treino às 7h')
|
||||||
|
page.get_by_role('button', name='Adicionar').click()
|
||||||
|
expect(page.get_by_text('Treino às 7h')).to_be_visible(timeout=5000)
|
||||||
|
if capturas:
|
||||||
|
page.screenshot(path=str(Path(capturas) / 'conversa.png'), full_page=True)
|
||||||
|
|
||||||
|
# 6c. reações: criar emoji, mostrar no celular, excluir e desfazer pelo toast
|
||||||
|
page.get_by_role('link', name='Reações').first.click()
|
||||||
|
page.get_by_role('button', name='Novo emoji').click()
|
||||||
|
page.get_by_label('Nome').fill('Ideia brilhante')
|
||||||
|
page.get_by_label('Quando usar').fill('Quando tiver uma ideia')
|
||||||
|
page.get_by_role('radio', name='🚀').click()
|
||||||
|
page.get_by_role('button', name='Salvar').click()
|
||||||
|
cartao = page.locator('li.reacao', has_text='Ideia brilhante')
|
||||||
|
expect(cartao).to_be_visible(timeout=5000)
|
||||||
|
cartao.get_by_role('button', name='Mostrar').click()
|
||||||
|
page.wait_for_timeout(400)
|
||||||
|
assert server.treinamento.expressao['receita']['nome'] == 'Ideia brilhante'
|
||||||
|
cartao.get_by_role('button', name='Excluir').click()
|
||||||
|
expect(cartao).to_have_count(0, timeout=5000)
|
||||||
|
page.get_by_role('button', name='Desfazer').last.click()
|
||||||
|
expect(page.locator('li.reacao', has_text='Ideia brilhante')).to_be_visible(timeout=5000)
|
||||||
|
if capturas:
|
||||||
|
page.screenshot(path=str(Path(capturas) / 'reacoes.png'), full_page=True)
|
||||||
|
|
||||||
|
# 6d. braço: opt-in, homem-morto e desligamento pelo prazo ao soltar
|
||||||
|
hw = server.servos.hw
|
||||||
|
page.get_by_role('link', name='Movimento').first.click()
|
||||||
|
segurar = page.get_by_role('button', name='Segure para ir ao alvo')
|
||||||
|
expect(segurar).to_be_disabled()
|
||||||
|
page.get_by_role('switch', name='Ativar movimento físico').locator('xpath=..').click()
|
||||||
|
expect(segurar).to_be_enabled()
|
||||||
|
hw.calls.clear()
|
||||||
|
segurar.hover()
|
||||||
|
page.mouse.down()
|
||||||
|
page.wait_for_timeout(700)
|
||||||
|
assert server.servos.active, 'motores deveriam estar ligados enquanto segura'
|
||||||
|
expect(page.get_by_text('Motores ligados')).to_be_visible(timeout=3000)
|
||||||
|
page.mouse.up()
|
||||||
|
page.wait_for_timeout(900)
|
||||||
|
assert not server.servos.active, 'motores deveriam desligar sozinhos após soltar'
|
||||||
|
assert any(us for _, us in hw.calls), hw.calls
|
||||||
|
if capturas:
|
||||||
|
page.screenshot(path=str(Path(capturas) / 'movimento.png'), full_page=True)
|
||||||
|
# E-Stop desativa o movimento físico na hora
|
||||||
|
page.get_by_role('button', name='Parar tudo').click()
|
||||||
|
expect(page.get_by_role('switch', name='Ativar movimento físico')).to_be_disabled(timeout=3000)
|
||||||
|
expect(segurar).to_be_disabled()
|
||||||
|
page.get_by_role('button', name='PARADO · Rearmar').click()
|
||||||
|
expect(page.get_by_role('button', name='Parar tudo')).to_be_visible(timeout=3000)
|
||||||
|
|
||||||
# 7. celular: barra inferior e nada de rolagem horizontal
|
# 7. celular: barra inferior e nada de rolagem horizontal
|
||||||
page.set_viewport_size({'width': 400, 'height': 860})
|
page.set_viewport_size({'width': 400, 'height': 860})
|
||||||
page.get_by_role('link', name='Ao vivo').click()
|
page.get_by_role('link', name='Ao vivo').click()
|
||||||
@@ -129,7 +196,7 @@ def testar(base, server, capturas):
|
|||||||
|
|
||||||
assert not erros, erros
|
assert not erros, erros
|
||||||
browser.close()
|
browser.close()
|
||||||
print('OK: token, SSE, dock 1-9, paleta, E-Stop, ajustes otimistas, celular 400px, tema claro')
|
print('OK: token, SSE, dock 1-9, paleta, E-Stop, ajustes otimistas, conversa, memória, reações com desfazer, braço com homem-morto, celular 400px, tema')
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
@@ -215,6 +215,14 @@ class BracoMovimentoTest(unittest.TestCase):
|
|||||||
self.assertEqual(self.servos.active, {})
|
self.assertEqual(self.servos.active, {})
|
||||||
self.assertIsNone(self.servos.dono)
|
self.assertIsNone(self.servos.dono)
|
||||||
|
|
||||||
|
def test_renovar_no_alvo_informa_que_chegou(self):
|
||||||
|
self.arm.move([90] * 7)
|
||||||
|
self.hw.calls.clear()
|
||||||
|
r = self.arm.move([90] * 7, velocidade=60, ttl_ms=400)
|
||||||
|
self.assertFalse(r['movendo'])
|
||||||
|
self.assertIsNone(self.arm.alvo)
|
||||||
|
self.assertEqual(len(self.hw.calls), 8) # reenergiza os 8 canais com o novo prazo
|
||||||
|
|
||||||
def test_parametros_invalidos(self):
|
def test_parametros_invalidos(self):
|
||||||
for kwargs in (dict(velocidade=1000), dict(velocidade=True), dict(ttl_ms=50), dict(ttl_ms=5000)):
|
for kwargs in (dict(velocidade=1000), dict(velocidade=True), dict(ttl_ms=50), dict(ttl_ms=5000)):
|
||||||
with self.assertRaises(ValueError):
|
with self.assertRaises(ValueError):
|
||||||
|
|||||||
+1
-1
@@ -169,7 +169,7 @@
|
|||||||
<Tela />
|
<Tela />
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
{#if nav.atual !== 'ao-vivo'}
|
{#if nav.atual !== 'ao-vivo' && nav.atual !== 'reacoes'}
|
||||||
<MiniRosto />
|
<MiniRosto />
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,214 @@
|
|||||||
|
/**
|
||||||
|
* Braço (/braco/*) e diagnóstico (/servos/*). Segurança:
|
||||||
|
* - homem-morto: só há movimento enquanto o botão/slider está pressionado; cada pedido leva
|
||||||
|
* um prazo curto (ttl_ms) e o servidor desliga os motores se ele vencer sem renovação;
|
||||||
|
* - a interpolação e o limite de velocidade são do servidor, não deste navegador.
|
||||||
|
*/
|
||||||
|
import { pedir, postar } from './api';
|
||||||
|
import { avisos } from './avisos.svelte';
|
||||||
|
import { estado } from './estado.svelte';
|
||||||
|
|
||||||
|
export interface Calibracao {
|
||||||
|
canal: number;
|
||||||
|
minimo: number;
|
||||||
|
maximo: number;
|
||||||
|
centro: number;
|
||||||
|
}
|
||||||
|
export interface Postura {
|
||||||
|
nome: string;
|
||||||
|
angulos: number[];
|
||||||
|
}
|
||||||
|
export interface StatusBraco {
|
||||||
|
calibracao: Calibracao[];
|
||||||
|
posturas: Postura[];
|
||||||
|
disponivel: boolean;
|
||||||
|
erro: string;
|
||||||
|
dono: string | null;
|
||||||
|
travado: boolean;
|
||||||
|
atual: number[] | null;
|
||||||
|
movendo: boolean;
|
||||||
|
articulacoes: { nome: string; canal: number }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PRAZO_MS = 450;
|
||||||
|
const RENOVAR_MS = 150;
|
||||||
|
|
||||||
|
function anguloDoPulso(p: number, c: Calibracao) {
|
||||||
|
const centro = c.centro ?? 1500;
|
||||||
|
return p <= centro ? (90 * (p - 500)) / (centro - 500) : 90 + (90 * (p - centro)) / (2500 - centro);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Faixa segura (graus) de cada articulação a partir da calibração; o canal 5 respeita o par 6 invertido. */
|
||||||
|
export function limites(st: StatusBraco): [number, number][] {
|
||||||
|
return st.articulacoes.map(({ canal }) => {
|
||||||
|
const c = st.calibracao[canal];
|
||||||
|
let lo = anguloDoPulso(c.minimo, c);
|
||||||
|
let hi = anguloDoPulso(c.maximo, c);
|
||||||
|
if (canal === 5) {
|
||||||
|
const par = st.calibracao[6];
|
||||||
|
lo = Math.max(lo, 180 - anguloDoPulso(par.maximo, par));
|
||||||
|
hi = Math.min(hi, 180 - anguloDoPulso(par.minimo, par));
|
||||||
|
}
|
||||||
|
return [Math.ceil(lo), Math.floor(hi)];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** As 5 sequências prontas, escaladas para a faixa calibrada (porta de movimentos-core.js). */
|
||||||
|
export function sequencias(faixas: [number, number][]): { nome: string; passos: number[][] }[] {
|
||||||
|
const neutro = [0, 0, 0, 0, 0, 0, 0];
|
||||||
|
const base: [string, number[][]][] = [
|
||||||
|
['Acenar', [[0, -0.7, 0.5, 0.2, 0, 0.1, 0], [0, 0.7, -0.5, 0.2, 0, 0.1, 0], [0, -0.7, 0.5, 0.2, 0, 0.1, 0], [0, 0.7, -0.5, 0.2, 0, 0.1, 0], neutro]],
|
||||||
|
['Olhar para os lados', [[0, 0.2, -0.4, 0, 0, 0, -0.7], [0, -0.2, 0.4, 0, 0, 0, 0.7], neutro]],
|
||||||
|
['Alcançar e recolher', [[0, 0, 0.2, 0.6, -0.5, 0.4, 0], [0, 0, -0.2, -0.4, 0.5, -0.4, 0], neutro]],
|
||||||
|
['Garra e punho', [[-0.7, 0.3, 0, 0.2, 0, 0.1, 0], [0.7, -0.3, 0, 0.2, 0, 0.1, 0], [-0.7, 0.3, 0, 0, 0, 0, 0], neutro]],
|
||||||
|
['Apresentação', [[0.3, 0.3, -0.3, 0.4, -0.3, 0.3, -0.6], [-0.3, -0.3, 0.3, -0.3, 0.4, -0.3, 0.6], [0.5, 0.4, 0.2, 0.3, -0.3, 0.2, 0], neutro]],
|
||||||
|
];
|
||||||
|
return base.map(([nome, passos]) => ({
|
||||||
|
nome,
|
||||||
|
passos: passos.map((s) =>
|
||||||
|
s.map((v, i) => {
|
||||||
|
const [lo, hi] = faixas[i];
|
||||||
|
// Centro 90°, mas sempre dentro da faixa calibrada.
|
||||||
|
const meio = Math.max(lo, Math.min(hi, 90));
|
||||||
|
return Math.round(meio + v * (v < 0 ? meio - lo : hi - meio));
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
class Braco {
|
||||||
|
status = $state<StatusBraco | null>(null);
|
||||||
|
alvo = $state<number[]>(Array(7).fill(90));
|
||||||
|
velocidade = $state(60);
|
||||||
|
/** Opt-in explícito antes de qualquer movimento físico. */
|
||||||
|
ativado = $state(false);
|
||||||
|
segurando = $state(false);
|
||||||
|
passoSequencia = $state<{ nome: string; indice: number; total: number } | null>(null);
|
||||||
|
|
||||||
|
private relogio = 0;
|
||||||
|
private emVoo = false;
|
||||||
|
private sequencia: number[][] | null = null;
|
||||||
|
private pausaAte = 0;
|
||||||
|
|
||||||
|
faixas = $derived(this.status ? limites(this.status) : []);
|
||||||
|
|
||||||
|
async carregar() {
|
||||||
|
try {
|
||||||
|
this.status = await pedir<StatusBraco>('/braco/status');
|
||||||
|
this.limitarAlvo();
|
||||||
|
} catch (e) {
|
||||||
|
avisos.erro(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
limitarAlvo() {
|
||||||
|
if (!this.faixas.length) return;
|
||||||
|
this.alvo = this.alvo.map((v, i) => Math.max(this.faixas[i][0], Math.min(this.faixas[i][1], v)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Começa a segurar: renova o movimento a cada 150 ms até soltar. */
|
||||||
|
segurar(sequencia?: { nome: string; passos: number[][] }) {
|
||||||
|
if (!this.ativado || this.segurando) return;
|
||||||
|
if (sequencia) {
|
||||||
|
this.sequencia = sequencia.passos;
|
||||||
|
this.passoSequencia = { nome: sequencia.nome, indice: 0, total: sequencia.passos.length };
|
||||||
|
this.alvo = [...sequencia.passos[0]];
|
||||||
|
this.pausaAte = 0;
|
||||||
|
}
|
||||||
|
this.segurando = true;
|
||||||
|
this.renovar();
|
||||||
|
this.relogio = window.setInterval(() => this.renovar(), RENOVAR_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Soltou: para de renovar. O servidor desliga os motores quando o prazo vence (≤ 450 ms). */
|
||||||
|
soltar() {
|
||||||
|
if (!this.segurando) return;
|
||||||
|
this.segurando = false;
|
||||||
|
clearInterval(this.relogio);
|
||||||
|
if (this.passoSequencia) avisos.mostrar(`${this.passoSequencia.nome} interrompida ao soltar.`);
|
||||||
|
this.sequencia = null;
|
||||||
|
this.passoSequencia = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async renovar() {
|
||||||
|
if (this.emVoo || !this.segurando) return;
|
||||||
|
this.emVoo = true;
|
||||||
|
try {
|
||||||
|
const r = await postar<{ movendo: boolean }>('/braco/mover', {
|
||||||
|
angulos: $state.snapshot(this.alvo),
|
||||||
|
velocidade: this.velocidade,
|
||||||
|
ttl_ms: PRAZO_MS,
|
||||||
|
});
|
||||||
|
if (!r.movendo && this.sequencia && this.passoSequencia) this.avancarSequencia();
|
||||||
|
} catch (e) {
|
||||||
|
this.segurando = false;
|
||||||
|
clearInterval(this.relogio);
|
||||||
|
this.sequencia = null;
|
||||||
|
this.passoSequencia = null;
|
||||||
|
avisos.erro(e);
|
||||||
|
} finally {
|
||||||
|
this.emVoo = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private avancarSequencia() {
|
||||||
|
if (!this.pausaAte) {
|
||||||
|
this.pausaAte = performance.now() + 700;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (performance.now() < this.pausaAte) return;
|
||||||
|
this.pausaAte = 0;
|
||||||
|
const p = this.passoSequencia!;
|
||||||
|
if (p.indice + 1 >= p.total) {
|
||||||
|
avisos.ok(`${p.nome} concluída.`);
|
||||||
|
this.sequencia = null;
|
||||||
|
this.passoSequencia = null;
|
||||||
|
this.segurando = false;
|
||||||
|
clearInterval(this.relogio);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.passoSequencia = { ...p, indice: p.indice + 1 };
|
||||||
|
this.alvo = [...this.sequencia![p.indice + 1]];
|
||||||
|
}
|
||||||
|
|
||||||
|
async pararMotores() {
|
||||||
|
this.soltar();
|
||||||
|
try {
|
||||||
|
await postar('/braco/parar');
|
||||||
|
} catch (e) {
|
||||||
|
avisos.erro(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async desativar() {
|
||||||
|
this.ativado = false;
|
||||||
|
await this.pararMotores();
|
||||||
|
}
|
||||||
|
|
||||||
|
async salvar(dados: { calibracao: Calibracao[]; posturas: Postura[] }, sucesso: string) {
|
||||||
|
this.soltar();
|
||||||
|
try {
|
||||||
|
await postar('/braco/parar');
|
||||||
|
this.status = await postar<StatusBraco>('/braco/config', dados);
|
||||||
|
this.limitarAlvo();
|
||||||
|
avisos.ok(sucesso);
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
avisos.erro(e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const braco = new Braco();
|
||||||
|
|
||||||
|
// Segurança: aba escondida ou E-Stop param de segurar na hora.
|
||||||
|
document.addEventListener('visibilitychange', () => document.hidden && braco.soltar());
|
||||||
|
$effect.root(() => {
|
||||||
|
$effect(() => {
|
||||||
|
if (estado.estop.ativo) {
|
||||||
|
braco.soltar();
|
||||||
|
braco.ativado = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
<script lang="ts" generics="T extends string">
|
||||||
|
let { abas, ativa = $bindable(), rotulo }: { abas: { id: T; titulo: string; contador?: number }[]; ativa: T; rotulo: string } =
|
||||||
|
$props();
|
||||||
|
|
||||||
|
function tecla(e: KeyboardEvent, i: number) {
|
||||||
|
const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;
|
||||||
|
if (!d) return;
|
||||||
|
const prox = abas[(i + d + abas.length) % abas.length];
|
||||||
|
ativa = prox.id;
|
||||||
|
(e.currentTarget as HTMLElement).parentElement?.querySelector<HTMLElement>(`[data-aba="${prox.id}"]`)?.focus();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="abas" role="tablist" aria-label={rotulo}>
|
||||||
|
{#each abas as aba, i (aba.id)}
|
||||||
|
<button
|
||||||
|
role="tab"
|
||||||
|
data-aba={aba.id}
|
||||||
|
aria-selected={ativa === aba.id}
|
||||||
|
tabindex={ativa === aba.id ? 0 : -1}
|
||||||
|
onclick={() => (ativa = aba.id)}
|
||||||
|
onkeydown={(e) => tecla(e, i)}
|
||||||
|
>
|
||||||
|
{aba.titulo}
|
||||||
|
{#if aba.contador !== undefined}<span class="contador">{aba.contador}</span>{/if}
|
||||||
|
</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.abas {
|
||||||
|
display: flex;
|
||||||
|
gap: var(--e-1);
|
||||||
|
border-bottom: 1px solid var(--borda);
|
||||||
|
overflow-x: auto;
|
||||||
|
scrollbar-width: none;
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--e-2);
|
||||||
|
padding: var(--e-2) var(--e-3);
|
||||||
|
min-height: 40px;
|
||||||
|
border: 0;
|
||||||
|
border-bottom: 2px solid transparent;
|
||||||
|
margin-bottom: -1px;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--texto-3);
|
||||||
|
font: 500 var(--t-sm) var(--fonte);
|
||||||
|
cursor: pointer;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
button[aria-selected='true'] {
|
||||||
|
color: var(--texto);
|
||||||
|
border-bottom-color: var(--destaque);
|
||||||
|
}
|
||||||
|
.contador {
|
||||||
|
font-size: var(--t-xs);
|
||||||
|
padding: 0 6px;
|
||||||
|
border-radius: var(--raio-pill);
|
||||||
|
background: var(--superficie-3);
|
||||||
|
color: var(--texto-2);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
// Vista lateral esquemática: cada articulação é um <g> aninhado que gira no próprio eixo.
|
||||||
|
// Ordem dos ângulos: 0 garra, 1 punho 1, 2 punho 2, 3 braço superior, 4 braço inferior, 5 antebraço, 6 base.
|
||||||
|
let { pose, fantasma = null }: { pose: number[]; fantasma?: number[] | null } = $props();
|
||||||
|
const r = (v: number) => v - 90;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#snippet braco(p: number[], classe: string)}
|
||||||
|
<g class={classe}>
|
||||||
|
<g transform="translate(120 236) rotate({r(p[4])})">
|
||||||
|
<line x1="0" y1="0" x2="0" y2="-78" class="seg" />
|
||||||
|
<g transform="translate(0 -78) rotate({r(p[3])})">
|
||||||
|
<line x1="0" y1="0" x2="0" y2="-66" class="seg" />
|
||||||
|
<g transform="translate(0 -66) rotate({r(p[5])})">
|
||||||
|
<line x1="0" y1="0" x2="0" y2="-40" class="seg fino" />
|
||||||
|
<g transform="translate(0 -40) rotate({r(p[1])})">
|
||||||
|
<line x1="0" y1="0" x2="0" y2="-18" class="seg fino" />
|
||||||
|
<ellipse cx="0" cy="-18" rx={7 * Math.abs(Math.cos(((p[2] - 90) * Math.PI) / 180)) + 2} ry="4" class="punho" />
|
||||||
|
<g transform="translate(0 -20)">
|
||||||
|
<path d="M0 0 L-4 -16 L-1 -24" class="dedo" transform="rotate({-8 - (p[0] - 90) * 0.25})" />
|
||||||
|
<path d="M0 0 L4 -16 L1 -24" class="dedo" transform="rotate({8 + (p[0] - 90) * 0.25})" />
|
||||||
|
</g>
|
||||||
|
<circle r="4" class="junta" />
|
||||||
|
</g>
|
||||||
|
<circle r="5" class="junta" />
|
||||||
|
</g>
|
||||||
|
<circle r="6" class="junta" />
|
||||||
|
</g>
|
||||||
|
<circle r="7" class="junta" />
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
<svg viewBox="0 0 240 290" role="img" aria-label="Postura do braço">
|
||||||
|
<!-- base: o arco mostra a rotação (vista de cima) -->
|
||||||
|
<rect x="80" y="240" width="80" height="16" rx="5" class="base" />
|
||||||
|
<path d="M85 274 A40 14 0 0 0 155 274" class="trilho" />
|
||||||
|
<circle
|
||||||
|
cx={120 + 35 * Math.cos(Math.PI - (pose[6] * Math.PI) / 180)}
|
||||||
|
cy={274 + 12 * Math.sin((pose[6] * Math.PI) / 180) * 0.4}
|
||||||
|
r="4"
|
||||||
|
class="marcador"
|
||||||
|
/>
|
||||||
|
{#if fantasma}{@render braco(fantasma, 'fantasma')}{/if}
|
||||||
|
{@render braco(pose, 'real')}
|
||||||
|
</svg>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
svg {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
.seg {
|
||||||
|
stroke: var(--destaque);
|
||||||
|
stroke-width: 12;
|
||||||
|
stroke-linecap: round;
|
||||||
|
}
|
||||||
|
.fino {
|
||||||
|
stroke-width: 8;
|
||||||
|
}
|
||||||
|
.junta {
|
||||||
|
fill: var(--superficie);
|
||||||
|
stroke: var(--texto-2);
|
||||||
|
stroke-width: 2;
|
||||||
|
}
|
||||||
|
.punho {
|
||||||
|
fill: var(--texto-2);
|
||||||
|
}
|
||||||
|
.dedo {
|
||||||
|
fill: none;
|
||||||
|
stroke: var(--texto);
|
||||||
|
stroke-width: 4;
|
||||||
|
stroke-linecap: round;
|
||||||
|
stroke-linejoin: round;
|
||||||
|
}
|
||||||
|
.base {
|
||||||
|
fill: var(--superficie-3);
|
||||||
|
stroke: var(--borda-forte);
|
||||||
|
}
|
||||||
|
.trilho {
|
||||||
|
fill: none;
|
||||||
|
stroke: var(--borda-forte);
|
||||||
|
stroke-width: 2;
|
||||||
|
stroke-dasharray: 3 4;
|
||||||
|
}
|
||||||
|
.marcador {
|
||||||
|
fill: var(--aviso);
|
||||||
|
}
|
||||||
|
.fantasma {
|
||||||
|
opacity: 0.25;
|
||||||
|
}
|
||||||
|
.fantasma .seg {
|
||||||
|
stroke: var(--texto-3);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { SIMBOLO_EMOJI } from '../treinamento.svelte';
|
||||||
|
|
||||||
|
// Prévia estática de uma reação (sem iframe): figurinha SVG, emoji ou olhos do 1º passo.
|
||||||
|
let { receita, tamanho = 64 }: { receita: any; tamanho?: number } = $props();
|
||||||
|
const passo = $derived(receita?.passos?.[0]);
|
||||||
|
const simbolo = $derived(receita?.emoji?.caractere || SIMBOLO_EMOJI[receita?.simbolo] || '');
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="miniatura" style="--t: {tamanho}px" aria-hidden="true">
|
||||||
|
{#if receita?.figurinha?.formas}
|
||||||
|
<svg viewBox="0 0 100 100" width={tamanho} height={tamanho}>
|
||||||
|
{#each receita.figurinha.formas as forma, i (i)}
|
||||||
|
<path d={forma.caminho} fill={forma.cor} />
|
||||||
|
{/each}
|
||||||
|
</svg>
|
||||||
|
{:else if receita?.emoji}
|
||||||
|
<span class="emoji">{receita.emoji.caractere}</span>
|
||||||
|
{:else}
|
||||||
|
<svg viewBox="0 0 100 60" width={tamanho} height={tamanho * 0.6}>
|
||||||
|
{#if passo?.olhos === 'feliz'}
|
||||||
|
<path d="M18 38 Q30 18 42 38 M58 38 Q70 18 82 38" stroke={passo.cor} stroke-width="8" fill="none" stroke-linecap="round" />
|
||||||
|
{:else if passo?.olhos === 'triste'}
|
||||||
|
<path d="M18 26 Q30 44 42 26 M58 26 Q70 44 82 26" stroke={passo.cor} stroke-width="8" fill="none" stroke-linecap="round" />
|
||||||
|
{:else}
|
||||||
|
{@const ry = passo?.olhos === 'surpreso' ? 20 : 16}
|
||||||
|
<ellipse cx="30" cy="30" rx="12" {ry} fill={passo?.cor ?? '#5cd6ff'} />
|
||||||
|
<ellipse cx="70" cy="30" rx="12" {ry} fill={passo?.cor ?? '#5cd6ff'} />
|
||||||
|
{/if}
|
||||||
|
</svg>
|
||||||
|
{#if simbolo}<span class="simbolo">{simbolo}</span>{/if}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.miniatura {
|
||||||
|
position: relative;
|
||||||
|
width: var(--t);
|
||||||
|
height: var(--t);
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
border-radius: var(--raio);
|
||||||
|
background: #05080c;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
.emoji {
|
||||||
|
font-size: calc(var(--t) * 0.55);
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
.simbolo {
|
||||||
|
position: absolute;
|
||||||
|
right: 2px;
|
||||||
|
bottom: 0;
|
||||||
|
font-size: calc(var(--t) * 0.3);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { X } from '@lucide/svelte';
|
||||||
|
import type { Snippet } from 'svelte';
|
||||||
|
|
||||||
|
// <dialog> nativo: foco preso, Esc e fundo vêm de graça.
|
||||||
|
let { aberto = $bindable(false), titulo, children }: { aberto: boolean; titulo: string; children: Snippet } = $props();
|
||||||
|
let dialogo: HTMLDialogElement;
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (aberto && !dialogo.open) dialogo.showModal();
|
||||||
|
else if (!aberto && dialogo.open) dialogo.close();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<dialog
|
||||||
|
bind:this={dialogo}
|
||||||
|
onclose={() => (aberto = false)}
|
||||||
|
onclick={(e) => e.target === dialogo && (aberto = false)}
|
||||||
|
aria-label={titulo}
|
||||||
|
>
|
||||||
|
<div class="conteudo">
|
||||||
|
<header>
|
||||||
|
<h2>{titulo}</h2>
|
||||||
|
<button class="btn fantasma icone pequeno" aria-label="Fechar" onclick={() => (aberto = false)}><X size={18} /></button>
|
||||||
|
</header>
|
||||||
|
{#if aberto}{@render children()}{/if}
|
||||||
|
</div>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
dialog {
|
||||||
|
width: min(480px, calc(100vw - 2 * var(--e-4)));
|
||||||
|
padding: 0;
|
||||||
|
border: 1px solid var(--borda-forte);
|
||||||
|
border-radius: var(--raio-lg);
|
||||||
|
background: var(--superficie);
|
||||||
|
color: var(--texto);
|
||||||
|
box-shadow: var(--sombra-flutuante);
|
||||||
|
}
|
||||||
|
dialog::backdrop {
|
||||||
|
background: rgb(0 0 0 / 0.5);
|
||||||
|
}
|
||||||
|
.conteudo {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-4);
|
||||||
|
padding: var(--e-5);
|
||||||
|
}
|
||||||
|
header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
h2 {
|
||||||
|
font-size: var(--t-lg);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -101,7 +101,7 @@ img, video, canvas, iframe { max-width: 100%; }
|
|||||||
.btn.fantasma:hover:not(:disabled) { background: var(--superficie-2); }
|
.btn.fantasma:hover:not(:disabled) { background: var(--superficie-2); }
|
||||||
.btn.icone { padding: 0; width: 40px; }
|
.btn.icone { padding: 0; width: 40px; }
|
||||||
.btn.pequeno { min-height: 32px; padding: 0 var(--e-3); font-size: var(--t-xs); }
|
.btn.pequeno { min-height: 32px; padding: 0 var(--e-3); font-size: var(--t-xs); }
|
||||||
.btn.pequeno.icone { width: 32px; }
|
.btn.pequeno.icone { width: 32px; padding: 0; }
|
||||||
|
|
||||||
/* ---------- formulários ---------- */
|
/* ---------- formulários ---------- */
|
||||||
.campo { display: grid; gap: var(--e-1); }
|
.campo { display: grid; gap: var(--e-1); }
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
/**
|
||||||
|
* Biblioteca de reações, rotinas e diário (/treinamento/*). Sem polling: recarrega ao abrir a
|
||||||
|
* tela, depois de cada ação e quando o servidor avisa (SSE 'treinamento') que terminou de criar.
|
||||||
|
*/
|
||||||
|
import { pedir, postar } from './api';
|
||||||
|
import { avisos } from './avisos.svelte';
|
||||||
|
import { ouvir } from './estado.svelte';
|
||||||
|
|
||||||
|
export interface ReacaoBiblioteca {
|
||||||
|
id: number;
|
||||||
|
horario: number;
|
||||||
|
receita: any;
|
||||||
|
feedback: -1 | 0 | 1;
|
||||||
|
ativa: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StatusTreinamento {
|
||||||
|
ocupado: boolean;
|
||||||
|
erro: string;
|
||||||
|
automatico: boolean;
|
||||||
|
rotina: { id: number; texto: string }[];
|
||||||
|
diario: { id: number; horario: number; papel: string; texto: string }[];
|
||||||
|
resumos: { id: number; horario: number; texto: string }[];
|
||||||
|
emojis: string[];
|
||||||
|
desfazer: [string] | null;
|
||||||
|
reacoes: ReacaoBiblioteca[];
|
||||||
|
prompt_orientacao: string;
|
||||||
|
ultimo_prompt_figurinha: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Treinamento {
|
||||||
|
status = $state<StatusTreinamento | null>(null);
|
||||||
|
carregando = $state(false);
|
||||||
|
|
||||||
|
async carregar() {
|
||||||
|
this.carregando = true;
|
||||||
|
try {
|
||||||
|
this.status = await pedir<StatusTreinamento>('/treinamento/status');
|
||||||
|
} catch (e) {
|
||||||
|
avisos.erro(e);
|
||||||
|
} finally {
|
||||||
|
this.carregando = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Executa uma ação e recarrega; devolve true se deu certo (erro vira toast). */
|
||||||
|
async acao(rota: string, dados: object = {}, sucesso?: string) {
|
||||||
|
try {
|
||||||
|
await postar('/treinamento/' + rota, dados);
|
||||||
|
if (sucesso) avisos.ok(sucesso);
|
||||||
|
await this.carregar();
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
avisos.erro(e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const treinamento = new Treinamento();
|
||||||
|
|
||||||
|
let estavaOcupado = false;
|
||||||
|
ouvir('treinamento', (d: { ocupado: boolean; erro: string }) => {
|
||||||
|
if (treinamento.status) treinamento.status = { ...treinamento.status, ocupado: d.ocupado, erro: d.erro };
|
||||||
|
if (estavaOcupado && !d.ocupado) {
|
||||||
|
if (d.erro) avisos.mostrar('Gemini: ' + d.erro, 'erro');
|
||||||
|
else avisos.ok('Novas reações prontas.');
|
||||||
|
treinamento.carregar();
|
||||||
|
}
|
||||||
|
estavaOcupado = d.ocupado;
|
||||||
|
});
|
||||||
|
|
||||||
|
export const SIMBOLO_EMOJI: Record<string, string> = { ideia: '💡', cafe: '☕', musica: '🎵', coracao: '❤️', estrela: '⭐' };
|
||||||
@@ -1,7 +1,403 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { Mic, MicOff, Plus, Send, Trash2, Volume2, X } from '@lucide/svelte';
|
||||||
|
import { onMount, tick } from 'svelte';
|
||||||
|
import { postar } from '../lib/api';
|
||||||
|
import { avisos, tentar } from '../lib/avisos.svelte';
|
||||||
|
import { gesto, GESTOS_INFO } from '../lib/comandos.svelte';
|
||||||
|
import Abas from '../lib/componentes/Abas.svelte';
|
||||||
import Card from '../lib/componentes/Card.svelte';
|
import Card from '../lib/componentes/Card.svelte';
|
||||||
|
import Selo from '../lib/componentes/Selo.svelte';
|
||||||
|
import Toggle from '../lib/componentes/Toggle.svelte';
|
||||||
|
import { estado, ouvir } from '../lib/estado.svelte';
|
||||||
|
import { treinamento } from '../lib/treinamento.svelte';
|
||||||
|
|
||||||
|
const SUGESTOES = ['Oi, Carinha! Tudo bem?', 'Que horas são?', 'Me conta uma curiosidade', 'Como você está se sentindo?'];
|
||||||
|
|
||||||
|
let texto = $state('');
|
||||||
|
let enviando = $state(false);
|
||||||
|
let lista = $state<HTMLElement>();
|
||||||
|
const conversa = $derived(estado.conversa);
|
||||||
|
const ocupado = $derived(enviando || !!conversa?.ocupado);
|
||||||
|
|
||||||
|
async function enviar(mensagem = texto) {
|
||||||
|
const t = mensagem.trim();
|
||||||
|
if (!t || ocupado) return;
|
||||||
|
enviando = true;
|
||||||
|
try {
|
||||||
|
await postar('/conversa/enviar', { texto: t });
|
||||||
|
texto = '';
|
||||||
|
} catch (e) {
|
||||||
|
avisos.erro(e);
|
||||||
|
} finally {
|
||||||
|
enviando = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rola para o fim quando chegam mensagens.
|
||||||
|
$effect(() => {
|
||||||
|
void conversa?.historico.length;
|
||||||
|
void conversa?.ocupado;
|
||||||
|
tick().then(() => lista?.scrollTo({ top: lista.scrollHeight, behavior: 'smooth' }));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- voz (Web Speech API): fala só respostas novas, nunca a antiga ao abrir
|
||||||
|
let lerEmVoz = $state(false);
|
||||||
|
try {
|
||||||
|
lerEmVoz = localStorage.getItem('carinha_voz') === '1';
|
||||||
|
} catch {
|
||||||
|
/* ok */
|
||||||
|
}
|
||||||
|
function falar(t: string) {
|
||||||
|
if (!('speechSynthesis' in window) || !t) return;
|
||||||
|
speechSynthesis.cancel();
|
||||||
|
const u = new SpeechSynthesisUtterance(t);
|
||||||
|
u.lang = 'pt-BR';
|
||||||
|
u.pitch = 1.35;
|
||||||
|
u.rate = 1.05;
|
||||||
|
const voz = speechSynthesis.getVoices().find((v) => v.lang.startsWith('pt'));
|
||||||
|
if (voz) u.voice = voz;
|
||||||
|
speechSynthesis.speak(u);
|
||||||
|
}
|
||||||
|
let ultimaFalada = estado.conversa?.ultima?.id;
|
||||||
|
onMount(() =>
|
||||||
|
ouvir('conversa', (c) => {
|
||||||
|
if (c.ultima && c.ultima.id !== ultimaFalada) {
|
||||||
|
ultimaFalada = c.ultima.id;
|
||||||
|
if (lerEmVoz) falar(c.ultima.texto);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const Reconhecimento = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
|
||||||
|
const vozDisponivel = !!Reconhecimento && window.isSecureContext;
|
||||||
|
const motivoSemVoz = !Reconhecimento
|
||||||
|
? 'Este navegador não reconhece voz.'
|
||||||
|
: 'O microfone do navegador exige HTTPS ou localhost.';
|
||||||
|
let gravando = $state(false);
|
||||||
|
let reconhecimento: any = null;
|
||||||
|
function microfone() {
|
||||||
|
if (gravando) return reconhecimento?.stop();
|
||||||
|
reconhecimento = new Reconhecimento();
|
||||||
|
reconhecimento.lang = 'pt-BR';
|
||||||
|
reconhecimento.interimResults = false;
|
||||||
|
reconhecimento.onstart = () => (gravando = true);
|
||||||
|
reconhecimento.onend = () => (gravando = false);
|
||||||
|
reconhecimento.onerror = (e: any) => {
|
||||||
|
gravando = false;
|
||||||
|
avisos.mostrar(e.error === 'not-allowed' ? 'Permissão do microfone negada.' : 'Microfone: ' + e.error, 'erro');
|
||||||
|
};
|
||||||
|
reconhecimento.onresult = (e: any) => {
|
||||||
|
texto = e.results[0][0].transcript;
|
||||||
|
enviar();
|
||||||
|
};
|
||||||
|
reconhecimento.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- memória: lembranças da conversa + rotinas do treinamento
|
||||||
|
type AbaMemoria = 'lembrancas' | 'rotinas';
|
||||||
|
let aba = $state<AbaMemoria>('lembrancas');
|
||||||
|
let nova = $state('');
|
||||||
|
const itensMemoria = $derived(aba === 'lembrancas' ? (conversa?.lembrancas ?? []) : (treinamento.status?.rotina ?? []));
|
||||||
|
onMount(() => {
|
||||||
|
treinamento.carregar();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function adicionar(e: SubmitEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
const t = nova.trim();
|
||||||
|
if (!t) return;
|
||||||
|
const ok =
|
||||||
|
aba === 'lembrancas'
|
||||||
|
? await tentar(() => postar('/conversa/lembrar', { texto: t }))
|
||||||
|
: await treinamento.acao('rotina', { texto: t });
|
||||||
|
if (ok) nova = '';
|
||||||
|
}
|
||||||
|
const apagarLembranca = (id: number) => tentar(() => postar('/conversa/apagar', { id }));
|
||||||
|
const apagarRotina = (id: number) => treinamento.acao('rotina-apagar', { id });
|
||||||
|
|
||||||
|
let confirmarLimpar = $state(false);
|
||||||
|
async function limparTudo() {
|
||||||
|
confirmarLimpar = false;
|
||||||
|
await tentar(() => postar('/conversa/limpar'), 'Conversa, lembranças e diário apagados.');
|
||||||
|
treinamento.carregar();
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<Card titulo="Conversa" descricao="Chat, voz e memória migram na fase 3.">
|
<div class="conversa">
|
||||||
<p class="pequeno-texto">Enquanto isso, use a tela antiga: <a href="/conversa">abrir Conversa (versão anterior)</a>.</p>
|
<Card class="chat">
|
||||||
|
{#snippet acoes()}
|
||||||
|
{#if conversa}
|
||||||
|
<Selo tom="destaque">{conversa.provedor === 'gemini' ? 'Gemini' : 'Qwen local'} · {conversa.modelo}</Selo>
|
||||||
|
<a class="pequeno-texto" href="#/ajustes">trocar</a>
|
||||||
|
{/if}
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
<div class="mensagens" bind:this={lista} aria-live="polite">
|
||||||
|
{#if !conversa?.historico.length}
|
||||||
|
<div class="boas-vindas">
|
||||||
|
<p>Converse com o Carinha. Ele responde aqui e reage com o rosto no celular.</p>
|
||||||
|
<div class="sugestoes">
|
||||||
|
{#each SUGESTOES as s (s)}
|
||||||
|
<button class="btn pequeno" onclick={() => enviar(s)} disabled={ocupado}>{s}</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{#each conversa?.historico ?? [] as m, i (i)}
|
||||||
|
<div class="msg {m.role}">
|
||||||
|
<p>{m.content}</p>
|
||||||
|
{#if m.role === 'assistant'}
|
||||||
|
<button class="btn fantasma pequeno icone" aria-label="Ler em voz alta" onclick={() => falar(m.content)}>
|
||||||
|
<Volume2 size={14} />
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{#if conversa?.ocupado}
|
||||||
|
<div class="msg assistant pensando" aria-label="Carinha está pensando"><span></span><span></span><span></span></div>
|
||||||
|
{/if}
|
||||||
|
{#if conversa?.ultima && !conversa.ocupado && GESTOS_INFO[conversa.ultima.gesto]}
|
||||||
|
<button class="gesto-resposta" onclick={() => gesto(conversa.ultima!.gesto)}>
|
||||||
|
{GESTOS_INFO[conversa.ultima.gesto].emoji} reagiu com {GESTOS_INFO[conversa.ultima.gesto].nome.toLowerCase()} · repetir
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if conversa?.erro}<p class="erro pequeno-texto">{conversa.erro}</p>{/if}
|
||||||
|
|
||||||
|
<form
|
||||||
|
class="entrada"
|
||||||
|
onsubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
enviar();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn icone"
|
||||||
|
class:gravando
|
||||||
|
onclick={microfone}
|
||||||
|
disabled={!vozDisponivel || ocupado}
|
||||||
|
title={vozDisponivel ? (gravando ? 'Parar de ouvir' : 'Falar') : motivoSemVoz}
|
||||||
|
aria-label={gravando ? 'Parar de ouvir' : 'Falar'}
|
||||||
|
>
|
||||||
|
{#if vozDisponivel}<Mic size={18} />{:else}<MicOff size={18} />{/if}
|
||||||
|
</button>
|
||||||
|
<input type="text" bind:value={texto} placeholder="Escreva para o Carinha…" maxlength="600" aria-label="Mensagem" />
|
||||||
|
<button class="btn primario" type="submit" disabled={ocupado || !texto.trim()}>
|
||||||
|
<Send size={16} /> <span class="rotulo-enviar">Enviar</span>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
<div class="linha entre">
|
||||||
|
<Toggle
|
||||||
|
rotulo="Ler respostas em voz alta neste PC"
|
||||||
|
checked={lerEmVoz}
|
||||||
|
onchange={(v) => {
|
||||||
|
lerEmVoz = v;
|
||||||
|
try {
|
||||||
|
localStorage.setItem('carinha_voz', v ? '1' : '0');
|
||||||
|
} catch {
|
||||||
|
/* ok */
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
<Card titulo="Memória" descricao="O que o Carinha leva em conta ao responder. São dados, nunca instruções.">
|
||||||
|
<Abas
|
||||||
|
rotulo="Memória"
|
||||||
|
bind:ativa={aba}
|
||||||
|
abas={[
|
||||||
|
{ id: 'lembrancas', titulo: 'Lembranças', contador: conversa?.lembrancas.length ?? 0 },
|
||||||
|
{ id: 'rotinas', titulo: 'Rotina e preferências', contador: treinamento.status?.rotina.length ?? 0 },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
<form class="linha nova" onsubmit={adicionar}>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
bind:value={nova}
|
||||||
|
maxlength="300"
|
||||||
|
placeholder={aba === 'lembrancas' ? 'Ex.: Meu nome é Júlio' : 'Ex.: Treino às 7h de segunda a sexta'}
|
||||||
|
aria-label={aba === 'lembrancas' ? 'Nova lembrança' : 'Nova rotina'}
|
||||||
|
/>
|
||||||
|
<button class="btn" type="submit" disabled={!nova.trim()}><Plus size={16} /> Adicionar</button>
|
||||||
|
</form>
|
||||||
|
<ul class="itens">
|
||||||
|
{#each itensMemoria as item (item.id)}
|
||||||
|
<li>
|
||||||
|
<span>{item.texto}</span>
|
||||||
|
<button
|
||||||
|
class="btn fantasma pequeno icone"
|
||||||
|
aria-label="Apagar"
|
||||||
|
onclick={() => (aba === 'lembrancas' ? apagarLembranca(item.id) : apagarRotina(item.id))}
|
||||||
|
>
|
||||||
|
<X size={14} />
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
{:else}
|
||||||
|
<li class="fraco pequeno-texto">Nada guardado ainda.</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
<div class="perigo-zona">
|
||||||
|
{#if confirmarLimpar}
|
||||||
|
<p class="pequeno-texto">Apagar conversa, lembranças e diário? Rotinas e reações ficam.</p>
|
||||||
|
<div class="linha">
|
||||||
|
<button class="btn perigo pequeno" onclick={limparTudo}>Sim, apagar</button>
|
||||||
|
<button class="btn pequeno" onclick={() => (confirmarLimpar = false)}>Cancelar</button>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<button class="btn fantasma pequeno" onclick={() => (confirmarLimpar = true)}>
|
||||||
|
<Trash2 size={14} /> Apagar conversa e lembranças
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.conversa {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-4);
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
:global(.chat) {
|
||||||
|
grid-template-rows: auto 1fr auto auto;
|
||||||
|
}
|
||||||
|
.mensagens {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--e-3);
|
||||||
|
min-height: 320px;
|
||||||
|
max-height: min(60vh, 640px);
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: var(--e-1);
|
||||||
|
}
|
||||||
|
.boas-vindas {
|
||||||
|
margin: auto;
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-4);
|
||||||
|
justify-items: center;
|
||||||
|
text-align: center;
|
||||||
|
color: var(--texto-2);
|
||||||
|
max-width: 420px;
|
||||||
|
}
|
||||||
|
.sugestoes {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: var(--e-2);
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
.msg {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-end;
|
||||||
|
gap: var(--e-1);
|
||||||
|
max-width: 82%;
|
||||||
|
}
|
||||||
|
.msg p {
|
||||||
|
padding: var(--e-2) var(--e-3);
|
||||||
|
border-radius: var(--raio);
|
||||||
|
white-space: pre-wrap;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.msg.user {
|
||||||
|
align-self: flex-end;
|
||||||
|
}
|
||||||
|
.msg.user p {
|
||||||
|
background: var(--destaque);
|
||||||
|
color: var(--destaque-texto);
|
||||||
|
border-bottom-right-radius: 4px;
|
||||||
|
}
|
||||||
|
.msg.assistant p {
|
||||||
|
background: var(--superficie-2);
|
||||||
|
border: 1px solid var(--borda);
|
||||||
|
border-bottom-left-radius: 4px;
|
||||||
|
}
|
||||||
|
.pensando {
|
||||||
|
gap: 4px;
|
||||||
|
padding: var(--e-3);
|
||||||
|
border-radius: var(--raio);
|
||||||
|
background: var(--superficie-2);
|
||||||
|
width: fit-content;
|
||||||
|
}
|
||||||
|
.pensando span {
|
||||||
|
width: 7px;
|
||||||
|
height: 7px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--texto-3);
|
||||||
|
animation: pulo 1s infinite ease-in-out;
|
||||||
|
}
|
||||||
|
.pensando span:nth-child(2) {
|
||||||
|
animation-delay: 0.15s;
|
||||||
|
}
|
||||||
|
.pensando span:nth-child(3) {
|
||||||
|
animation-delay: 0.3s;
|
||||||
|
}
|
||||||
|
@keyframes pulo {
|
||||||
|
50% {
|
||||||
|
transform: translateY(-4px);
|
||||||
|
opacity: 0.5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.gesto-resposta {
|
||||||
|
align-self: flex-start;
|
||||||
|
border: 1px dashed var(--borda-forte);
|
||||||
|
border-radius: var(--raio-pill);
|
||||||
|
background: transparent;
|
||||||
|
color: var(--texto-2);
|
||||||
|
font: var(--t-xs) var(--fonte);
|
||||||
|
padding: 4px 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.entrada {
|
||||||
|
display: flex;
|
||||||
|
gap: var(--e-2);
|
||||||
|
}
|
||||||
|
.gravando {
|
||||||
|
background: var(--perigo-suave);
|
||||||
|
border-color: var(--perigo);
|
||||||
|
color: var(--perigo);
|
||||||
|
}
|
||||||
|
.erro {
|
||||||
|
color: var(--perigo);
|
||||||
|
}
|
||||||
|
.nova input {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 180px;
|
||||||
|
}
|
||||||
|
.itens {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-1);
|
||||||
|
max-height: 320px;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
.itens li {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: var(--e-2);
|
||||||
|
padding: var(--e-2) var(--e-3);
|
||||||
|
border-radius: var(--raio-sm);
|
||||||
|
background: var(--superficie-2);
|
||||||
|
font-size: var(--t-sm);
|
||||||
|
}
|
||||||
|
.perigo-zona {
|
||||||
|
border-top: 1px solid var(--borda);
|
||||||
|
padding-top: var(--e-3);
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-2);
|
||||||
|
}
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.rotulo-enviar {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (min-width: 1100px) {
|
||||||
|
.conversa {
|
||||||
|
grid-template-columns: 3fr 2fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|||||||
@@ -1,7 +1,88 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import Card from '../lib/componentes/Card.svelte';
|
import { Power } from '@lucide/svelte';
|
||||||
|
import { onDestroy, onMount } from 'svelte';
|
||||||
|
import { braco } from '../lib/braco.svelte';
|
||||||
|
import Abas from '../lib/componentes/Abas.svelte';
|
||||||
|
import Selo from '../lib/componentes/Selo.svelte';
|
||||||
|
import { estado } from '../lib/estado.svelte';
|
||||||
|
import { registrarNaPaleta } from '../lib/paleta.svelte';
|
||||||
|
import Calibracao from './movimento/Calibracao.svelte';
|
||||||
|
import Controle from './movimento/Controle.svelte';
|
||||||
|
import Diagnostico from './movimento/Diagnostico.svelte';
|
||||||
|
|
||||||
|
type Aba = 'controle' | 'calibracao' | 'diagnostico';
|
||||||
|
let aba = $state<Aba>('controle');
|
||||||
|
const motores = $derived(estado.motores);
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
braco.carregar();
|
||||||
|
});
|
||||||
|
// Posturas na paleta: carregar como alvo (mover exige segurar o botão).
|
||||||
|
const sair = registrarNaPaleta(() =>
|
||||||
|
(braco.status?.posturas ?? []).map((p, i) => ({
|
||||||
|
id: 'postura-' + i,
|
||||||
|
grupo: 'Posturas do braço',
|
||||||
|
titulo: 'Carregar ' + p.nome,
|
||||||
|
fazer: () => (braco.alvo = [...p.angulos]),
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
onDestroy(() => {
|
||||||
|
sair();
|
||||||
|
braco.soltar();
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<Card titulo="Movimento" descricao="Braço, calibração e diagnóstico migram na fase 4.">
|
<div class="movimento">
|
||||||
<p class="pequeno-texto">Enquanto isso, use a tela antiga: <a href="/braco">abrir Movimento (versão anterior)</a>.</p>
|
<div class="estado">
|
||||||
</Card>
|
<div class="linha">
|
||||||
|
{#if !motores?.disponivel}
|
||||||
|
<Selo tom="aviso">PCA9685 indisponível neste servidor</Selo>
|
||||||
|
{:else if estado.estop.ativo || motores.travado}
|
||||||
|
<Selo tom="perigo">Travado pelo E-Stop</Selo>
|
||||||
|
{:else if motores.ativos.length}
|
||||||
|
<Selo tom="ok">Motores ligados · {motores.dono === 'braco' ? 'braço' : 'diagnóstico'} · canais {motores.ativos.join(', ')}</Selo>
|
||||||
|
{:else}
|
||||||
|
<Selo>Motores desligados</Selo>
|
||||||
|
{/if}
|
||||||
|
{#if motores?.erro}<span class="erro pequeno-texto">{motores.erro}</span>{/if}
|
||||||
|
</div>
|
||||||
|
<button class="btn" onclick={() => braco.pararMotores()} disabled={!motores?.ativos.length}>
|
||||||
|
<Power size={16} /> Desligar motores
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Abas
|
||||||
|
rotulo="Movimento"
|
||||||
|
bind:ativa={aba}
|
||||||
|
abas={[
|
||||||
|
{ id: 'controle', titulo: 'Controle' },
|
||||||
|
{ id: 'calibracao', titulo: 'Calibração' },
|
||||||
|
{ id: 'diagnostico', titulo: 'Diagnóstico' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{#if aba === 'controle'}
|
||||||
|
<Controle />
|
||||||
|
{:else if aba === 'calibracao'}
|
||||||
|
<Calibracao />
|
||||||
|
{:else}
|
||||||
|
<Diagnostico />
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.movimento {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-4);
|
||||||
|
}
|
||||||
|
.estado {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--e-3);
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.erro {
|
||||||
|
color: var(--perigo);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|||||||
@@ -1,7 +1,449 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import {
|
||||||
|
Copy, Download, Eye, EyeOff, Pencil, Plus, Search, Send, Sparkles, Square, ThumbsDown, ThumbsUp, Trash2, Undo2,
|
||||||
|
} from '@lucide/svelte';
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { postar } from '../lib/api';
|
||||||
|
import { avisos, tentar } from '../lib/avisos.svelte';
|
||||||
|
import Abas from '../lib/componentes/Abas.svelte';
|
||||||
import Card from '../lib/componentes/Card.svelte';
|
import Card from '../lib/componentes/Card.svelte';
|
||||||
|
import Gestos from '../lib/componentes/Gestos.svelte';
|
||||||
|
import Miniatura from '../lib/componentes/Miniatura.svelte';
|
||||||
|
import Modal from '../lib/componentes/Modal.svelte';
|
||||||
|
import RostoPrevia from '../lib/componentes/RostoPrevia.svelte';
|
||||||
|
import Selo from '../lib/componentes/Selo.svelte';
|
||||||
|
import Toggle from '../lib/componentes/Toggle.svelte';
|
||||||
|
import { treinamento, type ReacaoBiblioteca } from '../lib/treinamento.svelte';
|
||||||
|
|
||||||
|
type Aba = 'biblioteca' | 'criar' | 'gestos' | 'diario';
|
||||||
|
let aba = $state<Aba>('biblioteca');
|
||||||
|
let previa = $state<{ previa: (receita: unknown) => void }>();
|
||||||
|
let busca = $state('');
|
||||||
|
const st = $derived(treinamento.status);
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
treinamento.carregar();
|
||||||
|
});
|
||||||
|
|
||||||
|
const normal = (t: string) => t.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
|
||||||
|
const reacoes = $derived(
|
||||||
|
(st?.reacoes ?? []).filter((r) => !busca || normal(r.receita.nome + ' ' + r.receita.motivo).includes(normal(busca))),
|
||||||
|
);
|
||||||
|
const tipo = (r: ReacaoBiblioteca) => (r.receita.figurinha ? 'Desenho' : r.receita.emoji ? 'Emoji' : 'Animação');
|
||||||
|
|
||||||
|
// ---------- ações da biblioteca
|
||||||
|
const mostrar = (r: ReacaoBiblioteca) => tentar(() => postar('/comando', { tipo: 'reacao', valor: r.id }), 'Enviada ao celular.');
|
||||||
|
const pararNoCelular = () => {
|
||||||
|
previa?.previa({ limpar: true });
|
||||||
|
tentar(() => postar('/comando', { tipo: 'parar_reacao' }));
|
||||||
|
};
|
||||||
|
const biblioteca = (dados: object, sucesso?: string) => treinamento.acao('biblioteca', dados, sucesso);
|
||||||
|
const desfazer = () => biblioteca({ acao: 'desfazer' }, 'Alteração desfeita.');
|
||||||
|
|
||||||
|
async function excluir(r: ReacaoBiblioteca) {
|
||||||
|
if (await biblioteca({ acao: 'excluir', id: r.id }))
|
||||||
|
avisos.ok(`“${r.receita.nome}” excluída.`, { rotulo: 'Desfazer', fazer: desfazer });
|
||||||
|
}
|
||||||
|
const feedback = (r: ReacaoBiblioteca, valor: -1 | 1) =>
|
||||||
|
treinamento.acao('feedback', { id: r.id, valor: r.feedback === valor ? 0 : valor });
|
||||||
|
|
||||||
|
function exportar() {
|
||||||
|
if (!st) return;
|
||||||
|
const url = URL.createObjectURL(
|
||||||
|
new Blob([JSON.stringify(st.reacoes.map((r) => r.receita), null, 2)], { type: 'application/json' }),
|
||||||
|
);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = 'carinha-reacoes.json';
|
||||||
|
a.click();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- editor
|
||||||
|
let editorAberto = $state(false);
|
||||||
|
let editando = $state<ReacaoBiblioteca | null>(null);
|
||||||
|
let form = $state({ nome: '', motivo: '', caractere: '💡', local: 'olhos' });
|
||||||
|
function abrirEditor(r: ReacaoBiblioteca | null) {
|
||||||
|
editando = r;
|
||||||
|
form = {
|
||||||
|
nome: r?.receita.nome ?? '',
|
||||||
|
motivo: r?.receita.motivo ?? '',
|
||||||
|
caractere: r?.receita.emoji?.caractere ?? (r ? '' : '💡'),
|
||||||
|
local: r?.receita.emoji?.local ?? r?.receita.figurinha?.local ?? 'olhos',
|
||||||
|
};
|
||||||
|
editorAberto = true;
|
||||||
|
}
|
||||||
|
async function salvarEditor(e: SubmitEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
const dados = { acao: editando ? 'editar' : 'criar', id: editando?.id ?? null, ...form, nome: form.nome.trim(), motivo: form.motivo.trim() };
|
||||||
|
if (await biblioteca(dados, editando ? 'Reação atualizada.' : 'Emoji criado.')) editorAberto = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- criar com IA
|
||||||
|
let pedido = $state('');
|
||||||
|
async function desenhar(e: SubmitEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (await treinamento.acao('figurinha', { texto: pedido.trim() }, 'Pedido enviado ao Gemini. A figurinha aparece no celular quando ficar pronta.'))
|
||||||
|
pedido = '';
|
||||||
|
}
|
||||||
|
let confirmarDiario = $state(false);
|
||||||
|
const hora = (t: number) => new Date(t * 1000).toLocaleString('pt-BR', { dateStyle: 'short', timeStyle: 'short' });
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<Card titulo="Reações" descricao="Biblioteca e criação com IA migram na fase 3.">
|
<div class="reacoes">
|
||||||
<p class="pequeno-texto">Enquanto isso, use a tela antiga: <a href="/emojis">abrir Reações (versão anterior)</a>.</p>
|
<div class="principal">
|
||||||
|
<Abas
|
||||||
|
rotulo="Reações"
|
||||||
|
bind:ativa={aba}
|
||||||
|
abas={[
|
||||||
|
{ id: 'biblioteca', titulo: 'Biblioteca', contador: st?.reacoes.length },
|
||||||
|
{ id: 'criar', titulo: 'Criar com IA' },
|
||||||
|
{ id: 'gestos', titulo: 'Gestos do rosto' },
|
||||||
|
{ id: 'diario', titulo: 'Diário' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{#if aba === 'biblioteca'}
|
||||||
|
<div class="barra">
|
||||||
|
<label class="busca">
|
||||||
|
<Search size={16} />
|
||||||
|
<input type="search" bind:value={busca} placeholder="Buscar reação" aria-label="Buscar reação" />
|
||||||
|
</label>
|
||||||
|
<button class="btn primario" onclick={() => abrirEditor(null)} disabled={st?.ocupado}><Plus size={16} /> Novo emoji</button>
|
||||||
|
<button class="btn" onclick={desfazer} disabled={!st?.desfazer || st?.ocupado}><Undo2 size={16} /> Desfazer</button>
|
||||||
|
<button class="btn" onclick={pararNoCelular}><Square size={16} /> Parar no celular</button>
|
||||||
|
<button class="btn fantasma" onclick={exportar} disabled={!st?.reacoes.length}><Download size={16} /> Exportar</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if !st}
|
||||||
|
<p class="fraco">Carregando biblioteca…</p>
|
||||||
|
{:else}
|
||||||
|
<ul class="grade-reacoes">
|
||||||
|
{#each reacoes as r (r.id)}
|
||||||
|
<li class="reacao" class:inativa={!r.ativa}>
|
||||||
|
<button class="topo" onclick={() => previa?.previa(r.receita)} title="Ver na prévia">
|
||||||
|
<Miniatura receita={r.receita} />
|
||||||
|
<div class="info">
|
||||||
|
<strong>{r.receita.nome}</strong>
|
||||||
|
<span class="fraco pequeno-texto">{r.receita.motivo}</span>
|
||||||
|
<span class="linha">
|
||||||
|
<Selo>{tipo(r)}</Selo>
|
||||||
|
{#if !r.ativa}<Selo tom="aviso">Desativada</Selo>{/if}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
<div class="acoes">
|
||||||
|
<button class="btn pequeno primario" onclick={() => mostrar(r)}><Send size={14} /> Mostrar</button>
|
||||||
|
<button
|
||||||
|
class="btn pequeno icone"
|
||||||
|
class:marcado={r.feedback === 1}
|
||||||
|
aria-pressed={r.feedback === 1}
|
||||||
|
aria-label="Gostei"
|
||||||
|
onclick={() => feedback(r, 1)}><ThumbsUp size={14} /></button
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
class="btn pequeno icone"
|
||||||
|
class:marcado-ruim={r.feedback === -1}
|
||||||
|
aria-pressed={r.feedback === -1}
|
||||||
|
aria-label="Não gostei"
|
||||||
|
onclick={() => feedback(r, -1)}><ThumbsDown size={14} /></button
|
||||||
|
>
|
||||||
|
<span class="espaco"></span>
|
||||||
|
<button class="btn pequeno icone fantasma" aria-label="Editar" title="Editar" onclick={() => abrirEditor(r)}><Pencil size={14} /></button>
|
||||||
|
<button class="btn pequeno icone fantasma" aria-label="Duplicar" title="Duplicar" onclick={() => biblioteca({ acao: 'duplicar', id: r.id }, 'Reação duplicada.')}
|
||||||
|
><Copy size={14} /></button
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
class="btn pequeno icone fantasma"
|
||||||
|
aria-label={r.ativa ? 'Desativar' : 'Ativar'}
|
||||||
|
title={r.ativa ? 'Desativar (a IA deixa de usar)' : 'Ativar'}
|
||||||
|
onclick={() => biblioteca({ acao: 'ativar', id: r.id, ativa: !r.ativa })}
|
||||||
|
>
|
||||||
|
{#if r.ativa}<EyeOff size={14} />{:else}<Eye size={14} />{/if}
|
||||||
|
</button>
|
||||||
|
<button class="btn pequeno icone fantasma perigo-texto" aria-label="Excluir" title="Excluir" onclick={() => excluir(r)}><Trash2 size={14} /></button>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
{:else}
|
||||||
|
<li class="fraco">{busca ? 'Nenhuma reação encontrada.' : 'Crie um emoji ou peça um desenho ao Gemini.'}</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
{/if}
|
||||||
|
{:else if aba === 'criar'}
|
||||||
|
<div class="grade-criar">
|
||||||
|
<Card titulo="Desenhar figurinha" descricao="O Gemini desenha um SVG e o celular mostra assim que ficar pronto.">
|
||||||
|
<form class="grade" onsubmit={desenhar}>
|
||||||
|
<label class="campo">
|
||||||
|
<span>O que desenhar</span>
|
||||||
|
<textarea bind:value={pedido} maxlength="1000" placeholder="Ex.: um sol de óculos escuros sorrindo" required></textarea>
|
||||||
|
</label>
|
||||||
|
<button class="btn primario" type="submit" disabled={st?.ocupado || !pedido.trim()}>
|
||||||
|
<Sparkles size={16} /> {st?.ocupado ? 'Gemini trabalhando…' : 'Desenhar e mostrar'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
{#if st?.ultimo_prompt_figurinha}
|
||||||
|
<details>
|
||||||
|
<summary class="pequeno-texto fraco">Último pedido enviado</summary>
|
||||||
|
<pre class="mono">{st.ultimo_prompt_figurinha}</pre>
|
||||||
|
</details>
|
||||||
|
{/if}
|
||||||
</Card>
|
</Card>
|
||||||
|
<Card titulo="Reações automáticas" descricao="A partir da conversa e da rotina, o Gemini inventa 3 animações novas.">
|
||||||
|
<button class="btn" onclick={() => treinamento.acao('gerar', {}, 'Gemini está criando 3 reações…')} disabled={st?.ocupado}>
|
||||||
|
<Sparkles size={16} /> Gerar 3 agora
|
||||||
|
</button>
|
||||||
|
<Toggle
|
||||||
|
rotulo="Gerar sozinho a cada hora"
|
||||||
|
ajuda="Cada geração é uma chamada paga ao Gemini"
|
||||||
|
checked={!!st?.automatico}
|
||||||
|
disabled={!st}
|
||||||
|
onchange={(v) => treinamento.acao('config', { automatico: v })}
|
||||||
|
/>
|
||||||
|
{#if st?.ocupado}<Selo tom="aviso">Gemini trabalhando…</Selo>{/if}
|
||||||
|
{#if st?.erro}<p class="erro pequeno-texto">{st.erro}</p>{/if}
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
{:else if aba === 'gestos'}
|
||||||
|
<Card titulo="Gestos do rosto" descricao="Toque para mandar ao celular. A estrela fixa o gesto nos favoritos (atalhos 1 a 9).">
|
||||||
|
<Gestos completo />
|
||||||
|
</Card>
|
||||||
|
{:else}
|
||||||
|
<div class="grade-criar">
|
||||||
|
<Card titulo="Resumos">
|
||||||
|
{#each st?.resumos ?? [] as r (r.id)}
|
||||||
|
<article class="entrada"><time class="fraco pequeno-texto">{hora(r.horario)}</time><p>{r.texto}</p></article>
|
||||||
|
{:else}
|
||||||
|
<p class="fraco pequeno-texto">Os resumos aparecem quando o Gemini gera reações.</p>
|
||||||
|
{/each}
|
||||||
|
</Card>
|
||||||
|
<Card titulo="Diário">
|
||||||
|
{#snippet acoes()}
|
||||||
|
{#if confirmarDiario}
|
||||||
|
<button
|
||||||
|
class="btn perigo pequeno"
|
||||||
|
onclick={async () => {
|
||||||
|
confirmarDiario = false;
|
||||||
|
await treinamento.acao('limpar-diario', {}, 'Diário e resumos apagados.');
|
||||||
|
}}>Apagar diário</button
|
||||||
|
>
|
||||||
|
<button class="btn pequeno" onclick={() => (confirmarDiario = false)}>Cancelar</button>
|
||||||
|
{:else}
|
||||||
|
<button class="btn pequeno fantasma" onclick={() => (confirmarDiario = true)} disabled={!st?.diario.length}>
|
||||||
|
<Trash2 size={14} /> Limpar
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
{/snippet}
|
||||||
|
<div class="diario">
|
||||||
|
{#each st?.diario ?? [] as m (m.id)}
|
||||||
|
<article class="entrada">
|
||||||
|
<time class="fraco pequeno-texto">{hora(m.horario)} · {m.papel === 'user' ? 'Você' : 'Carinha'}</time>
|
||||||
|
<p>{m.texto}</p>
|
||||||
|
</article>
|
||||||
|
{:else}
|
||||||
|
<p class="fraco pequeno-texto">Vazio.</p>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<aside class="lateral">
|
||||||
|
<div class="quadro"><RostoPrevia bind:this={previa} titulo="Prévia das reações" /></div>
|
||||||
|
<p class="fraco pequeno-texto">Clique numa reação para ver aqui sem mandar ao celular.</p>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Modal bind:aberto={editorAberto} titulo={editando ? 'Editar reação' : 'Novo emoji'}>
|
||||||
|
<form class="grade" onsubmit={salvarEditor}>
|
||||||
|
<label class="campo"><span>Nome</span><input type="text" bind:value={form.nome} maxlength="50" required /></label>
|
||||||
|
<label class="campo"><span>Quando usar</span><input type="text" bind:value={form.motivo} maxlength="200" required /></label>
|
||||||
|
{#if !editando?.receita.figurinha}
|
||||||
|
<div class="campo">
|
||||||
|
<span>Emoji</span>
|
||||||
|
<div class="emojis" role="radiogroup" aria-label="Emoji">
|
||||||
|
{#each st?.emojis ?? [] as e (e)}
|
||||||
|
<button type="button" role="radio" aria-checked={form.caractere === e} onclick={() => (form.caractere = e)}>{e}</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<label class="campo">
|
||||||
|
<span>Onde aparece</span>
|
||||||
|
<select bind:value={form.local}>
|
||||||
|
<option value="olhos">Nos olhos</option>
|
||||||
|
<option value="ao_redor">Ao redor do rosto</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
{/if}
|
||||||
|
<div class="linha">
|
||||||
|
<button class="btn primario" type="submit" disabled={!editando && !form.caractere}>Salvar</button>
|
||||||
|
<button class="btn" type="button" onclick={() => (editorAberto = false)}>Cancelar</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.reacoes {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-4);
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
.principal {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-4);
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.barra {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: var(--e-2);
|
||||||
|
}
|
||||||
|
.busca {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 200px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--e-2);
|
||||||
|
padding-left: var(--e-3);
|
||||||
|
border: 1px solid var(--borda-forte);
|
||||||
|
border-radius: var(--raio-sm);
|
||||||
|
background: var(--fundo-2);
|
||||||
|
color: var(--texto-3);
|
||||||
|
}
|
||||||
|
.busca input {
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
.grade-reacoes {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-3);
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(min(100%, 300px), 1fr));
|
||||||
|
}
|
||||||
|
.reacao {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-3);
|
||||||
|
padding: var(--e-3);
|
||||||
|
border: 1px solid var(--borda);
|
||||||
|
border-radius: var(--raio-lg);
|
||||||
|
background: var(--superficie);
|
||||||
|
}
|
||||||
|
.reacao.inativa {
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
.topo {
|
||||||
|
display: flex;
|
||||||
|
gap: var(--e-3);
|
||||||
|
text-align: left;
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
font: inherit;
|
||||||
|
padding: 0;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.info {
|
||||||
|
display: grid;
|
||||||
|
gap: 4px;
|
||||||
|
min-width: 0;
|
||||||
|
align-content: start;
|
||||||
|
}
|
||||||
|
.info strong {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.acoes {
|
||||||
|
display: flex;
|
||||||
|
gap: var(--e-1);
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.espaco {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
.marcado {
|
||||||
|
color: var(--ok);
|
||||||
|
border-color: var(--ok);
|
||||||
|
}
|
||||||
|
.marcado-ruim {
|
||||||
|
color: var(--perigo);
|
||||||
|
border-color: var(--perigo);
|
||||||
|
}
|
||||||
|
.perigo-texto:hover {
|
||||||
|
color: var(--perigo);
|
||||||
|
}
|
||||||
|
.grade-criar {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-4);
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr));
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
pre {
|
||||||
|
white-space: pre-wrap;
|
||||||
|
font-size: var(--t-xs);
|
||||||
|
color: var(--texto-2);
|
||||||
|
max-height: 200px;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
.erro {
|
||||||
|
color: var(--perigo);
|
||||||
|
}
|
||||||
|
.entrada {
|
||||||
|
display: grid;
|
||||||
|
gap: 2px;
|
||||||
|
font-size: var(--t-sm);
|
||||||
|
}
|
||||||
|
.diario {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-3);
|
||||||
|
max-height: 480px;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
.lateral {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-2);
|
||||||
|
}
|
||||||
|
.quadro {
|
||||||
|
aspect-ratio: 16 / 9;
|
||||||
|
border-radius: var(--raio-lg);
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid var(--borda);
|
||||||
|
background: #000;
|
||||||
|
}
|
||||||
|
.emojis {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(40px, 1fr));
|
||||||
|
gap: 4px;
|
||||||
|
max-height: 180px;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
.emojis button {
|
||||||
|
height: 40px;
|
||||||
|
border: 1px solid var(--borda);
|
||||||
|
border-radius: var(--raio-sm);
|
||||||
|
background: var(--superficie-2);
|
||||||
|
font-size: 1.3rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.emojis button[aria-checked='true'] {
|
||||||
|
border-color: var(--destaque);
|
||||||
|
background: var(--destaque-suave);
|
||||||
|
}
|
||||||
|
@media (max-width: 1099px) {
|
||||||
|
.lateral {
|
||||||
|
order: -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (min-width: 1100px) {
|
||||||
|
.reacoes {
|
||||||
|
grid-template-columns: 1fr 340px;
|
||||||
|
}
|
||||||
|
.lateral {
|
||||||
|
position: sticky;
|
||||||
|
top: calc(var(--topo-altura) + var(--e-4));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|||||||
@@ -0,0 +1,195 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Minus, Plus, Save, Target } from '@lucide/svelte';
|
||||||
|
import { postar } from '../../lib/api';
|
||||||
|
import { avisos } from '../../lib/avisos.svelte';
|
||||||
|
import { braco, type Calibracao } from '../../lib/braco.svelte';
|
||||||
|
import Card from '../../lib/componentes/Card.svelte';
|
||||||
|
import Selo from '../../lib/componentes/Selo.svelte';
|
||||||
|
import Toggle from '../../lib/componentes/Toggle.svelte';
|
||||||
|
import { estado } from '../../lib/estado.svelte';
|
||||||
|
|
||||||
|
const st = $derived(braco.status);
|
||||||
|
// Cópia local editável; só vai ao servidor em "Salvar calibração".
|
||||||
|
let cal = $state<Calibracao[]>([]);
|
||||||
|
let sujo = $state(false);
|
||||||
|
$effect(() => {
|
||||||
|
if (st && !sujo) cal = st.calibracao.map((c) => ({ ...c, centro: c.centro ?? 1500 }));
|
||||||
|
});
|
||||||
|
|
||||||
|
let habilitado = $state(false);
|
||||||
|
let canal = $state(0);
|
||||||
|
let pulso = $state(1500);
|
||||||
|
let ocupado = $state(false);
|
||||||
|
const nomeCanal = (i: number) => st?.articulacoes.find((a) => a.canal === i)?.nome ?? (i === 6 ? 'Antebraço (par invertido)' : `Canal ${i}`);
|
||||||
|
|
||||||
|
function trocarCanal(i: number) {
|
||||||
|
canal = i;
|
||||||
|
pulso = cal[i]?.centro ?? 1500;
|
||||||
|
habilitado = false;
|
||||||
|
braco.pararMotores();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testar(delta: number) {
|
||||||
|
if (!habilitado || ocupado) return;
|
||||||
|
const prox = pulso + delta;
|
||||||
|
if (prox < 500 || prox > 2500) return avisos.mostrar('Faixa absoluta: 500–2500 µs', 'erro');
|
||||||
|
ocupado = true;
|
||||||
|
try {
|
||||||
|
braco.soltar();
|
||||||
|
const r = await postar<{ pulsos: Record<string, number> }>('/braco/calibrar', { canal, pulso: prox });
|
||||||
|
pulso = prox;
|
||||||
|
avisos.mostrar(`Teste: ${Object.entries(r.pulsos).map(([c, us]) => `canal ${c} = ${us} µs`).join(', ')}. Desliga em 2 s.`);
|
||||||
|
} catch (e) {
|
||||||
|
avisos.erro(e);
|
||||||
|
} finally {
|
||||||
|
ocupado = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function marcar(campo: 'minimo' | 'centro' | 'maximo') {
|
||||||
|
cal[canal] = { ...cal[canal], [campo]: pulso };
|
||||||
|
sujo = true;
|
||||||
|
}
|
||||||
|
function editar(i: number, campo: 'minimo' | 'centro' | 'maximo', v: number) {
|
||||||
|
cal[i] = { ...cal[i], [campo]: v };
|
||||||
|
sujo = true;
|
||||||
|
}
|
||||||
|
const invalido = $derived(cal.find((c) => !(c.minimo < c.centro && c.centro < c.maximo)));
|
||||||
|
|
||||||
|
async function salvar() {
|
||||||
|
if (!st) return;
|
||||||
|
habilitado = false;
|
||||||
|
if (await braco.salvar({ calibracao: $state.snapshot(cal), posturas: st.posturas }, 'Calibração salva. Movimento desativado.')) {
|
||||||
|
sujo = false;
|
||||||
|
braco.ativado = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="calibracao">
|
||||||
|
<Card titulo="Testar fim de curso" descricao="Passos de 100 µs. Observe o motor e recue ao atingir o limite: não há detecção automática.">
|
||||||
|
<Toggle
|
||||||
|
rotulo="Habilitar testes de calibração"
|
||||||
|
ajuda="Cada teste mantém o sinal por até 2 s"
|
||||||
|
checked={habilitado}
|
||||||
|
disabled={!st?.disponivel || estado.estop.ativo}
|
||||||
|
onchange={(v) => {
|
||||||
|
habilitado = v;
|
||||||
|
if (!v) braco.pararMotores();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<label class="campo">
|
||||||
|
<span>Canal</span>
|
||||||
|
<select value={canal} onchange={(e) => trocarCanal(Number(e.currentTarget.value))}>
|
||||||
|
{#each Array.from({ length: 8 }, (_, i) => i) as i (i)}
|
||||||
|
<option value={i}>Canal {i} · {nomeCanal(i)}{i === 5 || i === 6 ? ' (par 5/6)' : ''}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<div class="pulso">
|
||||||
|
<button class="btn icone" onclick={() => testar(-100)} disabled={!habilitado || ocupado} aria-label="Menos 100 µs"><Minus size={18} /></button>
|
||||||
|
<output class="mono" aria-live="polite">{pulso} µs</output>
|
||||||
|
<button class="btn icone" onclick={() => testar(100)} disabled={!habilitado || ocupado} aria-label="Mais 100 µs"><Plus size={18} /></button>
|
||||||
|
</div>
|
||||||
|
<button class="btn" onclick={() => testar(0)} disabled={!habilitado || ocupado}><Target size={16} /> Testar posição atual</button>
|
||||||
|
<div class="linha">
|
||||||
|
<button class="btn pequeno" onclick={() => marcar('minimo')}>Marcar mínimo</button>
|
||||||
|
<button class="btn pequeno" onclick={() => marcar('centro')}>Marcar centro</button>
|
||||||
|
<button class="btn pequeno" onclick={() => marcar('maximo')}>Marcar máximo</button>
|
||||||
|
</div>
|
||||||
|
<p class="fraco pequeno-texto">Marcar só altera a tabela; nada se move. Canais 5 e 6 andam juntos, espelhados.</p>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card titulo="Limites por canal">
|
||||||
|
{#snippet acoes()}
|
||||||
|
{#if sujo}<Selo tom="aviso">Alterações não salvas</Selo>{/if}
|
||||||
|
<button class="btn pequeno primario" onclick={salvar} disabled={!sujo || !!invalido}><Save size={14} /> Salvar calibração</button>
|
||||||
|
{/snippet}
|
||||||
|
<div class="tabela">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr><th>Canal</th><th>Mínimo</th><th>Centro</th><th>Máximo</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{#each cal as c, i (i)}
|
||||||
|
<tr class:atual={i === canal} class:erro={!(c.minimo < c.centro && c.centro < c.maximo)}>
|
||||||
|
<th scope="row">{i} <small class="fraco">{nomeCanal(i)}</small></th>
|
||||||
|
{#each ['minimo', 'centro', 'maximo'] as const as campo (campo)}
|
||||||
|
<td>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="500"
|
||||||
|
max="2500"
|
||||||
|
step="10"
|
||||||
|
value={c[campo]}
|
||||||
|
aria-label="{campo} do canal {i}"
|
||||||
|
onchange={(e) => editar(i, campo, Number(e.currentTarget.value))}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
{/each}
|
||||||
|
</tr>
|
||||||
|
{/each}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{#if invalido}<p class="erro pequeno-texto">Canal {invalido.canal}: o centro precisa ficar entre mínimo e máximo.</p>{/if}
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.calibracao {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-4);
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 360px), 1fr));
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
.pulso {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: var(--e-4);
|
||||||
|
}
|
||||||
|
output {
|
||||||
|
font-size: var(--t-xl);
|
||||||
|
min-width: 7ch;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.tabela {
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-size: var(--t-sm);
|
||||||
|
}
|
||||||
|
th,
|
||||||
|
td {
|
||||||
|
padding: var(--e-1) var(--e-2);
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
thead th {
|
||||||
|
color: var(--texto-3);
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: var(--t-xs);
|
||||||
|
}
|
||||||
|
tbody th {
|
||||||
|
font-weight: 500;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
tbody th small {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
td input {
|
||||||
|
min-width: 84px;
|
||||||
|
min-height: 34px;
|
||||||
|
}
|
||||||
|
tr.atual {
|
||||||
|
background: var(--destaque-suave);
|
||||||
|
}
|
||||||
|
tr.erro input {
|
||||||
|
border-color: var(--perigo);
|
||||||
|
}
|
||||||
|
.erro {
|
||||||
|
color: var(--perigo);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,325 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Crosshair, Download, Eye, Hand, Play, Save, Trash2, Upload } from '@lucide/svelte';
|
||||||
|
import { onDestroy } from 'svelte';
|
||||||
|
import { avisos } from '../../lib/avisos.svelte';
|
||||||
|
import { braco, sequencias } from '../../lib/braco.svelte';
|
||||||
|
import BracoDesenho from '../../lib/componentes/BracoDesenho.svelte';
|
||||||
|
import Card from '../../lib/componentes/Card.svelte';
|
||||||
|
import Slider from '../../lib/componentes/Slider.svelte';
|
||||||
|
import Toggle from '../../lib/componentes/Toggle.svelte';
|
||||||
|
import { estado } from '../../lib/estado.svelte';
|
||||||
|
|
||||||
|
const st = $derived(braco.status);
|
||||||
|
const podeMover = $derived(!!st?.disponivel && !estado.estop.ativo);
|
||||||
|
const seqs = $derived(st ? sequencias(braco.faixas) : []);
|
||||||
|
|
||||||
|
// ---------- botão de homem-morto (mouse, toque e teclado)
|
||||||
|
function segurarBotao(e: PointerEvent, seq?: { nome: string; passos: number[][] }) {
|
||||||
|
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
|
||||||
|
braco.segurar(seq);
|
||||||
|
}
|
||||||
|
function teclaSegurar(e: KeyboardEvent, seq?: { nome: string; passos: number[][] }) {
|
||||||
|
if ((e.key === ' ' || e.key === 'Enter') && !e.repeat) {
|
||||||
|
e.preventDefault();
|
||||||
|
braco.segurar(seq);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function teclaSoltar(e: KeyboardEvent) {
|
||||||
|
if (e.key === ' ' || e.key === 'Enter') braco.soltar();
|
||||||
|
}
|
||||||
|
// Arrastar um slider com o movimento ativado também é "segurar".
|
||||||
|
function teclaSlider(e: KeyboardEvent) {
|
||||||
|
if (braco.ativado && /^Arrow|Page|Home|End/.test(e.key)) braco.segurar();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- prévia animada (só na tela)
|
||||||
|
let previa = $state<number[] | null>(null);
|
||||||
|
let quadro = 0;
|
||||||
|
function animar(passos: number[][]) {
|
||||||
|
cancelAnimationFrame(quadro);
|
||||||
|
let pose = [...braco.alvo];
|
||||||
|
let i = 0;
|
||||||
|
let pausa = 0;
|
||||||
|
let antes = performance.now();
|
||||||
|
const passo = (agora: number) => {
|
||||||
|
const dt = Math.min(0.1, (agora - antes) / 1000);
|
||||||
|
antes = agora;
|
||||||
|
const meta = passos[i];
|
||||||
|
const dist = Math.max(...pose.map((v, k) => Math.abs(meta[k] - v)));
|
||||||
|
const frac = dist ? Math.min(1, (braco.velocidade * dt) / dist) : 1;
|
||||||
|
pose = pose.map((v, k) => v + (meta[k] - v) * frac);
|
||||||
|
previa = pose;
|
||||||
|
if (dist < 0.01) {
|
||||||
|
if (!pausa) pausa = agora + 700;
|
||||||
|
if (agora >= pausa) {
|
||||||
|
pausa = 0;
|
||||||
|
if (++i >= passos.length) {
|
||||||
|
previa = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
quadro = requestAnimationFrame(passo);
|
||||||
|
};
|
||||||
|
quadro = requestAnimationFrame(passo);
|
||||||
|
}
|
||||||
|
onDestroy(() => {
|
||||||
|
cancelAnimationFrame(quadro);
|
||||||
|
braco.soltar();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- posturas
|
||||||
|
let nomePostura = $state('');
|
||||||
|
let excluindo = $state<number | null>(null);
|
||||||
|
async function salvarPostura(e: SubmitEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!st) return;
|
||||||
|
const nome = nomePostura.trim() || `Postura ${st.posturas.length + 1}`;
|
||||||
|
const posturas = [...st.posturas, { nome, angulos: $state.snapshot(braco.alvo) }];
|
||||||
|
if (await braco.salvar({ calibracao: st.calibracao, posturas }, `“${nome}” salva, sem movimento.`)) nomePostura = '';
|
||||||
|
}
|
||||||
|
async function excluirPostura(i: number) {
|
||||||
|
if (!st) return;
|
||||||
|
excluindo = null;
|
||||||
|
await braco.salvar({ calibracao: st.calibracao, posturas: st.posturas.filter((_, k) => k !== i) }, 'Postura excluída.');
|
||||||
|
}
|
||||||
|
const salvas = $derived(st?.posturas.length ? { nome: 'Posturas salvas em ordem', passos: st.posturas.map((p) => p.angulos) } : null);
|
||||||
|
|
||||||
|
function exportar() {
|
||||||
|
if (!st) return;
|
||||||
|
const url = URL.createObjectURL(
|
||||||
|
new Blob([JSON.stringify({ formato: 'carinha-braco-v1', calibracao: st.calibracao, posturas: st.posturas }, null, 2)], {
|
||||||
|
type: 'application/json',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = 'braco-posturas.json';
|
||||||
|
a.click();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||||
|
}
|
||||||
|
let arquivo: HTMLInputElement;
|
||||||
|
async function importar() {
|
||||||
|
const f = arquivo.files?.[0];
|
||||||
|
arquivo.value = '';
|
||||||
|
if (!f) return;
|
||||||
|
try {
|
||||||
|
if (f.size > 65536) throw new Error('Arquivo maior que 64 KB');
|
||||||
|
const dados = JSON.parse(await f.text());
|
||||||
|
if (dados.formato !== 'carinha-braco-v1') throw new Error('Use um arquivo exportado por este painel');
|
||||||
|
await braco.salvar({ calibracao: dados.calibracao, posturas: dados.posturas }, 'Calibração e posturas importadas, sem movimento.');
|
||||||
|
} catch (e) {
|
||||||
|
avisos.erro(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:window onpointerup={() => braco.soltar()} />
|
||||||
|
|
||||||
|
<div class="controle">
|
||||||
|
<Card class="desenho">
|
||||||
|
<div class="tela"><BracoDesenho pose={previa ?? braco.alvo} fantasma={previa ? null : st?.atual} /></div>
|
||||||
|
<p class="fraco pequeno-texto">
|
||||||
|
{#if previa}Prévia na tela · sem movimento físico{:else if st?.atual}Contorno claro: última posição enviada aos motores{:else}Alvo na tela{/if}
|
||||||
|
</p>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<div class="coluna">
|
||||||
|
<Card titulo="Mover">
|
||||||
|
<Toggle
|
||||||
|
rotulo="Ativar movimento físico"
|
||||||
|
ajuda={!st?.disponivel ? 'PCA9685 indisponível neste servidor' : estado.estop.ativo ? 'Rearme o E-Stop primeiro' : 'Com isso desligado, tudo acontece só na tela'}
|
||||||
|
checked={braco.ativado}
|
||||||
|
disabled={!podeMover}
|
||||||
|
onchange={(v) => (v ? (braco.ativado = true) : braco.desativar())}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
class="segurar"
|
||||||
|
class:ativo={braco.segurando}
|
||||||
|
disabled={!braco.ativado}
|
||||||
|
onpointerdown={(e) => segurarBotao(e)}
|
||||||
|
onpointerup={() => braco.soltar()}
|
||||||
|
onpointercancel={() => braco.soltar()}
|
||||||
|
onlostpointercapture={() => braco.soltar()}
|
||||||
|
onkeydown={(e) => teclaSegurar(e)}
|
||||||
|
onkeyup={teclaSoltar}
|
||||||
|
onblur={() => braco.soltar()}
|
||||||
|
oncontextmenu={(e) => e.preventDefault()}
|
||||||
|
>
|
||||||
|
<Hand size={22} />
|
||||||
|
{#if braco.passoSequencia}
|
||||||
|
{braco.passoSequencia.nome} · passo {braco.passoSequencia.indice + 1}/{braco.passoSequencia.total}
|
||||||
|
{:else if braco.segurando}Movendo… solte para parar{:else}Segure para ir ao alvo{/if}
|
||||||
|
</button>
|
||||||
|
<p class="fraco pequeno-texto">
|
||||||
|
O braço só se move enquanto você segura (botão, slider ou Espaço). Ao soltar, os motores desligam em menos de meio segundo.
|
||||||
|
</p>
|
||||||
|
<Slider rotulo="Velocidade" valor={braco.velocidade} min={5} max={180} passo={5} unidade=" °/s" oninput={(v) => (braco.velocidade = v)} />
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card titulo="Articulações">
|
||||||
|
{#snippet acoes()}
|
||||||
|
<button class="btn pequeno" onclick={() => ((braco.alvo = Array(7).fill(90)), braco.limitarAlvo())}>
|
||||||
|
<Crosshair size={14} /> Centralizar
|
||||||
|
</button>
|
||||||
|
{/snippet}
|
||||||
|
{#if st}
|
||||||
|
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||||
|
<div
|
||||||
|
class="articulacoes"
|
||||||
|
onpointerdown={(e) => braco.ativado && (e.target as HTMLElement).tagName === 'INPUT' && braco.segurar()}
|
||||||
|
onkeydown={teclaSlider}
|
||||||
|
onkeyup={() => braco.soltar()}
|
||||||
|
>
|
||||||
|
{#each st.articulacoes as a, i (a.canal)}
|
||||||
|
<Slider
|
||||||
|
rotulo={`${a.nome} · canal ${a.canal}${a.canal === 5 ? ' + 6' : ''}`}
|
||||||
|
valor={braco.alvo[i]}
|
||||||
|
min={braco.faixas[i][0]}
|
||||||
|
max={braco.faixas[i][1]}
|
||||||
|
unidade="°"
|
||||||
|
oninput={(v) => (braco.alvo[i] = v)}
|
||||||
|
/>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card titulo="Sequências" descricao="Prévia anima só a tela. Para executar, segure o botão até o fim.">
|
||||||
|
<ul class="lista">
|
||||||
|
{#each salvas ? [...seqs, salvas] : seqs as s (s.nome)}
|
||||||
|
<li>
|
||||||
|
<span>{s.nome}</span>
|
||||||
|
<span class="linha">
|
||||||
|
<button class="btn pequeno" onclick={() => animar(s.passos)}><Eye size={14} /> Prévia</button>
|
||||||
|
<button
|
||||||
|
class="btn pequeno primario"
|
||||||
|
disabled={!braco.ativado || (braco.segurando && braco.passoSequencia?.nome !== s.nome)}
|
||||||
|
onpointerdown={(e) => segurarBotao(e, s)}
|
||||||
|
onpointerup={() => braco.soltar()}
|
||||||
|
onpointercancel={() => braco.soltar()}
|
||||||
|
onkeydown={(e) => teclaSegurar(e, s)}
|
||||||
|
onkeyup={teclaSoltar}
|
||||||
|
oncontextmenu={(e) => e.preventDefault()}
|
||||||
|
>
|
||||||
|
<Play size={14} /> Segure
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card titulo="Posturas">
|
||||||
|
{#snippet acoes()}
|
||||||
|
<button class="btn pequeno fantasma" onclick={exportar} disabled={!st}><Download size={14} /> Exportar</button>
|
||||||
|
<button class="btn pequeno fantasma" onclick={() => arquivo.click()}><Upload size={14} /> Importar</button>
|
||||||
|
<input bind:this={arquivo} type="file" accept="application/json" hidden onchange={importar} />
|
||||||
|
{/snippet}
|
||||||
|
<form class="linha" onsubmit={salvarPostura}>
|
||||||
|
<input type="text" bind:value={nomePostura} maxlength="40" placeholder="Nome da postura atual" aria-label="Nome da postura" />
|
||||||
|
<button class="btn" type="submit" disabled={!st}><Save size={16} /> Salvar atual</button>
|
||||||
|
</form>
|
||||||
|
<ul class="lista">
|
||||||
|
{#each st?.posturas ?? [] as p, i (i)}
|
||||||
|
<li>
|
||||||
|
<button class="nome" onclick={() => (braco.alvo = [...p.angulos])} title="Carregar como alvo (sem mover)">{p.nome}</button>
|
||||||
|
<span class="linha">
|
||||||
|
{#if excluindo === i}
|
||||||
|
<button class="btn pequeno perigo" onclick={() => excluirPostura(i)}>Excluir</button>
|
||||||
|
<button class="btn pequeno" onclick={() => (excluindo = null)}>Cancelar</button>
|
||||||
|
{:else}
|
||||||
|
<button class="btn pequeno" onclick={() => (braco.alvo = [...p.angulos])}>Carregar</button>
|
||||||
|
<button class="btn pequeno icone fantasma" aria-label="Excluir {p.nome}" onclick={() => (excluindo = i)}><Trash2 size={14} /></button>
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
{:else}
|
||||||
|
<li class="fraco pequeno-texto">Nenhuma postura salva. Ajuste as articulações e salve.</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.controle {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-4);
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 340px), 1fr));
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
.coluna {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-4);
|
||||||
|
}
|
||||||
|
.tela {
|
||||||
|
aspect-ratio: 4 / 5;
|
||||||
|
max-height: 520px;
|
||||||
|
margin: 0 auto;
|
||||||
|
width: 100%;
|
||||||
|
background: var(--fundo-2);
|
||||||
|
border-radius: var(--raio);
|
||||||
|
}
|
||||||
|
.segurar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: var(--e-3);
|
||||||
|
min-height: 64px;
|
||||||
|
padding: var(--e-3);
|
||||||
|
border: 2px dashed var(--destaque);
|
||||||
|
border-radius: var(--raio);
|
||||||
|
background: var(--destaque-suave);
|
||||||
|
color: var(--destaque);
|
||||||
|
font: 600 var(--t-md) var(--fonte);
|
||||||
|
cursor: pointer;
|
||||||
|
touch-action: none;
|
||||||
|
user-select: none;
|
||||||
|
-webkit-user-select: none;
|
||||||
|
}
|
||||||
|
.segurar.ativo {
|
||||||
|
border-style: solid;
|
||||||
|
background: var(--destaque);
|
||||||
|
color: var(--destaque-texto);
|
||||||
|
}
|
||||||
|
.segurar:disabled {
|
||||||
|
opacity: 0.45;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
.articulacoes {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-3);
|
||||||
|
}
|
||||||
|
.lista {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-2);
|
||||||
|
}
|
||||||
|
.lista li {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: var(--e-2);
|
||||||
|
padding: var(--e-2) var(--e-3);
|
||||||
|
border-radius: var(--raio-sm);
|
||||||
|
background: var(--superficie-2);
|
||||||
|
font-size: var(--t-sm);
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.nome {
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
font: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
form input {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 160px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Plus, Save, Trash2, Zap } from '@lucide/svelte';
|
||||||
|
import { onDestroy, onMount } from 'svelte';
|
||||||
|
import { pedir, postar } from '../../lib/api';
|
||||||
|
import { avisos, tentar } from '../../lib/avisos.svelte';
|
||||||
|
import Card from '../../lib/componentes/Card.svelte';
|
||||||
|
import Selo from '../../lib/componentes/Selo.svelte';
|
||||||
|
import Slider from '../../lib/componentes/Slider.svelte';
|
||||||
|
import Toggle from '../../lib/componentes/Toggle.svelte';
|
||||||
|
import { estado } from '../../lib/estado.svelte';
|
||||||
|
|
||||||
|
interface Servo {
|
||||||
|
nome: string;
|
||||||
|
canal: number;
|
||||||
|
minimo: number;
|
||||||
|
maximo: number;
|
||||||
|
centro: number;
|
||||||
|
}
|
||||||
|
let servos = $state<Servo[]>([]);
|
||||||
|
let pulsos = $state<number[]>([]);
|
||||||
|
let disponivel = $state(false);
|
||||||
|
let sujo = $state(false);
|
||||||
|
let aoVivo = $state(false);
|
||||||
|
|
||||||
|
async function carregar() {
|
||||||
|
const st = await tentar(() => pedir<{ servos: Servo[]; disponivel: boolean }>('/servos/status'));
|
||||||
|
if (!st) return;
|
||||||
|
servos = st.servos;
|
||||||
|
pulsos = st.servos.map((s) => s.centro);
|
||||||
|
disponivel = st.disponivel;
|
||||||
|
sujo = false;
|
||||||
|
}
|
||||||
|
onMount(carregar);
|
||||||
|
|
||||||
|
// Ao vivo: no máximo 10 comandos/s, sempre o último valor.
|
||||||
|
let pendente: { indice: number; pulso: number } | null = null;
|
||||||
|
let emVoo = false;
|
||||||
|
let ultimo = 0;
|
||||||
|
let espera = 0;
|
||||||
|
function enfileirar(indice: number, pulso: number) {
|
||||||
|
pulsos[indice] = pulso;
|
||||||
|
if (!aoVivo || sujo) return;
|
||||||
|
pendente = { indice, pulso };
|
||||||
|
bombear();
|
||||||
|
}
|
||||||
|
async function bombear() {
|
||||||
|
if (!pendente || emVoo || espera) return;
|
||||||
|
const falta = 100 - (performance.now() - ultimo);
|
||||||
|
if (falta > 0) {
|
||||||
|
espera = window.setTimeout(() => {
|
||||||
|
espera = 0;
|
||||||
|
bombear();
|
||||||
|
}, falta);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const cmd = pendente;
|
||||||
|
pendente = null;
|
||||||
|
ultimo = performance.now();
|
||||||
|
emVoo = true;
|
||||||
|
try {
|
||||||
|
await postar('/servos/mover', cmd);
|
||||||
|
} catch (e) {
|
||||||
|
aoVivo = false;
|
||||||
|
avisos.erro(e);
|
||||||
|
} finally {
|
||||||
|
emVoo = false;
|
||||||
|
bombear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function parar() {
|
||||||
|
aoVivo = false;
|
||||||
|
pendente = null;
|
||||||
|
clearTimeout(espera);
|
||||||
|
espera = 0;
|
||||||
|
await tentar(() => postar('/servos/parar'));
|
||||||
|
}
|
||||||
|
onDestroy(() => {
|
||||||
|
if (aoVivo) parar();
|
||||||
|
});
|
||||||
|
|
||||||
|
const testar = (i: number, pulso: number) =>
|
||||||
|
tentar(() => postar('/servos/mover', { indice: i, pulso }), `${servos[i].nome}: ${pulso} µs por 2 s.`);
|
||||||
|
|
||||||
|
function editar(i: number, campo: keyof Servo, v: string) {
|
||||||
|
servos[i] = { ...servos[i], [campo]: campo === 'nome' ? v : Number(v) };
|
||||||
|
sujo = true;
|
||||||
|
aoVivo = false;
|
||||||
|
}
|
||||||
|
function adicionar() {
|
||||||
|
const canal = Array.from({ length: 16 }, (_, i) => i).find((c) => !servos.some((s) => s.canal === c));
|
||||||
|
if (canal === undefined) return;
|
||||||
|
servos = [...servos, { nome: `Servo ${servos.length + 1}`, canal, minimo: 1400, maximo: 1600, centro: 1500 }];
|
||||||
|
pulsos = [...pulsos, 1500];
|
||||||
|
sujo = true;
|
||||||
|
}
|
||||||
|
function remover(i: number) {
|
||||||
|
servos = servos.filter((_, k) => k !== i);
|
||||||
|
pulsos = pulsos.filter((_, k) => k !== i);
|
||||||
|
sujo = true;
|
||||||
|
}
|
||||||
|
async function salvar() {
|
||||||
|
await parar();
|
||||||
|
const r = await tentar(() => postar<{ servos: Servo[] }>('/servos/config', { servos: $state.snapshot(servos) }), 'Servos salvos. Nenhum movimento enviado.');
|
||||||
|
if (r) {
|
||||||
|
servos = r.servos;
|
||||||
|
pulsos = r.servos.map((s) => s.centro);
|
||||||
|
sujo = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const ocupadoPeloBraco = $derived(estado.motores?.dono === 'braco' && !!estado.motores.ativos.length);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="diagnostico">
|
||||||
|
<Card titulo="Diagnóstico do PCA9685" descricao="Teste canal a canal, com limites conservadores (1000–2000 µs). Use com o braço parado.">
|
||||||
|
{#snippet acoes()}
|
||||||
|
{#if sujo}<Selo tom="aviso">Alterações não salvas</Selo>{/if}
|
||||||
|
<button class="btn pequeno" onclick={adicionar} disabled={servos.length >= 16}><Plus size={14} /> Servo</button>
|
||||||
|
<button class="btn pequeno primario" onclick={salvar} disabled={!sujo}><Save size={14} /> Salvar</button>
|
||||||
|
{/snippet}
|
||||||
|
{#if ocupadoPeloBraco}
|
||||||
|
<p class="aviso pequeno-texto">O braço está usando os motores. Pare o braço antes de testar aqui.</p>
|
||||||
|
{/if}
|
||||||
|
<Toggle
|
||||||
|
rotulo="Controle ao vivo"
|
||||||
|
ajuda="Arrastar o pulso envia ao motor (até 10 vezes por segundo)"
|
||||||
|
checked={aoVivo}
|
||||||
|
disabled={!disponivel || sujo || estado.estop.ativo || ocupadoPeloBraco}
|
||||||
|
onchange={(v) => (v ? (aoVivo = true) : parar())}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<div class="servos">
|
||||||
|
{#each servos as s, i (i)}
|
||||||
|
<Card>
|
||||||
|
<div class="campos">
|
||||||
|
<label class="campo nome"><span>Nome</span><input type="text" maxlength="40" value={s.nome} onchange={(e) => editar(i, 'nome', e.currentTarget.value)} /></label>
|
||||||
|
<label class="campo"><span>Canal</span><input type="number" min="0" max="15" value={s.canal} onchange={(e) => editar(i, 'canal', e.currentTarget.value)} /></label>
|
||||||
|
<label class="campo"><span>Mín. µs</span><input type="number" min="1000" max="2000" value={s.minimo} onchange={(e) => editar(i, 'minimo', e.currentTarget.value)} /></label>
|
||||||
|
<label class="campo"><span>Centro</span><input type="number" min="1000" max="2000" value={s.centro} onchange={(e) => editar(i, 'centro', e.currentTarget.value)} /></label>
|
||||||
|
<label class="campo"><span>Máx. µs</span><input type="number" min="1000" max="2000" value={s.maximo} onchange={(e) => editar(i, 'maximo', e.currentTarget.value)} /></label>
|
||||||
|
</div>
|
||||||
|
<Slider rotulo="Pulso" valor={pulsos[i] ?? s.centro} min={s.minimo} max={s.maximo} passo={5} unidade=" µs" oninput={(v) => enfileirar(i, v)} />
|
||||||
|
<div class="linha">
|
||||||
|
<button class="btn pequeno" disabled={!disponivel || sujo} onclick={() => testar(i, pulsos[i])}><Zap size={14} /> Testar 2 s</button>
|
||||||
|
<button class="btn pequeno" disabled={!disponivel || sujo} onclick={() => testar(i, s.centro)}>Centro</button>
|
||||||
|
<span class="espaco"></span>
|
||||||
|
<button class="btn pequeno icone fantasma" aria-label="Remover {s.nome}" onclick={() => remover(i)}><Trash2 size={14} /></button>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.diagnostico {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-4);
|
||||||
|
}
|
||||||
|
.servos {
|
||||||
|
display: grid;
|
||||||
|
gap: var(--e-4);
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(min(100%, 320px), 1fr));
|
||||||
|
}
|
||||||
|
.campos {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(4, 1fr);
|
||||||
|
gap: var(--e-2);
|
||||||
|
}
|
||||||
|
.campos .nome {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
}
|
||||||
|
.campos input {
|
||||||
|
min-height: 34px;
|
||||||
|
padding: var(--e-1) var(--e-2);
|
||||||
|
}
|
||||||
|
.espaco {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
.aviso {
|
||||||
|
color: var(--aviso);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
Reference in New Issue
Block a user