Compare commits
No commits in common. "master" and "v1.11.0" have entirely different histories.
11 changed files with 9 additions and 810 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -15,7 +15,6 @@ server/data/
|
||||||
!.env.example
|
!.env.example
|
||||||
**/.env
|
**/.env
|
||||||
**/.env.*
|
**/.env.*
|
||||||
!**/.env.example
|
|
||||||
|
|
||||||
# OS / IDE
|
# OS / IDE
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
|
||||||
|
|
@ -1988,30 +1988,6 @@ Marque zonas de proibição (alarme alto) ou atenção (aviso suave). Detecção
|
||||||
<div class="field-hint" style="margin-top:8px">Limitações: <strong>iOS Safari não suporta Web Bluetooth</strong>. APK Android usa plugin nativo. BMS proprietários (Victron, JBD) podem aparecer mas não expor Battery Service padrão.</div>
|
<div class="field-hint" style="margin-top:8px">Limitações: <strong>iOS Safari não suporta Web Bluetooth</strong>. APK Android usa plugin nativo. BMS proprietários (Victron, JBD) podem aparecer mas não expor Battery Service padrão.</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Smart Home / Casa do Barco -->
|
|
||||||
<div class="export-card" id="smart-home-card">
|
|
||||||
<div class="export-card-title">🏠 Casa do Barco · Dispositivos Smart Life</div>
|
|
||||||
<div class="export-card-text" style="margin-bottom:10px">Controle lâmpadas, tomadas, ventiladores e qualquer dispositivo do app <strong>Smart Life</strong> (Tuya / Alexa via WiFi 2.4 GHz). Funciona com Starlink ou qualquer internet do barco.</div>
|
|
||||||
<div id="smart-status" style="font-family:var(--f-mono);font-size:10.5px;color:var(--sepia);margin-bottom:10px;letter-spacing:.04em;line-height:1.55">Verificando configuração...</div>
|
|
||||||
<button class="btn btn-block btn-primary" onclick="openSmartDeviceModal()">+ Adicionar dispositivo</button>
|
|
||||||
<div id="smart-devices-list" style="margin-top:14px"></div>
|
|
||||||
<div class="field-hint" style="margin-top:8px"><strong>Setup</strong> (1x): admin precisa configurar credenciais Tuya no servidor (ver <code>.env.example</code>). Depois disso, qualquer dispositivo no Smart Life aparece aqui automático.</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Modal: lista dispositivos da conta Tuya pra o usuário escolher -->
|
|
||||||
<div class="modal-backdrop" id="smart-device-modal" onclick="if(event.target===this)closeModal('smart-device-modal')">
|
|
||||||
<div class="modal" style="max-width:520px">
|
|
||||||
<div class="modal-head">
|
|
||||||
<h3>🏠 Adicionar dispositivo</h3>
|
|
||||||
<button class="icon-btn" onclick="closeModal('smart-device-modal')">✕</button>
|
|
||||||
</div>
|
|
||||||
<div class="modal-body">
|
|
||||||
<div id="smart-modal-status" style="font-family:var(--f-mono);font-size:11px;color:var(--sepia);margin-bottom:10px;letter-spacing:.04em">Buscando dispositivos da sua conta Smart Life...</div>
|
|
||||||
<div id="smart-modal-list" class="fleet-list"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Raymarine Gateway -->
|
<!-- Raymarine Gateway -->
|
||||||
<div class="export-card" id="nmea-gateway-card">
|
<div class="export-card" id="nmea-gateway-card">
|
||||||
<div class="export-card-title">⚓ Instrumentos Raymarine (gateway NMEA 2000)</div>
|
<div class="export-card-title">⚓ Instrumentos Raymarine (gateway NMEA 2000)</div>
|
||||||
|
|
@ -2638,7 +2614,7 @@ Hora: {HORA}</textarea>
|
||||||
<div class="zone-toast" id="zone-toast"></div>
|
<div class="zone-toast" id="zone-toast"></div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const state={boat:{name:'Shivao',model:''},boats:[],activeBoatId:null,units:'metric',trips:[],maint:[],pending:[],passengers:[],contacts:[],alarmTemplate:'🚨 ALERTA: Shivao saiu da posição de fundeio.\nEstou em {LAT}, {LNG}\nMapa: https://maps.google.com/?q={LAT},{LNG}\nHora: {HORA}',cloud:{url:'',token:'',lastSync:0},auth:null,license:null,webhooks:{telegram:{token:'',chatIds:''},discord:{url:''},generic:{url:''}},anchorHistory:[],zones:[],checklists:[],weatherCfg:{windyKey:'',model:'gfs'},smartDevices:[]};
|
const state={boat:{name:'Shivao',model:''},boats:[],activeBoatId:null,units:'metric',trips:[],maint:[],pending:[],passengers:[],contacts:[],alarmTemplate:'🚨 ALERTA: Shivao saiu da posição de fundeio.\nEstou em {LAT}, {LNG}\nMapa: https://maps.google.com/?q={LAT},{LNG}\nHora: {HORA}',cloud:{url:'',token:'',lastSync:0},auth:null,license:null,webhooks:{telegram:{token:'',chatIds:''},discord:{url:''},generic:{url:''}},anchorHistory:[],zones:[],checklists:[],weatherCfg:{windyKey:'',model:'gfs'}};
|
||||||
|
|
||||||
// ============ NAUTICAL HELPERS (multi-boat + fleet + calculations) ============
|
// ============ NAUTICAL HELPERS (multi-boat + fleet + calculations) ============
|
||||||
// Storage interno SEMPRE em metros (ISO). Conversão só pra display.
|
// Storage interno SEMPRE em metros (ISO). Conversão só pra display.
|
||||||
|
|
@ -3770,229 +3746,6 @@ async function updateStorageInfo(){
|
||||||
}catch(e){document.getElementById('storage-info').textContent='—'}
|
}catch(e){document.getElementById('storage-info').textContent='—'}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============ SMART HOME (Tuya / Smart Life) ============
|
|
||||||
// State.smartDevices = [{id, name, category, category_label, online, lastState, lastSeen}]
|
|
||||||
// Polling de status só roda quando aba "Arquivo" está visível (economiza dados Starlink).
|
|
||||||
|
|
||||||
let _smartPollTimer=null;
|
|
||||||
let _smartConsecFails={};
|
|
||||||
|
|
||||||
function setSmartStatus(msg,kind){
|
|
||||||
const el=document.getElementById('smart-status');if(!el)return;
|
|
||||||
const colors={ok:'#22c55e',warn:'#f59e0b',err:'#ef4444',info:'var(--sepia)'};
|
|
||||||
el.style.color=colors[kind]||'var(--sepia)';
|
|
||||||
el.textContent=msg;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function refreshSmartStatus(){
|
|
||||||
if(!cloudConfigured()){setSmartStatus('☁ Nuvem não configurada','warn');return}
|
|
||||||
try{
|
|
||||||
const r=await cloudFetch('/api/iot/devices');
|
|
||||||
const j=await r.json();
|
|
||||||
const n=(j.devices||[]).length;
|
|
||||||
setSmartStatus(`✓ Conectado · ${n} dispositivo${n!==1?'s':''} disponível${n!==1?'is':''} na conta Smart Life`,'ok');
|
|
||||||
}catch(e){
|
|
||||||
if((e.message||'').includes('503')||(e.message||'').includes('tuya_not_configured')){
|
|
||||||
setSmartStatus('⚙ Tuya não configurado no servidor (admin: configure TUYA_ACCESS_ID em .env)','warn');
|
|
||||||
}else{
|
|
||||||
setSmartStatus('✗ '+(e.message||'erro'),'err');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function openSmartDeviceModal(){
|
|
||||||
if(!cloudConfigured()){toast('Configure a nuvem primeiro');return}
|
|
||||||
openModal('smart-device-modal');
|
|
||||||
const list=document.getElementById('smart-modal-list');
|
|
||||||
const status=document.getElementById('smart-modal-status');
|
|
||||||
list.innerHTML='';
|
|
||||||
status.textContent='Buscando dispositivos da sua conta Smart Life...';
|
|
||||||
status.style.color='var(--sepia)';
|
|
||||||
try{
|
|
||||||
const r=await cloudFetch('/api/iot/devices');
|
|
||||||
const j=await r.json();
|
|
||||||
const devices=j.devices||[];
|
|
||||||
if(devices.length===0){
|
|
||||||
status.textContent='Nenhum dispositivo encontrado. Adicione no app Smart Life primeiro.';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
status.textContent=`${devices.length} dispositivo${devices.length!==1?'s':''} encontrado${devices.length!==1?'s':''}. Toque pra adicionar:`;
|
|
||||||
list.innerHTML='';
|
|
||||||
for(const d of devices){
|
|
||||||
const already=state.smartDevices.find(s=>s.id===d.id);
|
|
||||||
const dot=d.online?'🟢':'⚪';
|
|
||||||
const item=document.createElement('div');
|
|
||||||
item.className='fleet-item';
|
|
||||||
item.style.cssText='display:flex;justify-content:space-between;align-items:center;padding:10px;border:1px solid var(--m-border,rgba(255,255,255,.08));border-radius:6px;margin-bottom:6px;'+(already?'opacity:.5':'cursor:pointer');
|
|
||||||
item.innerHTML=`<div><div style="font-weight:600">${dot} ${escapeHtml(d.name)}</div><div style="font-size:11px;color:var(--sepia);font-family:var(--f-mono)">${escapeHtml(d.category_label||d.category||'')}</div></div>${already?'<span style="font-size:11px;color:var(--sepia)">já adicionado</span>':'<button class="btn btn-sm btn-primary">+ Adicionar</button>'}`;
|
|
||||||
if(!already){
|
|
||||||
item.onclick=()=>{addSmartDevice(d);closeModal('smart-device-modal')};
|
|
||||||
}
|
|
||||||
list.appendChild(item);
|
|
||||||
}
|
|
||||||
}catch(e){
|
|
||||||
if((e.message||'').includes('503')||(e.message||'').includes('tuya_not_configured')){
|
|
||||||
status.style.color='#f59e0b';
|
|
||||||
status.innerHTML='⚙ Tuya não configurado.<br>Admin precisa adicionar <code>TUYA_ACCESS_ID</code> + <code>TUYA_ACCESS_SECRET</code> no env do servidor.<br>Veja <code>server/.env.example</code>.';
|
|
||||||
}else{
|
|
||||||
status.style.color='#ef4444';
|
|
||||||
status.textContent='Erro: '+(e.message||'falha');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function addSmartDevice(d){
|
|
||||||
if(!state.smartDevices)state.smartDevices=[];
|
|
||||||
if(state.smartDevices.find(s=>s.id===d.id)){toast('Já adicionado');return}
|
|
||||||
state.smartDevices.push({
|
|
||||||
id:d.id,
|
|
||||||
name:d.name,
|
|
||||||
category:d.category,
|
|
||||||
category_label:d.category_label||d.category,
|
|
||||||
online:d.online,
|
|
||||||
lastState:null,
|
|
||||||
lastSeen:Date.now(),
|
|
||||||
addedAt:Date.now(),
|
|
||||||
});
|
|
||||||
saveState();
|
|
||||||
renderSmartDevices();
|
|
||||||
toast(`+ ${d.name}`);
|
|
||||||
// Busca estado inicial
|
|
||||||
refreshSmartDeviceState(d.id).catch(()=>{});
|
|
||||||
}
|
|
||||||
|
|
||||||
function removeSmartDevice(id){
|
|
||||||
if(!confirm('Remover este dispositivo do Shivão? (não apaga do Smart Life)'))return;
|
|
||||||
state.smartDevices=(state.smartDevices||[]).filter(d=>d.id!==id);
|
|
||||||
saveState();
|
|
||||||
renderSmartDevices();
|
|
||||||
toast('Removido');
|
|
||||||
}
|
|
||||||
|
|
||||||
function smartDeviceIcon(category){
|
|
||||||
const icons={cz:'🔌',dj:'💡',kg:'🎚️',fs:'🌀',dd:'💡',xdd:'🔆',dc:'💡',tdq:'⚡',kt:'❄️',wsdcg:'🌡️',mcs:'🚪',sd:'🤖',cl:'🪟',clkg:'🪟',wnykq:'🌡️'};
|
|
||||||
return icons[category]||'🔧';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encontra DP de "switch principal" pra renderizar toggle.
|
|
||||||
// Tuya pode usar switch_1, switch_led, switch — depende do produto.
|
|
||||||
function findMainSwitch(status){
|
|
||||||
if(!Array.isArray(status))return null;
|
|
||||||
// Prioridade: switch > switch_1 > switch_led > primeiro boolean
|
|
||||||
const candidates=['switch','switch_1','switch_led'];
|
|
||||||
for(const c of candidates){
|
|
||||||
const dp=status.find(s=>s.code===c&&typeof s.value==='boolean');
|
|
||||||
if(dp)return dp;
|
|
||||||
}
|
|
||||||
return status.find(s=>typeof s.value==='boolean')||null;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function refreshSmartDeviceState(id){
|
|
||||||
try{
|
|
||||||
const r=await cloudFetch('/api/iot/status/'+encodeURIComponent(id));
|
|
||||||
const j=await r.json();
|
|
||||||
const dev=state.smartDevices.find(d=>d.id===id);
|
|
||||||
if(!dev)return;
|
|
||||||
dev.lastState=j.status;
|
|
||||||
dev.online=true;
|
|
||||||
dev.lastSeen=Date.now();
|
|
||||||
_smartConsecFails[id]=0;
|
|
||||||
saveState();
|
|
||||||
renderSmartDevices();
|
|
||||||
}catch(e){
|
|
||||||
const dev=state.smartDevices.find(d=>d.id===id);
|
|
||||||
if(dev){
|
|
||||||
_smartConsecFails[id]=(_smartConsecFails[id]||0)+1;
|
|
||||||
// Backoff exponencial: marca offline após 3 falhas consecutivas
|
|
||||||
if(_smartConsecFails[id]>=3){
|
|
||||||
dev.online=false;
|
|
||||||
saveState();
|
|
||||||
renderSmartDevices();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function toggleSmartDevice(id){
|
|
||||||
const dev=state.smartDevices.find(d=>d.id===id);
|
|
||||||
if(!dev)return;
|
|
||||||
const sw=findMainSwitch(dev.lastState);
|
|
||||||
const newVal=sw?!sw.value:true;
|
|
||||||
// OPTIMISTIC UI: atualiza imediato, reverte em caso de erro
|
|
||||||
if(sw){sw.value=newVal}else if(dev.lastState){dev.lastState.push({code:'switch',value:newVal})}else{dev.lastState=[{code:'switch',value:newVal}]}
|
|
||||||
renderSmartDevices();
|
|
||||||
try{
|
|
||||||
const code=sw?sw.code:'switch';
|
|
||||||
const r=await cloudFetch('/api/iot/command/'+encodeURIComponent(id),{
|
|
||||||
method:'POST',
|
|
||||||
body:JSON.stringify({commands:[{code,value:newVal}]}),
|
|
||||||
});
|
|
||||||
await r.json();
|
|
||||||
// Confirma re-buscando status real após 800ms (Tuya leva ~500ms pra refletir)
|
|
||||||
setTimeout(()=>{refreshSmartDeviceState(id).catch(()=>{})},800);
|
|
||||||
}catch(e){
|
|
||||||
// Reverte UI
|
|
||||||
if(sw)sw.value=!newVal;
|
|
||||||
renderSmartDevices();
|
|
||||||
toast('Falhou: '+(e.message||'erro'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderSmartDevices(){
|
|
||||||
const wrap=document.getElementById('smart-devices-list');
|
|
||||||
if(!wrap)return;
|
|
||||||
const devs=state.smartDevices||[];
|
|
||||||
if(devs.length===0){wrap.innerHTML='<div class="field-hint" style="text-align:center;padding:20px 10px">Nenhum dispositivo adicionado.<br>Toque "+ Adicionar" pra ver os dispositivos da sua conta Smart Life.</div>';return}
|
|
||||||
wrap.innerHTML='';
|
|
||||||
for(const d of devs){
|
|
||||||
const sw=findMainSwitch(d.lastState);
|
|
||||||
const isOn=sw?sw.value:false;
|
|
||||||
const dot=d.online===false?'⚪':(d.online?'🟢':'🟡');
|
|
||||||
const lastSeen=d.lastSeen?Math.round((Date.now()-d.lastSeen)/1000):null;
|
|
||||||
const lastSeenStr=lastSeen==null?'':(lastSeen<60?`${lastSeen}s atrás`:lastSeen<3600?`${Math.round(lastSeen/60)}min atrás`:`${Math.round(lastSeen/3600)}h atrás`);
|
|
||||||
const card=document.createElement('div');
|
|
||||||
card.style.cssText='display:flex;align-items:center;gap:12px;padding:12px;border:1px solid var(--m-border,rgba(255,255,255,.08));border-radius:8px;margin-bottom:8px;background:var(--m-bg-2,#0f2a40)';
|
|
||||||
card.innerHTML=`
|
|
||||||
<div style="font-size:28px;line-height:1">${smartDeviceIcon(d.category)}</div>
|
|
||||||
<div style="flex:1;min-width:0">
|
|
||||||
<div style="font-weight:600;font-size:14px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${escapeHtml(d.name)}</div>
|
|
||||||
<div style="font-size:10.5px;color:var(--sepia);font-family:var(--f-mono);letter-spacing:.04em">${dot} ${escapeHtml(d.category_label||'')}${lastSeenStr?' · '+lastSeenStr:''}</div>
|
|
||||||
</div>
|
|
||||||
${sw?`<button class="btn btn-sm" style="background:${isOn?'#22c55e':'#475569'};color:white;border:none;min-width:64px" onclick="toggleSmartDevice('${d.id}')">${isOn?'ON':'OFF'}</button>`:`<button class="btn btn-sm btn-primary" onclick="refreshSmartDeviceState('${d.id}')">↻</button>`}
|
|
||||||
<button class="icon-btn" title="Remover" onclick="removeSmartDevice('${d.id}')" style="font-size:14px">✕</button>
|
|
||||||
`;
|
|
||||||
wrap.appendChild(card);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function startSmartPolling(){
|
|
||||||
if(_smartPollTimer)return;
|
|
||||||
_smartPollTimer=setInterval(()=>{
|
|
||||||
if(document.hidden)return; // Pausa em background
|
|
||||||
const devs=state.smartDevices||[];
|
|
||||||
for(const d of devs){
|
|
||||||
// Backoff: não tenta tão frequente em devices offline
|
|
||||||
const fails=_smartConsecFails[d.id]||0;
|
|
||||||
const skip=fails>=3&&((Date.now()/1000|0)%30!==0);
|
|
||||||
if(skip)continue;
|
|
||||||
refreshSmartDeviceState(d.id).catch(()=>{});
|
|
||||||
}
|
|
||||||
},10000);
|
|
||||||
}
|
|
||||||
|
|
||||||
function stopSmartPolling(){
|
|
||||||
if(_smartPollTimer){clearInterval(_smartPollTimer);_smartPollTimer=null}
|
|
||||||
}
|
|
||||||
|
|
||||||
function initSmartHome(){
|
|
||||||
if(!state.smartDevices)state.smartDevices=[];
|
|
||||||
// Limpa entries inválidas (migration defensiva)
|
|
||||||
state.smartDevices=state.smartDevices.filter(d=>d&&typeof d==='object'&&d.id);
|
|
||||||
refreshSmartStatus();
|
|
||||||
renderSmartDevices();
|
|
||||||
startSmartPolling();
|
|
||||||
}
|
|
||||||
|
|
||||||
(async()=>{
|
(async()=>{
|
||||||
// Wrapper try/catch pra capturar crash no boot (Capacitor WebView pode fechar silenciosamente)
|
// Wrapper try/catch pra capturar crash no boot (Capacitor WebView pode fechar silenciosamente)
|
||||||
try{
|
try{
|
||||||
|
|
@ -4022,7 +3775,6 @@ function initSmartHome(){
|
||||||
try{initBattery()}catch(e){console.error('[boot] battery',e)}
|
try{initBattery()}catch(e){console.error('[boot] battery',e)}
|
||||||
try{initServiceWorker()}catch(e){console.error('[boot] sw',e)}
|
try{initServiceWorker()}catch(e){console.error('[boot] sw',e)}
|
||||||
try{initSensorWidget()}catch(e){console.error('[boot] sensors',e)}
|
try{initSensorWidget()}catch(e){console.error('[boot] sensors',e)}
|
||||||
try{initSmartHome()}catch(e){console.error('[boot] smarthome',e)}
|
|
||||||
try{setSyncStatus(cloudConfigured()?'syncing':'disabled')}catch(e){}
|
try{setSyncStatus(cloudConfigured()?'syncing':'disabled')}catch(e){}
|
||||||
if(cloudConfigured()){
|
if(cloudConfigured()){
|
||||||
try{rtConnect()}catch(e){console.error('[boot] rt',e)}
|
try{rtConnect()}catch(e){console.error('[boot] rt',e)}
|
||||||
|
|
@ -6956,7 +6708,7 @@ async function removeBluetoothDevice(id){
|
||||||
renderBluetoothCard();
|
renderBluetoothCard();
|
||||||
}
|
}
|
||||||
|
|
||||||
const APP_VERSION='1.12.0';
|
const APP_VERSION='1.11.0';
|
||||||
function renderBluetoothCard(){
|
function renderBluetoothCard(){
|
||||||
const el=document.getElementById('bt-list');
|
const el=document.getElementById('bt-list');
|
||||||
const supportEl=document.getElementById('bt-support');
|
const supportEl=document.getElementById('bt-support');
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,8 @@ android {
|
||||||
applicationId "br.com.pontualtech.shivao"
|
applicationId "br.com.pontualtech.shivao"
|
||||||
minSdkVersion rootProject.ext.minSdkVersion
|
minSdkVersion rootProject.ext.minSdkVersion
|
||||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||||
versionCode 33
|
versionCode 32
|
||||||
versionName "1.12.0"
|
versionName "1.11.0"
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||||
aaptOptions {
|
aaptOptions {
|
||||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,6 @@ android {
|
||||||
|
|
||||||
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
|
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation project(':capacitor-community-bluetooth-le')
|
|
||||||
implementation project(':capacitor-app')
|
implementation project(':capacitor-app')
|
||||||
implementation project(':capacitor-geolocation')
|
implementation project(':capacitor-geolocation')
|
||||||
implementation project(':capacitor-local-notifications')
|
implementation project(':capacitor-local-notifications')
|
||||||
|
|
|
||||||
|
|
@ -2,9 +2,6 @@
|
||||||
include ':capacitor-android'
|
include ':capacitor-android'
|
||||||
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
|
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
|
||||||
|
|
||||||
include ':capacitor-community-bluetooth-le'
|
|
||||||
project(':capacitor-community-bluetooth-le').projectDir = new File('../node_modules/@capacitor-community/bluetooth-le/android')
|
|
||||||
|
|
||||||
include ':capacitor-app'
|
include ':capacitor-app'
|
||||||
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
|
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "shivao-mobile",
|
"name": "shivao-mobile",
|
||||||
"version": "1.12.0",
|
"version": "1.11.0",
|
||||||
"description": "Shivao app nativo (Capacitor wrapper Android/iOS)",
|
"description": "Shivao app nativo (Capacitor wrapper Android/iOS)",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|
|
||||||
|
|
@ -1,81 +0,0 @@
|
||||||
# ======================================================
|
|
||||||
# SHIVAO CLOUD - Configuração
|
|
||||||
# Copie este arquivo para .env e preencha os valores
|
|
||||||
# ======================================================
|
|
||||||
|
|
||||||
# --- Autenticação ---
|
|
||||||
# Token único do barco. GERE UMA STRING ALEATÓRIA LONGA!
|
|
||||||
# Sugestão: openssl rand -hex 32
|
|
||||||
BOAT_TOKEN=troque-este-valor-por-uma-string-aleatoria-longa-e-secreta
|
|
||||||
|
|
||||||
# --- Dead-man switch ---
|
|
||||||
# Se o app não enviar heartbeat por X segundos enquanto fundeado,
|
|
||||||
# o servidor dispara o alarme automaticamente. Padrão: 300 (5 min)
|
|
||||||
HEARTBEAT_TIMEOUT_SEC=300
|
|
||||||
|
|
||||||
# ======================================================
|
|
||||||
# CANAIS DE NOTIFICAÇÃO (configure os que quiser usar)
|
|
||||||
# ======================================================
|
|
||||||
|
|
||||||
# --- Telegram (RECOMENDADO - grátis, instantâneo) ---
|
|
||||||
# 1. No Telegram, fale com @BotFather → /newbot → anote o token
|
|
||||||
# 2. Inicie conversa com seu novo bot
|
|
||||||
# 3. Acesse https://api.telegram.org/bot<TOKEN>/getUpdates → anote o chat.id
|
|
||||||
# Você pode enviar para múltiplos chats separando por vírgula
|
|
||||||
TELEGRAM_BOT_TOKEN=
|
|
||||||
TELEGRAM_CHAT_IDS=
|
|
||||||
|
|
||||||
# --- ntfy.sh (push notifications grátis sem cadastro) ---
|
|
||||||
# Instale o app ntfy no celular, escolha um tópico secreto único
|
|
||||||
# Ex: shivao-alertas-x7k9p2 — qualquer pessoa com o nome ouve, então use algo aleatório
|
|
||||||
NTFY_TOPIC=
|
|
||||||
NTFY_SERVER=https://ntfy.sh
|
|
||||||
|
|
||||||
# --- E-mail (SMTP) ---
|
|
||||||
# Para Gmail: ative 2FA, crie "App password" em
|
|
||||||
# https://myaccount.google.com/apppasswords
|
|
||||||
SMTP_HOST=
|
|
||||||
SMTP_PORT=587
|
|
||||||
SMTP_SECURE=false
|
|
||||||
SMTP_USER=
|
|
||||||
SMTP_PASS=
|
|
||||||
SMTP_FROM=Shivao Alertas <alerts@example.com>
|
|
||||||
# Múltiplos destinatários separados por vírgula
|
|
||||||
SMTP_TO=
|
|
||||||
|
|
||||||
# --- Twilio SMS / WhatsApp (PAGO) ---
|
|
||||||
# Crie conta em twilio.com
|
|
||||||
TWILIO_ACCOUNT_SID=
|
|
||||||
TWILIO_AUTH_TOKEN=
|
|
||||||
TWILIO_FROM_NUMBER=
|
|
||||||
TWILIO_WHATSAPP_FROM=
|
|
||||||
# Múltiplos números (com DDI, ex: +5521999998888) separados por vírgula
|
|
||||||
TWILIO_SMS_TO=
|
|
||||||
TWILIO_WHATSAPP_TO=
|
|
||||||
|
|
||||||
# --- Webhook genérico ---
|
|
||||||
# Para Discord, Slack, n8n, ou seu próprio endpoint
|
|
||||||
# Recebe POST com JSON {boat, message, lat, lng, distance, ...}
|
|
||||||
WEBHOOK_URL=
|
|
||||||
|
|
||||||
# ======================================================
|
|
||||||
# IOT (Smart Life / Tuya) — controlar dispositivos do barco
|
|
||||||
# ======================================================
|
|
||||||
# Tuya é o fabricante por trás do app Smart Life. Lâmpadas/tomadas
|
|
||||||
# brand X (Positivo, Multilaser, Intelbras, RWS) são todas Tuya.
|
|
||||||
#
|
|
||||||
# Setup (5 min, gratuito):
|
|
||||||
# 1. Crie conta em https://iot.tuya.com (use mesmo email do Smart Life)
|
|
||||||
# 2. Cloud → Development → Create Cloud Project
|
|
||||||
# - Industry: Smart Home
|
|
||||||
# - Method: Custom Development
|
|
||||||
# - Data Center: escolha o mesmo da app Smart Life
|
|
||||||
# (Eu → Account & Security → Region)
|
|
||||||
# 3. Aba Service API → autorize: IoT Core, Authorization, Smart Home Basic
|
|
||||||
# 4. Aba Devices → Link Tuya App Account → escaneia QR Code com Smart Life
|
|
||||||
# 5. Copie da aba Overview: Access ID + Access Secret
|
|
||||||
TUYA_ACCESS_ID=
|
|
||||||
TUYA_ACCESS_SECRET=
|
|
||||||
# Data center: tuyaus (US, default Brasil), tuyaeu (Europa), tuyacn (China),
|
|
||||||
# tuyain (Índia). Mude se sua conta estiver em outra região.
|
|
||||||
TUYA_BASE_URL=https://openapi.tuyaus.com
|
|
||||||
|
|
@ -1988,30 +1988,6 @@ Marque zonas de proibição (alarme alto) ou atenção (aviso suave). Detecção
|
||||||
<div class="field-hint" style="margin-top:8px">Limitações: <strong>iOS Safari não suporta Web Bluetooth</strong>. APK Android usa plugin nativo. BMS proprietários (Victron, JBD) podem aparecer mas não expor Battery Service padrão.</div>
|
<div class="field-hint" style="margin-top:8px">Limitações: <strong>iOS Safari não suporta Web Bluetooth</strong>. APK Android usa plugin nativo. BMS proprietários (Victron, JBD) podem aparecer mas não expor Battery Service padrão.</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Smart Home / Casa do Barco -->
|
|
||||||
<div class="export-card" id="smart-home-card">
|
|
||||||
<div class="export-card-title">🏠 Casa do Barco · Dispositivos Smart Life</div>
|
|
||||||
<div class="export-card-text" style="margin-bottom:10px">Controle lâmpadas, tomadas, ventiladores e qualquer dispositivo do app <strong>Smart Life</strong> (Tuya / Alexa via WiFi 2.4 GHz). Funciona com Starlink ou qualquer internet do barco.</div>
|
|
||||||
<div id="smart-status" style="font-family:var(--f-mono);font-size:10.5px;color:var(--sepia);margin-bottom:10px;letter-spacing:.04em;line-height:1.55">Verificando configuração...</div>
|
|
||||||
<button class="btn btn-block btn-primary" onclick="openSmartDeviceModal()">+ Adicionar dispositivo</button>
|
|
||||||
<div id="smart-devices-list" style="margin-top:14px"></div>
|
|
||||||
<div class="field-hint" style="margin-top:8px"><strong>Setup</strong> (1x): admin precisa configurar credenciais Tuya no servidor (ver <code>.env.example</code>). Depois disso, qualquer dispositivo no Smart Life aparece aqui automático.</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Modal: lista dispositivos da conta Tuya pra o usuário escolher -->
|
|
||||||
<div class="modal-backdrop" id="smart-device-modal" onclick="if(event.target===this)closeModal('smart-device-modal')">
|
|
||||||
<div class="modal" style="max-width:520px">
|
|
||||||
<div class="modal-head">
|
|
||||||
<h3>🏠 Adicionar dispositivo</h3>
|
|
||||||
<button class="icon-btn" onclick="closeModal('smart-device-modal')">✕</button>
|
|
||||||
</div>
|
|
||||||
<div class="modal-body">
|
|
||||||
<div id="smart-modal-status" style="font-family:var(--f-mono);font-size:11px;color:var(--sepia);margin-bottom:10px;letter-spacing:.04em">Buscando dispositivos da sua conta Smart Life...</div>
|
|
||||||
<div id="smart-modal-list" class="fleet-list"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Raymarine Gateway -->
|
<!-- Raymarine Gateway -->
|
||||||
<div class="export-card" id="nmea-gateway-card">
|
<div class="export-card" id="nmea-gateway-card">
|
||||||
<div class="export-card-title">⚓ Instrumentos Raymarine (gateway NMEA 2000)</div>
|
<div class="export-card-title">⚓ Instrumentos Raymarine (gateway NMEA 2000)</div>
|
||||||
|
|
@ -2638,7 +2614,7 @@ Hora: {HORA}</textarea>
|
||||||
<div class="zone-toast" id="zone-toast"></div>
|
<div class="zone-toast" id="zone-toast"></div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const state={boat:{name:'Shivao',model:''},boats:[],activeBoatId:null,units:'metric',trips:[],maint:[],pending:[],passengers:[],contacts:[],alarmTemplate:'🚨 ALERTA: Shivao saiu da posição de fundeio.\nEstou em {LAT}, {LNG}\nMapa: https://maps.google.com/?q={LAT},{LNG}\nHora: {HORA}',cloud:{url:'',token:'',lastSync:0},auth:null,license:null,webhooks:{telegram:{token:'',chatIds:''},discord:{url:''},generic:{url:''}},anchorHistory:[],zones:[],checklists:[],weatherCfg:{windyKey:'',model:'gfs'},smartDevices:[]};
|
const state={boat:{name:'Shivao',model:''},boats:[],activeBoatId:null,units:'metric',trips:[],maint:[],pending:[],passengers:[],contacts:[],alarmTemplate:'🚨 ALERTA: Shivao saiu da posição de fundeio.\nEstou em {LAT}, {LNG}\nMapa: https://maps.google.com/?q={LAT},{LNG}\nHora: {HORA}',cloud:{url:'',token:'',lastSync:0},auth:null,license:null,webhooks:{telegram:{token:'',chatIds:''},discord:{url:''},generic:{url:''}},anchorHistory:[],zones:[],checklists:[],weatherCfg:{windyKey:'',model:'gfs'}};
|
||||||
|
|
||||||
// ============ NAUTICAL HELPERS (multi-boat + fleet + calculations) ============
|
// ============ NAUTICAL HELPERS (multi-boat + fleet + calculations) ============
|
||||||
// Storage interno SEMPRE em metros (ISO). Conversão só pra display.
|
// Storage interno SEMPRE em metros (ISO). Conversão só pra display.
|
||||||
|
|
@ -3770,229 +3746,6 @@ async function updateStorageInfo(){
|
||||||
}catch(e){document.getElementById('storage-info').textContent='—'}
|
}catch(e){document.getElementById('storage-info').textContent='—'}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============ SMART HOME (Tuya / Smart Life) ============
|
|
||||||
// State.smartDevices = [{id, name, category, category_label, online, lastState, lastSeen}]
|
|
||||||
// Polling de status só roda quando aba "Arquivo" está visível (economiza dados Starlink).
|
|
||||||
|
|
||||||
let _smartPollTimer=null;
|
|
||||||
let _smartConsecFails={};
|
|
||||||
|
|
||||||
function setSmartStatus(msg,kind){
|
|
||||||
const el=document.getElementById('smart-status');if(!el)return;
|
|
||||||
const colors={ok:'#22c55e',warn:'#f59e0b',err:'#ef4444',info:'var(--sepia)'};
|
|
||||||
el.style.color=colors[kind]||'var(--sepia)';
|
|
||||||
el.textContent=msg;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function refreshSmartStatus(){
|
|
||||||
if(!cloudConfigured()){setSmartStatus('☁ Nuvem não configurada','warn');return}
|
|
||||||
try{
|
|
||||||
const r=await cloudFetch('/api/iot/devices');
|
|
||||||
const j=await r.json();
|
|
||||||
const n=(j.devices||[]).length;
|
|
||||||
setSmartStatus(`✓ Conectado · ${n} dispositivo${n!==1?'s':''} disponível${n!==1?'is':''} na conta Smart Life`,'ok');
|
|
||||||
}catch(e){
|
|
||||||
if((e.message||'').includes('503')||(e.message||'').includes('tuya_not_configured')){
|
|
||||||
setSmartStatus('⚙ Tuya não configurado no servidor (admin: configure TUYA_ACCESS_ID em .env)','warn');
|
|
||||||
}else{
|
|
||||||
setSmartStatus('✗ '+(e.message||'erro'),'err');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function openSmartDeviceModal(){
|
|
||||||
if(!cloudConfigured()){toast('Configure a nuvem primeiro');return}
|
|
||||||
openModal('smart-device-modal');
|
|
||||||
const list=document.getElementById('smart-modal-list');
|
|
||||||
const status=document.getElementById('smart-modal-status');
|
|
||||||
list.innerHTML='';
|
|
||||||
status.textContent='Buscando dispositivos da sua conta Smart Life...';
|
|
||||||
status.style.color='var(--sepia)';
|
|
||||||
try{
|
|
||||||
const r=await cloudFetch('/api/iot/devices');
|
|
||||||
const j=await r.json();
|
|
||||||
const devices=j.devices||[];
|
|
||||||
if(devices.length===0){
|
|
||||||
status.textContent='Nenhum dispositivo encontrado. Adicione no app Smart Life primeiro.';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
status.textContent=`${devices.length} dispositivo${devices.length!==1?'s':''} encontrado${devices.length!==1?'s':''}. Toque pra adicionar:`;
|
|
||||||
list.innerHTML='';
|
|
||||||
for(const d of devices){
|
|
||||||
const already=state.smartDevices.find(s=>s.id===d.id);
|
|
||||||
const dot=d.online?'🟢':'⚪';
|
|
||||||
const item=document.createElement('div');
|
|
||||||
item.className='fleet-item';
|
|
||||||
item.style.cssText='display:flex;justify-content:space-between;align-items:center;padding:10px;border:1px solid var(--m-border,rgba(255,255,255,.08));border-radius:6px;margin-bottom:6px;'+(already?'opacity:.5':'cursor:pointer');
|
|
||||||
item.innerHTML=`<div><div style="font-weight:600">${dot} ${escapeHtml(d.name)}</div><div style="font-size:11px;color:var(--sepia);font-family:var(--f-mono)">${escapeHtml(d.category_label||d.category||'')}</div></div>${already?'<span style="font-size:11px;color:var(--sepia)">já adicionado</span>':'<button class="btn btn-sm btn-primary">+ Adicionar</button>'}`;
|
|
||||||
if(!already){
|
|
||||||
item.onclick=()=>{addSmartDevice(d);closeModal('smart-device-modal')};
|
|
||||||
}
|
|
||||||
list.appendChild(item);
|
|
||||||
}
|
|
||||||
}catch(e){
|
|
||||||
if((e.message||'').includes('503')||(e.message||'').includes('tuya_not_configured')){
|
|
||||||
status.style.color='#f59e0b';
|
|
||||||
status.innerHTML='⚙ Tuya não configurado.<br>Admin precisa adicionar <code>TUYA_ACCESS_ID</code> + <code>TUYA_ACCESS_SECRET</code> no env do servidor.<br>Veja <code>server/.env.example</code>.';
|
|
||||||
}else{
|
|
||||||
status.style.color='#ef4444';
|
|
||||||
status.textContent='Erro: '+(e.message||'falha');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function addSmartDevice(d){
|
|
||||||
if(!state.smartDevices)state.smartDevices=[];
|
|
||||||
if(state.smartDevices.find(s=>s.id===d.id)){toast('Já adicionado');return}
|
|
||||||
state.smartDevices.push({
|
|
||||||
id:d.id,
|
|
||||||
name:d.name,
|
|
||||||
category:d.category,
|
|
||||||
category_label:d.category_label||d.category,
|
|
||||||
online:d.online,
|
|
||||||
lastState:null,
|
|
||||||
lastSeen:Date.now(),
|
|
||||||
addedAt:Date.now(),
|
|
||||||
});
|
|
||||||
saveState();
|
|
||||||
renderSmartDevices();
|
|
||||||
toast(`+ ${d.name}`);
|
|
||||||
// Busca estado inicial
|
|
||||||
refreshSmartDeviceState(d.id).catch(()=>{});
|
|
||||||
}
|
|
||||||
|
|
||||||
function removeSmartDevice(id){
|
|
||||||
if(!confirm('Remover este dispositivo do Shivão? (não apaga do Smart Life)'))return;
|
|
||||||
state.smartDevices=(state.smartDevices||[]).filter(d=>d.id!==id);
|
|
||||||
saveState();
|
|
||||||
renderSmartDevices();
|
|
||||||
toast('Removido');
|
|
||||||
}
|
|
||||||
|
|
||||||
function smartDeviceIcon(category){
|
|
||||||
const icons={cz:'🔌',dj:'💡',kg:'🎚️',fs:'🌀',dd:'💡',xdd:'🔆',dc:'💡',tdq:'⚡',kt:'❄️',wsdcg:'🌡️',mcs:'🚪',sd:'🤖',cl:'🪟',clkg:'🪟',wnykq:'🌡️'};
|
|
||||||
return icons[category]||'🔧';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encontra DP de "switch principal" pra renderizar toggle.
|
|
||||||
// Tuya pode usar switch_1, switch_led, switch — depende do produto.
|
|
||||||
function findMainSwitch(status){
|
|
||||||
if(!Array.isArray(status))return null;
|
|
||||||
// Prioridade: switch > switch_1 > switch_led > primeiro boolean
|
|
||||||
const candidates=['switch','switch_1','switch_led'];
|
|
||||||
for(const c of candidates){
|
|
||||||
const dp=status.find(s=>s.code===c&&typeof s.value==='boolean');
|
|
||||||
if(dp)return dp;
|
|
||||||
}
|
|
||||||
return status.find(s=>typeof s.value==='boolean')||null;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function refreshSmartDeviceState(id){
|
|
||||||
try{
|
|
||||||
const r=await cloudFetch('/api/iot/status/'+encodeURIComponent(id));
|
|
||||||
const j=await r.json();
|
|
||||||
const dev=state.smartDevices.find(d=>d.id===id);
|
|
||||||
if(!dev)return;
|
|
||||||
dev.lastState=j.status;
|
|
||||||
dev.online=true;
|
|
||||||
dev.lastSeen=Date.now();
|
|
||||||
_smartConsecFails[id]=0;
|
|
||||||
saveState();
|
|
||||||
renderSmartDevices();
|
|
||||||
}catch(e){
|
|
||||||
const dev=state.smartDevices.find(d=>d.id===id);
|
|
||||||
if(dev){
|
|
||||||
_smartConsecFails[id]=(_smartConsecFails[id]||0)+1;
|
|
||||||
// Backoff exponencial: marca offline após 3 falhas consecutivas
|
|
||||||
if(_smartConsecFails[id]>=3){
|
|
||||||
dev.online=false;
|
|
||||||
saveState();
|
|
||||||
renderSmartDevices();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function toggleSmartDevice(id){
|
|
||||||
const dev=state.smartDevices.find(d=>d.id===id);
|
|
||||||
if(!dev)return;
|
|
||||||
const sw=findMainSwitch(dev.lastState);
|
|
||||||
const newVal=sw?!sw.value:true;
|
|
||||||
// OPTIMISTIC UI: atualiza imediato, reverte em caso de erro
|
|
||||||
if(sw){sw.value=newVal}else if(dev.lastState){dev.lastState.push({code:'switch',value:newVal})}else{dev.lastState=[{code:'switch',value:newVal}]}
|
|
||||||
renderSmartDevices();
|
|
||||||
try{
|
|
||||||
const code=sw?sw.code:'switch';
|
|
||||||
const r=await cloudFetch('/api/iot/command/'+encodeURIComponent(id),{
|
|
||||||
method:'POST',
|
|
||||||
body:JSON.stringify({commands:[{code,value:newVal}]}),
|
|
||||||
});
|
|
||||||
await r.json();
|
|
||||||
// Confirma re-buscando status real após 800ms (Tuya leva ~500ms pra refletir)
|
|
||||||
setTimeout(()=>{refreshSmartDeviceState(id).catch(()=>{})},800);
|
|
||||||
}catch(e){
|
|
||||||
// Reverte UI
|
|
||||||
if(sw)sw.value=!newVal;
|
|
||||||
renderSmartDevices();
|
|
||||||
toast('Falhou: '+(e.message||'erro'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderSmartDevices(){
|
|
||||||
const wrap=document.getElementById('smart-devices-list');
|
|
||||||
if(!wrap)return;
|
|
||||||
const devs=state.smartDevices||[];
|
|
||||||
if(devs.length===0){wrap.innerHTML='<div class="field-hint" style="text-align:center;padding:20px 10px">Nenhum dispositivo adicionado.<br>Toque "+ Adicionar" pra ver os dispositivos da sua conta Smart Life.</div>';return}
|
|
||||||
wrap.innerHTML='';
|
|
||||||
for(const d of devs){
|
|
||||||
const sw=findMainSwitch(d.lastState);
|
|
||||||
const isOn=sw?sw.value:false;
|
|
||||||
const dot=d.online===false?'⚪':(d.online?'🟢':'🟡');
|
|
||||||
const lastSeen=d.lastSeen?Math.round((Date.now()-d.lastSeen)/1000):null;
|
|
||||||
const lastSeenStr=lastSeen==null?'':(lastSeen<60?`${lastSeen}s atrás`:lastSeen<3600?`${Math.round(lastSeen/60)}min atrás`:`${Math.round(lastSeen/3600)}h atrás`);
|
|
||||||
const card=document.createElement('div');
|
|
||||||
card.style.cssText='display:flex;align-items:center;gap:12px;padding:12px;border:1px solid var(--m-border,rgba(255,255,255,.08));border-radius:8px;margin-bottom:8px;background:var(--m-bg-2,#0f2a40)';
|
|
||||||
card.innerHTML=`
|
|
||||||
<div style="font-size:28px;line-height:1">${smartDeviceIcon(d.category)}</div>
|
|
||||||
<div style="flex:1;min-width:0">
|
|
||||||
<div style="font-weight:600;font-size:14px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${escapeHtml(d.name)}</div>
|
|
||||||
<div style="font-size:10.5px;color:var(--sepia);font-family:var(--f-mono);letter-spacing:.04em">${dot} ${escapeHtml(d.category_label||'')}${lastSeenStr?' · '+lastSeenStr:''}</div>
|
|
||||||
</div>
|
|
||||||
${sw?`<button class="btn btn-sm" style="background:${isOn?'#22c55e':'#475569'};color:white;border:none;min-width:64px" onclick="toggleSmartDevice('${d.id}')">${isOn?'ON':'OFF'}</button>`:`<button class="btn btn-sm btn-primary" onclick="refreshSmartDeviceState('${d.id}')">↻</button>`}
|
|
||||||
<button class="icon-btn" title="Remover" onclick="removeSmartDevice('${d.id}')" style="font-size:14px">✕</button>
|
|
||||||
`;
|
|
||||||
wrap.appendChild(card);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function startSmartPolling(){
|
|
||||||
if(_smartPollTimer)return;
|
|
||||||
_smartPollTimer=setInterval(()=>{
|
|
||||||
if(document.hidden)return; // Pausa em background
|
|
||||||
const devs=state.smartDevices||[];
|
|
||||||
for(const d of devs){
|
|
||||||
// Backoff: não tenta tão frequente em devices offline
|
|
||||||
const fails=_smartConsecFails[d.id]||0;
|
|
||||||
const skip=fails>=3&&((Date.now()/1000|0)%30!==0);
|
|
||||||
if(skip)continue;
|
|
||||||
refreshSmartDeviceState(d.id).catch(()=>{});
|
|
||||||
}
|
|
||||||
},10000);
|
|
||||||
}
|
|
||||||
|
|
||||||
function stopSmartPolling(){
|
|
||||||
if(_smartPollTimer){clearInterval(_smartPollTimer);_smartPollTimer=null}
|
|
||||||
}
|
|
||||||
|
|
||||||
function initSmartHome(){
|
|
||||||
if(!state.smartDevices)state.smartDevices=[];
|
|
||||||
// Limpa entries inválidas (migration defensiva)
|
|
||||||
state.smartDevices=state.smartDevices.filter(d=>d&&typeof d==='object'&&d.id);
|
|
||||||
refreshSmartStatus();
|
|
||||||
renderSmartDevices();
|
|
||||||
startSmartPolling();
|
|
||||||
}
|
|
||||||
|
|
||||||
(async()=>{
|
(async()=>{
|
||||||
// Wrapper try/catch pra capturar crash no boot (Capacitor WebView pode fechar silenciosamente)
|
// Wrapper try/catch pra capturar crash no boot (Capacitor WebView pode fechar silenciosamente)
|
||||||
try{
|
try{
|
||||||
|
|
@ -4022,7 +3775,6 @@ function initSmartHome(){
|
||||||
try{initBattery()}catch(e){console.error('[boot] battery',e)}
|
try{initBattery()}catch(e){console.error('[boot] battery',e)}
|
||||||
try{initServiceWorker()}catch(e){console.error('[boot] sw',e)}
|
try{initServiceWorker()}catch(e){console.error('[boot] sw',e)}
|
||||||
try{initSensorWidget()}catch(e){console.error('[boot] sensors',e)}
|
try{initSensorWidget()}catch(e){console.error('[boot] sensors',e)}
|
||||||
try{initSmartHome()}catch(e){console.error('[boot] smarthome',e)}
|
|
||||||
try{setSyncStatus(cloudConfigured()?'syncing':'disabled')}catch(e){}
|
try{setSyncStatus(cloudConfigured()?'syncing':'disabled')}catch(e){}
|
||||||
if(cloudConfigured()){
|
if(cloudConfigured()){
|
||||||
try{rtConnect()}catch(e){console.error('[boot] rt',e)}
|
try{rtConnect()}catch(e){console.error('[boot] rt',e)}
|
||||||
|
|
@ -6956,7 +6708,7 @@ async function removeBluetoothDevice(id){
|
||||||
renderBluetoothCard();
|
renderBluetoothCard();
|
||||||
}
|
}
|
||||||
|
|
||||||
const APP_VERSION='1.12.0';
|
const APP_VERSION='1.11.0';
|
||||||
function renderBluetoothCard(){
|
function renderBluetoothCard(){
|
||||||
const el=document.getElementById('bt-list');
|
const el=document.getElementById('bt-list');
|
||||||
const supportEl=document.getElementById('bt-support');
|
const supportEl=document.getElementById('bt-support');
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
// Shivao Service Worker — offline real
|
// Shivao Service Worker — offline real
|
||||||
// Estratégia: shell precachado, tiles cache-first, windy network-first, /api passa direto.
|
// Estratégia: shell precachado, tiles cache-first, windy network-first, /api passa direto.
|
||||||
// Versão usada nos cache names — bumpa essa string pra invalidar caches antigos em deploys.
|
// Versão usada nos cache names — bumpa essa string pra invalidar caches antigos em deploys.
|
||||||
const VERSION = 'shivao-v1.12.0';
|
const VERSION = 'shivao-v1.11.0';
|
||||||
const SHELL_CACHE = `shivao-shell-${VERSION}`;
|
const SHELL_CACHE = `shivao-shell-${VERSION}`;
|
||||||
const TILES_CACHE = 'shivao-tiles-v1'; // separado pra não invalidar tiles em update do shell
|
const TILES_CACHE = 'shivao-tiles-v1'; // separado pra não invalidar tiles em update do shell
|
||||||
const WINDY_CACHE = `shivao-windy-${VERSION}`;
|
const WINDY_CACHE = `shivao-windy-${VERSION}`;
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,6 @@ import { hashPassword, verifyPassword, signAccessToken, signRefreshToken, verify
|
||||||
import * as billing from './billing.js';
|
import * as billing from './billing.js';
|
||||||
import { initRealtime, broadcastStateChange, getOnlineCount } from './realtime.js';
|
import { initRealtime, broadcastStateChange, getOnlineCount } from './realtime.js';
|
||||||
import * as gcal from './google-calendar.js';
|
import * as gcal from './google-calendar.js';
|
||||||
import * as tuya from './tuya.js';
|
|
||||||
|
|
||||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
const PORT = parseInt(process.env.PORT || '3000');
|
const PORT = parseInt(process.env.PORT || '3000');
|
||||||
|
|
@ -193,59 +192,6 @@ app.get('/api/bms/diag-log/:file', requireAuth, (req, res) => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ===== IoT (Smart Life / Tuya) =====
|
|
||||||
// Proxy assinado pra Tuya Cloud API. Access Secret nunca vai pro client.
|
|
||||||
|
|
||||||
app.get('/api/iot/devices', requireAuth, async (req, res) => {
|
|
||||||
if (!tuya.isEnabled()) return tuya.disabledResponse(res);
|
|
||||||
try {
|
|
||||||
const r = await tuya.listDevices();
|
|
||||||
if (r.error) return res.status(502).json({ error: r.error, code: r.code });
|
|
||||||
// Enriquece com label humano
|
|
||||||
const devices = r.devices.map(d => ({ ...d, category_label: tuya.categoryLabel(d.category) }));
|
|
||||||
res.json({ devices });
|
|
||||||
} catch (e) {
|
|
||||||
res.status(500).json({ error: e.message });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.get('/api/iot/status/:deviceId', requireAuth, async (req, res) => {
|
|
||||||
if (!tuya.isEnabled()) return tuya.disabledResponse(res);
|
|
||||||
const deviceId = (req.params.deviceId || '').replace(/[^a-zA-Z0-9]/g, '');
|
|
||||||
if (!deviceId) return res.status(400).json({ error: 'deviceId required' });
|
|
||||||
try {
|
|
||||||
const r = await tuya.getDeviceStatus(deviceId);
|
|
||||||
if (r.error) return res.status(502).json({ error: r.error, code: r.code });
|
|
||||||
res.json({ status: r.status });
|
|
||||||
} catch (e) {
|
|
||||||
res.status(500).json({ error: e.message });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.post('/api/iot/command/:deviceId', requireAuth, async (req, res) => {
|
|
||||||
if (!tuya.isEnabled()) return tuya.disabledResponse(res);
|
|
||||||
const deviceId = (req.params.deviceId || '').replace(/[^a-zA-Z0-9]/g, '');
|
|
||||||
const { commands } = req.body || {};
|
|
||||||
if (!deviceId) return res.status(400).json({ error: 'deviceId required' });
|
|
||||||
if (!Array.isArray(commands) || commands.length === 0) {
|
|
||||||
return res.status(400).json({ error: 'commands array required' });
|
|
||||||
}
|
|
||||||
// Validação básica: cada item precisa ter code:string + value
|
|
||||||
for (const c of commands) {
|
|
||||||
if (!c || typeof c.code !== 'string') {
|
|
||||||
return res.status(400).json({ error: 'each command needs {code:string, value:any}' });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const r = await tuya.sendCommand(deviceId, commands);
|
|
||||||
if (!r.ok) return res.status(502).json({ error: r.error, code: r.code });
|
|
||||||
db.audit(req.user.id, 'iot_command', 'tuya', deviceId, { commands }, req.ip);
|
|
||||||
res.json({ ok: true });
|
|
||||||
} catch (e) {
|
|
||||||
res.status(500).json({ error: e.message });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// ===== Google Login via OAuth redirect (pra apps Capacitor onde GSI popup não funciona) =====
|
// ===== Google Login via OAuth redirect (pra apps Capacitor onde GSI popup não funciona) =====
|
||||||
// In-memory store: session_id → { tokens, createdAt }. Auto-expira em 10min.
|
// In-memory store: session_id → { tokens, createdAt }. Auto-expira em 10min.
|
||||||
const pendingGoogleSessions = new Map();
|
const pendingGoogleSessions = new Map();
|
||||||
|
|
@ -467,7 +413,7 @@ app.get('/.well-known/assetlinks.json', (req, res) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
// Atalho: /apk redireciona pra última APK release no Forgejo
|
// Atalho: /apk redireciona pra última APK release no Forgejo
|
||||||
const LATEST_APK_URL = 'https://git.pontualtech.work/karlao/shivao-projeto/releases/download/v1.12.0/Shivao-v1.12.0.apk';
|
const LATEST_APK_URL = 'https://git.pontualtech.work/karlao/shivao-projeto/releases/download/v1.11.0/Shivao-v1.11.0.apk';
|
||||||
app.get('/apk', (req, res) => res.redirect(302, LATEST_APK_URL));
|
app.get('/apk', (req, res) => res.redirect(302, LATEST_APK_URL));
|
||||||
|
|
||||||
// Página A4 imprimível com QR Code + instruções (cola no barco/marina)
|
// Página A4 imprimível com QR Code + instruções (cola no barco/marina)
|
||||||
|
|
|
||||||
|
|
@ -1,165 +0,0 @@
|
||||||
// Tuya OpenAPI client — Smart Life devices via HMAC-SHA256 signing
|
|
||||||
// Docs: https://developer.tuya.com/en/docs/cloud/cloud-api-best-practice
|
|
||||||
//
|
|
||||||
// Why server-side: Access Secret never goes to client (PWA), pra evitar token
|
|
||||||
// leak via DevTools. Client só conhece deviceId; server assina e proxia.
|
|
||||||
|
|
||||||
import crypto from 'node:crypto';
|
|
||||||
|
|
||||||
const ACCESS_ID = process.env.TUYA_ACCESS_ID || '';
|
|
||||||
const ACCESS_SECRET = process.env.TUYA_ACCESS_SECRET || '';
|
|
||||||
// Tuya tem 5 data centers. Escolha o mesmo da conta Smart Life (Eu → Account → Region):
|
|
||||||
// us = openapi.tuyaus.com (default North America)
|
|
||||||
// eu = openapi.tuyaeu.com (Europe)
|
|
||||||
// cn = openapi.tuyacn.com (China)
|
|
||||||
// in = openapi.tuyain.com (India)
|
|
||||||
// sg = openapi-sg.iotbing.com (South Asia)
|
|
||||||
// Brasil normalmente cai no US.
|
|
||||||
const BASE_URL = process.env.TUYA_BASE_URL || 'https://openapi.tuyaus.com';
|
|
||||||
|
|
||||||
let cachedToken = null; // {access_token, expires_at_ms}
|
|
||||||
|
|
||||||
export function isEnabled() {
|
|
||||||
return !!(ACCESS_ID && ACCESS_SECRET);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function disabledResponse(res) {
|
|
||||||
return res.status(503).json({
|
|
||||||
error: 'tuya_not_configured',
|
|
||||||
message: 'Configure TUYA_ACCESS_ID + TUYA_ACCESS_SECRET no env do servidor.',
|
|
||||||
setup_url: 'https://iot.tuya.com',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function sha256(str) {
|
|
||||||
return crypto.createHash('sha256').update(str, 'utf8').digest('hex');
|
|
||||||
}
|
|
||||||
|
|
||||||
function hmacSha256(key, str) {
|
|
||||||
return crypto.createHmac('sha256', key).update(str, 'utf8').digest('hex').toUpperCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
// stringToSign = HTTPMethod + "\n" + Content-SHA256 + "\n" + Headers + "\n" + Url
|
|
||||||
// Headers fica vazio porque não usamos signedHeaders custom.
|
|
||||||
function buildStringToSign(method, urlPath, body) {
|
|
||||||
const contentSha = sha256(body || '');
|
|
||||||
return `${method.toUpperCase()}\n${contentSha}\n\n${urlPath}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Para token endpoint: sign = client_id + t + nonce + stringToSign
|
|
||||||
// Para business endpoints: sign = client_id + access_token + t + nonce + stringToSign
|
|
||||||
function buildSignature(method, urlPath, body, withToken) {
|
|
||||||
const t = String(Date.now());
|
|
||||||
const nonce = crypto.randomBytes(16).toString('hex');
|
|
||||||
const stringToSign = buildStringToSign(method, urlPath, body);
|
|
||||||
const tokenPart = withToken && cachedToken ? cachedToken.access_token : '';
|
|
||||||
const str = ACCESS_ID + tokenPart + t + nonce + stringToSign;
|
|
||||||
const sign = hmacSha256(ACCESS_SECRET, str);
|
|
||||||
return { sign, t, nonce };
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchToken() {
|
|
||||||
const urlPath = '/v1.0/token?grant_type=1';
|
|
||||||
const { sign, t, nonce } = buildSignature('GET', urlPath, '', false);
|
|
||||||
const r = await fetch(BASE_URL + urlPath, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
'client_id': ACCESS_ID,
|
|
||||||
'sign': sign,
|
|
||||||
'sign_method': 'HMAC-SHA256',
|
|
||||||
't': t,
|
|
||||||
'nonce': nonce,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const j = await r.json();
|
|
||||||
if (!j.success) throw new Error(`tuya_token_failed: ${j.code} ${j.msg}`);
|
|
||||||
cachedToken = {
|
|
||||||
access_token: j.result.access_token,
|
|
||||||
refresh_token: j.result.refresh_token,
|
|
||||||
expires_at_ms: Date.now() + (j.result.expire_time * 1000) - 60000, // refresh 1min antes
|
|
||||||
};
|
|
||||||
return cachedToken;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function ensureToken() {
|
|
||||||
if (cachedToken && Date.now() < cachedToken.expires_at_ms) return cachedToken;
|
|
||||||
return await fetchToken();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Request genérico assinado a um endpoint Tuya OpenAPI
|
|
||||||
async function tuyaRequest(method, urlPath, body) {
|
|
||||||
await ensureToken();
|
|
||||||
const bodyStr = body ? JSON.stringify(body) : '';
|
|
||||||
const { sign, t, nonce } = buildSignature(method, urlPath, bodyStr, true);
|
|
||||||
const r = await fetch(BASE_URL + urlPath, {
|
|
||||||
method,
|
|
||||||
headers: {
|
|
||||||
'client_id': ACCESS_ID,
|
|
||||||
'access_token': cachedToken.access_token,
|
|
||||||
'sign': sign,
|
|
||||||
'sign_method': 'HMAC-SHA256',
|
|
||||||
't': t,
|
|
||||||
'nonce': nonce,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: bodyStr || undefined,
|
|
||||||
});
|
|
||||||
const j = await r.json();
|
|
||||||
// Token expirado mid-flight: invalida + retry 1x
|
|
||||||
if (j.code === 1010 || j.code === 1011 || j.code === 1004) {
|
|
||||||
cachedToken = null;
|
|
||||||
return tuyaRequest(method, urlPath, body);
|
|
||||||
}
|
|
||||||
return j;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===== APIs públicas =====
|
|
||||||
|
|
||||||
// Lista todos os devices vinculados ao app Smart Life autorizado
|
|
||||||
// (vinculado em iot.tuya.com → Cloud → Devices → Link Tuya App Account)
|
|
||||||
export async function listDevices(uid) {
|
|
||||||
// uid é opcional; sem uid retorna devices da org. Pra Karlão (1 conta) ok sem.
|
|
||||||
const res = await tuyaRequest('GET', '/v1.3/iot-03/devices?source_type=tuyaUser&source_id=' + (uid || ''), null);
|
|
||||||
if (!res.success) return { error: res.msg, code: res.code, devices: [] };
|
|
||||||
return {
|
|
||||||
devices: (res.result?.list || []).map(d => ({
|
|
||||||
id: d.id,
|
|
||||||
name: d.name,
|
|
||||||
online: d.online,
|
|
||||||
product_id: d.product_id,
|
|
||||||
product_name: d.product_name,
|
|
||||||
category: d.category, // 'cz' = socket, 'dj' = light, 'kg' = switch, 'fs' = fan, etc.
|
|
||||||
icon: d.icon,
|
|
||||||
ip: d.ip,
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Status atual do device (lista de DPs / data points)
|
|
||||||
export async function getDeviceStatus(deviceId) {
|
|
||||||
const res = await tuyaRequest('GET', `/v1.0/iot-03/devices/${deviceId}/status`, null);
|
|
||||||
if (!res.success) return { error: res.msg, code: res.code };
|
|
||||||
// Result é array tipo [{code:'switch_1', value:true}, {code:'bright_value', value:600}]
|
|
||||||
return { status: res.result || [] };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dispara comando: array de {code, value}
|
|
||||||
// Ex pra ligar: [{code:'switch_1', value:true}]
|
|
||||||
// Ex pra dimmer: [{code:'switch_led', value:true}, {code:'bright_value_v2', value:800}]
|
|
||||||
export async function sendCommand(deviceId, commands) {
|
|
||||||
const res = await tuyaRequest('POST', `/v1.0/iot-03/devices/${deviceId}/commands`, { commands });
|
|
||||||
if (!res.success) return { ok: false, error: res.msg, code: res.code };
|
|
||||||
return { ok: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Categoria → função humanizada (ajuda UI a renderizar ícone certo)
|
|
||||||
export function categoryLabel(cat) {
|
|
||||||
const map = {
|
|
||||||
cz: 'Tomada', dj: 'Lâmpada', kg: 'Interruptor', fs: 'Ventilador',
|
|
||||||
dd: 'Fita LED', xdd: 'Luminária', dc: 'Cordão LED', tdq: 'Disjuntor',
|
|
||||||
cwwsq: 'Alimentador', kt: 'Ar-condicionado', wsdcg: 'Sensor temp/umid',
|
|
||||||
mcs: 'Sensor porta', co2bj: 'Sensor CO2', sd: 'Robô aspirador',
|
|
||||||
cl: 'Cortina', clkg: 'Switch cortina', wnykq: 'Termostato',
|
|
||||||
};
|
|
||||||
return map[cat] || cat || 'Dispositivo';
|
|
||||||
}
|
|
||||||
Loading…
Reference in a new issue