#21 Add PowerOFF when print is finished

This commit is contained in:
David Zingg 2020-06-28 16:12:45 +02:00
parent 8ea9f65048
commit ebb6391bda
2 changed files with 245 additions and 228 deletions

View File

@ -48,13 +48,6 @@
<option name="presentableId" value="Default" /> <option name="presentableId" value="Default" />
<updated>1574193087583</updated> <updated>1574193087583</updated>
</task> </task>
<task id="LOCAL-00032" summary="#8 Relais ein / ausschalten von Ocotprint aus">
<created>1574607723126</created>
<option name="number" value="00032" />
<option name="presentableId" value="LOCAL-00032" />
<option name="project" value="LOCAL" />
<updated>1574607723126</updated>
</task>
<task id="LOCAL-00033" summary="#8 Relais ein / ausschalten von Ocotprint aus"> <task id="LOCAL-00033" summary="#8 Relais ein / ausschalten von Ocotprint aus">
<created>1574608168544</created> <created>1574608168544</created>
<option name="number" value="00033" /> <option name="number" value="00033" />
@ -391,7 +384,14 @@
<option name="project" value="LOCAL" /> <option name="project" value="LOCAL" />
<updated>1593352569980</updated> <updated>1593352569980</updated>
</task> </task>
<option name="localTasksCounter" value="81" /> <task id="LOCAL-00081" summary="#21 Add PowerOFF when print is finished">
<created>1593352709926</created>
<option name="number" value="00081" />
<option name="presentableId" value="LOCAL-00081" />
<option name="project" value="LOCAL" />
<updated>1593352709926</updated>
</task>
<option name="localTasksCounter" value="82" />
<servers /> <servers />
</component> </component>
<component name="UnknownFeatures"> <component name="UnknownFeatures">

View File

@ -84,6 +84,7 @@ class MyStromSwitchPlugin(octoprint.plugin.SettingsPlugin,
def _shutdown_timer_start(self): def _shutdown_timer_start(self):
if self._abort_timer is not None: if self._abort_timer is not None:
return return
self._logger.info("_shutdown_timer_start")
if self._wait_for_timelapse_timer is not None: if self._wait_for_timelapse_timer is not None:
self._wait_for_timelapse_timer.cancel() self._wait_for_timelapse_timer.cancel()
@ -97,6 +98,7 @@ class MyStromSwitchPlugin(octoprint.plugin.SettingsPlugin,
def _wait_for_timelapse_start(self): def _wait_for_timelapse_start(self):
if self._wait_for_timelapse_timer is not None: if self._wait_for_timelapse_timer is not None:
return return
self._logger.info("_wait_for_timelapse_start()")
self._wait_for_timelapse_timer = RepeatedTimer(5, self._wait_for_timelapse) self._wait_for_timelapse_timer = RepeatedTimer(5, self._wait_for_timelapse)
self._wait_for_timelapse_timer.start() self._wait_for_timelapse_timer.start()
@ -124,6 +126,7 @@ class MyStromSwitchPlugin(octoprint.plugin.SettingsPlugin,
if self.shutdownAfterPrintFinished: if self.shutdownAfterPrintFinished:
self._shutdown_system() self._shutdown_system()
elif self.powerOffAfterPrintFinished: elif self.powerOffAfterPrintFinished:
self._logger.info("only Shutdown Relais")
self._setRelaisState(False) self._setRelaisState(False)
def _status_timer_start(self): def _status_timer_start(self):
@ -137,241 +140,255 @@ class MyStromSwitchPlugin(octoprint.plugin.SettingsPlugin,
self._status_timer.start() self._status_timer.start()
def _shutdown_system(self): def _shutdown_system(self):
self._logger.info("Shutdown Relais and System")
self._powerCycleRelais(False, self.powerOffDelay) self._powerCycleRelais(False, self.powerOffDelay)
if self.shutdownAfterPrintFinished: shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"])
shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"]) self._logger.info("Shutting down system with command: {command}".format(command=shutdown_command))
self._logger.info("Shutting down system with command: {command}".format(command=shutdown_command)) try:
try: import sarge
import sarge p = sarge.run(shutdown_command, async=True)
p = sarge.run(shutdown_command, async=True) except Exception as e:
except Exception as e: self._logger.exception("Error when shutting down: {error}".format(error=e))
self._logger.exception("Error when shutting down: {error}".format(error=e)) return
return
def _status_timer_task(self):
if self.ip is not None:
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): def _status_timer_task(self):
nbRetry = 0 if self.ip is not None:
value = '0' try:
if newState:
value = '1'
while nbRetry < 3:
try: try:
request = requests.get( request = requests.get(
'http://{}/relay'.format(self.ip), params={'state': value}, timeout=1) '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:
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 set new Relais State, Http Status Code: {}".format(request.status_code)) "Could not powerCycle Relais, Http Status Code: {}".format(request.status_code))
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError as e:
self._logger.info("Error during set Relais state") self._logger.exception(e)
nbRetry = nbRetry + 1 self._logger.info("Error during powerCycle Relais: " + str(e.message))
except Exception as exp:
self._logger.exception(exp)
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:
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 _toggleRelay(self): def _toggleRelay(self):
nbRetry = 0 nbRetry = 0
while nbRetry < 3: while nbRetry < 3:
try: try:
request = requests.get( request = requests.get(
'http://{}/toggle'.format(self.ip), timeout=1) 'http://{}/toggle'.format(self.ip), timeout=1)
if request.status_code == 200: if request.status_code == 200:
return return
else: else:
self._logger.info("Could not toggle Relay State, Http Status Code: {}".format(request.status_code)) self._logger.info("Could not toggle Relay State, Http Status Code: {}".format(request.status_code))
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
self._logger.info("Error during toggle Relais state") self._logger.info("Error during toggle Relais state")
nbRetry = nbRetry + 1 nbRetry = nbRetry + 1
def on_api_command(self, command, data):
if command == "enableRelais": def on_api_command(self, command, data):
self._logger.info("enableRelais") if command == "enableRelais":
self._setRelaisState(True) self._logger.info("enableRelais")
elif command == "disableRelais": self._setRelaisState(True)
self._logger.info("disableRelais") elif command == "disableRelais":
self._logger.info("disableRelais")
self._setRelaisState(False)
elif command == "toggleRelais":
self._logger.info("toggleRelais")
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 get_api_commands(self):
return dict(
enableRelais=[],
disableRelais=[],
toggleRelais=[],
disableShutdownAfterFinish=[],
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)
elif command == "toggleRelais": else:
self._logger.info("toggleRelais") self._logger.info("Turn off Relais on Shutdown Delayed")
self._toggleRelay() self._powerCycleRelais(False, self.powerOffDelay)
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 get_api_commands(self):
return dict( def on_settings_migrate(self, target, current):
enableRelais=[], if target > current:
disableRelais=[], if current <= 1:
toggleRelais=[], self.onOffButtonEnabled = False
disableShutdownAfterFinish=[], if current <= 2:
enableShutdownAfterFinish=[], self.powerOnOnStart = False,
disablePowerOffAfterFinish=[], self.powerOffOnShutdown = False,
enablePowerOffAfterFinish=[] self.powerOffDelay = 0
) if current <= 3:
self.showShutdownOctopiOption = False
def on_after_startup(self): self.showPowerOffPrintFinishOption = False
if self.powerOnOnStart: self.shutdownDelay = 60
self._logger.info("Turn on Relais on Start")
self._setRelaisState(True)
def get_settings_version(self):
def on_shutdown(self): return 4
self._logger.info("on_shutdown_event")
if self.powerOffOnShutdown:
if self.powerOffDelay <= 0: def get_settings_defaults(self):
self._logger.info("Turn off Relais on Shutdown") return dict(
self._setRelaisState(False) ip=None,
else: intervall=1,
self._logger.info("Turn off Relais on Shutdown Delayed") onOffButtonEnabled=False,
self._powerCycleRelais(False, self.powerOffDelay) powerOnOnStart=False,
powerOffOnShutdown=False,
def on_settings_migrate(self, target, current): powerOffDelay=0,
if target > current: showShutdownOctopiOption=False,
if current <= 1: showPowerOffPrintFinishOption=False,
self.onOffButtonEnabled = False shutdownDelay=60
if current <= 2: )
self.powerOnOnStart = False,
self.powerOffOnShutdown = False,
self.powerOffDelay = 0 def get_settings_restricted_paths(self):
if current <= 3: return dict(admin=[
self.showShutdownOctopiOption = False ['ip']
self.showPowerOffPrintFinishOption = False ])
self.shutdownDelay = 60
def get_settings_version(self): def on_settings_save(self, data):
return 4 self._logger.info("on_settings_save")
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
def get_settings_defaults(self): self.initialize()
return dict(
ip=None,
intervall=1, def on_event(self, event, payload):
onOffButtonEnabled=False, if not self.shutdownAfterPrintFinished and not self.powerOffAfterPrintFinished:
powerOnOnStart=False, return
powerOffOnShutdown=False,
powerOffDelay=0, if not self._settings.global_get(["server", "commands", "systemShutdownCommand"]):
showShutdownOctopiOption=False, self._logger.warning("systemShutdownCommand is not defined. Aborting shutdown...")
showPowerOffPrintFinishOption=False, return
shutdownDelay=60
) if event not in [Events.PRINT_DONE, Events.PRINT_FAILED]:
return
def get_settings_restricted_paths(self):
return dict(admin=[ if event == Events.PRINT_FAILED and not self._printer.is_closed_or_error():
['ip'] # Cancelled job
]) return
def on_settings_save(self, data): if event in [Events.PRINT_DONE, Events.PRINT_FAILED]:
self._logger.info("on_settings_save") webcam_config = self._settings.global_get(["webcam", "timelapse"], merged=True)
octoprint.plugin.SettingsPlugin.on_settings_save(self, data) timelapse_type = webcam_config["type"]
self.initialize() if (timelapse_type is not None and timelapse_type != "off"):
self._wait_for_timelapse_start()
def on_event(self, event, payload): else:
self._shutdown_timer_start()
if not self.shutdownAfterPrintFinished and not self.powerOffAfterPrintFinished: return
return
if not self._settings.global_get(["server", "commands", "systemShutdownCommand"]): def get_update_information(self):
self._logger.warning("systemShutdownCommand is not defined. Aborting shutdown...") return dict(
return mystromswitch=dict(
displayName="OctoPrint-MyStromSwitch",
if event not in [Events.PRINT_DONE, Events.PRINT_FAILED]: displayVersion=self._plugin_version,
return
# version check: github repository
if event == Events.PRINT_FAILED and not self._printer.is_closed_or_error(): type="github_release",
# Cancelled job user="da4id",
return repo="OctoPrint-MyStromSwitch",
current=self._plugin_version,
if event in [Events.PRINT_DONE, Events.PRINT_FAILED]:
webcam_config = self._settings.global_get(["webcam", "timelapse"], merged=True) # update method: pip w/ dependency links
timelapse_type = webcam_config["type"] pip="https://github.com/da4id/OctoPrint-MyStromSwitch/archive/{target_version}.zip"
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"