feat: household TV companion with scoped pairing and direct LAN camera strip

This commit is contained in:
Codex
2026-10-16 00:35:17 +08:00
parent fb87ae4de9
commit 6aa20391b2
42 changed files with 1153 additions and 33 deletions
@@ -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));
}
}
@@ -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<Tile> 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||lease<SystemClock.elapsedRealtime())return;
if(cameras.length()==0){row.addView(text("本家庭还没有接入摄像头",0xff888471,.011f));return;}
int start=group*3;
for(int i=start;i<Math.min(start+3,cameras.length());i++){
JSONObject camera=cameras.optJSONObject(i);if(camera==null)continue;
Tile t=new Tile(camera);tiles.add(t);
LayoutParams p=new LayoutParams(0,-1,1);p.setMargins(8,4,8,0);row.addView(t,p);
}
lastRotation=SystemClock.elapsedRealtime();
}
void clear(){for(Tile t:tiles)t.close();tiles.clear();row.removeAllViews();report="[]";}
void foreground(boolean value){foreground=value;if(value)render();else clear();}
void close(){stopped=true;ui.removeCallbacksAndMessages(null);worker.shutdownNow();clear();}
final Runnable watch=new Runnable(){public void run(){
if(stopped)return;
long now=SystemClock.elapsedRealtime();
if(lease>0&&lease<now){clear();signature="";title.setText("授权连接暂时中断 · 等待同步");}
else if(foreground&&cameras.length()>3&&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;bit<prefix;bit++)if((own[bit/8]&(1<<(7-bit%8)))!=(remote[bit/8]&(1<<(7-bit%8)))){match=false;break;}
if(match)return true;
}
}
}catch(Exception ignored){}
return false;
}
final class Tile extends FrameLayout implements TextureView.SurfaceTextureListener {
final JSONObject camera;final TextureView texture;final TextView label;final View curtain;
MediaPlayer player;Surface surface;String state="connecting";long lastFrame=SystemClock.elapsedRealtime();
int failures=0;boolean closed=false,visible=false;
final Runnable retry=()->connect();
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<SystemClock.elapsedRealtime())return;
release();ui.removeCallbacks(retry);
if(!sameNetwork(camera.optString("host"))){fail("不在同一局域网","outside_lan");return;}
try{
URI uri=new URI(camera.getString("url"));
if(!"rtsp".equals(uri.getScheme())||!camera.getString("host").equals(uri.getHost())){fail("直连地址不正确","unsupported");return;}
state="connecting";label.setText(camera.optString("name")+" · 正在直连");curtain.setVisibility(VISIBLE);visible=false;lastFrame=SystemClock.elapsedRealtime();
MediaPlayer p=new MediaPlayer();player=p;p.setSurface(surface);p.setVolume(0,0);
p.setOnPreparedListener(mp->{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")+" · 局域网直连");}}
}
}
@@ -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;}}
}
@@ -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<byte[]> 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);}
});
}
}
@@ -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){}
}
}