Вы находитесь на странице: 1из 7

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';

void main() => runApp(new MyApp());

///
///
///
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}

///
///
///
class _MyAppState extends State<MyApp> {
static final TextEditingController _message = new TextEditingController();
static final TextEditingController _text = new TextEditingController();

List<Map<String, dynamic>> _times = [


{
"hours": 0,
"minutes": 0,
},
{
"hours": 0,
"minutes": 0,
},
];

FlutterBluetoothSerial bluetooth = FlutterBluetoothSerial.instance;

List<BluetoothDevice> _devices = [];


BluetoothDevice _device;
bool _connected = false;
bool _pressed = false;
Timer _timer0;
Timer _timer1;
int minutes0 = 0;
int minutes1 = 0;

///
///
///
@override
void initState() {
super.initState();
initPlatformState();
}

void startTimer(int relay) {


const oneMin = const Duration(minutes: 1);
if(relay == 0){
_timer0 = new Timer.periodic(
oneMin,
(Timer timer) => setState(() {
if (_times[0]["minutes"] < 1 && _times[0]["hours"] < 1) {
timer.cancel();
} else {
_times[0]["minutes"] -= 1;
if(_times[0]["minutes"] < 0){
_times[0]["hours"] -= 1;
_times[0]["minutes"] = 59;
}
if(_times[0]["hours"] < 0){
_times[0]["hours"] = 0;
timer.cancel();
}
}
})
);
}else{
_timer1 = new Timer.periodic(
oneMin,
(Timer timer) => setState(() {
if (_times[1]["minutes"] < 1 && _times[1]["hours"] < 1) {
timer.cancel();
} else {
_times[1]["minutes"] -= 1;
if(_times[1]["minutes"] < 0){
_times[1]["hours"] -= 1;
_times[1]["minutes"] = 59;
}
if(_times[1]["hours"] < 0){
_times[1]["hours"] = 0;
timer.cancel();
}
}
})
);
}
}

///
///
///
Future<void> initPlatformState() async {
List<BluetoothDevice> devices = [];

try {
devices = await bluetooth.getBondedDevices();
} on PlatformException {
// TODO - Error
}

bluetooth.onStateChanged().listen((state) {
switch (state) {
case FlutterBluetoothSerial.CONNECTED:
setState(() {
_connected = true;
_pressed = false;
});
break;
case FlutterBluetoothSerial.DISCONNECTED:
setState(() {
_connected = false;
_pressed = false;
});
break;
default:
// TODO
print(state);
break;
}
});

bluetooth.onRead().listen((msg) {
setState(() {
print('Read: $msg');
_text.text += msg;
});
});

if (!mounted) return;
setState(() {
_devices = devices;
});
}

///
///
///
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Super Enchufe",
home: Scaffold(
appBar: AppBar(
title: Text('Super Enchufe'),
),
body: Container(
child: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 0.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'Device:',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
DropdownButton(
items: _getDeviceItems(),
onChanged: (value) => setState(() => _device = value),
value: _device,
),
RaisedButton(
onPressed:
_pressed ? null : _connected ? _disconnect : _connect,
child: Text(_connected ? 'Disconnect' : 'Connect'),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 0.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'Toma 1:',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
Expanded(
child: Builder(builder: (BuildContext context){
return FlatButton(
onPressed: () {
DateTime now = DateTime.now();
DatePicker.showTimePicker(
context,
currentTime: DateTime(now.year, now.month, now.day,
_times[0]["hours"], _times[0]["minutes"]),
showTitleActions: true,
onConfirm: (date){
setState((){
_times[0]["hours"] = date.hour;
_times[0]["minutes"] = date.minute;
});
},
);
},
child: Text(
(_times[0]["hours"] < 10 ? "0" : "") + _times[0]
["hours"].toString() + ":" + (_times[0]["minutes"] < 10 ? "0" : "") + _times[0]
["minutes"].toString(),
style: TextStyle(color: Colors.blue),
)
);
},),
),
RaisedButton(
onPressed: (){
if(_connected){
_writeTest(0);
}
},
child: Text('Setear'),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 0.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'Toma 2:',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
Expanded(
child: Builder(builder: (BuildContext context){
return FlatButton(
onPressed: () {
DateTime now = DateTime.now();
DatePicker.showTimePicker(
context,
currentTime: DateTime(now.year, now.month, now.day,
_times[1]["hours"], _times[1]["minutes"]),
showTitleActions: true,
onConfirm: (date){
setState((){
_times[1]["hours"] = date.hour;
_times[1]["minutes"] = date.minute;
});
},
);
},
child: Text(
(_times[1]["hours"] < 10 ? "0" : "") + _times[1]
["hours"].toString() + ":" + (_times[1]["minutes"] < 10 ? "0" : "") + _times[1]
["minutes"].toString(),
style: TextStyle(color: Colors.blue),
)
);
},),
),
RaisedButton(
onPressed: (){
if(_connected){
_writeTest(1);
}
},
child: Text('Setear'),
),
],
),
),

],
),
),
),
);
}

///
///
///
List<DropdownMenuItem<BluetoothDevice>> _getDeviceItems() {
List<DropdownMenuItem<BluetoothDevice>> items = [];
if (_devices.isEmpty) {
items.add(DropdownMenuItem(
child: Text('NONE'),
));
} else {
_devices.forEach((device) {
items.add(DropdownMenuItem(
child: Text(device.name),
value: device,
));
});
}
return items;
}

///
///
///
void _connect() {
if (_device == null) {
show('No device selected.');
} else {
bluetooth.isConnected.then((isConnected) {
if (!isConnected) {
bluetooth.connect(_device).catchError((error) {
setState(() => _pressed = false);
});
setState(() => _pressed = true);
}
});
}
}

///
///
///
void _disconnect() {
bluetooth.disconnect();
setState(() => _pressed = true);
}

///
///
///
void _writeTest(int relay) {
bluetooth.isConnected.then((isConnected) {
if (isConnected) {
int val = _times[relay]["hours"]*60+_times[relay]["minutes"];
if(val > 999){
val = 999;
}
setState((){
if(relay == 0){
minutes0 = val;
}else{
minutes1 = val;
}
});
startTimer(relay);

String timer = val.toString();


while(timer.length < 3){
timer = "0" + timer;
}
bluetooth.write("/"+relay.toString()+timer+"\\");
}
});
}

///
///
///
Future show(
String message, {
Duration duration: const Duration(seconds: 3),
}) async {
await new Future.delayed(new Duration(milliseconds: 100));
Scaffold.of(context).showSnackBar(
new SnackBar(
content: new Text(
message,
style: new TextStyle(
color: Colors.white,
),
),
duration: duration,
),
);
}
}

Вам также может понравиться