chore: 初始化仓库基线(AGENTS.md、git 规范、敏感文件排除)
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
import { get, post, toArray } from './client';
|
||||
import type { Alarm, AlarmClip } from '../types';
|
||||
|
||||
export interface AlarmQuery {
|
||||
openOnly?: boolean;
|
||||
deviceKey?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export const getAlarms = async (query: AlarmQuery = {}): Promise<Alarm[]> => {
|
||||
const data = await get<Alarm[] | { items?: Alarm[] }>('/alarms', query);
|
||||
return toArray(data);
|
||||
};
|
||||
|
||||
export const ackAlarm = (id: string) =>
|
||||
post<{ ok?: boolean }>(`/alarms/${id}/ack`);
|
||||
|
||||
export const getAlarmClip = (id: string) =>
|
||||
get<AlarmClip>(`/alarms/${id}/clip`);
|
||||
@@ -0,0 +1,7 @@
|
||||
import { post, get } from './client';
|
||||
import type { LoginResponse, User } from '../types';
|
||||
|
||||
export const loginApi = (username: string, password: string) =>
|
||||
post<LoginResponse>('/auth/login', { username, password });
|
||||
|
||||
export const getMeApi = () => get<User>('/auth/me');
|
||||
@@ -0,0 +1,89 @@
|
||||
import axios from 'axios';
|
||||
import type { AxiosInstance, AxiosError } from 'axios';
|
||||
import { API_BASE_URL } from '@env';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
|
||||
export const TOKEN_KEY = 'silkworm_access_token';
|
||||
export const REFRESH_TOKEN_KEY = 'silkworm_refresh_token';
|
||||
|
||||
// Navigation ref for redirecting to login on 401
|
||||
let navigationRef: { navigate: (screen: string) => void } | null = null;
|
||||
|
||||
export const setNavigationRef = (ref: { navigate: (screen: string) => void }) => {
|
||||
navigationRef = ref;
|
||||
};
|
||||
|
||||
// Debug: log the actual API_BASE_URL at module load time
|
||||
console.log('[DEBUG] API_BASE_URL from @env:', JSON.stringify(API_BASE_URL));
|
||||
|
||||
export const http: AxiosInstance = axios.create({
|
||||
baseURL: API_BASE_URL || 'http://localhost:3000/api/v1',
|
||||
timeout: 8000,
|
||||
});
|
||||
|
||||
// Request interceptor: attach JWT token
|
||||
http.interceptors.request.use(async (config) => {
|
||||
const token = await AsyncStorage.getItem(TOKEN_KEY);
|
||||
if (token) {
|
||||
config.headers = config.headers ?? {};
|
||||
config.headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
// Response interceptor: handle 401
|
||||
http.interceptors.response.use(
|
||||
(res) => res,
|
||||
async (err: AxiosError) => {
|
||||
const status = err.response?.status;
|
||||
if (status === 401) {
|
||||
await AsyncStorage.multiRemove([TOKEN_KEY, REFRESH_TOKEN_KEY]);
|
||||
// Redirect to login screen
|
||||
if (navigationRef) {
|
||||
navigationRef.navigate('Login');
|
||||
}
|
||||
}
|
||||
return Promise.reject(err);
|
||||
},
|
||||
);
|
||||
|
||||
// Helper to extract response data
|
||||
export const request = <T = unknown>(config: Parameters<AxiosInstance['request']>[0]): Promise<T> =>
|
||||
http.request<T>(config).then((r) => r.data);
|
||||
|
||||
export const get = <T = unknown>(url: string, params?: Record<string, any>) =>
|
||||
request<T>({ method: 'GET', url, params });
|
||||
|
||||
export const post = <T = unknown>(url: string, data?: unknown) =>
|
||||
request<T>({ method: 'POST', url, data });
|
||||
|
||||
export const patch = <T = unknown>(url: string, data?: unknown) =>
|
||||
request<T>({ method: 'PATCH', url, data });
|
||||
|
||||
export const put = <T = unknown>(url: string, data?: unknown) =>
|
||||
request<T>({ method: 'PUT', url, data });
|
||||
|
||||
export const del = <T = unknown>(url: string, params?: Record<string, any>) =>
|
||||
request<T>({ method: 'DELETE', url, params });
|
||||
|
||||
// Helper: normalize array response (backend may return array or {items:[...]})
|
||||
export const toArray = <T>(data: T[] | { items?: T[] } | undefined): T[] => {
|
||||
if (!data) return [];
|
||||
return Array.isArray(data) ? data : data.items ?? [];
|
||||
};
|
||||
|
||||
export const extractErrorMessage = (err: any): string => {
|
||||
return (
|
||||
err?.response?.data?.message ||
|
||||
err?.response?.data?.msg ||
|
||||
err?.message ||
|
||||
'请求失败'
|
||||
);
|
||||
};
|
||||
|
||||
// Resolve relative URL (e.g. /api/v1/video/clips/1/stream) to full URL
|
||||
export const resolveUrl = (path: string): string => {
|
||||
if (path.startsWith('http://') || path.startsWith('https://')) return path;
|
||||
const base = (API_BASE_URL || 'http://localhost:3000/api/v1').replace(/\/api\/v1$/, '');
|
||||
return base + path;
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import { get, post, toArray } from './client';
|
||||
import type { Device } from '../types';
|
||||
|
||||
export const getDevices = async (params?: Record<string, any>): Promise<Device[]> => {
|
||||
const data = await get<Device[] | { items?: Device[] }>('/devices', params);
|
||||
return toArray(data);
|
||||
};
|
||||
|
||||
export const getDevice = (id: string) => get<Device>(`/devices/${id}`);
|
||||
|
||||
export interface ControlCommand {
|
||||
deviceKey: string;
|
||||
action: string;
|
||||
value?: any;
|
||||
payload?: any;
|
||||
}
|
||||
|
||||
export const sendControl = (command: ControlCommand) =>
|
||||
post<{ ok?: boolean; success?: boolean }>('/control/send', command);
|
||||
|
||||
export const getControlLogs = async (params?: Record<string, any>) => {
|
||||
const data = await get<any[] | { items?: any[] }>('/control/logs', params);
|
||||
return toArray(data);
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
import { get, toArray } from './client';
|
||||
import type { Room } from '../types';
|
||||
|
||||
export const getRooms = async (): Promise<Room[]> => {
|
||||
const data = await get<Room[] | { items?: Room[] }>('/rooms');
|
||||
return toArray(data);
|
||||
};
|
||||
|
||||
export const getRoom = (id: string) => get<Room>(`/rooms/${id}`);
|
||||
@@ -0,0 +1,67 @@
|
||||
import { get, toArray } from './client';
|
||||
import type { TelemetryRecord, RealtimeMetric, TrendPoint } from '../types';
|
||||
import { normalizeMetricKey, getMetricName, getMetricUnit, metricStatus } from '../utils/format';
|
||||
|
||||
export interface TelemetryQuery {
|
||||
deviceKey?: string;
|
||||
metric?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export const getTelemetry = async (query: TelemetryQuery = {}): Promise<TelemetryRecord[]> => {
|
||||
const data = await get<TelemetryRecord[] | { items?: TelemetryRecord[] }>('/telemetry', query);
|
||||
return toArray(data);
|
||||
};
|
||||
|
||||
export const getLatestTelemetry = async (deviceKey: string): Promise<TelemetryRecord[]> => {
|
||||
const data = await get<TelemetryRecord[] | { items?: TelemetryRecord[] }>(
|
||||
`/telemetry/${deviceKey}/latest`,
|
||||
);
|
||||
return toArray(data);
|
||||
};
|
||||
|
||||
// Normalize telemetry records into metric display format
|
||||
export const normalizeRealtime = (records: TelemetryRecord[]): RealtimeMetric[] => {
|
||||
const latestByMetric = new Map<string, TelemetryRecord>();
|
||||
for (const record of records) {
|
||||
const key = normalizeMetricKey(record.metric);
|
||||
const prev = latestByMetric.get(key);
|
||||
if (!prev || new Date(record.timestamp).getTime() > new Date(prev.timestamp).getTime()) {
|
||||
latestByMetric.set(key, record);
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(latestByMetric.entries()).map(([key, record]) => ({
|
||||
key,
|
||||
name: getMetricName(key) || record.metric,
|
||||
value: Number(record.value),
|
||||
unit: getMetricUnit(key) || '',
|
||||
status: metricStatus(key, Number(record.value)),
|
||||
}));
|
||||
};
|
||||
|
||||
// Fetch trend data for chart
|
||||
export const fetchTrend = async (hours = 24): Promise<TrendPoint[]> => {
|
||||
const to = new Date();
|
||||
const from = new Date(to.getTime() - hours * 3600 * 1000);
|
||||
const records = await getTelemetry({
|
||||
from: from.toISOString(),
|
||||
to: to.toISOString(),
|
||||
limit: 1000,
|
||||
});
|
||||
|
||||
return records
|
||||
.slice()
|
||||
.reverse()
|
||||
.reduce<TrendPoint[]>((acc, record) => {
|
||||
const key = normalizeMetricKey(record.metric);
|
||||
if (!['temp', 'humidity', 'co2'].includes(key)) return acc;
|
||||
const time = new Date(record.timestamp).toLocaleTimeString().slice(0, 5);
|
||||
const point = acc.find((item) => item.time === time) ?? { time };
|
||||
(point as unknown as Record<string, string | number | undefined>)[key] = Number(record.value);
|
||||
if (!acc.includes(point)) acc.push(point);
|
||||
return acc;
|
||||
}, []);
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
import { get, post, patch, del, toArray } from './client';
|
||||
import type { Threshold } from '../types';
|
||||
|
||||
export const getThresholds = async (params?: Record<string, any>): Promise<Threshold[]> => {
|
||||
const data = await get<Threshold[] | { items?: Threshold[] }>('/thresholds', params);
|
||||
return toArray(data);
|
||||
};
|
||||
|
||||
export const createThreshold = (data: Partial<Threshold>) =>
|
||||
post<Threshold>('/thresholds', {
|
||||
...data,
|
||||
minValue: data.minValue ?? data.min,
|
||||
maxValue: data.maxValue ?? data.max,
|
||||
});
|
||||
|
||||
export const updateThreshold = (id: string, data: Partial<Threshold>) =>
|
||||
patch<Threshold>(`/thresholds/${id}`, {
|
||||
...data,
|
||||
minValue: data.minValue ?? data.min,
|
||||
maxValue: data.maxValue ?? data.max,
|
||||
});
|
||||
|
||||
export const deleteThreshold = (id: string) => del<{ ok?: boolean }>(`/thresholds/${id}`);
|
||||
@@ -0,0 +1,23 @@
|
||||
import { get, post, toArray } from './client';
|
||||
import type { Camera, PlayInfo, VideoClip, ClipListResponse } from '../types';
|
||||
|
||||
export const getCameras = async (): Promise<Camera[]> => {
|
||||
const data = await get<Camera[] | { items?: Camera[] }>('/video/cameras');
|
||||
return toArray(data);
|
||||
};
|
||||
|
||||
export const playCamera = (id: number | string, format: 'hls' | 'flv' | 'webrtc' = 'hls') =>
|
||||
post<PlayInfo>(`/video/cameras/${id}/play`, { format });
|
||||
|
||||
export interface ClipQuery {
|
||||
cameraId?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export const getClips = async (query: ClipQuery = {}): Promise<VideoClip[]> => {
|
||||
const data = await get<ClipListResponse | VideoClip[]>('/video/clips', query);
|
||||
if (Array.isArray(data)) return data;
|
||||
return data.items ?? [];
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
import React from 'react';
|
||||
import { View, StyleSheet, Text, Dimensions } from 'react-native';
|
||||
|
||||
interface MiniChartProps {
|
||||
data: { time: string; temp?: number; humidity?: number; co2?: number }[];
|
||||
height?: number;
|
||||
color?: string;
|
||||
metric?: 'temp' | 'humidity' | 'co2';
|
||||
}
|
||||
|
||||
export const MiniChart: React.FC<MiniChartProps> = ({ data, height = 120, color = '#7A9E7E', metric = 'temp' }) => {
|
||||
const values = data.map(d => d[metric]).filter((v): v is number => v !== undefined);
|
||||
if (values.length === 0) return <Text style={{ textAlign: 'center', color: '#B8B3AA', padding: 20 }}>暂无数据</Text>;
|
||||
|
||||
const min = Math.min(...values);
|
||||
const max = Math.max(...values);
|
||||
const range = max - min || 1;
|
||||
|
||||
return (
|
||||
<View style={[styles.container, { height }]}>
|
||||
{values.map((v, i) => {
|
||||
const barHeight = ((v - min) / range) * (height - 20);
|
||||
return (
|
||||
<View key={i} style={[styles.bar, { height: barHeight + 2, backgroundColor: color }]} />
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: { flexDirection: 'row', alignItems: 'flex-end', paddingHorizontal: 10, gap: 2 },
|
||||
bar: { flex: 1, borderRadius: 3, minHeight: 2 },
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import React from 'react';
|
||||
import { StyleSheet, View } from 'react-native';
|
||||
import { Card, Text, useTheme } from 'react-native-paper';
|
||||
import type { MD3Theme } from 'react-native-paper';
|
||||
|
||||
interface StatCardProps {
|
||||
title: string;
|
||||
value: number | string;
|
||||
suffix?: string;
|
||||
color?: string;
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
export const StatCard: React.FC<StatCardProps> = ({ title, value, suffix, color, icon }) => {
|
||||
const theme = useTheme<MD3Theme>();
|
||||
|
||||
return (
|
||||
<Card style={styles.card} mode="elevated">
|
||||
<Card.Content style={styles.content}>
|
||||
<View style={styles.headerRow}>
|
||||
{icon ? (
|
||||
<Text style={[styles.icon, { color: color || theme.colors.primary }]}>{icon}</Text>
|
||||
) : null}
|
||||
<Text variant="labelMedium" style={styles.title}>
|
||||
{title}
|
||||
</Text>
|
||||
</View>
|
||||
<Text variant="headlineMedium" style={[styles.value, { color: color || '#2D2A26' }]}>
|
||||
{value}
|
||||
{suffix ? <Text variant="titleMedium" style={styles.suffix}> {suffix}</Text> : null}
|
||||
</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
flex: 1,
|
||||
minWidth: 140,
|
||||
},
|
||||
content: {
|
||||
paddingVertical: 12,
|
||||
paddingHorizontal: 16,
|
||||
},
|
||||
headerRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
marginBottom: 4,
|
||||
},
|
||||
icon: {
|
||||
fontSize: 18,
|
||||
marginRight: 6,
|
||||
},
|
||||
title: {
|
||||
opacity: 0.7,
|
||||
},
|
||||
value: {
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
suffix: {
|
||||
fontWeight: 'normal',
|
||||
opacity: 0.6,
|
||||
},
|
||||
});
|
||||
|
||||
interface StatCardRowProps {
|
||||
items: StatCardProps[];
|
||||
}
|
||||
|
||||
export const StatCardRow: React.FC<StatCardRowProps> = ({ items }) => {
|
||||
return (
|
||||
<View style={statRowStyles.container}>
|
||||
{items.map((item, index) => (
|
||||
<StatCard key={`${item.title}-${index}`} {...item} />
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
const statRowStyles = StyleSheet.create({
|
||||
container: {
|
||||
flexDirection: 'row',
|
||||
flexWrap: 'wrap',
|
||||
gap: 12,
|
||||
marginVertical: 6,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,232 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { NavigationContainer, useNavigation } from '@react-navigation/native';
|
||||
import { createNativeStackNavigator } from '@react-navigation/native-stack';
|
||||
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
|
||||
import { Provider as PaperProvider, useTheme, MD3LightTheme } from 'react-native-paper';
|
||||
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
|
||||
import { setNavigationRef } from '../api/client';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { useAppStore } from '../store/appStore';
|
||||
import { wsManager } from '../utils/ws';
|
||||
import type { RootStackParamList, MainTabParamList } from '../types';
|
||||
|
||||
import LoginScreen from '../screens/LoginScreen';
|
||||
import DashboardScreen from '../screens/DashboardScreen';
|
||||
import RoomsScreen from '../screens/RoomsScreen';
|
||||
import RoomDetailScreen from '../screens/RoomDetailScreen';
|
||||
import DevicesScreen from '../screens/DevicesScreen';
|
||||
import DeviceControlScreen from '../screens/DeviceControlScreen';
|
||||
import AlertsScreen from '../screens/AlertsScreen';
|
||||
import ThresholdsScreen from '../screens/ThresholdsScreen';
|
||||
import VideoScreen from '../screens/VideoScreen';
|
||||
import VideoPlayerScreen from '../screens/VideoPlayerScreen';
|
||||
import SettingsScreen from '../screens/SettingsScreen';
|
||||
|
||||
const Stack = createNativeStackNavigator<RootStackParamList>();
|
||||
const Tab = createBottomTabNavigator<MainTabParamList>();
|
||||
|
||||
const TabIcon: React.FC<{ name: string; activeName: string; color: string; size: number; focused: boolean }> = ({ name, activeName, color, size, focused }) => (
|
||||
<Icon name={focused ? activeName : name} size={focused ? 26 : 22} color={color} />
|
||||
);
|
||||
|
||||
function MainTabs() {
|
||||
const navigation = useNavigation<any>();
|
||||
|
||||
return (
|
||||
<Tab.Navigator
|
||||
screenOptions={{
|
||||
headerShown: true,
|
||||
tabBarActiveTintColor: '#5C7D60',
|
||||
tabBarInactiveTintColor: '#C4BFB6',
|
||||
tabBarStyle: {
|
||||
backgroundColor: '#FFFFFF',
|
||||
borderTopColor: '#F0EDE8',
|
||||
borderTopWidth: 1,
|
||||
paddingBottom: 6,
|
||||
paddingTop: 6,
|
||||
height: 60,
|
||||
},
|
||||
tabBarLabelStyle: {
|
||||
fontSize: 15,
|
||||
fontWeight: '700',
|
||||
marginTop: 2,
|
||||
},
|
||||
tabBarIconStyle: {
|
||||
marginBottom: 2,
|
||||
},
|
||||
headerStyle: {
|
||||
backgroundColor: '#FAF8F5',
|
||||
},
|
||||
headerTitleStyle: {
|
||||
color: '#2D2A26',
|
||||
fontSize: 18,
|
||||
fontWeight: '500',
|
||||
},
|
||||
headerTintColor: '#5C7D60',
|
||||
headerRight: () => (
|
||||
<Icon
|
||||
name="cog-outline"
|
||||
size={24}
|
||||
color="#8C8780"
|
||||
style={{ marginRight: 12 }}
|
||||
onPress={() => navigation.navigate('Settings')}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
>
|
||||
<Tab.Screen
|
||||
name="Dashboard"
|
||||
component={DashboardScreen}
|
||||
options={{
|
||||
title: '仪表盘',
|
||||
tabBarIcon: ({ color, size, focused }) => <TabIcon name="view-dashboard-outline" activeName="view-dashboard" color={color} size={size} focused={focused} />,
|
||||
}}
|
||||
/>
|
||||
<Tab.Screen
|
||||
name="Rooms"
|
||||
component={RoomsScreen}
|
||||
options={{
|
||||
title: '蚕房',
|
||||
tabBarIcon: ({ color, size, focused }) => <TabIcon name="home-outline" activeName="home-variant" color={color} size={size} focused={focused} />,
|
||||
}}
|
||||
/>
|
||||
<Tab.Screen
|
||||
name="Devices"
|
||||
component={DevicesScreen}
|
||||
options={{
|
||||
title: '设备',
|
||||
tabBarIcon: ({ color, size, focused }) => <TabIcon name="router-wireless" activeName="router-wireless" color={color} size={size} focused={focused} />,
|
||||
}}
|
||||
/>
|
||||
<Tab.Screen
|
||||
name="Alerts"
|
||||
component={AlertsScreen}
|
||||
options={{
|
||||
title: '告警',
|
||||
tabBarIcon: ({ color, size, focused }) => <TabIcon name="bell-alert-outline" activeName="bell-alert" color={color} size={size} focused={focused} />,
|
||||
}}
|
||||
/>
|
||||
<Tab.Screen
|
||||
name="Video"
|
||||
component={VideoScreen}
|
||||
options={{
|
||||
title: '视频',
|
||||
tabBarIcon: ({ color, size, focused }) => <TabIcon name="video-outline" activeName="video" color={color} size={size} focused={focused} />,
|
||||
}}
|
||||
/>
|
||||
</Tab.Navigator>
|
||||
);
|
||||
}
|
||||
|
||||
function AppContent() {
|
||||
const token = useAuthStore((s) => s.token);
|
||||
const restoreSession = useAuthStore((s) => s.restoreSession);
|
||||
const setRealtimeData = useAppStore((s) => s.setRealtimeData);
|
||||
const [isReady, setIsReady] = React.useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
await restoreSession();
|
||||
setIsReady(true);
|
||||
})();
|
||||
}, [restoreSession]);
|
||||
|
||||
// Subscribe to WebSocket telemetry
|
||||
useEffect(() => {
|
||||
const unsub = wsManager.subscribe((data) => {
|
||||
if (data?.type === 'telemetry' || data?.metric) {
|
||||
const telemetry = useAppStore.getState().realtimeData;
|
||||
setRealtimeData([...telemetry, data].slice(-100));
|
||||
}
|
||||
});
|
||||
return unsub;
|
||||
}, [setRealtimeData]);
|
||||
|
||||
if (!isReady) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<NavigationContainer
|
||||
ref={(ref) => {
|
||||
if (ref) {
|
||||
setNavigationRef({
|
||||
navigate: (screen: string) => {
|
||||
(ref as any).navigate(screen);
|
||||
},
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Stack.Navigator screenOptions={{ headerShown: false }} initialRouteName={token ? 'Main' : 'Login'}>
|
||||
<Stack.Screen name="Login" component={LoginScreen} />
|
||||
<Stack.Screen name="Main" component={MainTabs} />
|
||||
<Stack.Screen
|
||||
name="RoomDetail"
|
||||
component={RoomDetailScreen}
|
||||
options={{ headerShown: true, title: '蚕房详情', headerBackTitle: '返回' }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="DeviceControl"
|
||||
component={DeviceControlScreen}
|
||||
options={{ headerShown: true, title: '设备控制', headerBackTitle: '返回' }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="VideoPlayer"
|
||||
component={VideoPlayerScreen}
|
||||
options={{ headerShown: false }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="Thresholds"
|
||||
component={ThresholdsScreen}
|
||||
options={{ headerShown: true, title: '阈值管理', headerBackTitle: '返回' }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="Settings"
|
||||
component={SettingsScreen}
|
||||
options={{ headerShown: true, title: '设置', headerBackTitle: '返回' }}
|
||||
/>
|
||||
</Stack.Navigator>
|
||||
</NavigationContainer>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AppNavigator() {
|
||||
const silkTheme = {
|
||||
...MD3LightTheme,
|
||||
colors: {
|
||||
...MD3LightTheme.colors,
|
||||
primary: '#7A9E7E',
|
||||
primaryContainer: '#E8F0E9',
|
||||
onPrimary: '#FFFFFF',
|
||||
onPrimaryContainer: '#5C7D60',
|
||||
secondary: '#6B8F71',
|
||||
secondaryContainer: '#F0EDE8',
|
||||
onSecondary: '#FFFFFF',
|
||||
onSecondaryContainer: '#5C7D60',
|
||||
error: '#D4847A',
|
||||
errorContainer: '#F9E8E5',
|
||||
onError: '#FFFFFF',
|
||||
background: '#FAF8F5',
|
||||
onBackground: '#2D2A26',
|
||||
surface: '#FFFFFF',
|
||||
onSurface: '#2D2A26',
|
||||
surfaceVariant: '#F5F0E8',
|
||||
onSurfaceVariant: '#8C8780',
|
||||
outline: '#E8E4DE',
|
||||
outlineVariant: '#F0EDE8',
|
||||
elevation: {
|
||||
...MD3LightTheme.colors.elevation,
|
||||
level0: 'transparent',
|
||||
level1: '#FFFFFF',
|
||||
level2: '#FFFFFF',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<PaperProvider theme={silkTheme}>
|
||||
<AppContent />
|
||||
</PaperProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import { StyleSheet, View, FlatList, RefreshControl, Alert } from 'react-native';
|
||||
import { Text, Card, useTheme, ActivityIndicator, Surface, SegmentedButtons, Button, Snackbar } from 'react-native-paper';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import { getAlarms, ackAlarm, getAlarmClip } from '../api/alarms';
|
||||
import { extractErrorMessage } from '../api/client';
|
||||
import { formatRelativeTime, getSeverityLabel } from '../utils/format';
|
||||
import type { Alarm } from '../types';
|
||||
|
||||
export default function AlertsScreen() {
|
||||
const theme = useTheme();
|
||||
const navigation = useNavigation<any>();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [alarms, setAlarms] = useState<Alarm[]>([]);
|
||||
const [filter, setFilter] = useState('open');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [snackMsg, setSnackMsg] = useState('');
|
||||
const [snackVisible, setSnackVisible] = useState(false);
|
||||
const [ackingId, setAkingId] = useState<string | null>(null);
|
||||
|
||||
const getSevColor = (severity?: string) => {
|
||||
switch (severity?.toLowerCase()) {
|
||||
case 'danger':
|
||||
case 'critical':
|
||||
case 'high':
|
||||
return '#D4847A';
|
||||
case 'warn':
|
||||
case 'warning':
|
||||
case 'medium':
|
||||
return '#D4B87A';
|
||||
case 'info':
|
||||
case 'low':
|
||||
return '#6B8F71';
|
||||
default:
|
||||
return '#B8B3AA';
|
||||
}
|
||||
};
|
||||
|
||||
const loadData = useCallback(async (isRefresh = false) => {
|
||||
if (isRefresh) setRefreshing(true);
|
||||
try {
|
||||
const data = await getAlarms({ openOnly: filter === 'open' });
|
||||
setAlarms(data);
|
||||
setError(null);
|
||||
} catch (err: any) {
|
||||
setError(err?.message || '加载失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
}
|
||||
}, [filter]);
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
const handleAck = async (id: string) => {
|
||||
setAkingId(id);
|
||||
try {
|
||||
await ackAlarm(id);
|
||||
setAlarms((prev) =>
|
||||
prev.map((a) => (a.id === id ? { ...a, acknowledged: true, open: false } : a)),
|
||||
);
|
||||
setSnackMsg('告警已确认');
|
||||
setSnackVisible(true);
|
||||
} catch (err: any) {
|
||||
Alert.alert('操作失败', extractErrorMessage(err));
|
||||
} finally {
|
||||
setAkingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleViewClip = async (alarm: Alarm) => {
|
||||
try {
|
||||
const clip = await getAlarmClip(alarm.id);
|
||||
if (clip.playbackUrl) {
|
||||
Alert.alert(
|
||||
'告警片段',
|
||||
`开始时间: ${formatRelativeTime(clip.startAt)}\n结束时间: ${formatRelativeTime(clip.endAt)}`,
|
||||
);
|
||||
} else {
|
||||
Alert.alert('提示', '暂无关联的视频片段');
|
||||
}
|
||||
} catch (err: any) {
|
||||
Alert.alert('获取片段失败', extractErrorMessage(err));
|
||||
}
|
||||
};
|
||||
|
||||
const renderItem = ({ item }: { item: Alarm }) => {
|
||||
const sevColor = getSevColor(item.severity || item.level);
|
||||
return (
|
||||
<Card style={[styles.card, { borderLeftColor: sevColor, borderLeftWidth: 4 }]}>
|
||||
<Card.Content style={styles.cardContent}>
|
||||
<View style={styles.alarmHeader}>
|
||||
<View style={styles.alarmTitleRow}>
|
||||
<Surface style={[styles.sevBadge, { backgroundColor: sevColor }]}>
|
||||
<Text style={styles.sevBadgeText}>{getSeverityLabel(item.severity || item.level)}</Text>
|
||||
</Surface>
|
||||
<Text variant="bodyMedium" style={styles.alarmTitle}>
|
||||
{item.title || item.message || item.content || item.code || '告警'}
|
||||
</Text>
|
||||
</View>
|
||||
{item.open ? (
|
||||
<Surface style={styles.openBadge}>
|
||||
<Text style={styles.openBadgeText}>未处理</Text>
|
||||
</Surface>
|
||||
) : (
|
||||
<Surface style={[styles.openBadge, { backgroundColor: '#F0EDE8' }]}>
|
||||
<Text style={[styles.openBadgeText, { color: '#8C8780' }]}>已关闭</Text>
|
||||
</Surface>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{item.message && item.title ? (
|
||||
<Text variant="bodySmall" style={styles.alarmMessage}>{item.message}</Text>
|
||||
) : null}
|
||||
|
||||
<View style={styles.alarmMeta}>
|
||||
{item.deviceKey ? <Text style={styles.metaText}>设备: {item.deviceKey}</Text> : null}
|
||||
{item.metric ? <Text style={styles.metaText}>指标: {item.metric}</Text> : null}
|
||||
{item.value !== undefined ? <Text style={styles.metaText}>值: {item.value}</Text> : null}
|
||||
</View>
|
||||
|
||||
<View style={styles.alarmFooter}>
|
||||
<Text style={styles.timeText}>
|
||||
{formatRelativeTime(item.triggeredAt || item.createdAt)}
|
||||
</Text>
|
||||
<View style={styles.footerActions}>
|
||||
{item.open && !item.acknowledged ? (
|
||||
<Button
|
||||
mode="text"
|
||||
onPress={() => handleAck(item.id)}
|
||||
loading={ackingId === item.id}
|
||||
disabled={ackingId === item.id}
|
||||
textColor="#5C7D60"
|
||||
>
|
||||
确认
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
mode="text"
|
||||
onPress={() => handleViewClip(item)}
|
||||
textColor="#6B8F71"
|
||||
icon="video"
|
||||
>
|
||||
片段
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<SafeAreaView style={styles.center}>
|
||||
<ActivityIndicator size="large" />
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container} edges={['bottom']}>
|
||||
<View style={styles.filterContainer}>
|
||||
<SegmentedButtons
|
||||
value={filter}
|
||||
onValueChange={setFilter}
|
||||
buttons={[
|
||||
{ value: 'open', label: '未处理' },
|
||||
{ value: 'all', label: '全部' },
|
||||
]}
|
||||
/>
|
||||
</View>
|
||||
<FlatList
|
||||
data={alarms}
|
||||
keyExtractor={(item) => item.id}
|
||||
renderItem={renderItem}
|
||||
contentContainerStyle={styles.list}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
|
||||
}
|
||||
ListEmptyComponent={
|
||||
error ? (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Text style={styles.emptyText}>{error}</Text>
|
||||
</View>
|
||||
) : (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Text style={styles.emptyText}>暂无告警</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Snackbar
|
||||
visible={snackVisible}
|
||||
onDismiss={() => setSnackVisible(false)}
|
||||
duration={2000}
|
||||
>
|
||||
{snackMsg}
|
||||
</Snackbar>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#FAF8F5',
|
||||
},
|
||||
center: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
filterContainer: {
|
||||
padding: 16,
|
||||
paddingBottom: 8,
|
||||
},
|
||||
list: {
|
||||
padding: 16,
|
||||
paddingTop: 8,
|
||||
paddingBottom: 32,
|
||||
},
|
||||
card: {
|
||||
marginBottom: 12,
|
||||
borderRadius: 14,
|
||||
backgroundColor: '#FFFFFF',
|
||||
},
|
||||
cardContent: {
|
||||
paddingVertical: 12,
|
||||
},
|
||||
alarmHeader: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'flex-start',
|
||||
marginBottom: 4,
|
||||
},
|
||||
alarmTitleRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
flex: 1,
|
||||
},
|
||||
sevBadge: {
|
||||
paddingHorizontal: 8,
|
||||
paddingVertical: 3,
|
||||
borderRadius: 10,
|
||||
elevation: 0,
|
||||
},
|
||||
sevBadgeText: {
|
||||
color: 'white',
|
||||
fontSize: 11,
|
||||
fontWeight: '500',
|
||||
},
|
||||
alarmTitle: {
|
||||
color: '#2D2A26',
|
||||
fontWeight: '500',
|
||||
flex: 1,
|
||||
},
|
||||
openBadge: {
|
||||
backgroundColor: '#F9E8E5',
|
||||
paddingHorizontal: 8,
|
||||
paddingVertical: 3,
|
||||
borderRadius: 10,
|
||||
elevation: 0,
|
||||
},
|
||||
openBadgeText: {
|
||||
color: '#D4847A',
|
||||
fontSize: 11,
|
||||
fontWeight: '500',
|
||||
},
|
||||
alarmMessage: {
|
||||
color: '#8C8780',
|
||||
marginTop: 4,
|
||||
},
|
||||
alarmMeta: {
|
||||
flexDirection: 'row',
|
||||
flexWrap: 'wrap',
|
||||
gap: 12,
|
||||
marginTop: 8,
|
||||
},
|
||||
metaText: {
|
||||
fontSize: 12,
|
||||
color: '#B8B3AA',
|
||||
},
|
||||
alarmFooter: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginTop: 8,
|
||||
},
|
||||
timeText: {
|
||||
fontSize: 12,
|
||||
color: '#B8B3AA',
|
||||
},
|
||||
footerActions: {
|
||||
flexDirection: 'row',
|
||||
gap: 4,
|
||||
},
|
||||
emptyContainer: {
|
||||
alignItems: 'center',
|
||||
paddingTop: 64,
|
||||
},
|
||||
emptyText: {
|
||||
color: '#B8B3AA',
|
||||
fontSize: 16,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,369 @@
|
||||
import React, { useEffect, useState, useCallback, useRef } from 'react';
|
||||
import { StyleSheet, View, ScrollView, RefreshControl } from 'react-native';
|
||||
import { Text, Card, ActivityIndicator, Surface } from 'react-native-paper';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { MiniChart } from '../components/MiniChart';
|
||||
import { StatCard } from '../components/StatCard';
|
||||
import { getRooms } from '../api/rooms';
|
||||
import { getDevices } from '../api/devices';
|
||||
import { getAlarms } from '../api/alarms';
|
||||
import { getTelemetry, normalizeRealtime, fetchTrend } from '../api/telemetry';
|
||||
import type { Room, Device, Alarm, RealtimeMetric, TrendPoint } from '../types';
|
||||
|
||||
export default function DashboardScreen() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [rooms, setRooms] = useState<Room[]>([]);
|
||||
const [devices, setDevices] = useState<Device[]>([]);
|
||||
const [alarms, setAlarms] = useState<Alarm[]>([]);
|
||||
const [metrics, setMetrics] = useState<RealtimeMetric[]>([]);
|
||||
const [trend, setTrend] = useState<TrendPoint[]>([]);
|
||||
const [trendLoading, setTrendLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
const loadTrend = useCallback(async () => {
|
||||
setTrendLoading(true);
|
||||
try {
|
||||
const trendData = await fetchTrend(24).catch(() => [] as TrendPoint[]);
|
||||
setTrend(trendData);
|
||||
} finally {
|
||||
setTrendLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadData = useCallback(async (isRefresh = false) => {
|
||||
if (isRefresh) setRefreshing(true);
|
||||
try {
|
||||
const [roomsData, devicesData, alarmsData, telemetryData] = await Promise.all([
|
||||
getRooms().catch(() => [] as Room[]),
|
||||
getDevices().catch(() => [] as Device[]),
|
||||
getAlarms({ openOnly: true }).catch(() => [] as Alarm[]),
|
||||
getTelemetry({ limit: 100 }).catch(() => [] as any[]),
|
||||
]);
|
||||
|
||||
setRooms(roomsData);
|
||||
setDevices(devicesData);
|
||||
setAlarms(alarmsData);
|
||||
setMetrics(normalizeRealtime(telemetryData));
|
||||
setError(null);
|
||||
} catch (err: any) {
|
||||
setError(err?.message || '数据加载失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
}
|
||||
// Load trend data in the background (non-blocking)
|
||||
loadTrend();
|
||||
}, [loadTrend]);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
intervalRef.current = setInterval(() => loadData(), 30000);
|
||||
return () => {
|
||||
if (intervalRef.current) clearInterval(intervalRef.current);
|
||||
};
|
||||
}, [loadData]);
|
||||
|
||||
const onlineDevices = devices.filter((d) => d.onlineStatus === 'online' || d.status === 'online').length;
|
||||
const offlineDevices = devices.length - onlineDevices;
|
||||
const activeAlarms = alarms.filter((a) => a.open).length;
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<SafeAreaView style={styles.center}>
|
||||
<ActivityIndicator size="large" />
|
||||
<Text style={styles.loadingText}>加载中...</Text>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const statusColor = (status: RealtimeMetric['status']) => {
|
||||
switch (status) {
|
||||
case 'danger': return '#D4847A';
|
||||
case 'warn': return '#D4B87A';
|
||||
default: return '#7A9E7E';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container} edges={['bottom']}>
|
||||
<ScrollView
|
||||
style={styles.scrollView}
|
||||
contentContainerStyle={styles.content}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
|
||||
}
|
||||
>
|
||||
{error ? (
|
||||
<Card style={styles.errorCard}>
|
||||
<Card.Content>
|
||||
<Text style={{ color: '#D4847A' }}>{error}</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
<View style={styles.statsRow}>
|
||||
<StatCard title="蚕房总数" value={rooms.length} icon="🏠" color="#7A9E7E" />
|
||||
<StatCard title="在线设备" value={onlineDevices} icon="📡" color="#7A9E7E" />
|
||||
</View>
|
||||
<View style={styles.statsRow}>
|
||||
<StatCard title="离线设备" value={offlineDevices} icon="📡" color="#B8B3AA" />
|
||||
<StatCard title="活跃告警" value={activeAlarms} icon="🔔" color={activeAlarms > 0 ? '#D4847A' : '#7A9E7E'} />
|
||||
</View>
|
||||
|
||||
<View style={styles.sectionTitleRow}>
|
||||
<View style={styles.sectionDot} />
|
||||
<Text variant="titleLarge" style={styles.sectionTitle}>实时环境指标</Text>
|
||||
</View>
|
||||
{metrics.length === 0 ? (
|
||||
<Card style={styles.emptyCard}>
|
||||
<Card.Content>
|
||||
<Text style={styles.emptyText}>暂无遥测数据</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
) : (
|
||||
<View style={styles.metricsGrid}>
|
||||
{metrics.map((m) => (
|
||||
<Card key={m.key} style={[styles.metricCard, { borderLeftColor: statusColor(m.status), borderLeftWidth: 4 }]}>
|
||||
<Card.Content style={styles.metricContent}>
|
||||
<Text variant="labelMedium" style={styles.metricName}>{m.name}</Text>
|
||||
<Text style={[styles.metricValue, { color: statusColor(m.status) }]}>
|
||||
{m.value.toFixed(1)}
|
||||
<Text style={styles.metricUnit}> {m.unit}</Text>
|
||||
</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
|
||||
<View style={styles.sectionTitleRow}>
|
||||
<View style={styles.sectionDot} />
|
||||
<Text variant="titleLarge" style={styles.sectionTitle}>24小时趋势</Text>
|
||||
</View>
|
||||
{trendLoading && trend.length === 0 ? (
|
||||
<Card style={styles.emptyCard}>
|
||||
<Card.Content>
|
||||
<View style={styles.trendLoadingRow}>
|
||||
<ActivityIndicator size="small" color="#7A9E7E" />
|
||||
<Text style={styles.emptyText}>趋势数据加载中...</Text>
|
||||
</View>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
) : trend.length > 0 ? (
|
||||
<Card style={styles.chartCard} mode="elevated">
|
||||
<Card.Content>
|
||||
<Text style={styles.chartMetricLabel}>温度 (°C)</Text>
|
||||
<MiniChart data={trend} metric="temp" color="#D4847A" height={100} />
|
||||
<Text style={styles.chartMetricLabel}>湿度 (%)</Text>
|
||||
<MiniChart data={trend} metric="humidity" color="#6B8F71" height={100} />
|
||||
<View style={styles.legendRow}>
|
||||
<View style={styles.legendItem}>
|
||||
<View style={[styles.legendDot, { backgroundColor: '#D4847A' }]} />
|
||||
<Text style={styles.legendText}>温度</Text>
|
||||
</View>
|
||||
<View style={styles.legendItem}>
|
||||
<View style={[styles.legendDot, { backgroundColor: '#6B8F71' }]} />
|
||||
<Text style={styles.legendText}>湿度</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
) : (
|
||||
<Card style={styles.emptyCard}>
|
||||
<Card.Content>
|
||||
<Text style={styles.emptyText}>暂无趋势数据</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<View style={styles.sectionTitleRow}>
|
||||
<View style={styles.sectionDot} />
|
||||
<Text variant="titleLarge" style={styles.sectionTitle}>最近告警</Text>
|
||||
</View>
|
||||
{alarms.length === 0 ? (
|
||||
<Card style={styles.emptyCard}>
|
||||
<Card.Content>
|
||||
<Text style={styles.emptyText}>暂无告警</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
) : (
|
||||
alarms.slice(0, 5).map((alarm) => (
|
||||
<Card key={alarm.id} style={styles.alarmCard}>
|
||||
<Card.Content style={styles.alarmContent}>
|
||||
<View style={styles.alarmLeft}>
|
||||
<Text variant="bodyMedium" style={styles.alarmTitle}>
|
||||
{alarm.title || alarm.message || alarm.code || '告警'}
|
||||
</Text>
|
||||
<Text variant="bodySmall" style={styles.alarmTime}>
|
||||
{alarm.triggeredAt || alarm.createdAt || '-'}
|
||||
</Text>
|
||||
</View>
|
||||
<Surface style={[styles.alarmBadge, { backgroundColor: alarm.severity === 'danger' ? '#D4847A' : alarm.severity === 'warn' ? '#D4B87A' : '#7A9E7E' }]}>
|
||||
<Text style={styles.alarmBadgeText}>
|
||||
{alarm.severity === 'danger' ? '严重' : alarm.severity === 'warn' ? '警告' : '提示'}
|
||||
</Text>
|
||||
</Surface>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
))
|
||||
)}
|
||||
</ScrollView>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#FAF8F5',
|
||||
},
|
||||
center: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
loadingText: {
|
||||
marginTop: 12,
|
||||
color: '#8C8780',
|
||||
},
|
||||
scrollView: {
|
||||
flex: 1,
|
||||
},
|
||||
content: {
|
||||
padding: 16,
|
||||
paddingBottom: 32,
|
||||
},
|
||||
errorCard: {
|
||||
marginBottom: 12,
|
||||
backgroundColor: '#F9E8E5',
|
||||
},
|
||||
statsRow: {
|
||||
flexDirection: 'row',
|
||||
gap: 12,
|
||||
marginBottom: 12,
|
||||
},
|
||||
sectionTitle: {
|
||||
fontWeight: 'bold',
|
||||
color: '#2D2A26',
|
||||
},
|
||||
sectionTitleRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
marginTop: 20,
|
||||
marginBottom: 12,
|
||||
gap: 8,
|
||||
},
|
||||
sectionDot: {
|
||||
width: 8,
|
||||
height: 8,
|
||||
borderRadius: 4,
|
||||
backgroundColor: '#7A9E7E',
|
||||
},
|
||||
metricsGrid: {
|
||||
flexDirection: 'row',
|
||||
flexWrap: 'wrap',
|
||||
gap: 12,
|
||||
},
|
||||
metricCard: {
|
||||
flexBasis: '47%',
|
||||
flexGrow: 1,
|
||||
backgroundColor: '#FDFAF5',
|
||||
borderColor: '#E8E4DE',
|
||||
borderWidth: 1,
|
||||
borderRadius: 14,
|
||||
},
|
||||
metricContent: {
|
||||
paddingVertical: 8,
|
||||
},
|
||||
metricName: {
|
||||
opacity: 0.7,
|
||||
marginBottom: 4,
|
||||
},
|
||||
metricValue: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
metricUnit: {
|
||||
fontSize: 14,
|
||||
fontWeight: 'normal',
|
||||
opacity: 0.6,
|
||||
},
|
||||
chartCard: {
|
||||
borderRadius: 14,
|
||||
},
|
||||
chartMetricLabel: {
|
||||
fontSize: 12,
|
||||
color: '#8C8780',
|
||||
marginTop: 8,
|
||||
marginBottom: 4,
|
||||
},
|
||||
legendRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'center',
|
||||
gap: 24,
|
||||
marginTop: 8,
|
||||
},
|
||||
legendItem: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
},
|
||||
legendDot: {
|
||||
width: 12,
|
||||
height: 12,
|
||||
borderRadius: 6,
|
||||
},
|
||||
legendText: {
|
||||
fontSize: 12,
|
||||
color: '#8C8780',
|
||||
},
|
||||
emptyCard: {
|
||||
marginBottom: 12,
|
||||
backgroundColor: '#F5F0E8',
|
||||
},
|
||||
trendLoadingRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: 8,
|
||||
paddingVertical: 4,
|
||||
},
|
||||
emptyText: {
|
||||
textAlign: 'center',
|
||||
color: '#B8B3AA',
|
||||
paddingVertical: 8,
|
||||
},
|
||||
alarmCard: {
|
||||
marginBottom: 8,
|
||||
borderRadius: 14,
|
||||
},
|
||||
alarmContent: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
paddingVertical: 8,
|
||||
},
|
||||
alarmLeft: {
|
||||
flex: 1,
|
||||
},
|
||||
alarmTitle: {
|
||||
fontWeight: '500',
|
||||
},
|
||||
alarmTime: {
|
||||
color: '#B8B3AA',
|
||||
marginTop: 2,
|
||||
},
|
||||
alarmBadge: {
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 4,
|
||||
borderRadius: 12,
|
||||
elevation: 0,
|
||||
},
|
||||
alarmBadgeText: {
|
||||
color: 'white',
|
||||
fontSize: 12,
|
||||
fontWeight: '500',
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,367 @@
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import { StyleSheet, View, ScrollView, Alert } from 'react-native';
|
||||
import { Text, Card, Button, Switch, useTheme, ActivityIndicator, TextInput, SegmentedButtons, Divider, Snackbar } from 'react-native-paper';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { useRoute } from '@react-navigation/native';
|
||||
import { sendControl } from '../api/devices';
|
||||
import { getTelemetry, normalizeRealtime } from '../api/telemetry';
|
||||
import { extractErrorMessage } from '../api/client';
|
||||
import { formatNumber } from '../utils/format';
|
||||
import type { RealtimeMetric } from '../types';
|
||||
|
||||
export default function DeviceControlScreen() {
|
||||
const theme = useTheme();
|
||||
const route = useRoute<any>();
|
||||
const { deviceKey, deviceName } = route.params;
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [metrics, setMetrics] = useState<RealtimeMetric[]>([]);
|
||||
const [isOn, setIsOn] = useState(false);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [snackMsg, setSnackMsg] = useState('');
|
||||
const [snackVisible, setSnackVisible] = useState(false);
|
||||
const [speed, setSpeed] = useState('1');
|
||||
const [mode, setMode] = useState('cool');
|
||||
const [tempValue, setTempValue] = useState('26');
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
try {
|
||||
const [telemetryData] = await Promise.all([
|
||||
getTelemetry({ deviceKey, limit: 50 }).catch(() => [] as any[]),
|
||||
]);
|
||||
setMetrics(normalizeRealtime(telemetryData));
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [deviceKey]);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
const interval = setInterval(loadData, 30000);
|
||||
return () => clearInterval(interval);
|
||||
}, [loadData]);
|
||||
|
||||
const handleSend = async (action: string, value?: any) => {
|
||||
setSending(true);
|
||||
try {
|
||||
await sendControl({ deviceKey, action, value });
|
||||
setSnackMsg(`命令已发送: ${action}`);
|
||||
setSnackVisible(true);
|
||||
if (action === 'power') {
|
||||
setIsOn(!!value);
|
||||
}
|
||||
} catch (err: any) {
|
||||
const msg = extractErrorMessage(err);
|
||||
setSnackMsg(`发送失败: ${msg}`);
|
||||
setSnackVisible(true);
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggle = (newVal: boolean) => {
|
||||
handleSend('power', newVal ? 'on' : 'off');
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<SafeAreaView style={styles.center}>
|
||||
<ActivityIndicator size="large" />
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container} edges={['bottom']}>
|
||||
<ScrollView contentContainerStyle={styles.content}>
|
||||
<Card style={[styles.card, styles.headerCard]} mode="elevated">
|
||||
<Card.Content>
|
||||
<View style={styles.headerRow}>
|
||||
<View>
|
||||
<Text variant="headlineSmall" style={styles.deviceName}>{deviceName}</Text>
|
||||
<Text variant="bodySmall" style={styles.deviceKey}>Key: {deviceKey}</Text>
|
||||
</View>
|
||||
<View style={styles.powerRow}>
|
||||
<Text style={styles.powerLabel}>{isOn ? '开启' : '关闭'}</Text>
|
||||
<Switch
|
||||
value={isOn}
|
||||
onValueChange={handleToggle}
|
||||
disabled={sending}
|
||||
color={'#7A9E7E'}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
|
||||
<Card style={styles.card}>
|
||||
<Card.Content>
|
||||
<Text variant="titleMedium" style={styles.sectionTitle}>控制面板</Text>
|
||||
|
||||
<Text style={styles.controlLabel}>运行模式</Text>
|
||||
<SegmentedButtons
|
||||
value={mode}
|
||||
onValueChange={setMode}
|
||||
buttons={[
|
||||
{ value: 'cool', label: '制冷' },
|
||||
{ value: 'heat', label: '制热' },
|
||||
{ value: 'fan', label: '通风' },
|
||||
{ value: 'auto', label: '自动' },
|
||||
]}
|
||||
style={styles.segmented}
|
||||
theme={{ colors: { primary: '#7A9E7E' } }}
|
||||
/>
|
||||
|
||||
<Divider style={styles.divider} />
|
||||
|
||||
<Text style={styles.controlLabel}>风速</Text>
|
||||
<SegmentedButtons
|
||||
value={speed}
|
||||
onValueChange={setSpeed}
|
||||
buttons={[
|
||||
{ value: '0', label: '自动' },
|
||||
{ value: '1', label: '低' },
|
||||
{ value: '2', label: '中' },
|
||||
{ value: '3', label: '高' },
|
||||
]}
|
||||
style={styles.segmented}
|
||||
theme={{ colors: { primary: '#7A9E7E' } }}
|
||||
/>
|
||||
|
||||
<Divider style={styles.divider} />
|
||||
|
||||
<Text style={styles.controlLabel}>目标温度</Text>
|
||||
<View style={styles.tempRow}>
|
||||
<TextInput
|
||||
mode="outlined"
|
||||
keyboardType="numeric"
|
||||
value={tempValue}
|
||||
onChangeText={setTempValue}
|
||||
style={styles.tempInput}
|
||||
right={<TextInput.Affix text="℃" />}
|
||||
/>
|
||||
<Button
|
||||
mode="contained"
|
||||
onPress={() => handleSend('set_temp', parseInt(tempValue, 10) || 26)}
|
||||
disabled={sending}
|
||||
style={styles.sendBtn}
|
||||
buttonColor="#7A9E7E"
|
||||
>
|
||||
设置
|
||||
</Button>
|
||||
</View>
|
||||
|
||||
<Divider style={styles.divider} />
|
||||
|
||||
<View style={styles.actionButtons}>
|
||||
<Button
|
||||
mode="outlined"
|
||||
onPress={() => handleSend('fan_on')}
|
||||
disabled={sending}
|
||||
style={styles.actionBtn}
|
||||
icon="fan"
|
||||
textColor="#5C7D60"
|
||||
theme={{ colors: { outline: '#7A9E7E' } }}
|
||||
>
|
||||
开启风扇
|
||||
</Button>
|
||||
<Button
|
||||
mode="outlined"
|
||||
onPress={() => handleSend('fan_off')}
|
||||
disabled={sending}
|
||||
style={styles.actionBtn}
|
||||
icon="fan-off"
|
||||
textColor="#5C7D60"
|
||||
theme={{ colors: { outline: '#7A9E7E' } }}
|
||||
>
|
||||
关闭风扇
|
||||
</Button>
|
||||
</View>
|
||||
<View style={styles.actionButtons}>
|
||||
<Button
|
||||
mode="outlined"
|
||||
onPress={() => handleSend('dehumidifier_on')}
|
||||
disabled={sending}
|
||||
style={styles.actionBtn}
|
||||
icon="water-percent"
|
||||
textColor="#5C7D60"
|
||||
theme={{ colors: { outline: '#7A9E7E' } }}
|
||||
>
|
||||
开启除湿
|
||||
</Button>
|
||||
<Button
|
||||
mode="outlined"
|
||||
onPress={() => handleSend('dehumidifier_off')}
|
||||
disabled={sending}
|
||||
style={styles.actionBtn}
|
||||
icon="water-off"
|
||||
textColor="#5C7D60"
|
||||
theme={{ colors: { outline: '#7A9E7E' } }}
|
||||
>
|
||||
关闭除湿
|
||||
</Button>
|
||||
</View>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
|
||||
<Text variant="titleLarge" style={styles.sectionTitle}>实时数据</Text>
|
||||
{metrics.length === 0 ? (
|
||||
<Card style={styles.emptyCard}>
|
||||
<Card.Content>
|
||||
<Text style={styles.emptyText}>暂无遥测数据</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
) : (
|
||||
<View style={styles.metricsGrid}>
|
||||
{metrics.map((m) => {
|
||||
const color = m.status === 'danger' ? '#D4847A' : m.status === 'warn' ? '#D4B87A' : '#7A9E7E';
|
||||
return (
|
||||
<Card key={m.key} style={[styles.metricCard, { borderLeftColor: color, borderLeftWidth: 4 }]}>
|
||||
<Card.Content style={styles.metricContent}>
|
||||
<Text variant="labelMedium" style={styles.metricName}>{m.name}</Text>
|
||||
<Text style={[styles.metricValue, { color }]}>
|
||||
{formatNumber(m.value, 1)}
|
||||
<Text style={styles.metricUnit}> {m.unit}</Text>
|
||||
</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
</ScrollView>
|
||||
|
||||
<Snackbar
|
||||
visible={snackVisible}
|
||||
onDismiss={() => setSnackVisible(false)}
|
||||
duration={3000}
|
||||
>
|
||||
{snackMsg}
|
||||
</Snackbar>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#FAF8F5',
|
||||
},
|
||||
center: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
content: {
|
||||
padding: 16,
|
||||
paddingBottom: 32,
|
||||
},
|
||||
card: {
|
||||
marginBottom: 16,
|
||||
borderRadius: 14,
|
||||
},
|
||||
headerCard: {
|
||||
borderRadius: 20,
|
||||
backgroundColor: '#FDFAF5',
|
||||
borderWidth: 1,
|
||||
borderColor: '#E8E4DE',
|
||||
},
|
||||
headerRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
},
|
||||
deviceName: {
|
||||
color: '#2D2A26',
|
||||
fontWeight: '600',
|
||||
},
|
||||
deviceKey: {
|
||||
color: '#B8B3AA',
|
||||
marginTop: 4,
|
||||
},
|
||||
powerRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
},
|
||||
powerLabel: {
|
||||
fontSize: 14,
|
||||
color: '#8C8780',
|
||||
},
|
||||
sectionTitle: {
|
||||
color: '#2D2A26',
|
||||
fontWeight: '600',
|
||||
marginBottom: 12,
|
||||
},
|
||||
controlLabel: {
|
||||
fontSize: 14,
|
||||
color: '#8C8780',
|
||||
marginBottom: 8,
|
||||
marginTop: 8,
|
||||
},
|
||||
segmented: {
|
||||
marginBottom: 8,
|
||||
},
|
||||
divider: {
|
||||
marginVertical: 12,
|
||||
},
|
||||
tempRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 12,
|
||||
},
|
||||
tempInput: {
|
||||
flex: 1,
|
||||
},
|
||||
sendBtn: {
|
||||
borderRadius: 999,
|
||||
},
|
||||
actionButtons: {
|
||||
flexDirection: 'row',
|
||||
gap: 12,
|
||||
marginBottom: 8,
|
||||
},
|
||||
actionBtn: {
|
||||
flex: 1,
|
||||
borderRadius: 999,
|
||||
},
|
||||
metricsGrid: {
|
||||
flexDirection: 'row',
|
||||
flexWrap: 'wrap',
|
||||
gap: 12,
|
||||
},
|
||||
metricCard: {
|
||||
flexBasis: '47%',
|
||||
flexGrow: 1,
|
||||
backgroundColor: '#FDFAF5',
|
||||
borderRadius: 14,
|
||||
borderWidth: 1,
|
||||
borderColor: '#E8E4DE',
|
||||
},
|
||||
metricContent: {
|
||||
paddingVertical: 8,
|
||||
},
|
||||
metricName: {
|
||||
opacity: 0.7,
|
||||
marginBottom: 4,
|
||||
},
|
||||
metricValue: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
metricUnit: {
|
||||
fontSize: 14,
|
||||
fontWeight: 'normal',
|
||||
opacity: 0.6,
|
||||
},
|
||||
emptyCard: {
|
||||
marginBottom: 12,
|
||||
backgroundColor: '#F5F0E8',
|
||||
},
|
||||
emptyText: {
|
||||
textAlign: 'center',
|
||||
color: '#B8B3AA',
|
||||
paddingVertical: 8,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,245 @@
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import { StyleSheet, View, FlatList, RefreshControl } from 'react-native';
|
||||
import { Text, Card, useTheme, ActivityIndicator, Surface, Searchbar, IconButton } from 'react-native-paper';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import { getDevices } from '../api/devices';
|
||||
import { formatRelativeTime } from '../utils/format';
|
||||
import type { Device } from '../types';
|
||||
|
||||
export default function DevicesScreen() {
|
||||
const theme = useTheme();
|
||||
const navigation = useNavigation<any>();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [devices, setDevices] = useState<Device[]>([]);
|
||||
const [filteredDevices, setFilteredDevices] = useState<Device[]>([]);
|
||||
const [search, setSearch] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const loadData = useCallback(async (isRefresh = false) => {
|
||||
if (isRefresh) setRefreshing(true);
|
||||
try {
|
||||
const data = await getDevices();
|
||||
setDevices(data);
|
||||
setFilteredDevices(data);
|
||||
setError(null);
|
||||
} catch (err: any) {
|
||||
setError(err?.message || '加载失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!search.trim()) {
|
||||
setFilteredDevices(devices);
|
||||
} else {
|
||||
const lower = search.toLowerCase();
|
||||
setFilteredDevices(
|
||||
devices.filter(
|
||||
(d) =>
|
||||
d.name.toLowerCase().includes(lower) ||
|
||||
d.deviceKey.toLowerCase().includes(lower) ||
|
||||
(d.kind || '').toLowerCase().includes(lower),
|
||||
),
|
||||
);
|
||||
}
|
||||
}, [search, devices]);
|
||||
|
||||
const isControllable = (device: Device) => {
|
||||
const kind = (device.kind || device.type || '').toLowerCase();
|
||||
return kind === 'actuator' || kind === 'controller' || kind === 'fan' || kind === 'ac' || kind === 'dehumidifier';
|
||||
};
|
||||
|
||||
const getDeviceIcon = (device: Device) => {
|
||||
const kind = (device.kind || device.type || '').toLowerCase();
|
||||
const name = device.name.toLowerCase();
|
||||
if (name.includes('fan') || kind.includes('fan')) return 'fan';
|
||||
if (name.includes('ac') || name.includes('空调') || kind.includes('ac')) return 'air-conditioner';
|
||||
if (name.includes('humid') || name.includes('除湿') || kind.includes('humid')) return 'water-percent';
|
||||
if (name.includes('light') || name.includes('灯') || kind.includes('light')) return 'lightbulb';
|
||||
if (name.includes('sensor') || kind.includes('sensor')) return 'thermometer';
|
||||
if (name.includes('camera') || kind.includes('camera')) return 'video';
|
||||
return 'router-wireless';
|
||||
};
|
||||
|
||||
const renderItem = ({ item }: { item: Device }) => {
|
||||
const isOnline = item.onlineStatus === 'online' || item.status === 'online';
|
||||
const controllable = isControllable(item);
|
||||
return (
|
||||
<Card
|
||||
style={styles.card}
|
||||
onPress={controllable ? () => navigation.navigate('DeviceControl', { deviceKey: item.deviceKey, deviceName: item.name }) : undefined}
|
||||
>
|
||||
<Card.Content style={styles.cardContent}>
|
||||
<View style={styles.deviceLeft}>
|
||||
<View style={[styles.iconBox, { backgroundColor: isOnline ? '#E8F0E9' : '#F5F0E8' }]}>
|
||||
<IconButton icon={getDeviceIcon(item)} size={24} iconColor={isOnline ? '#7A9E7E' : '#B8B3AA'} />
|
||||
</View>
|
||||
<View style={styles.deviceInfo}>
|
||||
<Text variant="bodyMedium" style={styles.deviceName}>{item.name}</Text>
|
||||
<Text variant="bodySmall" style={styles.deviceKey}>{item.deviceKey}</Text>
|
||||
<View style={styles.tagRow}>
|
||||
<Text variant="bodySmall" style={styles.deviceKind}>{item.kind || item.type || '设备'}</Text>
|
||||
{item.model ? <Text variant="bodySmall" style={styles.deviceModel}> · {item.model}</Text> : null}
|
||||
</View>
|
||||
{item.lastSeen ? (
|
||||
<Text variant="bodySmall" style={styles.deviceTime}>最后在线: {formatRelativeTime(item.lastSeen)}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.deviceRight}>
|
||||
<Surface style={[styles.statusBadge, { backgroundColor: isOnline ? '#7A9E7E' : '#B8B3AA' }]}>
|
||||
<Text style={styles.statusText}>{isOnline ? '在线' : '离线'}</Text>
|
||||
</Surface>
|
||||
{controllable ? (
|
||||
<IconButton icon="chevron-right" size={24} iconColor="#B8B3AA" />
|
||||
) : null}
|
||||
</View>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<SafeAreaView style={styles.center}>
|
||||
<ActivityIndicator size="large" />
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container} edges={['bottom']}>
|
||||
<View style={styles.searchContainer}>
|
||||
<Searchbar
|
||||
placeholder="搜索设备..."
|
||||
value={search}
|
||||
onChangeText={setSearch}
|
||||
style={styles.searchbar}
|
||||
/>
|
||||
</View>
|
||||
<FlatList
|
||||
data={filteredDevices}
|
||||
keyExtractor={(item) => item.id}
|
||||
renderItem={renderItem}
|
||||
contentContainerStyle={styles.list}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
|
||||
}
|
||||
ListEmptyComponent={
|
||||
error ? (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Text style={styles.emptyText}>{error}</Text>
|
||||
</View>
|
||||
) : (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Text style={styles.emptyText}>暂无设备</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#FAF8F5',
|
||||
},
|
||||
center: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
searchContainer: {
|
||||
padding: 16,
|
||||
paddingBottom: 8,
|
||||
},
|
||||
searchbar: {
|
||||
borderRadius: 14,
|
||||
backgroundColor: '#FFFFFF',
|
||||
},
|
||||
list: {
|
||||
padding: 16,
|
||||
paddingTop: 8,
|
||||
paddingBottom: 32,
|
||||
},
|
||||
card: {
|
||||
marginBottom: 12,
|
||||
borderRadius: 14,
|
||||
backgroundColor: '#FFFFFF',
|
||||
},
|
||||
cardContent: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
paddingVertical: 4,
|
||||
},
|
||||
deviceLeft: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
flex: 1,
|
||||
},
|
||||
iconBox: {
|
||||
borderRadius: 12,
|
||||
marginRight: 8,
|
||||
},
|
||||
deviceInfo: {
|
||||
flex: 1,
|
||||
},
|
||||
deviceName: {
|
||||
color: '#2D2A26',
|
||||
fontWeight: '500',
|
||||
},
|
||||
deviceKey: {
|
||||
color: '#B8B3AA',
|
||||
fontSize: 12,
|
||||
marginTop: 2,
|
||||
},
|
||||
tagRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
marginTop: 2,
|
||||
},
|
||||
deviceKind: {
|
||||
color: '#8C8780',
|
||||
},
|
||||
deviceModel: {
|
||||
color: '#B8B3AA',
|
||||
},
|
||||
deviceTime: {
|
||||
color: '#B8B3AA',
|
||||
marginTop: 2,
|
||||
},
|
||||
deviceRight: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
},
|
||||
statusBadge: {
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 4,
|
||||
borderRadius: 14,
|
||||
elevation: 0,
|
||||
},
|
||||
statusText: {
|
||||
color: 'white',
|
||||
fontSize: 12,
|
||||
fontWeight: '500',
|
||||
},
|
||||
emptyContainer: {
|
||||
alignItems: 'center',
|
||||
paddingTop: 64,
|
||||
},
|
||||
emptyText: {
|
||||
color: '#B8B3AA',
|
||||
fontSize: 16,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import React, { useState } from 'react';
|
||||
import { StyleSheet, View, KeyboardAvoidingView, Platform, ScrollView, Alert } from 'react-native';
|
||||
import { Text, TextInput, Button, Card, ActivityIndicator } from 'react-native-paper';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
|
||||
export default function LoginScreen() {
|
||||
const navigation = useNavigation<any>();
|
||||
const { login, isLoading, error } = useAuthStore();
|
||||
const [username, setUsername] = useState('admin');
|
||||
const [password, setPassword] = useState('silk@123');
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
|
||||
const handleLogin = async () => {
|
||||
if (!username.trim() || !password.trim()) {
|
||||
Alert.alert('提示', '请输入用户名和密码');
|
||||
return;
|
||||
}
|
||||
const success = await login(username.trim(), password);
|
||||
if (success) {
|
||||
navigation.reset({
|
||||
index: 0,
|
||||
routes: [{ name: 'Main' }],
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container}>
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
|
||||
style={styles.flex}
|
||||
>
|
||||
<ScrollView contentContainerStyle={styles.scrollContent} keyboardShouldPersistTaps="handled">
|
||||
<View style={styles.header}>
|
||||
<Text style={[styles.title, { color: '#5C7D60' }]}>蚕房监控</Text>
|
||||
<Text style={styles.subtitle}>智慧蚕业环境监测系统</Text>
|
||||
</View>
|
||||
|
||||
<Card style={styles.card} mode="elevated">
|
||||
<Card.Content style={styles.cardContent}>
|
||||
<TextInput
|
||||
label="用户名"
|
||||
value={username}
|
||||
onChangeText={setUsername}
|
||||
mode="outlined"
|
||||
left={<TextInput.Icon icon="account" />}
|
||||
style={styles.input}
|
||||
activeOutlineColor="#7A9E7E"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
/>
|
||||
<TextInput
|
||||
label="密码"
|
||||
value={password}
|
||||
onChangeText={setPassword}
|
||||
mode="outlined"
|
||||
left={<TextInput.Icon icon="lock" />}
|
||||
right={
|
||||
<TextInput.Icon
|
||||
icon={showPassword ? 'eye-off' : 'eye'}
|
||||
onPress={() => setShowPassword(!showPassword)}
|
||||
/>
|
||||
}
|
||||
secureTextEntry={!showPassword}
|
||||
style={styles.input}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
/>
|
||||
|
||||
{error ? <Text style={styles.errorText}>{error}</Text> : null}
|
||||
|
||||
<Button
|
||||
mode="contained"
|
||||
onPress={handleLogin}
|
||||
style={styles.button}
|
||||
buttonColor="#7A9E7E"
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? <ActivityIndicator color="white" size="small" /> : '登录'}
|
||||
</Button>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
</ScrollView>
|
||||
</KeyboardAvoidingView>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#FAF8F5',
|
||||
},
|
||||
flex: {
|
||||
flex: 1,
|
||||
},
|
||||
scrollContent: {
|
||||
flexGrow: 1,
|
||||
justifyContent: 'center',
|
||||
padding: 24,
|
||||
},
|
||||
header: {
|
||||
alignItems: 'center',
|
||||
marginBottom: 32,
|
||||
},
|
||||
title: {
|
||||
fontSize: 32,
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
subtitle: {
|
||||
fontSize: 16,
|
||||
color: '#8C8780',
|
||||
marginTop: 8,
|
||||
},
|
||||
card: {
|
||||
borderRadius: 20,
|
||||
backgroundColor: '#F5F0E8',
|
||||
},
|
||||
cardContent: {
|
||||
padding: 8,
|
||||
},
|
||||
input: {
|
||||
marginBottom: 16,
|
||||
},
|
||||
errorText: {
|
||||
color: '#D4847A',
|
||||
fontSize: 14,
|
||||
marginBottom: 12,
|
||||
},
|
||||
button: {
|
||||
marginTop: 8,
|
||||
paddingVertical: 6,
|
||||
borderRadius: 999,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,321 @@
|
||||
import React, { useEffect, useState, useCallback, useRef } from 'react';
|
||||
import { StyleSheet, View, ScrollView, RefreshControl } from 'react-native';
|
||||
import { Text, Card, useTheme, ActivityIndicator, Surface } from 'react-native-paper';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { useRoute } from '@react-navigation/native';
|
||||
import { getRoom } from '../api/rooms';
|
||||
import { getTelemetry, normalizeRealtime, fetchTrend } from '../api/telemetry';
|
||||
import { getDevices } from '../api/devices';
|
||||
import { MiniChart } from '../components/MiniChart';
|
||||
import { formatRelativeTime } from '../utils/format';
|
||||
import type { Room, RealtimeMetric, Device, TrendPoint } from '../types';
|
||||
|
||||
export default function RoomDetailScreen() {
|
||||
const theme = useTheme();
|
||||
const route = useRoute<any>();
|
||||
const { roomId, roomName } = route.params;
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [room, setRoom] = useState<Room | null>(null);
|
||||
const [metrics, setMetrics] = useState<RealtimeMetric[]>([]);
|
||||
const [devices, setDevices] = useState<Device[]>([]);
|
||||
const [trend, setTrend] = useState<TrendPoint[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
const loadData = useCallback(async (isRefresh = false) => {
|
||||
if (isRefresh) setRefreshing(true);
|
||||
try {
|
||||
const [roomData, devicesData, telemetryData] = await Promise.all([
|
||||
getRoom(roomId).catch(() => null),
|
||||
getDevices({ roomId }).catch(() => [] as Device[]),
|
||||
getTelemetry({ limit: 100 }).catch(() => [] as any[]),
|
||||
]);
|
||||
|
||||
setRoom(roomData);
|
||||
setDevices(devicesData);
|
||||
setMetrics(normalizeRealtime(telemetryData));
|
||||
|
||||
// Build trend from telemetry
|
||||
const trendData = await fetchTrend(24).catch(() => [] as TrendPoint[]);
|
||||
setTrend(trendData);
|
||||
setError(null);
|
||||
} catch (err: any) {
|
||||
setError(err?.message || '加载失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
}
|
||||
}, [roomId]);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
intervalRef.current = setInterval(() => loadData(), 30000);
|
||||
return () => {
|
||||
if (intervalRef.current) clearInterval(intervalRef.current);
|
||||
};
|
||||
}, [loadData]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<SafeAreaView style={styles.center}>
|
||||
<ActivityIndicator size="large" />
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const statusColor = (status: RealtimeMetric['status']) => {
|
||||
switch (status) {
|
||||
case 'danger': return '#D4847A';
|
||||
case 'warn': return '#D4B87A';
|
||||
default: return '#7A9E7E';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container} edges={['bottom']}>
|
||||
<ScrollView
|
||||
contentContainerStyle={styles.content}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
|
||||
}
|
||||
>
|
||||
{error ? (
|
||||
<Card style={styles.errorCard}>
|
||||
<Card.Content>
|
||||
<Text style={{ color: '#D4847A' }}>{error}</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
<Card style={styles.infoCard} mode="elevated">
|
||||
<Card.Content>
|
||||
<Text variant="headlineSmall" style={styles.roomName}>{room?.name || roomName}</Text>
|
||||
{room?.code ? <Text style={styles.infoText}>编号: {room.code}</Text> : null}
|
||||
{room?.location ? <Text style={styles.infoText}>位置: {room.location}</Text> : null}
|
||||
{room?.description ? <Text style={styles.infoText}>描述: {room.description}</Text> : null}
|
||||
{room?.status ? <Text style={styles.infoText}>状态: {room.status}</Text> : null}
|
||||
</Card.Content>
|
||||
</Card>
|
||||
|
||||
<Text variant="titleLarge" style={styles.sectionTitle}>实时环境指标</Text>
|
||||
{metrics.length === 0 ? (
|
||||
<Card style={styles.emptyCard}>
|
||||
<Card.Content>
|
||||
<Text style={styles.emptyText}>暂无遥测数据</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
) : (
|
||||
<View style={styles.metricsGrid}>
|
||||
{metrics.map((m) => (
|
||||
<Card key={m.key} style={[styles.metricCard, { borderLeftColor: statusColor(m.status), borderLeftWidth: 4 }]}>
|
||||
<Card.Content style={styles.metricContent}>
|
||||
<Text variant="labelMedium" style={styles.metricName}>{m.name}</Text>
|
||||
<Text style={[styles.metricValue, { color: statusColor(m.status) }]}>
|
||||
{m.value.toFixed(1)}
|
||||
<Text style={styles.metricUnit}> {m.unit}</Text>
|
||||
</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
|
||||
<Text variant="titleLarge" style={styles.sectionTitle}>24小时趋势</Text>
|
||||
{trend.length > 0 ? (
|
||||
<Card style={styles.chartCard} mode="elevated">
|
||||
<Card.Content>
|
||||
<Text style={styles.chartMetricLabel}>温度 (°C)</Text>
|
||||
<MiniChart data={trend} metric="temp" color="#D4847A" height={100} />
|
||||
<Text style={styles.chartMetricLabel}>湿度 (%)</Text>
|
||||
<MiniChart data={trend} metric="humidity" color="#6B8F71" height={100} />
|
||||
<View style={styles.legendRow}>
|
||||
<View style={styles.legendItem}>
|
||||
<View style={[styles.legendDot, { backgroundColor: '#D4847A' }]} />
|
||||
<Text style={styles.legendText}>温度</Text>
|
||||
</View>
|
||||
<View style={styles.legendItem}>
|
||||
<View style={[styles.legendDot, { backgroundColor: '#6B8F71' }]} />
|
||||
<Text style={styles.legendText}>湿度</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
) : (
|
||||
<Card style={styles.emptyCard}>
|
||||
<Card.Content>
|
||||
<Text style={styles.emptyText}>暂无趋势数据</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Text variant="titleLarge" style={styles.sectionTitle}>设备列表</Text>
|
||||
{devices.length === 0 ? (
|
||||
<Card style={styles.emptyCard}>
|
||||
<Card.Content>
|
||||
<Text style={styles.emptyText}>暂无设备</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
) : (
|
||||
devices.map((device) => (
|
||||
<Card key={device.id} style={styles.deviceCard}>
|
||||
<Card.Content style={styles.deviceContent}>
|
||||
<View style={styles.deviceInfo}>
|
||||
<Text variant="bodyMedium" style={styles.deviceName}>{device.name}</Text>
|
||||
<Text variant="bodySmall" style={styles.deviceKey}>Key: {device.deviceKey}</Text>
|
||||
{device.lastSeen ? (
|
||||
<Text variant="bodySmall" style={styles.deviceTime}>
|
||||
最后在线: {formatRelativeTime(device.lastSeen)}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Surface style={[styles.deviceBadge, { backgroundColor: device.onlineStatus === 'online' || device.status === 'online' ? '#7A9E7E' : '#B8B3AA' }]}>
|
||||
<Text style={styles.deviceBadgeText}>
|
||||
{device.onlineStatus === 'online' || device.status === 'online' ? '在线' : '离线'}
|
||||
</Text>
|
||||
</Surface>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
))
|
||||
)}
|
||||
</ScrollView>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#FAF8F5',
|
||||
},
|
||||
center: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
content: {
|
||||
padding: 16,
|
||||
paddingBottom: 32,
|
||||
},
|
||||
errorCard: {
|
||||
marginBottom: 12,
|
||||
backgroundColor: '#F9E8E5',
|
||||
},
|
||||
infoCard: {
|
||||
borderRadius: 12,
|
||||
marginBottom: 8,
|
||||
},
|
||||
roomName: {
|
||||
color: '#2D2A26',
|
||||
fontWeight: '600',
|
||||
marginBottom: 8,
|
||||
},
|
||||
infoText: {
|
||||
color: '#8C8780',
|
||||
marginTop: 4,
|
||||
},
|
||||
sectionTitle: {
|
||||
marginTop: 20,
|
||||
marginBottom: 12,
|
||||
color: '#2D2A26',
|
||||
fontWeight: '600',
|
||||
},
|
||||
metricsGrid: {
|
||||
flexDirection: 'row',
|
||||
flexWrap: 'wrap',
|
||||
gap: 12,
|
||||
},
|
||||
metricCard: {
|
||||
flexBasis: '47%',
|
||||
flexGrow: 1,
|
||||
},
|
||||
metricContent: {
|
||||
paddingVertical: 8,
|
||||
},
|
||||
metricName: {
|
||||
opacity: 0.7,
|
||||
marginBottom: 4,
|
||||
},
|
||||
metricValue: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
metricUnit: {
|
||||
fontSize: 14,
|
||||
fontWeight: 'normal',
|
||||
opacity: 0.6,
|
||||
},
|
||||
chartCard: {
|
||||
borderRadius: 12,
|
||||
},
|
||||
chartMetricLabel: {
|
||||
fontSize: 12,
|
||||
color: '#8C8780',
|
||||
marginTop: 8,
|
||||
marginBottom: 4,
|
||||
},
|
||||
legendRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'center',
|
||||
gap: 24,
|
||||
marginTop: 8,
|
||||
},
|
||||
legendItem: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
},
|
||||
legendDot: {
|
||||
width: 12,
|
||||
height: 12,
|
||||
borderRadius: 6,
|
||||
},
|
||||
legendText: {
|
||||
fontSize: 12,
|
||||
color: '#8C8780',
|
||||
},
|
||||
emptyCard: {
|
||||
marginBottom: 12,
|
||||
backgroundColor: '#F5F0E8',
|
||||
},
|
||||
emptyText: {
|
||||
textAlign: 'center',
|
||||
color: '#B8B3AA',
|
||||
paddingVertical: 8,
|
||||
},
|
||||
deviceCard: {
|
||||
marginBottom: 8,
|
||||
borderRadius: 8,
|
||||
},
|
||||
deviceContent: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
paddingVertical: 8,
|
||||
},
|
||||
deviceInfo: {
|
||||
flex: 1,
|
||||
},
|
||||
deviceName: {
|
||||
fontWeight: '500',
|
||||
},
|
||||
deviceKey: {
|
||||
color: '#B8B3AA',
|
||||
marginTop: 2,
|
||||
},
|
||||
deviceTime: {
|
||||
color: '#B8B3AA',
|
||||
marginTop: 2,
|
||||
},
|
||||
deviceBadge: {
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 4,
|
||||
borderRadius: 12,
|
||||
elevation: 0,
|
||||
},
|
||||
deviceBadgeText: {
|
||||
color: 'white',
|
||||
fontSize: 12,
|
||||
fontWeight: '500',
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import { StyleSheet, View, FlatList, RefreshControl } from 'react-native';
|
||||
import { Text, Card, useTheme, ActivityIndicator, IconButton } from 'react-native-paper';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import { getRooms } from '../api/rooms';
|
||||
import { formatRelativeTime } from '../utils/format';
|
||||
import type { Room } from '../types';
|
||||
|
||||
export default function RoomsScreen() {
|
||||
const theme = useTheme();
|
||||
const navigation = useNavigation<any>();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [rooms, setRooms] = useState<Room[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const loadData = useCallback(async (isRefresh = false) => {
|
||||
if (isRefresh) setRefreshing(true);
|
||||
try {
|
||||
const data = await getRooms();
|
||||
setRooms(data);
|
||||
setError(null);
|
||||
} catch (err: any) {
|
||||
setError(err?.message || '加载失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
const getStatusColor = (status?: string) => {
|
||||
switch (status) {
|
||||
case 'active':
|
||||
case 'running':
|
||||
return '#7A9E7E';
|
||||
case 'alarm':
|
||||
return '#D4847A';
|
||||
case 'idle':
|
||||
case 'inactive':
|
||||
return '#B8B3AA';
|
||||
default:
|
||||
return '#6B8F71';
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusLabel = (status?: string) => {
|
||||
switch (status) {
|
||||
case 'active': return '运行中';
|
||||
case 'running': return '运行中';
|
||||
case 'idle': return '空闲';
|
||||
case 'inactive': return '停用';
|
||||
case 'alarm': return '告警';
|
||||
default: return status || '未知';
|
||||
}
|
||||
};
|
||||
|
||||
const renderItem = ({ item }: { item: Room }) => (
|
||||
<Card
|
||||
style={styles.card}
|
||||
onPress={() => navigation.navigate('RoomDetail', { roomId: item.id, roomName: item.name })}
|
||||
>
|
||||
<Card.Content style={styles.cardContent}>
|
||||
<View style={styles.roomInfo}>
|
||||
<View style={styles.roomHeader}>
|
||||
<Text variant="titleMedium" style={styles.roomName}>{item.name}</Text>
|
||||
<View style={[styles.statusBadge, { backgroundColor: getStatusColor(item.status) }]}>
|
||||
<Text style={styles.statusText}>{getStatusLabel(item.status)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
{item.code ? <Text variant="bodySmall" style={styles.roomCode}>编号: {item.code}</Text> : null}
|
||||
{item.location ? <Text variant="bodySmall" style={styles.roomLocation}>📍 {item.location}</Text> : null}
|
||||
{item.description ? <Text variant="bodySmall" style={styles.roomDesc} numberOfLines={2}>{item.description}</Text> : null}
|
||||
</View>
|
||||
<IconButton icon="chevron-right" size={28} iconColor="#B8B3AA" />
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<SafeAreaView style={styles.center}>
|
||||
<ActivityIndicator size="large" />
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container} edges={['bottom']}>
|
||||
<FlatList
|
||||
data={rooms}
|
||||
keyExtractor={(item) => item.id}
|
||||
renderItem={renderItem}
|
||||
contentContainerStyle={styles.list}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
|
||||
}
|
||||
ListEmptyComponent={
|
||||
error ? (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Text style={styles.emptyText}>{error}</Text>
|
||||
</View>
|
||||
) : (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Text style={styles.emptyText}>暂无蚕房数据</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#FAF8F5',
|
||||
},
|
||||
center: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
list: {
|
||||
padding: 16,
|
||||
paddingBottom: 32,
|
||||
},
|
||||
card: {
|
||||
marginBottom: 12,
|
||||
borderRadius: 14,
|
||||
backgroundColor: '#FFFFFF',
|
||||
},
|
||||
cardContent: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
},
|
||||
roomInfo: {
|
||||
flex: 1,
|
||||
},
|
||||
roomHeader: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
marginBottom: 4,
|
||||
},
|
||||
roomName: {
|
||||
color: '#2D2A26',
|
||||
fontWeight: '600',
|
||||
},
|
||||
statusBadge: {
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 3,
|
||||
borderRadius: 12,
|
||||
},
|
||||
statusText: {
|
||||
color: 'white',
|
||||
fontSize: 11,
|
||||
fontWeight: '500',
|
||||
},
|
||||
roomCode: {
|
||||
color: '#B8B3AA',
|
||||
marginBottom: 2,
|
||||
},
|
||||
roomLocation: {
|
||||
color: '#8C8780',
|
||||
marginBottom: 2,
|
||||
},
|
||||
roomDesc: {
|
||||
color: '#8C8780',
|
||||
},
|
||||
emptyContainer: {
|
||||
alignItems: 'center',
|
||||
paddingTop: 64,
|
||||
},
|
||||
emptyText: {
|
||||
color: '#B8B3AA',
|
||||
fontSize: 16,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import React, { useState } from 'react';
|
||||
import { StyleSheet, View, Alert, ScrollView } from 'react-native';
|
||||
import { Text, Card, Button, useTheme, Divider, TextInput, List, Avatar } from 'react-native-paper';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { API_BASE_URL } from '@env';
|
||||
|
||||
export default function SettingsScreen() {
|
||||
const theme = useTheme();
|
||||
const navigation = useNavigation<any>();
|
||||
const { user, logout } = useAuthStore();
|
||||
const [apiUrl, setApiUrl] = useState(API_BASE_URL || 'http://localhost:3000/api/v1');
|
||||
|
||||
const handleLogout = () => {
|
||||
Alert.alert('确认退出', '确定要退出登录吗?', [
|
||||
{ text: '取消', style: 'cancel' },
|
||||
{
|
||||
text: '退出',
|
||||
style: 'destructive',
|
||||
onPress: async () => {
|
||||
await logout();
|
||||
},
|
||||
},
|
||||
]);
|
||||
};
|
||||
|
||||
const getRoleLabel = (role?: string) => {
|
||||
switch (role) {
|
||||
case 'admin': return '管理员';
|
||||
case 'operator': return '操作员';
|
||||
case 'viewer': return '查看者';
|
||||
default: return role || '未知';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container} edges={['bottom']}>
|
||||
<ScrollView style={styles.scrollView} contentContainerStyle={styles.content}>
|
||||
<View style={styles.profileSection}>
|
||||
<Avatar.Text
|
||||
size={72}
|
||||
label={user?.username?.charAt(0).toUpperCase() || 'U'}
|
||||
style={{ backgroundColor: theme.colors.primary }}
|
||||
color="white"
|
||||
/>
|
||||
<Text variant="headlineSmall" style={styles.userName}>
|
||||
{user?.fullName || user?.username || '用户'}
|
||||
</Text>
|
||||
<Text style={styles.userRole}>{getRoleLabel(user?.role)}</Text>
|
||||
</View>
|
||||
|
||||
<Card style={styles.card} mode="elevated">
|
||||
<Card.Content>
|
||||
<Text variant="titleMedium" style={styles.sectionTitle}>用户信息</Text>
|
||||
<List.Item
|
||||
title="用户名"
|
||||
description={user?.username || '-'}
|
||||
left={(props) => <List.Icon {...props} icon="account" />}
|
||||
/>
|
||||
<Divider />
|
||||
<List.Item
|
||||
title="邮箱"
|
||||
description={user?.email || '-'}
|
||||
left={(props) => <List.Icon {...props} icon="email" />}
|
||||
/>
|
||||
<Divider />
|
||||
<List.Item
|
||||
title="姓名"
|
||||
description={user?.fullName || '-'}
|
||||
left={(props) => <List.Icon {...props} icon="card-account-details" />}
|
||||
/>
|
||||
<Divider />
|
||||
<List.Item
|
||||
title="角色"
|
||||
description={getRoleLabel(user?.role)}
|
||||
left={(props) => <List.Icon {...props} icon="shield-account" />}
|
||||
/>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
|
||||
<Card style={styles.card}>
|
||||
<Card.Content>
|
||||
<Text variant="titleMedium" style={styles.sectionTitle}>服务器配置</Text>
|
||||
<TextInput
|
||||
label="API 地址"
|
||||
value={apiUrl}
|
||||
onChangeText={setApiUrl}
|
||||
mode="outlined"
|
||||
style={styles.input}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
/>
|
||||
<Text style={styles.hintText}>
|
||||
修改后需重启应用生效。Android 模拟器请使用 10.0.2.2 代替 localhost。
|
||||
</Text>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
|
||||
<Card style={styles.card}>
|
||||
<Card.Content>
|
||||
<Text variant="titleMedium" style={styles.sectionTitle}>关于</Text>
|
||||
<List.Item
|
||||
title="应用名称"
|
||||
description="智慧蚕房"
|
||||
left={(props) => <List.Icon {...props} icon="information" />}
|
||||
/>
|
||||
<Divider />
|
||||
<List.Item
|
||||
title="版本"
|
||||
description="1.0.0"
|
||||
left={(props) => <List.Icon {...props} icon="tag" />}
|
||||
/>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
|
||||
<Button
|
||||
mode="contained"
|
||||
onPress={handleLogout}
|
||||
style={styles.logoutBtn}
|
||||
buttonColor="#D4847A"
|
||||
icon="logout"
|
||||
>
|
||||
退出登录
|
||||
</Button>
|
||||
</ScrollView>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#FAF8F5',
|
||||
},
|
||||
scrollView: {
|
||||
flex: 1,
|
||||
},
|
||||
content: {
|
||||
padding: 16,
|
||||
paddingBottom: 32,
|
||||
},
|
||||
profileSection: {
|
||||
alignItems: 'center',
|
||||
paddingVertical: 24,
|
||||
},
|
||||
userName: {
|
||||
color: '#2D2A26',
|
||||
fontWeight: '600',
|
||||
marginTop: 12,
|
||||
},
|
||||
userRole: {
|
||||
color: '#8C8780',
|
||||
marginTop: 4,
|
||||
},
|
||||
card: {
|
||||
marginBottom: 16,
|
||||
borderRadius: 14,
|
||||
backgroundColor: '#FFFFFF',
|
||||
},
|
||||
sectionTitle: {
|
||||
color: '#2D2A26',
|
||||
fontWeight: '600',
|
||||
marginBottom: 8,
|
||||
},
|
||||
input: {
|
||||
marginTop: 8,
|
||||
},
|
||||
hintText: {
|
||||
fontSize: 12,
|
||||
color: '#B8B3AA',
|
||||
marginTop: 8,
|
||||
},
|
||||
logoutBtn: {
|
||||
marginTop: 16,
|
||||
borderRadius: 999,
|
||||
paddingVertical: 6,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,433 @@
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import { StyleSheet, View, FlatList, RefreshControl, Alert, Modal } from 'react-native';
|
||||
import { Text, Card, Button, Switch, useTheme, ActivityIndicator, TextInput, FAB, IconButton, Surface } from 'react-native-paper';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { getThresholds, createThreshold, updateThreshold, deleteThreshold } from '../api/thresholds';
|
||||
import { extractErrorMessage } from '../api/client';
|
||||
import { getMetricName, getMetricUnit } from '../utils/format';
|
||||
import type { Threshold } from '../types';
|
||||
|
||||
export default function ThresholdsScreen() {
|
||||
const theme = useTheme();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [thresholds, setThresholds] = useState<Threshold[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [modalVisible, setModalVisible] = useState(false);
|
||||
const [editing, setEditing] = useState<Threshold | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
// Form state
|
||||
const [name, setName] = useState('');
|
||||
const [metric, setMetric] = useState('temperature');
|
||||
const [minValue, setMinValue] = useState('20');
|
||||
const [maxValue, setMaxValue] = useState('30');
|
||||
const [debounce, setDebounce] = useState('30');
|
||||
const [severity, setSeverity] = useState('1');
|
||||
const [enabled, setEnabled] = useState(true);
|
||||
|
||||
const loadData = useCallback(async (isRefresh = false) => {
|
||||
if (isRefresh) setRefreshing(true);
|
||||
try {
|
||||
const data = await getThresholds();
|
||||
setThresholds(data);
|
||||
setError(null);
|
||||
} catch (err: any) {
|
||||
setError(err?.message || '加载失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setName('');
|
||||
setMetric('temperature');
|
||||
setMinValue('20');
|
||||
setMaxValue('30');
|
||||
setDebounce('30');
|
||||
setSeverity('1');
|
||||
setEnabled(true);
|
||||
setModalVisible(true);
|
||||
};
|
||||
|
||||
const openEdit = (item: Threshold) => {
|
||||
setEditing(item);
|
||||
setName(item.name || '');
|
||||
setMetric(item.metric || 'temperature');
|
||||
setMinValue(String(item.minValue ?? item.min ?? ''));
|
||||
setMaxValue(String(item.maxValue ?? item.max ?? ''));
|
||||
setDebounce(String(item.debounceSeconds ?? '30'));
|
||||
setSeverity(String(item.severity ?? '1'));
|
||||
setEnabled(item.enabled);
|
||||
setModalVisible(true);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!metric.trim()) {
|
||||
Alert.alert('提示', '请输入监控指标');
|
||||
return;
|
||||
}
|
||||
const payload = {
|
||||
name: name.trim() || undefined,
|
||||
metric: metric.trim(),
|
||||
minValue: parseFloat(minValue) || 0,
|
||||
maxValue: parseFloat(maxValue) || 0,
|
||||
debounceSeconds: parseInt(debounce, 10) || 0,
|
||||
severity: parseInt(severity, 10) || 1,
|
||||
enabled,
|
||||
};
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
if (editing) {
|
||||
await updateThreshold(editing.id, payload);
|
||||
setThresholds((prev) =>
|
||||
prev.map((t) => (t.id === editing.id ? { ...t, ...payload } : t)),
|
||||
);
|
||||
} else {
|
||||
const created = await createThreshold(payload);
|
||||
setThresholds((prev) => [...prev, created]);
|
||||
}
|
||||
setModalVisible(false);
|
||||
} catch (err: any) {
|
||||
Alert.alert('保存失败', extractErrorMessage(err));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = (item: Threshold) => {
|
||||
Alert.alert('确认删除', `确定要删除阈值"${item.name || item.metric}"吗?`, [
|
||||
{ text: '取消', style: 'cancel' },
|
||||
{
|
||||
text: '删除',
|
||||
style: 'destructive',
|
||||
onPress: async () => {
|
||||
try {
|
||||
await deleteThreshold(item.id);
|
||||
setThresholds((prev) => prev.filter((t) => t.id !== item.id));
|
||||
} catch (err: any) {
|
||||
Alert.alert('删除失败', extractErrorMessage(err));
|
||||
}
|
||||
},
|
||||
},
|
||||
]);
|
||||
};
|
||||
|
||||
const getSevColor = (sev: number) => {
|
||||
if (sev >= 3) return '#D4847A';
|
||||
if (sev >= 2) return '#D4B87A';
|
||||
return '#6B8F71';
|
||||
};
|
||||
|
||||
const renderItem = ({ item }: { item: Threshold }) => (
|
||||
<Card style={styles.card}>
|
||||
<Card.Content style={styles.cardContent}>
|
||||
<View style={styles.headerRow}>
|
||||
<View style={styles.titleRow}>
|
||||
<Surface style={[styles.sevDot, { backgroundColor: getSevColor(item.severity) }]}>{null}</Surface>
|
||||
<Text variant="titleMedium" style={styles.thresholdName}>
|
||||
{item.name || getMetricName(item.metric || '')}
|
||||
</Text>
|
||||
</View>
|
||||
<Switch
|
||||
value={item.enabled}
|
||||
onValueChange={async (val) => {
|
||||
try {
|
||||
await updateThreshold(item.id, { enabled: val });
|
||||
setThresholds((prev) =>
|
||||
prev.map((t) => (t.id === item.id ? { ...t, enabled: val } : t)),
|
||||
);
|
||||
} catch (err: any) {
|
||||
Alert.alert('更新失败', extractErrorMessage(err));
|
||||
}
|
||||
}}
|
||||
color={theme.colors.primary}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.rangeRow}>
|
||||
<View style={styles.rangeItem}>
|
||||
<Text style={styles.rangeLabel}>下限</Text>
|
||||
<Text style={styles.rangeValue}>
|
||||
{item.minValue ?? item.min} {getMetricUnit(item.metric || '')}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.rangeItem}>
|
||||
<Text style={styles.rangeLabel}>上限</Text>
|
||||
<Text style={styles.rangeValue}>
|
||||
{item.maxValue ?? item.max} {getMetricUnit(item.metric || '')}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.rangeItem}>
|
||||
<Text style={styles.rangeLabel}>延迟</Text>
|
||||
<Text style={styles.rangeValue}>{item.debounceSeconds}s</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={styles.actionsRow}>
|
||||
<Button mode="text" onPress={() => openEdit(item)} textColor="#5C7D60">
|
||||
编辑
|
||||
</Button>
|
||||
<Button mode="text" onPress={() => handleDelete(item)} textColor="#D4847A">
|
||||
删除
|
||||
</Button>
|
||||
</View>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<SafeAreaView style={styles.center}>
|
||||
<ActivityIndicator size="large" />
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container} edges={['bottom']}>
|
||||
<FlatList
|
||||
data={thresholds}
|
||||
keyExtractor={(item) => item.id}
|
||||
renderItem={renderItem}
|
||||
contentContainerStyle={styles.list}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
|
||||
}
|
||||
ListEmptyComponent={
|
||||
error ? (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Text style={styles.emptyText}>{error}</Text>
|
||||
</View>
|
||||
) : (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Text style={styles.emptyText}>暂无阈值配置</Text>
|
||||
<Text style={styles.emptySubtext}>点击右下角按钮添加阈值</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
<FAB icon="plus" style={styles.fab} onPress={openCreate} color="white" />
|
||||
|
||||
<Modal visible={modalVisible} animationType="slide" transparent>
|
||||
<View style={styles.modalOverlay}>
|
||||
<Card style={styles.modalCard}>
|
||||
<Card.Content>
|
||||
<View style={styles.modalHeader}>
|
||||
<Text variant="titleLarge">{editing ? '编辑阈值' : '新建阈值'}</Text>
|
||||
<IconButton icon="close" onPress={() => setModalVisible(false)} />
|
||||
</View>
|
||||
|
||||
<TextInput
|
||||
label="名称 (可选)"
|
||||
value={name}
|
||||
onChangeText={setName}
|
||||
mode="outlined"
|
||||
style={styles.input}
|
||||
/>
|
||||
<TextInput
|
||||
label="监控指标"
|
||||
value={metric}
|
||||
onChangeText={setMetric}
|
||||
mode="outlined"
|
||||
style={styles.input}
|
||||
placeholder="temperature, humidity, co2..."
|
||||
/>
|
||||
<View style={styles.twoColRow}>
|
||||
<TextInput
|
||||
label="下限"
|
||||
value={minValue}
|
||||
onChangeText={setMinValue}
|
||||
mode="outlined"
|
||||
keyboardType="numeric"
|
||||
style={styles.halfInput}
|
||||
/>
|
||||
<TextInput
|
||||
label="上限"
|
||||
value={maxValue}
|
||||
onChangeText={setMaxValue}
|
||||
mode="outlined"
|
||||
keyboardType="numeric"
|
||||
style={styles.halfInput}
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.twoColRow}>
|
||||
<TextInput
|
||||
label="延迟(秒)"
|
||||
value={debounce}
|
||||
onChangeText={setDebounce}
|
||||
mode="outlined"
|
||||
keyboardType="numeric"
|
||||
style={styles.halfInput}
|
||||
/>
|
||||
<TextInput
|
||||
label="严重级别(1-3)"
|
||||
value={severity}
|
||||
onChangeText={setSeverity}
|
||||
mode="outlined"
|
||||
keyboardType="numeric"
|
||||
style={styles.halfInput}
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.switchRow}>
|
||||
<Text>启用</Text>
|
||||
<Switch value={enabled} onValueChange={setEnabled} color={theme.colors.primary} />
|
||||
</View>
|
||||
|
||||
<View style={styles.modalActions}>
|
||||
<Button mode="outlined" onPress={() => setModalVisible(false)} style={styles.modalBtn}>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
mode="contained"
|
||||
onPress={handleSave}
|
||||
loading={saving}
|
||||
disabled={saving}
|
||||
style={styles.modalBtn}
|
||||
>
|
||||
保存
|
||||
</Button>
|
||||
</View>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
</View>
|
||||
</Modal>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#FAF8F5',
|
||||
},
|
||||
center: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
list: {
|
||||
padding: 16,
|
||||
paddingBottom: 80,
|
||||
},
|
||||
card: {
|
||||
marginBottom: 12,
|
||||
borderRadius: 14,
|
||||
backgroundColor: '#FFFFFF',
|
||||
},
|
||||
cardContent: {
|
||||
paddingVertical: 8,
|
||||
},
|
||||
headerRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: 8,
|
||||
},
|
||||
titleRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
},
|
||||
sevDot: {
|
||||
width: 10,
|
||||
height: 10,
|
||||
borderRadius: 5,
|
||||
elevation: 0,
|
||||
},
|
||||
thresholdName: {
|
||||
color: '#2D2A26',
|
||||
fontWeight: '500',
|
||||
},
|
||||
rangeRow: {
|
||||
flexDirection: 'row',
|
||||
gap: 16,
|
||||
marginBottom: 8,
|
||||
},
|
||||
rangeItem: {
|
||||
flex: 1,
|
||||
},
|
||||
rangeLabel: {
|
||||
fontSize: 12,
|
||||
color: '#B8B3AA',
|
||||
},
|
||||
rangeValue: {
|
||||
fontSize: 16,
|
||||
color: '#2D2A26',
|
||||
fontWeight: '500',
|
||||
marginTop: 2,
|
||||
},
|
||||
actionsRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'flex-end',
|
||||
},
|
||||
emptyContainer: {
|
||||
alignItems: 'center',
|
||||
paddingTop: 64,
|
||||
},
|
||||
emptyText: {
|
||||
color: '#B8B3AA',
|
||||
fontSize: 16,
|
||||
},
|
||||
emptySubtext: {
|
||||
color: '#C4BFB6',
|
||||
fontSize: 14,
|
||||
marginTop: 8,
|
||||
},
|
||||
fab: {
|
||||
position: 'absolute',
|
||||
margin: 16,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
backgroundColor: '#7A9E7E',
|
||||
},
|
||||
modalOverlay: {
|
||||
flex: 1,
|
||||
backgroundColor: 'rgba(0,0,0,0.5)',
|
||||
justifyContent: 'center',
|
||||
padding: 24,
|
||||
},
|
||||
modalCard: {
|
||||
borderRadius: 20,
|
||||
maxHeight: '85%',
|
||||
},
|
||||
modalHeader: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: 16,
|
||||
},
|
||||
input: {
|
||||
marginBottom: 12,
|
||||
},
|
||||
twoColRow: {
|
||||
flexDirection: 'row',
|
||||
gap: 12,
|
||||
},
|
||||
halfInput: {
|
||||
flex: 1,
|
||||
marginBottom: 12,
|
||||
},
|
||||
switchRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: 16,
|
||||
},
|
||||
modalActions: {
|
||||
flexDirection: 'row',
|
||||
gap: 12,
|
||||
},
|
||||
modalBtn: {
|
||||
flex: 1,
|
||||
borderRadius: 999,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
import React, { useState, useRef, useEffect } from 'react';
|
||||
import { StyleSheet, View, StatusBar, Alert, ActivityIndicator } from 'react-native';
|
||||
import { Text, IconButton, Surface } from 'react-native-paper';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { useRoute, useNavigation } from '@react-navigation/native';
|
||||
import Video, { type VideoRef } from 'react-native-video';
|
||||
|
||||
export default function VideoPlayerScreen() {
|
||||
const route = useRoute<any>();
|
||||
const navigation = useNavigation<any>();
|
||||
const { cameraName, streamUrl } = route.params;
|
||||
const videoRef = useRef<VideoRef>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [paused, setPaused] = useState(false);
|
||||
const [muted, setMuted] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!streamUrl) {
|
||||
setError('无视频流地址');
|
||||
setLoading(false);
|
||||
}
|
||||
}, [streamUrl]);
|
||||
|
||||
const handleLoad = () => {
|
||||
setLoading(false);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const handleError = (e: any) => {
|
||||
setLoading(false);
|
||||
const msg = e?.error?.errorString || e?.error?.localizedDescription || '视频加载失败';
|
||||
setError(msg);
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<StatusBar barStyle="light-content" />
|
||||
<SafeAreaView style={styles.header} edges={['top']}>
|
||||
<IconButton
|
||||
icon="arrow-left"
|
||||
iconColor="white"
|
||||
size={24}
|
||||
onPress={() => navigation.goBack()}
|
||||
/>
|
||||
<Text style={styles.headerTitle}>{cameraName}</Text>
|
||||
<View style={{ width: 48 }} />
|
||||
</SafeAreaView>
|
||||
|
||||
<View style={styles.videoContainer}>
|
||||
{error ? (
|
||||
<View style={styles.errorContainer}>
|
||||
<IconButton icon="alert-circle-outline" size={48} iconColor="#B8B3AA" />
|
||||
<Text style={styles.errorText}>{error}</Text>
|
||||
</View>
|
||||
) : (
|
||||
<>
|
||||
{streamUrl ? (
|
||||
<Video
|
||||
ref={videoRef}
|
||||
source={{ uri: streamUrl }}
|
||||
style={styles.video}
|
||||
resizeMode="contain"
|
||||
paused={paused}
|
||||
muted={muted}
|
||||
onLoad={handleLoad}
|
||||
onError={handleError}
|
||||
playInBackground={false}
|
||||
controls={false}
|
||||
bufferConfig={{
|
||||
minBufferMs: 1000,
|
||||
maxBufferMs: 3000,
|
||||
bufferForPlaybackMs: 500,
|
||||
bufferForPlaybackAfterRebufferMs: 1000,
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{loading ? (
|
||||
<View style={styles.loadingOverlay}>
|
||||
<ActivityIndicator size="large" color="white" />
|
||||
<Text style={styles.loadingText}>加载中...</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{!loading && !error ? (
|
||||
<View style={styles.controlsOverlay}>
|
||||
<Surface style={styles.controlBar}>
|
||||
<IconButton
|
||||
icon={paused ? 'play' : 'pause'}
|
||||
iconColor="white"
|
||||
size={28}
|
||||
onPress={() => setPaused(!paused)}
|
||||
/>
|
||||
<IconButton
|
||||
icon={muted ? 'volume-off' : 'volume-high'}
|
||||
iconColor="white"
|
||||
size={24}
|
||||
onPress={() => setMuted(!muted)}
|
||||
/>
|
||||
</Surface>
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View style={styles.footer}>
|
||||
<Text style={styles.streamUrl}>流地址: {streamUrl || 'N/A'}</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#000',
|
||||
},
|
||||
header: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
backgroundColor: '#1A1815',
|
||||
paddingHorizontal: 4,
|
||||
},
|
||||
headerTitle: {
|
||||
color: 'white',
|
||||
fontSize: 18,
|
||||
fontWeight: '500',
|
||||
flex: 1,
|
||||
textAlign: 'center',
|
||||
},
|
||||
videoContainer: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
backgroundColor: '#000',
|
||||
},
|
||||
video: {
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
},
|
||||
loadingOverlay: {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
backgroundColor: 'rgba(26,24,21,0.5)',
|
||||
},
|
||||
loadingText: {
|
||||
color: 'white',
|
||||
marginTop: 12,
|
||||
},
|
||||
controlsOverlay: {
|
||||
position: 'absolute',
|
||||
bottom: 24,
|
||||
left: 0,
|
||||
right: 0,
|
||||
alignItems: 'center',
|
||||
},
|
||||
controlBar: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
backgroundColor: 'rgba(26,24,21,0.6)',
|
||||
borderRadius: 28,
|
||||
paddingHorizontal: 8,
|
||||
elevation: 0,
|
||||
},
|
||||
errorContainer: {
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
errorText: {
|
||||
color: '#B8B3AA',
|
||||
fontSize: 16,
|
||||
marginTop: 8,
|
||||
textAlign: 'center',
|
||||
paddingHorizontal: 32,
|
||||
},
|
||||
footer: {
|
||||
padding: 12,
|
||||
backgroundColor: '#1A1815',
|
||||
},
|
||||
streamUrl: {
|
||||
color: '#8C8780',
|
||||
fontSize: 11,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import { StyleSheet, View, FlatList, RefreshControl, Alert } from 'react-native';
|
||||
import { Text, Card, Button, useTheme, ActivityIndicator, Surface, IconButton, SegmentedButtons } from 'react-native-paper';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import { getCameras, getClips, playCamera } from '../api/video';
|
||||
import { extractErrorMessage, resolveUrl } from '../api/client';
|
||||
import { formatDateTime, formatDuration, formatFileSize } from '../utils/format';
|
||||
import type { Camera, VideoClip } from '../types';
|
||||
|
||||
export default function VideoScreen() {
|
||||
const theme = useTheme();
|
||||
const navigation = useNavigation<any>();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [cameras, setCameras] = useState<Camera[]>([]);
|
||||
const [clips, setClips] = useState<VideoClip[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [tab, setTab] = useState('cameras');
|
||||
|
||||
const loadData = useCallback(async (isRefresh = false) => {
|
||||
if (isRefresh) setRefreshing(true);
|
||||
try {
|
||||
const [camerasData, clipsData] = await Promise.all([
|
||||
getCameras().catch(() => [] as Camera[]),
|
||||
getClips({ limit: 20 }).catch(() => [] as VideoClip[]),
|
||||
]);
|
||||
setCameras(camerasData);
|
||||
setClips(clipsData);
|
||||
setError(null);
|
||||
} catch (err: any) {
|
||||
setError(err?.message || '加载失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
const handlePlay = async (camera: Camera) => {
|
||||
const streamUrl = resolveUrl(`/api/v1/video/cameras/${camera.id}/live/stream`);
|
||||
navigation.navigate('VideoPlayer', {
|
||||
cameraId: camera.id,
|
||||
cameraName: camera.name,
|
||||
streamUrl,
|
||||
});
|
||||
};
|
||||
|
||||
const handlePlayClip = async (clip: VideoClip) => {
|
||||
if (clip.playbackUrl) {
|
||||
navigation.navigate('VideoPlayer', {
|
||||
cameraId: clip.cameraId,
|
||||
cameraName: `录像片段 ${clip.startAt ? formatDateTime(clip.startAt) : ''}`,
|
||||
streamUrl: resolveUrl(clip.playbackUrl),
|
||||
});
|
||||
} else {
|
||||
Alert.alert('提示', '该录像暂无播放地址');
|
||||
}
|
||||
};
|
||||
|
||||
const renderCamera = ({ item }: { item: Camera }) => {
|
||||
const isOnline = item.isOnline ?? item.online;
|
||||
return (
|
||||
<Card style={styles.card}>
|
||||
<Card.Content style={styles.cardContent}>
|
||||
<View style={styles.cameraInfo}>
|
||||
<View style={[styles.iconBox, { backgroundColor: isOnline ? '#E8F0E9' : '#F5F0E8' }]}>
|
||||
<IconButton icon="video" size={24} iconColor={isOnline ? '#7A9E7E' : '#B8B3AA'} />
|
||||
</View>
|
||||
<View style={styles.cameraDetail}>
|
||||
<Text variant="bodyMedium" style={styles.cameraName}>{item.name}</Text>
|
||||
<Text variant="bodySmall" style={styles.cameraCode}>编号: {item.code}</Text>
|
||||
{item.position ? <Text variant="bodySmall" style={styles.cameraMeta}>📍 {item.position}</Text> : null}
|
||||
{item.resolution ? <Text variant="bodySmall" style={styles.cameraMeta}>分辨率: {item.resolution}</Text> : null}
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.cameraRight}>
|
||||
<Surface style={[styles.statusBadge, { backgroundColor: isOnline ? '#7A9E7E' : '#B8B3AA' }]}>
|
||||
<Text style={styles.statusText}>{isOnline ? '在线' : '离线'}</Text>
|
||||
</Surface>
|
||||
<Button
|
||||
mode="contained"
|
||||
onPress={() => handlePlay(item)}
|
||||
disabled={!isOnline}
|
||||
style={styles.playBtn}
|
||||
buttonColor="#7A9E7E"
|
||||
icon="play"
|
||||
>
|
||||
播放
|
||||
</Button>
|
||||
</View>
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
const renderClip = ({ item }: { item: VideoClip }) => (
|
||||
<Card style={styles.card} onPress={() => handlePlayClip(item)}>
|
||||
<Card.Content style={styles.cardContent}>
|
||||
<View style={styles.clipInfo}>
|
||||
<IconButton icon="filmstrip" size={28} iconColor={theme.colors.primary} />
|
||||
<View style={styles.clipDetail}>
|
||||
<Text variant="bodyMedium" style={styles.clipTitle}>
|
||||
{item.trigger === 'alarm' ? '告警录像' : item.trigger === 'manual' ? '手动录像' : item.trigger === 'schedule' ? '定时录像' : '录像片段'}
|
||||
</Text>
|
||||
<Text variant="bodySmall" style={styles.clipMeta}>
|
||||
开始: {formatDateTime(item.startAt)}
|
||||
</Text>
|
||||
<Text variant="bodySmall" style={styles.clipMeta}>
|
||||
时长: {formatDuration(item.durationSec)}
|
||||
{item.resolution ? ` · ${item.resolution}` : ''}
|
||||
</Text>
|
||||
{item.sizeBytes ? (
|
||||
<Text variant="bodySmall" style={styles.clipMeta}>
|
||||
大小: {formatFileSize(item.sizeBytes)}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
<IconButton icon="play-circle-outline" size={32} iconColor={theme.colors.primary} />
|
||||
</Card.Content>
|
||||
</Card>
|
||||
);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<SafeAreaView style={styles.center}>
|
||||
<ActivityIndicator size="large" />
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container} edges={['bottom']}>
|
||||
<View style={styles.filterContainer}>
|
||||
<SegmentedButtons
|
||||
value={tab}
|
||||
onValueChange={setTab}
|
||||
buttons={[
|
||||
{ value: 'cameras', label: '摄像头' },
|
||||
{ value: 'clips', label: '录像片段' },
|
||||
]}
|
||||
/>
|
||||
</View>
|
||||
<FlatList
|
||||
data={(tab === 'cameras' ? cameras : clips) as any[]}
|
||||
keyExtractor={(item) => String(item.id)}
|
||||
renderItem={(tab === 'cameras' ? renderCamera : renderClip) as any}
|
||||
contentContainerStyle={styles.list}
|
||||
refreshControl={
|
||||
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
|
||||
}
|
||||
ListEmptyComponent={
|
||||
error ? (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Text style={styles.emptyText}>{error}</Text>
|
||||
</View>
|
||||
) : (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Text style={styles.emptyText}>
|
||||
{tab === 'cameras' ? '暂无摄像头' : '暂无录像片段'}
|
||||
</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#FAF8F5',
|
||||
},
|
||||
center: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
filterContainer: {
|
||||
padding: 16,
|
||||
paddingBottom: 8,
|
||||
},
|
||||
list: {
|
||||
padding: 16,
|
||||
paddingTop: 8,
|
||||
paddingBottom: 32,
|
||||
},
|
||||
card: {
|
||||
marginBottom: 12,
|
||||
borderRadius: 14,
|
||||
backgroundColor: '#FFFFFF',
|
||||
},
|
||||
cardContent: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
paddingVertical: 8,
|
||||
},
|
||||
cameraInfo: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
flex: 1,
|
||||
},
|
||||
iconBox: {
|
||||
borderRadius: 12,
|
||||
},
|
||||
cameraDetail: {
|
||||
flex: 1,
|
||||
marginLeft: 4,
|
||||
},
|
||||
cameraName: {
|
||||
color: '#2D2A26',
|
||||
fontWeight: '500',
|
||||
},
|
||||
cameraCode: {
|
||||
color: '#B8B3AA',
|
||||
fontSize: 12,
|
||||
marginTop: 2,
|
||||
},
|
||||
cameraMeta: {
|
||||
color: '#B8B3AA',
|
||||
fontSize: 12,
|
||||
marginTop: 2,
|
||||
},
|
||||
cameraRight: {
|
||||
alignItems: 'flex-end',
|
||||
gap: 6,
|
||||
},
|
||||
statusBadge: {
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 3,
|
||||
borderRadius: 12,
|
||||
elevation: 0,
|
||||
},
|
||||
statusText: {
|
||||
color: 'white',
|
||||
fontSize: 11,
|
||||
fontWeight: '500',
|
||||
},
|
||||
playBtn: {
|
||||
borderRadius: 999,
|
||||
},
|
||||
clipInfo: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
flex: 1,
|
||||
},
|
||||
clipDetail: {
|
||||
flex: 1,
|
||||
marginLeft: 4,
|
||||
},
|
||||
clipTitle: {
|
||||
color: '#2D2A26',
|
||||
fontWeight: '500',
|
||||
},
|
||||
clipMeta: {
|
||||
color: '#B8B3AA',
|
||||
fontSize: 12,
|
||||
marginTop: 2,
|
||||
},
|
||||
emptyContainer: {
|
||||
alignItems: 'center',
|
||||
paddingTop: 64,
|
||||
},
|
||||
emptyText: {
|
||||
color: '#B8B3AA',
|
||||
fontSize: 16,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { create } from 'zustand';
|
||||
import type { Room, TelemetryRecord } from '../types';
|
||||
|
||||
interface AppState {
|
||||
currentRoom: Room | null;
|
||||
setCurrentRoom: (room: Room | null) => void;
|
||||
refreshTrigger: number;
|
||||
triggerRefresh: () => void;
|
||||
realtimeData: TelemetryRecord[];
|
||||
setRealtimeData: (data: TelemetryRecord[]) => void;
|
||||
wsConnected: boolean;
|
||||
setWsConnected: (connected: boolean) => void;
|
||||
}
|
||||
|
||||
export const useAppStore = create<AppState>()((set) => ({
|
||||
currentRoom: null,
|
||||
setCurrentRoom: (room) => set({ currentRoom: room }),
|
||||
refreshTrigger: 0,
|
||||
triggerRefresh: () => set((state) => ({ refreshTrigger: state.refreshTrigger + 1 })),
|
||||
realtimeData: [],
|
||||
setRealtimeData: (data) => set({ realtimeData: data }),
|
||||
wsConnected: false,
|
||||
setWsConnected: (connected) => set({ wsConnected: connected }),
|
||||
}));
|
||||
@@ -0,0 +1,97 @@
|
||||
import { create } from 'zustand';
|
||||
import { persist, createJSONStorage } from 'zustand/middleware';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { loginApi, getMeApi } from '../api/auth';
|
||||
import { TOKEN_KEY, REFRESH_TOKEN_KEY } from '../api/client';
|
||||
import { wsManager } from '../utils/ws';
|
||||
import type { User } from '../types';
|
||||
|
||||
interface AuthState {
|
||||
token: string | null;
|
||||
refreshToken: string | null;
|
||||
user: User | null;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
login: (username: string, password: string) => Promise<boolean>;
|
||||
logout: () => Promise<void>;
|
||||
fetchUser: () => Promise<void>;
|
||||
restoreSession: () => Promise<void>;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
token: null,
|
||||
refreshToken: null,
|
||||
user: null,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
|
||||
login: async (username: string, password: string) => {
|
||||
set({ isLoading: true, error: null });
|
||||
try {
|
||||
const res = await loginApi(username, password);
|
||||
const token = res.accessToken;
|
||||
const refreshToken = res.refreshToken || null;
|
||||
|
||||
await AsyncStorage.setItem(TOKEN_KEY, token);
|
||||
if (refreshToken) {
|
||||
await AsyncStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
|
||||
}
|
||||
|
||||
set({
|
||||
token,
|
||||
refreshToken,
|
||||
user: res.user,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
wsManager.connect(token);
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
const msg =
|
||||
err?.response?.data?.message ||
|
||||
err?.response?.data?.msg ||
|
||||
err?.message ||
|
||||
'登录失败';
|
||||
set({ isLoading: false, error: msg });
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
logout: async () => {
|
||||
wsManager.disconnect();
|
||||
await AsyncStorage.multiRemove([TOKEN_KEY, REFRESH_TOKEN_KEY]);
|
||||
set({ token: null, refreshToken: null, user: null, error: null });
|
||||
},
|
||||
|
||||
fetchUser: async () => {
|
||||
const user = await getMeApi();
|
||||
set({ user });
|
||||
},
|
||||
|
||||
restoreSession: async () => {
|
||||
const token = await AsyncStorage.getItem(TOKEN_KEY);
|
||||
if (token) {
|
||||
set({ token });
|
||||
try {
|
||||
await get().fetchUser();
|
||||
wsManager.connect(token);
|
||||
} catch {
|
||||
await get().logout();
|
||||
}
|
||||
}
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: 'auth-storage',
|
||||
storage: createJSONStorage(() => AsyncStorage),
|
||||
partialize: (state) => ({
|
||||
token: state.token,
|
||||
refreshToken: state.refreshToken,
|
||||
user: state.user,
|
||||
}),
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,179 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
email?: string;
|
||||
fullName?: string;
|
||||
role?: string;
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
accessToken: string;
|
||||
refreshToken?: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface Room {
|
||||
id: string;
|
||||
name: string;
|
||||
code?: string;
|
||||
location?: string;
|
||||
status?: string;
|
||||
description?: string;
|
||||
capacity?: number;
|
||||
stage?: string;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
export interface Device {
|
||||
id: string;
|
||||
deviceKey: string;
|
||||
name: string;
|
||||
kind: string;
|
||||
type?: string;
|
||||
model?: string;
|
||||
onlineStatus: string;
|
||||
status?: string;
|
||||
lastSeen?: string;
|
||||
roomId?: string;
|
||||
houseId?: string;
|
||||
meta?: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface TelemetryRecord {
|
||||
deviceKey: string;
|
||||
metric: string;
|
||||
value: number;
|
||||
timestamp: string;
|
||||
unit?: string;
|
||||
}
|
||||
|
||||
export interface Alarm {
|
||||
id: string;
|
||||
code?: string;
|
||||
title?: string;
|
||||
message?: string;
|
||||
content?: string;
|
||||
severity?: string;
|
||||
level?: string;
|
||||
open: boolean;
|
||||
acknowledged: boolean;
|
||||
triggeredAt: string;
|
||||
resolvedAt?: string;
|
||||
deviceKey?: string;
|
||||
metric?: string;
|
||||
value?: number;
|
||||
thresholdMin?: number;
|
||||
thresholdMax?: number;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
export interface AlarmClip {
|
||||
id: string;
|
||||
playbackUrl?: string;
|
||||
cameraId?: string;
|
||||
startAt?: string;
|
||||
endAt?: string;
|
||||
mock?: boolean;
|
||||
}
|
||||
|
||||
export interface Threshold {
|
||||
id: string;
|
||||
name?: string;
|
||||
metric?: string;
|
||||
minValue: number;
|
||||
maxValue: number;
|
||||
min?: number;
|
||||
max?: number;
|
||||
debounceSeconds: number;
|
||||
severity: number;
|
||||
enabled: boolean;
|
||||
sensorId?: string;
|
||||
roomId?: string;
|
||||
houseId?: string;
|
||||
unit?: string;
|
||||
}
|
||||
|
||||
export interface Camera {
|
||||
id: number;
|
||||
roomId?: string;
|
||||
code: string;
|
||||
name: string;
|
||||
rtspUrl?: string;
|
||||
streamUrl?: string;
|
||||
hlsUrl?: string;
|
||||
flvUrl?: string;
|
||||
webrtcUrl?: string;
|
||||
isOnline: boolean;
|
||||
online?: boolean;
|
||||
gbDeviceId?: string;
|
||||
gbChannelId?: string;
|
||||
position?: string;
|
||||
resolution?: string;
|
||||
}
|
||||
|
||||
export interface PlayInfo {
|
||||
cameraId: string;
|
||||
format: 'hls' | 'flv' | 'webrtc';
|
||||
url: string;
|
||||
expiresAt?: string;
|
||||
mock?: boolean;
|
||||
}
|
||||
|
||||
export interface VideoClip {
|
||||
id: string;
|
||||
cameraId: string;
|
||||
trigger: string;
|
||||
format: string;
|
||||
startAt: string;
|
||||
endAt?: string;
|
||||
durationSec: number;
|
||||
resolution?: string;
|
||||
sizeBytes?: string | number;
|
||||
playbackUrl?: string;
|
||||
mock?: boolean;
|
||||
}
|
||||
|
||||
export interface ClipListResponse {
|
||||
items: VideoClip[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface RealtimeMetric {
|
||||
key: string;
|
||||
name: string;
|
||||
value: number;
|
||||
unit: string;
|
||||
status: 'normal' | 'warn' | 'danger';
|
||||
}
|
||||
|
||||
export interface TrendPoint {
|
||||
time: string;
|
||||
temp?: number;
|
||||
humidity?: number;
|
||||
co2?: number;
|
||||
}
|
||||
|
||||
export interface DeviceSummary {
|
||||
total: number;
|
||||
online: number;
|
||||
offline: number;
|
||||
alarm: number;
|
||||
}
|
||||
|
||||
export type RootStackParamList = {
|
||||
Login: undefined;
|
||||
Main: undefined;
|
||||
RoomDetail: { roomId: string; roomName: string };
|
||||
DeviceControl: { deviceKey: string; deviceName: string };
|
||||
VideoPlayer: { cameraId: number; cameraName: string; streamUrl?: string };
|
||||
Thresholds: { roomId?: string } | undefined;
|
||||
Settings: undefined;
|
||||
};
|
||||
|
||||
export type MainTabParamList = {
|
||||
Dashboard: undefined;
|
||||
Rooms: undefined;
|
||||
Devices: undefined;
|
||||
Alerts: undefined;
|
||||
Video: undefined;
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
declare module 'react-native-vector-icons/MaterialCommunityIcons' {
|
||||
import * as React from 'react';
|
||||
export default class MaterialCommunityIcons extends React.Component<any, any> {}
|
||||
}
|
||||
declare module 'react-native-vector-icons' {
|
||||
import * as React from 'react';
|
||||
export default class VectorIcon extends React.Component<any, any> {}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
export const formatDateTime = (date: string | Date | undefined): string => {
|
||||
if (!date) return '-';
|
||||
return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
|
||||
};
|
||||
|
||||
export const formatDate = (date: string | Date | undefined): string => {
|
||||
if (!date) return '-';
|
||||
return dayjs(date).format('YYYY-MM-DD');
|
||||
};
|
||||
|
||||
export const formatTime = (date: string | Date | undefined): string => {
|
||||
if (!date) return '-';
|
||||
return dayjs(date).format('HH:mm:ss');
|
||||
};
|
||||
|
||||
export const formatRelativeTime = (date: string | Date | undefined): string => {
|
||||
if (!date) return '-';
|
||||
const now = dayjs();
|
||||
const target = dayjs(date);
|
||||
const diffSec = now.diff(target, 'second');
|
||||
const diffMin = now.diff(target, 'minute');
|
||||
const diffHour = now.diff(target, 'hour');
|
||||
const diffDay = now.diff(target, 'day');
|
||||
|
||||
if (diffSec < 60) return `${diffSec}秒前`;
|
||||
if (diffMin < 60) return `${diffMin}分钟前`;
|
||||
if (diffHour < 24) return `${diffHour}小时前`;
|
||||
if (diffDay < 30) return `${diffDay}天前`;
|
||||
return formatDate(date);
|
||||
};
|
||||
|
||||
export const formatNumber = (value: number | undefined, digits = 1): string => {
|
||||
if (value === undefined || value === null || isNaN(value)) return '-';
|
||||
return value.toFixed(digits);
|
||||
};
|
||||
|
||||
export const formatDuration = (seconds: number): string => {
|
||||
if (seconds < 60) return `${seconds}秒`;
|
||||
const min = Math.floor(seconds / 60);
|
||||
const sec = seconds % 60;
|
||||
return `${min}分${sec}秒`;
|
||||
};
|
||||
|
||||
export const formatFileSize = (bytes: number | string | undefined): string => {
|
||||
if (bytes === undefined || bytes === null) return '-';
|
||||
const size = typeof bytes === 'string' ? parseInt(bytes, 10) : bytes;
|
||||
if (isNaN(size)) return '-';
|
||||
if (size < 1024) return `${size} B`;
|
||||
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
|
||||
if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(1)} MB`;
|
||||
return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`;
|
||||
};
|
||||
|
||||
export const METRIC_NAME: Record<string, string> = {
|
||||
temperature: '温度',
|
||||
temp: '温度',
|
||||
humidity: '湿度',
|
||||
co2: 'CO₂',
|
||||
light: '光照',
|
||||
ph: 'PH',
|
||||
};
|
||||
|
||||
export const METRIC_UNIT: Record<string, string> = {
|
||||
temperature: '℃',
|
||||
temp: '℃',
|
||||
humidity: '%',
|
||||
co2: 'ppm',
|
||||
light: 'lux',
|
||||
ph: '',
|
||||
};
|
||||
|
||||
export const getMetricName = (metric: string): string => {
|
||||
return METRIC_NAME[metric] || metric;
|
||||
};
|
||||
|
||||
export const getMetricUnit = (metric: string): string => {
|
||||
return METRIC_UNIT[metric] || '';
|
||||
};
|
||||
|
||||
export const normalizeMetricKey = (metric: string): string => {
|
||||
return metric === 'temperature' ? 'temp' : metric;
|
||||
};
|
||||
|
||||
export const metricStatus = (key: string, value: number): 'normal' | 'warn' | 'danger' => {
|
||||
if (key === 'temp') return value < 20 || value > 30 ? 'danger' : value < 22 || value > 28 ? 'warn' : 'normal';
|
||||
if (key === 'humidity') return value < 55 || value > 85 ? 'danger' : value < 60 || value > 80 ? 'warn' : 'normal';
|
||||
if (key === 'co2') return value > 1500 ? 'danger' : value > 1000 ? 'warn' : 'normal';
|
||||
return 'normal';
|
||||
};
|
||||
|
||||
export const getSeverityColor = (severity?: string): string => {
|
||||
switch (severity?.toLowerCase()) {
|
||||
case 'danger':
|
||||
case 'critical':
|
||||
case 'high':
|
||||
return '#D4847A';
|
||||
case 'warn':
|
||||
case 'warning':
|
||||
case 'medium':
|
||||
return '#D4B87A';
|
||||
case 'info':
|
||||
case 'low':
|
||||
return '#6B8F71';
|
||||
default:
|
||||
return '#B8B3AA';
|
||||
}
|
||||
};
|
||||
|
||||
export const getSeverityLabel = (severity?: string): string => {
|
||||
switch (severity?.toLowerCase()) {
|
||||
case 'danger':
|
||||
case 'critical':
|
||||
case 'high':
|
||||
return '严重';
|
||||
case 'warn':
|
||||
case 'warning':
|
||||
case 'medium':
|
||||
return '警告';
|
||||
case 'info':
|
||||
case 'low':
|
||||
return '提示';
|
||||
default:
|
||||
return severity || '未知';
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,123 @@
|
||||
import { WS_BASE_URL } from '@env';
|
||||
|
||||
export type WSMessageHandler = (data: any) => void;
|
||||
|
||||
class WebSocketManager {
|
||||
private ws: WebSocket | null = null;
|
||||
private token: string | null = null;
|
||||
private handlers: Set<WSMessageHandler> = new Set();
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private reconnectAttempts = 0;
|
||||
private maxReconnectAttempts = 10;
|
||||
private isManualClose = false;
|
||||
|
||||
connect(token: string): void {
|
||||
// Close any existing connection before creating a new one
|
||||
if (this.ws) {
|
||||
this.isManualClose = true;
|
||||
this.ws.onclose = null;
|
||||
this.ws.onerror = null;
|
||||
this.ws.close();
|
||||
this.ws = null;
|
||||
}
|
||||
if (this.reconnectTimer) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
this.reconnectAttempts = 0;
|
||||
this.token = token;
|
||||
this.isManualClose = false;
|
||||
this.doConnect();
|
||||
}
|
||||
|
||||
private doConnect(): void {
|
||||
if (!this.token) return;
|
||||
|
||||
const wsUrl = (WS_BASE_URL || 'ws://localhost:3000/ws').replace(/\?.*$/, '');
|
||||
const url = `${wsUrl}?token=${encodeURIComponent(this.token)}`;
|
||||
|
||||
try {
|
||||
this.ws = new WebSocket(url);
|
||||
} catch (e) {
|
||||
console.warn('[WS] Failed to create WebSocket:', e);
|
||||
this.scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
this.ws.onopen = () => {
|
||||
console.log('[WS] Connected');
|
||||
this.reconnectAttempts = 0;
|
||||
};
|
||||
|
||||
this.ws.onmessage = (event: WebSocketMessageEvent) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
this.handlers.forEach((handler) => handler(data));
|
||||
} catch (e) {
|
||||
console.warn('[WS] Failed to parse message:', e);
|
||||
}
|
||||
};
|
||||
|
||||
this.ws.onerror = (error: WebSocketErrorEvent) => {
|
||||
console.warn('[WS] Error:', error);
|
||||
};
|
||||
|
||||
this.ws.onclose = () => {
|
||||
console.log('[WS] Disconnected');
|
||||
this.ws = null;
|
||||
if (!this.isManualClose) {
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
||||
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
||||
console.warn('[WS] Max reconnection attempts reached');
|
||||
return;
|
||||
}
|
||||
|
||||
this.reconnectAttempts++;
|
||||
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
|
||||
console.log(`[WS] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);
|
||||
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
if (!this.isManualClose && this.token) {
|
||||
this.doConnect();
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
this.isManualClose = true;
|
||||
if (this.reconnectTimer) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
if (this.ws) {
|
||||
this.ws.close();
|
||||
this.ws = null;
|
||||
}
|
||||
this.reconnectAttempts = 0;
|
||||
}
|
||||
|
||||
subscribe(handler: WSMessageHandler): () => void {
|
||||
this.handlers.add(handler);
|
||||
return () => {
|
||||
this.handlers.delete(handler);
|
||||
};
|
||||
}
|
||||
|
||||
send(data: any): void {
|
||||
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(JSON.stringify(data));
|
||||
}
|
||||
}
|
||||
|
||||
get isConnected(): boolean {
|
||||
return this.ws?.readyState === WebSocket.OPEN;
|
||||
}
|
||||
}
|
||||
|
||||
export const wsManager = new WebSocketManager();
|
||||
Reference in New Issue
Block a user