#21 Add PowerOFF when print is finished

This commit is contained in:
David Zingg 2020-06-28 16:34:51 +02:00
parent 39ff47e829
commit 6f96140e10
2 changed files with 230 additions and 231 deletions

View File

@ -2,8 +2,7 @@
<project version="4"> <project version="4">
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="7e2e0eec-b22e-4d48-8f24-196d1ed9b51a" name="Default Changelist" comment=""> <list default="true" id="7e2e0eec-b22e-4d48-8f24-196d1ed9b51a" name="Default Changelist" comment="">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/octoprint_mystromswitch/__init__.py" beforeDir="false" afterPath="$PROJECT_DIR$/octoprint_mystromswitch/__init__.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/setup.py" beforeDir="false" afterPath="$PROJECT_DIR$/setup.py" afterDir="false" />
</list> </list>
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" /> <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
@ -48,13 +47,6 @@
<option name="presentableId" value="Default" /> <option name="presentableId" value="Default" />
<updated>1574193087583</updated> <updated>1574193087583</updated>
</task> </task>
<task id="LOCAL-00034" summary="#8 Relais ein / ausschalten von Ocotprint aus">
<created>1574608700412</created>
<option name="number" value="00034" />
<option name="presentableId" value="LOCAL-00034" />
<option name="project" value="LOCAL" />
<updated>1574608700412</updated>
</task>
<task id="LOCAL-00035" summary="#8 Relais ein / ausschalten von Ocotprint aus"> <task id="LOCAL-00035" summary="#8 Relais ein / ausschalten von Ocotprint aus">
<created>1574609194050</created> <created>1574609194050</created>
<option name="number" value="00035" /> <option name="number" value="00035" />
@ -391,7 +383,14 @@
<option name="project" value="LOCAL" /> <option name="project" value="LOCAL" />
<updated>1593353565224</updated> <updated>1593353565224</updated>
</task> </task>
<option name="localTasksCounter" value="83" /> <task id="LOCAL-00083" summary="#21 Add PowerOFF when print is finished">
<created>1593354627917</created>
<option name="number" value="00083" />
<option name="presentableId" value="LOCAL-00083" />
<option name="project" value="LOCAL" />
<updated>1593354627917</updated>
</task>
<option name="localTasksCounter" value="84" />
<servers /> <servers />
</component> </component>
<component name="UnknownFeatures"> <component name="UnknownFeatures">

View File

@ -152,243 +152,243 @@ class MyStromSwitchPlugin(octoprint.plugin.SettingsPlugin,
return return
def _status_timer_task(self): def _status_timer_task(self):
if self.ip is not None: if self.ip is not None:
try: try:
try:
request = requests.get(
'http://{}/report'.format(self.ip), timeout=1)
if request.status_code == 200:
timestamp = time.time()
data = request.json()
if not self.lastTimeStamp == 0:
intervall = timestamp - self.lastTimeStamp
# Energy in Wh
self.energy = self.energy + (intervall * data["power"] / 3600)
self._logger.debug(
"Energy: " + str(self.energy) + " interval: " + str(intervall) + " power: " + str(
data["power"]))
self.lastTimeStamp = timestamp
data["energy"] = self.energy
data["onOffButtonEnabled"] = self.onOffButtonEnabled
data["showShutdownOctopiOption"] = self.showShutdownOctopiOption
data["showPowerOffPrintFinishOption"] = self.showPowerOffPrintFinishOption
data["automaticShutdownEnabled"] = self.shutdownAfterPrintFinished
data["automaticPowerOffEnabled"] = self.powerOffAfterPrintFinished
self._plugin_manager.send_plugin_message(self._identifier, data)
return
except (requests.exceptions.ConnectionError, ValueError) as e:
self._logger.exception(e)
except Exception as exp:
self._logger.exception(exp)
else:
self._logger.info("Ip is None")
data = {"relay": True, "energy": 0, "onOffButtonEnabled": False, "showShutdownOctopiOption": False,
"showPowerOffPrintFinishOption": False, "automaticShutdownEnabled": self.shutdownAfterPrintFinished,
"v": self.powerOffAfterPrintFinished}
self._plugin_manager.send_plugin_message(self._identifier, data)
def _setRelaisState(self, newState):
nbRetry = 0
value = '0'
if newState:
value = '1'
while nbRetry < 3:
try: try:
request = requests.get( request = requests.get(
'http://{}/report'.format(self.ip), timeout=1) 'http://{}/relay'.format(self.ip), params={'state': value}, timeout=1)
if request.status_code == 200:
timestamp = time.time()
data = request.json()
if not self.lastTimeStamp == 0:
intervall = timestamp - self.lastTimeStamp
# Energy in Wh
self.energy = self.energy + (intervall * data["power"] / 3600)
self._logger.debug(
"Energy: " + str(self.energy) + " interval: " + str(intervall) + " power: " + str(
data["power"]))
self.lastTimeStamp = timestamp
data["energy"] = self.energy
data["onOffButtonEnabled"] = self.onOffButtonEnabled
data["showShutdownOctopiOption"] = self.showShutdownOctopiOption
data["showPowerOffPrintFinishOption"] = self.showPowerOffPrintFinishOption
data["automaticShutdownEnabled"] = self.shutdownAfterPrintFinished
data["automaticPowerOffEnabled"] = self.powerOffAfterPrintFinished
self._plugin_manager.send_plugin_message(self._identifier, data)
return
except (requests.exceptions.ConnectionError, ValueError) as e:
self._logger.exception(e)
except Exception as exp:
self._logger.exception(exp)
else:
self._logger.info("Ip is None")
data = {"relay": True, "energy": 0, "onOffButtonEnabled": False, "showShutdownOctopiOption": False,
"showPowerOffPrintFinishOption": False, "automaticShutdownEnabled": self.shutdownAfterPrintFinished,
"v": self.powerOffAfterPrintFinished}
self._plugin_manager.send_plugin_message(self._identifier, data)
def _setRelaisState(self, newState):
nbRetry = 0
value = '0'
if newState:
value = '1'
while nbRetry < 3:
try:
request = requests.get(
'http://{}/relay'.format(self.ip), params={'state': value}, timeout=1)
if request.status_code == 200:
return
else:
self._logger.info(
"Could not set new Relais State, Http Status Code: {}".format(request.status_code))
except requests.exceptions.ConnectionError:
self._logger.info("Error during set Relais state")
nbRetry = nbRetry + 1
# Sets the switch to a specific inverse newState,
# waits for a specified amount of time (max 3h),
# then sets the the switch to the newState.
def _powerCycleRelais(self, newState, time):
nbRetry = 0
value = 'on'
if newState:
value = 'off'
while nbRetry < 3:
try:
try:
self._logger.info("try to send Powercycle Request")
self._logger.info('http://{}/timer'.format(self.ip))
request = requests.post(
'http://{}/timer'.format(self.ip), params={'mode': value, 'time': time}, timeout=1)
if request.status_code == 200: if request.status_code == 200:
return return
else: else:
self._logger.info( self._logger.info(
"Could not powerCycle Relais, Http Status Code: {}".format(request.status_code)) "Could not set new Relais State, Http Status Code: {}".format(request.status_code))
except requests.exceptions.ConnectionError as e: except requests.exceptions.ConnectionError:
self._logger.exception(e) self._logger.info("Error during set Relais state")
self._logger.info("Error during powerCycle Relais: " + str(e.message)) nbRetry = nbRetry + 1
except Exception as exp:
self._logger.exception(exp)
nbRetry = nbRetry + 1
def _toggleRelay(self): # Sets the switch to a specific inverse newState,
nbRetry = 0 # waits for a specified amount of time (max 3h),
while nbRetry < 3: # then sets the the switch to the newState.
try: def _powerCycleRelais(self, newState, time):
request = requests.get( nbRetry = 0
'http://{}/toggle'.format(self.ip), timeout=1) value = 'on'
if request.status_code == 200: if newState:
return value = 'off'
else: while nbRetry < 3:
self._logger.info("Could not toggle Relay State, Http Status Code: {}".format(request.status_code)) try:
except requests.exceptions.ConnectionError: try:
self._logger.info("Error during toggle Relais state") self._logger.info("try to send Powercycle Request")
nbRetry = nbRetry + 1 self._logger.info('http://{}/timer'.format(self.ip))
request = requests.post(
'http://{}/timer'.format(self.ip), params={'mode': value, 'time': time}, timeout=1)
if request.status_code == 200:
return
else:
self._logger.info(
"Could not powerCycle Relais, Http Status Code: {}".format(request.status_code))
except requests.exceptions.ConnectionError as e:
self._logger.exception(e)
self._logger.info("Error during powerCycle Relais: " + str(e.message))
except Exception as exp:
self._logger.exception(exp)
nbRetry = nbRetry + 1
def on_api_command(self, command, data): def _toggleRelay(self):
if command == "enableRelais": nbRetry = 0
self._logger.info("enableRelais") while nbRetry < 3:
self._setRelaisState(True) try:
elif command == "disableRelais": request = requests.get(
self._logger.info("disableRelais") 'http://{}/toggle'.format(self.ip), timeout=1)
self._setRelaisState(False) if request.status_code == 200:
elif command == "toggleRelais": return
self._logger.info("toggleRelais") else:
self._toggleRelay() self._logger.info("Could not toggle Relay State, Http Status Code: {}".format(request.status_code))
elif command == "enableShutdownAfterFinish": except requests.exceptions.ConnectionError:
self._logger.info("enableShutdownAfterFinish") self._logger.info("Error during toggle Relais state")
self.shutdownAfterPrintFinished = True nbRetry = nbRetry + 1
elif command == "disableShutdownAfterFinish":
self._logger.info("disableShutdownAfterFinish")
self.shutdownAfterPrintFinished = False
elif command == "enablePowerOffAfterFinish":
self._logger.info("enablePowerOffAfterFinish")
self.powerOffAfterPrintFinished = True
elif command == "disablePowerOffAfterFinish":
self._logger.info("disablePowerOffAfterFinish")
self.powerOffAfterPrintFinished = False
def get_api_commands(self): def on_api_command(self, command, data):
return dict( if command == "enableRelais":
enableRelais=[], self._logger.info("enableRelais")
disableRelais=[], self._setRelaisState(True)
toggleRelais=[], elif command == "disableRelais":
disableShutdownAfterFinish=[], self._logger.info("disableRelais")
enableShutdownAfterFinish=[],
disablePowerOffAfterFinish=[],
enablePowerOffAfterFinish=[]
)
def on_after_startup(self):
if self.powerOnOnStart:
self._logger.info("Turn on Relais on Start")
self._setRelaisState(True)
def on_shutdown(self):
self._logger.info("on_shutdown_event")
if self.powerOffOnShutdown:
if self.powerOffDelay <= 0:
self._logger.info("Turn off Relais on Shutdown")
self._setRelaisState(False) self._setRelaisState(False)
else: elif command == "toggleRelais":
self._logger.info("Turn off Relais on Shutdown Delayed") self._logger.info("toggleRelais")
self._powerCycleRelais(False, self.powerOffDelay) self._toggleRelay()
elif command == "enableShutdownAfterFinish":
self._logger.info("enableShutdownAfterFinish")
self.shutdownAfterPrintFinished = True
elif command == "disableShutdownAfterFinish":
self._logger.info("disableShutdownAfterFinish")
self.shutdownAfterPrintFinished = False
elif command == "enablePowerOffAfterFinish":
self._logger.info("enablePowerOffAfterFinish")
self.powerOffAfterPrintFinished = True
elif command == "disablePowerOffAfterFinish":
self._logger.info("disablePowerOffAfterFinish")
self.powerOffAfterPrintFinished = False
def on_settings_migrate(self, target, current): def get_api_commands(self):
if target > current: return dict(
if current <= 1: enableRelais=[],
self.onOffButtonEnabled = False disableRelais=[],
if current <= 2: toggleRelais=[],
self.powerOnOnStart = False, disableShutdownAfterFinish=[],
self.powerOffOnShutdown = False, enableShutdownAfterFinish=[],
self.powerOffDelay = 0 disablePowerOffAfterFinish=[],
if current <= 3: enablePowerOffAfterFinish=[]
self.showShutdownOctopiOption = False )
self.showPowerOffPrintFinishOption = False
self.shutdownDelay = 60
def on_after_startup(self):
if self.powerOnOnStart:
def get_settings_version(self): self._logger.info("Turn on Relais on Start")
return 4 self._setRelaisState(True)
def get_settings_defaults(self): def on_shutdown(self):
return dict( self._logger.info("on_shutdown_event")
ip=None, if self.powerOffOnShutdown:
intervall=1, if self.powerOffDelay <= 0:
onOffButtonEnabled=False, self._logger.info("Turn off Relais on Shutdown")
powerOnOnStart=False, self._setRelaisState(False)
powerOffOnShutdown=False, else:
powerOffDelay=0, self._logger.info("Turn off Relais on Shutdown Delayed")
showShutdownOctopiOption=False, self._powerCycleRelais(False, self.powerOffDelay)
showPowerOffPrintFinishOption=False,
shutdownDelay=60
) def on_settings_migrate(self, target, current):
if target > current:
if current <= 1:
def get_settings_restricted_paths(self): self.onOffButtonEnabled = False
return dict(admin=[ if current <= 2:
['ip'] self.powerOnOnStart = False,
]) self.powerOffOnShutdown = False,
self.powerOffDelay = 0
if current <= 3:
def on_settings_save(self, data): self.showShutdownOctopiOption = False
self._logger.info("on_settings_save") self.showPowerOffPrintFinishOption = False
octoprint.plugin.SettingsPlugin.on_settings_save(self, data) self.shutdownDelay = 60
self.initialize()
def get_settings_version(self):
def on_event(self, event, payload): return 4
if not self.shutdownAfterPrintFinished and not self.powerOffAfterPrintFinished:
return
def get_settings_defaults(self):
if not self._settings.global_get(["server", "commands", "systemShutdownCommand"]): return dict(
self._logger.warning("systemShutdownCommand is not defined. Aborting shutdown...") ip=None,
return intervall=1,
onOffButtonEnabled=False,
if event not in [Events.PRINT_DONE, Events.PRINT_FAILED]: powerOnOnStart=False,
return powerOffOnShutdown=False,
powerOffDelay=0,
if event == Events.PRINT_FAILED and not self._printer.is_closed_or_error(): showShutdownOctopiOption=False,
# Cancelled job showPowerOffPrintFinishOption=False,
return shutdownDelay=60
)
if event in [Events.PRINT_DONE, Events.PRINT_FAILED]:
webcam_config = self._settings.global_get(["webcam", "timelapse"], merged=True)
timelapse_type = webcam_config["type"] def get_settings_restricted_paths(self):
if (timelapse_type is not None and timelapse_type != "off"): return dict(admin=[
self._wait_for_timelapse_start() ['ip']
else: ])
self._shutdown_timer_start()
return
def on_settings_save(self, data):
self._logger.info("on_settings_save")
def get_update_information(self): octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
return dict( self.initialize()
mystromswitch=dict(
displayName="OctoPrint-MyStromSwitch",
displayVersion=self._plugin_version, def on_event(self, event, payload):
if not self.shutdownAfterPrintFinished and not self.powerOffAfterPrintFinished:
# version check: github repository return
type="github_release",
user="da4id", if not self._settings.global_get(["server", "commands", "systemShutdownCommand"]):
repo="OctoPrint-MyStromSwitch", self._logger.warning("systemShutdownCommand is not defined. Aborting shutdown...")
current=self._plugin_version, return
# update method: pip w/ dependency links if event not in [Events.PRINT_DONE, Events.PRINT_FAILED]:
pip="https://github.com/da4id/OctoPrint-MyStromSwitch/archive/{target_version}.zip" return
if event == Events.PRINT_FAILED and not self._printer.is_closed_or_error():
# Cancelled job
return
if event in [Events.PRINT_DONE, Events.PRINT_FAILED]:
webcam_config = self._settings.global_get(["webcam", "timelapse"], merged=True)
timelapse_type = webcam_config["type"]
if (timelapse_type is not None and timelapse_type != "off"):
self._wait_for_timelapse_start()
else:
self._shutdown_timer_start()
return
def get_update_information(self):
return dict(
mystromswitch=dict(
displayName="OctoPrint-MyStromSwitch",
displayVersion=self._plugin_version,
# version check: github repository
type="github_release",
user="da4id",
repo="OctoPrint-MyStromSwitch",
current=self._plugin_version,
# update method: pip w/ dependency links
pip="https://github.com/da4id/OctoPrint-MyStromSwitch/archive/{target_version}.zip"
)
) )
)
__plugin_name__ = "MyStrom Switch" __plugin_name__ = "MyStrom Switch"