Каркас приложения: авторизация, зоны/устройства/правила, управление устройствами
HTTP-клиент к /api/v1 с Sanctum-токеном (хранится в secure storage), модели зеркалят Laravel API Resources. Экраны: логин, список устройств с живым статусом, детальная страница устройства (история телеметрии, turn-on/turn-off/set-level с проверкой capability), списки зон и правил автоматизации (пока только чтение — формы создания/редактирования впереди).
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../core/api_service.dart';
|
||||
import '../models/automation_rule.dart';
|
||||
|
||||
class AutomationRulesTab extends StatefulWidget {
|
||||
const AutomationRulesTab({super.key});
|
||||
|
||||
@override
|
||||
State<AutomationRulesTab> createState() => _AutomationRulesTabState();
|
||||
}
|
||||
|
||||
class _AutomationRulesTabState extends State<AutomationRulesTab> {
|
||||
late Future<List<AutomationRule>> _future;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_future = _load();
|
||||
}
|
||||
|
||||
Future<List<AutomationRule>> _load() => context.read<ApiService>().automationRules();
|
||||
|
||||
Future<void> _refresh() async {
|
||||
final future = _load();
|
||||
setState(() => _future = future);
|
||||
await future;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return RefreshIndicator(
|
||||
onRefresh: _refresh,
|
||||
child: FutureBuilder<List<AutomationRule>>(
|
||||
future: _future,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState != ConnectionState.done) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (snapshot.hasError) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text('${snapshot.error}', textAlign: TextAlign.center),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
final rules = snapshot.data!;
|
||||
if (rules.isEmpty) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
children: const [
|
||||
Padding(
|
||||
padding: EdgeInsets.all(24),
|
||||
child: Text('Правил пока нет.', textAlign: TextAlign.center),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return ListView.separated(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
itemCount: rules.length,
|
||||
separatorBuilder: (context, index) => const Divider(height: 1),
|
||||
itemBuilder: (context, index) {
|
||||
final rule = rules[index];
|
||||
final condition =
|
||||
'${rule.conditionSourceDevice?.name ?? '?'}: ${rule.conditionSensorType} ${rule.conditionOperator} ${rule.conditionValue}';
|
||||
final action = rule.level != null
|
||||
? '${rule.actionType} (${rule.level}) → ${rule.targetDevice?.name ?? '?'}'
|
||||
: '${rule.actionType} → ${rule.targetDevice?.name ?? '?'}';
|
||||
|
||||
return ListTile(
|
||||
leading: Icon(rule.isActive ? Icons.bolt : Icons.bolt_outlined),
|
||||
title: Text('ЕСЛИ $condition'),
|
||||
subtitle: Text('ТО $action'),
|
||||
isThreeLine: true,
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../core/api_client.dart';
|
||||
import '../core/api_service.dart';
|
||||
import '../models/device.dart';
|
||||
import '../widgets/status_badge.dart';
|
||||
|
||||
class DeviceDetailScreen extends StatefulWidget {
|
||||
const DeviceDetailScreen({super.key, required this.deviceId});
|
||||
|
||||
final int deviceId;
|
||||
|
||||
@override
|
||||
State<DeviceDetailScreen> createState() => _DeviceDetailScreenState();
|
||||
}
|
||||
|
||||
class _DeviceDetailScreenState extends State<DeviceDetailScreen> {
|
||||
late Future<DeviceDetail> _future;
|
||||
bool _isSendingCommand = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_future = _load();
|
||||
}
|
||||
|
||||
Future<DeviceDetail> _load() => context.read<ApiService>().device(widget.deviceId);
|
||||
|
||||
Future<void> _refresh() async {
|
||||
final future = _load();
|
||||
setState(() => _future = future);
|
||||
await future;
|
||||
}
|
||||
|
||||
Future<void> _runCommand(Future<String> Function() command) async {
|
||||
setState(() => _isSendingCommand = true);
|
||||
try {
|
||||
final message = await command();
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
|
||||
await _refresh();
|
||||
} on ApiException catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.message)));
|
||||
} finally {
|
||||
if (mounted) setState(() => _isSendingCommand = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _promptSetLevel(int deviceId) async {
|
||||
final apiService = context.read<ApiService>();
|
||||
double level = 50;
|
||||
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => StatefulBuilder(
|
||||
builder: (context, setDialogState) => AlertDialog(
|
||||
title: const Text('Установить уровень'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text('${level.round()}'),
|
||||
Slider(
|
||||
value: level,
|
||||
min: 0,
|
||||
max: 100,
|
||||
divisions: 100,
|
||||
onChanged: (value) => setDialogState(() => level = value),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Отмена')),
|
||||
FilledButton(onPressed: () => Navigator.pop(context, true), child: const Text('Отправить')),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed == true) {
|
||||
await _runCommand(() => apiService.setLevel(deviceId, level));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final apiService = context.read<ApiService>();
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Устройство')),
|
||||
body: RefreshIndicator(
|
||||
onRefresh: _refresh,
|
||||
child: FutureBuilder<DeviceDetail>(
|
||||
future: _future,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState != ConnectionState.done) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (snapshot.hasError) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text('${snapshot.error}', textAlign: TextAlign.center),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
final detail = snapshot.data!;
|
||||
final device = detail.device;
|
||||
final capabilities = device.deviceType?.capabilities ?? const [];
|
||||
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(device.name, style: Theme.of(context).textTheme.headlineSmall),
|
||||
),
|
||||
StatusBadge(status: device.status),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text('${device.zone?.name ?? '—'} · ${device.deviceType?.code ?? device.protocol}'),
|
||||
if (detail.lastSeen != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text('Последний сигнал: ${detail.lastSeen}'),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
if (capabilities.contains('turn_on') || capabilities.contains('turn_off'))
|
||||
Row(
|
||||
children: [
|
||||
if (capabilities.contains('turn_on'))
|
||||
Expanded(
|
||||
child: FilledButton(
|
||||
onPressed: _isSendingCommand ? null : () => _runCommand(() => apiService.turnOn(device.id)),
|
||||
child: const Text('Включить'),
|
||||
),
|
||||
),
|
||||
if (capabilities.contains('turn_on') && capabilities.contains('turn_off'))
|
||||
const SizedBox(width: 12),
|
||||
if (capabilities.contains('turn_off'))
|
||||
Expanded(
|
||||
child: OutlinedButton(
|
||||
onPressed:
|
||||
_isSendingCommand ? null : () => _runCommand(() => apiService.turnOff(device.id)),
|
||||
child: const Text('Выключить'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (capabilities.contains('set_level')) ...[
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton(
|
||||
onPressed: _isSendingCommand ? null : () => _promptSetLevel(device.id),
|
||||
child: const Text('Установить уровень'),
|
||||
),
|
||||
],
|
||||
if (detail.reportedState.isNotEmpty) ...[
|
||||
const SizedBox(height: 24),
|
||||
Text('Сообщённое состояние', style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
_KeyValueTable(data: detail.reportedState),
|
||||
],
|
||||
if (detail.telemetry.isNotEmpty) ...[
|
||||
const SizedBox(height: 24),
|
||||
Text('История показаний', style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
...detail.telemetry.map(
|
||||
(reading) => ListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text('${reading.sensorType}: ${reading.value}'),
|
||||
subtitle: Text(reading.recordedAt),
|
||||
dense: true,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _KeyValueTable extends StatelessWidget {
|
||||
const _KeyValueTable({required this.data});
|
||||
|
||||
final Map<String, dynamic> data;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: data.entries
|
||||
.map((entry) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 2),
|
||||
child: Text('${entry.key}: ${entry.value}'),
|
||||
))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../core/api_service.dart';
|
||||
import '../models/device.dart';
|
||||
import '../widgets/status_badge.dart';
|
||||
import 'device_detail_screen.dart';
|
||||
|
||||
class DevicesTab extends StatefulWidget {
|
||||
const DevicesTab({super.key});
|
||||
|
||||
@override
|
||||
State<DevicesTab> createState() => _DevicesTabState();
|
||||
}
|
||||
|
||||
class _DevicesTabState extends State<DevicesTab> {
|
||||
late Future<List<Device>> _future;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_future = _load();
|
||||
}
|
||||
|
||||
Future<List<Device>> _load() => context.read<ApiService>().devices();
|
||||
|
||||
Future<void> _refresh() async {
|
||||
final future = _load();
|
||||
setState(() => _future = future);
|
||||
await future;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return RefreshIndicator(
|
||||
onRefresh: _refresh,
|
||||
child: FutureBuilder<List<Device>>(
|
||||
future: _future,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState != ConnectionState.done) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (snapshot.hasError) {
|
||||
return _ErrorList(message: '${snapshot.error}', onRetry: _refresh);
|
||||
}
|
||||
|
||||
final devices = snapshot.data!;
|
||||
if (devices.isEmpty) {
|
||||
return _ErrorList(message: 'Устройств пока нет.', onRetry: _refresh);
|
||||
}
|
||||
|
||||
return ListView.separated(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
itemCount: devices.length,
|
||||
separatorBuilder: (context, index) => const Divider(height: 1),
|
||||
itemBuilder: (context, index) {
|
||||
final device = devices[index];
|
||||
return ListTile(
|
||||
title: Text(device.name),
|
||||
subtitle: Text('${device.zone?.name ?? '—'} · ${device.deviceType?.code ?? device.protocol}'),
|
||||
trailing: StatusBadge(status: device.status),
|
||||
onTap: () => Navigator.of(context).push(
|
||||
MaterialPageRoute(builder: (_) => DeviceDetailScreen(deviceId: device.id)),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ErrorList extends StatelessWidget {
|
||||
const _ErrorList({required this.message, required this.onRetry});
|
||||
|
||||
final String message;
|
||||
final Future<void> Function() onRetry;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 64, horizontal: 24),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(message, textAlign: TextAlign.center),
|
||||
const SizedBox(height: 12),
|
||||
TextButton(onPressed: onRetry, child: const Text('Повторить')),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../core/auth_service.dart';
|
||||
import 'automation_rules_tab.dart';
|
||||
import 'devices_tab.dart';
|
||||
import 'zones_tab.dart';
|
||||
|
||||
class HomeScreen extends StatefulWidget {
|
||||
const HomeScreen({super.key});
|
||||
|
||||
@override
|
||||
State<HomeScreen> createState() => _HomeScreenState();
|
||||
}
|
||||
|
||||
class _HomeScreenState extends State<HomeScreen> {
|
||||
int _index = 0;
|
||||
|
||||
static const _titles = ['Устройства', 'Зоны', 'Правила'];
|
||||
static const _tabs = [DevicesTab(), ZonesTab(), AutomationRulesTab()];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(_titles[_index]),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.logout),
|
||||
tooltip: 'Выйти',
|
||||
onPressed: () => context.read<AuthService>().logout(),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: IndexedStack(index: _index, children: _tabs),
|
||||
bottomNavigationBar: NavigationBar(
|
||||
selectedIndex: _index,
|
||||
onDestinationSelected: (index) => setState(() => _index = index),
|
||||
destinations: const [
|
||||
NavigationDestination(icon: Icon(Icons.devices_other), label: 'Устройства'),
|
||||
NavigationDestination(icon: Icon(Icons.room), label: 'Зоны'),
|
||||
NavigationDestination(icon: Icon(Icons.rule), label: 'Правила'),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../core/api_client.dart';
|
||||
import '../core/auth_service.dart';
|
||||
|
||||
class LoginScreen extends StatefulWidget {
|
||||
const LoginScreen({super.key});
|
||||
|
||||
@override
|
||||
State<LoginScreen> createState() => _LoginScreenState();
|
||||
}
|
||||
|
||||
class _LoginScreenState extends State<LoginScreen> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _emailController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
|
||||
bool _isSubmitting = false;
|
||||
String? _errorMessage;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
|
||||
setState(() {
|
||||
_isSubmitting = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
|
||||
try {
|
||||
await context.read<AuthService>().login(_emailController.text.trim(), _passwordController.text);
|
||||
} on ApiException catch (e) {
|
||||
setState(() => _errorMessage = e.message);
|
||||
} finally {
|
||||
if (mounted) setState(() => _isSubmitting = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
'Домашняя автоматизация',
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
TextFormField(
|
||||
controller: _emailController,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
autofillHints: const [AutofillHints.email],
|
||||
decoration: const InputDecoration(labelText: 'Email'),
|
||||
validator: (value) => (value == null || value.isEmpty) ? 'Введите email' : null,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _passwordController,
|
||||
obscureText: true,
|
||||
autofillHints: const [AutofillHints.password],
|
||||
decoration: const InputDecoration(labelText: 'Пароль'),
|
||||
validator: (value) => (value == null || value.isEmpty) ? 'Введите пароль' : null,
|
||||
onFieldSubmitted: (_) => _submit(),
|
||||
),
|
||||
if (_errorMessage != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
_errorMessage!,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
FilledButton(
|
||||
onPressed: _isSubmitting ? null : _submit,
|
||||
child: _isSubmitting
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('Войти'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../core/api_service.dart';
|
||||
import '../models/zone.dart';
|
||||
|
||||
class ZonesTab extends StatefulWidget {
|
||||
const ZonesTab({super.key});
|
||||
|
||||
@override
|
||||
State<ZonesTab> createState() => _ZonesTabState();
|
||||
}
|
||||
|
||||
class _ZonesTabState extends State<ZonesTab> {
|
||||
late Future<List<Zone>> _future;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_future = _load();
|
||||
}
|
||||
|
||||
Future<List<Zone>> _load() => context.read<ApiService>().zones();
|
||||
|
||||
Future<void> _refresh() async {
|
||||
final future = _load();
|
||||
setState(() => _future = future);
|
||||
await future;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return RefreshIndicator(
|
||||
onRefresh: _refresh,
|
||||
child: FutureBuilder<List<Zone>>(
|
||||
future: _future,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState != ConnectionState.done) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (snapshot.hasError) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text('${snapshot.error}', textAlign: TextAlign.center),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
final zones = snapshot.data!;
|
||||
return ListView.separated(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
itemCount: zones.length,
|
||||
separatorBuilder: (context, index) => const Divider(height: 1),
|
||||
itemBuilder: (context, index) {
|
||||
final zone = zones[index];
|
||||
return ListTile(
|
||||
title: Text(zone.name),
|
||||
subtitle: zone.description != null ? Text(zone.description!) : null,
|
||||
trailing: Text('${zone.devicesCount ?? 0} устр.'),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user