Skip to content

Latest commit

 

History

History
471 lines (359 loc) · 7.8 KB

API.md

File metadata and controls

471 lines (359 loc) · 7.8 KB

API — Endpoints REST e WebSocket

Referência completa de endpoints, payloads e eventos.


Configuração Base

// Base URL
const BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:8080/api'

// WebSocket URL
const WS_URL = process.env.REACT_APP_WS_URL || 'ws://localhost:8080'

Autenticação

POST /auth/login

Autentica usuário e retorna JWT token.

Campo Valor
Método POST
Auth Requerida NÃO
Content-Type application/json

Request:

{
  "email": "user@example.com",
  "password": "senha123"
}

Response (200 OK):

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "user-123",
    "name": "João Silva",
    "email": "user@example.com",
    "specialty": "Fisioterapeuta",
    "role": "therapist"
  }
}

Response (401 Unauthorized):

{
  "message": "Email ou senha incorretos"
}

POST /auth/register

Cria nova conta de usuário.

Campo Valor
Método POST
Auth Requerida NÃO
Content-Type application/json

Request:

{
  "name": "Maria Santos",
  "email": "maria@example.com",
  "password": "segura@123",
  "specialty": "Terapeuta Ocupacional"
}

Response (201 Created):

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "user-456",
    "name": "Maria Santos",
    "email": "maria@example.com"
  }
}

POST /auth/logout

Invalida token atual.

Campo Valor
Método POST
Auth Requerida SIM (Bearer token)

Response (204 No Content):

(vazio)

Guincho (Hoist)

GET /hoist/{id}/status

Obtém status atual do guincho.

Campo Valor
Método GET
Auth Requerida SIM
Params id — ID do guincho

Response (200 OK):

{
  "id": "hoist-123",
  "height": 120,              // cm
  "battery": 85,              // %
  "speed": 0,                 // %
  "isMoving": false,
  "obstacleDetected": false,
  "overload": false,
  "mode": "manual",           // manual, automatic, suspended
  "lastUpdate": "2024-05-06T15:30:45Z"
}

POST /hoist/{id}/move

Envia comando de movimento para o guincho.

Campo Valor
Método POST
Auth Requerida SIM
Params id — ID do guincho

Request:

{
  "direction": 1,   // 1=up, -1=down, 0=stop
  "speed": 70       // 0-100
}

Response (200 OK):

{
  "success": true,
  "message": "Comando recebido",
  "state": "moving_up"
}

Response (403 Forbidden) — Obstáculo detectado:

{
  "success": false,
  "message": "Movimento bloqueado: obstáculo detectado"
}

POST /hoist/{id}/emergency-stop

[CRÍTICO] Parada de emergência — bloqueia movimento imediatamente.

Campo Valor
Método POST
Auth Requerida SIM
Params id — ID do guincho

Response (200 OK):

{
  "success": true,
  "message": "Parada de emergência ativada",
  "state": "emergency_stop"
}

GET /hoist/{id}/telemetry

Obtém histórico de telemetria (últimos eventos).

Campo Valor
Método GET
Auth Requerida SIM
Query limit=100 (padrão)

Response (200 OK):

{
  "events": [
    {
      "event": "status_update",
      "timestamp": "2024-05-06T15:30:45Z",
      "height": 120,
      "battery": 85,
      "speed": 50
    },
    {
      "event": "battery_low",
      "timestamp": "2024-05-06T15:25:30Z",
      "battery": 20
    },
    {
      "event": "obstacle_detected",
      "timestamp": "2024-05-06T15:20:15Z",
      "distance": 30
    }
  ]
}

Chat (AI Chatbot)

POST /chat/message

Envia mensagem para assistente IA.

Campo Valor
Método POST
Auth Requerida SIM

Request:

{
  "message": "Como faço exercício de reabilitação?",
  "conversationId": "conv-123"  // null para iniciar nova conversa
}

Response (200 OK):

{
  "reply": "Os exercícios de reabilitação devem ser feitos com supervisão médica...",
  "confidence": 0.95,
  "conversationId": "conv-123"
}

POST /chat/conversation

Inicia nova conversa.

Campo Valor
Método POST
Auth Requerida SIM

Response (201 Created):

{
  "conversationId": "conv-456",
  "createdAt": "2024-05-06T15:30:00Z"
}

WebSocket Events

Conexão: ws://{WS_URL}/ws/guincho/{id}

Event: status_update

Atualização periódica de status.

Direction: Server → Client
Frequency: A cada 1-2 segundos

Payload:

{
  "event": "status_update",
  "height": 120,
  "battery": 85,
  "speed": 50,
  "isMoving": true,
  "mode": "manual",
  "timestamp": "2024-05-06T15:30:45Z"
}

Event: bateria_low

Alerta de bateria baixa (≤ 20%).

Direction: Server → Client
Frequency: Uma vez ao atingir limite

Payload:

{
  "event": "bateria_low",
  "battery": 15,
  "timestamp": "2024-05-06T15:25:30Z"
}

Event: obstaculo_detectado

[CRÍTICO] Obstáculo detectado pela IA (Raspberry Pi).

Direction: Server → Client
Frequency: Quando detectado

Payload:

{
  "event": "obstaculo_detectado",
  "distance": 30,              // cm
  "confidence": 0.97,
  "timestamp": "2024-05-06T15:20:15Z"
}

Ação Automática: Mobile app bloqueia movimento


Event: sobrecarga_detectada

[CRÍTICO] Sobrecarga detectada (FSR > limite).

Direction: Server → Client
Frequency: Quando detectado

Payload:

{
  "event": "sobrecarga_detectada",
  "load": 125,                 // kg
  "limit": 100,
  "timestamp": "2024-05-06T15:20:15Z"
}

Ação Automática: Mobile app bloqueia movimento


Códigos HTTP

Código Significado
200 OK — Sucesso
201 Created — Recurso criado
204 No Content — Sucesso sem body
400 Bad Request — Dados inválidos
401 Unauthorized — Token expirado/inválido
403 Forbidden — Permissão negada
404 Not Found — Recurso não encontrado
409 Conflict — Conflito (ex: email já existe)
500 Server Error — Erro interno
503 Service Unavailable — Serviço indisponível

Tratamento de Erros

Todos os endpoints retornam erros neste formato:

{
  "error": {
    "code": "INVALID_EMAIL",
    "message": "Email inválido",
    "details": null
  }
}

Rate Limiting

  • Limite: 100 requests/minuto por usuário
  • Header: X-RateLimit-Remaining
  • 429 Too Many Requests ao exceder limite

Versionamento

API versão: v1
Future: /api/v2/...


cURL Examples

Login

curl -X POST http://localhost:8080/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "senha123"
  }'

Get Hoist Status

curl -X GET http://localhost:8080/api/hoist/hoist-123/status \
  -H "Authorization: Bearer $TOKEN"

Send Movement Command

curl -X POST http://localhost:8080/api/hoist/hoist-123/move \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "direction": 1,
    "speed": 70
  }'

Emergency Stop

curl -X POST http://localhost:8080/api/hoist/hoist-123/emergency-stop \
  -H "Authorization: Bearer $TOKEN"

Documentação Swagger/OpenAPI

Disponível em: /api/v1/swagger-ui.html


TODO

  • Endpoints de settings/preferences
  • Batch telemetry API
  • Export de relatórios
  • WebSocket authentication refresh