Skip to main content

hikvision_acs_ble 1.0.1 copy "hikvision_acs_ble: ^1.0.1" to clipboard
hikvision_acs_ble: ^1.0.1 copied to clipboard

Flutter package for Hikvision Access Control Terminal BLE unlocking with direct ISAPI integration and zero backend dependency.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:hikvision_acs_ble/hikvision_acs_ble.dart';

void main() {
  runApp(const MaterialApp(
    title: 'Hikvision ACS BLE Demo',
    debugShowCheckedModeBanner: false,
    home: HikvisionExampleScreen(),
  ));
}

class HikvisionExampleScreen extends StatefulWidget {
  const HikvisionExampleScreen({super.key});

  @override
  State<HikvisionExampleScreen> createState() => _HikvisionExampleScreenState();
}

class _HikvisionExampleScreenState extends State<HikvisionExampleScreen> {
  final HikvisionAcsClient _client = HikvisionAcsClient();

  // Controllers
  final _ipController = TextEditingController(text: '192.168.1.100');
  final _portController = TextEditingController(text: '80');
  final _usernameController = TextEditingController(text: 'admin');
  final _passwordController = TextEditingController(text: 'Hikvision123');
  final _employeeNoController = TextEditingController(text: '1001');

  // State
  bool _isLoading = false;
  String _currentStatus = 'Idle';
  final List<String> _logs = [];
  List<DiscoveredTerminal> _terminals = [];
  AcsEncryptionInfo? _cachedEncryptionInfo;

  @override
  void dispose() {
    _client.dispose();
    _ipController.dispose();
    _portController.dispose();
    _usernameController.dispose();
    _passwordController.dispose();
    _employeeNoController.dispose();
    super.dispose();
  }

  void _addLog(String message) {
    setState(() {
      _logs.insert(0, '${DateTime.now().toIso8601String().substring(11, 19)} - $message');
      if (_logs.length > 100) _logs.removeLast();
    });
  }

  AcsDeviceConfig _getConfig() {
    return AcsDeviceConfig(
      ipAddress: _ipController.text.trim(),
      port: int.tryParse(_portController.text.trim()) ?? 80,
      username: _usernameController.text.trim(),
      password: _passwordController.text.trim(),
    );
  }

  // 1. Scan Terminals
  Future<void> _scanTerminals() async {
    setState(() {
      _isLoading = true;
      _currentStatus = 'Scanning BLE...';
      _terminals = [];
    });
    _addLog('Starting BLE Scan for 5 seconds...');

    try {
      final results = await _client.scanNearbyTerminals(
        timeout: const Duration(seconds: 5),
        onLog: _addLog,
      );

      setState(() {
        _terminals = results;
        _currentStatus = 'Scan finished (${results.length} found)';
      });
      _addLog('Scan completed: ${results.length} terminals found.');
    } catch (e) {
      _addLog('Scan error: $e');
      setState(() => _currentStatus = 'Scan error');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  // 2. Fetch and Cache Encryption Info (for Offline Mode)
  Future<void> _fetchAndCacheEncryptionInfo() async {
    setState(() {
      _isLoading = true;
      _currentStatus = 'Fetching ISAPI parameters...';
    });

    try {
      final config = _getConfig();
      _addLog('Connecting to ${config.ipAddress}:${config.port}...');
      final info = await _client.fetchEncryptionInfo(config);
      setState(() {
        _cachedEncryptionInfo = info;
        _currentStatus = 'Encryption info cached!';
      });
      _addLog('✅ Cached Encryption Info: authData=${info.authData.substring(0, 8)}... loop=${info.loopCount}');
    } catch (e) {
      _addLog('❌ Fetch error: $e');
      setState(() => _currentStatus = 'Fetch failed');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  // 3. Online Unlock via ISAPI + BLE
  Future<void> _unlockOnline() async {
    setState(() {
      _isLoading = true;
      _currentStatus = 'Starting Online Unlock...';
    });

    try {
      final config = _getConfig();
      final result = await _client.unlockDoorWithIsapi(
        config: config,
        employeeNo: _employeeNoController.text.trim(),
        doorId: 1,
        onStatusChanged: (status, detail) {
          setState(() => _currentStatus = '${status.label}: ${detail ?? ""}');
        },
        onLog: _addLog,
      );

      if (result.isSuccess) {
        _addLog('🎉 Door Unlocked Successfully! (${result.duration?.inMilliseconds}ms)');
      } else {
        _addLog('❌ Unlock Failed: ${result.statusDescription} (Code: ${result.statusCode})');
      }
    } catch (e) {
      _addLog('❌ Online unlock error: $e');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  // 4. Smart Offline Unlock
  Future<void> _unlockOffline() async {
    if (_cachedEncryptionInfo == null) {
      _addLog('⚠️ Please fetch and cache encryption info first!');
      return;
    }

    setState(() {
      _isLoading = true;
      _currentStatus = 'Starting Offline Unlock...';
    });

    try {
      final result = await _client.unlockDoorWithEncryptionInfo(
        encryptionInfo: _cachedEncryptionInfo!,
        employeeNo: _employeeNoController.text.trim(),
        doorId: 1,
        onStatusChanged: (status, detail) {
          setState(() => _currentStatus = '${status.label}: ${detail ?? ""}');
        },
        onLog: _addLog,
      );

      if (result.isSuccess) {
        _addLog('🎉 [Offline] Door Unlocked Successfully!');
      } else {
        _addLog('❌ [Offline] Unlock Failed: ${result.statusDescription}');
      }
    } catch (e) {
      _addLog('❌ Offline unlock error: $e');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Hikvision ACS BLE Demo'),
        backgroundColor: Colors.blueGrey.shade800,
        foregroundColor: Colors.white,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // Status Card
            Card(
              color: Colors.blueGrey.shade900,
              child: Padding(
                padding: const EdgeInsets.all(12.0),
                child: Row(
                  children: [
                    if (_isLoading)
                      const Padding(
                        padding: EdgeInsets.only(right: 12.0),
                        child: SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2),
                        ),
                      ),
                    Expanded(
                      child: Text(
                        'Status: $_currentStatus',
                        style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 12),

            // Form Configuration
            Card(
              child: Padding(
                padding: const EdgeInsets.all(12.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('Terminal & User Config', style: TextStyle(fontWeight: FontWeight.bold)),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Expanded(flex: 3, child: TextField(controller: _ipController, decoration: const InputDecoration(labelText: 'IP Address', isDense: true))),
                        const SizedBox(width: 8),
                        Expanded(flex: 1, child: TextField(controller: _portController, decoration: const InputDecoration(labelText: 'Port', isDense: true), keyboardType: TextInputType.number)),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Expanded(child: TextField(controller: _usernameController, decoration: const InputDecoration(labelText: 'ISAPI User', isDense: true))),
                        const SizedBox(width: 8),
                        Expanded(child: TextField(controller: _passwordController, decoration: const InputDecoration(labelText: 'ISAPI Password', isDense: true), obscureText: true)),
                      ],
                    ),
                    const SizedBox(height: 8),
                    TextField(controller: _employeeNoController, decoration: const InputDecoration(labelText: 'Employee No / ID', isDense: true)),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 12),

            // Action Buttons
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                ElevatedButton.icon(
                  onPressed: _isLoading ? null : _scanTerminals,
                  icon: const Icon(Icons.bluetooth_searching),
                  label: const Text('Scan BLE'),
                ),
                ElevatedButton.icon(
                  onPressed: _isLoading ? null : _fetchAndCacheEncryptionInfo,
                  icon: const Icon(Icons.cloud_download),
                  label: const Text('Cache ISAPI Keys'),
                ),
                FilledButton.icon(
                  onPressed: _isLoading ? null : _unlockOnline,
                  icon: const Icon(Icons.lock_open),
                  label: const Text('Unlock (Online)'),
                ),
                FilledButton.tonalIcon(
                  onPressed: _isLoading || _cachedEncryptionInfo == null ? null : _unlockOffline,
                  icon: const Icon(Icons.offline_bolt),
                  label: const Text('Unlock (Offline BLE)'),
                ),
              ],
            ),
            const SizedBox(height: 12),

            // Discovered Terminals
            if (_terminals.isNotEmpty) ...[
              const Text('Discovered Terminals:', style: TextStyle(fontWeight: FontWeight.bold)),
              const SizedBox(height: 4),
              ..._terminals.map((t) => ListTile(
                    dense: true,
                    leading: const Icon(Icons.devices, color: Colors.blue),
                    title: Text('${t.name} (${t.serialNumber ?? "Unknown Serial"})'),
                    subtitle: Text('ID: ${t.id} | RSSI: ${t.rssi} dBm'),
                  )),
              const SizedBox(height: 12),
            ],

            // Log Console
            const Text('Event & Debug Logs:', style: TextStyle(fontWeight: FontWeight.bold)),
            const SizedBox(height: 4),
            Container(
              height: 200,
              padding: const EdgeInsets.all(8.0),
              decoration: BoxDecoration(
                color: Colors.black87,
                borderRadius: BorderRadius.circular(8),
              ),
              child: _logs.isEmpty
                  ? const Center(child: Text('No logs yet.', style: TextStyle(color: Colors.grey)))
                  : ListView.builder(
                      itemCount: _logs.length,
                      itemBuilder: (context, index) {
                        return Text(
                          _logs[index],
                          style: const TextStyle(color: Colors.greenAccent, fontSize: 11, fontFamily: 'monospace'),
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }
}
1
likes
140
points
25
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Flutter package for Hikvision Access Control Terminal BLE unlocking with direct ISAPI integration and zero backend dependency.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

crypto, encrypt, flutter, flutter_blue_plus, http, permission_handler

More

Packages that depend on hikvision_acs_ble