Compare commits
16 Commits
Author | SHA1 | Date | |
---|---|---|---|
7f2611b410 | |||
648750655c | |||
8a0d5581d9 | |||
98d716109b | |||
ebb2f2b4e5 | |||
d910e4dd43 | |||
95d80fbbfc | |||
41297150c2 | |||
b14b248f2f | |||
13fc1bff27 | |||
eee8f21e76 | |||
8ce3560d8d | |||
9e97bac85b | |||
4a0b447f00 | |||
bc4969dae8 | |||
5025b3d384 |
@ -1,486 +0,0 @@
|
||||
part of 'main.dart';
|
||||
|
||||
class Entity {
|
||||
static const STATE_ICONS_COLORS = {
|
||||
"on": Colors.amber,
|
||||
"off": Color.fromRGBO(68, 115, 158, 1.0),
|
||||
"unavailable": Colors.black12,
|
||||
"unknown": Colors.black12,
|
||||
"playing": Colors.amber
|
||||
};
|
||||
static const RIGHT_WIDGET_PADDING = 14.0;
|
||||
static const LEFT_WIDGET_PADDING = 8.0;
|
||||
static const EXTENDED_WIDGET_HEIGHT = 50.0;
|
||||
static const WIDGET_HEIGHT = 34.0;
|
||||
static const ICON_SIZE = 28.0;
|
||||
static const STATE_FONT_SIZE = 16.0;
|
||||
static const NAME_FONT_SIZE = 16.0;
|
||||
static const SMALL_FONT_SIZE = 14.0;
|
||||
static const INPUT_WIDTH = 160.0;
|
||||
|
||||
Map _attributes;
|
||||
String _domain;
|
||||
String _entityId;
|
||||
String _state;
|
||||
DateTime _lastUpdated;
|
||||
|
||||
String get displayName =>
|
||||
_attributes["friendly_name"] ?? (_attributes["name"] ?? "_");
|
||||
String get domain => _domain;
|
||||
String get entityId => _entityId;
|
||||
String get state => _state;
|
||||
set state(value) => _state = value;
|
||||
|
||||
String get deviceClass => _attributes["device_class"] ?? null;
|
||||
bool get isView =>
|
||||
(_domain == "group") &&
|
||||
(_attributes != null ? _attributes["view"] ?? false : false);
|
||||
bool get isGroup => _domain == "group";
|
||||
String get icon => _attributes["icon"] ?? "";
|
||||
bool get isOn => state == "on";
|
||||
String get entityPicture => _attributes["entity_picture"];
|
||||
String get unitOfMeasurement => _attributes["unit_of_measurement"] ?? "";
|
||||
List get childEntities => _attributes["entity_id"] ?? [];
|
||||
String get lastUpdated => _getLastUpdatedFormatted();
|
||||
|
||||
Entity(Map rawData) {
|
||||
update(rawData);
|
||||
}
|
||||
|
||||
void update(Map rawData) {
|
||||
_attributes = rawData["attributes"] ?? {};
|
||||
_domain = rawData["entity_id"].split(".")[0];
|
||||
_entityId = rawData["entity_id"];
|
||||
_state = rawData["state"];
|
||||
_lastUpdated = DateTime.tryParse(rawData["last_updated"]);
|
||||
}
|
||||
|
||||
String _getLastUpdatedFormatted() {
|
||||
if (_lastUpdated == null) {
|
||||
return "-";
|
||||
} else {
|
||||
DateTime now = DateTime.now();
|
||||
Duration d = now.difference(_lastUpdated);
|
||||
String text;
|
||||
int v;
|
||||
if (d.inDays == 0) {
|
||||
if (d.inHours == 0) {
|
||||
if (d.inMinutes == 0) {
|
||||
text = "seconds ago";
|
||||
v = d.inSeconds;
|
||||
} else {
|
||||
text = "minutes ago";
|
||||
v = d.inMinutes;
|
||||
}
|
||||
} else {
|
||||
text = "hours ago";
|
||||
v = d.inHours;
|
||||
}
|
||||
} else {
|
||||
text = "days ago";
|
||||
v = d.inDays;
|
||||
}
|
||||
return "$v $text";
|
||||
}
|
||||
}
|
||||
|
||||
void openEntityPage() {
|
||||
eventBus.fire(new ShowEntityPageEvent(this));
|
||||
}
|
||||
|
||||
void sendNewState(newState) {
|
||||
return;
|
||||
}
|
||||
|
||||
Widget buildWidget(bool inCard, BuildContext context) {
|
||||
return SizedBox(
|
||||
height: Entity.WIDGET_HEIGHT,
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
GestureDetector(
|
||||
child: _buildIconWidget(),
|
||||
onTap: inCard ? openEntityPage : null,
|
||||
),
|
||||
Expanded(
|
||||
child: GestureDetector(
|
||||
child: _buildNameWidget(),
|
||||
onTap: inCard ? openEntityPage : null,
|
||||
),
|
||||
),
|
||||
_buildActionWidget(inCard, context)
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget buildAdditionalWidget() {
|
||||
return _buildLastUpdatedWidget();
|
||||
}
|
||||
|
||||
Widget _buildIconWidget() {
|
||||
return Padding(
|
||||
padding: EdgeInsets.fromLTRB(Entity.LEFT_WIDGET_PADDING, 0.0, 12.0, 0.0),
|
||||
child: MaterialDesignIcons.createIconWidgetFromEntityData(
|
||||
this,
|
||||
Entity.ICON_SIZE,
|
||||
Entity.STATE_ICONS_COLORS[_state] ?? Colors.blueGrey),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLastUpdatedWidget() {
|
||||
return Padding(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
Entity.LEFT_WIDGET_PADDING, Entity.SMALL_FONT_SIZE, 0.0, 0.0),
|
||||
child: Text(
|
||||
'${this.lastUpdated}',
|
||||
textAlign: TextAlign.left,
|
||||
style:
|
||||
TextStyle(fontSize: Entity.SMALL_FONT_SIZE, color: Colors.black26),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildNameWidget() {
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(right: 10.0),
|
||||
child: Text(
|
||||
"${this.displayName}",
|
||||
overflow: TextOverflow.ellipsis,
|
||||
softWrap: false,
|
||||
style: TextStyle(fontSize: Entity.NAME_FONT_SIZE),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
return Padding(
|
||||
padding:
|
||||
EdgeInsets.fromLTRB(0.0, 0.0, Entity.RIGHT_WIDGET_PADDING, 0.0),
|
||||
child: GestureDetector(
|
||||
child: Text(
|
||||
"$_state${this.unitOfMeasurement}",
|
||||
textAlign: TextAlign.right,
|
||||
style: new TextStyle(
|
||||
fontSize: Entity.STATE_FONT_SIZE,
|
||||
)),
|
||||
onTap: openEntityPage,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class SwitchEntity extends Entity {
|
||||
SwitchEntity(Map rawData) : super(rawData);
|
||||
|
||||
@override
|
||||
void sendNewState(newValue) {
|
||||
eventBus.fire(new ServiceCallEvent(
|
||||
_domain, (newValue as bool) ? "turn_on" : "turn_off", entityId, null));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
return Switch(
|
||||
value: this.isOn,
|
||||
onChanged: ((switchState) {
|
||||
sendNewState(switchState);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ButtonEntity extends Entity {
|
||||
ButtonEntity(Map rawData) : super(rawData);
|
||||
|
||||
@override
|
||||
void sendNewState(newValue) {
|
||||
eventBus.fire(new ServiceCallEvent(_domain, "turn_on", _entityId, null));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
return FlatButton(
|
||||
onPressed: (() {
|
||||
sendNewState(null);
|
||||
}),
|
||||
child: Text(
|
||||
"EXECUTE",
|
||||
textAlign: TextAlign.right,
|
||||
style:
|
||||
new TextStyle(fontSize: Entity.STATE_FONT_SIZE, color: Colors.blue),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// SLIDER
|
||||
//
|
||||
class SliderEntity extends Entity {
|
||||
int _multiplier = 1;
|
||||
|
||||
double get minValue => _attributes["min"] ?? 0.0;
|
||||
double get maxValue => _attributes["max"] ?? 100.0;
|
||||
double get valueStep => _attributes["step"] ?? 1.0;
|
||||
double get doubleState => double.tryParse(_state) ?? 0.0;
|
||||
|
||||
SliderEntity(Map rawData) : super(rawData) {
|
||||
if (valueStep < 1) {
|
||||
_multiplier = 10;
|
||||
} else if (valueStep < 0.1) {
|
||||
_multiplier = 100;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void sendNewState(newValue) {
|
||||
eventBus.fire(new ServiceCallEvent(_domain, "set_value", _entityId,
|
||||
{"value": "${newValue.toString()}"}));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
return Container(
|
||||
width: 200.0,
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Slider(
|
||||
min: this.minValue * _multiplier,
|
||||
max: this.maxValue * _multiplier,
|
||||
value: (this.doubleState <= this.maxValue) &&
|
||||
(this.doubleState >= this.minValue)
|
||||
? this.doubleState * _multiplier
|
||||
: this.minValue * _multiplier,
|
||||
onChanged: (value) {
|
||||
eventBus.fire(new StateChangedEvent(_entityId,
|
||||
(value.roundToDouble() / _multiplier).toString(), true));
|
||||
},
|
||||
onChangeEnd: (value) {
|
||||
sendNewState(value.roundToDouble() / _multiplier);
|
||||
},
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: EdgeInsets.only(right: Entity.RIGHT_WIDGET_PADDING),
|
||||
child: Text("$_state${this.unitOfMeasurement}",
|
||||
textAlign: TextAlign.right,
|
||||
style: new TextStyle(
|
||||
fontSize: Entity.STATE_FONT_SIZE,
|
||||
)),
|
||||
)
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// DATETIME
|
||||
//
|
||||
|
||||
class DateTimeEntity extends Entity {
|
||||
bool get hasDate => _attributes["has_date"] ?? false;
|
||||
bool get hasTime => _attributes["has_time"] ?? false;
|
||||
int get year => _attributes["year"] ?? 1970;
|
||||
int get month => _attributes["month"] ?? 1;
|
||||
int get day => _attributes["day"] ?? 1;
|
||||
int get hour => _attributes["hour"] ?? 0;
|
||||
int get minute => _attributes["minute"] ?? 0;
|
||||
int get second => _attributes["second"] ?? 0;
|
||||
String get formattedState => _getFormattedState();
|
||||
DateTime get dateTimeState => _getDateTimeState();
|
||||
|
||||
DateTimeEntity(Map rawData) : super(rawData);
|
||||
|
||||
DateTime _getDateTimeState() {
|
||||
return DateTime(this.year, this.month, this.day, this.hour, this.minute, this.second);
|
||||
}
|
||||
|
||||
String _getFormattedState() {
|
||||
String formattedState = "";
|
||||
if (this.hasDate) {
|
||||
formattedState += formatDate(dateTimeState, [M, ' ', d, ', ', yyyy]);
|
||||
}
|
||||
if (this.hasTime) {
|
||||
formattedState += " "+formatDate(dateTimeState, [HH, ':', nn]);
|
||||
}
|
||||
return formattedState;
|
||||
}
|
||||
|
||||
@override
|
||||
void sendNewState(newValue) {
|
||||
eventBus.fire(new ServiceCallEvent(_domain, "set_datetime", _entityId,
|
||||
newValue));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
return Padding(
|
||||
padding:
|
||||
EdgeInsets.fromLTRB(0.0, 0.0, Entity.RIGHT_WIDGET_PADDING, 0.0),
|
||||
child: GestureDetector(
|
||||
child: Text(
|
||||
"$formattedState",
|
||||
textAlign: TextAlign.right,
|
||||
style: new TextStyle(
|
||||
fontSize: Entity.STATE_FONT_SIZE,
|
||||
)),
|
||||
onTap: () => _handleStateTap(context),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
void _handleStateTap(BuildContext context) {
|
||||
if (hasDate) {
|
||||
_showDatePicker(context).then((date) {
|
||||
if (date != null) {
|
||||
if (hasTime) {
|
||||
_showTimePicker(context).then((time){
|
||||
sendNewState({"date": "${formatDate(date, [yyyy, '-', mm, '-', dd])}", "time": "${formatDate(DateTime(1970, 1, 1, time.hour, time.minute), [HH, ':', nn])}"});
|
||||
});
|
||||
} else {
|
||||
sendNewState({"date": "${formatDate(date, [yyyy, '-', mm, '-', dd])}"});
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (hasTime) {
|
||||
_showTimePicker(context).then((time){
|
||||
if (time != null) {
|
||||
sendNewState({"time": "${formatDate(DateTime(1970, 1, 1, time.hour, time.minute), [HH, ':', nn])}"});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
TheLogger.log("Warning", "$entityId has no date and no time");
|
||||
}
|
||||
}
|
||||
|
||||
Future _showDatePicker(BuildContext context) {
|
||||
return showDatePicker(
|
||||
context: context,
|
||||
initialDate: dateTimeState,
|
||||
firstDate: DateTime(1970),
|
||||
lastDate: DateTime(2037) //Unix timestamp will finish at Jan 19, 2038
|
||||
);
|
||||
}
|
||||
|
||||
Future _showTimePicker(BuildContext context) {
|
||||
return showTimePicker(
|
||||
context: context,
|
||||
initialTime: TimeOfDay.fromDateTime(dateTimeState)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class SelectEntity extends Entity {
|
||||
List<String> _listOptions = [];
|
||||
String get initialValue => _attributes["initial"] ?? null;
|
||||
|
||||
SelectEntity(Map rawData) : super(rawData) {
|
||||
if (_attributes["options"] != null) {
|
||||
_attributes["options"].forEach((value){
|
||||
_listOptions.add(value.toString());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void sendNewState(newValue) {
|
||||
eventBus.fire(new ServiceCallEvent(_domain, "select_option", _entityId,
|
||||
{"option": "$newValue"}));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
return Container(
|
||||
width: Entity.INPUT_WIDTH,
|
||||
child: DropdownButton<String>(
|
||||
value: _state,
|
||||
items: this._listOptions.map((String value) {
|
||||
return new DropdownMenuItem<String>(
|
||||
value: value,
|
||||
child: new Text(value),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (_) {
|
||||
sendNewState(_);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class TextEntity extends Entity {
|
||||
String tmpState;
|
||||
FocusNode _focusNode;
|
||||
bool validValue = false;
|
||||
|
||||
int get valueMinLength => _attributes["min"] ?? -1;
|
||||
int get valueMaxLength => _attributes["max"] ?? -1;
|
||||
String get valuePattern => _attributes["pattern"] ?? null;
|
||||
bool get isTextField => _attributes["mode"] == "text";
|
||||
bool get isPasswordField => _attributes["mode"] == "password";
|
||||
|
||||
TextEntity(Map rawData) : super(rawData) {
|
||||
_focusNode = FocusNode();
|
||||
//TODO possible memory leak generator
|
||||
_focusNode.addListener(_focusListener);
|
||||
//tmpState = state;
|
||||
}
|
||||
|
||||
@override
|
||||
void sendNewState(newValue) {
|
||||
if (validate(newValue)) {
|
||||
eventBus.fire(new ServiceCallEvent(_domain, "set_value", _entityId,
|
||||
{"value": "{newValue"}));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void update(Map rawData) {
|
||||
super.update(rawData);
|
||||
tmpState = _state;
|
||||
}
|
||||
|
||||
bool validate(newValue) {
|
||||
if (newValue is String) {
|
||||
//TODO add pattern support
|
||||
validValue = (newValue.length >= this.valueMinLength) &&
|
||||
(this.valueMaxLength == -1 ||
|
||||
(newValue.length <= this.valueMaxLength));
|
||||
} else {
|
||||
validValue = true;
|
||||
}
|
||||
return validValue;
|
||||
}
|
||||
|
||||
void _focusListener() {
|
||||
if (!_focusNode.hasFocus && (tmpState != state)) {
|
||||
sendNewState(tmpState);
|
||||
tmpState = state;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
if (this.isTextField || this.isPasswordField) {
|
||||
return Container(
|
||||
width: Entity.INPUT_WIDTH,
|
||||
child: TextField(
|
||||
focusNode: inCard ? _focusNode : null,
|
||||
obscureText: this.isPasswordField,
|
||||
controller: new TextEditingController.fromValue(
|
||||
new TextEditingValue(
|
||||
text: tmpState,
|
||||
selection:
|
||||
new TextSelection.collapsed(offset: tmpState.length))),
|
||||
onChanged: (value) {
|
||||
tmpState = value;
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
TheLogger.log("Warning", "Unsupported input mode for $entityId");
|
||||
return super._buildActionWidget(inCard, context);
|
||||
}
|
||||
}
|
||||
}
|
@ -3,7 +3,7 @@ part of 'main.dart';
|
||||
class EntityViewPage extends StatefulWidget {
|
||||
EntityViewPage({Key key, this.entity}) : super(key: key);
|
||||
|
||||
Entity entity;
|
||||
final Entity entity;
|
||||
|
||||
@override
|
||||
_EntityViewPageState createState() => new _EntityViewPageState();
|
||||
@ -44,22 +44,13 @@ class _EntityViewPageState extends State<EntityViewPage> {
|
||||
),
|
||||
body: Padding(
|
||||
padding: EdgeInsets.all(10.0),
|
||||
child: ListView(
|
||||
children: <Widget>[
|
||||
_entity.buildWidget(false, context),
|
||||
_entity.buildAdditionalWidget()
|
||||
],
|
||||
),
|
||||
child: _entity.buildWidget(context, false)
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose(){
|
||||
if (_entity is TextEntity && (_entity as TextEntity).tmpState != _entity.state) {
|
||||
eventBus.fire(new ServiceCallEvent(_entity.domain, "set_value", _entity.entityId, {"value": "${(_entity as TextEntity).tmpState}"}));
|
||||
TheLogger.log("Debug", "Saving changed input value for ${_entity.entityId}");
|
||||
}
|
||||
if (_stateSubscription != null) _stateSubscription.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
24
lib/entity_class/button_entity.class.dart
Normal file
24
lib/entity_class/button_entity.class.dart
Normal file
@ -0,0 +1,24 @@
|
||||
part of '../main.dart';
|
||||
|
||||
class _ButtonEntityWidgetState extends _EntityWidgetState {
|
||||
|
||||
@override
|
||||
void setNewState(newValue) {
|
||||
eventBus.fire(new ServiceCallEvent(widget.entity.domain, "turn_on", widget.entity.entityId, null));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
return FlatButton(
|
||||
onPressed: (() {
|
||||
setNewState(null);
|
||||
}),
|
||||
child: Text(
|
||||
"EXECUTE",
|
||||
textAlign: TextAlign.right,
|
||||
style:
|
||||
new TextStyle(fontSize: Entity.STATE_FONT_SIZE, color: Colors.blue),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
92
lib/entity_class/datetime_entity.class.dart
Normal file
92
lib/entity_class/datetime_entity.class.dart
Normal file
@ -0,0 +1,92 @@
|
||||
part of '../main.dart';
|
||||
|
||||
class _DateTimeEntityWidgetState extends _EntityWidgetState {
|
||||
bool get hasDate => widget.entity._attributes["has_date"] ?? false;
|
||||
bool get hasTime => widget.entity._attributes["has_time"] ?? false;
|
||||
int get year => widget.entity._attributes["year"] ?? 1970;
|
||||
int get month => widget.entity._attributes["month"] ?? 1;
|
||||
int get day => widget.entity._attributes["day"] ?? 1;
|
||||
int get hour => widget.entity._attributes["hour"] ?? 0;
|
||||
int get minute => widget.entity._attributes["minute"] ?? 0;
|
||||
int get second => widget.entity._attributes["second"] ?? 0;
|
||||
String get formattedState => _getFormattedState();
|
||||
DateTime get dateTimeState => _getDateTimeState();
|
||||
|
||||
DateTime _getDateTimeState() {
|
||||
return DateTime(this.year, this.month, this.day, this.hour, this.minute, this.second);
|
||||
}
|
||||
|
||||
String _getFormattedState() {
|
||||
String formattedState = "";
|
||||
if (this.hasDate) {
|
||||
formattedState += formatDate(dateTimeState, [M, ' ', d, ', ', yyyy]);
|
||||
}
|
||||
if (this.hasTime) {
|
||||
formattedState += " "+formatDate(dateTimeState, [HH, ':', nn]);
|
||||
}
|
||||
return formattedState;
|
||||
}
|
||||
|
||||
@override
|
||||
void setNewState(newValue) {
|
||||
eventBus.fire(new ServiceCallEvent(widget.entity.domain, "set_datetime", widget.entity.entityId,
|
||||
newValue));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
return Padding(
|
||||
padding:
|
||||
EdgeInsets.fromLTRB(0.0, 0.0, Entity.RIGHT_WIDGET_PADDING, 0.0),
|
||||
child: GestureDetector(
|
||||
child: Text(
|
||||
"$formattedState",
|
||||
textAlign: TextAlign.right,
|
||||
style: new TextStyle(
|
||||
fontSize: Entity.STATE_FONT_SIZE,
|
||||
)),
|
||||
onTap: () => _handleStateTap(context),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
void _handleStateTap(BuildContext context) {
|
||||
if (hasDate) {
|
||||
_showDatePicker(context).then((date) {
|
||||
if (date != null) {
|
||||
if (hasTime) {
|
||||
_showTimePicker(context).then((time){
|
||||
setNewState({"date": "${formatDate(date, [yyyy, '-', mm, '-', dd])}", "time": "${formatDate(DateTime(1970, 1, 1, time.hour, time.minute), [HH, ':', nn])}"});
|
||||
});
|
||||
} else {
|
||||
setNewState({"date": "${formatDate(date, [yyyy, '-', mm, '-', dd])}"});
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (hasTime) {
|
||||
_showTimePicker(context).then((time){
|
||||
if (time != null) {
|
||||
setNewState({"time": "${formatDate(DateTime(1970, 1, 1, time.hour, time.minute), [HH, ':', nn])}"});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
TheLogger.log("Warning", "${widget.entity.entityId} has no date and no time");
|
||||
}
|
||||
}
|
||||
|
||||
Future _showDatePicker(BuildContext context) {
|
||||
return showDatePicker(
|
||||
context: context,
|
||||
initialDate: dateTimeState,
|
||||
firstDate: DateTime(1970),
|
||||
lastDate: DateTime(2037) //Unix timestamp will finish at Jan 19, 2038
|
||||
);
|
||||
}
|
||||
|
||||
Future _showTimePicker(BuildContext context) {
|
||||
return showTimePicker(
|
||||
context: context,
|
||||
initialTime: TimeOfDay.fromDateTime(dateTimeState)
|
||||
);
|
||||
}
|
||||
}
|
242
lib/entity_class/entity.class.dart
Normal file
242
lib/entity_class/entity.class.dart
Normal file
@ -0,0 +1,242 @@
|
||||
part of '../main.dart';
|
||||
|
||||
class Entity {
|
||||
static const STATE_ICONS_COLORS = {
|
||||
"on": Colors.amber,
|
||||
"off": Color.fromRGBO(68, 115, 158, 1.0),
|
||||
"unavailable": Colors.black12,
|
||||
"unknown": Colors.black12,
|
||||
"playing": Colors.amber
|
||||
};
|
||||
static const RIGHT_WIDGET_PADDING = 14.0;
|
||||
static const LEFT_WIDGET_PADDING = 8.0;
|
||||
static const EXTENDED_WIDGET_HEIGHT = 50.0;
|
||||
static const WIDGET_HEIGHT = 34.0;
|
||||
static const ICON_SIZE = 28.0;
|
||||
static const STATE_FONT_SIZE = 16.0;
|
||||
static const NAME_FONT_SIZE = 16.0;
|
||||
static const SMALL_FONT_SIZE = 14.0;
|
||||
static const INPUT_WIDTH = 160.0;
|
||||
|
||||
Map _attributes;
|
||||
String _domain;
|
||||
String _entityId;
|
||||
String _state;
|
||||
String assumedState;
|
||||
DateTime _lastUpdated;
|
||||
|
||||
String get displayName =>
|
||||
_attributes["friendly_name"] ?? (_attributes["name"] ?? "_");
|
||||
String get domain => _domain;
|
||||
String get entityId => _entityId;
|
||||
String get state => _state;
|
||||
set state(value) => _state = value;
|
||||
|
||||
String get deviceClass => _attributes["device_class"] ?? null;
|
||||
bool get isView =>
|
||||
(_domain == "group") &&
|
||||
(_attributes != null ? _attributes["view"] ?? false : false);
|
||||
bool get isGroup => _domain == "group";
|
||||
String get icon => _attributes["icon"] ?? "";
|
||||
bool get isOn => state == "on";
|
||||
String get entityPicture => _attributes["entity_picture"];
|
||||
String get unitOfMeasurement => _attributes["unit_of_measurement"] ?? "";
|
||||
List get childEntities => _attributes["entity_id"] ?? [];
|
||||
String get lastUpdated => _getLastUpdatedFormatted();
|
||||
|
||||
Entity(Map rawData) {
|
||||
update(rawData);
|
||||
}
|
||||
|
||||
void update(Map rawData) {
|
||||
_attributes = rawData["attributes"] ?? {};
|
||||
_domain = rawData["entity_id"].split(".")[0];
|
||||
_entityId = rawData["entity_id"];
|
||||
_state = rawData["state"];
|
||||
assumedState = _state;
|
||||
_lastUpdated = DateTime.tryParse(rawData["last_updated"]);
|
||||
}
|
||||
|
||||
EntityWidget buildWidget(BuildContext context, bool inCard) {
|
||||
return EntityWidget(
|
||||
entity: this,
|
||||
inCard: inCard,
|
||||
);
|
||||
}
|
||||
|
||||
String _getLastUpdatedFormatted() {
|
||||
if (_lastUpdated == null) {
|
||||
return "-";
|
||||
} else {
|
||||
DateTime now = DateTime.now();
|
||||
Duration d = now.difference(_lastUpdated);
|
||||
String text;
|
||||
int v;
|
||||
if (d.inDays == 0) {
|
||||
if (d.inHours == 0) {
|
||||
if (d.inMinutes == 0) {
|
||||
text = "seconds ago";
|
||||
v = d.inSeconds;
|
||||
} else {
|
||||
text = "minutes ago";
|
||||
v = d.inMinutes;
|
||||
}
|
||||
} else {
|
||||
text = "hours ago";
|
||||
v = d.inHours;
|
||||
}
|
||||
} else {
|
||||
text = "days ago";
|
||||
v = d.inDays;
|
||||
}
|
||||
return "$v $text";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
class EntityWidget extends StatefulWidget {
|
||||
EntityWidget({Key key, this.entity, this.inCard}) : super(key: key);
|
||||
|
||||
final Entity entity;
|
||||
final bool inCard;
|
||||
|
||||
@override
|
||||
_EntityWidgetState createState() {
|
||||
switch (entity.domain) {
|
||||
case "automation":
|
||||
case "input_boolean ":
|
||||
case "switch":
|
||||
case "light": {
|
||||
return _SwitchEntityWidgetState();
|
||||
}
|
||||
|
||||
case "script":
|
||||
case "scene": {
|
||||
return _ButtonEntityWidgetState();
|
||||
}
|
||||
|
||||
case "input_datetime": {
|
||||
return _DateTimeEntityWidgetState();
|
||||
}
|
||||
|
||||
case "input_select": {
|
||||
return _SelectEntityWidgetState();
|
||||
}
|
||||
|
||||
case "input_number": {
|
||||
return _SliderEntityWidgetState();
|
||||
}
|
||||
|
||||
case "input_text": {
|
||||
return _TextEntityWidgetState();
|
||||
}
|
||||
|
||||
default: {
|
||||
return _EntityWidgetState();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _EntityWidgetState extends State<EntityWidget> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (widget.inCard) {
|
||||
return _buildMainWidget(context);
|
||||
} else {
|
||||
return ListView(
|
||||
children: <Widget>[
|
||||
_buildMainWidget(context),
|
||||
_buildLastUpdatedWidget()
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildMainWidget(BuildContext context) {
|
||||
return SizedBox(
|
||||
height: Entity.WIDGET_HEIGHT,
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
GestureDetector(
|
||||
child: _buildIconWidget(),
|
||||
onTap: widget.inCard ? openEntityPage : null,
|
||||
),
|
||||
Expanded(
|
||||
child: GestureDetector(
|
||||
child: _buildNameWidget(),
|
||||
onTap: widget.inCard ? openEntityPage : null,
|
||||
),
|
||||
),
|
||||
_buildActionWidget(widget.inCard, context)
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void openEntityPage() {
|
||||
eventBus.fire(new ShowEntityPageEvent(widget.entity));
|
||||
}
|
||||
|
||||
void setNewState(newState) {
|
||||
return;
|
||||
}
|
||||
|
||||
Widget buildAdditionalWidget() {
|
||||
return _buildLastUpdatedWidget();
|
||||
}
|
||||
|
||||
Widget _buildIconWidget() {
|
||||
return Padding(
|
||||
padding: EdgeInsets.fromLTRB(Entity.LEFT_WIDGET_PADDING, 0.0, 12.0, 0.0),
|
||||
child: MaterialDesignIcons.createIconWidgetFromEntityData(
|
||||
widget.entity,
|
||||
Entity.ICON_SIZE,
|
||||
Entity.STATE_ICONS_COLORS[widget.entity.state] ?? Colors.blueGrey),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLastUpdatedWidget() {
|
||||
return Padding(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
Entity.LEFT_WIDGET_PADDING, Entity.SMALL_FONT_SIZE, 0.0, 0.0),
|
||||
child: Text(
|
||||
'${widget.entity.lastUpdated}',
|
||||
textAlign: TextAlign.left,
|
||||
style:
|
||||
TextStyle(fontSize: Entity.SMALL_FONT_SIZE, color: Colors.black26),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildNameWidget() {
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(right: 10.0),
|
||||
child: Text(
|
||||
"${widget.entity.displayName}",
|
||||
overflow: TextOverflow.ellipsis,
|
||||
softWrap: false,
|
||||
style: TextStyle(fontSize: Entity.NAME_FONT_SIZE),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
return Padding(
|
||||
padding:
|
||||
EdgeInsets.fromLTRB(0.0, 0.0, Entity.RIGHT_WIDGET_PADDING, 0.0),
|
||||
child: GestureDetector(
|
||||
child: Text(
|
||||
"${widget.entity.state}${widget.entity.unitOfMeasurement}",
|
||||
textAlign: TextAlign.right,
|
||||
style: new TextStyle(
|
||||
fontSize: Entity.STATE_FONT_SIZE,
|
||||
)),
|
||||
onTap: openEntityPage,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
36
lib/entity_class/select_entity.class.dart
Normal file
36
lib/entity_class/select_entity.class.dart
Normal file
@ -0,0 +1,36 @@
|
||||
part of '../main.dart';
|
||||
|
||||
class _SelectEntityWidgetState extends _EntityWidgetState {
|
||||
List<String> _listOptions = [];
|
||||
|
||||
@override
|
||||
void setNewState(newValue) {
|
||||
eventBus.fire(new ServiceCallEvent(widget.entity.domain, "select_option", widget.entity.entityId,
|
||||
{"option": "$newValue"}));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
_listOptions.clear();
|
||||
if (widget.entity._attributes["options"] != null) {
|
||||
widget.entity._attributes["options"].forEach((value){
|
||||
_listOptions.add(value.toString());
|
||||
});
|
||||
}
|
||||
return Expanded(
|
||||
//width: Entity.INPUT_WIDTH,
|
||||
child: DropdownButton<String>(
|
||||
value: widget.entity.state,
|
||||
items: this._listOptions.map((String value) {
|
||||
return new DropdownMenuItem<String>(
|
||||
value: value,
|
||||
child: new Text(value),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (_) {
|
||||
setNewState(_);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
65
lib/entity_class/slider_entity.class.dart
Normal file
65
lib/entity_class/slider_entity.class.dart
Normal file
@ -0,0 +1,65 @@
|
||||
part of '../main.dart';
|
||||
|
||||
class _SliderEntityWidgetState extends _EntityWidgetState {
|
||||
int _multiplier = 1;
|
||||
|
||||
double get minValue => widget.entity._attributes["min"] ?? 0.0;
|
||||
double get maxValue => widget.entity._attributes["max"] ?? 100.0;
|
||||
double get valueStep => widget.entity._attributes["step"] ?? 1.0;
|
||||
double get doubleState => double.tryParse(widget.entity.state) ?? 0.0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@override
|
||||
void setNewState(newValue) {
|
||||
eventBus.fire(new ServiceCallEvent(widget.entity.domain, "set_value", widget.entity.entityId,
|
||||
{"value": "${newValue.toString()}"}));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
if (valueStep < 1) {
|
||||
_multiplier = 10;
|
||||
} else if (valueStep < 0.1) {
|
||||
_multiplier = 100;
|
||||
}
|
||||
return Expanded(
|
||||
//width: 200.0,
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Slider(
|
||||
min: this.minValue * _multiplier,
|
||||
max: this.maxValue * _multiplier,
|
||||
value: (doubleState <= this.maxValue) &&
|
||||
(doubleState >= this.minValue)
|
||||
? doubleState * _multiplier
|
||||
: this.minValue * _multiplier,
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
widget.entity.state = (value.roundToDouble() / _multiplier).toString();
|
||||
});
|
||||
/*eventBus.fire(new StateChangedEvent(widget.entity.entityId,
|
||||
(value.roundToDouble() / _multiplier).toString(), true));*/
|
||||
},
|
||||
onChangeEnd: (value) {
|
||||
setNewState(value.roundToDouble() / _multiplier);
|
||||
},
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: EdgeInsets.only(right: Entity.RIGHT_WIDGET_PADDING),
|
||||
child: Text("${widget.entity.state}${widget.entity.unitOfMeasurement}",
|
||||
textAlign: TextAlign.right,
|
||||
style: new TextStyle(
|
||||
fontSize: Entity.STATE_FONT_SIZE,
|
||||
)),
|
||||
)
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
33
lib/entity_class/switch_entity.class.dart
Normal file
33
lib/entity_class/switch_entity.class.dart
Normal file
@ -0,0 +1,33 @@
|
||||
part of '../main.dart';
|
||||
|
||||
class _SwitchEntityWidgetState extends _EntityWidgetState {
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@override
|
||||
void setNewState(newValue) {
|
||||
setState(() {
|
||||
widget.entity.assumedState = newValue ? 'on' : 'off';
|
||||
});
|
||||
Timer(Duration(seconds: 2), (){
|
||||
setState(() {
|
||||
widget.entity.assumedState = widget.entity.state;
|
||||
});
|
||||
});
|
||||
eventBus.fire(new ServiceCallEvent(
|
||||
widget.entity.domain, (newValue as bool) ? "turn_on" : "turn_off", widget.entity.entityId, null));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
return Switch(
|
||||
value: widget.entity.assumedState == 'on',
|
||||
onChanged: ((switchState) {
|
||||
setNewState(switchState);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
83
lib/entity_class/text_entity.class.dart
Normal file
83
lib/entity_class/text_entity.class.dart
Normal file
@ -0,0 +1,83 @@
|
||||
part of '../main.dart';
|
||||
|
||||
class _TextEntityWidgetState extends _EntityWidgetState {
|
||||
String _tmpValue;
|
||||
FocusNode _focusNode = FocusNode();
|
||||
bool validValue = false;
|
||||
|
||||
int get valueMinLength => widget.entity._attributes["min"] ?? -1;
|
||||
int get valueMaxLength => widget.entity._attributes["max"] ?? -1;
|
||||
String get valuePattern => widget.entity._attributes["pattern"] ?? null;
|
||||
bool get isTextField => widget.entity._attributes["mode"] == "text";
|
||||
bool get isPasswordField => widget.entity._attributes["mode"] == "password";
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_focusNode.addListener(_focusListener);
|
||||
_tmpValue = widget.entity.state;
|
||||
}
|
||||
|
||||
@override
|
||||
void setNewState(newValue) {
|
||||
if (validate(newValue)) {
|
||||
eventBus.fire(new ServiceCallEvent(widget.entity.domain, "set_value", widget.entity.entityId,
|
||||
{"value": "$newValue"}));
|
||||
} else {
|
||||
setState(() {
|
||||
_tmpValue = widget.entity.state;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
bool validate(newValue) {
|
||||
if (newValue is String) {
|
||||
validValue = (newValue.length >= this.valueMinLength) &&
|
||||
(this.valueMaxLength == -1 ||
|
||||
(newValue.length <= this.valueMaxLength));
|
||||
} else {
|
||||
validValue = true;
|
||||
}
|
||||
return validValue;
|
||||
}
|
||||
|
||||
void _focusListener() {
|
||||
if (!_focusNode.hasFocus && (_tmpValue != widget.entity.state)) {
|
||||
setNewState(_tmpValue);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget _buildActionWidget(bool inCard, BuildContext context) {
|
||||
if (!_focusNode.hasFocus && (_tmpValue != widget.entity.state)) {
|
||||
_tmpValue = widget.entity.state;
|
||||
}
|
||||
if (this.isTextField || this.isPasswordField) {
|
||||
return Expanded(
|
||||
//width: Entity.INPUT_WIDTH,
|
||||
child: TextField(
|
||||
focusNode: _focusNode,
|
||||
obscureText: this.isPasswordField,
|
||||
controller: new TextEditingController.fromValue(
|
||||
new TextEditingValue(
|
||||
text: _tmpValue,
|
||||
selection:
|
||||
new TextSelection.collapsed(offset: _tmpValue.length))),
|
||||
onChanged: (value) {
|
||||
_tmpValue = value;
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
TheLogger.log("Warning", "Unsupported input mode for ${widget.entity.entityId}");
|
||||
return super._buildActionWidget(inCard, context);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_focusNode.removeListener(_focusListener);
|
||||
_focusNode.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
}
|
@ -27,39 +27,7 @@ class EntityCollection {
|
||||
}
|
||||
|
||||
Entity _createEntityInstance(rawEntityData) {
|
||||
switch (rawEntityData["entity_id"].split(".")[0]) {
|
||||
case "automation":
|
||||
case "input_boolean ":
|
||||
case "switch":
|
||||
case "light": {
|
||||
return SwitchEntity(rawEntityData);
|
||||
}
|
||||
|
||||
case "script":
|
||||
case "scene": {
|
||||
return ButtonEntity(rawEntityData);
|
||||
}
|
||||
|
||||
case "input_datetime": {
|
||||
return DateTimeEntity(rawEntityData);
|
||||
}
|
||||
|
||||
case "input_select": {
|
||||
return SelectEntity(rawEntityData);
|
||||
}
|
||||
|
||||
case "input_number": {
|
||||
return SliderEntity(rawEntityData);
|
||||
}
|
||||
|
||||
case "input_text": {
|
||||
return TextEntity(rawEntityData);
|
||||
}
|
||||
|
||||
default: {
|
||||
return Entity(rawEntityData);
|
||||
}
|
||||
}
|
||||
return Entity(rawEntityData);
|
||||
}
|
||||
|
||||
void updateState(Map rawStateData) {
|
||||
|
@ -6,6 +6,7 @@ class HomeAssistant {
|
||||
String _hassioAuthType;
|
||||
|
||||
IOWebSocketChannel _hassioChannel;
|
||||
SendMessageQueue _messageQueue;
|
||||
|
||||
int _currentMessageId = 0;
|
||||
int _statesMessageId = 0;
|
||||
@ -20,7 +21,13 @@ class HomeAssistant {
|
||||
Completer _statesCompleter;
|
||||
Completer _servicesCompleter;
|
||||
Completer _configCompleter;
|
||||
Timer _fetchingTimer;
|
||||
Completer _connectionCompleter;
|
||||
Timer _connectionTimer;
|
||||
Timer _fetchTimer;
|
||||
|
||||
int messageExpirationTime = 50; //seconds
|
||||
Duration fetchTimeout = Duration(seconds: 30);
|
||||
Duration connectTimeout = Duration(seconds: 10);
|
||||
|
||||
String get locationName => _instanceConfig["location_name"] ?? "";
|
||||
int get viewsCount => _entities.viewList.length ?? 0;
|
||||
@ -34,19 +41,19 @@ class HomeAssistant {
|
||||
_hassioAuthType = authType;
|
||||
_entities = EntityCollection();
|
||||
_uiBuilder = UIBuilder();
|
||||
_messageQueue = SendMessageQueue(messageExpirationTime);
|
||||
}
|
||||
|
||||
Future fetch() {
|
||||
if ((_fetchCompleter != null) && (!_fetchCompleter.isCompleted)) {
|
||||
TheLogger.log("Warning","Previous fetch is not complited");
|
||||
} else {
|
||||
//TODO: Fetch timeout timer. Should be removed after #21 fix
|
||||
_fetchingTimer = Timer(Duration(seconds: 15), () {
|
||||
closeConnection();
|
||||
_fetchCompleter.completeError({"errorCode" : 1,"errorMessage": "Connection timeout"});
|
||||
});
|
||||
_fetchCompleter = new Completer();
|
||||
_reConnectSocket().then((r) {
|
||||
_fetchTimer = Timer(fetchTimeout, () {
|
||||
closeConnection();
|
||||
_finishFetching({"errorCode" : 9,"errorMessage": "Couldn't get data from server"});
|
||||
});
|
||||
_connection().then((r) {
|
||||
_getData();
|
||||
}).catchError((e) {
|
||||
_finishFetching(e);
|
||||
@ -62,18 +69,32 @@ class HomeAssistant {
|
||||
_hassioChannel = null;
|
||||
}
|
||||
|
||||
Future _reConnectSocket() {
|
||||
var _connectionCompleter = new Completer();
|
||||
if ((_hassioChannel == null) || (_hassioChannel.closeCode != null)) {
|
||||
TheLogger.log("Debug","Socket connecting...");
|
||||
_hassioChannel = IOWebSocketChannel.connect(_hassioAPIEndpoint);
|
||||
_hassioChannel.stream.handleError((e) {
|
||||
TheLogger.log("Error","Unhandled socket error: ${e.toString()}");
|
||||
});
|
||||
_hassioChannel.stream.listen((message) =>
|
||||
_handleMessage(_connectionCompleter, message));
|
||||
Future _connection() {
|
||||
if ((_connectionCompleter != null) && (!_connectionCompleter.isCompleted)) {
|
||||
TheLogger.log("Debug","Previous connection is not complited");
|
||||
} else {
|
||||
_connectionCompleter.complete();
|
||||
if ((_hassioChannel == null) || (_hassioChannel.sink == null) || (_hassioChannel.closeCode != null)) {
|
||||
TheLogger.log("Debug", "Socket connecting...");
|
||||
_connectionCompleter = new Completer();
|
||||
_connectionTimer = Timer(connectTimeout, () {
|
||||
closeConnection();
|
||||
_finishConnecting({"errorCode" : 1,"errorMessage": "Couldn't connect to Home Assistant. Looks like a network issues"});
|
||||
});
|
||||
_hassioChannel = IOWebSocketChannel.connect(
|
||||
_hassioAPIEndpoint, pingInterval: Duration(seconds: 30));
|
||||
_hassioChannel.stream.handleError((e) {
|
||||
TheLogger.log("Error", "Unhandled socket error: ${e.toString()}");
|
||||
});
|
||||
_hassioChannel.stream.listen((message) =>
|
||||
_handleMessage(_connectionCompleter, message));
|
||||
_hassioChannel.sink.done.whenComplete(() {
|
||||
TheLogger.log("Debug","Socket sink finished. Assuming it is closed.");
|
||||
closeConnection();
|
||||
});
|
||||
} else {
|
||||
//TheLogger.log("Debug","Socket looks connected...${_hassioChannel.protocol}, ${_hassioChannel.closeCode}, ${_hassioChannel.closeReason}");
|
||||
_finishConnecting(null);
|
||||
}
|
||||
}
|
||||
return _connectionCompleter.future;
|
||||
}
|
||||
@ -94,12 +115,26 @@ class HomeAssistant {
|
||||
});
|
||||
}
|
||||
|
||||
_finishFetching(error) {
|
||||
_fetchingTimer.cancel();
|
||||
void _finishFetching(error) {
|
||||
_fetchTimer.cancel();
|
||||
_finishConnecting(error);
|
||||
if (error != null) {
|
||||
_fetchCompleter.completeError(error);
|
||||
if (!_fetchCompleter.isCompleted)
|
||||
_fetchCompleter.completeError(error);
|
||||
} else {
|
||||
_fetchCompleter.complete();
|
||||
if (!_fetchCompleter.isCompleted)
|
||||
_fetchCompleter.complete();
|
||||
}
|
||||
}
|
||||
|
||||
void _finishConnecting(error) {
|
||||
_connectionTimer.cancel();
|
||||
if (error != null) {
|
||||
if (!_connectionCompleter.isCompleted)
|
||||
_connectionCompleter.completeError(error);
|
||||
} else {
|
||||
if (!_connectionCompleter.isCompleted)
|
||||
_connectionCompleter.complete();
|
||||
}
|
||||
}
|
||||
|
||||
@ -107,12 +142,12 @@ class HomeAssistant {
|
||||
var data = json.decode(message);
|
||||
//TheLogger.log("Debug","[Received] => Message type: ${data['type']}");
|
||||
if (data["type"] == "auth_required") {
|
||||
_sendMessageRaw('{"type": "auth","$_hassioAuthType": "$_hassioPassword"}');
|
||||
_sendAuthMessageRaw('{"type": "auth","$_hassioAuthType": "$_hassioPassword"}');
|
||||
} else if (data["type"] == "auth_ok") {
|
||||
_finishConnecting(null);
|
||||
_sendSubscribe();
|
||||
connectionCompleter.complete();
|
||||
} else if (data["type"] == "auth_invalid") {
|
||||
connectionCompleter.completeError({"errorCode": 6, "errorMessage": "${data["message"]}"});
|
||||
_finishFetching({"errorCode": 6, "errorMessage": "${data["message"]}"});
|
||||
} else if (data["type"] == "result") {
|
||||
if (data["id"] == _configMessageId) {
|
||||
_parseConfig(data);
|
||||
@ -139,14 +174,14 @@ class HomeAssistant {
|
||||
void _sendSubscribe() {
|
||||
_incrementMessageId();
|
||||
_subscriptionMessageId = _currentMessageId;
|
||||
_sendMessageRaw('{"id": $_subscriptionMessageId, "type": "subscribe_events", "event_type": "state_changed"}');
|
||||
_sendMessageRaw('{"id": $_subscriptionMessageId, "type": "subscribe_events", "event_type": "state_changed"}', false);
|
||||
}
|
||||
|
||||
Future _getConfig() {
|
||||
_configCompleter = new Completer();
|
||||
_incrementMessageId();
|
||||
_configMessageId = _currentMessageId;
|
||||
_sendMessageRaw('{"id": $_configMessageId, "type": "get_config"}');
|
||||
_sendMessageRaw('{"id": $_configMessageId, "type": "get_config"}', false);
|
||||
|
||||
return _configCompleter.future;
|
||||
}
|
||||
@ -155,7 +190,7 @@ class HomeAssistant {
|
||||
_statesCompleter = new Completer();
|
||||
_incrementMessageId();
|
||||
_statesMessageId = _currentMessageId;
|
||||
_sendMessageRaw('{"id": $_statesMessageId, "type": "get_states"}');
|
||||
_sendMessageRaw('{"id": $_statesMessageId, "type": "get_states"}', false);
|
||||
|
||||
return _statesCompleter.future;
|
||||
}
|
||||
@ -164,7 +199,7 @@ class HomeAssistant {
|
||||
_servicesCompleter = new Completer();
|
||||
_incrementMessageId();
|
||||
_servicesMessageId = _currentMessageId;
|
||||
_sendMessageRaw('{"id": $_servicesMessageId, "type": "get_services"}');
|
||||
_sendMessageRaw('{"id": $_servicesMessageId, "type": "get_services"}', false);
|
||||
|
||||
return _servicesCompleter.future;
|
||||
}
|
||||
@ -173,17 +208,44 @@ class HomeAssistant {
|
||||
_currentMessageId += 1;
|
||||
}
|
||||
|
||||
_sendMessageRaw(String message) {
|
||||
if (message.indexOf('"type": "auth"') > 0) {
|
||||
TheLogger.log("Debug", "[Sending] ==> auth request");
|
||||
} else {
|
||||
TheLogger.log("Debug", "[Sending] ==> $message");
|
||||
}
|
||||
void _sendAuthMessageRaw(String message) {
|
||||
TheLogger.log("Debug", "[Sending] ==> auth request");
|
||||
_hassioChannel.sink.add(message);
|
||||
}
|
||||
|
||||
_sendMessageRaw(String message, bool queued) {
|
||||
var sendCompleter = Completer();
|
||||
if (queued) _messageQueue.add(message);
|
||||
_connection().then((r) {
|
||||
_messageQueue.getActualMessages().forEach((message){
|
||||
TheLogger.log("Debug", "[Sending queued] ==> $message");
|
||||
_hassioChannel.sink.add(message);
|
||||
});
|
||||
if (!queued) {
|
||||
TheLogger.log("Debug", "[Sending] ==> $message");
|
||||
_hassioChannel.sink.add(message);
|
||||
}
|
||||
sendCompleter.complete();
|
||||
}).catchError((e){
|
||||
sendCompleter.completeError(e);
|
||||
});
|
||||
return sendCompleter.future;
|
||||
}
|
||||
|
||||
Future callService(String domain, String service, String entityId, Map<String, String> additionalParams) {
|
||||
_incrementMessageId();
|
||||
String message = '{"id": $_currentMessageId, "type": "call_service", "domain": "$domain", "service": "$service", "service_data": {"entity_id": "$entityId"';
|
||||
if (additionalParams != null) {
|
||||
additionalParams.forEach((name, value){
|
||||
message += ', "$name" : "$value"';
|
||||
});
|
||||
}
|
||||
message += '}}';
|
||||
return _sendMessageRaw(message, true);
|
||||
}
|
||||
|
||||
void _handleEntityStateChange(Map eventData) {
|
||||
TheLogger.log("Debug", "New state for ${eventData['entity_id']}");
|
||||
//TheLogger.log("Debug", "New state for ${eventData['entity_id']}");
|
||||
_entities.updateState(eventData);
|
||||
eventBus.fire(new StateChangedEvent(eventData["entity_id"], null, false));
|
||||
}
|
||||
@ -232,29 +294,44 @@ class HomeAssistant {
|
||||
_uiBuilder.build(_entities);
|
||||
_statesCompleter.complete();
|
||||
}
|
||||
}
|
||||
|
||||
Future callService(String domain, String service, String entityId, Map<String, String> additionalParams) {
|
||||
var sendCompleter = Completer();
|
||||
//TODO: Send service call timeout timer. Should be removed after #21 fix
|
||||
Timer _sendTimer = Timer(Duration(seconds: 7), () {
|
||||
sendCompleter.completeError({"errorCode" : 8,"errorMessage": "Connection timeout"});
|
||||
class SendMessageQueue {
|
||||
int _messageTimeout;
|
||||
List<HAMessage> _queue = [];
|
||||
|
||||
SendMessageQueue(this._messageTimeout);
|
||||
|
||||
void add(String message) {
|
||||
_queue.add(HAMessage(_messageTimeout, message));
|
||||
}
|
||||
|
||||
List<String> getActualMessages() {
|
||||
_queue.removeWhere((item) => item.isExpired());
|
||||
List<String> result = [];
|
||||
_queue.forEach((haMessage){
|
||||
result.add(haMessage.message);
|
||||
});
|
||||
_reConnectSocket().then((r) {
|
||||
_incrementMessageId();
|
||||
String message = '{"id": $_currentMessageId, "type": "call_service", "domain": "$domain", "service": "$service", "service_data": {"entity_id": "$entityId"';
|
||||
if (additionalParams != null) {
|
||||
additionalParams.forEach((name, value){
|
||||
message += ', "$name" : "$value"';
|
||||
});
|
||||
}
|
||||
message += '}}';
|
||||
_sendMessageRaw(message);
|
||||
_sendTimer.cancel();
|
||||
sendCompleter.complete();
|
||||
}).catchError((e){
|
||||
_sendTimer.cancel();
|
||||
sendCompleter.completeError(e);
|
||||
});
|
||||
return sendCompleter.future;
|
||||
this.clear();
|
||||
return result;
|
||||
}
|
||||
|
||||
void clear() {
|
||||
_queue.clear();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class HAMessage {
|
||||
DateTime _timeStamp;
|
||||
int _messageTimeout;
|
||||
String message;
|
||||
|
||||
HAMessage(this._messageTimeout, this.message) {
|
||||
_timeStamp = DateTime.now();
|
||||
}
|
||||
|
||||
bool isExpired() {
|
||||
return _timeStamp.difference(DateTime.now()).inSeconds > _messageTimeout;
|
||||
}
|
||||
}
|
@ -44,7 +44,7 @@ class _LogViewPageState extends State<LogViewPage> {
|
||||
onPressed: () {
|
||||
String body = "```\n$_logData```";
|
||||
String encodedBody = "${Uri.encodeFull(body)}";
|
||||
haUtils.launchURL("https://github.com/estevez-dev/ha_client_pub/issues/new?body=$encodedBody");
|
||||
HAUtils.launchURL("https://github.com/estevez-dev/ha_client_pub/issues/new?body=$encodedBody");
|
||||
},
|
||||
),
|
||||
],
|
||||
|
@ -12,13 +12,20 @@ import 'package:url_launcher/url_launcher.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:date_format/date_format.dart';
|
||||
|
||||
part 'entity_class/entity.class.dart';
|
||||
part 'entity_class/button_entity.class.dart';
|
||||
part 'entity_class/datetime_entity.class.dart';
|
||||
part 'entity_class/select_entity.class.dart';
|
||||
part 'entity_class/slider_entity.class.dart';
|
||||
part 'entity_class/switch_entity.class.dart';
|
||||
part 'entity_class/text_entity.class.dart';
|
||||
|
||||
part 'settings.page.dart';
|
||||
part 'home_assistant.class.dart';
|
||||
part 'log.page.dart';
|
||||
part 'entity.page.dart';
|
||||
part 'utils.class.dart';
|
||||
part 'mdi.class.dart';
|
||||
part 'entity.class.dart';
|
||||
part 'entity_collection.class.dart';
|
||||
part 'ui_builder_class.dart';
|
||||
part 'view_class.dart';
|
||||
@ -27,7 +34,7 @@ part 'badge_class.dart';
|
||||
|
||||
EventBus eventBus = new EventBus();
|
||||
const String appName = "HA Client";
|
||||
const appVersion = "0.2.1";
|
||||
const appVersion = "0.2.3";
|
||||
|
||||
String homeAssistantWebHost;
|
||||
|
||||
@ -60,7 +67,7 @@ class HAClientApp extends StatelessWidget {
|
||||
),
|
||||
initialRoute: "/",
|
||||
routes: {
|
||||
"/": (context) => MainPage(title: 'Hass Client'),
|
||||
"/": (context) => MainPage(title: 'HA Client'),
|
||||
"/connection-settings": (context) => ConnectionSettingsPage(title: "Connection Settings"),
|
||||
"/log-view": (context) => LogViewPage(title: "Log")
|
||||
},
|
||||
@ -190,14 +197,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver {
|
||||
}
|
||||
|
||||
void _callService(String domain, String service, String entityId, Map<String, String> additionalParams) {
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
});
|
||||
_homeAssistant.callService(domain, service, entityId, additionalParams).then((r) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}).catchError((e) => _setErrorState(e));
|
||||
_homeAssistant.callService(domain, service, entityId, additionalParams).catchError((e) => _setErrorState(e));
|
||||
}
|
||||
|
||||
void _showEntityPage(Entity entity) {
|
||||
@ -409,7 +409,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver {
|
||||
entities.add(
|
||||
Padding(
|
||||
padding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0),
|
||||
child: entity.buildWidget(true, context),
|
||||
child: entity.buildWidget(context, true),
|
||||
));
|
||||
}
|
||||
});
|
||||
@ -480,7 +480,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver {
|
||||
title: Text("Report an issue"),
|
||||
onTap: () {
|
||||
Navigator.of(context).pop();
|
||||
haUtils.launchURL("https://github.com/estevez-dev/ha_client_pub/issues/new");
|
||||
HAUtils.launchURL("https://github.com/estevez-dev/ha_client_pub/issues/new");
|
||||
},
|
||||
),
|
||||
new AboutListTile(
|
||||
@ -498,6 +498,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver {
|
||||
String message = _lastErrorMessage;
|
||||
SnackBarAction action;
|
||||
switch (_errorCodeToBeShown) {
|
||||
case 9:
|
||||
case 1: {
|
||||
action = SnackBarAction(
|
||||
label: "Retry",
|
||||
|
@ -32,7 +32,7 @@ class TheLogger {
|
||||
|
||||
}
|
||||
|
||||
class haUtils {
|
||||
class HAUtils {
|
||||
static void launchURL(String url) async {
|
||||
if (await canLaunch(url)) {
|
||||
await launch(url);
|
||||
|
@ -1,7 +1,7 @@
|
||||
name: hass_client
|
||||
description: Home Assistant Android Client
|
||||
|
||||
version: 0.2.1+23
|
||||
version: 0.2.3+25
|
||||
|
||||
environment:
|
||||
sdk: ">=2.0.0-dev.68.0 <3.0.0"
|
||||
|
Reference in New Issue
Block a user