diff --git a/.gitignore b/.gitignore
index ec50e2a..dead7b7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,3 +16,5 @@ mediamtx.exe
/frontend/node_modules/
/frontend/.vite/
+/android-display/build/
+*.jks
diff --git a/RELEASE-v0.1.44.md b/RELEASE-v0.1.44.md
new file mode 100644
index 0000000..8345105
--- /dev/null
+++ b/RELEASE-v0.1.44.md
@@ -0,0 +1,19 @@
+# v0.1.44 · 家庭电视与设备看板
+
+- 新增 `/tv`:本地 Vue + Bootstrap,温暖简洁的竖屏 / 横屏家庭看板。方形模拟时钟、北京时间、农历、ISO 周数、家庭设备与未来 60 天已发布家庭记事。设备多于四台时分组轮换;网络短暂中断保留上次资料并标明状态,授权失效清空家庭数据。
+- 天气经管理员设置城市与经纬度后,由服务端读取 Open-Meteo。15 分钟缓存,过期标记,六小时后不再展示旧天气;没有外部 CDN 或字体。天气来源及协议:https://open-meteo.com/en/docs 。
+- 电视登记为所在家庭的设备对象。展示凭据仅能读取单家庭的精简数据,以及上报自身遥测;数据库只保存凭据摘要,一年有效,可随时停用。电视不持有管理员密码,不能调用设备控制或人员接口。
+- 电视管理提供心跳状态、最后采样时间、处理器温度、可用内存 / 存储、IP、Android 版本、屏幕分辨率与前台状态。没有传感器的指标明确显示未提供;本批硬件的 test_battery 节点不作为功耗传感器。
+- 安卓家庭屏应用:保留系统旋转设置,全屏展示,前台保持亮屏,20 秒硬件心跳;重启后启动遥测服务。系统是否允许自动打开前台应用仍取决于系统策略,本版不替换电视默认桌面。
+- App 使用 8 位一次性配对码绑定家庭,10 分钟有效;摄像头凭据使用独立的原生授权,普通展示链接不能读取。底部固定一行镜头,占屏幕约 12%,最多三路并排、更多镜头每分钟分组轮换。原生播放器直接连接同局域网 RTSP 子码流,断线隐藏旧帧并重连,不通过平台转发视频。授权连接失联超过五分钟停止画面。
+- 管理员按需查看模拟屏,60 秒内约每 20 秒回传当前应用窗口;使用 PixelCopy,非系统级远程桌面。退出应用后不采集其他应用。预览只在服务端内存短暂保存,90 秒失效,不写磁盘或网盘。
+- 自动告警:心跳中断超过 100 秒,温度 ≥75°C / ≥85°C,可用内存低于 5%,可用存储低于 0.5 GB,以及看板退出前台。记录触发与恢复,单授权保留最近 200 条已恢复记录。报警显示在家庭设备页,尚无短信或微信推送。
+- 超级管理员可跨家庭转移设备,原区域、人员引用与上级设备清空,电视旧展示授权立即撤销。直接接入的摄像头随同镜头转移;仍关联录像机的设备需先解除关联。家庭管理员不能跨家庭移动。
+
+## 构建
+
+前端:`pnpm --dir frontend build`。安卓:`android-display/build.ps1`,可通过 ToolRoot 参数指定本机 Android SDK / JDK。签名文件在本机 LOCALAPPDATA/ZhaoDisplay,APK 不包含任何授权令牌;安装后单独授权。
+
+## 数据库
+
+新增 `household_displays`、`display_native_keys`、`display_telemetry`、`display_alerts` 表。旧版服务可忽略新增表,原业务表结构未改变。上线前执行 SQLite 一致性备份。
diff --git a/VERSION b/VERSION
index 278cbc8..6871b9e 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.1.43
+0.1.44
diff --git a/android-display/AndroidManifest.xml b/android-display/AndroidManifest.xml
new file mode 100644
index 0000000..c455717
--- /dev/null
+++ b/android-display/AndroidManifest.xml
@@ -0,0 +1,15 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/android-display/build.ps1 b/android-display/build.ps1
new file mode 100644
index 0000000..3d6a5d8
--- /dev/null
+++ b/android-display/build.ps1
@@ -0,0 +1,43 @@
+param([string]$ToolRoot='C:\Users\Administrator\Documents\ChatGPT\优创未来\services\toplc-vpn-android\.tools')
+$ErrorActionPreference='Stop'
+$source=Split-Path -Parent $MyInvocation.MyCommand.Path
+$stage=Join-Path 'C:\CodexBuild' ('ZhaoDisplay-'+[guid]::NewGuid().ToString('N'))
+New-Item -ItemType Directory -Path $stage | Out-Null
+Copy-Item -LiteralPath (Join-Path $source 'AndroidManifest.xml') -Destination $stage
+Copy-Item -LiteralPath (Join-Path $source 'res'),(Join-Path $source 'src') -Destination $stage -Recurse
+$jdk=Join-Path $ToolRoot 'jdk-staging\jdk-21.0.12.1+1'
+$sdk=Join-Path $ToolRoot 'android-sdk'
+$bt=Join-Path $sdk 'build-tools\36.0.0'
+$android=Join-Path $sdk 'platforms\android-37.0\android.jar'
+$env:JAVA_HOME=$jdk
+$env:Path="$jdk\bin;$env:Path"
+$build=Join-Path $stage 'build'
+New-Item -ItemType Directory -Path $build,"$build\classes","$build\dex","$build\generated" | Out-Null
+& "$bt\aapt2.exe" compile --dir "$stage\res" -o "$build\compiled.zip"
+if($LASTEXITCODE){throw 'Resource compilation failed'}
+& "$bt\aapt2.exe" link -o "$build\unsigned.apk" -I $android --manifest "$stage\AndroidManifest.xml" --java "$build\generated" "$build\compiled.zip"
+if($LASTEXITCODE){throw 'Resource linking failed'}
+$sources=@((Get-ChildItem "$stage\src","$build\generated" -Recurse -Filter '*.java').FullName)
+& "$jdk\bin\javac.exe" -encoding UTF-8 -source 8 -target 8 -cp $android -d "$build\classes" $sources
+if($LASTEXITCODE){throw 'Java compilation failed'}
+& "$jdk\bin\jar.exe" cf "$build\classes.jar" -C "$build\classes" .
+& "$bt\d8.bat" --lib $android --min-api 26 --output "$build\dex" "$build\classes.jar"
+if($LASTEXITCODE){throw 'Dex compilation failed'}
+Copy-Item "$build\unsigned.apk" "$build\with-dex.apk"
+Add-Type -AssemblyName System.IO.Compression.FileSystem
+$zip=[IO.Compression.ZipFile]::Open("$build\with-dex.apk",[IO.Compression.ZipArchiveMode]::Update)
+try{[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,"$build\dex\classes.dex",'classes.dex',[IO.Compression.CompressionLevel]::Optimal) | Out-Null}finally{$zip.Dispose()}
+& "$bt\zipalign.exe" -f 4 "$build\with-dex.apk" "$build\aligned.apk"
+$keydir=Join-Path $env:LOCALAPPDATA 'ZhaoDisplay'
+New-Item -ItemType Directory -Force -Path $keydir | Out-Null
+$keystore=Join-Path $keydir 'display-signing.jks'
+if(!(Test-Path -LiteralPath $keystore)){
+ & "$jdk\bin\keytool.exe" -genkeypair -keystore $keystore -storepass android -keypass android -alias zhaodisplay -keyalg RSA -keysize 2048 -validity 10000 -dname 'CN=Zhao Household Display,O=UCVL,C=CN'
+ if($LASTEXITCODE){throw 'Signing key generation failed'}
+}
+New-Item -ItemType Directory -Force -Path "$source\build" | Out-Null
+& "$bt\apksigner.bat" sign --ks $keystore --ks-pass pass:android --key-pass pass:android --ks-key-alias zhaodisplay --out "$source\build\ZhaoDisplay.apk" "$build\aligned.apk"
+if($LASTEXITCODE){throw 'APK signing failed'}
+& "$bt\apksigner.bat" verify "$source\build\ZhaoDisplay.apk"
+if($LASTEXITCODE){throw 'APK verification failed'}
+Write-Output "$source\build\ZhaoDisplay.apk"
diff --git a/android-display/res/values/strings.xml b/android-display/res/values/strings.xml
new file mode 100644
index 0000000..5d9688d
--- /dev/null
+++ b/android-display/res/values/strings.xml
@@ -0,0 +1 @@
+赵府家庭屏
diff --git a/android-display/src/cn/ucvl/zhaodisplay/BootReceiver.java b/android-display/src/cn/ucvl/zhaodisplay/BootReceiver.java
new file mode 100644
index 0000000..f1f94b3
--- /dev/null
+++ b/android-display/src/cn/ucvl/zhaodisplay/BootReceiver.java
@@ -0,0 +1,8 @@
+package cn.ucvl.zhaodisplay;
+import android.content.*;
+public class BootReceiver extends BroadcastReceiver {
+ @Override public void onReceive(Context context,Intent intent){
+ if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) && !context.getSharedPreferences("display",0).getString("token","").isEmpty())
+ context.startForegroundService(new Intent(context,MonitorService.class));
+ }
+}
diff --git a/android-display/src/cn/ucvl/zhaodisplay/CameraStrip.java b/android-display/src/cn/ucvl/zhaodisplay/CameraStrip.java
new file mode 100644
index 0000000..bf14e00
--- /dev/null
+++ b/android-display/src/cn/ucvl/zhaodisplay/CameraStrip.java
@@ -0,0 +1,135 @@
+package cn.ucvl.zhaodisplay;
+
+import android.graphics.*;
+import android.media.MediaPlayer;
+import android.view.*;
+import android.widget.*;
+import android.os.Handler;
+import android.os.SystemClock;
+import android.util.TypedValue;
+import org.json.*;
+import java.net.*;
+import java.util.*;
+import java.util.concurrent.*;
+
+/** Direct LAN decoding. No video request is sent to the platform media server. */
+final class CameraStrip extends LinearLayout {
+ final MainActivity app;
+ final Handler ui=new Handler();
+ final ScheduledExecutorService worker=Executors.newSingleThreadScheduledExecutor();
+ final LinearLayout row;
+ final TextView title;
+ final List tiles=new ArrayList<>();
+ JSONArray cameras=new JSONArray();
+ String signature="";
+ int group=0;
+ boolean stopped=false, foreground=false;
+ long lease=0,lastRotation=0;
+ static volatile String report="[]";
+ CameraStrip(MainActivity a){
+ super(a);app=a;setOrientation(VERTICAL);setBackgroundColor(0xffe8e5db);
+ int pad=Math.max(12,a.getResources().getDisplayMetrics().widthPixels/50);
+ setPadding(pad,pad/3,pad,pad/3);
+ LinearLayout heading=new LinearLayout(a);heading.setGravity(Gravity.CENTER_VERTICAL);
+ title=text("家中画面 · 局域网直连",0xff57634e,.009f);
+ heading.addView(title,new LayoutParams(0,LayoutParams.WRAP_CONTENT,1));
+ TextView setting=text("绑定家庭 ⚙",0xff5f6f52,.009f);setting.setPadding(pad,0,pad,0);setting.setFocusable(true);setting.setOnClickListener(v->app.pairDialog());
+ heading.addView(setting);addView(heading);
+ row=new LinearLayout(a);row.setGravity(Gravity.CENTER);addView(row,new LayoutParams(-1,0,1));
+ worker.scheduleWithFixedDelay(this::fetch,0,60,TimeUnit.SECONDS);
+ ui.postDelayed(watch,5000);
+ }
+ TextView text(String content,int color,float ratio){TextView t=new TextView(app);t.setText(content);t.setTextColor(color);t.setTextSize(TypedValue.COMPLEX_UNIT_PX,Math.max(18,app.getResources().getDisplayMetrics().heightPixels*ratio));return t;}
+ void fetch(){
+ if(stopped)return;
+ String token=app.getSharedPreferences("display",0).getString("nativeToken","");
+ if(token.isEmpty()){ui.post(()->{clear();title.setText("家中画面 · 请先绑定家庭");});return;}
+ try{
+ JSONObject value=DisplayApi.call("/api/display/cameras",token,null);
+ JSONArray found=value.getJSONArray("items");String sig=found.toString();
+ ui.post(()->{if(stopped)return;lease=SystemClock.elapsedRealtime()+300000;title.setText("家中画面 · 局域网直连");if(!signature.equals(sig)){cameras=found;signature=sig;group=0;render();}});
+ }catch(DisplayApi.ApiError e){if(e.status==401||e.status==403)ui.post(()->{lease=0;clear();signature="";title.setText("展示授权已失效 · 请重新绑定家庭");});}
+ catch(Exception ignored){}
+ }
+ void refresh(){signature="";clear();if(!worker.isShutdown())worker.execute(this::fetch);}
+ void render(){
+ clear();if(!foreground||lease0&&lease3&&now-lastRotation>60000){group=(group+1)%((cameras.length()+2)/3);render();}
+ JSONArray states=new JSONArray();
+ for(Tile t:new ArrayList<>(tiles)){
+ if(t.player!=null&&now-t.lastFrame>20000)t.fail("画面中断 · 自动重连","offline");
+ try{states.put(new JSONObject().put("id",t.camera.optString("id")).put("state",t.state));}catch(Exception ignored){}
+ }
+ report=states.toString();ui.postDelayed(this,5000);
+ }};
+ static boolean sameNetwork(String host){
+ try{
+ if(!host.matches("[0-9.]+"))return false;
+ byte[] remote=InetAddress.getByName(host).getAddress();
+ if(remote.length!=4)return false;
+ for(NetworkInterface net:Collections.list(NetworkInterface.getNetworkInterfaces())){
+ if(!net.isUp()||net.isLoopback())continue;
+ for(InterfaceAddress local:net.getInterfaceAddresses()){
+ byte[] own=local.getAddress().getAddress();int prefix=local.getNetworkPrefixLength();
+ if(own.length!=4||prefix<=0||prefix>32)continue;
+ boolean match=true;for(int bit=0;bitconnect();
+ Tile(JSONObject c){super(app);camera=c;setBackgroundColor(0xff24322b);
+ texture=new TextureView(app);texture.setSurfaceTextureListener(this);addView(texture,new FrameLayout.LayoutParams(-1,-1));
+ curtain=new View(app);curtain.setBackgroundColor(0xff24322b);addView(curtain,new FrameLayout.LayoutParams(-1,-1));
+ label=text(camera.optString("name")+" · 正在直连",0xfffaf7eb,.009f);label.setPadding(16,4,12,4);label.setBackgroundColor(0xb0334237);
+ FrameLayout.LayoutParams p=new FrameLayout.LayoutParams(-1,-2,Gravity.BOTTOM);addView(label,p);
+ setFocusable(true);setOnClickListener(v->{failures=0;connect();});
+ }
+ void connect(){
+ if(closed||!foreground||surface==null||lease{if(player==mp&&!closed)mp.start();});
+ p.setOnVideoSizeChangedListener((mp,w,h)->fit(w,h));
+ p.setOnErrorListener((mp,what,extra)->{if(player==mp)fail(extra==-1010?"电视暂不支持此编码":"直连未成功 · 自动重试",extra==-1010?"unsupported":"offline");return true;});
+ p.setOnCompletionListener(mp->{if(player==mp)fail("画面中断 · 自动重连","offline");});
+ p.setDataSource(camera.getString("url"));p.prepareAsync();
+ }catch(Exception e){fail("直连未成功 · 自动重试","offline");}
+ }
+ void fit(int w,int h){if(w<=0||h<=0||texture.getWidth()==0||texture.getHeight()==0)return;float scale=Math.min((float)texture.getWidth()/w,(float)texture.getHeight()/h);Matrix matrix=new Matrix();matrix.setScale(w*scale/texture.getWidth(),h*scale/texture.getHeight(),texture.getWidth()/2f,texture.getHeight()/2f);texture.setTransform(matrix);}
+ void fail(String text,String value){if(closed)return;state=value;release();curtain.setVisibility(VISIBLE);visible=false;label.setText(camera.optString("name")+" · "+text);ui.removeCallbacks(retry);ui.postDelayed(retry,Math.min(60000,10000L*(++failures)));}
+ void release(){MediaPlayer old=player;player=null;if(old!=null){try{old.reset();old.release();}catch(Exception ignored){}}}
+ void close(){closed=true;ui.removeCallbacks(retry);release();if(surface!=null){surface.release();surface=null;}}
+ public void onSurfaceTextureAvailable(SurfaceTexture s,int w,int h){surface=new Surface(s);connect();}
+ public void onSurfaceTextureSizeChanged(SurfaceTexture s,int w,int h){if(player!=null)try{fit(player.getVideoWidth(),player.getVideoHeight());}catch(Exception ignored){}}
+ public boolean onSurfaceTextureDestroyed(SurfaceTexture s){release();if(surface!=null)surface.release();surface=null;return true;}
+ public void onSurfaceTextureUpdated(SurfaceTexture s){lastFrame=SystemClock.elapsedRealtime();if(player!=null&&!visible){visible=true;state="online";failures=0;curtain.setVisibility(GONE);label.setText(camera.optString("name")+" · 局域网直连");}}
+ }
+}
diff --git a/android-display/src/cn/ucvl/zhaodisplay/DisplayApi.java b/android-display/src/cn/ucvl/zhaodisplay/DisplayApi.java
new file mode 100644
index 0000000..fed8a23
--- /dev/null
+++ b/android-display/src/cn/ucvl/zhaodisplay/DisplayApi.java
@@ -0,0 +1,28 @@
+package cn.ucvl.zhaodisplay;
+
+import org.json.JSONObject;
+import java.net.URL;
+import java.io.*;
+import java.nio.charset.StandardCharsets;
+import javax.net.ssl.HttpsURLConnection;
+
+final class DisplayApi {
+ static JSONObject call(String path,String token,JSONObject body)throws Exception{
+ HttpsURLConnection c=(HttpsURLConnection)new URL("https://zhao.ucvl.cn"+path).openConnection();
+ c.setInstanceFollowRedirects(false);c.setConnectTimeout(10000);c.setReadTimeout(10000);
+ if(token!=null&&!token.isEmpty())c.setRequestProperty("Authorization","Bearer "+token);
+ try{
+ if(body!=null){
+ c.setRequestMethod("POST");c.setDoOutput(true);c.setRequestProperty("Content-Type","application/json");
+ byte[] bytes=body.toString().getBytes(StandardCharsets.UTF_8);c.setFixedLengthStreamingMode(bytes.length);
+ try(OutputStream out=c.getOutputStream()){out.write(bytes);}
+ }
+ int status=c.getResponseCode();
+ if(status!=200)throw new ApiError(status);
+ ByteArrayOutputStream out=new ByteArrayOutputStream();byte[] b=new byte[2048];
+ try(InputStream in=c.getInputStream()){int n;while((n=in.read(b))>=0){out.write(b,0,n);if(out.size()>262144)throw new IOException("Response too large");}}
+ return new JSONObject(out.toString("UTF-8"));
+ }finally{c.disconnect();}
+ }
+ static final class ApiError extends IOException {final int status;ApiError(int code){super("HTTP "+code);status=code;}}
+}
diff --git a/android-display/src/cn/ucvl/zhaodisplay/MainActivity.java b/android-display/src/cn/ucvl/zhaodisplay/MainActivity.java
new file mode 100644
index 0000000..b9e7bd0
--- /dev/null
+++ b/android-display/src/cn/ucvl/zhaodisplay/MainActivity.java
@@ -0,0 +1,96 @@
+package cn.ucvl.zhaodisplay;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.PixelCopy;
+import android.view.View;
+import android.view.WindowManager;
+import android.widget.LinearLayout;
+import android.widget.EditText;
+import android.widget.Toast;
+import android.text.InputType;
+import org.json.JSONObject;
+import android.webkit.WebView;
+import android.webkit.WebViewClient;
+import android.webkit.WebResourceRequest;
+import java.io.ByteArrayOutputStream;
+import java.util.function.Consumer;
+
+public class MainActivity extends Activity {
+ static volatile MainActivity active;
+ WebView web;
+ CameraStrip cameras;
+ @Override public void onCreate(Bundle state) {
+ super.onCreate(state);
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+ immersive();
+ web=new WebView(this);
+ web.setBackgroundColor(0xfff1ede4);
+ web.getSettings().setJavaScriptEnabled(true);
+ web.getSettings().setDomStorageEnabled(true);
+ web.getSettings().setAllowFileAccess(false);
+ web.getSettings().setAllowContentAccess(false);
+ web.getSettings().setMixedContentMode(0);
+ web.setWebViewClient(new WebViewClient(){
+ @Override public boolean shouldOverrideUrlLoading(WebView view,WebResourceRequest request){
+ return !"https".equals(request.getUrl().getScheme()) || !"zhao.ucvl.cn".equals(request.getUrl().getHost()) || !request.getUrl().getPath().startsWith("/tv");
+ }
+ });
+ LinearLayout layout=new LinearLayout(this);layout.setOrientation(LinearLayout.VERTICAL);
+ layout.addView(web,new LinearLayout.LayoutParams(-1,0,88));
+ cameras=new CameraStrip(this);layout.addView(cameras,new LinearLayout.LayoutParams(-1,0,12));
+ setContentView(layout);
+ configure(getIntent());
+ }
+ void configure(Intent intent){
+ String code=intent.getStringExtra("pairing_code");
+ if(code!=null&&code.matches("[0-9]{8}")){intent.removeExtra("pairing_code");pair(code);return;}
+ String token=getSharedPreferences("display",MODE_PRIVATE).getString("token","");
+ web.loadUrl("https://zhao.ucvl.cn/tv"+(token.isEmpty()?"":"#display="+token));
+ if(!token.isEmpty())startForegroundService(new Intent(this,MonitorService.class));
+ else pairDialog();
+ }
+ void pairDialog(){
+ EditText code=new EditText(this);code.setInputType(InputType.TYPE_CLASS_NUMBER);code.setHint("8 位家庭屏配对码");
+ code.setFilters(new android.text.InputFilter[]{new android.text.InputFilter.LengthFilter(8)});
+ new AlertDialog.Builder(this).setTitle("绑定家庭中心").setMessage("在赵府智家中进入目标家庭 → 电视设备 → 电视管理 → 生成配对码。更换家庭前,请先由管理员移动这台设备的归属。")
+ .setView(code).setNegativeButton("取消",null).setPositiveButton("绑定",(dialog,which)->pair(code.getText().toString().trim())).show();
+ }
+ void pair(String code){
+ if(!code.matches("[0-9]{8}")){Toast.makeText(this,"请输入 8 位配对码",Toast.LENGTH_LONG).show();return;}
+ new Thread(()->{
+ try{
+ JSONObject value=DisplayApi.call("/api/display/pair",null,new JSONObject().put("code",code));
+ getSharedPreferences("display",MODE_PRIVATE).edit().putString("token",value.getString("token")).putString("nativeToken",value.getString("nativeToken")).apply();
+ runOnUiThread(()->{configure(new Intent());cameras.refresh();Toast.makeText(this,"已绑定:"+value.optString("home"),Toast.LENGTH_LONG).show();});
+ }catch(Exception e){runOnUiThread(()->Toast.makeText(this,"绑定未成功,请检查网络或重新生成配对码",Toast.LENGTH_LONG).show());}
+ },"display-pair").start();
+ }
+ @Override public void onNewIntent(Intent intent){super.onNewIntent(intent);setIntent(intent);configure(intent);}
+ @Override public void onResume(){super.onResume();active=this;immersive();if(cameras!=null)cameras.foreground(true);}
+ @Override public void onPause(){if(active==this)active=null;if(cameras!=null)cameras.foreground(false);super.onPause();}
+ @Override public void onDestroy(){if(active==this)active=null;if(cameras!=null)cameras.close();web.destroy();super.onDestroy();}
+ @Override public void onWindowFocusChanged(boolean hasFocus){super.onWindowFocusChanged(hasFocus);if(hasFocus)immersive();}
+ void immersive(){getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN|View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_LAYOUT_STABLE|View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);}
+ static void capture(Consumer callback){
+ MainActivity a=active;
+ if(a==null){callback.accept(null);return;}
+ a.runOnUiThread(()->{
+ if(active!=a){callback.accept(null);return;}
+ try {
+ // PixelCopy captures this app's actual window, never other applications.
+ Bitmap image=Bitmap.createBitmap(a.getWindow().getDecorView().getWidth(),a.getWindow().getDecorView().getHeight(),Bitmap.Config.ARGB_8888);
+ PixelCopy.request(a.getWindow(),image,result->{
+ if(result!=PixelCopy.SUCCESS){image.recycle();callback.accept(null);return;}
+ Bitmap small=Bitmap.createScaledBitmap(image,480,Math.max(1,Math.round(480f*image.getHeight()/image.getWidth())),true);
+ ByteArrayOutputStream out=new ByteArrayOutputStream();small.compress(Bitmap.CompressFormat.JPEG,65,out);
+ small.recycle();image.recycle();callback.accept(out.toByteArray());
+ },new Handler(a.getMainLooper()));
+ }catch(Exception|OutOfMemoryError e){callback.accept(null);}
+ });
+ }
+}
diff --git a/android-display/src/cn/ucvl/zhaodisplay/MonitorService.java b/android-display/src/cn/ucvl/zhaodisplay/MonitorService.java
new file mode 100644
index 0000000..66a7be0
--- /dev/null
+++ b/android-display/src/cn/ucvl/zhaodisplay/MonitorService.java
@@ -0,0 +1,92 @@
+package cn.ucvl.zhaodisplay;
+
+import android.app.*;
+import android.content.*;
+import android.os.*;
+import android.util.Base64;
+import android.util.DisplayMetrics;
+import android.view.WindowManager;
+import org.json.JSONObject;
+import java.io.*;
+import java.net.*;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.*;
+import java.util.concurrent.*;
+import javax.net.ssl.HttpsURLConnection;
+
+public class MonitorService extends Service {
+ ScheduledExecutorService worker;
+ @Override public void onCreate(){
+ super.onCreate();
+ NotificationManager nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
+ nm.createNotificationChannel(new NotificationChannel("display","家庭屏运行状态",NotificationManager.IMPORTANCE_LOW));
+ PendingIntent open=PendingIntent.getActivity(this,0,new Intent(this,MainActivity.class),PendingIntent.FLAG_IMMUTABLE|PendingIntent.FLAG_UPDATE_CURRENT);
+ startForeground(44,new Notification.Builder(this,"display").setContentTitle("赵府家庭屏")
+ .setContentText("家庭设备状态同步中 · 预览仅限当前看板画面").setSmallIcon(android.R.drawable.ic_menu_view).setContentIntent(open).setOngoing(true).build());
+ worker=Executors.newSingleThreadScheduledExecutor();
+ worker.scheduleWithFixedDelay(this::heartbeat,1,20,TimeUnit.SECONDS);
+ }
+ @Override public int onStartCommand(Intent intent,int flags,int startId){return START_STICKY;}
+ @Override public IBinder onBind(Intent intent){return null;}
+ @Override public void onDestroy(){if(worker!=null)worker.shutdownNow();super.onDestroy();}
+ JSONObject hardware()throws Exception{
+ JSONObject result=new JSONObject();
+ result.put("model",Build.MODEL);result.put("osVersion",Build.VERSION.RELEASE);result.put("appVersion","0.1.44");
+ result.put("foreground",MainActivity.active!=null);
+ result.put("cameraStates",new org.json.JSONArray(CameraStrip.report));
+ result.put("screenOn",((PowerManager)getSystemService(POWER_SERVICE)).isInteractive());
+ ActivityManager.MemoryInfo memory=new ActivityManager.MemoryInfo();((ActivityManager)getSystemService(ACTIVITY_SERVICE)).getMemoryInfo(memory);
+ result.put("memoryTotalMB",memory.totalMem/1048576d);result.put("memoryAvailableMB",memory.availMem/1048576d);
+ StatFs disk=new StatFs(getFilesDir().getAbsolutePath());
+ result.put("storageTotalGB",disk.getTotalBytes()/1073741824d);result.put("storageAvailableGB",disk.getAvailableBytes()/1073741824d);
+ result.put("uptimeSeconds",SystemClock.elapsedRealtime()/1000);
+ DisplayMetrics metrics=new DisplayMetrics();WindowManager wm=(WindowManager)getSystemService(WINDOW_SERVICE);wm.getDefaultDisplay().getRealMetrics(metrics);
+ result.put("screenWidth",metrics.widthPixels);result.put("screenHeight",metrics.heightPixels);result.put("rotation",wm.getDefaultDisplay().getRotation());
+ double hottest=-999;String source="系统未开放传感器";
+ File[] zones=new File("/sys/class/thermal").listFiles();
+ if(zones!=null)for(File zone:zones){
+ if(!zone.getName().startsWith("thermal_zone"))continue;
+ try{
+ String type=new String(Files.readAllBytes(new File(zone,"type").toPath()),StandardCharsets.UTF_8).trim();
+ if(!type.matches("(?i).*(soc|cpu|gpu).*"))continue;
+ double value=Double.parseDouble(new String(Files.readAllBytes(new File(zone,"temp").toPath()),StandardCharsets.UTF_8).trim())/1000d;
+ if(value>0 && value<150 && value>hottest){hottest=value;source=type;}
+ }catch(Exception ignored){}
+ }
+ result.put("temperatureC",hottest>-999?hottest:JSONObject.NULL);result.put("temperatureSource",source);
+ // This board exposes test_battery/test_ac; these are not power meters.
+ result.put("powerW",JSONObject.NULL);result.put("powerSource","未提供整机功率传感器,需接入计量插座");
+ String ip="";
+ for(NetworkInterface net:Collections.list(NetworkInterface.getNetworkInterfaces())){
+ if(!net.isUp()||net.isLoopback())continue;
+ for(InetAddress addr:Collections.list(net.getInetAddresses()))if(addr instanceof Inet4Address && addr.isSiteLocalAddress())ip=addr.getHostAddress();
+ }
+ result.put("ip",ip);return result;
+ }
+ JSONObject post(String path,JSONObject body)throws Exception{
+ String token=getSharedPreferences("display",MODE_PRIVATE).getString("token","");
+ if(token.isEmpty())throw new IOException("Not paired");
+ HttpsURLConnection c=(HttpsURLConnection)new URL("https://zhao.ucvl.cn"+path).openConnection();
+ c.setInstanceFollowRedirects(false);c.setConnectTimeout(10000);c.setReadTimeout(10000);c.setRequestMethod("POST");c.setDoOutput(true);
+ c.setRequestProperty("Authorization","Bearer "+token);c.setRequestProperty("Content-Type","application/json");
+ byte[] bytes=body.toString().getBytes(StandardCharsets.UTF_8);c.setFixedLengthStreamingMode(bytes.length);
+ try{
+ try(OutputStream out=c.getOutputStream()){out.write(bytes);}
+ if(c.getResponseCode()!=200)throw new IOException("HTTP "+c.getResponseCode());
+ ByteArrayOutputStream out=new ByteArrayOutputStream();byte[] b=new byte[1024];
+ try(InputStream in=c.getInputStream()){int n;while((n=in.read(b))>=0){out.write(b,0,n);if(out.size()>65536)throw new IOException("Response too large");}}
+ return new JSONObject(out.toString("UTF-8"));
+ }finally{c.disconnect();}
+ }
+ void heartbeat(){
+ try{
+ JSONObject response=post("/api/display/heartbeat",hardware());
+ if(response.optBoolean("capturePreview"))MainActivity.capture(bytes->{
+ if(bytes!=null && bytes.length<180000 && !worker.isShutdown())worker.execute(()->{
+ try{post("/api/display/preview",new JSONObject().put("jpeg",Base64.encodeToString(bytes,Base64.NO_WRAP)));}catch(Exception ignored){}
+ });
+ });
+ }catch(Exception ignored){}
+ }
+}
diff --git a/app.py b/app.py
index 6d76546..18008e4 100644
--- a/app.py
+++ b/app.py
@@ -42,6 +42,7 @@ import backups
import baidu
import journal
import ptz
+import displays
ROOT = Path(__file__).resolve().parent
os.umask(0o077)
@@ -93,6 +94,7 @@ BACKUPS = backups.Backups(sys.modules[__name__])
BAIDU = baidu.Baidu(sys.modules[__name__])
JOURNAL = journal.Journal(sys.modules[__name__])
CLOUD_IMAGES = cloud_images.CloudImages(sys.modules[__name__])
+DISPLAYS = displays.Displays(sys.modules[__name__])
def setting(key, default=None):
@@ -665,6 +667,12 @@ class Handler(BaseHTTPRequestHandler):
def do_POST(self):
try:
path = url.urlsplit(self.path).path
+ if path in ('/api/display/heartbeat','/api/display/preview'):
+ authorization = self.headers.get('Authorization','')
+ grant = DISPLAYS.authorize(authorization[7:] if authorization.startswith('Bearer ') else '')
+ data = self.body(250000 if path.endswith('preview') else 16384)
+ self.answer(DISPLAYS.accept_preview(grant,data) if path.endswith('preview') else DISPLAYS.heartbeat(grant,data))
+ return
if path == '/api/journal/chunk':
self.validate_origin(); self.require_auth()
query = dict(url.parse_qsl(url.urlsplit(self.path).query))
@@ -680,6 +688,9 @@ class Handler(BaseHTTPRequestHandler):
# 12,000 Chinese characters plus JSON escapes and linked people exceed 16 KiB.
data = self.body(3*1024*1024 if path in ('/api/appearance','/api/households') else 131072 if path in ('/api/family/event','/api/heritage','/api/journal') else 16384)
self.validate_origin()
+ if path == '/api/display/pair':
+ self.answer(DISPLAYS.pair(data, self.client_address[0]))
+ return
if path in ('/api/login', '/api/setup'):
self.login(data, path == '/api/setup')
return
@@ -775,6 +786,10 @@ class Handler(BaseHTTPRequestHandler):
self.answer(HERITAGE.save(data, self.user))
elif path == '/api/devices':
self.answer(INVENTORY.save(data, self.user))
+ elif path == '/api/devices/transfer':
+ self.answer(INVENTORY.transfer(data, self.user))
+ elif path == '/api/displays':
+ self.answer(DISPLAYS.manage(self.user, data))
elif path in ('/api/family/person', '/api/family/link', '/api/family/event'):
self.answer(FAMILY.save(path.rsplit('/', 1)[-1], data, self.user))
elif path == '/api/sites':
@@ -947,12 +962,33 @@ class Handler(BaseHTTPRequestHandler):
if path == '/healthz':
self.answer({'status': 'running', 'version': (ROOT / 'VERSION').read_text().strip()})
return
+ if path in ('/api/display/snapshot', '/api/display/cameras'):
+ authorization = self.headers.get('Authorization', '')
+ token = authorization[7:] if authorization.startswith('Bearer ') else ''
+ if path.endswith('/cameras'):
+ self.answer(DISPLAYS.cameras(DISPLAYS.authorize_native(token)))
+ else:
+ self.answer(DISPLAYS.snapshot(DISPLAYS.authorize(token)))
+ return
if path.startswith(('/api/', '/media/')):
self.require_auth()
if path == '/api/state':
self.answer(ACCOUNTS.state(self.user, status()))
elif path == '/api/devices/network':
self.require_manager(); self.answer(NETWORK.read(self.user, query))
+ elif path == '/api/displays':
+ self.require_manager(); self.answer(DISPLAYS.listing(self.user, query.get('deviceId')))
+ elif path == '/api/displays/hardware':
+ self.require_manager(); self.answer(DISPLAYS.hardware(self.user, query.get('deviceId')))
+ elif path == '/api/displays/preview':
+ self.require_manager()
+ at, raw = DISPLAYS.preview(self.user, query.get('deviceId'))
+ self.send_response(200)
+ self.send_header('Content-Type','image/jpeg')
+ self.send_header('Content-Length',str(len(raw)))
+ self.send_header('Cache-Control','no-store')
+ self.send_header('X-Content-Type-Options','nosniff')
+ self.end_headers(); self.wfile.write(raw)
elif path == '/api/baidu/config':
self.require_admin(); self.answer(BAIDU.public_config())
elif path == '/api/baidu/status':
@@ -1100,8 +1136,10 @@ class Handler(BaseHTTPRequestHandler):
'/monitor.js': 'monitor.js', '/calendar.js': 'calendar.js', '/date-fields.js': 'date-fields.js',
'/zhao-icon.png': 'zhao-icon.png',
'/vendor/hls.min.js': 'vendor/hls.min.js'}
- if re.fullmatch(r'/ui/assets/[A-Za-z0-9_-]+\.(?:js|css)', path):
+ if re.fullmatch(r'/ui/assets/[A-Za-z0-9_.-]+\.(?:js|css)', path):
files[path] = path[1:]
+ if path in ('/tv', '/tv/'):
+ files[path] = 'ui/tv.html'
if path not in files or not (ROOT / 'web' / files[path]).is_file():
raise Problem('页面不存在', 404)
file = ROOT / 'web' / files[path]
@@ -1131,6 +1169,7 @@ def initialize():
FAMILY.initialize()
ACCOUNTS.initialize()
HOUSEHOLDS.initialize()
+ DISPLAYS.initialize()
HERITAGE.initialize()
JOURNAL.initialize()
if not setting('storage'):
@@ -1149,6 +1188,7 @@ if __name__ == '__main__':
threading.Thread(target=storage_watch, daemon=True).start()
threading.Thread(target=media_config_watch, daemon=True).start()
threading.Thread(target=BACKUPS.watch, daemon=True).start()
+ threading.Thread(target=DISPLAYS.watch, daemon=True).start()
bindings = [h.strip() for h in os.environ.get('VISION_BIND', '127.0.0.1').split(',') if h.strip()]
port = int(os.environ.get('VISION_PORT', '8790'))
servers = []
diff --git a/displays.py b/displays.py
new file mode 100644
index 0000000..19559fd
--- /dev/null
+++ b/displays.py
@@ -0,0 +1,341 @@
+"""Household display grants: revocable, read-only and bound to one registered TV."""
+import datetime as dt
+import hashlib
+import json
+import math
+import re
+import secrets
+import threading
+import time
+import urllib.parse
+import urllib.request
+import base64
+import ipaddress
+
+TZ = dt.timezone(dt.timedelta(hours=8))
+
+
+class Displays:
+ def __init__(self, app):
+ self.a = app
+ self.weather_cache = {}
+ self.weather_lock = threading.Lock()
+ self.weather_pending = set()
+ self.state_cache = (0, {})
+ self.state_lock = threading.Lock()
+ self.previews = {}
+ self.preview_requests = {}
+ self.pair_codes = {}
+ self.pair_attempts = {}
+
+ def initialize(self):
+ with self.a.LOCK, self.a.DB:
+ self.a.DB.execute('CREATE TABLE IF NOT EXISTS household_displays '
+ '(id TEXT PRIMARY KEY, family_id TEXT NOT NULL, device_id TEXT NOT NULL, '
+ 'token_hash TEXT UNIQUE NOT NULL, created_at REAL, expires_at REAL, '
+ 'last_seen REAL DEFAULT 0, revoked INTEGER DEFAULT 0, weather TEXT NOT NULL)')
+ self.a.DB.execute('CREATE TABLE IF NOT EXISTS display_telemetry (id TEXT PRIMARY KEY, at REAL, body TEXT NOT NULL)')
+ self.a.DB.execute('CREATE TABLE IF NOT EXISTS display_alerts (id INTEGER PRIMARY KEY, display_id TEXT, '
+ 'code TEXT, message TEXT, severity TEXT, opened REAL, cleared REAL DEFAULT 0)')
+ self.a.DB.execute('CREATE TABLE IF NOT EXISTS display_native_keys (id TEXT PRIMARY KEY, token_hash TEXT UNIQUE NOT NULL)')
+
+ def device(self, user, device_id):
+ if not self.a.HOUSEHOLDS.manager(user):
+ raise self.a.Problem('需要家庭管理员权限', 403)
+ device = self.a.HOUSEHOLDS.owns(user, self.a.get_object('devices', device_id))
+ if not re.search('电视|显示|大屏', device.get('deviceType', '')):
+ raise self.a.Problem('请先登记电视或显示屏设备')
+ return device
+
+ def listing(self, user, device_id):
+ self.device(user, device_id)
+ with self.a.LOCK:
+ rows = self.a.DB.execute('SELECT id,created_at,expires_at,last_seen,revoked FROM household_displays '
+ 'WHERE device_id=? AND family_id=? ORDER BY created_at DESC LIMIT 20',
+ (device_id, self.a.HOUSEHOLDS.scope(user))).fetchall()
+ return {'items': [dict(r) for r in rows]}
+
+ def manage(self, user, data):
+ a = self.a
+ device = self.device(user, data.get('deviceId'))
+ family = a.HOUSEHOLDS.scope(user)
+ if data.get('action') == 'preview':
+ with a.LOCK:
+ row = a.DB.execute('SELECT id FROM household_displays WHERE device_id=? AND family_id=? AND revoked=0 AND expires_at>?',
+ (device['id'], family, time.time())).fetchone()
+ if not row: raise a.Problem('电视尚未授权', 404)
+ self.preview_requests[row['id']] = time.time()+65
+ return {'ok': True, 'expiresIn': 65}
+ if data.get('action') == 'revoke':
+ with a.LOCK, a.DB:
+ result = a.DB.execute('UPDATE household_displays SET revoked=1 WHERE id=? AND device_id=? AND family_id=?',
+ (data.get('id'), device['id'], family))
+ if not result.rowcount: raise a.Problem('展示授权不存在', 404)
+ a.audit('停用电视展示', device['name'])
+ return {'ok': True}
+ if data.get('action') != 'create': raise a.Problem('展示操作不正确')
+ city = a.clean_text(data.get('city', ''), 60)
+ weather = {'city': city}
+ if data.get('latitude') not in ('', None) or data.get('longitude') not in ('', None):
+ try:
+ lat, lon = float(data['latitude']), float(data['longitude'])
+ if not math.isfinite(lat+lon) or not -90 <= lat <= 90 or not -180 <= lon <= 180: raise ValueError()
+ except (ValueError, TypeError, KeyError): raise a.Problem('天气经纬度不正确')
+ weather.update(latitude=round(lat, 4), longitude=round(lon, 4))
+ token, key, now = secrets.token_urlsafe(32), secrets.token_hex(8), time.time()
+ with a.LOCK, a.DB:
+ # Replacing the grant invalidates the old TV link immediately.
+ a.DB.execute('UPDATE household_displays SET revoked=1 WHERE device_id=? AND family_id=?', (device['id'], family))
+ a.DB.execute('INSERT INTO household_displays VALUES (?,?,?,?,?,?,0,0,?)',
+ (key, family, device['id'], hashlib.sha256(token.encode()).hexdigest(), now,
+ now+365*86400, json.dumps(weather)))
+ a.audit('授权家庭电视展示', device['name'])
+ code = f'{secrets.randbelow(100000000):08d}'
+ with a.LOCK:
+ self.pair_codes = {k:v for k,v in self.pair_codes.items() if v['expires']>now}
+ if len(self.pair_codes)>=128: self.pair_codes.pop(next(iter(self.pair_codes)))
+ self.pair_codes[hashlib.sha256(code.encode()).hexdigest()] = dict(id=key,token=token,expires=now+600)
+ return {'id': key, 'token': token, 'expiresAt': now+365*86400, 'path': '/tv#display='+token,
+ 'pairingCode':code,'pairingExpiresAt':now+600}
+
+ def pair(self, body, ip):
+ now = time.time()
+ code = body.get('code','')
+ with self.a.LOCK:
+ self.pair_attempts = {k:v for k,v in self.pair_attempts.items() if v[1]>now}
+ count, until = self.pair_attempts.get(ip,(0,now+600))
+ if count>=5: raise self.a.Problem('配对尝试过多,请 10 分钟后再试',429)
+ self.pair_attempts[ip]=(count+1,until)
+ if not isinstance(code,str) or not re.fullmatch('[0-9]{8}',code): raise self.a.Problem('请输入 8 位配对码')
+ key=hashlib.sha256(code.encode()).hexdigest()
+ item=self.pair_codes.get(key)
+ if not item or item['expires']?',
+ (hashlib.sha256(token.encode()).hexdigest(),time.time())).fetchone()
+ if not row: raise self.a.Problem('App 授权已失效',401)
+ grant=dict(row)
+ device=self.a.get_object('devices',grant['device_id'])
+ if not device or self.a.HOUSEHOLDS.family_of(device)!=grant['family_id']: raise self.a.Problem('设备归属已更改',403)
+ return grant
+
+ def cameras(self, grant):
+ # Scoped credentials travel only over TLS to the paired native player, never to the WebView.
+ items=[]
+ nets=[ipaddress.ip_network(n) for n in ('10.0.0.0/8','172.16.0.0/12','192.168.0.0/16','100.64.0.0/10')]
+ for c in self.a.objects('cameras'):
+ if self.a.HOUSEHOLDS.family_of(c)!=grant['family_id'] or not c.get('enabled',True): continue
+ endpoint=self.a.get_object('recorders',c.get('recorderId')) if c.get('sourceKind')=='recorder' else c
+ if not endpoint or self.a.HOUSEHOLDS.family_of(endpoint)!=grant['family_id']: continue
+ try: address=ipaddress.ip_address(endpoint.get('host',''))
+ except ValueError: continue
+ if not any(address in net for net in nets): continue
+ items.append(dict(id=c['id'],name=c['name'],host=str(address),url=self.a.source(c,'sub')))
+ return dict(items=items,transport='direct',leaseSeconds=300)
+
+ def heartbeat(self, grant, body):
+ """Only typed, bounded telemetry; never accept a caller-selected device or household."""
+ a, key, now = self.a, grant['id'], time.time()
+ allowed_numbers = {'memoryTotalMB':(1,1048576), 'memoryAvailableMB':(0,1048576),
+ 'storageTotalGB':(0,1048576), 'storageAvailableGB':(0,1048576),
+ 'uptimeSeconds':(0,1e10), 'temperatureC':(-30,150), 'powerW':(0,10000),
+ 'screenWidth':(1,16384), 'screenHeight':(1,16384), 'rotation':(0,3)}
+ clean = {}
+ for name,(lo,hi) in allowed_numbers.items():
+ value = body.get(name)
+ if value is None: clean[name] = None
+ elif type(value) not in (int,float) or not math.isfinite(value) or not lo <= value <= hi:
+ raise a.Problem('硬件数据格式不正确:'+name)
+ else: clean[name] = value
+ for name in ('model','osVersion','appVersion','temperatureSource','powerSource','ip'):
+ clean[name] = a.clean_text(body.get(name,''),120)
+ clean['foreground'] = body.get('foreground') is True
+ clean['screenOn'] = body.get('screenOn') is True
+ clean['cameraStates'] = []
+ if body.get('cameraStates') is not None and not isinstance(body['cameraStates'],list): raise a.Problem('镜头状态格式不正确')
+ for item in (body.get('cameraStates') or [])[:32]:
+ if isinstance(item,dict) and re.fullmatch('[a-f0-9]{16}',str(item.get('id',''))) and item.get('state') in ('online','connecting','offline','outside_lan','unsupported'):
+ clean['cameraStates'].append(dict(id=item['id'],state=item['state']))
+ with a.LOCK, a.DB:
+ old = a.DB.execute('SELECT at FROM display_telemetry WHERE id=?', (key,)).fetchone()
+ if old and now-old['at'] < 5: raise a.Problem('心跳过于频繁',429)
+ a.DB.execute('INSERT OR REPLACE INTO display_telemetry VALUES (?,?,?)',(key,now,json.dumps(clean)))
+ self.alerts_for(key, now, clean, now)
+ return {'ok':True, 'capturePreview': self.preview_requests.get(key,0) > now}
+
+ def accept_preview(self, grant, body):
+ key, now = grant['id'], time.time()
+ if self.preview_requests.get(key,0) < now: raise self.a.Problem('未请求屏幕预览',403)
+ encoded = body.get('jpeg','')
+ if not isinstance(encoded,str) or len(encoded)>240000: raise self.a.Problem('预览图片过大')
+ try: raw = base64.b64decode(encoded,validate=True)
+ except Exception: raise self.a.Problem('预览图片不正确')
+ if not raw.startswith(b'\xff\xd8\xff') or not raw.endswith(b'\xff\xd9'): raise self.a.Problem('需要 JPEG 预览')
+ with self.a.LOCK:
+ self.previews = {k:v for k,v in self.previews.items() if now-v[0]<90}
+ if len(self.previews)>=32: self.previews.pop(next(iter(self.previews)))
+ self.previews[key] = (now,raw)
+ return {'ok':True}
+
+ def preview(self,user,device_id):
+ self.device(user,device_id)
+ with self.a.LOCK:
+ row=self.a.DB.execute('SELECT id FROM household_displays WHERE device_id=? AND family_id=? AND revoked=0 AND expires_at>?',
+ (device_id,self.a.HOUSEHOLDS.scope(user),time.time())).fetchone()
+ value=self.previews.get(row['id']) if row else None
+ if not value or time.time()-value[0]>90: raise self.a.Problem('等待电视回传当前应用画面',404)
+ return value
+
+ def alerts_for(self,key,at,body,now):
+ wanted = {}
+ if now-at > 100: wanted['offline'] = ('电视心跳中断','warning')
+ else:
+ temp=body.get('temperatureC')
+ if temp is not None and temp >= 75: wanted['temperature'] = ('处理器温度偏高(阈值 75°C)','critical' if temp>=85 else 'warning')
+ total, available=body.get('memoryTotalMB'),body.get('memoryAvailableMB')
+ if total and available is not None and available/total<.05: wanted['memory']=('可用内存不足 5%','warning')
+ free=body.get('storageAvailableGB')
+ if free is not None and free < .5: wanted['storage']=('可用存储不足 0.5 GB','warning')
+ if not body.get('foreground'): wanted['background']=('家庭看板当前不在前台','warning')
+ current={r['code']:r for r in self.a.DB.execute('SELECT * FROM display_alerts WHERE display_id=? AND cleared=0',(key,))}
+ for code,(message,severity) in wanted.items():
+ if code not in current:
+ self.a.DB.execute('INSERT INTO display_alerts(display_id,code,message,severity,opened) VALUES (?,?,?,?,?)',
+ (key,code,message,severity,now))
+ else: self.a.DB.execute('UPDATE display_alerts SET severity=? WHERE id=?',(severity,current[code]['id']))
+ for code,row in current.items():
+ if code not in wanted: self.a.DB.execute('UPDATE display_alerts SET cleared=? WHERE id=?',(now,row['id']))
+ self.a.DB.execute('DELETE FROM display_alerts WHERE display_id=? AND cleared>0 AND id NOT IN '
+ '(SELECT id FROM display_alerts WHERE display_id=? ORDER BY id DESC LIMIT 200)',(key,key))
+
+ def watch(self):
+ while True:
+ try:
+ with self.a.LOCK,self.a.DB:
+ rows=self.a.DB.execute('SELECT t.* FROM display_telemetry t JOIN household_displays d ON d.id=t.id '
+ 'WHERE d.revoked=0 AND d.expires_at>?',(time.time(),)).fetchall()
+ for row in rows:self.alerts_for(row['id'],row['at'],json.loads(row['body']),time.time())
+ except Exception: pass
+ time.sleep(20)
+
+ def hardware(self,user,device_id):
+ self.device(user,device_id)
+ with self.a.LOCK:
+ row=self.a.DB.execute('SELECT d.id,t.at,t.body FROM household_displays d LEFT JOIN display_telemetry t ON d.id=t.id '
+ 'WHERE d.device_id=? AND d.family_id=? AND d.revoked=0 AND d.expires_at>? ORDER BY d.created_at DESC LIMIT 1',
+ (device_id,self.a.HOUSEHOLDS.scope(user),time.time())).fetchone()
+ if not row:return {'paired':False,'online':False,'alerts':[]}
+ alerts=[dict(r) for r in self.a.DB.execute('SELECT code,message,severity,opened,cleared FROM display_alerts WHERE display_id=? ORDER BY id DESC LIMIT 30',(row['id'],))]
+ preview=self.previews.get(row['id'])
+ return dict(paired=True,online=bool(row['at'] and time.time()-row['at']<100),lastSeen=row['at'],
+ hardware=json.loads(row['body']) if row['body'] else {},alerts=alerts,
+ previewAt=preview[0] if preview and time.time()-preview[0]<90 else None)
+
+ def authorize(self, token):
+ if not isinstance(token, str) or not re.fullmatch('[A-Za-z0-9_-]{43}', token):
+ raise self.a.Problem('请在设备页生成电视展示链接', 401)
+ a, now = self.a, time.time()
+ with a.LOCK:
+ row = a.DB.execute('SELECT * FROM household_displays WHERE token_hash=? AND revoked=0 AND expires_at>?',
+ (hashlib.sha256(token.encode()).hexdigest(), now)).fetchone()
+ if not row: raise a.Problem('展示授权已失效,请联系家庭管理员重新连接', 401)
+ grant = dict(row)
+ device = a.get_object('devices', grant['device_id'])
+ if not device or a.HOUSEHOLDS.family_of(device) != grant['family_id']:
+ raise a.Problem('电视已移出原家庭,请重新授权', 403)
+ if now-grant['last_seen'] > 60:
+ a.DB.execute('UPDATE household_displays SET last_seen=? WHERE id=?', (now, grant['id']))
+ a.DB.commit()
+ return grant
+
+ def weather(self, location):
+ if 'latitude' not in location:
+ return {'available': False, 'city': location.get('city', ''), 'message': '天气位置未设置'}
+ key = (location['latitude'], location['longitude'])
+ now = time.time()
+ with self.weather_lock:
+ cached = self.weather_cache.get(key, {})
+ if now-cached.get('attemptAt', 0) > 900 and key not in self.weather_pending:
+ self.weather_pending.add(key)
+ threading.Thread(target=self.fetch_weather, args=(key,), daemon=True).start()
+ if cached.get('data') and now-cached.get('at', 0) < 6*3600:
+ return dict(cached['data'], available=True, stale=now-cached['at'] > 1800,
+ updatedAt=cached['at'], city=location.get('city', ''), source='Open-Meteo')
+ return {'available': False, 'city': location.get('city', ''), 'message': '天气正在更新' if not cached else '天气暂时不可用'}
+
+ def fetch_weather(self, key):
+ now = time.time()
+ try:
+ query = urllib.parse.urlencode(dict(latitude=key[0], longitude=key[1], timezone='Asia/Shanghai',
+ current='temperature_2m,relative_humidity_2m,apparent_temperature,weather_code,wind_speed_10m,is_day',
+ daily='temperature_2m_max,temperature_2m_min,weather_code', forecast_days=3))
+ with urllib.request.urlopen('https://api.open-meteo.com/v1/forecast?'+query, timeout=8) as response:
+ value = json.loads(response.read(100000))
+ current, daily = value['current'], value['daily']
+ if not isinstance(current.get('temperature_2m'), (int, float)): raise ValueError()
+ data = dict(current={k: current.get(k) for k in ('time','temperature_2m','relative_humidity_2m',
+ 'apparent_temperature','weather_code','wind_speed_10m','is_day')},
+ days=[dict(date=d, high=daily['temperature_2m_max'][i], low=daily['temperature_2m_min'][i],
+ code=daily['weather_code'][i]) for i,d in enumerate(daily['time'][:3])])
+ with self.weather_lock:
+ if len(self.weather_cache) >= 128: self.weather_cache.pop(next(iter(self.weather_cache)))
+ self.weather_cache[key] = {'data': data, 'at': now, 'attemptAt': now}
+ except Exception:
+ with self.weather_lock:
+ self.weather_cache[key] = {**self.weather_cache.get(key, {}), 'attemptAt': now}
+ finally:
+ with self.weather_lock: self.weather_pending.discard(key)
+
+ def media_state(self):
+ with self.state_lock:
+ if time.monotonic()-self.state_cache[0] > 20:
+ self.state_cache = (time.monotonic(), self.a.status())
+ return self.state_cache[1]
+
+ def snapshot(self, grant):
+ a, family = self.a, grant['family_id']
+ home = a.get_object('households', family)
+ if not home: raise a.Problem('家庭已不可用', 404)
+ def scoped(table): return [x for x in a.objects(table) if a.HOUSEHOLDS.family_of(x) == family]
+ sites = {x['id']: x['name'] for x in scoped('sites')}
+ state = self.media_state()
+ channels = [c for c in state.get('cameras', []) if a.HOUSEHOLDS.family_of(c) == family]
+ devices = []
+ with a.LOCK:
+ displays = {r['device_id']: r['last_seen'] for r in a.DB.execute(
+ 'SELECT device_id,last_seen FROM household_displays WHERE family_id=? AND revoked=0 AND expires_at>?', (family,time.time()))}
+ for table, kind in (('assets','摄像机'), ('devices','设备'), ('recorders','录像机')):
+ for item in scoped(table):
+ label, condition = '状态未接入', 'unknown'
+ matched = [c for c in channels if c.get('assetId') == item['id'] or c.get('recorderId') == item['id']]
+ if matched:
+ if not state.get('mediaOnline'): label = '视频服务未连接'
+ elif any(c.get('ready') for c in matched): label, condition = '画面已连接', 'online'
+ else: label, condition = '画面未连接', 'offline'
+ elif item['id'] in displays:
+ condition = 'online' if time.time()-displays[item['id']] < 100 else 'offline'
+ label = '正在展示' if condition == 'online' else '展示未连接'
+ devices.append(dict(id=item['id'],name=item['name'],type=item.get('deviceType',kind),
+ location=sites.get(item.get('siteId'), '位置待设置'),status=condition,statusLabel=label))
+ today = dt.datetime.now(TZ).date()
+ until = (today+dt.timedelta(days=60)).isoformat()
+ events = sorted([dict(id=e['id'],title=e['title'],date=e['eventDate']) for e in scoped('family_events')
+ if e.get('status') == 'published' and not e.get('archived')
+ and today.isoformat() <= e.get('eventDate','') <= until], key=lambda e:(e['date'],e['id']))
+ return dict(serverTime=dt.datetime.now(dt.timezone.utc).isoformat(), timezone='Asia/Shanghai',
+ home=dict(name=home['name'],city=home.get('city',''),district=home.get('district',''),
+ spaces=len(sites),deviceCount=len(devices)),
+ display=dict(id=grant['id'],deviceId=grant['device_id']),devices=devices,
+ events=events[:12],eventCount=len(events),weather=self.weather(json.loads(grant['weather'])))
diff --git a/frontend/package.json b/frontend/package.json
index 08e2cd2..b2e4ee2 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,7 +1,7 @@
{
"name": "zhao-steward-ui",
"private": true,
- "version": "0.1.43",
+ "version": "0.1.44",
"type": "module",
"scripts": {
"build": "vite build",
diff --git a/frontend/src/compat/load.js b/frontend/src/compat/load.js
index 5acf4e1..5ce5d00 100644
--- a/frontend/src/compat/load.js
+++ b/frontend/src/compat/load.js
@@ -15,6 +15,6 @@ export function enhance(root){
export async function loadControllers(){
enhance(document.getElementById('app'))
new MutationObserver(records=>{for(const record of records)for(const node of record.addedNodes)enhance(node)}).observe(document.getElementById('app'),{childList:true,subtree:true})
- for(const path of [...scripts,'/vue-bridge.js'])await new Promise((resolve,reject)=>{const script=document.createElement('script');script.src=path+'?ui=0.1.43';script.onload=resolve;script.onerror=()=>reject(new Error('Could not load '+path));document.head.append(script)})
+ for(const path of [...scripts,'/vue-bridge.js'])await new Promise((resolve,reject)=>{const script=document.createElement('script');script.src=path+'?ui=0.1.44';script.onload=resolve;script.onerror=()=>reject(new Error('Could not load '+path));document.head.append(script)})
await window.ZhaoVue.boot()
}
diff --git a/frontend/src/components/DeviceCollection.vue b/frontend/src/components/DeviceCollection.vue
index 10a234c..ea381cd 100644
--- a/frontend/src/components/DeviceCollection.vue
+++ b/frontend/src/components/DeviceCollection.vue
@@ -7,6 +7,8 @@ import {
} from "../composables/bridge.js";
import AppIcon from "./AppIcon.vue";
import NetworkStatus from "./NetworkStatus.vue";
+import DisplayManager from './DisplayManager.vue';
+import DeviceTransfer from './DeviceTransfer.vue';
const channels = (d) =>
(snapshot.value.state.cameras || []).filter((c) =>
d.source === "camera"
@@ -118,6 +120,8 @@ const monitored = (d) =>
snapshot.page === 'objects' && deviceView.mode === 'cards'
"
/>
+
+