feat: GeViScope SDK integration with C# Bridge and Flutter app

- Add GeViScope Bridge (C# .NET 8.0) on port 7720
  - Full SDK wrapper for camera control, PTZ, actions/events
  - 17 REST API endpoints for GeViScope server interaction
  - Support for MCS (Media Channel Simulator) with 16 test channels
  - Real-time action/event streaming via PLC callbacks

- Add GeViServer Bridge (C# .NET 8.0) on port 7710
  - Integration with GeViSoft orchestration layer
  - Input/output control and event management

- Update Python API with new routers
  - /api/geviscope/* - Proxy to GeViScope Bridge
  - /api/geviserver/* - Proxy to GeViServer Bridge
  - /api/excel/* - Excel import functionality

- Add Flutter app GeViScope integration
  - GeViScopeRemoteDataSource with 17 API methods
  - GeViScopeBloc for state management
  - GeViScopeScreen with PTZ controls
  - App drawer navigation to GeViScope

- Add SDK documentation (extracted from PDFs)
  - GeViScope SDK docs (7 parts + action reference)
  - GeViSoft SDK docs (12 chunks)

- Add .mcp.json for Claude Code MCP server config

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Administrator
2026-01-19 08:14:17 +01:00
parent c9e83e4277
commit a92b909539
76 changed files with 62101 additions and 176 deletions

View File

@@ -33,4 +33,57 @@ class ApiConstants {
// Cross-switching endpoints
static const String crossSwitchEndpoint = '/crossswitch';
// GeViServer endpoints
static const String geviServerConnect = '/geviserver/connect';
static const String geviServerDisconnect = '/geviserver/disconnect';
static const String geviServerStatus = '/geviserver/status';
static const String geviServerPing = '/geviserver/ping';
static const String geviServerSendMessage = '/geviserver/send-message';
// GeViServer video control
static const String geviServerVideoCrossSwitch = '/geviserver/video/crossswitch';
static const String geviServerVideoClearOutput = '/geviserver/video/clear-output';
// GeViServer digital I/O
static const String geviServerDigitalIoCloseContact = '/geviserver/digital-io/close-contact';
static const String geviServerDigitalIoOpenContact = '/geviserver/digital-io/open-contact';
// GeViServer timer control
static const String geviServerTimerStart = '/geviserver/timer/start';
static const String geviServerTimerStop = '/geviserver/timer/stop';
// GeViServer custom actions
static const String geviServerCustomAction = '/geviserver/custom-action';
// GeViScope endpoints (Camera Server SDK)
static const String geviScopeConnect = '/geviscope/connect';
static const String geviScopeDisconnect = '/geviscope/disconnect';
static const String geviScopeStatus = '/geviscope/status';
// GeViScope media channels
static const String geviScopeChannels = '/geviscope/channels';
static const String geviScopeChannelsRefresh = '/geviscope/channels/refresh';
// GeViScope actions
static const String geviScopeAction = '/geviscope/action';
static const String geviScopeCustomAction = '/geviscope/custom-action';
// GeViScope video control
static const String geviScopeCrossSwitch = '/geviscope/video/crossswitch';
// GeViScope PTZ camera control
static const String geviScopeCameraPan = '/geviscope/camera/pan';
static const String geviScopeCameraTilt = '/geviscope/camera/tilt';
static const String geviScopeCameraZoom = '/geviscope/camera/zoom';
static const String geviScopeCameraStop = '/geviscope/camera/stop';
static const String geviScopeCameraPreset = '/geviscope/camera/preset';
// GeViScope digital I/O
static const String geviScopeDigitalIoClose = '/geviscope/digital-io/close';
static const String geviScopeDigitalIoOpen = '/geviscope/digital-io/open';
// GeViScope messages
static const String geviScopeMessages = '/geviscope/messages';
static const String geviScopeMessagesClear = '/geviscope/messages/clear';
}

View File

@@ -1,13 +1,15 @@
/// Simple in-memory token storage for web (when secure storage fails)
import 'dart:html' as html;
/// Token storage for web using localStorage to persist across page reloads
class TokenManager {
static final TokenManager _instance = TokenManager._internal();
factory TokenManager() => _instance;
TokenManager._internal();
String? _accessToken;
String? _refreshToken;
String? _username;
String? _userRole;
static const String _accessTokenKey = 'auth_access_token';
static const String _refreshTokenKey = 'auth_refresh_token';
static const String _usernameKey = 'auth_username';
static const String _userRoleKey = 'auth_user_role';
void saveTokens({
String? accessToken,
@@ -15,21 +17,29 @@ class TokenManager {
String? username,
String? userRole,
}) {
if (accessToken != null) _accessToken = accessToken;
if (refreshToken != null) _refreshToken = refreshToken;
if (username != null) _username = username;
if (userRole != null) _userRole = userRole;
if (accessToken != null) {
html.window.localStorage[_accessTokenKey] = accessToken;
}
if (refreshToken != null) {
html.window.localStorage[_refreshTokenKey] = refreshToken;
}
if (username != null) {
html.window.localStorage[_usernameKey] = username;
}
if (userRole != null) {
html.window.localStorage[_userRoleKey] = userRole;
}
}
String? get accessToken => _accessToken;
String? get refreshToken => _refreshToken;
String? get username => _username;
String? get userRole => _userRole;
String? get accessToken => html.window.localStorage[_accessTokenKey];
String? get refreshToken => html.window.localStorage[_refreshTokenKey];
String? get username => html.window.localStorage[_usernameKey];
String? get userRole => html.window.localStorage[_userRoleKey];
void clear() {
_accessToken = null;
_refreshToken = null;
_username = null;
_userRole = null;
html.window.localStorage.remove(_accessTokenKey);
html.window.localStorage.remove(_refreshTokenKey);
html.window.localStorage.remove(_usernameKey);
html.window.localStorage.remove(_userRoleKey);
}
}

View File

@@ -81,18 +81,24 @@ class SecureStorageManager {
Future<String?> getUsername() async {
try {
return await storage.read(key: 'username');
final username = await storage.read(key: 'username');
if (username != null) return username;
} catch (e) {
throw CacheException('Failed to read username');
print('Warning: Failed to read username from secure storage, using memory');
}
// Fallback to memory storage (which now uses localStorage on web)
return TokenManager().username;
}
Future<String?> getUserRole() async {
try {
return await storage.read(key: 'user_role');
final role = await storage.read(key: 'user_role');
if (role != null) return role;
} catch (e) {
throw CacheException('Failed to read user role');
print('Warning: Failed to read user role from secure storage, using memory');
}
// Fallback to memory storage (which now uses localStorage on web)
return TokenManager().userRole;
}
// Clear all data

View File

@@ -25,7 +25,8 @@ abstract class ServerLocalDataSource {
Future<void> markServerAsSynced(String id, String type);
/// Replace all servers (used after fetching from API)
Future<void> replaceAllServers(List<ServerModel> servers);
/// If force=true, discards all local changes and replaces with fresh data
Future<void> replaceAllServers(List<ServerModel> servers, {bool force = false});
/// Clear all local data
Future<void> clearAll();
@@ -127,27 +128,38 @@ class ServerLocalDataSourceImpl implements ServerLocalDataSource {
}
@override
Future<void> replaceAllServers(List<ServerModel> servers) async {
Future<void> replaceAllServers(List<ServerModel> servers, {bool force = false}) async {
final b = await box;
// Don't clear dirty servers - keep them for sync
final dirtyServers = await getDirtyServers();
final dirtyKeys = dirtyServers.map((s) => _getKey(s.id, s.serverType)).toSet();
if (force) {
// Force mode: discard all local changes and replace with fresh data
await b.clear();
// Clear only non-dirty servers
await b.clear();
// Re-add dirty servers
for (final dirty in dirtyServers) {
await b.put(_getKey(dirty.id, dirty.serverType), dirty);
}
// Add all fetched servers (but don't overwrite dirty ones)
for (final server in servers) {
final key = _getKey(server.id, server.serverType);
if (!dirtyKeys.contains(key)) {
// Add all fetched servers
for (final server in servers) {
final key = _getKey(server.id, server.serverType);
await b.put(key, ServerHiveModel.fromServerModel(server));
}
} else {
// Normal mode: preserve dirty servers for sync
final dirtyServers = await getDirtyServers();
final dirtyKeys = dirtyServers.map((s) => _getKey(s.id, s.serverType)).toSet();
// Clear all servers
await b.clear();
// Re-add dirty servers
for (final dirty in dirtyServers) {
await b.put(_getKey(dirty.id, dirty.serverType), dirty);
}
// Add all fetched servers (but don't overwrite dirty ones)
for (final server in servers) {
final key = _getKey(server.id, server.serverType);
if (!dirtyKeys.contains(key)) {
await b.put(key, ServerHiveModel.fromServerModel(server));
}
}
}
}

View File

@@ -0,0 +1,356 @@
import 'package:dio/dio.dart';
import '../../../core/constants/api_constants.dart';
/// Remote data source for GeViScope operations
///
/// This data source provides methods to interact with GeViScope Camera Server
/// through the FastAPI backend, which wraps the GeViScope SDK.
/// GeViScope handles video recording, PTZ control, and media channel management.
class GeViScopeRemoteDataSource {
final Dio _dio;
GeViScopeRemoteDataSource({required Dio dio}) : _dio = dio;
// ============================================================================
// Connection Management
// ============================================================================
/// Connect to GeViScope Camera Server
///
/// [address] - Server address (e.g., 'localhost' or IP address)
/// [username] - Username for authentication (default: sysadmin)
/// [password] - Password (default: masterkey)
Future<Map<String, dynamic>> connect({
required String address,
required String username,
required String password,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviScopeConnect,
data: {
'address': address,
'username': username,
'password': password,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Connection failed: ${e.message}');
}
}
/// Disconnect from GeViScope
Future<Map<String, dynamic>> disconnect() async {
try {
final response = await _dio.post(
ApiConstants.geviScopeDisconnect,
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Disconnection failed: ${e.message}');
}
}
/// Get connection status
Future<Map<String, dynamic>> getStatus() async {
try {
final response = await _dio.get(
ApiConstants.geviScopeStatus,
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Status check failed: ${e.message}');
}
}
// ============================================================================
// Media Channels
// ============================================================================
/// Get list of media channels (cameras)
Future<Map<String, dynamic>> getChannels() async {
try {
final response = await _dio.get(
ApiConstants.geviScopeChannels,
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Get channels failed: ${e.message}');
}
}
/// Refresh media channel list
Future<Map<String, dynamic>> refreshChannels() async {
try {
final response = await _dio.post(
ApiConstants.geviScopeChannelsRefresh,
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Refresh channels failed: ${e.message}');
}
}
// ============================================================================
// Actions
// ============================================================================
/// Send generic action to GeViScope
///
/// [action] - Action string (e.g., "CustomAction(1,\"Hello\")")
Future<Map<String, dynamic>> sendAction(String action) async {
try {
final response = await _dio.post(
ApiConstants.geviScopeAction,
data: {
'action': action,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Send action failed: ${e.message}');
}
}
/// Send custom action
///
/// [typeId] - Action type ID
/// [text] - Action text/parameters
Future<Map<String, dynamic>> sendCustomAction({
required int typeId,
String text = '',
}) async {
try {
final response = await _dio.post(
ApiConstants.geviScopeCustomAction,
queryParameters: {
'type_id': typeId,
'text': text,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('CustomAction failed: ${e.message}');
}
}
// ============================================================================
// Video Control
// ============================================================================
/// CrossSwitch - Route video input to output
///
/// [videoInput] - Source camera/channel number
/// [videoOutput] - Destination monitor/output number
/// [switchMode] - Switch mode (0 = normal)
Future<Map<String, dynamic>> crossSwitch({
required int videoInput,
required int videoOutput,
int switchMode = 0,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviScopeCrossSwitch,
queryParameters: {
'video_input': videoInput,
'video_output': videoOutput,
'switch_mode': switchMode,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('CrossSwitch failed: ${e.message}');
}
}
// ============================================================================
// PTZ Camera Control
// ============================================================================
/// Pan camera left or right
///
/// [camera] - Camera/PTZ head number
/// [direction] - 'left' or 'right'
/// [speed] - Movement speed (1-100)
Future<Map<String, dynamic>> cameraPan({
required int camera,
required String direction,
int speed = 50,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviScopeCameraPan,
queryParameters: {
'camera': camera,
'direction': direction,
'speed': speed,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Camera pan failed: ${e.message}');
}
}
/// Tilt camera up or down
///
/// [camera] - Camera/PTZ head number
/// [direction] - 'up' or 'down'
/// [speed] - Movement speed (1-100)
Future<Map<String, dynamic>> cameraTilt({
required int camera,
required String direction,
int speed = 50,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviScopeCameraTilt,
queryParameters: {
'camera': camera,
'direction': direction,
'speed': speed,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Camera tilt failed: ${e.message}');
}
}
/// Zoom camera in or out
///
/// [camera] - Camera/PTZ head number
/// [direction] - 'in' or 'out'
/// [speed] - Movement speed (1-100)
Future<Map<String, dynamic>> cameraZoom({
required int camera,
required String direction,
int speed = 50,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviScopeCameraZoom,
queryParameters: {
'camera': camera,
'direction': direction,
'speed': speed,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Camera zoom failed: ${e.message}');
}
}
/// Stop all camera movement
///
/// [camera] - Camera/PTZ head number
Future<Map<String, dynamic>> cameraStop({
required int camera,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviScopeCameraStop,
queryParameters: {
'camera': camera,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Camera stop failed: ${e.message}');
}
}
/// Go to camera preset position
///
/// [camera] - Camera/PTZ head number
/// [preset] - Preset position number
Future<Map<String, dynamic>> cameraPreset({
required int camera,
required int preset,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviScopeCameraPreset,
queryParameters: {
'camera': camera,
'preset': preset,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Camera preset failed: ${e.message}');
}
}
// ============================================================================
// Digital I/O
// ============================================================================
/// Close digital output contact (activate relay)
///
/// [contactId] - Digital contact ID
Future<Map<String, dynamic>> digitalIoClose({
required int contactId,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviScopeDigitalIoClose,
queryParameters: {
'contact_id': contactId,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Digital I/O close failed: ${e.message}');
}
}
/// Open digital output contact (deactivate relay)
///
/// [contactId] - Digital contact ID
Future<Map<String, dynamic>> digitalIoOpen({
required int contactId,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviScopeDigitalIoOpen,
queryParameters: {
'contact_id': contactId,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Digital I/O open failed: ${e.message}');
}
}
// ============================================================================
// Message Log
// ============================================================================
/// Get received message log
Future<Map<String, dynamic>> getMessages() async {
try {
final response = await _dio.get(
ApiConstants.geviScopeMessages,
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Get messages failed: ${e.message}');
}
}
/// Clear message log
Future<Map<String, dynamic>> clearMessages() async {
try {
final response = await _dio.post(
ApiConstants.geviScopeMessagesClear,
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Clear messages failed: ${e.message}');
}
}
}

View File

@@ -0,0 +1,266 @@
import 'package:dio/dio.dart';
import '../../../core/constants/api_constants.dart';
/// Remote data source for GeViServer operations
///
/// This data source provides methods to interact with GeViServer through
/// the FastAPI backend, which wraps GeViProcAPI.dll
class GeViServerRemoteDataSource {
final Dio _dio;
GeViServerRemoteDataSource({required Dio dio}) : _dio = dio;
// ============================================================================
// Connection Management
// ============================================================================
/// Connect to GeViServer
///
/// [address] - Server address (e.g., 'localhost' or IP address)
/// [username] - Username for authentication
/// [password] - Password (will be encrypted by backend)
Future<Map<String, dynamic>> connect({
required String address,
required String username,
required String password,
String? username2,
String? password2,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviServerConnect,
data: {
'address': address,
'username': username,
'password': password,
if (username2 != null) 'username2': username2,
if (password2 != null) 'password2': password2,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Connection failed: ${e.message}');
}
}
/// Disconnect from GeViServer
Future<Map<String, dynamic>> disconnect() async {
try {
final response = await _dio.post(
ApiConstants.geviServerDisconnect,
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Disconnection failed: ${e.message}');
}
}
/// Get connection status
Future<Map<String, dynamic>> getStatus() async {
try {
final response = await _dio.get(
ApiConstants.geviServerStatus,
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Status check failed: ${e.message}');
}
}
/// Send ping to GeViServer
Future<Map<String, dynamic>> sendPing() async {
try {
final response = await _dio.post(
ApiConstants.geviServerPing,
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Ping failed: ${e.message}');
}
}
// ============================================================================
// Message Sending
// ============================================================================
/// Send generic action message to GeViServer
///
/// [message] - ASCII action message (e.g., "CrossSwitch(7,3,0)")
Future<Map<String, dynamic>> sendMessage(String message) async {
try {
final response = await _dio.post(
ApiConstants.geviServerSendMessage,
data: {
'message': message,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('Send message failed: ${e.message}');
}
}
// ============================================================================
// Video Control
// ============================================================================
/// Cross-switch video input to output
///
/// [videoInput] - Video input channel number
/// [videoOutput] - Video output channel number
/// [switchMode] - Switch mode (default: 0 for normal)
Future<Map<String, dynamic>> crossSwitch({
required int videoInput,
required int videoOutput,
int switchMode = 0,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviServerVideoCrossSwitch,
queryParameters: {
'video_input': videoInput,
'video_output': videoOutput,
'switch_mode': switchMode,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('CrossSwitch failed: ${e.message}');
}
}
/// Clear video output
///
/// [videoOutput] - Video output channel number
Future<Map<String, dynamic>> clearOutput({
required int videoOutput,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviServerVideoClearOutput,
queryParameters: {
'video_output': videoOutput,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('ClearOutput failed: ${e.message}');
}
}
// ============================================================================
// Digital I/O Control
// ============================================================================
/// Close digital output contact
///
/// [contactId] - Digital contact ID
Future<Map<String, dynamic>> closeContact({
required int contactId,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviServerDigitalIoCloseContact,
queryParameters: {
'contact_id': contactId,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('CloseContact failed: ${e.message}');
}
}
/// Open digital output contact
///
/// [contactId] - Digital contact ID
Future<Map<String, dynamic>> openContact({
required int contactId,
}) async {
try {
final response = await _dio.post(
ApiConstants.geviServerDigitalIoOpenContact,
queryParameters: {
'contact_id': contactId,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('OpenContact failed: ${e.message}');
}
}
// ============================================================================
// Timer Control
// ============================================================================
/// Start timer
///
/// [timerId] - Timer ID (0 to use name)
/// [timerName] - Timer name
Future<Map<String, dynamic>> startTimer({
int timerId = 0,
String timerName = '',
}) async {
try {
final response = await _dio.post(
ApiConstants.geviServerTimerStart,
queryParameters: {
'timer_id': timerId,
'timer_name': timerName,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('StartTimer failed: ${e.message}');
}
}
/// Stop timer
///
/// [timerId] - Timer ID (0 to use name)
/// [timerName] - Timer name
Future<Map<String, dynamic>> stopTimer({
int timerId = 0,
String timerName = '',
}) async {
try {
final response = await _dio.post(
ApiConstants.geviServerTimerStop,
queryParameters: {
'timer_id': timerId,
'timer_name': timerName,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('StopTimer failed: ${e.message}');
}
}
// ============================================================================
// Custom Actions
// ============================================================================
/// Send custom action
///
/// [typeId] - Action type ID
/// [text] - Action text/parameters
Future<Map<String, dynamic>> sendCustomAction({
required int typeId,
String text = '',
}) async {
try {
final response = await _dio.post(
ApiConstants.geviServerCustomAction,
queryParameters: {
'type_id': typeId,
'text': text,
},
);
return response.data as Map<String, dynamic>;
} on DioException catch (e) {
throw Exception('CustomAction failed: ${e.message}');
}
}
}

View File

@@ -0,0 +1,161 @@
import 'dart:typed_data';
import 'package:dio/dio.dart';
import '../../domain/entities/server.dart';
import '../../core/constants/api_constants.dart';
import '../../core/storage/token_manager.dart';
import '../data_sources/local/server_local_data_source.dart';
import '../models/server_hive_model.dart';
import 'package:uuid/uuid.dart';
class ExcelImportService {
final _uuid = const Uuid();
final Dio _dio = Dio();
final ServerLocalDataSource? _localDataSource;
ExcelImportService({ServerLocalDataSource? localDataSource})
: _localDataSource = localDataSource;
/// Import servers from Excel file using backend API
/// Expected columns (starting from row 2):
/// - Column B: Hostname/Alias
/// - Column C: Type (GeViScope or G-Core)
/// - Column D: IP Server/Host
/// - Column E: Username
/// - Column F: Password
Future<List<Server>> importServersFromExcel(Uint8List fileBytes, String fileName) async {
try {
print('[ExcelImport] Starting import, file size: ${fileBytes.length} bytes');
// Get auth token
final token = TokenManager().accessToken;
// Prepare multipart request
final formData = FormData.fromMap({
'file': MultipartFile.fromBytes(
fileBytes,
filename: fileName,
),
});
// Call backend API
final response = await _dio.post(
'${ApiConstants.baseUrl}/excel/import-servers',
data: formData,
options: Options(
headers: {
'Authorization': 'Bearer $token',
},
),
);
if (response.statusCode != 200) {
throw Exception('Server returned status ${response.statusCode}');
}
final data = response.data as Map<String, dynamic>;
final serversData = data['servers'] as List<dynamic>;
print('[ExcelImport] Server returned ${serversData.length} servers');
// Convert API response to Server entities
final servers = <Server>[];
for (final serverData in serversData) {
final serverType = serverData['type'] == 'gcore'
? ServerType.gcore
: ServerType.geviscope;
final server = Server(
id: _uuid.v4(),
alias: serverData['alias'] as String,
host: serverData['host'] as String,
user: serverData['user'] as String? ?? 'sysadmin',
password: serverData['password'] as String? ?? '',
type: serverType,
enabled: serverData['enabled'] as bool? ?? true,
deactivateEcho: serverData['deactivateEcho'] as bool? ?? false,
deactivateLiveCheck: serverData['deactivateLiveCheck'] as bool? ?? false,
);
servers.add(server);
}
print('[ExcelImport] Import completed: ${servers.length} servers parsed');
return servers;
} catch (e) {
print('[ExcelImport] Fatal error: $e');
if (e is DioException) {
print('[ExcelImport] DioException type: ${e.type}');
print('[ExcelImport] Response status: ${e.response?.statusCode}');
print('[ExcelImport] Response data: ${e.response?.data}');
print('[ExcelImport] Request URL: ${e.requestOptions.uri}');
final errorMessage = e.response?.data?['detail'] ??
e.response?.data?['error'] ??
e.message ??
'Unknown error';
throw Exception('Failed to import Excel file: $errorMessage');
}
throw Exception('Failed to import Excel file: $e');
}
}
/// Merge imported servers with existing servers
/// Only adds servers that don't already exist (based on alias or host)
List<Server> mergeServers({
required List<Server> existing,
required List<Server> imported,
}) {
final newServers = <Server>[];
int duplicateCount = 0;
for (final importedServer in imported) {
// Check if server already exists by alias or host
final isDuplicate = existing.any((existingServer) =>
existingServer.alias.toLowerCase() == importedServer.alias.toLowerCase() ||
existingServer.host.toLowerCase() == importedServer.host.toLowerCase());
if (!isDuplicate) {
newServers.add(importedServer);
print('[ExcelImport] New server: ${importedServer.alias}');
} else {
duplicateCount++;
print('[ExcelImport] Duplicate skipped: ${importedServer.alias}');
}
}
print('[ExcelImport] Merge complete: ${newServers.length} new servers, $duplicateCount duplicates skipped');
return newServers;
}
/// Save imported servers directly to local storage as dirty (unsaved) servers
/// This bypasses the bloc to avoid triggering multiple rebuilds during import
Future<void> saveImportedServersToStorage(List<Server> servers) async {
if (_localDataSource == null) {
throw Exception('LocalDataSource not available for direct storage access');
}
print('[ExcelImport] Saving ${servers.length} servers directly to storage...');
for (final server in servers) {
final hiveModel = ServerHiveModel(
id: server.id,
alias: server.alias,
host: server.host,
user: server.user,
password: server.password,
serverType: server.type == ServerType.gcore ? 'gcore' : 'geviscope',
enabled: server.enabled,
deactivateEcho: server.deactivateEcho,
deactivateLiveCheck: server.deactivateLiveCheck,
isDirty: true, // Mark as dirty (unsaved change)
syncOperation: 'create', // Needs to be created on server
lastModified: DateTime.now(),
);
await _localDataSource!.saveServer(hiveModel);
print('[ExcelImport] Saved to storage: ${server.alias}');
}
print('[ExcelImport] All ${servers.length} servers saved to storage as unsaved changes');
}
}

View File

@@ -139,8 +139,8 @@ class SyncServiceImpl implements SyncService {
// Fetch all servers from API
final servers = await remoteDataSource.getAllServers();
// Replace local storage (preserving dirty servers)
await localDataSource.replaceAllServers(servers);
// Replace local storage with force=true to discard all local changes
await localDataSource.replaceAllServers(servers, force: true);
return Right(servers.length);
} on ServerException catch (e) {

View File

@@ -8,12 +8,15 @@ import 'core/network/dio_client.dart';
import 'data/data_sources/remote/auth_remote_data_source.dart';
import 'data/data_sources/remote/server_remote_data_source.dart';
import 'data/data_sources/remote/action_mapping_remote_data_source.dart';
import 'data/data_sources/remote/geviserver_remote_data_source.dart';
import 'data/data_sources/remote/geviscope_remote_data_source.dart';
import 'data/data_sources/local/secure_storage_manager.dart';
import 'data/data_sources/local/server_local_data_source.dart';
import 'data/data_sources/local/action_mapping_local_data_source.dart';
// Services
import 'data/services/sync_service.dart';
import 'data/services/excel_import_service.dart';
// Repositories
import 'data/repositories/auth_repository_impl.dart';
@@ -31,6 +34,8 @@ import 'domain/use_cases/servers/get_servers.dart';
import 'presentation/blocs/auth/auth_bloc.dart';
import 'presentation/blocs/server/server_bloc.dart';
import 'presentation/blocs/action_mapping/action_mapping_bloc.dart';
import 'presentation/blocs/geviserver/geviserver_bloc.dart';
import 'presentation/blocs/geviscope/geviscope_bloc.dart';
final sl = GetIt.instance;
@@ -55,6 +60,18 @@ Future<void> init() async {
),
);
sl.registerFactory(
() => GeViServerBloc(
remoteDataSource: sl(),
),
);
sl.registerFactory(
() => GeViScopeBloc(
remoteDataSource: sl<GeViScopeRemoteDataSource>(),
),
);
// Use cases
sl.registerLazySingleton(() => Login(sl()));
sl.registerLazySingleton(() => GetServers(sl()));
@@ -93,6 +110,10 @@ Future<void> init() async {
),
);
sl.registerLazySingleton(
() => ExcelImportService(localDataSource: sl()),
);
// Data sources
sl.registerLazySingleton<AuthRemoteDataSource>(
() => AuthRemoteDataSourceImpl(dio: sl<DioClient>().dio),
@@ -114,6 +135,14 @@ Future<void> init() async {
() => ActionMappingLocalDataSourceImpl(),
);
sl.registerLazySingleton(
() => GeViServerRemoteDataSource(dio: sl<DioClient>().dio),
);
sl.registerLazySingleton(
() => GeViScopeRemoteDataSource(dio: sl<DioClient>().dio),
);
sl.registerLazySingleton(
() => SecureStorageManager(storage: sl()),
);

View File

@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:html' as html;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
@@ -12,7 +13,11 @@ import 'presentation/blocs/server/server_bloc.dart';
import 'presentation/blocs/server/server_event.dart';
import 'presentation/blocs/action_mapping/action_mapping_bloc.dart';
import 'presentation/blocs/action_mapping/action_mapping_event.dart';
import 'presentation/blocs/geviserver/geviserver_bloc.dart';
import 'presentation/blocs/geviscope/geviscope_bloc.dart';
import 'presentation/screens/auth/login_screen.dart';
import 'presentation/screens/geviserver/geviserver_screen.dart';
import 'presentation/screens/geviscope/geviscope_screen.dart';
import 'presentation/screens/servers/server_list_screen.dart';
import 'presentation/screens/servers/servers_management_screen.dart';
import 'presentation/screens/servers/server_form_screen.dart';
@@ -39,13 +44,34 @@ void main() async {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late final AuthBloc _authBloc;
late final GoRouter _router;
@override
void initState() {
super.initState();
_authBloc = di.sl<AuthBloc>()..add(const CheckAuthStatus());
_router = _createRouter(_authBloc);
}
@override
void dispose() {
_authBloc.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => di.sl<AuthBloc>()..add(const CheckAuthStatus()),
return BlocProvider.value(
value: _authBloc,
child: MaterialApp.router(
title: 'GeViAPI - Video Management System',
debugShowCheckedModeBanner: false,
@@ -85,99 +111,124 @@ class MyApp extends StatelessWidget {
}
}
final _router = GoRouter(
routes: [
GoRoute(
path: '/login',
builder: (context, state) => BlocProvider.value(
value: context.read<AuthBloc>(),
child: const LoginScreen(),
GoRouter _createRouter(AuthBloc authBloc) {
return GoRouter(
routes: [
GoRoute(
path: '/login',
builder: (context, state) => BlocProvider.value(
value: context.read<AuthBloc>(),
child: const LoginScreen(),
),
),
),
GoRoute(
path: '/',
builder: (context, state) => BlocProvider.value(
value: context.read<AuthBloc>(),
child: const ServerListScreen(),
GoRoute(
path: '/',
builder: (context, state) => BlocProvider.value(
value: context.read<AuthBloc>(),
child: const ServerListScreen(),
),
),
),
ShellRoute(
builder: (context, state, child) => BlocProvider(
create: (_) => di.sl<ServerBloc>()..add(const LoadServers()),
child: child,
ShellRoute(
builder: (context, state, child) => BlocProvider(
create: (_) => di.sl<ServerBloc>()..add(const LoadServers()),
child: child,
),
routes: [
GoRoute(
path: '/servers',
builder: (context, state) => const ServersManagementScreen(),
),
GoRoute(
path: '/servers/create',
builder: (context, state) {
final serverType = state.uri.queryParameters['type'] == 'geviscope'
? ServerType.geviscope
: ServerType.gcore;
return ServerFormScreen(serverType: serverType);
},
),
GoRoute(
path: '/servers/edit/:id',
builder: (context, state) {
final server = state.extra as Server;
return ServerFormScreen(server: server, serverType: server.type);
},
),
],
),
routes: [
GoRoute(
path: '/servers',
builder: (context, state) => const ServersManagementScreen(),
ShellRoute(
builder: (context, state, child) => BlocProvider(
create: (_) => di.sl<ActionMappingBloc>()..add(const LoadActionMappings()),
child: child,
),
GoRoute(
path: '/servers/create',
builder: (context, state) {
final serverType = state.uri.queryParameters['type'] == 'geviscope'
? ServerType.geviscope
: ServerType.gcore;
return ServerFormScreen(serverType: serverType);
},
),
GoRoute(
path: '/servers/edit/:id',
builder: (context, state) {
final server = state.extra as Server;
return ServerFormScreen(server: server, serverType: server.type);
},
),
],
),
ShellRoute(
builder: (context, state, child) => BlocProvider(
create: (_) => di.sl<ActionMappingBloc>()..add(const LoadActionMappings()),
child: child,
routes: [
GoRoute(
path: '/action-mappings',
builder: (context, state) => const ActionMappingsListScreen(),
),
GoRoute(
path: '/action-mappings/create',
builder: (context, state) => const ActionMappingFormScreen(),
),
GoRoute(
path: '/action-mappings/edit/:id',
builder: (context, state) {
final mapping = state.extra as ActionMapping;
return ActionMappingFormScreen(mapping: mapping);
},
),
],
),
routes: [
GoRoute(
path: '/action-mappings',
builder: (context, state) => const ActionMappingsListScreen(),
GoRoute(
path: '/geviserver',
builder: (context, state) => BlocProvider(
create: (_) => di.sl<GeViServerBloc>(),
child: const GeViServerScreen(),
),
GoRoute(
path: '/action-mappings/create',
builder: (context, state) => const ActionMappingFormScreen(),
),
GoRoute(
path: '/geviscope',
builder: (context, state) => BlocProvider(
create: (_) => di.sl<GeViScopeBloc>(),
child: const GeViScopeScreen(),
),
GoRoute(
path: '/action-mappings/edit/:id',
builder: (context, state) {
final mapping = state.extra as ActionMapping;
return ActionMappingFormScreen(mapping: mapping);
},
),
],
),
],
redirect: (context, state) {
final authBloc = context.read<AuthBloc>();
final authState = authBloc.state;
),
],
redirect: (context, state) {
final authState = authBloc.state;
final isLoginRoute = state.matchedLocation == '/login';
final isLoginRoute = state.matchedLocation == '/login';
if (authState is Authenticated) {
// If authenticated and trying to access login, redirect to home
if (isLoginRoute) {
return '/';
if (authState is Authenticated) {
// Check for post-import redirect flag
final postImportRedirect = html.window.localStorage['post_import_redirect'];
if (postImportRedirect != null && postImportRedirect.isNotEmpty) {
// Clear the flag
html.window.localStorage.remove('post_import_redirect');
// Redirect to the saved path
print('[Router] Post-import redirect to: $postImportRedirect');
return postImportRedirect;
}
// If authenticated and trying to access login, redirect to home
if (isLoginRoute) {
return '/';
}
} else {
// If not authenticated and not on login page, redirect to login
if (!isLoginRoute) {
return '/login';
}
}
} else {
// If not authenticated and not on login page, redirect to login
if (!isLoginRoute) {
return '/login';
}
}
// No redirect needed
return null;
},
refreshListenable: GoRouterRefreshStream(
di.sl<AuthBloc>().stream,
),
);
// No redirect needed
return null;
},
refreshListenable: GoRouterRefreshStream(
authBloc.stream,
),
);
}
class GoRouterRefreshStream extends ChangeNotifier {
GoRouterRefreshStream(Stream<dynamic> stream) {

View File

@@ -0,0 +1,499 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../data/data_sources/remote/geviscope_remote_data_source.dart';
import 'geviscope_event.dart';
import 'geviscope_state.dart';
class GeViScopeBloc extends Bloc<GeViScopeEvent, GeViScopeState> {
final GeViScopeRemoteDataSource remoteDataSource;
GeViScopeBloc({required this.remoteDataSource})
: super(const GeViScopeState()) {
on<ConnectGeViScopeEvent>(_onConnect);
on<DisconnectGeViScopeEvent>(_onDisconnect);
on<CheckGeViScopeStatusEvent>(_onCheckStatus);
on<LoadChannelsEvent>(_onLoadChannels);
on<RefreshChannelsEvent>(_onRefreshChannels);
on<SendGeViScopeCrossSwitchEvent>(_onSendCrossSwitch);
on<CameraPanEvent>(_onCameraPan);
on<CameraTiltEvent>(_onCameraTilt);
on<CameraZoomEvent>(_onCameraZoom);
on<CameraStopEvent>(_onCameraStop);
on<CameraPresetEvent>(_onCameraPreset);
on<GeViScopeCloseContactEvent>(_onCloseContact);
on<GeViScopeOpenContactEvent>(_onOpenContact);
on<SendGeViScopeCustomActionEvent>(_onSendCustomAction);
on<SendGeViScopeActionEvent>(_onSendAction);
on<ClearGeViScopeActionResultEvent>(_onClearActionResult);
}
Future<void> _onConnect(
ConnectGeViScopeEvent event,
Emitter<GeViScopeState> emit,
) async {
emit(state.copyWith(
connectionStatus: GeViScopeConnectionStatus.connecting,
isLoading: true,
clearErrorMessage: true,
));
try {
final result = await remoteDataSource.connect(
address: event.address,
username: event.username,
password: event.password,
);
if (result['success'] == true) {
emit(state.copyWith(
connectionStatus: GeViScopeConnectionStatus.connected,
serverAddress: event.address,
username: event.username,
channelCount: result['channelCount'] ?? 0,
connectedAt: DateTime.now(),
isLoading: false,
lastActionResult: 'Connected to GeViScope at ${event.address}',
lastActionSuccess: true,
));
// Auto-load channels after connection
add(const LoadChannelsEvent());
} else {
emit(state.copyWith(
connectionStatus: GeViScopeConnectionStatus.error,
isLoading: false,
errorMessage: result['message'] ?? result['error'] ?? 'Connection failed',
lastActionResult: result['message'] ?? result['error'] ?? 'Connection failed',
lastActionSuccess: false,
));
}
} catch (e) {
emit(state.copyWith(
connectionStatus: GeViScopeConnectionStatus.error,
isLoading: false,
errorMessage: e.toString(),
lastActionResult: 'Connection error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onDisconnect(
DisconnectGeViScopeEvent event,
Emitter<GeViScopeState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
await remoteDataSource.disconnect();
emit(state.copyWith(
connectionStatus: GeViScopeConnectionStatus.disconnected,
isLoading: false,
channelCount: 0,
channels: const [],
clearServerAddress: true,
clearUsername: true,
clearConnectedAt: true,
lastActionResult: 'Disconnected from GeViScope',
lastActionSuccess: true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
errorMessage: e.toString(),
lastActionResult: 'Disconnect error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onCheckStatus(
CheckGeViScopeStatusEvent event,
Emitter<GeViScopeState> emit,
) async {
try {
final result = await remoteDataSource.getStatus();
final isConnected = result['is_connected'] == true;
emit(state.copyWith(
connectionStatus: isConnected
? GeViScopeConnectionStatus.connected
: GeViScopeConnectionStatus.disconnected,
serverAddress: result['address']?.toString(),
username: result['username']?.toString(),
channelCount: result['channel_count'] ?? 0,
));
} catch (e) {
emit(state.copyWith(
connectionStatus: GeViScopeConnectionStatus.error,
errorMessage: e.toString(),
));
}
}
Future<void> _onLoadChannels(
LoadChannelsEvent event,
Emitter<GeViScopeState> emit,
) async {
try {
final result = await remoteDataSource.getChannels();
if (result['channels'] != null) {
final channelsList = (result['channels'] as List)
.map((c) => MediaChannel.fromJson(c as Map<String, dynamic>))
.toList();
emit(state.copyWith(
channels: channelsList,
channelCount: result['count'] ?? channelsList.length,
));
}
} catch (e) {
emit(state.copyWith(
lastActionResult: 'Load channels error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onRefreshChannels(
RefreshChannelsEvent event,
Emitter<GeViScopeState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
await remoteDataSource.refreshChannels();
add(const LoadChannelsEvent());
emit(state.copyWith(
isLoading: false,
lastActionResult: 'Channels refreshed',
lastActionSuccess: true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'Refresh channels error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onSendCrossSwitch(
SendGeViScopeCrossSwitchEvent event,
Emitter<GeViScopeState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.crossSwitch(
videoInput: event.videoInput,
videoOutput: event.videoOutput,
switchMode: event.switchMode,
);
final message = 'CrossSwitch(${event.videoInput}, ${event.videoOutput}, ${event.switchMode})';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'CrossSwitch sent successfully'
: result['message'] ?? 'CrossSwitch failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'CrossSwitch error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onCameraPan(
CameraPanEvent event,
Emitter<GeViScopeState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.cameraPan(
camera: event.camera,
direction: event.direction,
speed: event.speed,
);
final message = 'CameraPan(${event.camera}, ${event.direction}, ${event.speed})';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'Camera pan ${event.direction}'
: result['message'] ?? 'Camera pan failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'Camera pan error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onCameraTilt(
CameraTiltEvent event,
Emitter<GeViScopeState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.cameraTilt(
camera: event.camera,
direction: event.direction,
speed: event.speed,
);
final message = 'CameraTilt(${event.camera}, ${event.direction}, ${event.speed})';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'Camera tilt ${event.direction}'
: result['message'] ?? 'Camera tilt failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'Camera tilt error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onCameraZoom(
CameraZoomEvent event,
Emitter<GeViScopeState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.cameraZoom(
camera: event.camera,
direction: event.direction,
speed: event.speed,
);
final message = 'CameraZoom(${event.camera}, ${event.direction}, ${event.speed})';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'Camera zoom ${event.direction}'
: result['message'] ?? 'Camera zoom failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'Camera zoom error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onCameraStop(
CameraStopEvent event,
Emitter<GeViScopeState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.cameraStop(camera: event.camera);
final message = 'CameraStop(${event.camera})';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'Camera stopped'
: result['message'] ?? 'Camera stop failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'Camera stop error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onCameraPreset(
CameraPresetEvent event,
Emitter<GeViScopeState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.cameraPreset(
camera: event.camera,
preset: event.preset,
);
final message = 'CameraPreset(${event.camera}, ${event.preset})';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'Camera moved to preset ${event.preset}'
: result['message'] ?? 'Camera preset failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'Camera preset error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onCloseContact(
GeViScopeCloseContactEvent event,
Emitter<GeViScopeState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.digitalIoClose(contactId: event.contactId);
final message = 'DigitalIO_Close(${event.contactId})';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'Digital output ${event.contactId} closed'
: result['message'] ?? 'Close contact failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'Close contact error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onOpenContact(
GeViScopeOpenContactEvent event,
Emitter<GeViScopeState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.digitalIoOpen(contactId: event.contactId);
final message = 'DigitalIO_Open(${event.contactId})';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'Digital output ${event.contactId} opened'
: result['message'] ?? 'Open contact failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'Open contact error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onSendCustomAction(
SendGeViScopeCustomActionEvent event,
Emitter<GeViScopeState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.sendCustomAction(
typeId: event.typeId,
text: event.text,
);
final message = 'CustomAction(${event.typeId}, "${event.text}")';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'CustomAction sent'
: result['message'] ?? 'CustomAction failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'CustomAction error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onSendAction(
SendGeViScopeActionEvent event,
Emitter<GeViScopeState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.sendAction(event.action);
_addToLog(emit, event.action);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'Action sent'
: result['message'] ?? 'Action failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'Send action error: $e',
lastActionSuccess: false,
));
}
}
void _onClearActionResult(
ClearGeViScopeActionResultEvent event,
Emitter<GeViScopeState> emit,
) {
emit(state.copyWith(clearLastActionResult: true, clearErrorMessage: true));
}
void _addToLog(Emitter<GeViScopeState> emit, String message) {
final timestamp = DateTime.now().toIso8601String().substring(11, 19);
final logEntry = '[$timestamp] $message';
final newLog = [...state.messageLog, logEntry];
// Keep only last 100 messages
if (newLog.length > 100) {
newLog.removeRange(0, newLog.length - 100);
}
emit(state.copyWith(messageLog: newLog));
}
}

View File

@@ -0,0 +1,181 @@
import 'package:equatable/equatable.dart';
abstract class GeViScopeEvent extends Equatable {
const GeViScopeEvent();
@override
List<Object?> get props => [];
}
/// Connect to GeViScope Camera Server
class ConnectGeViScopeEvent extends GeViScopeEvent {
final String address;
final String username;
final String password;
const ConnectGeViScopeEvent({
required this.address,
required this.username,
required this.password,
});
@override
List<Object?> get props => [address, username, password];
}
/// Disconnect from GeViScope
class DisconnectGeViScopeEvent extends GeViScopeEvent {
const DisconnectGeViScopeEvent();
}
/// Check connection status
class CheckGeViScopeStatusEvent extends GeViScopeEvent {
const CheckGeViScopeStatusEvent();
}
/// Load media channels
class LoadChannelsEvent extends GeViScopeEvent {
const LoadChannelsEvent();
}
/// Refresh media channels
class RefreshChannelsEvent extends GeViScopeEvent {
const RefreshChannelsEvent();
}
/// Send CrossSwitch command
class SendGeViScopeCrossSwitchEvent extends GeViScopeEvent {
final int videoInput;
final int videoOutput;
final int switchMode;
const SendGeViScopeCrossSwitchEvent({
required this.videoInput,
required this.videoOutput,
this.switchMode = 0,
});
@override
List<Object?> get props => [videoInput, videoOutput, switchMode];
}
/// PTZ Camera Pan
class CameraPanEvent extends GeViScopeEvent {
final int camera;
final String direction;
final int speed;
const CameraPanEvent({
required this.camera,
required this.direction,
this.speed = 50,
});
@override
List<Object?> get props => [camera, direction, speed];
}
/// PTZ Camera Tilt
class CameraTiltEvent extends GeViScopeEvent {
final int camera;
final String direction;
final int speed;
const CameraTiltEvent({
required this.camera,
required this.direction,
this.speed = 50,
});
@override
List<Object?> get props => [camera, direction, speed];
}
/// PTZ Camera Zoom
class CameraZoomEvent extends GeViScopeEvent {
final int camera;
final String direction;
final int speed;
const CameraZoomEvent({
required this.camera,
required this.direction,
this.speed = 50,
});
@override
List<Object?> get props => [camera, direction, speed];
}
/// PTZ Camera Stop
class CameraStopEvent extends GeViScopeEvent {
final int camera;
const CameraStopEvent({required this.camera});
@override
List<Object?> get props => [camera];
}
/// PTZ Camera Preset
class CameraPresetEvent extends GeViScopeEvent {
final int camera;
final int preset;
const CameraPresetEvent({
required this.camera,
required this.preset,
});
@override
List<Object?> get props => [camera, preset];
}
/// Close digital contact
class GeViScopeCloseContactEvent extends GeViScopeEvent {
final int contactId;
const GeViScopeCloseContactEvent({required this.contactId});
@override
List<Object?> get props => [contactId];
}
/// Open digital contact
class GeViScopeOpenContactEvent extends GeViScopeEvent {
final int contactId;
const GeViScopeOpenContactEvent({required this.contactId});
@override
List<Object?> get props => [contactId];
}
/// Send custom action
class SendGeViScopeCustomActionEvent extends GeViScopeEvent {
final int typeId;
final String text;
const SendGeViScopeCustomActionEvent({
required this.typeId,
this.text = '',
});
@override
List<Object?> get props => [typeId, text];
}
/// Send raw action
class SendGeViScopeActionEvent extends GeViScopeEvent {
final String action;
const SendGeViScopeActionEvent({required this.action});
@override
List<Object?> get props => [action];
}
/// Clear last action result
class ClearGeViScopeActionResultEvent extends GeViScopeEvent {
const ClearGeViScopeActionResultEvent();
}

View File

@@ -0,0 +1,112 @@
import 'package:equatable/equatable.dart';
enum GeViScopeConnectionStatus {
disconnected,
connecting,
connected,
error,
}
class MediaChannel {
final int channelId;
final int globalNumber;
final String name;
final String description;
final bool isActive;
const MediaChannel({
required this.channelId,
required this.globalNumber,
required this.name,
required this.description,
required this.isActive,
});
factory MediaChannel.fromJson(Map<String, dynamic> json) {
return MediaChannel(
channelId: json['channelID'] ?? json['channelId'] ?? 0,
globalNumber: json['globalNumber'] ?? 0,
name: json['name'] ?? '',
description: json['description'] ?? '',
isActive: json['isActive'] ?? false,
);
}
}
class GeViScopeState extends Equatable {
final GeViScopeConnectionStatus connectionStatus;
final String? serverAddress;
final String? username;
final int channelCount;
final List<MediaChannel> channels;
final DateTime? connectedAt;
final bool isLoading;
final String? lastActionResult;
final bool lastActionSuccess;
final String? errorMessage;
final List<String> messageLog;
const GeViScopeState({
this.connectionStatus = GeViScopeConnectionStatus.disconnected,
this.serverAddress,
this.username,
this.channelCount = 0,
this.channels = const [],
this.connectedAt,
this.isLoading = false,
this.lastActionResult,
this.lastActionSuccess = false,
this.errorMessage,
this.messageLog = const [],
});
bool get isConnected => connectionStatus == GeViScopeConnectionStatus.connected;
GeViScopeState copyWith({
GeViScopeConnectionStatus? connectionStatus,
String? serverAddress,
String? username,
int? channelCount,
List<MediaChannel>? channels,
DateTime? connectedAt,
bool? isLoading,
String? lastActionResult,
bool? lastActionSuccess,
String? errorMessage,
List<String>? messageLog,
bool clearServerAddress = false,
bool clearUsername = false,
bool clearConnectedAt = false,
bool clearErrorMessage = false,
bool clearLastActionResult = false,
}) {
return GeViScopeState(
connectionStatus: connectionStatus ?? this.connectionStatus,
serverAddress: clearServerAddress ? null : (serverAddress ?? this.serverAddress),
username: clearUsername ? null : (username ?? this.username),
channelCount: channelCount ?? this.channelCount,
channels: channels ?? this.channels,
connectedAt: clearConnectedAt ? null : (connectedAt ?? this.connectedAt),
isLoading: isLoading ?? this.isLoading,
lastActionResult: clearLastActionResult ? null : (lastActionResult ?? this.lastActionResult),
lastActionSuccess: lastActionSuccess ?? this.lastActionSuccess,
errorMessage: clearErrorMessage ? null : (errorMessage ?? this.errorMessage),
messageLog: messageLog ?? this.messageLog,
);
}
@override
List<Object?> get props => [
connectionStatus,
serverAddress,
username,
channelCount,
channels,
connectedAt,
isLoading,
lastActionResult,
lastActionSuccess,
errorMessage,
messageLog,
];
}

View File

@@ -0,0 +1,381 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../data/data_sources/remote/geviserver_remote_data_source.dart';
import 'geviserver_event.dart';
import 'geviserver_state.dart';
class GeViServerBloc extends Bloc<GeViServerEvent, GeViServerState> {
final GeViServerRemoteDataSource remoteDataSource;
GeViServerBloc({required this.remoteDataSource})
: super(const GeViServerState()) {
on<ConnectGeViServerEvent>(_onConnect);
on<DisconnectGeViServerEvent>(_onDisconnect);
on<CheckStatusEvent>(_onCheckStatus);
on<SendCrossSwitchEvent>(_onSendCrossSwitch);
on<ClearVideoOutputEvent>(_onClearVideoOutput);
on<CloseContactEvent>(_onCloseContact);
on<OpenContactEvent>(_onOpenContact);
on<SendCustomActionEvent>(_onSendCustomAction);
on<SendMessageEvent>(_onSendMessage);
on<StartTimerEvent>(_onStartTimer);
on<StopTimerEvent>(_onStopTimer);
on<ClearActionResultEvent>(_onClearActionResult);
}
Future<void> _onConnect(
ConnectGeViServerEvent event,
Emitter<GeViServerState> emit,
) async {
emit(state.copyWith(
connectionStatus: ConnectionStatus.connecting,
isLoading: true,
clearErrorMessage: true,
));
try {
final result = await remoteDataSource.connect(
address: event.address,
username: event.username,
password: event.password,
);
if (result['success'] == true) {
emit(state.copyWith(
connectionStatus: ConnectionStatus.connected,
serverAddress: event.address,
username: event.username,
connectedAt: DateTime.now(),
isLoading: false,
lastActionResult: 'Connected to ${event.address}',
lastActionSuccess: true,
));
} else {
emit(state.copyWith(
connectionStatus: ConnectionStatus.error,
isLoading: false,
errorMessage: result['message'] ?? 'Connection failed',
lastActionResult: result['message'] ?? 'Connection failed',
lastActionSuccess: false,
));
}
} catch (e) {
emit(state.copyWith(
connectionStatus: ConnectionStatus.error,
isLoading: false,
errorMessage: e.toString(),
lastActionResult: 'Connection error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onDisconnect(
DisconnectGeViServerEvent event,
Emitter<GeViServerState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
await remoteDataSource.disconnect();
emit(state.copyWith(
connectionStatus: ConnectionStatus.disconnected,
isLoading: false,
clearServerAddress: true,
clearUsername: true,
clearConnectedAt: true,
lastActionResult: 'Disconnected',
lastActionSuccess: true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
errorMessage: e.toString(),
lastActionResult: 'Disconnect error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onCheckStatus(
CheckStatusEvent event,
Emitter<GeViServerState> emit,
) async {
try {
final result = await remoteDataSource.getStatus();
final isConnected = result['is_connected'] == true;
emit(state.copyWith(
connectionStatus: isConnected
? ConnectionStatus.connected
: ConnectionStatus.disconnected,
serverAddress: result['address']?.toString(),
username: result['username']?.toString(),
));
} catch (e) {
emit(state.copyWith(
connectionStatus: ConnectionStatus.error,
errorMessage: e.toString(),
));
}
}
Future<void> _onSendCrossSwitch(
SendCrossSwitchEvent event,
Emitter<GeViServerState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.crossSwitch(
videoInput: event.videoInput,
videoOutput: event.videoOutput,
switchMode: event.switchMode,
);
final message = 'CrossSwitch(${event.videoInput}, ${event.videoOutput}, ${event.switchMode})';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'CrossSwitch sent successfully'
: result['message'] ?? 'CrossSwitch failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'CrossSwitch error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onClearVideoOutput(
ClearVideoOutputEvent event,
Emitter<GeViServerState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.clearOutput(
videoOutput: event.videoOutput,
);
final message = 'ClearVideoOutput(${event.videoOutput})';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'ClearOutput sent successfully'
: result['message'] ?? 'ClearOutput failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'ClearOutput error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onCloseContact(
CloseContactEvent event,
Emitter<GeViServerState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.closeContact(
contactId: event.contactId,
);
final message = 'CloseContact(${event.contactId})';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'CloseContact sent successfully'
: result['message'] ?? 'CloseContact failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'CloseContact error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onOpenContact(
OpenContactEvent event,
Emitter<GeViServerState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.openContact(
contactId: event.contactId,
);
final message = 'OpenContact(${event.contactId})';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'OpenContact sent successfully'
: result['message'] ?? 'OpenContact failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'OpenContact error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onSendCustomAction(
SendCustomActionEvent event,
Emitter<GeViServerState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.sendCustomAction(
typeId: event.typeId,
text: event.text,
);
final message = 'CustomAction(${event.typeId}, "${event.text}")';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'CustomAction sent successfully'
: result['message'] ?? 'CustomAction failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'CustomAction error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onSendMessage(
SendMessageEvent event,
Emitter<GeViServerState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.sendMessage(event.message);
_addToLog(emit, event.message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'Message sent successfully'
: result['message'] ?? 'Send message failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'Send message error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onStartTimer(
StartTimerEvent event,
Emitter<GeViServerState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.startTimer(
timerId: event.timerId,
timerName: event.timerName,
);
final message = 'StartTimer(${event.timerId}, "${event.timerName}")';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'StartTimer sent successfully'
: result['message'] ?? 'StartTimer failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'StartTimer error: $e',
lastActionSuccess: false,
));
}
}
Future<void> _onStopTimer(
StopTimerEvent event,
Emitter<GeViServerState> emit,
) async {
emit(state.copyWith(isLoading: true));
try {
final result = await remoteDataSource.stopTimer(
timerId: event.timerId,
timerName: event.timerName,
);
final message = 'StopTimer(${event.timerId}, "${event.timerName}")';
_addToLog(emit, message);
emit(state.copyWith(
isLoading: false,
lastActionResult: result['success'] == true
? 'StopTimer sent successfully'
: result['message'] ?? 'StopTimer failed',
lastActionSuccess: result['success'] == true,
));
} catch (e) {
emit(state.copyWith(
isLoading: false,
lastActionResult: 'StopTimer error: $e',
lastActionSuccess: false,
));
}
}
void _onClearActionResult(
ClearActionResultEvent event,
Emitter<GeViServerState> emit,
) {
emit(state.copyWith(clearLastActionResult: true, clearErrorMessage: true));
}
void _addToLog(Emitter<GeViServerState> emit, String message) {
final timestamp = DateTime.now().toIso8601String().substring(11, 19);
final logEntry = '[$timestamp] $message';
final newLog = [...state.messageLog, logEntry];
// Keep only last 100 messages
if (newLog.length > 100) {
newLog.removeRange(0, newLog.length - 100);
}
emit(state.copyWith(messageLog: newLog));
}
}

View File

@@ -0,0 +1,137 @@
import 'package:equatable/equatable.dart';
abstract class GeViServerEvent extends Equatable {
const GeViServerEvent();
@override
List<Object?> get props => [];
}
/// Connect to GeViServer
class ConnectGeViServerEvent extends GeViServerEvent {
final String address;
final String username;
final String password;
const ConnectGeViServerEvent({
required this.address,
required this.username,
required this.password,
});
@override
List<Object?> get props => [address, username, password];
}
/// Disconnect from GeViServer
class DisconnectGeViServerEvent extends GeViServerEvent {
const DisconnectGeViServerEvent();
}
/// Check connection status
class CheckStatusEvent extends GeViServerEvent {
const CheckStatusEvent();
}
/// Send CrossSwitch command
class SendCrossSwitchEvent extends GeViServerEvent {
final int videoInput;
final int videoOutput;
final int switchMode;
const SendCrossSwitchEvent({
required this.videoInput,
required this.videoOutput,
this.switchMode = 0,
});
@override
List<Object?> get props => [videoInput, videoOutput, switchMode];
}
/// Clear video output
class ClearVideoOutputEvent extends GeViServerEvent {
final int videoOutput;
const ClearVideoOutputEvent({required this.videoOutput});
@override
List<Object?> get props => [videoOutput];
}
/// Close digital contact
class CloseContactEvent extends GeViServerEvent {
final int contactId;
const CloseContactEvent({required this.contactId});
@override
List<Object?> get props => [contactId];
}
/// Open digital contact
class OpenContactEvent extends GeViServerEvent {
final int contactId;
const OpenContactEvent({required this.contactId});
@override
List<Object?> get props => [contactId];
}
/// Send custom action
class SendCustomActionEvent extends GeViServerEvent {
final int typeId;
final String text;
const SendCustomActionEvent({
required this.typeId,
this.text = '',
});
@override
List<Object?> get props => [typeId, text];
}
/// Send raw message
class SendMessageEvent extends GeViServerEvent {
final String message;
const SendMessageEvent({required this.message});
@override
List<Object?> get props => [message];
}
/// Start timer
class StartTimerEvent extends GeViServerEvent {
final int timerId;
final String timerName;
const StartTimerEvent({
this.timerId = 0,
this.timerName = '',
});
@override
List<Object?> get props => [timerId, timerName];
}
/// Stop timer
class StopTimerEvent extends GeViServerEvent {
final int timerId;
final String timerName;
const StopTimerEvent({
this.timerId = 0,
this.timerName = '',
});
@override
List<Object?> get props => [timerId, timerName];
}
/// Clear last action result (to dismiss success/error messages)
class ClearActionResultEvent extends GeViServerEvent {
const ClearActionResultEvent();
}

View File

@@ -0,0 +1,76 @@
import 'package:equatable/equatable.dart';
enum ConnectionStatus {
disconnected,
connecting,
connected,
error,
}
class GeViServerState extends Equatable {
final ConnectionStatus connectionStatus;
final String? serverAddress;
final String? username;
final DateTime? connectedAt;
final bool isLoading;
final String? lastActionResult;
final bool lastActionSuccess;
final String? errorMessage;
final List<String> messageLog;
const GeViServerState({
this.connectionStatus = ConnectionStatus.disconnected,
this.serverAddress,
this.username,
this.connectedAt,
this.isLoading = false,
this.lastActionResult,
this.lastActionSuccess = false,
this.errorMessage,
this.messageLog = const [],
});
bool get isConnected => connectionStatus == ConnectionStatus.connected;
GeViServerState copyWith({
ConnectionStatus? connectionStatus,
String? serverAddress,
String? username,
DateTime? connectedAt,
bool? isLoading,
String? lastActionResult,
bool? lastActionSuccess,
String? errorMessage,
List<String>? messageLog,
bool clearServerAddress = false,
bool clearUsername = false,
bool clearConnectedAt = false,
bool clearErrorMessage = false,
bool clearLastActionResult = false,
}) {
return GeViServerState(
connectionStatus: connectionStatus ?? this.connectionStatus,
serverAddress: clearServerAddress ? null : (serverAddress ?? this.serverAddress),
username: clearUsername ? null : (username ?? this.username),
connectedAt: clearConnectedAt ? null : (connectedAt ?? this.connectedAt),
isLoading: isLoading ?? this.isLoading,
lastActionResult: clearLastActionResult ? null : (lastActionResult ?? this.lastActionResult),
lastActionSuccess: lastActionSuccess ?? this.lastActionSuccess,
errorMessage: clearErrorMessage ? null : (errorMessage ?? this.errorMessage),
messageLog: messageLog ?? this.messageLog,
);
}
@override
List<Object?> get props => [
connectionStatus,
serverAddress,
username,
connectedAt,
isLoading,
lastActionResult,
lastActionSuccess,
errorMessage,
messageLog,
];
}

View File

@@ -0,0 +1,964 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../blocs/geviscope/geviscope_bloc.dart';
import '../../blocs/geviscope/geviscope_event.dart';
import '../../blocs/geviscope/geviscope_state.dart';
import '../../widgets/app_drawer.dart';
class GeViScopeScreen extends StatefulWidget {
const GeViScopeScreen({super.key});
@override
State<GeViScopeScreen> createState() => _GeViScopeScreenState();
}
class _GeViScopeScreenState extends State<GeViScopeScreen> {
// Connection form controllers
final _addressController = TextEditingController(text: 'localhost');
final _usernameController = TextEditingController(text: 'sysadmin');
final _passwordController = TextEditingController(text: 'masterkey');
// CrossSwitch form controllers
final _videoInputController = TextEditingController(text: '1');
final _videoOutputController = TextEditingController(text: '1');
// PTZ controls
final _cameraController = TextEditingController(text: '1');
final _ptzSpeedController = TextEditingController(text: '50');
final _presetController = TextEditingController(text: '1');
// Digital I/O controller
final _contactIdController = TextEditingController(text: '1');
// Custom action controllers
final _customActionTypeIdController = TextEditingController(text: '1');
final _customActionTextController = TextEditingController(text: 'Test message');
// Raw action controller
final _rawActionController = TextEditingController();
bool _didCheckStatus = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (!_didCheckStatus) {
_didCheckStatus = true;
context.read<GeViScopeBloc>().add(const CheckGeViScopeStatusEvent());
}
}
@override
void dispose() {
_addressController.dispose();
_usernameController.dispose();
_passwordController.dispose();
_videoInputController.dispose();
_videoOutputController.dispose();
_cameraController.dispose();
_ptzSpeedController.dispose();
_presetController.dispose();
_contactIdController.dispose();
_customActionTypeIdController.dispose();
_customActionTextController.dispose();
_rawActionController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('GeViScope Control'),
actions: [
BlocBuilder<GeViScopeBloc, GeViScopeState>(
builder: (context, state) {
return Row(
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: _getStatusColor(state.connectionStatus).withOpacity(0.2),
borderRadius: BorderRadius.circular(16),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
_getStatusIcon(state.connectionStatus),
size: 16,
color: _getStatusColor(state.connectionStatus),
),
const SizedBox(width: 6),
Text(
_getStatusText(state.connectionStatus),
style: TextStyle(
color: _getStatusColor(state.connectionStatus),
fontWeight: FontWeight.bold,
),
),
if (state.channelCount > 0) ...[
const SizedBox(width: 8),
Text(
'(${state.channelCount} channels)',
style: TextStyle(
color: _getStatusColor(state.connectionStatus),
fontSize: 12,
),
),
],
],
),
),
const SizedBox(width: 16),
],
);
},
),
],
),
drawer: const AppDrawer(currentRoute: '/geviscope'),
body: BlocConsumer<GeViScopeBloc, GeViScopeState>(
listener: (context, state) {
if (state.lastActionResult != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.lastActionResult!),
backgroundColor: state.lastActionSuccess ? Colors.green : Colors.red,
duration: const Duration(seconds: 2),
),
);
context.read<GeViScopeBloc>().add(const ClearGeViScopeActionResultEvent());
}
},
builder: (context, state) {
return Row(
children: [
// Left panel - Controls
Expanded(
flex: 2,
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildConnectionCard(context, state),
const SizedBox(height: 16),
if (state.isConnected) ...[
_buildPTZControlCard(context, state),
const SizedBox(height: 16),
_buildVideoControlCard(context, state),
const SizedBox(height: 16),
_buildDigitalIOCard(context, state),
const SizedBox(height: 16),
_buildCustomActionCard(context, state),
const SizedBox(height: 16),
_buildRawActionCard(context, state),
],
],
),
),
),
// Right panel - Channels & Message log
Expanded(
flex: 1,
child: _buildRightPanel(context, state),
),
],
);
},
),
);
}
Widget _buildConnectionCard(BuildContext context, GeViScopeState state) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
Icons.power_settings_new,
color: state.isConnected ? Colors.green : Colors.grey,
),
const SizedBox(width: 8),
Text(
'Connection',
style: Theme.of(context).textTheme.titleLarge,
),
],
),
const Divider(),
if (!state.isConnected) ...[
Row(
children: [
Expanded(
child: TextField(
controller: _addressController,
decoration: const InputDecoration(
labelText: 'Server Address',
hintText: 'localhost',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _usernameController,
decoration: const InputDecoration(
labelText: 'Username',
hintText: 'sysadmin',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _passwordController,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Password',
hintText: 'masterkey',
border: OutlineInputBorder(),
isDense: true,
),
),
),
],
),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
context.read<GeViScopeBloc>().add(
ConnectGeViScopeEvent(
address: _addressController.text,
username: _usernameController.text,
password: _passwordController.text,
),
);
},
icon: state.isLoading
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.link),
label: Text(state.isLoading ? 'Connecting...' : 'Connect'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
),
),
),
] else ...[
ListTile(
leading: const Icon(Icons.videocam, color: Colors.green),
title: Text('Connected to ${state.serverAddress}'),
subtitle: Text('User: ${state.username} | ${state.channelCount} channels'),
contentPadding: EdgeInsets.zero,
),
const SizedBox(height: 8),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
context.read<GeViScopeBloc>().add(
const DisconnectGeViScopeEvent(),
);
},
icon: const Icon(Icons.link_off),
label: const Text('Disconnect'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
),
),
],
],
),
),
);
}
Widget _buildPTZControlCard(BuildContext context, GeViScopeState state) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.control_camera, color: Colors.orange),
const SizedBox(width: 8),
Text(
'PTZ Camera Control',
style: Theme.of(context).textTheme.titleLarge,
),
],
),
const Divider(),
Row(
children: [
Expanded(
child: TextField(
controller: _cameraController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Camera #',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _ptzSpeedController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Speed (1-100)',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _presetController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Preset #',
border: OutlineInputBorder(),
isDense: true,
),
),
),
],
),
const SizedBox(height: 16),
// PTZ Direction pad
Center(
child: SizedBox(
width: 200,
height: 200,
child: Stack(
children: [
// Up
Positioned(
top: 0,
left: 70,
child: _ptzButton(
context,
Icons.arrow_upward,
'Up',
() => _sendPTZ(context, 'tilt', 'up'),
),
),
// Down
Positioned(
bottom: 0,
left: 70,
child: _ptzButton(
context,
Icons.arrow_downward,
'Down',
() => _sendPTZ(context, 'tilt', 'down'),
),
),
// Left
Positioned(
left: 0,
top: 70,
child: _ptzButton(
context,
Icons.arrow_back,
'Left',
() => _sendPTZ(context, 'pan', 'left'),
),
),
// Right
Positioned(
right: 0,
top: 70,
child: _ptzButton(
context,
Icons.arrow_forward,
'Right',
() => _sendPTZ(context, 'pan', 'right'),
),
),
// Stop (center)
Positioned(
left: 70,
top: 70,
child: SizedBox(
width: 60,
height: 60,
child: ElevatedButton(
onPressed: state.isLoading
? null
: () {
final camera = int.tryParse(_cameraController.text) ?? 1;
context.read<GeViScopeBloc>().add(
CameraStopEvent(camera: camera),
);
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
shape: const CircleBorder(),
padding: EdgeInsets.zero,
),
child: const Icon(Icons.stop, size: 30),
),
),
),
],
),
),
),
const SizedBox(height: 16),
// Zoom controls
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton.icon(
onPressed: state.isLoading
? null
: () => _sendPTZ(context, 'zoom', 'out'),
icon: const Icon(Icons.zoom_out),
label: const Text('Zoom Out'),
),
const SizedBox(width: 16),
ElevatedButton.icon(
onPressed: state.isLoading
? null
: () => _sendPTZ(context, 'zoom', 'in'),
icon: const Icon(Icons.zoom_in),
label: const Text('Zoom In'),
),
],
),
const SizedBox(height: 16),
// Preset
Row(
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
final camera = int.tryParse(_cameraController.text) ?? 1;
final preset = int.tryParse(_presetController.text) ?? 1;
context.read<GeViScopeBloc>().add(
CameraPresetEvent(camera: camera, preset: preset),
);
},
icon: const Icon(Icons.bookmark),
label: const Text('Go to Preset'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.purple,
foregroundColor: Colors.white,
),
),
),
],
),
],
),
),
);
}
Widget _ptzButton(
BuildContext context,
IconData icon,
String tooltip,
VoidCallback onPressed,
) {
final state = context.read<GeViScopeBloc>().state;
return SizedBox(
width: 60,
height: 60,
child: ElevatedButton(
onPressed: state.isLoading ? null : onPressed,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.orange,
foregroundColor: Colors.white,
shape: const CircleBorder(),
padding: EdgeInsets.zero,
),
child: Icon(icon, size: 30),
),
);
}
void _sendPTZ(BuildContext context, String type, String direction) {
final camera = int.tryParse(_cameraController.text) ?? 1;
final speed = int.tryParse(_ptzSpeedController.text) ?? 50;
switch (type) {
case 'pan':
context.read<GeViScopeBloc>().add(
CameraPanEvent(camera: camera, direction: direction, speed: speed),
);
break;
case 'tilt':
context.read<GeViScopeBloc>().add(
CameraTiltEvent(camera: camera, direction: direction, speed: speed),
);
break;
case 'zoom':
context.read<GeViScopeBloc>().add(
CameraZoomEvent(camera: camera, direction: direction, speed: speed),
);
break;
}
}
Widget _buildVideoControlCard(BuildContext context, GeViScopeState state) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.videocam, color: Colors.blue),
const SizedBox(width: 8),
Text(
'Video CrossSwitch',
style: Theme.of(context).textTheme.titleLarge,
),
],
),
const Divider(),
Row(
children: [
Expanded(
child: TextField(
controller: _videoInputController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Video Input',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
const Icon(Icons.arrow_forward, color: Colors.grey),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _videoOutputController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Video Output',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
context.read<GeViScopeBloc>().add(
SendGeViScopeCrossSwitchEvent(
videoInput: int.tryParse(_videoInputController.text) ?? 1,
videoOutput: int.tryParse(_videoOutputController.text) ?? 1,
),
);
},
icon: const Icon(Icons.swap_horiz),
label: const Text('Switch'),
),
],
),
],
),
),
);
}
Widget _buildDigitalIOCard(BuildContext context, GeViScopeState state) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.toggle_on, color: Colors.purple),
const SizedBox(width: 8),
Text(
'Digital I/O',
style: Theme.of(context).textTheme.titleLarge,
),
],
),
const Divider(),
Row(
children: [
Expanded(
flex: 2,
child: TextField(
controller: _contactIdController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Contact ID',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
Expanded(
child: ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
context.read<GeViScopeBloc>().add(
GeViScopeCloseContactEvent(
contactId: int.tryParse(_contactIdController.text) ?? 1,
),
);
},
icon: const Icon(Icons.lock),
label: const Text('Close'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
),
),
const SizedBox(width: 8),
Expanded(
child: ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
context.read<GeViScopeBloc>().add(
GeViScopeOpenContactEvent(
contactId: int.tryParse(_contactIdController.text) ?? 1,
),
);
},
icon: const Icon(Icons.lock_open),
label: const Text('Open'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
),
),
),
],
),
],
),
),
);
}
Widget _buildCustomActionCard(BuildContext context, GeViScopeState state) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.send, color: Colors.teal),
const SizedBox(width: 8),
Text(
'Custom Action',
style: Theme.of(context).textTheme.titleLarge,
),
],
),
const Divider(),
Row(
children: [
Expanded(
child: TextField(
controller: _customActionTypeIdController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Type ID',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
Expanded(
flex: 3,
child: TextField(
controller: _customActionTextController,
decoration: const InputDecoration(
labelText: 'Text',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
context.read<GeViScopeBloc>().add(
SendGeViScopeCustomActionEvent(
typeId: int.tryParse(_customActionTypeIdController.text) ?? 1,
text: _customActionTextController.text,
),
);
},
icon: const Icon(Icons.send),
label: const Text('Send'),
),
],
),
],
),
),
);
}
Widget _buildRawActionCard(BuildContext context, GeViScopeState state) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.code, color: Colors.indigo),
const SizedBox(width: 8),
Text(
'Raw Action',
style: Theme.of(context).textTheme.titleLarge,
),
],
),
const Divider(),
Row(
children: [
Expanded(
child: TextField(
controller: _rawActionController,
decoration: const InputDecoration(
labelText: 'Action String',
hintText: 'e.g., CrossSwitch(1, 2, 0)',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
ElevatedButton.icon(
onPressed: state.isLoading || _rawActionController.text.isEmpty
? null
: () {
context.read<GeViScopeBloc>().add(
SendGeViScopeActionEvent(
action: _rawActionController.text,
),
);
_rawActionController.clear();
},
icon: const Icon(Icons.send),
label: const Text('Send'),
),
],
),
],
),
),
);
}
Widget _buildRightPanel(BuildContext context, GeViScopeState state) {
return Container(
decoration: BoxDecoration(
border: Border(
left: BorderSide(color: Colors.grey.shade300),
),
),
child: Column(
children: [
// Channels section
if (state.isConnected && state.channels.isNotEmpty) ...[
Container(
padding: const EdgeInsets.all(12),
color: Colors.blue.shade50,
child: Row(
children: [
const Icon(Icons.videocam, size: 18, color: Colors.blue),
const SizedBox(width: 8),
Text(
'Channels (${state.channels.length})',
style: const TextStyle(fontWeight: FontWeight.bold),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.refresh, size: 18),
onPressed: () {
context.read<GeViScopeBloc>().add(const RefreshChannelsEvent());
},
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
),
],
),
),
SizedBox(
height: 150,
child: ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: state.channels.length,
itemBuilder: (context, index) {
final channel = state.channels[index];
return ListTile(
dense: true,
leading: Icon(
Icons.camera_alt,
size: 16,
color: channel.isActive ? Colors.green : Colors.grey,
),
title: Text(
channel.name.isNotEmpty ? channel.name : 'Channel ${channel.channelId}',
style: const TextStyle(fontSize: 12),
),
subtitle: Text(
'ID: ${channel.channelId} | Global: ${channel.globalNumber}',
style: const TextStyle(fontSize: 10),
),
contentPadding: EdgeInsets.zero,
);
},
),
),
const Divider(height: 1),
],
// Message log section
Container(
padding: const EdgeInsets.all(12),
color: Colors.grey.shade100,
child: Row(
children: [
const Icon(Icons.list_alt, size: 18),
const SizedBox(width: 8),
const Text(
'Message Log',
style: TextStyle(fontWeight: FontWeight.bold),
),
const Spacer(),
Text(
'${state.messageLog.length}',
style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
),
],
),
),
Expanded(
child: state.messageLog.isEmpty
? const Center(
child: Text(
'No messages yet',
style: TextStyle(color: Colors.grey),
),
)
: ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: state.messageLog.length,
itemBuilder: (context, index) {
final reversedIndex = state.messageLog.length - 1 - index;
return Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
margin: const EdgeInsets.only(bottom: 4),
decoration: BoxDecoration(
color: Colors.grey.shade50,
borderRadius: BorderRadius.circular(4),
),
child: Text(
state.messageLog[reversedIndex],
style: const TextStyle(
fontFamily: 'monospace',
fontSize: 11,
),
),
);
},
),
),
],
),
);
}
Color _getStatusColor(GeViScopeConnectionStatus status) {
switch (status) {
case GeViScopeConnectionStatus.connected:
return Colors.green;
case GeViScopeConnectionStatus.connecting:
return Colors.orange;
case GeViScopeConnectionStatus.error:
return Colors.red;
case GeViScopeConnectionStatus.disconnected:
return Colors.grey;
}
}
IconData _getStatusIcon(GeViScopeConnectionStatus status) {
switch (status) {
case GeViScopeConnectionStatus.connected:
return Icons.check_circle;
case GeViScopeConnectionStatus.connecting:
return Icons.sync;
case GeViScopeConnectionStatus.error:
return Icons.error;
case GeViScopeConnectionStatus.disconnected:
return Icons.cancel;
}
}
String _getStatusText(GeViScopeConnectionStatus status) {
switch (status) {
case GeViScopeConnectionStatus.connected:
return 'Connected';
case GeViScopeConnectionStatus.connecting:
return 'Connecting...';
case GeViScopeConnectionStatus.error:
return 'Error';
case GeViScopeConnectionStatus.disconnected:
return 'Disconnected';
}
}
}

View File

@@ -0,0 +1,691 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../blocs/geviserver/geviserver_bloc.dart';
import '../../blocs/geviserver/geviserver_event.dart';
import '../../blocs/geviserver/geviserver_state.dart';
import '../../widgets/app_drawer.dart';
class GeViServerScreen extends StatefulWidget {
const GeViServerScreen({super.key});
@override
State<GeViServerScreen> createState() => _GeViServerScreenState();
}
class _GeViServerScreenState extends State<GeViServerScreen> {
// Connection form controllers
final _addressController = TextEditingController(text: 'localhost');
final _usernameController = TextEditingController(text: 'sysadmin');
final _passwordController = TextEditingController(text: 'masterkey');
// CrossSwitch form controllers
final _videoInputController = TextEditingController(text: '1');
final _videoOutputController = TextEditingController(text: '1');
final _switchModeController = TextEditingController(text: '0');
// Digital I/O controller
final _contactIdController = TextEditingController(text: '1');
// Custom action controllers
final _customActionTypeIdController = TextEditingController(text: '1');
final _customActionTextController = TextEditingController(text: 'Test message');
// Raw message controller
final _rawMessageController = TextEditingController();
bool _didCheckStatus = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Check status on init (only once)
if (!_didCheckStatus) {
_didCheckStatus = true;
context.read<GeViServerBloc>().add(const CheckStatusEvent());
}
}
@override
void dispose() {
_addressController.dispose();
_usernameController.dispose();
_passwordController.dispose();
_videoInputController.dispose();
_videoOutputController.dispose();
_switchModeController.dispose();
_contactIdController.dispose();
_customActionTypeIdController.dispose();
_customActionTextController.dispose();
_rawMessageController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('GeViServer Control'),
actions: [
BlocBuilder<GeViServerBloc, GeViServerState>(
builder: (context, state) {
return Row(
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: _getStatusColor(state.connectionStatus).withOpacity(0.2),
borderRadius: BorderRadius.circular(16),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
_getStatusIcon(state.connectionStatus),
size: 16,
color: _getStatusColor(state.connectionStatus),
),
const SizedBox(width: 6),
Text(
_getStatusText(state.connectionStatus),
style: TextStyle(
color: _getStatusColor(state.connectionStatus),
fontWeight: FontWeight.bold,
),
),
],
),
),
const SizedBox(width: 16),
],
);
},
),
],
),
drawer: const AppDrawer(currentRoute: '/geviserver'),
body: BlocConsumer<GeViServerBloc, GeViServerState>(
listener: (context, state) {
if (state.lastActionResult != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.lastActionResult!),
backgroundColor: state.lastActionSuccess ? Colors.green : Colors.red,
duration: const Duration(seconds: 2),
),
);
context.read<GeViServerBloc>().add(const ClearActionResultEvent());
}
},
builder: (context, state) {
return Row(
children: [
// Left panel - Controls
Expanded(
flex: 2,
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildConnectionCard(context, state),
const SizedBox(height: 16),
if (state.isConnected) ...[
_buildVideoControlCard(context, state),
const SizedBox(height: 16),
_buildDigitalIOCard(context, state),
const SizedBox(height: 16),
_buildCustomActionCard(context, state),
const SizedBox(height: 16),
_buildRawMessageCard(context, state),
],
],
),
),
),
// Right panel - Message log
Expanded(
flex: 1,
child: _buildMessageLogPanel(context, state),
),
],
);
},
),
);
}
Widget _buildConnectionCard(BuildContext context, GeViServerState state) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
Icons.power_settings_new,
color: state.isConnected ? Colors.green : Colors.grey,
),
const SizedBox(width: 8),
Text(
'Connection',
style: Theme.of(context).textTheme.titleLarge,
),
],
),
const Divider(),
if (!state.isConnected) ...[
Row(
children: [
Expanded(
child: TextField(
controller: _addressController,
decoration: const InputDecoration(
labelText: 'Server Address',
hintText: 'localhost',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _usernameController,
decoration: const InputDecoration(
labelText: 'Username',
hintText: 'sysadmin',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _passwordController,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Password',
border: OutlineInputBorder(),
isDense: true,
),
),
),
],
),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
context.read<GeViServerBloc>().add(
ConnectGeViServerEvent(
address: _addressController.text,
username: _usernameController.text,
password: _passwordController.text,
),
);
},
icon: state.isLoading
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.link),
label: Text(state.isLoading ? 'Connecting...' : 'Connect'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
),
),
),
] else ...[
ListTile(
leading: const Icon(Icons.computer, color: Colors.green),
title: Text('Connected to ${state.serverAddress}'),
subtitle: Text('User: ${state.username}'),
contentPadding: EdgeInsets.zero,
),
const SizedBox(height: 8),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
context.read<GeViServerBloc>().add(
const DisconnectGeViServerEvent(),
);
},
icon: const Icon(Icons.link_off),
label: const Text('Disconnect'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
),
),
],
],
),
),
);
}
Widget _buildVideoControlCard(BuildContext context, GeViServerState state) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.videocam, color: Colors.blue),
const SizedBox(width: 8),
Text(
'Video Control',
style: Theme.of(context).textTheme.titleLarge,
),
],
),
const Divider(),
Row(
children: [
Expanded(
child: TextField(
controller: _videoInputController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Video Input',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _videoOutputController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Video Output',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _switchModeController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Switch Mode',
border: OutlineInputBorder(),
isDense: true,
),
),
),
],
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
context.read<GeViServerBloc>().add(
SendCrossSwitchEvent(
videoInput: int.tryParse(_videoInputController.text) ?? 1,
videoOutput: int.tryParse(_videoOutputController.text) ?? 1,
switchMode: int.tryParse(_switchModeController.text) ?? 0,
),
);
},
icon: const Icon(Icons.swap_horiz),
label: const Text('CrossSwitch'),
),
),
const SizedBox(width: 8),
Expanded(
child: ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
context.read<GeViServerBloc>().add(
ClearVideoOutputEvent(
videoOutput: int.tryParse(_videoOutputController.text) ?? 1,
),
);
},
icon: const Icon(Icons.clear),
label: const Text('Clear Output'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.orange,
foregroundColor: Colors.white,
),
),
),
],
),
],
),
),
);
}
Widget _buildDigitalIOCard(BuildContext context, GeViServerState state) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.toggle_on, color: Colors.purple),
const SizedBox(width: 8),
Text(
'Digital I/O',
style: Theme.of(context).textTheme.titleLarge,
),
],
),
const Divider(),
Row(
children: [
Expanded(
flex: 2,
child: TextField(
controller: _contactIdController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Contact ID',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
Expanded(
child: ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
context.read<GeViServerBloc>().add(
CloseContactEvent(
contactId: int.tryParse(_contactIdController.text) ?? 1,
),
);
},
icon: const Icon(Icons.lock),
label: const Text('Close'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
),
),
const SizedBox(width: 8),
Expanded(
child: ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
context.read<GeViServerBloc>().add(
OpenContactEvent(
contactId: int.tryParse(_contactIdController.text) ?? 1,
),
);
},
icon: const Icon(Icons.lock_open),
label: const Text('Open'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
),
),
),
],
),
],
),
),
);
}
Widget _buildCustomActionCard(BuildContext context, GeViServerState state) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.send, color: Colors.teal),
const SizedBox(width: 8),
Text(
'Custom Action',
style: Theme.of(context).textTheme.titleLarge,
),
],
),
const Divider(),
Row(
children: [
Expanded(
child: TextField(
controller: _customActionTypeIdController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Type ID',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
Expanded(
flex: 3,
child: TextField(
controller: _customActionTextController,
decoration: const InputDecoration(
labelText: 'Text',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
ElevatedButton.icon(
onPressed: state.isLoading
? null
: () {
context.read<GeViServerBloc>().add(
SendCustomActionEvent(
typeId: int.tryParse(_customActionTypeIdController.text) ?? 1,
text: _customActionTextController.text,
),
);
},
icon: const Icon(Icons.send),
label: const Text('Send'),
),
],
),
],
),
),
);
}
Widget _buildRawMessageCard(BuildContext context, GeViServerState state) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.code, color: Colors.indigo),
const SizedBox(width: 8),
Text(
'Raw Message',
style: Theme.of(context).textTheme.titleLarge,
),
],
),
const Divider(),
Row(
children: [
Expanded(
child: TextField(
controller: _rawMessageController,
decoration: const InputDecoration(
labelText: 'Action Message',
hintText: 'e.g., CrossSwitch(7, 3, 0)',
border: OutlineInputBorder(),
isDense: true,
),
),
),
const SizedBox(width: 8),
ElevatedButton.icon(
onPressed: state.isLoading || _rawMessageController.text.isEmpty
? null
: () {
context.read<GeViServerBloc>().add(
SendMessageEvent(
message: _rawMessageController.text,
),
);
_rawMessageController.clear();
},
icon: const Icon(Icons.send),
label: const Text('Send'),
),
],
),
],
),
),
);
}
Widget _buildMessageLogPanel(BuildContext context, GeViServerState state) {
return Container(
decoration: BoxDecoration(
border: Border(
left: BorderSide(color: Colors.grey.shade300),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(16),
color: Colors.grey.shade100,
child: Row(
children: [
const Icon(Icons.list_alt, size: 20),
const SizedBox(width: 8),
const Text(
'Message Log',
style: TextStyle(fontWeight: FontWeight.bold),
),
const Spacer(),
Text(
'${state.messageLog.length} messages',
style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
),
],
),
),
Expanded(
child: state.messageLog.isEmpty
? const Center(
child: Text(
'No messages yet',
style: TextStyle(color: Colors.grey),
),
)
: ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: state.messageLog.length,
itemBuilder: (context, index) {
final reversedIndex = state.messageLog.length - 1 - index;
return Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
margin: const EdgeInsets.only(bottom: 4),
decoration: BoxDecoration(
color: Colors.grey.shade50,
borderRadius: BorderRadius.circular(4),
),
child: Text(
state.messageLog[reversedIndex],
style: const TextStyle(
fontFamily: 'monospace',
fontSize: 12,
),
),
);
},
),
),
],
),
);
}
Color _getStatusColor(ConnectionStatus status) {
switch (status) {
case ConnectionStatus.connected:
return Colors.green;
case ConnectionStatus.connecting:
return Colors.orange;
case ConnectionStatus.error:
return Colors.red;
case ConnectionStatus.disconnected:
return Colors.grey;
}
}
IconData _getStatusIcon(ConnectionStatus status) {
switch (status) {
case ConnectionStatus.connected:
return Icons.check_circle;
case ConnectionStatus.connecting:
return Icons.sync;
case ConnectionStatus.error:
return Icons.error;
case ConnectionStatus.disconnected:
return Icons.cancel;
}
}
String _getStatusText(ConnectionStatus status) {
switch (status) {
case ConnectionStatus.connected:
return 'Connected';
case ConnectionStatus.connecting:
return 'Connecting...';
case ConnectionStatus.error:
return 'Error';
case ConnectionStatus.disconnected:
return 'Disconnected';
}
}
}

View File

@@ -1,7 +1,12 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:html' as html;
import '../../../domain/entities/server.dart';
import '../../../data/services/excel_import_service.dart';
import '../../../data/data_sources/local/server_local_data_source.dart';
import '../../../injection.dart' as di;
import '../../blocs/auth/auth_bloc.dart';
import '../../blocs/auth/auth_event.dart';
import '../../blocs/auth/auth_state.dart';
@@ -140,6 +145,147 @@ class _ServersManagementScreenState extends State<ServersManagementScreen> {
);
}
Future<void> _importFromExcel() async {
print('[Import] Function called');
try {
print('[Import] Creating ExcelImportService...');
// Create ExcelImportService with ServerLocalDataSource from DI
final localDataSource = di.sl<ServerLocalDataSource>();
final excelImportService = ExcelImportService(localDataSource: localDataSource);
print('[Import] ExcelImportService created');
print('[Import] Opening file picker...');
// Pick Excel file
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['xlsx'],
withData: true, // Important for web - loads file data
);
print('[Import] File picker returned');
if (result == null || result.files.isEmpty) {
return; // User cancelled
}
final file = result.files.first;
if (file.bytes == null) {
throw Exception('Could not read file data');
}
// Show loading dialog
if (!mounted) return;
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => const Center(
child: Card(
child: Padding(
padding: EdgeInsets.all(24.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(),
SizedBox(height: 16),
Text('Importing servers from Excel...'),
],
),
),
),
),
);
// Parse Excel file via backend API
print('[Import] Calling backend API...');
final importedServers = await excelImportService.importServersFromExcel(
file.bytes!,
file.name,
);
print('[Import] Received ${importedServers.length} servers from API');
// Get existing servers
final bloc = context.read<ServerBloc>();
final state = bloc.state;
final existingServers = state is ServerLoaded ? state.servers : <Server>[];
print('[Import] Found ${existingServers.length} existing servers');
// Merge: only add new servers
final newServers = excelImportService.mergeServers(
existing: existingServers,
imported: importedServers,
);
print('[Import] ${newServers.length} new servers to add');
// Check if there are new servers
print('[Import] Import summary: ${importedServers.length} total, ${newServers.length} new');
if (newServers.isEmpty) {
print('[Import] No new servers to add');
// Close loading dialog
if (mounted) {
try {
Navigator.of(context).pop();
} catch (e) {
print('[Import] Error closing dialog: $e');
}
}
return;
}
print('[Import] Proceeding with import of ${newServers.length} servers');
// Save servers directly to storage, bypassing the bloc to avoid triggering rebuilds
print('[Import] Saving ${newServers.length} servers directly to storage...');
try {
await excelImportService.saveImportedServersToStorage(newServers);
print('[Import] All servers saved to storage as unsaved changes');
} catch (e) {
print('[Import] ERROR saving servers to storage: $e');
throw Exception('Failed to save servers: $e');
}
// Import complete - reload page
print('[Import] Successfully imported ${newServers.length} servers');
print('[Import] Servers added as unsaved changes. Use Sync button to upload to GeViServer.');
// Save redirect path so we return to servers page after reload
html.window.localStorage['post_import_redirect'] = '/servers';
// Brief delay to ensure Hive writes complete
await Future.delayed(const Duration(milliseconds: 300));
print('[Import] Reloading page (auth tokens now persist in localStorage)...');
// Reload page WITHOUT closing dialog to avoid crash
// Auth tokens are now stored in localStorage so you'll stay logged in!
html.window.location.reload();
} catch (e, stackTrace) {
print('[Import] ERROR: $e');
print('[Import] Stack trace: $stackTrace');
// Close loading dialog if open
if (mounted) {
try {
Navigator.of(context, rootNavigator: true).pop();
} catch (_) {
// Dialog might already be closed
}
}
// Show error
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Import failed: $e'),
backgroundColor: Colors.red,
duration: const Duration(seconds: 5),
),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -194,15 +340,56 @@ class _ServersManagementScreenState extends State<ServersManagementScreen> {
);
},
),
// Download/refresh button
Builder(
builder: (context) => IconButton(
icon: const Icon(Icons.cloud_download),
onPressed: () {
context.read<ServerBloc>().add(const DownloadServersEvent());
},
tooltip: 'Download latest from server',
),
// Download/refresh button with confirmation if there are unsaved changes
BlocBuilder<ServerBloc, ServerState>(
builder: (context, state) {
final dirtyCount = state is ServerLoaded ? state.dirtyCount : 0;
return IconButton(
icon: const Icon(Icons.cloud_download),
onPressed: () async {
// Show confirmation if there are unsaved changes
if (dirtyCount > 0) {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('Discard Changes?'),
content: Text(
'You have $dirtyCount unsaved change${dirtyCount != 1 ? 's' : ''}. '
'Downloading from server will discard all local changes.\n\n'
'Do you want to continue?'
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
style: FilledButton.styleFrom(
backgroundColor: Colors.orange,
),
child: const Text('Discard & Download'),
),
],
),
);
if (confirmed == true) {
if (context.mounted) {
context.read<ServerBloc>().add(const DownloadServersEvent());
}
}
} else {
// No unsaved changes, download directly
context.read<ServerBloc>().add(const DownloadServersEvent());
}
},
tooltip: dirtyCount > 0
? 'Discard $dirtyCount change${dirtyCount != 1 ? 's' : ''} & download from server'
: 'Download latest from server',
);
},
),
const SizedBox(width: 8),
BlocBuilder<AuthBloc, AuthState>(
@@ -278,6 +465,23 @@ class _ServersManagementScreenState extends State<ServersManagementScreen> {
),
),
const SizedBox(width: 16),
OutlinedButton.icon(
onPressed: () {
print('[Import] Button clicked');
try {
_importFromExcel();
} catch (e, stackTrace) {
print('[Import] Button handler error: $e');
print('[Import] Button handler stack: $stackTrace');
}
},
icon: const Icon(Icons.upload_file, size: 18),
label: const Text('Import Excel'),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
),
),
const SizedBox(width: 12),
ElevatedButton.icon(
onPressed: () {
_showAddServerDialog(context);

View File

@@ -105,6 +105,18 @@ class AppDrawer extends StatelessWidget {
title: 'Action Mappings',
route: '/action-mappings',
),
_buildNavItem(
context,
icon: Icons.computer,
title: 'GeViServer',
route: '/geviserver',
),
_buildNavItem(
context,
icon: Icons.videocam,
title: 'GeViScope',
route: '/geviscope',
),
_buildNavItem(
context,
icon: Icons.settings,

View File

@@ -5,11 +5,13 @@
import FlutterMacOS
import Foundation
import file_picker
import flutter_secure_storage_macos
import path_provider_foundation
import shared_preferences_foundation
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin"))
FlutterSecureStoragePlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStoragePlugin"))
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))

View File

@@ -40,6 +40,10 @@ dependencies:
dartz: ^0.10.1
uuid: ^4.5.1
# File handling
file_picker: ^8.1.4
excel: ^4.0.6
dev_dependencies:
flutter_test:
sdk: flutter