Skip to content

Commit 36386d3

Browse files
committed
add device discovery
fix loading config credentials
1 parent ffc5bf5 commit 36386d3

File tree

4 files changed

+118
-8
lines changed

4 files changed

+118
-8
lines changed

octoprint_tplinksmartplug/__init__.py

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ def get_settings_defaults(self):
232232
'thermal_runaway_monitoring': False, 'thermal_runaway_max_bed': 0, 'thermal_runaway_max_extruder': 0,
233233
'cost_rate': 0, 'abortTimeout': 30, 'powerOffWhenIdle': False, 'idleTimeout': 30, 'idleIgnoreCommands': 'M105',
234234
'idleIgnoreHeaters': '', 'idleTimeoutWaitTemp': 50, 'progress_polling': False, 'useDropDown': False,
235-
'device_configs': {}, 'connect_on_connect_request': False}
235+
'device_configs': {}, 'connect_on_connect_request': False, 'username': '', 'password': ''}
236236

237237
def on_settings_save(self, data):
238238
old_debug_logging = self._settings.get_boolean(["debug_logging"])
@@ -600,7 +600,8 @@ def get_api_commands(self):
600600
enableAutomaticShutdown=[],
601601
disableAutomaticShutdown=[],
602602
abortAutomaticShutdown=[],
603-
getListPlug=[])
603+
getListPlug=[],
604+
discoverDevices=["username", "password"])
604605

605606
def on_api_get(self, request):
606607
if not Permissions.PLUGIN_TPLINKSMARTPLUG_CONTROL.can():
@@ -666,8 +667,19 @@ def on_api_command(self, command, data):
666667
self._reset_idle_timer()
667668
elif command == "getListPlug":
668669
return json.dumps(self._settings.get(["arrSmartplugs"]))
670+
elif command == "discoverDevices":
671+
username = None
672+
password = None
673+
if "username" in data and data["username"] != "":
674+
username = data["username"]
675+
if "password" in data and data["password"] != "":
676+
password = data["password"]
677+
found_devices_task = self.worker.run_coroutine_threadsafe(self.discover_devices(username, password))
678+
found_devices = found_devices_task.result()
679+
response = {'discovered_devices': found_devices}
669680
else:
670681
response = dict(ip="{ip}".format(**data), currentState="unknown")
682+
671683
if command == "enableAutomaticShutdown" or command == "disableAutomaticShutdown":
672684
self._tplinksmartplug_logger.debug(f"Automatic power off setting changed: {self.powerOffWhenIdle}")
673685
self._settings.set_boolean(["powerOffWhenIdle"], self.powerOffWhenIdle)
@@ -1033,11 +1045,26 @@ def get_device_config(self, plugip: str):
10331045
self._tplinksmartplug_logger.debug(f"Unable to get device_config for {plugip}: {e}")
10341046
return config_dict
10351047

1036-
async def connect_device(self, config_dict):
1048+
async def update_device(self, dev):
10371049
try:
1038-
if "credentials" in config_dict:
1039-
config_dict["credentials"] = Credentials(**config_dict["credentials"])
1050+
await dev.update()
1051+
self._tplinksmartplug_logger.debug(f"found device {dev.alias} (model: {dev.model})")
1052+
except Exception as e:
1053+
self._tplinksmartplug_logger.debug(f"Unable to get device_config for {dev.host}: {e}")
1054+
self._tplinksmartplug_logger.debug(f"Unable to get device_config for {dev.host}: {e}")
10401055

1056+
async def discover_devices(self, username=None, password=None):
1057+
devices_mac = {}
1058+
found_devices = await Discover.discover(on_discovered=self.update_device, username=username, password=password)
1059+
for dev in found_devices.values():
1060+
devices_mac[dev.mac] = {'alias': dev.alias, 'host': dev.host, 'mac': dev.mac, 'model': dev.model, 'state': 'on' if dev.is_on else 'off'}
1061+
return devices_mac
1062+
1063+
async def connect_device(self, config_dict):
1064+
try:
1065+
# if "credentials" in config_dict:
1066+
# config_dict["credentials"] = Credentials(**config_dict["credentials"])
1067+
self._tplinksmartplug_logger.debug(config_dict)
10411068
device = await Device.connect(config=Device.Config.from_dict(config_dict))
10421069
await device.update()
10431070
return device

octoprint_tplinksmartplug/static/js/tplinksmartplug.js

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ $(function() {
3939
self.graph_end_date = ko.observable(moment().format('YYYY-MM-DDTHH:mm'));
4040
self.processing_api_request = ko.observable(false);
4141

42+
self.discovering = ko.observable(false);
43+
self.discovered_devices = ko.observableDictionary();
44+
4245
self.filteredSmartplugs = ko.computed(function(){
4346
return ko.utils.arrayFilter(self.dictSmartplugs.items(), function(item) {
4447
return "err_code" in item.value().emeter.get_realtime;
@@ -258,7 +261,8 @@ $(function() {
258261
'gcodeCmdOff': ko.observable(false),
259262
'gcodeRunCmdOn': ko.observable(''),
260263
'gcodeRunCmdOff': ko.observable(''),
261-
'connect_on_connect': ko.observable(false)
264+
'connect_on_connect': ko.observable(false),
265+
'receives_led_commands': ko.observable(false)
262266
});
263267
self.settings.settings.plugins.tplinksmartplug.arrSmartplugs.push(self.selectedPlug());
264268
$("#TPLinkPlugEditor").modal("show");
@@ -268,6 +272,62 @@ $(function() {
268272
self.settings.settings.plugins.tplinksmartplug.arrSmartplugs.remove(row);
269273
}
270274

275+
self.add_discovered_device = function(ip, alias) {
276+
self.selectedPlug({'ip':ko.observable(ip),
277+
'label':ko.observable(alias),
278+
'icon':ko.observable('icon-bolt'),
279+
'displayWarning':ko.observable(true),
280+
'warnPrinting':ko.observable(false),
281+
'gcodeEnabled':ko.observable(false),
282+
'gcodeOnDelay':ko.observable(0),
283+
'gcodeOffDelay':ko.observable(0),
284+
'autoConnect':ko.observable(true),
285+
'autoConnectDelay':ko.observable(10.0),
286+
'autoDisconnect':ko.observable(true),
287+
'autoDisconnectDelay':ko.observable(0),
288+
'sysCmdOn':ko.observable(false),
289+
'sysRunCmdOn':ko.observable(''),
290+
'sysCmdOnDelay':ko.observable(0),
291+
'sysCmdOff':ko.observable(false),
292+
'sysRunCmdOff':ko.observable(''),
293+
'sysCmdOffDelay':ko.observable(0),
294+
'currentState':ko.observable('unknown'),
295+
'btnColor':ko.observable('#808080'),
296+
'emeter':{get_realtime:{}},
297+
'thermal_runaway':ko.observable(false),
298+
'event_on_error':ko.observable(false),
299+
'event_on_disconnect':ko.observable(false),
300+
'event_on_shutdown': ko.observable(false),
301+
'automaticShutdownEnabled':ko.observable(false),
302+
'event_on_upload':ko.observable(false),
303+
'event_on_startup':ko.observable(false),
304+
'gcodeCmdOn': ko.observable(false),
305+
'gcodeCmdOff': ko.observable(false),
306+
'gcodeRunCmdOn': ko.observable(''),
307+
'gcodeRunCmdOff': ko.observable(''),
308+
'connect_on_connect': ko.observable(false),
309+
'receives_led_commands': ko.observable(false)
310+
});
311+
self.settings.settings.plugins.tplinksmartplug.arrSmartplugs.push(self.selectedPlug());
312+
$("#tplink_device_discovery").modal("hide");
313+
$("#TPLinkPlugEditor").modal("show");
314+
}
315+
316+
self.discover_devices = function() {
317+
self.discovering(true);
318+
self.discovered_devices.removeAll();
319+
$("#tplink_device_discovery").modal("show");
320+
OctoPrint.simpleApiCommand("tplinksmartplug", "discoverDevices", {"username": self.settings.settings.plugins.tplinksmartplug.username(), "password": self.settings.settings.plugins.tplinksmartplug.password()}).done(function(data){
321+
self.discovering(false);
322+
self.discovered_devices.pushAll(ko.toJS(data.discovered_devices));
323+
console.log(self.discovered_devices);
324+
}).fail(function(jqXHR, textStatus, errorThrown){
325+
self.discovering(false);
326+
console.error("Failed to discover devices:", textStatus, errorThrown, jqXHR);
327+
alert("Failed to discover devices, please consult developer tools for more details.");
328+
});
329+
}
330+
271331
self.onDataUpdaterPluginMessage = function(plugin, data) {
272332
if (plugin != "tplinksmartplug") {
273333
return;

octoprint_tplinksmartplug/templates/tplinksmartplug_settings.jinja2

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<tr>
55
<td>{{ _('Plug') }}</td>
66
<td style="text-align:center">{{ _('Options') }}</td>
7-
<td style="text-align:center"><a href="#" class="btn btn-mini" data-bind="click: addPlug"><i class="fas fa-plus" aria-hidden="true"></i></a></td>
7+
<td style="text-align:center"><a href="#" class="btn btn-mini" data-bind="click: addPlug"><i class="fas fa-plus" aria-hidden="true"></i></a><a href="#" class="btn btn-mini" data-bind="click: discover_devices"><i class="fas fa-search" aria-hidden="true"></i></a></td>
88
</tr>
99
</thead>
1010
<tbody data-bind="sortable: { data: settings.settings.plugins.tplinksmartplug.arrSmartplugs, options: { cancel: '.unsortable', handle: '.movePlug', axis:'y'} }">
@@ -197,6 +197,29 @@
197197
</div>
198198
</div>
199199

200+
<div id="tplink_device_discovery" class="modal hide fade">
201+
<div class="modal-header">
202+
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
203+
<h3>{{ _('TP-Link Device Discovery') }}</h3>
204+
</div>
205+
<div class="modal-body form-vertical">
206+
<div class="info" data-bind="visible: discovering()"><i class="fa fa-spinner fa-spin"></i> Discovering devices please wait.</div>
207+
<div class="row-fluid" data-bind="foreach: discovered_devices.items">
208+
<div class="control-group">
209+
<label><a href="#" data-bind="click: function(){$root.add_discovered_device(value()['host'], value()['alias'])}"><span data-bind="text: value()['alias']"></span></a></label>
210+
<div class="controls">
211+
MODEL: <span data-bind="text: value()['model']"></span> <br>
212+
MAC: <span data-bind="text: value()['mac']"></span> <br>
213+
IP: <span data-bind="text: value()['host']"></span>
214+
</div>
215+
</div>
216+
</div>
217+
</div>
218+
<div class="modal-footer">
219+
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</a>
220+
</div>
221+
</div>
222+
200223
<div id="TPLinkPlugEditor" data-bind="with: selectedPlug" class="modal hide fade">
201224
<div class="modal-header">
202225
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
plugin_name = "OctoPrint-TPLinkSmartplug"
1515

1616
# The plugin's version. Can be overwritten within OctoPrint's internal data via __plugin_version__ in the plugin module
17-
plugin_version = "2.0.0rc5"
17+
plugin_version = "2.0.0rc6"
1818

1919
# The plugin's description. Can be overwritten within OctoPrint's internal data via __plugin_description__ in the plugin
2020
# module

0 commit comments

Comments
 (0)