Bunch of updates, next up is token pipeline

This commit is contained in:
2025-12-22 20:26:33 -06:00
parent e0a41761ec
commit bd9ce4022f
12 changed files with 582 additions and 167 deletions

View File

@@ -7,6 +7,33 @@ import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:google_fonts/google_fonts.dart';
enum authTypes {
OPEN,
WEP,
WPA_PSK,
WPA2_PSK,
WPA_WPA2_PSK,
WPA2_ENTERPRISE,
WPA3_PSK,
WPA2_WPA3_PSK,
WAPI_PSK,
OWE,
WPA3_ENT_192,
WPA3_EXT_PSK,
WPA3_EXT_PSK_MIXED_MODE,
DPP,
WPA3_ENTERPRISE,
WPA2_WPA3_ENTERPRISE,
WPA_ENTERPRISE
}
const List<authTypes> enterprise = [
authTypes.WPA_ENTERPRISE,authTypes.WPA2_ENTERPRISE,
authTypes.WPA3_ENTERPRISE,authTypes.WPA2_WPA3_ENTERPRISE,
authTypes.WPA3_ENT_192
];
class DeviceSetup extends StatefulWidget {
final BluetoothDevice device;
@@ -19,17 +46,16 @@ class DeviceSetup extends StatefulWidget {
class _DeviceSetupState extends State<DeviceSetup> {
List<BluetoothService> _services = [];
List<String> openNetworks = [];
List<String> pskNetworks = [];
List<Map<String, dynamic>> networks = [];
late StreamSubscription<List<int>> _ssidSub;
StreamSubscription<List<int>>? _confirmSub;
Widget? wifiList;
String? message;
String? password;
final passControl = TextEditingController();
final unameControl = TextEditingController();
@override void initState() {
super.initState();
@@ -44,93 +70,77 @@ class _DeviceSetupState extends State<DeviceSetup> {
super.dispose();
}
Future setWifiListListener(BluetoothCharacteristic ssidListChar) async {
setState(() {
wifiList = null;
});
await ssidListChar.setNotifyValue(true);
_ssidSub = ssidListChar.onValueReceived.listen((List<int> value) {
List<String> ssidList = [];
bool noNetworks = false;
Future setRefreshListener(BluetoothCharacteristic ssidRefreshChar, BluetoothCharacteristic ssidListChar) async {
await ssidRefreshChar.setNotifyValue(true);
_ssidSub = ssidRefreshChar.onValueReceived.listen((List<int> value) async {
try {
final val = utf8.decode(value);
if (val == ';') noNetworks = true;
ssidList = val
.split(';')
.map((s) => s.trim())
.where((s) => s.isNotEmpty)
.toList();
openNetworks = ssidList
.where((s) => s.split(',')[1] == "OPEN")
.map((s) => s.split(',')[0])
.toList();
pskNetworks = ssidList
.where((s) => s.split(',')[1] == "SECURED")
.map((s) => s.split(',')[0])
.toList();
final command = utf8.decode(value);
if (command == "Ready") {
// Device is ready, now read the WiFi list
List<int> rawData = await ssidListChar.read();
try {
final val = utf8.decode(rawData);
networks = json.decode(val) as List<Map<String, dynamic>>;
} catch (e) {
if(!mounted)return;
ScaffoldMessenger.of(context).showSnackBar(errorSnackbar(e));
}
// Acknowledge completion
try {
await ssidRefreshChar.write(utf8.encode("Done"), withoutResponse: ssidRefreshChar.properties.writeWithoutResponse);
} catch (e) {
if(!mounted)return;
ScaffoldMessenger.of(context).showSnackBar(errorSnackbar(Exception("Failed to send Done")));
}
if(!mounted)return;
setState(() {
wifiList = networks.isEmpty
? SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.6,
child: const Center(
child: Text(
"No networks found...",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 15),
),
),
),
)
: ListView(
children: [
...buildSSIDs()
],
);
});
}
} catch (e) {
if(!mounted)return;
ScaffoldMessenger.of(context).showSnackBar(errorSnackbar(e));
}
setState(() {
wifiList = noNetworks
? SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.6,
child: const Center(
child: Text(
"No networks found...",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 15),
),
),
),
)
: ssidList.isNotEmpty
? ListView(
children: [
...buildSSIDs()
],
)
: null;
});
});
}
List<Widget> buildSSIDs() {
List<Widget> open = openNetworks.map((s) {
List<Widget> networkList = networks.map((s) {
return Card(
child: ListTile(
leading: const Icon(Icons.wifi),
title: Text(s),
leading: Icon((s["rssi"] as int < -70) ? Icons.wifi_1_bar : ((s["rssi"] as int < -50) ? Icons.wifi_2_bar: Icons.wifi)),
title: Text(s["ssid"] as String),
subtitle: Text(authTypes.values[s["auth"] as int].name),
trailing: const Icon(Icons.arrow_forward_ios_rounded),
onTap: () {
openConnect(s);
authenticate(s);
},
),
);
}).toList();
List<Widget> secure = pskNetworks.map((s) {
return Card(
child: ListTile(
leading: const Icon(Icons.wifi_password),
title: Text(s),
trailing: const Icon(Icons.arrow_forward_ios_rounded),
onTap: () {
setPassword(s);
},
),
);
}).toList();
return open + secure;
}
Future openConnect(String ssid) async {
await transmitWiFiDetails(ssid, "");
return networkList;
}
Future discoverServices() async{
@@ -157,37 +167,74 @@ class _DeviceSetupState extends State<DeviceSetup> {
Future initSetup() async {
await discoverServices();
final ssidListChar = _services[0].characteristics.lastWhere((c) => c.uuid.str == "0000");
await setWifiListListener(ssidListChar);
final ssidRefreshChar = _services[0].characteristics.lastWhere((c) => c.uuid.str == "0004");
await setRefreshListener(ssidRefreshChar, ssidListChar);
refreshWifiList();
}
Future setPassword(String ssid) async {
String? password = await showDialog(
bool isEnterprise(Map<String, dynamic> network) {
authTypes type = authTypes.values[network["auth"] as int];
return enterprise.contains(type);
}
bool isOpen(Map<String, dynamic> network) {
authTypes type = authTypes.values[network["auth"] as int];
return type == authTypes.OPEN;
}
Future authenticate(Map<String, dynamic> network) async {
bool ent = isEnterprise(network);
bool open = isOpen(network);
Map<String, String> creds = await showDialog(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: Text(
ssid,
network["ssid"],
style: GoogleFonts.aBeeZee(),
),
content: Form(
autovalidateMode: AutovalidateMode.onUnfocus,
child: TextFormField(
controller: passControl,
obscureText: true,
decoration: const InputDecoration(hintText: "Enter password"),
validator: (value) {
if (value == null) return "null input";
if (value.length < 8) return "not long enough!";
return null;
},
textInputAction: TextInputAction.send,
onFieldSubmitted: (value) => Navigator.pop(dialogContext, passControl.text),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (ent)
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
controller: unameControl,
decoration: const InputDecoration(hintText: "Enter your enterprise login"),
textInputAction: TextInputAction.next, // Shows "Next" on keyboard
onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(), // Moves to password
validator: (value) => (value == null || value.isEmpty) ? "Empty username!" : null,
),
const SizedBox(height: 16),
]
),
if (!open)
TextFormField(
controller: passControl,
obscureText: true,
decoration: const InputDecoration(hintText: "Enter password"),
validator: (value) => (value == null || value.length < 8) ? "Not long enough!" : null,
textInputAction: TextInputAction.send,
onFieldSubmitted: (value) {
if (Form.of(context).validate()) {
Navigator.pop(dialogContext, (ent ?
{"uname": unameControl.text, "password": passControl.text}
: (open ? {} : {"password": passControl.text})));
}
},
),
]
)
),
actions: [
TextButton(
onPressed: () {
unameControl.clear();
passControl.clear();
Navigator.pop(dialogContext);
},
@@ -197,6 +244,7 @@ class _DeviceSetupState extends State<DeviceSetup> {
onPressed: () {
Navigator.pop(dialogContext, passControl.text);
passControl.clear();
unameControl.clear();
},
child: const Text("Connect"),
),
@@ -205,37 +253,30 @@ class _DeviceSetupState extends State<DeviceSetup> {
}
);
await transmitWiFiDetails(ssid, password);
if (creds["password"] == null && !open) return;
if (creds["uname"] == null && ent) return;
await transmitWiFiDetails(network["ssid"], network["auth"], creds);
}
Future transmitWiFiDetails(String ssid, String? password) async {
if (password == null) return;
Future transmitWiFiDetails(String ssid, int auth, Map<String, String> creds) async {
setState(() {
wifiList = null;
message = "Attempting Connection...";
});
final ssidEntryChar = _services[0].characteristics.lastWhere((c) => c.uuid.str == "0001");
final credsChar = _services[0].characteristics.lastWhere((c) => c.uuid.str == "0001");
Map<String, dynamic> credsJson = {
"ssid": ssid,
"auth": auth,
...creds, // Spread operator adds all key-value pairs from creds
};
try {
String jsonString = json.encode(credsJson);
try {
await ssidEntryChar.write(utf8.encode(ssid), withoutResponse: ssidEntryChar.properties.writeWithoutResponse);
await credsChar.write(utf8.encode(jsonString), withoutResponse: credsChar.properties.writeWithoutResponse);
} catch (e) {
throw Exception("SSID Write Error");
}
} catch (e){
if(!mounted)return;
ScaffoldMessenger.of(context).showSnackBar(errorSnackbar(e));
refreshWifiList();
return;
}
final passEntryChar = _services[0].characteristics.lastWhere((c) => c.uuid.str == "0002");
try {
try {
await passEntryChar.write(utf8.encode(password), withoutResponse: passEntryChar.properties.writeWithoutResponse);
} catch (e) {
throw Exception("Password Write Error");
throw Exception("Credentials Write Error");
}
} catch (e){
if(!mounted)return;
@@ -265,7 +306,7 @@ class _DeviceSetupState extends State<DeviceSetup> {
});
} else if (connectResponse == "Error") {
_confirmSub?.cancel();
throw Exception("SSID/Password Incorrect");
throw Exception("SSID/Password Incorrect / Other credential error");
}
} catch (e) {
if (!mounted) return;
@@ -279,12 +320,13 @@ class _DeviceSetupState extends State<DeviceSetup> {
Future refreshWifiList() async{
final ssidRefreshChar = _services[0].characteristics.lastWhere((c) => c.uuid.str == "0004");
setState(() {
wifiList = null;
message = null;
});
try {
try {
await ssidRefreshChar.write(utf8.encode("refresh"), withoutResponse: ssidRefreshChar.properties.writeWithoutResponse);
await ssidRefreshChar.write(utf8.encode("Start"), withoutResponse: ssidRefreshChar.properties.writeWithoutResponse);
} catch (e) {
throw Exception ("Refresh Error");
}

View File

@@ -0,0 +1,204 @@
import 'package:blind_master/main.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class DayTimePicker extends StatefulWidget {
const DayTimePicker({super.key, required this.defaultTime, required this.sendSchedule});
final TimeOfDay defaultTime;
final void Function(TimeOfDay) sendSchedule;
@override
State<DayTimePicker> createState() => _DayTimePickerState();
}
class _DayTimePickerState extends State<DayTimePicker> {
TimeOfDay? scheduleTime;
double _blindPosition = 0;
String imagePath = "";
Set<DaysOfWeek> days = <DaysOfWeek>{};
@override
void initState() {
super.initState();
updateBackground();
}
Future selectTime() async {
scheduleTime = await showTimePicker(
context: context,
initialTime: scheduleTime ?? widget.defaultTime,
) ?? (scheduleTime ?? widget.defaultTime);
setState(() {
updateBackground();
});
}
void updateBackground() {
final hour = scheduleTime?.hour ?? widget.defaultTime.hour;
if (hour >= 5 && hour < 10) {
imagePath = 'assets/images/MorningSill.png';
} else if (hour >= 10 && hour < 18) {
imagePath = 'assets/images/NoonSill.png';
} else if (hour >= 18 && hour < 22) {
imagePath = 'assets/images/EveningSill.png';
} else {
imagePath = 'assets/images/NightSill.png';
}
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(
'New Schedule',
style: GoogleFonts.aBeeZee(),
),
content: Column(
mainAxisSize: MainAxisSize.min, // Keep column compact
children: <Widget>[
Text(
"Move to position"
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.3,
child: Container(
padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: MediaQuery.of(context).size.width * 0.11,
),
Stack(
children: [
// Background image
Align(
alignment: Alignment.center,
child: Image.asset(
imagePath,
// fit: BoxFit.cover,
width: MediaQuery.of(context).size.width * 0.45,
),
),
Align(
alignment: Alignment.center,
child: Container(
margin: EdgeInsets.only(top: MediaQuery.of(context).size.width * 0.05),
height: MediaQuery.of(context).size.width * 0.43,
width: MediaQuery.of(context).size.width * 0.45,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: List.generate(10, (index) {
return AnimatedContainer(
duration: const Duration(milliseconds: 300),
height: _blindPosition < 5 ?
3.65 * (5 - _blindPosition)
: 3.65 * (_blindPosition - 5),
width: MediaQuery.of(context).size.width * 0.40, // example
color: const Color.fromARGB(255, 121, 85, 72),
);
}),
),
)
),
],
),
// Slider on the side
Align(
alignment: Alignment.centerRight,
child: RotatedBox(
quarterTurns: -1,
child: Slider(
value: _blindPosition,
activeColor: Theme.of(context).primaryColorDark,
thumbColor: Theme.of(context).primaryColorLight,
inactiveColor: Theme.of(context).primaryColorDark,
min: 0,
max: 10,
divisions: 10,
onChanged: (value) {
setState(() {
_blindPosition = value;
});
},
),
),
)
],
),
)
),
Text(
"At"
),
Theme(
data: Theme.of(context).copyWith(
timePickerTheme: TimePickerThemeData(
hourMinuteColor: Theme.of(context).primaryColorDark,
dialBackgroundColor: Theme.of(context).primaryColorDark,
)
),
child: ElevatedButton(
onPressed: selectTime,
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)
),
backgroundColor: Theme.of(context).primaryColorDark,
foregroundColor: Theme.of(context).highlightColor
),
child: Text(scheduleTime?.format(context) ?? widget.defaultTime.format(context)),
),
),
Container(
padding: EdgeInsets.all(10),
child: Text(
"Every"
),
),
Wrap(
spacing: 5.0,
alignment: WrapAlignment.center,
children: DaysOfWeek.values.map((DaysOfWeek day) {
return FilterChip(
showCheckmark: false,
label: Text(day.name),
selected: days.contains(day),
selectedColor: Theme.of(context).primaryColorDark,
onSelected: (bool selected) {
setState(() {
if (selected) {
days.add(day);
} else {
days.remove(day);
}
});
},
);
}).toList(),
),
],
),
actions: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
"Cancel",
style: TextStyle(
color: Colors.red
),
)
),
]
)
],
);
}
}

View File

@@ -140,7 +140,7 @@ class _DeviceScreenState extends State<DeviceScreen> {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PeripheralScreen(peripheralId: peripheral['id'],
builder: (context) => PeripheralScreen(deviceName: deviceName, peripheralId: peripheral['id'],
peripheralNum: peripheral['port'], deviceId: widget.deviceId,),
),
).then((_) { populatePeripherals(); });
@@ -220,7 +220,7 @@ class _DeviceScreenState extends State<DeviceScreen> {
),
const SizedBox(height: 20),
DropdownButtonFormField<int>(
value: port,
initialValue: port,
decoration: const InputDecoration(
labelText: 'Hub Port',
border: OutlineInputBorder(),

View File

@@ -159,17 +159,20 @@ class _DevicesMenuState extends State<DevicesMenu> {
Widget build(BuildContext context) {
return Scaffold(
body: deviceList ?? const Center(child: CircularProgressIndicator()),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AddDevice()),
);
},
foregroundColor: Theme.of(context).highlightColor,
backgroundColor: Theme.of(context).primaryColorDark,
child: Icon(Icons.add),
),
floatingActionButton: Container(
padding: EdgeInsets.all(25),
child:FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AddDevice()),
);
},
foregroundColor: Theme.of(context).highlightColor,
backgroundColor: Theme.of(context).primaryColorDark,
child: Icon(Icons.add),
),
)
);
}
}

View File

@@ -10,10 +10,11 @@ import 'package:google_fonts/google_fonts.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;
class PeripheralScreen extends StatefulWidget {
const PeripheralScreen({super.key, required this.peripheralId, required this.deviceId, required this.peripheralNum});
const PeripheralScreen({super.key, required this.peripheralId, required this.deviceId, required this.peripheralNum, required this.deviceName});
final int peripheralId;
final int peripheralNum;
final int deviceId;
final String deviceName;
@override
State<PeripheralScreen> createState() => _PeripheralScreenState();
}
@@ -334,7 +335,7 @@ class _PeripheralScreenState extends State<PeripheralScreen> {
return Scaffold(
appBar: AppBar(
title: Text(
peripheralName,
"${widget.deviceName} - $peripheralName",
style: GoogleFonts.aBeeZee(),
),
backgroundColor: Theme.of(context).primaryColorLight,
@@ -462,7 +463,8 @@ class _PeripheralScreenState extends State<PeripheralScreen> {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SchedulesScreen()
builder: (context) => SchedulesScreen(peripheralId: widget.peripheralId, periphName: peripheralName,
deviceId: widget.deviceId, peripheralNum: widget.peripheralNum, deviceName: widget.deviceName,)
)
);
},

View File

@@ -1,15 +1,169 @@
import 'dart:convert';
import 'package:blind_master/BlindMasterResources/error_snackbar.dart';
import 'package:blind_master/BlindMasterResources/secure_transmissions.dart';
import 'package:blind_master/BlindMasterScreens/day_time_picker.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class SchedulesScreen extends StatefulWidget {
const SchedulesScreen({super.key});
const SchedulesScreen({super.key, required this.peripheralId, required this.deviceId,
required this.peripheralNum, required this.deviceName, required this.periphName});
final int peripheralId;
final int peripheralNum;
final int deviceId;
final String deviceName;
final String periphName;
@override
State<SchedulesScreen> createState() => _SchedulesScreenState();
}
class _SchedulesScreenState extends State<SchedulesScreen> {
List<Map<String, dynamic>> schedules = [];
Widget? scheduleList;
@override
void initState() {
super.initState();
getSchedules();
}
Future getSchedules() async {
try{
final payload = {
"periphId": widget.deviceId
};
final response = await securePost(payload, 'periph_schedule_list');
if (response == null) throw Exception("no response!");
if (response.statusCode == 200) {
final body = json.decode(response.body) as Map<String, dynamic>;
List tempList = body['scheduledUpdates'] as List;
schedules = tempList
.whereType<Map<String, dynamic>>()
.toList();
}
} catch(e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
errorSnackbar(e)
);
}
setState(() {
scheduleList = RefreshIndicator(
onRefresh: getSchedules,
child: schedules.isEmpty
? SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.6,
child: const Center(
child: Text(
"No schedules found...\nAdd one using the '+' button",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 16),
),
),
),
)
: ListView.builder(
itemCount: schedules.length,
itemBuilder: (context, i) {
final schedule = schedules[i];
return Dismissible(
key: Key(schedule['id'].toString()),
direction: DismissDirection.endToStart,
background: Container(
color: Colors.red,
alignment: Alignment.centerRight,
padding: const EdgeInsets.symmetric(horizontal: 20),
child: const Icon(Icons.delete, color: Colors.white),
),
confirmDismiss: (direction) async {
// Ask for confirmation (optional)
return await showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Delete Schedule'),
content: const Text('Are you sure you want to delete this schedule?'),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Delete'),
),
],
),
);
},
onDismissed: (direction) {
// TODO Actually delete the schedule
// deleteDevice(device['id'], i);
},
child: Card(
child: ListTile(
leading: const Icon(Icons.blinds),
title: Text("${schedule['pos']} every ${schedule['schedule']['daysOfWeek']} at ${schedule['schedule']['hours']}:${schedule['schedule']['minutes']}"),
trailing: const Icon(Icons.arrow_forward_ios_rounded),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Placeholder(),
// TODO open popup for schedule setter.
),
).then((_) { getSchedules(); });
},
),
),
);
},
),
);
});
return Future.delayed(Duration(milliseconds: 500));
}
Future<void> sendSchedule(TimeOfDay scheduleTime) async {
return;
}
void addSchedule() {
showDialog(
context: context,
builder: (BuildContext dialogContext) { // Use dialogContext for navigation within the dialog
return DayTimePicker(defaultTime: TimeOfDay(hour: 12, minute: 0), sendSchedule: sendSchedule);
}
);
}
@override
Widget build(BuildContext context) {
return const Placeholder();
return Scaffold(
appBar: AppBar(
title: Text(
"Schedules: ${widget.deviceName} - ${widget.periphName}",
style: GoogleFonts.aBeeZee(),
),
backgroundColor: Theme.of(context).primaryColorLight,
foregroundColor: Colors.white,
),
body: scheduleList ?? const Center(child: CircularProgressIndicator()),
floatingActionButton: Container(
padding: EdgeInsets.all(25),
child: FloatingActionButton(
backgroundColor: Theme.of(context).primaryColorDark,
foregroundColor: Theme.of(context).highlightColor,
heroTag: "add",
onPressed: addSchedule,
tooltip: "Add Schedule",
child: Icon(Icons.add),
)
)
);
}
}

View File

@@ -1,6 +1,8 @@
import 'package:blind_master/BlindMasterScreens/Startup/splash_screen.dart';
import 'package:flutter/material.dart';
enum DaysOfWeek {Su, M, Tu, W, Th, F, Sa}
void main() {
runApp(const MyApp());
}