Skip to content

Commit

Permalink
use timer
Browse files Browse the repository at this point in the history
  • Loading branch information
herzhenr committed Aug 20, 2023
1 parent 8a64a15 commit ed82a84
Showing 1 changed file with 56 additions and 61 deletions.
117 changes: 56 additions & 61 deletions lib/screens/home/home.dart
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,25 @@ class _HomePageState extends State<HomePage> {

late SortingOrder selectedMenu = widget.selectedMenu;

Timer? _timer;

@override
void initState() {
super.initState();
_loadDevices().then((value) => {
filterDevicesByType(),
sortDevices(),
_pingDevices(),
});
}

@override
void dispose() {
_timer?.cancel();
print('---------timer canceled----------');
super.dispose();
}

/// sort Devices by chipsDeviceTypes selection
void filterDevicesByType() {
List<StorageDevice> sortedDevices = [];
Expand All @@ -65,8 +75,7 @@ class _HomePageState extends State<HomePage> {
sortedDevices.add(device);
} else {
for (int i = 0; i < widget.chipsDeviceTypes.length; i++) {
if (deviceTypesValues[i] &&
device.deviceType == widget.chipsDeviceTypes[i].value) {
if (deviceTypesValues[i] && device.deviceType == widget.chipsDeviceTypes[i].value) {
sortedDevices.add(device);
break;
}
Expand All @@ -80,29 +89,42 @@ class _HomePageState extends State<HomePage> {

/// ping devices periodically in the background to get the current status
/// of the devices and update the ui accordingly
// void _pingDevices() {
// for (StorageDevice device in _devices) {
// Network.ping(device.hostName!).then((value) {
// if (value) {
// setState(() {
// device.status = DeviceStatus.online;
// });
// } else {
// setState(() {
// device.status = DeviceStatus.offline;
// });
// }
// });
// }
// }
void _pingDevices() {
print('---------timer started----------');
_timer = Timer.periodic(const Duration(seconds: 10), (timer) {
for (StorageDevice device in _devices) {
checkStatus(device);
}
});
}

/// ping a device and update the ui accordingly
/// [device] is the device to ping
/// if the widget is not mounted anymore, the function will stop
Future<void> checkStatus(StorageDevice device) async {
print('pinging device: ${device.hostName}');
bool isOnline = await pingDevice(ipAddress: device.ipAddress);
setState(() {
device.isOnline = isOnline;
});
// while (mounted) {
// print('pinging device: ${device.hostName}');
// bool isOnline = await pingDevice(ipAddress: device.ipAddress);
// if (mounted) {
// setState(() {
// device.isOnline = isOnline;
// });
// }
// await Future.delayed(const Duration(seconds: 10));
// }
}

/// sort devices by selectedMenu value. [alphabetical], [recently] and [type] are possible.
void sortDevices() {
switch (selectedMenu) {
case SortingOrder.alphabetical:
setState(() {
_devices.sort((a, b) =>
a.hostName.toLowerCase().compareTo(b.hostName.toLowerCase()));
_devices.sort((a, b) => a.hostName.toLowerCase().compareTo(b.hostName.toLowerCase()));
});
break;
case SortingOrder.recently:
Expand All @@ -112,9 +134,7 @@ class _HomePageState extends State<HomePage> {
break;
case SortingOrder.type:
setState(() {
_devices.sort((a, b) => a.deviceType == null
? -1
: a.deviceType!.compareTo(b.deviceType ?? ''));
_devices.sort((a, b) => a.deviceType == null ? -1 : a.deviceType!.compareTo(b.deviceType ?? ''));
});
break;
}
Expand Down Expand Up @@ -154,8 +174,7 @@ class _HomePageState extends State<HomePage> {
),
// The menu should appear below the button. The offset is dependent of the selected menu item so the offset is calculated dependent of
// the current selected menu item.
offset: Offset(0,
00 + 50.0 * (SortingOrder.values[selectedMenu.index].index + 1)),
offset: Offset(0, 00 + 50.0 * (SortingOrder.values[selectedMenu.index].index + 1)),
initialValue: selectedMenu,
// Callback that sets the selected popup menu item.
onSelected: (SortingOrder item) {
Expand Down Expand Up @@ -234,8 +253,7 @@ class _HomePageState extends State<HomePage> {

/// returns a List of Chips for filtering devices
ListView filterDevicesChipsV2() {
List<CustomChoiceChip<String>> chipsDeviceTypes =
AppConstants().getChipsDeviceTypes(context: context);
List<CustomChoiceChip<String>> chipsDeviceTypes = AppConstants().getChipsDeviceTypes(context: context);
return ListView(
primary: true,
shrinkWrap: true,
Expand All @@ -253,13 +271,9 @@ class _HomePageState extends State<HomePage> {
if (label != null) Text(label),
],
),
backgroundColor: deviceTypesValues[index]
? Theme.of(context).colorScheme.secondaryContainer
: Theme.of(context).colorScheme.surface,
backgroundColor: deviceTypesValues[index] ? Theme.of(context).colorScheme.secondaryContainer : Theme.of(context).colorScheme.surface,
side: BorderSide(
color: deviceTypesValues[index]
? Theme.of(context).colorScheme.secondaryContainer
: Theme.of(context).colorScheme.secondary,
color: deviceTypesValues[index] ? Theme.of(context).colorScheme.secondaryContainer : Theme.of(context).colorScheme.secondary,
width: 1.0,
),
// selected: mode == chipsTheme[index].value,
Expand All @@ -277,8 +291,7 @@ class _HomePageState extends State<HomePage> {

/// returns a List of Chips for filtering devices
ListView filterDevicesChipsV1() {
List<CustomChoiceChip<String>> chipsDeviceTypes =
AppConstants().getChipsDeviceTypes(context: context);
List<CustomChoiceChip<String>> chipsDeviceTypes = AppConstants().getChipsDeviceTypes(context: context);
return ListView(
primary: true,
shrinkWrap: true,
Expand Down Expand Up @@ -319,8 +332,7 @@ class _HomePageState extends State<HomePage> {
child: CircularProgressIndicator(),
)
: _devices.isEmpty
? Text(AppLocalizations.of(context)!.homeNoDevices,
style: Theme.of(context).textTheme.bodyMedium)
? Text(AppLocalizations.of(context)!.homeNoDevices, style: Theme.of(context).textTheme.bodyMedium)
: ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
Expand Down Expand Up @@ -367,20 +379,12 @@ class _HomePageState extends State<HomePage> {
showDialog(
context: context,
builder: (BuildContext context) {
return deviceInfoDialog(
device: device,
title: title,
subtitle1: subtitle1,
subtitle2: subtitle2);
return deviceInfoDialog(device: device, title: title, subtitle1: subtitle1, subtitle2: subtitle2);
});
}

/// returns the actual alert dialog for waking and editing the device
Widget deviceInfoDialog(
{required StorageDevice device,
required String title,
required String subtitle1,
required String subtitle2}) {
Widget deviceInfoDialog({required StorageDevice device, required String title, required String subtitle1, required String subtitle2}) {
return customDualChoiceAlertdialog(
title: title != "" ? title : null,
child: (subtitle1 != "" || subtitle2 != "")
Expand All @@ -400,11 +404,7 @@ class _HomePageState extends State<HomePage> {
rightOnPressed: () => {
Navigator.of(context).pop(),
showCustomBottomSheet(
context: context,
formPage: EditDeviceFormPage(
title: "Edit Device",
device: device,
onSubmitDeviceCallback: updateDevicesList))
context: context, formPage: EditDeviceFormPage(title: "Edit Device", device: device, onSubmitDeviceCallback: updateDevicesList))
});
}

Expand All @@ -416,21 +416,18 @@ class _HomePageState extends State<HomePage> {
builder: (context) {
return StreamBuilder<List<Message>>(
stream: sendWolAndGetMessages(device: device.toNetworkDevice()),
builder: (BuildContext context,
AsyncSnapshot<List<Message>> snapshot) {
builder: (BuildContext context, AsyncSnapshot<List<Message>> snapshot) {
// set color, text and icon of dialog box according to the arrived messages
Color? color;
String rightText = AppLocalizations.of(context)!.cancel;
IconData? rightIcon = AppConstants.denyIcon;
if (snapshot.hasData &&
snapshot.data!.last.type == MsgType.online) {
if (snapshot.hasData && snapshot.data!.last.type == MsgType.online) {
color = AppConstants.successMessageColor;
rightText = AppLocalizations.of(context)!.done;
rightIcon = AppConstants.checkIcon;
}

if (snapshot.hasData &&
snapshot.data!.last.type == MsgType.error) {
if (snapshot.hasData && snapshot.data!.last.type == MsgType.error) {
color = Theme.of(context).colorScheme.error;
rightText = AppLocalizations.of(context)!.ok;
rightIcon = null;
Expand All @@ -442,8 +439,7 @@ class _HomePageState extends State<HomePage> {
? SizedBox(
width: 200,
child: ListView.separated(
separatorBuilder: (context, index) =>
const Divider(),
separatorBuilder: (context, index) => const Divider(),
shrinkWrap: true,
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
Expand All @@ -453,8 +449,7 @@ class _HomePageState extends State<HomePage> {
style: TextStyle(
color: (message.type == MsgType.error)
? Theme.of(context).colorScheme.error
: (message.type == MsgType.check ||
message.type == MsgType.online)
: (message.type == MsgType.check || message.type == MsgType.online)
? AppConstants.successMessageColor
: null,
),
Expand Down

0 comments on commit ed82a84

Please sign in to comment.