From 1e8d272f7bd58963405d09e21860d4e128887be8 Mon Sep 17 00:00:00 2001 From: Vitor de Miranda Henrique Date: Tue, 19 Jun 2018 23:30:53 -0500 Subject: [PATCH 01/52] fix on templates --- octoprint_enclosure/templates/enclosure_settings.jinja2 | 6 +++--- octoprint_enclosure/templates/enclosure_tab.jinja2 | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/octoprint_enclosure/templates/enclosure_settings.jinja2 b/octoprint_enclosure/templates/enclosure_settings.jinja2 index b8bb251..ccae363 100644 --- a/octoprint_enclosure/templates/enclosure_settings.jinja2 +++ b/octoprint_enclosure/templates/enclosure_settings.jinja2 @@ -85,7 +85,7 @@ - +
@@ -175,7 +175,7 @@ - +
@@ -208,7 +208,7 @@
- +
- +
@@ -256,7 +262,7 @@
- +
- +
+ @@ -404,6 +411,27 @@
+ +
+ +
+ + Choose any GPIO pin to provide the Clock signal +
+ +
+ + Choose any GPIO pin to provide the Data +
+
+
+ +
+ + Value needs to follow the format rgb(value_red,value_green,value_blue) where values should be between 0 and 255 +
+
+
diff --git a/octoprint_enclosure/templates/enclosure_tab.jinja2 b/octoprint_enclosure/templates/enclosure_tab.jinja2 index dff7479..9b4feba 100644 --- a/octoprint_enclosure/templates/enclosure_tab.jinja2 +++ b/octoprint_enclosure/templates/enclosure_tab.jinja2 @@ -160,6 +160,19 @@
+ +

+ + ledstrip +

+
+ + +
+ +

-- 2.39.5 From 72c4e7077a8b5d40fd0499c0316820681e9c6fdf Mon Sep 17 00:00:00 2001 From: Vitor de Miranda Henrique Date: Mon, 25 Feb 2019 21:55:39 -0600 Subject: [PATCH 09/52] Update neopixel_direct.py updating to new rpi_ws281x --- octoprint_enclosure/neopixel_direct.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/octoprint_enclosure/neopixel_direct.py b/octoprint_enclosure/neopixel_direct.py index 382400a..3af63f9 100644 --- a/octoprint_enclosure/neopixel_direct.py +++ b/octoprint_enclosure/neopixel_direct.py @@ -1,4 +1,4 @@ -from neopixel import * +from rpi_ws281x import * import sys import time @@ -20,7 +20,7 @@ else: strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT) strip.begin() -color = Color(green, red, blue) +color = Color(red, green, blue) for i in range(LED_COUNT): strip.setPixelColor(i, color) -- 2.39.5 From 79ee94bf45b4134ec41a77c58063948522af8555 Mon Sep 17 00:00:00 2001 From: Vitor de Miranda Henrique Date: Mon, 25 Feb 2019 22:02:25 -0600 Subject: [PATCH 10/52] Update README.md --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index 0e32f2a..fc4f104 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,27 @@ Find the address of the sensor:
i2cdetect -y 1
+* For Neopixel + +If your setup does not have pip install pip: +`sudo apt-get install python-pip` + +Install the required library: +`sudo pip install rpi_ws281x` + +rpi_ws281x really needs sudo, and you need to setup up so your rpi does not ask for a password when runing a python script, so run: + +`sudo visudo` + +and add `pi ALL=(ALL) NOPASSWD: ALL` to the end of the file. + +Also backlist the audio kernel: + +`sudo nano /etc/modprobe.d/snd-blacklist.conf` + +add the `blacklist snd_bcm2835` to the end of the file: + + * GPIO This release uses RPi.GPIO to control IO of raspberry pi, it should install and work automatically. If it doesn't please update your octoprint with the latest release of octopi. -- 2.39.5 From 6b748e5e41520d46672ddf8c95ab2cd984300c9a Mon Sep 17 00:00:00 2001 From: Vitor de Miranda Henrique Date: Tue, 26 Feb 2019 12:57:42 -0600 Subject: [PATCH 11/52] fix for 207 --- octoprint_enclosure/__init__.py | 61 ++++++++++++++++----------------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 5fd1b5a..ae4ff88 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -1071,37 +1071,36 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, if self._settings.get(["debug"]) is True: self._logger.info( "GPIO event triggered on channel %s", channel) - rpi_input = [r_inp for r_inp in self.rpi_inputs if self.to_int( - r_inp['gpio_pin']) == self.to_int(channel)].pop() - gpio_pin = self.to_int(rpi_input['gpio_pin']) - controlled_io = self.to_int(rpi_input['controlled_io']) - if (rpi_input['edge'] == 'fall') ^ GPIO.input(gpio_pin): - rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int( - r_out['index_id']) == controlled_io].pop() - if rpi_output['output_type'] == 'regular': - if rpi_input['controlled_io_set_value'] == 'toggle': - val = GPIO.LOW if GPIO.input(self.to_int( - rpi_output['gpio_pin'])) == GPIO.HIGH else GPIO.HIGH - else: - val = GPIO.LOW if rpi_input['controlled_io_set_value'] == 'low' else GPIO.HIGH - self.write_gpio(self.to_int( - rpi_output['gpio_pin']), val) - for notification in self.notifications: - if notification['gpioAction']: - msg = "GPIO control action caused by input " + str(rpi_input['label']) + ". Setting GPIO" + str( - rpi_input['controlled_io']) + " to: " + str(rpi_input['controlled_io_set_value']) - self.send_notification(msg) - if rpi_output['output_type'] == 'gcode_output': - self.send_gcode_command(rpi_output['gcode']) - for notification in self.notifications: - if notification['gpioAction']: - msg = "GPIO control action caused by input " + \ - str(rpi_input['label']) + \ - ". Sending GCODE command" - self.send_notification(msg) - if rpi_output['output_type'] == 'shell_output': - command = rpi_output['shell_script'] - self.shell_command(command) + for rpi_input in list(filter(lambda item: self.to_int(item['gpio_pin']) == self.to_int(channel), self.rpi_inputs)): + gpio_pin = self.to_int(rpi_input['gpio_pin']) + controlled_io = self.to_int(rpi_input['controlled_io']) + if (rpi_input['edge'] == 'fall') ^ GPIO.input(gpio_pin): + rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int( + r_out['index_id']) == controlled_io].pop() + if rpi_output['output_type'] == 'regular': + if rpi_input['controlled_io_set_value'] == 'toggle': + val = GPIO.LOW if GPIO.input(self.to_int( + rpi_output['gpio_pin'])) == GPIO.HIGH else GPIO.HIGH + else: + val = GPIO.LOW if rpi_input['controlled_io_set_value'] == 'low' else GPIO.HIGH + self.write_gpio(self.to_int( + rpi_output['gpio_pin']), val) + for notification in self.notifications: + if notification['gpioAction']: + msg = "GPIO control action caused by input " + str(rpi_input['label']) + ". Setting GPIO" + str( + rpi_input['controlled_io']) + " to: " + str(rpi_input['controlled_io_set_value']) + self.send_notification(msg) + if rpi_output['output_type'] == 'gcode_output': + self.send_gcode_command(rpi_output['gcode']) + for notification in self.notifications: + if notification['gpioAction']: + msg = "GPIO control action caused by input " + \ + str(rpi_input['label']) + \ + ". Sending GCODE command" + self.send_notification(msg) + if rpi_output['output_type'] == 'shell_output': + command = rpi_output['shell_script'] + self.shell_command(command) except Exception as ex: self.log_error(ex) pass -- 2.39.5 From 7fa53827fd33a3e167c32cb66efb90367d4f6327 Mon Sep 17 00:00:00 2001 From: Arti4ever <39329296+Arti4ever@users.noreply.github.com> Date: Sat, 2 Mar 2019 15:37:38 +0100 Subject: [PATCH 12/52] update_ui on client connection and page refresh. This to avoid wrong gpio status after page refresh. --- octoprint_enclosure/__init__.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index ae4ff88..63d094c 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -1253,6 +1253,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, if event == Events.CONNECTED: self.update_ui() + if event == Events.CLIENT_OPENED: + self.update_ui() + if event == Events.PRINT_RESUMED: self.start_filament_detection() @@ -1707,4 +1710,3 @@ def __plugin_load__(): "octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.hook_gcode_queuing, "octoprint.plugin.softwareupdate.check_config": __plugin_implementation__.get_update_information } - -- 2.39.5 From e96284873e59eaf38808f55cd4de125dcf3fa482 Mon Sep 17 00:00:00 2001 From: Marshall Eubanks Date: Wed, 6 Mar 2019 14:12:44 -0500 Subject: [PATCH 13/52] added MAX31855 support --- octoprint_enclosure/__init__.py | 23 +++++++++++++++- octoprint_enclosure/max31855.py | 27 +++++++++++++++++++ .../templates/enclosure_settings.jinja2 | 26 +++++++++++++++++- 3 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 octoprint_enclosure/max31855.py diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 63d094c..ae83bb0 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -555,6 +555,10 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, temp = self.read_tmp102_temp( sensor['temp_sensor_address']) hum = 0 + elif sensor['temp_sensor_type'] == "max31855": + temp = self.read_max31855_temp( + sensor['temp_sensor_address']) + hum = 0 else: self._logger.info("temp_sensor_type no match") temp = None @@ -708,7 +712,24 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, "Failed to excecute python scripts, try disabling use SUDO on advanced section.") self.log_error(ex) return 0 - + + def read_max31855_temp(self, address): + try: + script = os.path.dirname(os.path.realpath(__file__)) + "/max31855.py" + args = ["python", script, str(address)] + if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + self._logger.info("Temperature MAX31855 cmd: %s", " ".join(args)) + proc = Popen(args, stdout=PIPE) + stdout, _ = proc.communicate() + if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + self._logger.info("MAX31855 result: %s", stdout) + return self.to_float(stdout.strip()) + except Exception as ex: + self._logger.info( + "Failed to excecute python scripts, try disabling use SUDO on advanced section.") + self.log_error(ex) + return 0 + def handle_pwm_linked_temperature(self): try: for pwm_output in list(filter(lambda item: item['output_type'] == 'pwm' and item['pwm_temperature_linked'], self.rpi_outputs)): diff --git a/octoprint_enclosure/max31855.py b/octoprint_enclosure/max31855.py new file mode 100644 index 0000000..208d0f9 --- /dev/null +++ b/octoprint_enclosure/max31855.py @@ -0,0 +1,27 @@ +import ctypes +import struct +import sys + +import Adafruit_GPIO.SPI as SPI +import Adafruit_MAX31855.MAX31855 as MAX31855 + + +def main(): + # Get bus address if provided or use default address + SPI_DEVICE = 0 + if len(sys.argv) >= 2: + SPI_DEVICE = int(sys.argv[1], 0) + + if not 0 <= SPI_DEVICE <= 1: + raise ValueError("Invalid address value") + + # Raspberry Pi hardware SPI configuration. + SPI_PORT = 0 + sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) + + temp = sensor.readTempC() + + print('{0:0.1f}'.format(temp)) + +if __name__ == "__main__": + main() diff --git a/octoprint_enclosure/templates/enclosure_settings.jinja2 b/octoprint_enclosure/templates/enclosure_settings.jinja2 index 97c05e5..9f60ed4 100644 --- a/octoprint_enclosure/templates/enclosure_settings.jinja2 +++ b/octoprint_enclosure/templates/enclosure_settings.jinja2 @@ -536,6 +536,7 @@ + Attention You need to install and configure the necessary libraries for the temperature sensor, check @@ -579,7 +580,30 @@

- + +
+ +
+ + GPIO pin for temperature sensor need to connect the sensor to SPI. Serial Clock to GPIO 1 (SCLK) and Master In/Slave Out Data to GPIO + 9 (MISO) + +
+
+
+ +
+ + CE select: CE0 on GPIO 8 or CE1 on GPIO 7 +
+
+ + +
-- 2.39.5 From a241dc50cae17ee4629e32b92305e0d4dd7248a2 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 10:47:52 +0000 Subject: [PATCH 14/52] add debug loggers --- octoprint_enclosure/__init__.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index ae83bb0..13261ad 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -1202,18 +1202,19 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, pass def write_pwm(self, gpio, pwm_value, queue_id=None): + self.logger.debug("Calling write_pwm: %s, %s ,%s", gpio, pwm_value, queue_id) try: if queue_id is not None and self._settings.get(["debug"]) is True: - self._logger.info("Runing scheduled queue id %s", queue_id) + self._logger.info("Running scheduled queue id %s", queue_id) for pwm in self.pwm_intances: + self.logger.debug("pwm: %s", pwm) if gpio in pwm: pwm_object = pwm[gpio] old_pwm_value = pwm['duty_cycle'] if 'duty_cycle' in pwm else -1 if not self.to_int(old_pwm_value) == self.to_int(pwm_value): pwm['duty_cycle'] = pwm_value pwm_object.ChangeDutyCycle(pwm_value) - if self._settings.get(["debug"]) is True: - self._logger.info( + self._logger.debug( "Writing PWM on gpio: %s value %s", gpio, pwm_value) self.update_ui() if queue_id is not None: -- 2.39.5 From 8a13019eca6e6bbde9b937819568475e5b0af173 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 10:49:03 +0000 Subject: [PATCH 15/52] add debug loggers --- octoprint_enclosure/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 13261ad..68324b5 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -753,8 +753,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, except: calculated_duty = 0 - if self._settings.get(["debug"]) is True: - self._logger.info( + + self._logger.info( "Calculated duty for PWM %s is %s", index_id, calculated_duty) elif self.print_complete: calculated_duty = self.to_int(pwm_output['duty_cycle']) -- 2.39.5 From 2cc7e621e8f40b5837555e73ab7628bc7994c763 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 10:52:47 +0000 Subject: [PATCH 16/52] remove if printing check from PWM temp linked --- octoprint_enclosure/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 68324b5..5125508 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -734,7 +734,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, try: for pwm_output in list(filter(lambda item: item['output_type'] == 'pwm' and item['pwm_temperature_linked'], self.rpi_outputs)): gpio_pin = self.to_int(pwm_output['gpio_pin']) - if self._printer.is_printing(): + if True==True: #if self._printer.is_printing(): index_id = self.to_int(pwm_output['index_id']) linked_id = self.to_int(pwm_output['linked_temp_sensor']) linked_data = self.get_linked_temp_sensor_data( -- 2.39.5 From 2a9f49cfb83336e8ab7beaf0aabb32b12a5e45b7 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 10:59:21 +0000 Subject: [PATCH 17/52] remove if printing check from PWM temp linked --- octoprint_enclosure/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 5125508..ca84e13 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -1202,12 +1202,12 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, pass def write_pwm(self, gpio, pwm_value, queue_id=None): - self.logger.debug("Calling write_pwm: %s, %s ,%s", gpio, pwm_value, queue_id) + self._logger.debug("Calling write_pwm: %s, %s ,%s", gpio, pwm_value, queue_id) try: if queue_id is not None and self._settings.get(["debug"]) is True: self._logger.info("Running scheduled queue id %s", queue_id) for pwm in self.pwm_intances: - self.logger.debug("pwm: %s", pwm) + self._logger.debug("pwm: %s", pwm) if gpio in pwm: pwm_object = pwm[gpio] old_pwm_value = pwm['duty_cycle'] if 'duty_cycle' in pwm else -1 -- 2.39.5 From f67c840a52119360363021003f6b19e4db3bea19 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 11:13:33 +0000 Subject: [PATCH 18/52] force int write pwm --- octoprint_enclosure/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index ca84e13..8c179d8 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -1202,6 +1202,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, pass def write_pwm(self, gpio, pwm_value, queue_id=None): + gpio =int(gpio) self._logger.debug("Calling write_pwm: %s, %s ,%s", gpio, pwm_value, queue_id) try: if queue_id is not None and self._settings.get(["debug"]) is True: -- 2.39.5 From ca966fa1189298e868c486d18906adacceb7fed4 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 11:19:03 +0000 Subject: [PATCH 19/52] force int write pwm --- octoprint_enclosure/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 8c179d8..e25d12f 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -1202,7 +1202,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, pass def write_pwm(self, gpio, pwm_value, queue_id=None): - gpio =int(gpio) + pwm_value =int(pwm_value) self._logger.debug("Calling write_pwm: %s, %s ,%s", gpio, pwm_value, queue_id) try: if queue_id is not None and self._settings.get(["debug"]) is True: -- 2.39.5 From 633e60491b56b3903481328e49e9169790bac1ef Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 11:43:34 +0000 Subject: [PATCH 20/52] update rpis gpio --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index c32c700..54921de 100644 --- a/setup.py +++ b/setup.py @@ -33,7 +33,7 @@ plugin_url = "https://github.com/vitormhenrique/OctoPrint-Enclosure" plugin_license = "AGPLv3" # Any additional requirements besides OctoPrint should be listed here -plugin_requires = ["RPi.GPIO>=0.6","requests>=2.7"] +plugin_requires = ["RPi.GPIO>=0.6.5","requests>=2.7"] additional_setup_parameters = {} -- 2.39.5 From 08ea7e2993fa2180938a0e1de530ffb22a926a82 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 11:50:54 +0000 Subject: [PATCH 21/52] more logging messages --- octoprint_enclosure/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index e25d12f..1f94804 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -1214,6 +1214,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, old_pwm_value = pwm['duty_cycle'] if 'duty_cycle' in pwm else -1 if not self.to_int(old_pwm_value) == self.to_int(pwm_value): pwm['duty_cycle'] = pwm_value + self._logger.debug("Changing duty cycle: %s", pwm_value) + self._logger.debug("PWM Object is: %s", pwm_object) pwm_object.ChangeDutyCycle(pwm_value) self._logger.debug( "Writing PWM on gpio: %s value %s", gpio, pwm_value) -- 2.39.5 From 820ede48b25ecda616c00c9e1f1aa391850eb4f9 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 12:04:23 +0000 Subject: [PATCH 22/52] yet more logging messages --- octoprint_enclosure/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 1f94804..dfcd524 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -1207,8 +1207,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, try: if queue_id is not None and self._settings.get(["debug"]) is True: self._logger.info("Running scheduled queue id %s", queue_id) + self._logger.debug("pwm_instances: %s", self.pwm_intances) for pwm in self.pwm_intances: - self._logger.debug("pwm: %s", pwm) + self._logger.debug("is gpio in pwm? : %s", (gpio in pwm)) if gpio in pwm: pwm_object = pwm[gpio] old_pwm_value = pwm['duty_cycle'] if 'duty_cycle' in pwm else -1 -- 2.39.5 From fa4252905dfee5df95e00960dbb06304af7c7fa8 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 12:28:07 +0000 Subject: [PATCH 23/52] try-except for creating pwm instances --- octoprint_enclosure/__init__.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index dfcd524..39c81cd 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -916,6 +916,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, self.log_error(ex) def clear_channel(self, channel): + self._logging.debug("Clearing channel: %s", channel) try: GPIO.cleanup(self.to_int(channel)) except Exception as ex: @@ -942,16 +943,22 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, GPIO.setup(pin, GPIO.OUT, initial=initial_value) for gpio_out_pwm in list(filter(lambda item: item['output_type'] == 'pwm', self.rpi_outputs)): pin = self.to_int(gpio_out_pwm['gpio_pin']) - self._logger.info( - "Setting GPIO pin %s as PWM", pin) + self._logger.info("Setting GPIO pin %s as PWM", pin) + for pwm in (pwm_dict for pwm_dict in self.pwm_intances if pin in pwm_dict): self.pwm_intances.remove(pwm) self.clear_channel(pin) - GPIO.setup(pin, GPIO.OUT) - pwm_instance = GPIO.PWM(pin, self.to_int( - gpio_out_pwm['pwm_frequency'])) - pwm_instance.start(0) - self.pwm_intances.append({pin: pwm_instance}) + try: + GPIO.setup(pin, GPIO.OUT) + pwm_instance = GPIO.PWM(pin, self.to_int( + gpio_out_pwm['pwm_frequency'])) + pwm_instance.start(0) + self.pwm_intances.append({pin: pwm_instance}) + except Exception as e: + self._logger.error(e.message) + self._logger.error(e.args) + self._logger.error(e) + for gpio_out_neopixel in list(filter(lambda item: item['output_type'] == 'neopixel_direct', self.rpi_outputs)): pin = self.to_int(gpio_out_neopixel['gpio_pin']) self.clear_channel(pin) -- 2.39.5 From 32237f892143add377a31a72c9850cde6f92e803 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 12:37:55 +0000 Subject: [PATCH 24/52] try-except for creating pwm instances --- octoprint_enclosure/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 39c81cd..15ca72b 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -916,7 +916,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, self.log_error(ex) def clear_channel(self, channel): - self._logging.debug("Clearing channel: %s", channel) + self._logger.debug("Clearing channel: %s", channel) try: GPIO.cleanup(self.to_int(channel)) except Exception as ex: @@ -946,6 +946,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, self._logger.info("Setting GPIO pin %s as PWM", pin) for pwm in (pwm_dict for pwm_dict in self.pwm_intances if pin in pwm_dict): + pwm.stop() self.pwm_intances.remove(pwm) self.clear_channel(pin) try: -- 2.39.5 From e8b34b4b7980fc6645c72499d70c8e6dc9eb7280 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 12:42:56 +0000 Subject: [PATCH 25/52] try-except for creating pwm instances --- octoprint_enclosure/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 15ca72b..2f715da 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -946,7 +946,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, self._logger.info("Setting GPIO pin %s as PWM", pin) for pwm in (pwm_dict for pwm_dict in self.pwm_intances if pin in pwm_dict): - pwm.stop() + pwm[pin].stop() self.pwm_intances.remove(pwm) self.clear_channel(pin) try: -- 2.39.5 From cab88a873a23344ccd1f472f070a0dc2eb10d10a Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 12:55:47 +0000 Subject: [PATCH 26/52] try-except for creating pwm instances --- octoprint_enclosure/__init__.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 2f715da..8ac0c2c 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -1221,13 +1221,16 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, if gpio in pwm: pwm_object = pwm[gpio] old_pwm_value = pwm['duty_cycle'] if 'duty_cycle' in pwm else -1 - if not self.to_int(old_pwm_value) == self.to_int(pwm_value): - pwm['duty_cycle'] = pwm_value - self._logger.debug("Changing duty cycle: %s", pwm_value) - self._logger.debug("PWM Object is: %s", pwm_object) - pwm_object.ChangeDutyCycle(pwm_value) - self._logger.debug( - "Writing PWM on gpio: %s value %s", gpio, pwm_value) + + + pwm['duty_cycle'] = pwm_value + self._logger.debug("Changing duty cycle: %s", pwm_value) + self._logger.debug("PWM Object is: %s", pwm_object) + pwm_object.ChangeDutyCycle(pwm_value) + self._logger.debug( + "Writing PWM on gpio: %s value %s", gpio, pwm_value) + + self.update_ui() if queue_id is not None: self.stop_queue_item(queue_id) -- 2.39.5 From 18eaf78c9c300c3ff30d4ab12978554e95d11093 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 13:21:35 +0000 Subject: [PATCH 27/52] use start instead of ChangeDutyCycle --- octoprint_enclosure/__init__.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 8ac0c2c..97b6244 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -1226,11 +1226,10 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, pwm['duty_cycle'] = pwm_value self._logger.debug("Changing duty cycle: %s", pwm_value) self._logger.debug("PWM Object is: %s", pwm_object) - pwm_object.ChangeDutyCycle(pwm_value) + pwm_object.start(pwm_value) self._logger.debug( "Writing PWM on gpio: %s value %s", gpio, pwm_value) - self.update_ui() if queue_id is not None: self.stop_queue_item(queue_id) -- 2.39.5 From 81f648725ce87e9e874096d741ac789de6dc4038 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 14:02:17 +0000 Subject: [PATCH 28/52] Spelling --- octoprint_enclosure/__init__.py | 765 ++++++++++++-------------------- 1 file changed, 294 insertions(+), 471 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 97b6244..045a203 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -20,18 +20,15 @@ import threading import json -class EnclosurePlugin(octoprint.plugin.StartupPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.BlueprintPlugin, +class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.SettingsPlugin, + octoprint.plugin.AssetPlugin, octoprint.plugin.BlueprintPlugin, octoprint.plugin.EventHandlerPlugin): rpi_outputs = [] rpi_inputs = [] waiting_temperature = [] rpi_outputs_not_changed = [] notifications = [] - pwm_intances = [] + pwm_instances = [] event_queue = [] temp_hum_control_status = [] temperature_sensor_data = [] @@ -46,8 +43,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, Function to start timer that checks enclosure temperature """ - self._check_temp_timer = RepeatedTimer( - 10, self.check_enclosure_temp, None, None, True) + self._check_temp_timer = RepeatedTimer(10, self.check_enclosure_temp, None, None, True) self._check_temp_timer.start() @staticmethod @@ -85,8 +81,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, @staticmethod def create_date(value): - temp_string = datetime.now().strftime( - '%m/%d/%Y') + " " + value + temp_string = datetime.now().strftime('%m/%d/%Y') + " " + value return datetime.strptime(temp_string, '%m/%d/%Y %H:%M') @staticmethod @@ -107,7 +102,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, # ~~ StartupPlugin mixin def on_after_startup(self): - self.pwm_intances = [] + self.pwm_instances = [] self.event_queue = [] self.rpi_outputs_not_changed = [] self.rpi_outputs = self._settings.get(["rpi_outputs"]) @@ -126,15 +121,13 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, return 6 def on_settings_migrate(self, target, current=None): - self._logger.warn( - "######### current settings version %s target settings version %s #########", current, target) + self._logger.warn("######### current settings version %s target settings version %s #########", current, target) self._logger.info("######### Current settings #########") self._logger.info("rpi_outputs: %s", self.rpi_outputs) self._logger.info("rpi_inputs: %s", self.rpi_inputs) self._logger.info("######### End Current Settings #########") if current >= 4 and target == 6: - self._logger.warn( - "######### migrating settings to v6 #########") + self._logger.warn("######### migrating settings to v6 #########") old_outputs = self._settings.get(["rpi_outputs"]) for rpi_output in old_outputs: if 'shutdown_on_failed' not in rpi_output: @@ -151,8 +144,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, # ~~ Blueprintplugin mixin @octoprint.plugin.BlueprintPlugin.route("/setEnclosureTempHum", methods=["GET"]) def set_enclosure_temp_humidity(self): - set_value = self.to_float( - flask.request.values["set_temperature"]) + set_value = self.to_float(flask.request.values["set_temperature"]) index_id = self.to_int(flask.request.values["index_id"]) for temp_hum_control in [item for item in self.rpi_outputs if item['index_id'] == index_id]: @@ -177,8 +169,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, for rpi_output in self.rpi_outputs: if rpi_output['output_type'] == 'regular': pin = self.to_int(rpi_output['gpio_pin']) - val = GPIO.input(pin) if not rpi_output['active_low'] else ( - not GPIO.input(pin)) + val = GPIO.input(pin) if not rpi_output['active_low'] else (not GPIO.input(pin)) index = self.to_int(rpi_output['index_id']) gpio_status.append(dict(index_id=index, status=val)) return flask.Response(json.dumps(gpio_status), mimetype='application/json') @@ -197,8 +188,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, def send_shell_command(self): output_index = self.to_int(flask.request.values["index_id"]) - rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int( - r_out['index_id']) == output_index].pop() + rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == output_index].pop() command = rpi_output['shell_script'] self.shell_command(command) @@ -216,8 +206,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, for output in self.rpi_outputs: if self.to_int(index) == self.to_int(output['index_id']): output['auto_startup'] = value - self._logger.info( - "Setting auto startup for output %s to : %s", index, value) + self._logger.info("Setting auto startup for output %s to : %s", index, value) self._settings.set(["rpi_outputs"], self.rpi_outputs) return flask.jsonify(success=True) @@ -234,8 +223,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, for output in self.rpi_outputs: if self.to_int(index) == self.to_int(output['index_id']): output['auto_shutdown'] = value - self._logger.info( - "Setting auto shutdown for output %s to : %s", index, value) + self._logger.info("Setting auto shutdown for output %s to : %s", index, value) self._settings.set(["rpi_outputs"], self.rpi_outputs) return flask.jsonify(success=True) @@ -246,8 +234,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, for sensor in self.rpi_inputs: if self.to_int(index) == self.to_int(sensor['index_id']): sensor['filament_sensor_enabled'] = value - self._logger.info( - "Setting filament sensor for input %s to : %s", index, value) + self._logger.info("Setting filament sensor for input %s to : %s", index, value) self._settings.set(["rpi_inputs"], self.rpi_inputs) return flask.jsonify(success=True) @@ -265,14 +252,13 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, @octoprint.plugin.BlueprintPlugin.route("/sendGcodeCommand", methods=["GET"]) def requested_gcode_command(self): gpio_index = self.to_int(flask.request.values["index_id"]) - rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int( - r_out['index_id']) == gpio_index].pop() + rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == gpio_index].pop() self.send_gcode_command(rpi_output['gcode']) return flask.jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/setNeopixel", methods=["GET"]) def set_neopixel(self): - """ set_neopixel method get request from octoprint and send the comand to arduino or neopixel""" + """ set_neopixel method get request from octoprint and send the command to arduino or neopixel""" gpio_index = self.to_int(flask.request.values["index_id"]) red = flask.request.values["red"] green = flask.request.values["green"] @@ -285,15 +271,14 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, neopixel_dirrect = rpi_output['output_type'] == 'neopixel_direct' - self.send_neopixel_command( - self.to_int(rpi_output['gpio_pin']), - led_count, led_brightness, red, green, blue, address, neopixel_dirrect, gpio_index) + self.send_neopixel_command(self.to_int(rpi_output['gpio_pin']), led_count, led_brightness, red, green, + blue, address, neopixel_dirrect, gpio_index) return flask.jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/setLedstripColor", methods=["GET"]) def set_ledstrip_color(self): - """ set_ledstrip_color method get request from octoprint and send the comand to Open-Smart RGB LED Strip""" + """ set_ledstrip_color method get request from octoprint and send the command to Open-Smart RGB LED Strip""" gpio_index = self.to_int(flask.request.values["index_id"]) rgb = flask.request.values["rgb"] for rpi_output in self.rpi_outputs: @@ -302,8 +287,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, return flask.jsonify(success=True) - def send_neopixel_command(self, led_pin, led_count, led_brightness, red, green, blue, address, - neopixel_dirrect, index_id, queue_id=None): + def send_neopixel_command(self, led_pin, led_count, led_brightness, red, green, blue, address, neopixel_dirrect, + index_id, queue_id=None): """Send neopixel command Arguments: @@ -311,27 +296,24 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, ledCount {int} -- number of LEDS ledBrightness {int} -- brightness from 0 to 255 red {int} -- red value from 0 to 255 - green {int} -- gren value from 0 to 255 + green {int} -- green value from 0 to 255 blue {int} -- blue value from 0 to 255 - address {int} -- i2c address from microcontroler + address {int} -- i2c address from microcontroller """ try: for rpi_output in self.rpi_outputs: if self.to_int(index_id) == self.to_int(rpi_output['index_id']): - rpi_output['neopixel_color'] = 'rgb({0!s},{1!s},{2!s})'.format( - red, green, blue) + rpi_output['neopixel_color'] = 'rgb({0!s},{1!s},{2!s})'.format(red, green, blue) if address == '': address = 0 if neopixel_dirrect: - script = os.path.dirname( - os.path.realpath(__file__)) + "/neopixel_direct.py " + script = os.path.dirname(os.path.realpath(__file__)) + "/neopixel_direct.py " else: - script = os.path.dirname( - os.path.realpath(__file__)) + "/neopixel_indirect.py " + script = os.path.dirname(os.path.realpath(__file__)) + "/neopixel_indirect.py " if self._settings.get(["use_sudo"]): sudo_str = "sudo " @@ -349,8 +331,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, if self._settings.get(["debug"]) is True: if queue_id is not None: - self._logger.info("Runing scheduled queue id %s", queue_id) - self._logger.info("Sending neopixel cmd: %s", cmd) + self._logger.debug("running scheduled queue id %s", queue_id) + self._logger.debug("Sending neopixel cmd: %s", cmd) Popen(cmd, shell=True) if queue_id is not None: self.stop_queue_item(queue_id) @@ -363,11 +345,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, for sensor in list(filter(lambda item: item['input_type'] == 'temperature_sensor', self.rpi_inputs)): temp, hum = self.get_sensor_data(sensor) if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: - self._logger.info( - "Sensor %s Temperature: %s humidity %s", sensor['label'], temp, hum) + self._logger.debug("Sensor %s Temperature: %s humidity %s", sensor['label'], temp, hum) if temp is not None and hum is not None: - sensor_data.append( - dict(index_id=sensor['index_id'], temperature=temp, humidity=hum)) + sensor_data.append(dict(index_id=sensor['index_id'], temperature=temp, humidity=hum)) self.temperature_sensor_data = sensor_data self.handle_temp_hum_control() self.handle_temperature_events() @@ -385,8 +365,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, if first_run: current_value = False else: - current_value = (not GPIO.input( - gpio_pin)) if output['active_low'] else GPIO.input(gpio_pin) + current_value = (not GPIO.input(gpio_pin)) if output['active_low'] else GPIO.input(gpio_pin) if current_value: time_delay = self.to_int(output['toggle_timer_off']) @@ -395,9 +374,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, if not self.print_complete: self.write_gpio(gpio_pin, not current_value) - thread = threading.Timer(time_delay, - self.toggle_output, - args=[index_id]) + thread = threading.Timer(time_delay, self.toggle_output, args=[index_id]) thread.start() else: off_value = True if output['active_low'] else False @@ -406,32 +383,27 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, return if output['output_type'] == 'pwm': - for pwm in self.pwm_intances: + for pwm in self.pwm_instances: if gpio_pin in pwm: if first_run: current_pwm_value = 0 else: if 'duty_cycle' in pwm: current_pwm_value = pwm['duty_cycle'] - current_pwm_value = self.to_int( - current_pwm_value) + current_pwm_value = self.to_int(current_pwm_value) else: current_pwm_value = 0 if not current_pwm_value == 0: - time_delay = self.to_int( - output['toggle_timer_off']) + time_delay = self.to_int(output['toggle_timer_off']) write_value = 0 else: time_delay = self.to_int(output['toggle_timer_on']) - write_value = self.to_int( - output['default_duty_cycle']) + write_value = self.to_int(output['default_duty_cycle']) if not self.print_complete: self.write_pwm(gpio_pin, write_value) - thread = threading.Timer(time_delay, - self.toggle_output, - args=[index_id]) + thread = threading.Timer(time_delay, self.toggle_output, args=[index_id]) thread.start() else: self.write_pwm(self.to_int(output['gpio_pin']), 0) @@ -445,37 +417,30 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, self.update_ui_inputs() def update_ui_current_temperature(self): - self._plugin_manager.send_plugin_message( - self._identifier, dict(sensor_data=self.temperature_sensor_data)) + self._plugin_manager.send_plugin_message(self._identifier, dict(sensor_data=self.temperature_sensor_data)) def update_ui_set_temperature(self): result = [] - for temp_crt_output in list(filter(lambda item: - item['output_type'] == 'temp_hum_control', - self.rpi_outputs)): - set_temperature = self.to_float( - temp_crt_output['temp_ctr_set_value']) - result.append( - dict(index_id=temp_crt_output['index_id'], set_temperature=set_temperature)) + for temp_crt_output in list(filter(lambda item: item['output_type'] == 'temp_hum_control', self.rpi_outputs)): + set_temperature = self.to_float(temp_crt_output['temp_ctr_set_value']) + result.append(dict(index_id=temp_crt_output['index_id'], set_temperature=set_temperature)) result.append(set_temperature) - self._plugin_manager.send_plugin_message( - self._identifier, dict(set_temperature=result)) + self._plugin_manager.send_plugin_message(self._identifier, dict(set_temperature=result)) def stop_queue_item(self, queue_id): old_list = self.event_queue if self._settings.get(["debug"]) is True: - self._logger.info("Stoping queue id %s...", queue_id) + self._logger.debug("Stopping queue id %s...", queue_id) for task in self.event_queue: if self._settings.get(["debug"]) is True: - self._logger.info("Queue id found...") + self._logger.debug("Queue id found...") if task['queue_id'] == queue_id: task['thread'].cancel() self.event_queue.remove(task) if self._settings.get(["debug"]) is True: - self._logger.info( - "Queue id stoped and removed from list...") - self._logger.info("Old queue list: %s", old_list) - self._logger.info("New queue list: %s", self.event_queue) + self._logger.debug("Queue id stopped and removed from list...") + self._logger.debug("Old queue list: %s", old_list) + self._logger.debug("New queue list: %s", self.event_queue) def update_ui_outputs(self): try: @@ -490,13 +455,11 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, shutdown = output['auto_shutdown'] if output['output_type'] == 'regular': - val = GPIO.input(pin) if not output['active_low'] else ( - not GPIO.input(pin)) + val = GPIO.input(pin) if not output['active_low'] else (not GPIO.input(pin)) regular_status.append( dict(index_id=index, status=val, auto_startup=startup, auto_shutdown=shutdown)) if output['output_type'] == 'temp_hum_control': - val = GPIO.input(pin) if not output['active_low'] else ( - not GPIO.input(pin)) + val = GPIO.input(pin) if not output['active_low'] else (not GPIO.input(pin)) temp_control_status.append( dict(index_id=index, status=val, auto_startup=startup, auto_shutdown=shutdown)) if output['output_type'] == 'neopixel_indirect' or output['output_type'] == 'neopixel_direct': @@ -504,7 +467,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, neopixel_status.append( dict(index_id=index, color=val, auto_startup=startup, auto_shutdown=shutdown)) if output['output_type'] == 'pwm': - for pwm in self.pwm_intances: + for pwm in self.pwm_instances: if pin in pwm: if 'duty_cycle' in pwm: pwm_val = pwm['duty_cycle'] @@ -513,10 +476,10 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, val = 0 pwm_status.append( dict(index_id=index, pwm_value=val, auto_startup=startup, auto_shutdown=shutdown)) - self._plugin_manager.send_plugin_message(self._identifier, dict(rpi_output_regular=regular_status, - rpi_output_pwm=pwm_status, - rpi_output_neopixel=neopixel_status, - rpi_output_temp_hum_ctrl=temp_control_status)) + self._plugin_manager.send_plugin_message(self._identifier, + dict(rpi_output_regular=regular_status, rpi_output_pwm=pwm_status, + rpi_output_neopixel=neopixel_status, + rpi_output_temp_hum_ctrl=temp_control_status)) except Exception as ex: self.log_error(ex) @@ -524,13 +487,12 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, try: sensor_status = [] for sensor in self.rpi_inputs: - if sensor['input_type'] == 'gpio' and sensor['action_type'] == 'printer_control' and sensor['printer_action'] == 'filament': + if sensor['input_type'] == 'gpio' and sensor['action_type'] == 'printer_control' and sensor[ + 'printer_action'] == 'filament': index = self.to_int(sensor['index_id']) value = sensor['filament_sensor_enabled'] - sensor_status.append( - dict(index_id=index, filament_sensor_enabled=value)) - self._plugin_manager.send_plugin_message( - self._identifier, dict(filament_sensor_status=sensor_status)) + sensor_status.append(dict(index_id=index, filament_sensor_enabled=value)) + self._plugin_manager.send_plugin_message(self._identifier, dict(filament_sensor_status=sensor_status)) except Exception as ex: self.log_error(ex) @@ -540,32 +502,27 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, temp, hum = self.read_dummy_temp() else: if sensor['temp_sensor_type'] in ["11", "22", "2302"]: - temp, hum = self.read_dht_temp( - sensor['temp_sensor_type'], sensor['gpio_pin']) + temp, hum = self.read_dht_temp(sensor['temp_sensor_type'], sensor['gpio_pin']) elif sensor['temp_sensor_type'] == "18b20": temp = self.read_18b20_temp(sensor['ds18b20_serial']) hum = 0 elif sensor['temp_sensor_type'] == "bme280": - temp, hum = self.read_bme280_temp( - sensor['temp_sensor_address']) + temp, hum = self.read_bme280_temp(sensor['temp_sensor_address']) elif sensor['temp_sensor_type'] == "si7021": - temp, hum = self.read_si7021_temp( - sensor['temp_sensor_address']) + temp, hum = self.read_si7021_temp(sensor['temp_sensor_address']) elif sensor['temp_sensor_type'] == "tmp102": - temp = self.read_tmp102_temp( - sensor['temp_sensor_address']) + temp = self.read_tmp102_temp(sensor['temp_sensor_address']) hum = 0 elif sensor['temp_sensor_type'] == "max31855": - temp = self.read_max31855_temp( - sensor['temp_sensor_address']) + temp = self.read_max31855_temp(sensor['temp_sensor_address']) hum = 0 else: self._logger.info("temp_sensor_type no match") temp = None hum = None if temp != -1 and hum != -1: - temp = round(self.to_float( - temp), 1) if not sensor['use_fahrenheit'] else round(self.to_float(temp) * 1.8 + 32, 1) + temp = round(self.to_float(temp), 1) if not sensor['use_fahrenheit'] else round( + self.to_float(temp) * 1.8 + 32, 1) hum = round(self.to_float(hum), 1) return temp, hum return None, None @@ -574,23 +531,22 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, def handle_temperature_events(self): for temperature_alarm in [item for item in self.rpi_outputs if item['output_type'] == 'temperature_alarm']: - set_temperature = self.to_float( - temperature_alarm['alarm_set_temp']) + set_temperature = self.to_float(temperature_alarm['alarm_set_temp']) if int(set_temperature) is 0: continue - linked_data = [item for item in self.temperature_sensor_data if item['index_id'] == - temperature_alarm['linked_temp_sensor']].pop() + linked_data = [item for item in self.temperature_sensor_data if + item['index_id'] == temperature_alarm['linked_temp_sensor']].pop() sensor_temperature = self.to_float(linked_data['temperature']) if set_temperature < sensor_temperature: for rpi_controlled_output in self.rpi_outputs: - if self.to_int(temperature_alarm['controlled_io']) == self.to_int(rpi_controlled_output['index_id']): + if self.to_int(temperature_alarm['controlled_io']) == self.to_int( + rpi_controlled_output['index_id']): val = GPIO.LOW if rpi_controlled_output['active_low'] else GPIO.HIGH - self.write_gpio(self.to_int( - rpi_controlled_output['gpio_pin']), val) + self.write_gpio(self.to_int(rpi_controlled_output['gpio_pin']), val) for notification in self.notifications: if notification['temperatureAction']: - msg = ("Temperature action: enclosure temperature exceed " + - temperature_alarm['alarm_set_temp']) + msg = ("Temperature action: enclosure temperature exceed " + temperature_alarm[ + 'alarm_set_temp']) self.send_notification(msg) def read_dummy_temp(self): @@ -606,67 +562,64 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, def read_dht_temp(self, sensor, pin): try: - script = os.path.dirname( - os.path.realpath(__file__)) + "/getDHTTemp.py " + script = os.path.dirname(os.path.realpath(__file__)) + "/getDHTTemp.py " if self._settings.get(["use_sudo"]): sudo_str = "sudo " else: sudo_str = "" cmd = sudo_str + "python " + script + str(sensor) + " " + str(pin) if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: - self._logger.info("Temperature dht cmd: %s", cmd) + self._logger.debug("Temperature dht cmd: %s", cmd) stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read() if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: - self._logger.info("Dht result: %s", stdout) + self._logger.debug("Dht result: %s", stdout) temp, hum = stdout.split("|") return (self.to_float(temp.strip()), self.to_float(hum.strip())) except Exception as ex: self._logger.info( - "Failed to excecute python scripts, try disabling use SUDO on advanced section of the plugin.") + "Failed to execute python scripts, try disabling use SUDO on advanced section of the plugin.") self.log_error(ex) return (0, 0) def read_bme280_temp(self, address): try: - script = os.path.dirname( - os.path.realpath(__file__)) + "/BME280.py " + script = os.path.dirname(os.path.realpath(__file__)) + "/BME280.py " if self._settings.get(["use_sudo"]): sudo_str = "sudo " else: sudo_str = "" cmd = sudo_str + "python " + script + str(address) if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: - self._logger.info("Temperature BME280 cmd: %s", cmd) + self._logger.debug("Temperature BME280 cmd: %s", cmd) stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read() if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: - self._logger.info("BME280 result: %s", stdout) + self._logger.debug("BME280 result: %s", stdout) temp, hum = stdout.split("|") return (self.to_float(temp.strip()), self.to_float(hum.strip())) except Exception as ex: self._logger.info( - "Failed to excecute python scripts, try disabling use SUDO on advanced section of the plugin.") + "Failed to execute python scripts, try disabling use SUDO on advanced section of the plugin.") self.log_error(ex) return (0, 0) def read_si7021_temp(self, address): try: - script = os.path.dirname( - os.path.realpath(__file__)) + "/SI7021.py " + script = os.path.dirname(os.path.realpath(__file__)) + "/SI7021.py " if self._settings.get(["use_sudo"]): sudo_str = "sudo " else: sudo_str = "" cmd = sudo_str + "python " + script + str(address) if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: - self._logger.info("Temperature SI7021 cmd: %s", cmd) + self._logger.debug("Temperature SI7021 cmd: %s", cmd) stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read() if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: - self._logger.info("SI7021 result: %s", stdout) + self._logger.debug("SI7021 result: %s", stdout) temp, hum = stdout.split("|") return (self.to_float(temp.strip()), self.to_float(hum.strip())) except Exception as ex: self._logger.info( - "Failed to excecute python scripts, try disabling use SUDO on advanced section of the plugin.") + "Failed to execute python scripts, try disabling use SUDO on advanced section of the plugin.") self.log_error(ex) return (0, 0) @@ -683,7 +636,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, temp_string = lines[1][equals_pos + 2:] temp_c = float(temp_string) / 1000. if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: - self._logger.info("DS18B20 result: %s", temp_c) + self._logger.debug("DS18B20 result: %s", temp_c) return '{0:0.1f}'.format(temp_c) return 0 @@ -701,46 +654,43 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, script = os.path.dirname(os.path.realpath(__file__)) + "/tmp102.py" args = ["python", script, str(address)] if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: - self._logger.info("Temperature TMP102 cmd: %s", " ".join(args)) + self._logger.debug("Temperature TMP102 cmd: %s", " ".join(args)) proc = Popen(args, stdout=PIPE) stdout, _ = proc.communicate() if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: - self._logger.info("TMP102 result: %s", stdout) + self._logger.debug("TMP102 result: %s", stdout) return self.to_float(stdout.strip()) except Exception as ex: - self._logger.info( - "Failed to excecute python scripts, try disabling use SUDO on advanced section.") + self._logger.info("Failed to execute python scripts, try disabling use SUDO on advanced section.") self.log_error(ex) return 0 - + def read_max31855_temp(self, address): try: script = os.path.dirname(os.path.realpath(__file__)) + "/max31855.py" args = ["python", script, str(address)] if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: - self._logger.info("Temperature MAX31855 cmd: %s", " ".join(args)) + self._logger.debug("Temperature MAX31855 cmd: %s", " ".join(args)) proc = Popen(args, stdout=PIPE) stdout, _ = proc.communicate() if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: - self._logger.info("MAX31855 result: %s", stdout) + self._logger.debug("MAX31855 result: %s", stdout) return self.to_float(stdout.strip()) except Exception as ex: - self._logger.info( - "Failed to excecute python scripts, try disabling use SUDO on advanced section.") + self._logger.info("Failed to execute python scripts, try disabling use SUDO on advanced section.") self.log_error(ex) return 0 - + def handle_pwm_linked_temperature(self): try: - for pwm_output in list(filter(lambda item: item['output_type'] == 'pwm' and item['pwm_temperature_linked'], self.rpi_outputs)): + for pwm_output in list(filter(lambda item: item['output_type'] == 'pwm' and item['pwm_temperature_linked'], + self.rpi_outputs)): gpio_pin = self.to_int(pwm_output['gpio_pin']) - if True==True: #if self._printer.is_printing(): + if self._printer.is_printing(): index_id = self.to_int(pwm_output['index_id']) linked_id = self.to_int(pwm_output['linked_temp_sensor']) - linked_data = self.get_linked_temp_sensor_data( - linked_id) - current_temp = self.to_float( - linked_data['temperature']) + linked_data = self.get_linked_temp_sensor_data(linked_id) + current_temp = self.to_float(linked_data['temperature']) duty_a = self.to_float(pwm_output['duty_a']) duty_b = self.to_float(pwm_output['duty_b']) @@ -748,57 +698,48 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, temp_b = self.to_float(pwm_output['temperature_b']) try: - calculated_duty = ((current_temp - temp_a) * - (duty_b - duty_a) / (temp_b - temp_a)) + duty_a + calculated_duty = ((current_temp - temp_a) * (duty_b - duty_a) / (temp_b - temp_a)) + duty_a except: calculated_duty = 0 - - self._logger.info( - "Calculated duty for PWM %s is %s", index_id, calculated_duty) + if self._settings.get(["debug"]) is True: + self._logger.debug("Calculated duty for PWM %s is %s", index_id, calculated_duty) elif self.print_complete: calculated_duty = self.to_int(pwm_output['duty_cycle']) else: calculated_duty = 0 - self.write_pwm(gpio_pin, self.constrain( - calculated_duty, 0, 100)) + self.write_pwm(gpio_pin, self.constrain(calculated_duty, 0, 100)) except Exception as ex: self.log_error(ex) def get_linked_temp_sensor_data(self, linked_id): try: - linked_data = [ - data for data in self.temperature_sensor_data if data['index_id'] == linked_id].pop() + linked_data = [data for data in self.temperature_sensor_data if data['index_id'] == linked_id].pop() return linked_data except: - self._logger.warn( - "No linked temperature sensor found for %s", linked_id) + self._logger.warn("No linked temperature sensor found for %s", linked_id) return None def handle_temp_hum_control(self): try: - for temp_hum_control in list(filter(lambda item: item['output_type'] == 'temp_hum_control', self.rpi_outputs)): + for temp_hum_control in list( + filter(lambda item: item['output_type'] == 'temp_hum_control', self.rpi_outputs)): - set_temperature = self.to_float( - temp_hum_control['temp_ctr_set_value']) - temp_deadband = self.to_float( - temp_hum_control['temp_ctr_deadband']) - max_temp = self.to_float( - temp_hum_control['temp_ctr_max_temp']) + set_temperature = self.to_float(temp_hum_control['temp_ctr_set_value']) + temp_deadband = self.to_float(temp_hum_control['temp_ctr_deadband']) + max_temp = self.to_float(temp_hum_control['temp_ctr_max_temp']) linked_id = temp_hum_control['linked_temp_sensor'] - previous_status = list(filter( - lambda item: item['index_id'] == temp_hum_control['index_id'], + previous_status = list(filter(lambda item: item['index_id'] == temp_hum_control['index_id'], self.temp_hum_control_status)).pop()['status'] if set_temperature == 0: current_status = False else: - linked_data = self.get_linked_temp_sensor_data( - linked_id) + linked_data = self.get_linked_temp_sensor_data(linked_id) control_type = str(temp_hum_control['temp_ctr_type']) @@ -806,8 +747,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, current_value = self.to_float(linked_data['humidity']) temp_deadband = 0 else: - current_value = self.to_float( - linked_data['temperature']) + current_value = self.to_float(linked_data['temperature']) if control_type == 'cooler' or control_type == 'dehumidifier': if current_value <= set_temperature and current_value >= (set_temperature - temp_deadband): @@ -826,18 +766,16 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, if control_type == 'heater' and max_temp > 0.0 and max_temp < current_value: if self._settings.get(["debug"]) is True: - self._logger.info( - "Maximun temperature reached for temperature control %s", temp_hum_control['index_id']) + self._logger.debug("Maximum temperature reached for temperature control %s", + temp_hum_control['index_id']) temp_hum_control['temp_ctr_set_value'] = 0 current_status = False if current_status != previous_status: if current_status: - self._logger.info( - "Turning gpio to control temperature on.") + self._logger.info("Turning gpio to control temperature on.") val = False if temp_hum_control['active_low'] else True - self.write_gpio(self.to_int( - temp_hum_control['gpio_pin']), val) + self.write_gpio(self.to_int(temp_hum_control['gpio_pin']), val) else: index_id = temp_hum_control['index_id'] if index_id in self.waiting_temperature: @@ -846,11 +784,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, if not self.waiting_temperature and self._printer.is_paused(): self._printer.resume_print() - self._logger.info( - "Turning gpio to control temperature off.") + self._logger.info("Turning gpio to control temperature off.") val = True if temp_hum_control['active_low'] else False - self.write_gpio(self.to_int( - temp_hum_control['gpio_pin']), val) + self.write_gpio(self.to_int(temp_hum_control['gpio_pin']), val) for control_status in self.temp_hum_control_status: if control_status['index_id'] == temp_hum_control['index_id']: control_status['status'] = current_status @@ -859,22 +795,19 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, def log_error(self, ex): template = "An exception of type {0} occurred on {1}. Arguments:\n{2!r}" - message = template.format( - type(ex).__name__, inspect.currentframe().f_code.co_name, ex.args) + message = template.format(type(ex).__name__, inspect.currentframe().f_code.co_name, ex.args) self._logger.warn(message) def setup_gpio(self): try: current_mode = GPIO.getmode() - set_mode = GPIO.BOARD if self._settings.get( - ["use_board_pin_number"]) else GPIO.BCM + set_mode = GPIO.BOARD if self._settings.get(["use_board_pin_number"]) else GPIO.BCM if current_mode is None: - outputs = list(filter(lambda item: item['output_type'] == 'regular' or - item['output_type'] == 'pwm' or - item['output_type'] == 'temp_hum_control' or - item['output_type'] == 'neopixel_direct', self.rpi_outputs)) - inputs = list(filter( - lambda item: item['input_type'] == 'gpio', self.rpi_inputs)) + outputs = list(filter( + lambda item: item['output_type'] == 'regular' or item['output_type'] == 'pwm' or item[ + 'output_type'] == 'temp_hum_control' or item['output_type'] == 'neopixel_direct', + self.rpi_outputs)) + inputs = list(filter(lambda item: item['input_type'] == 'gpio', self.rpi_inputs)) gpios = outputs + inputs if gpios: GPIO.setmode(set_mode) @@ -883,13 +816,11 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, elif current_mode != set_mode: GPIO.setmode(current_mode) tempstr = "BOARD" if current_mode == GPIO.BOARD else "BCM" - self._settings.set(["use_board_pin_number"], - True if current_mode == GPIO.BOARD else False) - warn_msg = "GPIO mode was configured before, GPIO mode will be forced to use: " + \ - tempstr + " as pin numbers. Please update GPIO accordingly!" + self._settings.set(["use_board_pin_number"], True if current_mode == GPIO.BOARD else False) + warn_msg = "GPIO mode was configured before, GPIO mode will be forced to use: " + tempstr + " as pin numbers. Please update GPIO accordingly!" self._logger.info(warn_msg) - self._plugin_manager.send_plugin_message( - self._identifier, dict(is_msg=True, msg=warn_msg, msg_type="error")) + self._plugin_manager.send_plugin_message(self._identifier, + dict(is_msg=True, msg=warn_msg, msg_type="error")) GPIO.setwarnings(False) except Exception as ex: self.log_error(ex) @@ -897,18 +828,17 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, def clear_gpio(self): try: - for gpio_out in list(filter(lambda item: item['output_type'] == 'regular' or - item['output_type'] == 'pwm' or - item['output_type'] == 'temp_hum_control' or - item['output_type'] == 'neopixel_direct', self.rpi_outputs)): + for gpio_out in list(filter( + lambda item: item['output_type'] == 'regular' or item['output_type'] == 'pwm' or item[ + 'output_type'] == 'temp_hum_control' or item['output_type'] == 'neopixel_direct', + self.rpi_outputs)): gpio_pin = self.to_int(gpio_out['gpio_pin']) if gpio_pin not in self.rpi_outputs_not_changed: GPIO.cleanup(gpio_pin) for gpio_in in list(filter(lambda item: item['input_type'] == 'gpio', self.rpi_inputs)): try: - GPIO.remove_event_detect( - self.to_int(gpio_in['gpio_pin'])) + GPIO.remove_event_detect(self.to_int(gpio_in['gpio_pin'])) except: pass GPIO.cleanup(self.to_int(gpio_in['gpio_pin'])) @@ -916,7 +846,6 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, self.log_error(ex) def clear_channel(self, channel): - self._logger.debug("Clearing channel: %s", channel) try: GPIO.cleanup(self.to_int(channel)) except Exception as ex: @@ -924,43 +853,33 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, def generate_temp_hum_control_status(self): status = [] - for temp_hum_control in list(filter(lambda item: - item['output_type'] == 'temp_hum_control', self.rpi_outputs)): - status.append( - dict(index_id=temp_hum_control['index_id'], status=False)) + for temp_hum_control in list(filter(lambda item: item['output_type'] == 'temp_hum_control', self.rpi_outputs)): + status.append(dict(index_id=temp_hum_control['index_id'], status=False)) self.temp_hum_control_status = status def configure_gpio(self): try: - for gpio_out in list(filter(lambda item: item['output_type'] == 'regular' or - item['output_type'] == 'temp_hum_control', self.rpi_outputs)): + for gpio_out in list( + filter(lambda item: item['output_type'] == 'regular' or item['output_type'] == 'temp_hum_control', + self.rpi_outputs)): initial_value = GPIO.HIGH if gpio_out['active_low'] else GPIO.LOW pin = self.to_int(gpio_out['gpio_pin']) if pin not in self.rpi_outputs_not_changed: - self._logger.info( - "Setting GPIO pin %s as OUTPUT with initial value: %s", pin, initial_value) + self._logger.info("Setting GPIO pin %s as OUTPUT with initial value: %s", pin, initial_value) GPIO.setup(pin, GPIO.OUT, initial=initial_value) for gpio_out_pwm in list(filter(lambda item: item['output_type'] == 'pwm', self.rpi_outputs)): pin = self.to_int(gpio_out_pwm['gpio_pin']) self._logger.info("Setting GPIO pin %s as PWM", pin) - - for pwm in (pwm_dict for pwm_dict in self.pwm_intances if pin in pwm_dict): - pwm[pin].stop() - self.pwm_intances.remove(pwm) + for pwm in (pwm_dict for pwm_dict in self.pwm_instances if pin in pwm_dict): + self.pwm_instances.remove(pwm) self.clear_channel(pin) - try: - GPIO.setup(pin, GPIO.OUT) - pwm_instance = GPIO.PWM(pin, self.to_int( - gpio_out_pwm['pwm_frequency'])) - pwm_instance.start(0) - self.pwm_intances.append({pin: pwm_instance}) - except Exception as e: - self._logger.error(e.message) - self._logger.error(e.args) - self._logger.error(e) - - for gpio_out_neopixel in list(filter(lambda item: item['output_type'] == 'neopixel_direct', self.rpi_outputs)): + GPIO.setup(pin, GPIO.OUT) + pwm_instance = GPIO.PWM(pin, self.to_int(gpio_out_pwm['pwm_frequency'])) + pwm_instance.start(0) + self.pwm_instances.append({pin: pwm_instance}) + for gpio_out_neopixel in list( + filter(lambda item: item['output_type'] == 'neopixel_direct', self.rpi_outputs)): pin = self.to_int(gpio_out_neopixel['gpio_pin']) self.clear_channel(pin) @@ -980,33 +899,27 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, edge = GPIO.BOTH if rpi_input['action_type'] == 'output_control': - self._logger.info( - "Adding GPIO event detect on pin %s with edge: %s", gpio_pin, edge) - GPIO.add_event_detect( - gpio_pin, edge, callback=self.handle_gpio_control, bouncetime=200) + self._logger.info("Adding GPIO event detect on pin %s with edge: %s", gpio_pin, edge) + GPIO.add_event_detect(gpio_pin, edge, callback=self.handle_gpio_control, bouncetime=200) if (rpi_input['action_type'] == 'printer_control' and rpi_input['printer_action'] != 'filament'): - GPIO.add_event_detect( - gpio_pin, edge, callback=self.handle_printer_action, bouncetime=200) - self._logger.info( - "Adding PRINTER CONTROL event detect on pin %s with edge: %s", gpio_pin, edge) + GPIO.add_event_detect(gpio_pin, edge, callback=self.handle_printer_action, bouncetime=200) + self._logger.info("Adding PRINTER CONTROL event detect on pin %s with edge: %s", gpio_pin, edge) except Exception as ex: self.log_error(ex) def handle_filamment_detection(self, channel): try: - for filament_sensor in list(filter(lambda item: item['input_type'] == 'gpio' and - item['action_type'] == 'printer_control' and - item['printer_action'] == 'filament' and - self.to_int(item['gpio_pin']) == self.to_int(channel), self.rpi_inputs)): + for filament_sensor in list(filter( + lambda item: item['input_type'] == 'gpio' and item['action_type'] == 'printer_control' and item[ + 'printer_action'] == 'filament' and self.to_int(item['gpio_pin']) == self.to_int(channel), + self.rpi_inputs)): if ((filament_sensor['edge'] == 'fall') ^ (GPIO.input(self.to_int(filament_sensor['gpio_pin']))) and filament_sensor['filament_sensor_enabled']): last_detected_time = list(filter(lambda item: item['index_id'] == filament_sensor['index_id'], self.last_filament_end_detected)).pop()['time'] time_now = time.time() - time_difference = self.to_int( - time_now - last_detected_time) - time_out_value = self.to_int( - filament_sensor['filament_sensor_timeout']) + time_difference = self.to_int(time_now - last_detected_time) + time_out_value = self.to_int(filament_sensor['filament_sensor_timeout']) if time_difference > time_out_value: self._logger.info("Detected end of filament.") for item in self.last_filament_end_detected: @@ -1015,48 +928,43 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, for line in self._settings.get(["filament_sensor_gcode"]).split('\n'): if line: self._printer.commands(line.strip().upper()) - self._logger.info( - "Sending GCODE command: %s", line.strip().upper()) + self._logger.info("Sending GCODE command: %s", line.strip().upper()) time.sleep(0.2) for notification in self.notifications: if notification['filamentChange']: - msg = "Filament change action caused by sensor: " + \ - str(filament_sensor['label']) + msg = "Filament change action caused by sensor: " + str(filament_sensor['label']) self.send_notification(msg) else: - self._logger.info( - "Prevented end of filament detection, filament sensor timeout not elapsed.") + self._logger.info("Prevented end of filament detection, filament sensor timeout not elapsed.") except Exception as ex: self.log_error(ex) def start_filament_detection(self): self.stop_filament_detection() try: - for filament_sensor in list(filter(lambda item: item['input_type'] == 'gpio' and - item['action_type'] == 'printer_control' and - item['printer_action'] == 'filament', self.rpi_inputs)): + for filament_sensor in list(filter( + lambda item: item['input_type'] == 'gpio' and item['action_type'] == 'printer_control' and item[ + 'printer_action'] == 'filament', self.rpi_inputs)): edge = GPIO.RISING if filament_sensor['edge'] == 'rise' else GPIO.FALLING if GPIO.input(self.to_int(filament_sensor['gpio_pin'])) == (edge == GPIO.RISING): self._printer.pause_print() self._logger.info("Started printing with no filament.") else: - self.last_filament_end_detected.append( - dict(index_id=filament_sensor['index_id'], time=0)) - self._logger.info( - "Adding GPIO event detect on pin %s with edge: %s", filament_sensor['gpio_pin'], edge) - GPIO.add_event_detect(self.to_int( - filament_sensor['gpio_pin']), edge, callback=self.handle_filamment_detection, bouncetime=200) + self.last_filament_end_detected.append(dict(index_id=filament_sensor['index_id'], time=0)) + self._logger.info("Adding GPIO event detect on pin %s with edge: %s", filament_sensor['gpio_pin'], + edge) + GPIO.add_event_detect(self.to_int(filament_sensor['gpio_pin']), edge, + callback=self.handle_filamment_detection, bouncetime=200) except Exception as ex: self.log_error(ex) def stop_filament_detection(self): try: self.last_filament_end_detected = [] - for filament_sensor in list(filter(lambda item: item['input_type'] == 'gpio' and - item['action_type'] == 'printer_control' and - item['printer_action'] == 'filament', self.rpi_inputs)): - GPIO.remove_event_detect( - self.to_int(filament_sensor['gpio_pin'])) + for filament_sensor in list(filter( + lambda item: item['input_type'] == 'gpio' and item['action_type'] == 'printer_control' and item[ + 'printer_action'] == 'filament', self.rpi_inputs)): + GPIO.remove_event_detect(self.to_int(filament_sensor['gpio_pin'])) except Exception as ex: self.log_error(ex) @@ -1070,17 +978,17 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, def handle_initial_gpio_control(self): try: - for rpi_input in list(filter(lambda item: item['input_type'] == 'gpio' and - item['action_type'] == 'output_control', self.rpi_inputs)): + for rpi_input in list( + filter(lambda item: item['input_type'] == 'gpio' and item['action_type'] == 'output_control', + self.rpi_inputs)): gpio_pin = self.to_int(rpi_input['gpio_pin']) controlled_io = self.to_int(rpi_input['controlled_io']) if (rpi_input['edge'] == 'fall') ^ GPIO.input(gpio_pin): - rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int( - r_out['index_id']) == controlled_io].pop() + rpi_output = [r_out for r_out in self.rpi_outputs if + self.to_int(r_out['index_id']) == controlled_io].pop() if rpi_output['output_type'] == 'regular': val = GPIO.LOW if rpi_input['controlled_io_set_value'] == 'low' else GPIO.HIGH - self.write_gpio(self.to_int( - rpi_output['gpio_pin']), val) + self.write_gpio(self.to_int(rpi_output['gpio_pin']), val) except Exception as ex: self.log_error(ex) pass @@ -1088,44 +996,43 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, def shell_command(self, command): try: stdout = (Popen(command, shell=True, stdout=PIPE).stdout).read() - self._plugin_manager.send_plugin_message( - self._identifier, dict(is_msg=True, msg=stdout, msg_type="success")) + self._plugin_manager.send_plugin_message(self._identifier, + dict(is_msg=True, msg=stdout, msg_type="success")) except Exception as ex: self.log_error(ex) - self._plugin_manager.send_plugin_message( - self._identifier, dict(is_msg=True, msg="Could not execute shell script", msg_type="error")) + self._plugin_manager.send_plugin_message(self._identifier, + dict(is_msg=True, msg="Could not execute shell script", msg_type="error")) def handle_gpio_control(self, channel): try: if self._settings.get(["debug"]) is True: - self._logger.info( - "GPIO event triggered on channel %s", channel) - for rpi_input in list(filter(lambda item: self.to_int(item['gpio_pin']) == self.to_int(channel), self.rpi_inputs)): + self._logger.debug("GPIO event triggered on channel %s", channel) + for rpi_input in list( + filter(lambda item: self.to_int(item['gpio_pin']) == self.to_int(channel), self.rpi_inputs)): gpio_pin = self.to_int(rpi_input['gpio_pin']) controlled_io = self.to_int(rpi_input['controlled_io']) if (rpi_input['edge'] == 'fall') ^ GPIO.input(gpio_pin): - rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int( - r_out['index_id']) == controlled_io].pop() + rpi_output = [r_out for r_out in self.rpi_outputs if + self.to_int(r_out['index_id']) == controlled_io].pop() if rpi_output['output_type'] == 'regular': if rpi_input['controlled_io_set_value'] == 'toggle': - val = GPIO.LOW if GPIO.input(self.to_int( - rpi_output['gpio_pin'])) == GPIO.HIGH else GPIO.HIGH + val = GPIO.LOW if GPIO.input( + self.to_int(rpi_output['gpio_pin'])) == GPIO.HIGH else GPIO.HIGH else: val = GPIO.LOW if rpi_input['controlled_io_set_value'] == 'low' else GPIO.HIGH - self.write_gpio(self.to_int( - rpi_output['gpio_pin']), val) + self.write_gpio(self.to_int(rpi_output['gpio_pin']), val) for notification in self.notifications: if notification['gpioAction']: - msg = "GPIO control action caused by input " + str(rpi_input['label']) + ". Setting GPIO" + str( + msg = "GPIO control action caused by input " + str( + rpi_input['label']) + ". Setting GPIO" + str( rpi_input['controlled_io']) + " to: " + str(rpi_input['controlled_io_set_value']) self.send_notification(msg) if rpi_output['output_type'] == 'gcode_output': self.send_gcode_command(rpi_output['gcode']) for notification in self.notifications: if notification['gpioAction']: - msg = "GPIO control action caused by input " + \ - str(rpi_input['label']) + \ - ". Sending GCODE command" + msg = "GPIO control action caused by input " + str( + rpi_input['label']) + ". Sending GCODE command" self.send_notification(msg) if rpi_output['output_type'] == 'shell_output': command = rpi_output['shell_script'] @@ -1138,16 +1045,15 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, for line in command.split('\n'): if line: self._printer.commands(line.strip().upper()) - self._logger.info( - "Sending GCODE command: %s", line.strip().upper()) + self._logger.info("Sending GCODE command: %s", line.strip().upper()) time.sleep(0.2) def handle_printer_action(self, channel): try: for rpi_input in self.rpi_inputs: - if (channel == self.to_int(rpi_input['gpio_pin']) and - rpi_input['action_type'] == 'printer_control' and - ((rpi_input['edge'] == 'fall') ^ GPIO.input(self.to_int(rpi_input['gpio_pin'])))): + if (channel == self.to_int(rpi_input['gpio_pin']) and rpi_input[ + 'action_type'] == 'printer_control' and ( + (rpi_input['edge'] == 'fall') ^ GPIO.input(self.to_int(rpi_input['gpio_pin'])))): if rpi_input['printer_action'] == 'resume': self._logger.info("Printer action resume.") self._printer.resume_print() @@ -1176,17 +1082,15 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, else: self._printer.connect() elif rpi_input['printer_action'] == 'stop_temp_hum_control': - self._logger.info( - "Printer action stoping temperature control.") + self._logger.info("Printer action stopping temperature control.") for rpi_output in self.rpi_outputs: if rpi_output['auto_shutdown'] and rpi_output['output_type'] == 'temp_hum_control': rpi_output['temp_ctr_set_value'] = 0 self.handle_temp_hum_control() for notification in self.notifications: if notification['printer_action']: - msg = "Printer action: " + \ - rpi_input['printer_action'] + \ - " caused by input: " + str(rpi_input['label']) + msg = "Printer action: " + rpi_input['printer_action'] + " caused by input: " + str( + rpi_input['label']) self.send_notification(msg) except Exception as ex: self.log_error(ex) @@ -1197,39 +1101,30 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, GPIO.output(gpio, value) if self._settings.get(["debug"]) is True: if queue_id is not None: - self._logger.info("Runing scheduled queue id %s", queue_id) - self._logger.info("Writing on gpio: %s value %s", gpio, value) + self._logger.debug("Running scheduled queue id %s", queue_id) + self._logger.debug("Writing on GPIO: %s value %s", gpio, value) self.update_ui() if queue_id is not None: self.stop_queue_item(queue_id) except Exception as ex: template = "An exception of type {0} occurred on {1} when writing on pin {2}. Arguments:\n{3!r}" - message = template.format( - type(ex).__name__, inspect.currentframe().f_code.co_name, gpio, ex.args) + message = template.format(type(ex).__name__, inspect.currentframe().f_code.co_name, gpio, ex.args) self._logger.warn(message) pass def write_pwm(self, gpio, pwm_value, queue_id=None): - pwm_value =int(pwm_value) - self._logger.debug("Calling write_pwm: %s, %s ,%s", gpio, pwm_value, queue_id) try: if queue_id is not None and self._settings.get(["debug"]) is True: - self._logger.info("Running scheduled queue id %s", queue_id) - self._logger.debug("pwm_instances: %s", self.pwm_intances) - for pwm in self.pwm_intances: - self._logger.debug("is gpio in pwm? : %s", (gpio in pwm)) + self._logger.debug("running scheduled queue id %s", queue_id) + for pwm in self.pwm_instances: if gpio in pwm: pwm_object = pwm[gpio] old_pwm_value = pwm['duty_cycle'] if 'duty_cycle' in pwm else -1 - - - pwm['duty_cycle'] = pwm_value - self._logger.debug("Changing duty cycle: %s", pwm_value) - self._logger.debug("PWM Object is: %s", pwm_object) - pwm_object.start(pwm_value) - self._logger.debug( - "Writing PWM on gpio: %s value %s", gpio, pwm_value) - + if not self.to_int(old_pwm_value) == self.to_int(pwm_value): + pwm['duty_cycle'] = pwm_value + pwm_object.ChangeDutyCycle(pwm_value) + if self._settings.get(["debug"]) is True: + self._logger.debug("Writing PWM on gpio: %s value %s", gpio, pwm_value) self.update_ui() if queue_id is not None: self.stop_queue_item(queue_id) @@ -1252,8 +1147,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, event = self._settings.get(["notification_event_name"]) api_key = self._settings.get(["notification_api_key"]) if self._settings.get(["debug"]) is True: - self._logger.info( - "Sending notification to: %s with msg: %s with key: %s", provider, message, api_key) + self._logger.debug("Sending notification to: %s with msg: %s with key: %s", provider, message, + api_key) try: res = self.ifttt_notification(message, event, api_key) except requests.exceptions.ConnectionError: @@ -1270,8 +1165,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, try: j = res.json() except ValueError: - self._logger.info( - 'Error: Could not parse server response. Event not sent') + self._logger.info('Error: Could not parse server response. Event not sent') for err in j['errors']: self._logger.info('Error: {}'.format(err['message'])) except Exception as ex: @@ -1279,8 +1173,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, pass def ifttt_notification(self, message, event, api_key): - url = "https://maker.ifttt.com/trigger/{e}/with/key/{k}/".format( - e=event, k=api_key) + url = "https://maker.ifttt.com/trigger/{e}/with/key/{k}/".format(e=event, k=api_key) payload = {'value1': message} return requests.post(url, data=payload) @@ -1291,7 +1184,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, if event == Events.CLIENT_OPENED: self.update_ui() - + if event == Events.PRINT_RESUMED: self.start_filament_detection() @@ -1302,18 +1195,14 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, self.start_filament_detection() for rpi_output in self.rpi_outputs: if rpi_output['auto_startup']: - delay_seconds = self.get_startup_delay_from_output( - rpi_output) - self.schedule_auto_startup_outputs( - rpi_output, delay_seconds) + delay_seconds = self.get_startup_delay_from_output(rpi_output) + self.schedule_auto_startup_outputs(rpi_output, delay_seconds) if rpi_output['toggle_timer']: if rpi_output['output_type'] == 'regular' or rpi_output['output_type'] == 'pwm': self.toggle_output(rpi_output['index_id'], True) if self.is_hour(rpi_output['shutdown_time']): - shutdown_delay_seconds = self.get_shutdown_delay_from_output( - rpi_output) - self.schedule_auto_shutdown_outputs( - rpi_output, shutdown_delay_seconds) + shutdown_delay_seconds = self.get_shutdown_delay_from_output(rpi_output) + self.schedule_auto_shutdown_outputs(rpi_output, shutdown_delay_seconds) self.run_tasks() self.update_ui() @@ -1326,8 +1215,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, rpi_output['duty_cycle'] = rpi_output['default_duty_cycle'] if rpi_output['auto_shutdown'] and not self.is_hour(shutdown_time): delay_seconds = self.to_float(shutdown_time) - self.schedule_auto_shutdown_outputs( - rpi_output, delay_seconds) + self.schedule_auto_shutdown_outputs(rpi_output, delay_seconds) self.run_tasks() self.update_ui() @@ -1342,8 +1230,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, rpi_output['duty_cycle'] = rpi_output['default_duty_cycle'] if rpi_output['auto_shutdown'] and not self.is_hour(shutdown_time): delay_seconds = self.to_float(shutdown_time) - self.schedule_auto_shutdown_outputs( - rpi_output, delay_seconds) + self.schedule_auto_shutdown_outputs(rpi_output, delay_seconds) if rpi_output['output_type'] == 'temp_hum_control': rpi_output['temp_ctr_set_value'] = 0 self.run_tasks() @@ -1353,10 +1240,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, if notification['printFinish']: file_name = os.path.basename(payload["file"]) elapsed_time_in_seconds = payload["time"] - elapsed_time = octoprint.util.get_formatted_timedelta( - timedelta(seconds=elapsed_time_in_seconds)) - msg = "Print job finished: " + file_name + \ - "finished printing in " + file_name, elapsed_time + elapsed_time = octoprint.util.get_formatted_timedelta(timedelta(seconds=elapsed_time_in_seconds)) + msg = "Print job finished: " + file_name + "finished printing in " + file_name, elapsed_time self.send_notification(msg) def run_tasks(self): @@ -1368,26 +1253,21 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, sufix = 'auto_shutdown' if rpi_output['output_type'] == 'regular': value = True if rpi_output['active_low'] else False - self.add_regular_output_to_queue( - shutdown_delay_seconds, rpi_output, value, sufix) + self.add_regular_output_to_queue(shutdown_delay_seconds, rpi_output, value, sufix) if rpi_output['output_type'] == 'ledstrip': self.ledstrip_set_rgb(rpi_output) if rpi_output['output_type'] == 'pwm' and not rpi_output['pwm_temperature_linked']: value = 0 - self.add_pwm_output_to_queue( - shutdown_delay_seconds, rpi_output, value, sufix) + self.add_pwm_output_to_queue(shutdown_delay_seconds, rpi_output, value, sufix) if rpi_output['output_type'] == 'pwm' and rpi_output['pwm_temperature_linked']: - self.schedule_pwm_duty_on_queue( - shutdown_delay_seconds, rpi_output, 0, sufix) + self.schedule_pwm_duty_on_queue(shutdown_delay_seconds, rpi_output, 0, sufix) if (rpi_output['output_type'] == 'neopixel_indirect' or rpi_output['output_type'] == 'neopixel_direct'): - self.add_neopixel_output_to_queue( - rpi_output, shutdown_delay_seconds, 0, 0, 0, sufix) + self.add_neopixel_output_to_queue(rpi_output, shutdown_delay_seconds, 0, 0, 0, sufix) if rpi_output['output_type'] == 'temp_hum_control': value = 0 - self.add_temperature_output_temperature_queue( - shutdown_delay_seconds, rpi_output, value, sufix) + self.add_temperature_output_temperature_queue(shutdown_delay_seconds, rpi_output, value, sufix) if self._settings.get(["debug"]) is True: - self._logger.info("Events scheduled to run %s", self.event_queue) + self._logger.debug("Events scheduled to run %s", self.event_queue) def ledstrip_set_rgb(self, rpi_output, rgb=None): clk = rpi_output["ledstrip_gpio_clk"] @@ -1415,15 +1295,14 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, value = self.to_int(rpi_output['default_duty_cycle']) self.write_pwm(gpio, value) if (rpi_output['output_type'] == 'neopixel_indirect' or rpi_output['output_type'] == 'neopixel_direct'): - red, green, blue = self.get_color_from_rgb( - rpi_output['default_neopixel_color']) + red, green, blue = self.get_color_from_rgb(rpi_output['default_neopixel_color']) led_count = rpi_output['neopixel_count'] led_brightness = rpi_output['neopixel_brightness'] address = rpi_output['microcontroller_address'] index_id = self.to_int(rpi_output['index_id']) - neopixel_dirrect = rpi_output['output_type'] == 'neopixel_direct' - self.send_neopixel_command(self.to_int(rpi_output['gpio_pin']), led_count, led_brightness, red, green, blue, - address, neopixel_dirrect, index_id) + neopixel_direct = rpi_output['output_type'] == 'neopixel_direct' + self.send_neopixel_command(self.to_int(rpi_output['gpio_pin']), led_count, led_brightness, red, + green, blue, address, neopixel_direct, index_id) if rpi_output['output_type'] == 'temp_hum_control': rpi_output['temp_ctr_set_value'] = rpi_output['temp_ctr_default_value'] @@ -1431,25 +1310,20 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, sufix = 'auto_startup' if rpi_output['output_type'] == 'regular': value = False if rpi_output['active_low'] else True - self.add_regular_output_to_queue( - delay_seconds, rpi_output, value, sufix) + self.add_regular_output_to_queue(delay_seconds, rpi_output, value, sufix) if rpi_output['output_type'] == 'ledstrip': self.ledstrip_set_rgb(rpi_output) if rpi_output['output_type'] == 'pwm' and not rpi_output['pwm_temperature_linked']: value = self.to_int(rpi_output['default_duty_cycle']) - self.add_pwm_output_to_queue( - delay_seconds, rpi_output, value, sufix) + self.add_pwm_output_to_queue(delay_seconds, rpi_output, value, sufix) if (rpi_output['output_type'] == 'neopixel_indirect' or rpi_output['output_type'] == 'neopixel_direct'): - red, green, blue = self.get_color_from_rgb( - rpi_output['default_neopixel_color']) - self.add_neopixel_output_to_queue( - rpi_output, delay_seconds, red, green, blue, sufix) + red, green, blue = self.get_color_from_rgb(rpi_output['default_neopixel_color']) + self.add_neopixel_output_to_queue(rpi_output, delay_seconds, red, green, blue, sufix) if rpi_output['output_type'] == 'temp_hum_control': value = rpi_output['temp_ctr_default_value'] - self.add_temperature_output_temperature_queue( - delay_seconds, rpi_output, value, sufix) + self.add_temperature_output_temperature_queue(delay_seconds, rpi_output, value, sufix) if self._settings.get(["debug"]) is True: - self._logger.info("Events scheduled to run %s", self.event_queue) + self._logger.debug("Events scheduled to run %s", self.event_queue) def get_color_from_rgb(self, stringColor): stringColor = stringColor.replace('rgb(', '') @@ -1483,12 +1357,11 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, queue_id = '{0!s}_{1!s}'.format(index_id, sufix) if self._settings.get(["debug"]) is True: - self._logger.info( - "Scheduling neopixel output id %s for on %s delay_seconds", queue_id, delay_seconds) + self._logger.debug("Scheduling neopixel output id %s for on %s delay_seconds", queue_id, delay_seconds) - thread = threading.Timer(delay_seconds, - self.send_neopixel_command, - args=[gpio_pin, ledCount, ledBrightness, red, green, blue, address, neopixel_direct, index_id, queue_id]) + thread = threading.Timer(delay_seconds, self.send_neopixel_command, + args=[gpio_pin, ledCount, ledBrightness, red, green, blue, address, neopixel_direct, + index_id, queue_id]) self.event_queue.append(dict(queue_id=queue_id, thread=thread)) @@ -1496,25 +1369,19 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, queue_id = '{0!s}_{1!s}'.format(rpi_output['index_id'], sufix) if self._settings.get(["debug"]) is True: - self._logger.info( - "Scheduling pwm output id %s for on %s delay_seconds", queue_id, delay_seconds) + self._logger.debug("Scheduling pwm output id %s for on %s delay_seconds", queue_id, delay_seconds) - thread = threading.Timer(delay_seconds, - self.write_pwm, + thread = threading.Timer(delay_seconds, self.write_pwm, args=[self.to_int(rpi_output['gpio_pin']), value, queue_id]) self.event_queue.append(dict(queue_id=queue_id, thread=thread)) def schedule_pwm_duty_on_queue(self, delay_seconds, rpi_output, value, sufix): - queue_id = '{0!s}_{1!s}_{2!s}'.format( - rpi_output['index_id'], "pwm_linked_temp", sufix) - thread = threading.Timer(delay_seconds, - self.set_pwm_duty_cycle, - args=[rpi_output, value, queue_id]) + queue_id = '{0!s}_{1!s}_{2!s}'.format(rpi_output['index_id'], "pwm_linked_temp", sufix) + thread = threading.Timer(delay_seconds, self.set_pwm_duty_cycle, args=[rpi_output, value, queue_id]) if self._settings.get(["debug"]) is True: - self._logger.info( - "Scheduling pwm linked temp output id %s on %s delay_seconds", queue_id, delay_seconds) + self._logger.debug("Scheduling pwm linked temp output id %s on %s delay_seconds", queue_id, delay_seconds) self.event_queue.append(dict(queue_id=queue_id, thread=thread)) @@ -1527,11 +1394,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, queue_id = '{0!s}_{1!s}'.format(rpi_output['index_id'], sufix) if self._settings.get(["debug"]) is True: - self._logger.info( - "Scheduling regular output id %s on %s delay_seconds", queue_id, delay_seconds) + self._logger.debug("Scheduling regular output id %s on %s delay_seconds", queue_id, delay_seconds) - thread = threading.Timer(delay_seconds, - self.write_gpio, + thread = threading.Timer(delay_seconds, self.write_gpio, args=[self.to_int(rpi_output['gpio_pin']), value, queue_id]) self.event_queue.append(dict(queue_id=queue_id, thread=thread)) @@ -1539,28 +1404,25 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, def add_temperature_output_temperature_queue(self, delay_seconds, rpi_output, value, sufix): queue_id = '{0!s}_{1!s}'.format(rpi_output['index_id'], sufix) if self._settings.get(["debug"]) is True: - self._logger.info( - "Scheduling temperature control id %s on %s delay_seconds", queue_id, delay_seconds) + self._logger.debug("Scheduling temperature control id %s on %s delay_seconds", queue_id, delay_seconds) - thread = threading.Timer(delay_seconds, - self.write_temperature_to_output, + thread = threading.Timer(delay_seconds, self.write_temperature_to_output, args=[self.to_int(rpi_output['index_id']), value, queue_id]) self.event_queue.append(dict(queue_id=queue_id, thread=thread)) def write_temperature_to_output(self, rpi_output_index, value, queue_id=None): try: - rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int( - r_out['index_id']) == rpi_output_index].pop() + rpi_output = [r_out for r_out in self.rpi_outputs if + self.to_int(r_out['index_id']) == rpi_output_index].pop() if rpi_output['output_type'] == 'temp_hum_control': rpi_output['temp_ctr_set_value'] = value if self._settings.get(["debug"]) is True: if queue_id is not None: - self._logger.info("Runing scheduled queue id %s", queue_id) - self._logger.info( - "Setting temperature to output index: %s value %s", rpi_output['index_id'], value) + self._logger.debug("running scheduled queue id %s", queue_id) + self._logger.debug("Setting temperature to output index: %s value %s", rpi_output['index_id'], value) self.update_ui() if queue_id is not None: @@ -1568,8 +1430,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, except Exception as ex: template = "An exception of type {0} occurred on {1}. Arguments:\n{3!r}" - message = template.format( - type(ex).__name__, inspect.currentframe().f_code.co_name, ex.args) + message = template.format(type(ex).__name__, inspect.currentframe().f_code.co_name, ex.args) self._logger.warn(message) pass @@ -1580,11 +1441,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, if start_up_date_time < datetime.now(): delay_seconds = 0.0 else: - delay_seconds = (start_up_date_time - - datetime.now()).total_seconds() + delay_seconds = (start_up_date_time - datetime.now()).total_seconds() else: - delay_seconds = self.to_float( - rpi_output['startup_time']) + delay_seconds = self.to_float(rpi_output['startup_time']) return delay_seconds # ~~ SettingsPlugin mixin @@ -1605,75 +1464,43 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, self.clear_gpio() if self._settings.get(["debug"]) is True: - self._logger.info("rpi_outputs: %s", self.rpi_outputs) - self._logger.info("rpi_inputs: %s", self.rpi_inputs) + self._logger.debug("rpi_outputs: %s", self.rpi_outputs) + self._logger.debug("rpi_inputs: %s", self.rpi_inputs) self.setup_gpio() self.configure_gpio() self.generate_temp_hum_control_status() def get_settings_defaults(self): - return dict( - rpi_outputs=[], - rpi_inputs=[], - filament_sensor_gcode="G91 ;Set Relative Mode \n" + - "G1 E-5.000000 F500 ;Retract 5mm\n" + - "G1 Z15 F300 ;move Z up 15mm\n" + - "G90 ;Set Absolute Mode\n " + - "G1 X20 Y20 F9000 ;Move to hold position\n" + - "G91 ;Set Relative Mode\n" + - "G1 E-40 F500 ;Retract 40mm\n" + - "M0 ;Idle Hold\n" + - "G90 ;Set Absolute Mode\n" + - "G1 F5000 ;Set speed limits\n" + - "G28 X0 Y0 ;Home X Y\n" + - "M82 ;Set extruder to Absolute Mode\n" + - "G92 E0 ;Set Extruder to 0", - use_sudo=True, - neopixel_dma=10, - debug=False, - gcode_control=False, - debug_temperature_log=False, - use_board_pin_number=False, - notification_provider="disabled", - notification_api_key="", - notification_event_name="printer_event", - notifications=[{'printFinish': True, 'filamentChange': True, - 'printer_action': True, 'temperatureAction': True, 'gpioAction': True}] - ) + return dict(rpi_outputs=[], rpi_inputs=[], + filament_sensor_gcode="G91 ;Set Relative Mode \n" + "G1 E-5.000000 F500 ;Retract 5mm\n" + "G1 Z15 F300 ;move Z up 15mm\n" + "G90 ;Set Absolute Mode\n " + "G1 X20 Y20 F9000 ;Move to hold position\n" + "G91 ;Set Relative Mode\n" + "G1 E-40 F500 ;Retract 40mm\n" + "M0 ;Idle Hold\n" + "G90 ;Set Absolute Mode\n" + "G1 F5000 ;Set speed limits\n" + "G28 X0 Y0 ;Home X Y\n" + "M82 ;Set extruder to Absolute Mode\n" + "G92 E0 ;Set Extruder to 0", + use_sudo=True, neopixel_dma=10, debug=False, gcode_control=False, debug_temperature_log=False, + use_board_pin_number=False, notification_provider="disabled", notification_api_key="", + notification_event_name="printer_event", notifications=[{ + 'printFinish' : True, + 'filamentChange' : True, + 'printer_action' : True, + 'temperatureAction': True, 'gpioAction': True + }]) # ~~ TemplatePlugin def get_template_configs(self): - return [ - dict(type="settings", custom_bindings=True), - dict(type="tab", custom_bindings=True), - dict(type="navbar", custom_bindings=True, - suffix="_1", classes=["dropdown"]), - dict(type="navbar", custom_bindings=True, - template="enclosure_navbar_input.jinja2", suffix="_2", classes=["dropdown"]) - ] + return [dict(type="settings", custom_bindings=True), dict(type="tab", custom_bindings=True), + dict(type="navbar", custom_bindings=True, suffix="_1", classes=["dropdown"]), + dict(type="navbar", custom_bindings=True, template="enclosure_navbar_input.jinja2", suffix="_2", + classes=["dropdown"])] # ~~ AssetPlugin mixin def get_assets(self): - return dict( - js=["js/enclosure.js", "js/bootstrap-colorpicker.min.js"], - css=["css/bootstrap-colorpicker.css", "css/enclosure.css"] - ) + return dict(js=["js/enclosure.js", "js/bootstrap-colorpicker.min.js"], + css=["css/bootstrap-colorpicker.css", "css/enclosure.css"]) # ~~ Softwareupdate hook def get_update_information(self): - return dict( - enclosure=dict( - displayName="Enclosure Plugin", - displayVersion=self._plugin_version, - # version check: github repository - type="github_release", - user="vitormhenrique", - repo="OctoPrint-Enclosure", - current=self._plugin_version, - # update method: pip - pip="https://github.com/vitormhenrique/OctoPrint-Enclosure/archive/{target_version}.zip" - ) - ) + return dict(enclosure=dict(displayName="Enclosure Plugin", displayVersion=self._plugin_version, + # version check: github repository + type="github_release", user="vitormhenrique", repo="OctoPrint-Enclosure", current=self._plugin_version, + # update method: pip + pip="https://github.com/vitormhenrique/OctoPrint-Enclosure/archive/{target_version}.zip")) def hook_gcode_queuing(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs): if self._settings.get(["gcode_control"]) is False: @@ -1681,7 +1508,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, if cmd.strip().startswith("ENC"): if self._settings.get(["debug"]) is True: - self._logger.info("Gcode queuing: %s", cmd) + self._logger.debug("Gcode queuing: %s", cmd) index_id = self.to_int(self.get_gcode_value(cmd, 'O')) for output in [item for item in self.rpi_outputs if item['index_id'] == index_id]: if output['output_type'] == 'regular': @@ -1690,16 +1517,14 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, value = True if set_value == 1 else False value = (not value) if output['active_low'] else value self.write_gpio(self.to_int(output['gpio_pin']), value) - comm_instance._log( - "Setting REGULAR output %s to value %s" % (index_id, value)) + comm_instance._log("Setting REGULAR output %s to value %s" % (index_id, value)) return if output['output_type'] == 'pwm': set_value = self.to_int(self.get_gcode_value(cmd, 'S')) set_value = self.constrain(set_value, 0, 100) output['duty_cycle'] = set_value self.write_pwm(self.to_int(output['gpio_pin']), set_value) - comm_instance._log( - "Setting PWM output %s to value %s" % (index_id, set_value)) + comm_instance._log("Setting PWM output %s to value %s" % (index_id, set_value)) return if output['output_type'] == 'neopixel_indirect' or output['output_type'] == 'neopixel_direct': red = self.get_gcode_value(cmd, 'R') @@ -1712,11 +1537,10 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, index_id = self.to_int(output['index_id']) - neopixel_dirrect = output['output_type'] == 'neopixel_direct' + neopixel_direct = output['output_type'] == 'neopixel_direct' - self.send_neopixel_command( - self.to_int(output['gpio_pin']), - led_count, led_brightness, red, green, blue, address, neopixel_dirrect, index_id) + self.send_neopixel_command(self.to_int(output['gpio_pin']), led_count, led_brightness, red, green, + blue, address, neopixel_direct, index_id) comm_instance._log( "Setting NEOPIXEL output %s to red: %s green: %s blue: %s" % (index_id, red, green, blue)) return @@ -1729,8 +1553,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, output['temp_ctr_set_value'] = set_value self.update_ui_set_temperature() self.handle_temp_hum_control() - comm_instance._log( - "Setting TEMP/HUM control output %s to value %s" % (index_id, set_value)) + comm_instance._log("Setting TEMP/HUM control output %s to value %s" % (index_id, set_value)) return @@ -1743,6 +1566,6 @@ def __plugin_load__(): global __plugin_hooks__ __plugin_hooks__ = { - "octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.hook_gcode_queuing, + "octoprint.comm.protocol.gcode.queuing" : __plugin_implementation__.hook_gcode_queuing, "octoprint.plugin.softwareupdate.check_config": __plugin_implementation__.get_update_information - } + } \ No newline at end of file -- 2.39.5 From cd46ddda297eb87a052f9a04f13ae025bc0f51a9 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 14:08:46 +0000 Subject: [PATCH 29/52] debug logging messages to logger.debug --- octoprint_enclosure/__init__.py | 68 ++++++++++++--------------------- 1 file changed, 25 insertions(+), 43 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 045a203..61a29f6 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -329,7 +329,6 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP else: cmd = cmd + str(address) - if self._settings.get(["debug"]) is True: if queue_id is not None: self._logger.debug("running scheduled queue id %s", queue_id) self._logger.debug("Sending neopixel cmd: %s", cmd) @@ -429,18 +428,15 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP def stop_queue_item(self, queue_id): old_list = self.event_queue - if self._settings.get(["debug"]) is True: - self._logger.debug("Stopping queue id %s...", queue_id) + self._logger.debug("Stopping queue id %s...", queue_id) for task in self.event_queue: - if self._settings.get(["debug"]) is True: - self._logger.debug("Queue id found...") + self._logger.debug("Queue id found...") if task['queue_id'] == queue_id: task['thread'].cancel() self.event_queue.remove(task) - if self._settings.get(["debug"]) is True: - self._logger.debug("Queue id stopped and removed from list...") - self._logger.debug("Old queue list: %s", old_list) - self._logger.debug("New queue list: %s", self.event_queue) + self._logger.debug("Queue id stopped and removed from list...") + self._logger.debug("Old queue list: %s", old_list) + self._logger.debug("New queue list: %s", self.event_queue) def update_ui_outputs(self): try: @@ -702,8 +698,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP except: calculated_duty = 0 - if self._settings.get(["debug"]) is True: - self._logger.debug("Calculated duty for PWM %s is %s", index_id, calculated_duty) + self._logger.debug("Calculated duty for PWM %s is %s", index_id, calculated_duty) elif self.print_complete: calculated_duty = self.to_int(pwm_output['duty_cycle']) else: @@ -765,8 +760,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP current_status = True if control_type == 'heater' and max_temp > 0.0 and max_temp < current_value: - if self._settings.get(["debug"]) is True: - self._logger.debug("Maximum temperature reached for temperature control %s", + self._logger.debug("Maximum temperature reached for temperature control %s", temp_hum_control['index_id']) temp_hum_control['temp_ctr_set_value'] = 0 current_status = False @@ -1004,9 +998,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP dict(is_msg=True, msg="Could not execute shell script", msg_type="error")) def handle_gpio_control(self, channel): + try: - if self._settings.get(["debug"]) is True: - self._logger.debug("GPIO event triggered on channel %s", channel) + self._logger.debug("GPIO event triggered on channel %s", channel) for rpi_input in list( filter(lambda item: self.to_int(item['gpio_pin']) == self.to_int(channel), self.rpi_inputs)): gpio_pin = self.to_int(rpi_input['gpio_pin']) @@ -1099,10 +1093,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP def write_gpio(self, gpio, value, queue_id=None): try: GPIO.output(gpio, value) - if self._settings.get(["debug"]) is True: - if queue_id is not None: - self._logger.debug("Running scheduled queue id %s", queue_id) - self._logger.debug("Writing on GPIO: %s value %s", gpio, value) + if queue_id is not None: + self._logger.debug("Running scheduled queue id %s", queue_id) + self._logger.debug("Writing on GPIO: %s value %s", gpio, value) self.update_ui() if queue_id is not None: self.stop_queue_item(queue_id) @@ -1123,8 +1116,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP if not self.to_int(old_pwm_value) == self.to_int(pwm_value): pwm['duty_cycle'] = pwm_value pwm_object.ChangeDutyCycle(pwm_value) - if self._settings.get(["debug"]) is True: - self._logger.debug("Writing PWM on gpio: %s value %s", gpio, pwm_value) + self._logger.debug("Writing PWM on gpio: %s value %s", gpio, pwm_value) self.update_ui() if queue_id is not None: self.stop_queue_item(queue_id) @@ -1146,8 +1138,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP if provider == 'ifttt': event = self._settings.get(["notification_event_name"]) api_key = self._settings.get(["notification_api_key"]) - if self._settings.get(["debug"]) is True: - self._logger.debug("Sending notification to: %s with msg: %s with key: %s", provider, message, + self._logger.debug("Sending notification to: %s with msg: %s with key: %s", provider, message, api_key) try: res = self.ifttt_notification(message, event, api_key) @@ -1266,8 +1257,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP if rpi_output['output_type'] == 'temp_hum_control': value = 0 self.add_temperature_output_temperature_queue(shutdown_delay_seconds, rpi_output, value, sufix) - if self._settings.get(["debug"]) is True: - self._logger.debug("Events scheduled to run %s", self.event_queue) + self._logger.debug("Events scheduled to run %s", self.event_queue) def ledstrip_set_rgb(self, rpi_output, rgb=None): clk = rpi_output["ledstrip_gpio_clk"] @@ -1322,8 +1312,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP if rpi_output['output_type'] == 'temp_hum_control': value = rpi_output['temp_ctr_default_value'] self.add_temperature_output_temperature_queue(delay_seconds, rpi_output, value, sufix) - if self._settings.get(["debug"]) is True: - self._logger.debug("Events scheduled to run %s", self.event_queue) + self._logger.debug("Events scheduled to run %s", self.event_queue) def get_color_from_rgb(self, stringColor): stringColor = stringColor.replace('rgb(', '') @@ -1356,8 +1345,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP queue_id = '{0!s}_{1!s}'.format(index_id, sufix) - if self._settings.get(["debug"]) is True: - self._logger.debug("Scheduling neopixel output id %s for on %s delay_seconds", queue_id, delay_seconds) + + self._logger.debug("Scheduling neopixel output id %s for on %s delay_seconds", queue_id, delay_seconds) thread = threading.Timer(delay_seconds, self.send_neopixel_command, args=[gpio_pin, ledCount, ledBrightness, red, green, blue, address, neopixel_direct, @@ -1368,8 +1357,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP def add_pwm_output_to_queue(self, delay_seconds, rpi_output, value, sufix): queue_id = '{0!s}_{1!s}'.format(rpi_output['index_id'], sufix) - if self._settings.get(["debug"]) is True: - self._logger.debug("Scheduling pwm output id %s for on %s delay_seconds", queue_id, delay_seconds) + self._logger.debug("Scheduling pwm output id %s for on %s delay_seconds", queue_id, delay_seconds) thread = threading.Timer(delay_seconds, self.write_pwm, args=[self.to_int(rpi_output['gpio_pin']), value, queue_id]) @@ -1380,8 +1368,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP queue_id = '{0!s}_{1!s}_{2!s}'.format(rpi_output['index_id'], "pwm_linked_temp", sufix) thread = threading.Timer(delay_seconds, self.set_pwm_duty_cycle, args=[rpi_output, value, queue_id]) - if self._settings.get(["debug"]) is True: - self._logger.debug("Scheduling pwm linked temp output id %s on %s delay_seconds", queue_id, delay_seconds) + self._logger.debug("Scheduling pwm linked temp output id %s on %s delay_seconds", queue_id, delay_seconds) self.event_queue.append(dict(queue_id=queue_id, thread=thread)) @@ -1393,8 +1380,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP def add_regular_output_to_queue(self, delay_seconds, rpi_output, value, sufix): queue_id = '{0!s}_{1!s}'.format(rpi_output['index_id'], sufix) - if self._settings.get(["debug"]) is True: - self._logger.debug("Scheduling regular output id %s on %s delay_seconds", queue_id, delay_seconds) + self._logger.debug("Scheduling regular output id %s on %s delay_seconds", queue_id, delay_seconds) thread = threading.Timer(delay_seconds, self.write_gpio, args=[self.to_int(rpi_output['gpio_pin']), value, queue_id]) @@ -1403,8 +1389,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP def add_temperature_output_temperature_queue(self, delay_seconds, rpi_output, value, sufix): queue_id = '{0!s}_{1!s}'.format(rpi_output['index_id'], sufix) - if self._settings.get(["debug"]) is True: - self._logger.debug("Scheduling temperature control id %s on %s delay_seconds", queue_id, delay_seconds) + self._logger.debug("Scheduling temperature control id %s on %s delay_seconds", queue_id, delay_seconds) thread = threading.Timer(delay_seconds, self.write_temperature_to_output, args=[self.to_int(rpi_output['index_id']), value, queue_id]) @@ -1419,7 +1404,6 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP if rpi_output['output_type'] == 'temp_hum_control': rpi_output['temp_ctr_set_value'] = value - if self._settings.get(["debug"]) is True: if queue_id is not None: self._logger.debug("running scheduled queue id %s", queue_id) self._logger.debug("Setting temperature to output index: %s value %s", rpi_output['index_id'], value) @@ -1463,9 +1447,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.rpi_outputs_not_changed = commonPins self.clear_gpio() - if self._settings.get(["debug"]) is True: - self._logger.debug("rpi_outputs: %s", self.rpi_outputs) - self._logger.debug("rpi_inputs: %s", self.rpi_inputs) + self._logger.debug("rpi_outputs: %s", self.rpi_outputs) + self._logger.debug("rpi_inputs: %s", self.rpi_inputs) self.setup_gpio() self.configure_gpio() self.generate_temp_hum_control_status() @@ -1507,8 +1490,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP return if cmd.strip().startswith("ENC"): - if self._settings.get(["debug"]) is True: - self._logger.debug("Gcode queuing: %s", cmd) + self._logger.debug("Gcode queuing: %s", cmd) index_id = self.to_int(self.get_gcode_value(cmd, 'O')) for output in [item for item in self.rpi_outputs if item['index_id'] == index_id]: if output['output_type'] == 'regular': -- 2.39.5 From d69ad9f5df5307f730af525ba751e7c00e1b52fd Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 14:23:36 +0000 Subject: [PATCH 30/52] hotfix to use start instead of ChangeDuty Cycle, and more spelling --- octoprint_enclosure/__init__.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 61a29f6..16b352e 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -200,8 +200,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP value = True if flask.request.values["status"] == 'true' else False if not value: - sufix = 'auto_startup' - queue_id = '{0!s}_{1!s}'.format(index, sufix) + suffix = 'auto_startup' + queue_id = '{0!s}_{1!s}'.format(index, suffix) self.stop_queue_item(queue_id) for output in self.rpi_outputs: if self.to_int(index) == self.to_int(output['index_id']): @@ -216,8 +216,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP value = True if flask.request.values["status"] == 'true' else False if not value: - sufix = 'auto_shutdown' - queue_id = '{0!s}_{1!s}'.format(index, sufix) + suffix = 'auto_shutdown' + queue_id = '{0!s}_{1!s}'.format(index, suffix) self.stop_queue_item(queue_id) for output in self.rpi_outputs: @@ -870,6 +870,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.clear_channel(pin) GPIO.setup(pin, GPIO.OUT) pwm_instance = GPIO.PWM(pin, self.to_int(gpio_out_pwm['pwm_frequency'])) + self._logger.info("starting PWM on pin %s", pin) pwm_instance.start(0) self.pwm_instances.append({pin: pwm_instance}) for gpio_out_neopixel in list( @@ -1107,7 +1108,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP def write_pwm(self, gpio, pwm_value, queue_id=None): try: - if queue_id is not None and self._settings.get(["debug"]) is True: + if queue_id is not None: self._logger.debug("running scheduled queue id %s", queue_id) for pwm in self.pwm_instances: if gpio in pwm: @@ -1115,7 +1116,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP old_pwm_value = pwm['duty_cycle'] if 'duty_cycle' in pwm else -1 if not self.to_int(old_pwm_value) == self.to_int(pwm_value): pwm['duty_cycle'] = pwm_value - pwm_object.ChangeDutyCycle(pwm_value) + pwm_object.start(pwm_value) self._logger.debug("Writing PWM on gpio: %s value %s", gpio, pwm_value) self.update_ui() if queue_id is not None: -- 2.39.5 From 3674b79af6d59bdcc312c0e816d3ed34363aeb89 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 15:33:39 +0000 Subject: [PATCH 31/52] remove debug setting from logging messages --- octoprint_enclosure/__init__.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 16b352e..d12375b 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -343,7 +343,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP sensor_data = [] for sensor in list(filter(lambda item: item['input_type'] == 'temperature_sensor', self.rpi_inputs)): temp, hum = self.get_sensor_data(sensor) - if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + if self._settings.get(["debug_temperature_log"]) is True: self._logger.debug("Sensor %s Temperature: %s humidity %s", sensor['label'], temp, hum) if temp is not None and hum is not None: sensor_data.append(dict(index_id=sensor['index_id'], temperature=temp, humidity=hum)) @@ -564,10 +564,10 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP else: sudo_str = "" cmd = sudo_str + "python " + script + str(sensor) + " " + str(pin) - if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + if self._settings.get(["debug_temperature_log"]) is True: self._logger.debug("Temperature dht cmd: %s", cmd) stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read() - if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + if self._settings.get(["debug_temperature_log"]) is True: self._logger.debug("Dht result: %s", stdout) temp, hum = stdout.split("|") return (self.to_float(temp.strip()), self.to_float(hum.strip())) @@ -585,10 +585,10 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP else: sudo_str = "" cmd = sudo_str + "python " + script + str(address) - if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + if self._settings.get(["debug_temperature_log"]) is True: self._logger.debug("Temperature BME280 cmd: %s", cmd) stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read() - if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + if self._settings.get(["debug_temperature_log"]) is True: self._logger.debug("BME280 result: %s", stdout) temp, hum = stdout.split("|") return (self.to_float(temp.strip()), self.to_float(hum.strip())) @@ -606,10 +606,10 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP else: sudo_str = "" cmd = sudo_str + "python " + script + str(address) - if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + if self._settings.get(["debug_temperature_log"]) is True: self._logger.debug("Temperature SI7021 cmd: %s", cmd) stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read() - if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + if self._settings.get(["debug_temperature_log"]) is True: self._logger.debug("SI7021 result: %s", stdout) temp, hum = stdout.split("|") return (self.to_float(temp.strip()), self.to_float(hum.strip())) @@ -631,7 +631,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP if equals_pos != -1: temp_string = lines[1][equals_pos + 2:] temp_c = float(temp_string) / 1000. - if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + if self._settings.get(["debug_temperature_log"]) is True: self._logger.debug("DS18B20 result: %s", temp_c) return '{0:0.1f}'.format(temp_c) return 0 @@ -649,11 +649,11 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP try: script = os.path.dirname(os.path.realpath(__file__)) + "/tmp102.py" args = ["python", script, str(address)] - if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + if self._settings.get(["debug_temperature_log"]) is True: self._logger.debug("Temperature TMP102 cmd: %s", " ".join(args)) proc = Popen(args, stdout=PIPE) stdout, _ = proc.communicate() - if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + if self._settings.get(["debug_temperature_log"]) is True: self._logger.debug("TMP102 result: %s", stdout) return self.to_float(stdout.strip()) except Exception as ex: @@ -665,11 +665,11 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP try: script = os.path.dirname(os.path.realpath(__file__)) + "/max31855.py" args = ["python", script, str(address)] - if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + if self._settings.get(["debug_temperature_log"]) is True: self._logger.debug("Temperature MAX31855 cmd: %s", " ".join(args)) proc = Popen(args, stdout=PIPE) stdout, _ = proc.communicate() - if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + if self._settings.get(["debug_temperature_log"]) is True: self._logger.debug("MAX31855 result: %s", stdout) return self.to_float(stdout.strip()) except Exception as ex: -- 2.39.5 From 210976537bcc72aeb5a8954a5217e27da35b0a0b Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 16:50:25 +0000 Subject: [PATCH 32/52] more spelling in templates --- .../templates/enclosure_settings.jinja2 | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/octoprint_enclosure/templates/enclosure_settings.jinja2 b/octoprint_enclosure/templates/enclosure_settings.jinja2 index 9f60ed4..7612751 100644 --- a/octoprint_enclosure/templates/enclosure_settings.jinja2 +++ b/octoprint_enclosure/templates/enclosure_settings.jinja2 @@ -101,8 +101,9 @@ - Attention Neopixel requires a microcontroler (ex: arduino) connected to I2C bus. This is the pin on the - microcontroler that is connected to the Neopixel. + Attention Neopixel requires a microcontroller (ex: arduino) + connected to I2C bus. This is the pin on the + microcontroller that is connected to the Neopixel.
@@ -116,7 +117,7 @@ {{ _('Link PWM to Temperature') }} Link PWM ouput to temperature. PWM output will be interpolated between the point from duty A, temperature A -> duty - B, temperature B. This output will automatomatically start when a print starts and will default to the default + B, temperature B. This output will automatically start when a print starts and will default to the default duty cycle when print is complete.
@@ -156,7 +157,7 @@ - Toggle output every amount of secconds. It will start when the print starts and stop when print is complete. For + Toggle output every amount of seconds. It will start when the print starts and stop when print is complete. For PWM pins it will use the default PWM value when ON.
@@ -166,7 +167,7 @@
- Time in secconds that the GPIO will remain ON + Time in seconds that the GPIO will remain ON
@@ -188,7 +189,7 @@ - Choose if output should turn on automatomatically when octoprint starts + Choose if output should turn on automatically when octoprint starts
@@ -196,7 +197,7 @@ - Choose if output should turn on automatomatically when print starts + Choose if output should turn on automatically when print starts
@@ -206,7 +207,7 @@
- Time delay in secconds to turn on GPIO when print starts OR exact time that the event should happen, note that + Time delay in seconds to turn on GPIO when print starts OR exact time that the event should happen, note that events will only be scheduled after a print starts, time should be formated as HH:MM on a 24 hours format, don't forget to check timezone of your Raspberry Pi.
@@ -257,7 +258,7 @@ - Active low means that the GPIO will turn on when receive a low signal (ground) from Raspbery PI + Active low means that the GPIO will turn on when receive a low signal (ground) from Raspberry PI @@ -406,7 +407,7 @@
- Microcontroller address in HEX value, you can find it by runing + Microcontroller address in HEX value, you can find it by running i2cdetect -y 1 on your Raspberry Pi
@@ -575,7 +576,7 @@
- Sensor address in HEX value, you can find it by runing + Sensor address in HEX value, you can find it by running i2cdetect -y 1 on your Raspberry Pi
@@ -636,14 +637,14 @@ Info: PRINTER actions when a condition is met, that can be a filament sensor, button, etc. Actions can be Pause \ Resume \ Cancel a printer_control job, change the filament or disable Temperature Control. You can use the "change filament" action and set up the input GPIO acording to your sensor, for example, if your filament - sensor conects to ground when detects the end of the filament, you should choose PULL UP resistors and detect + sensor connects to ground when detects the end of the filament, you should choose PULL UP resistors and detect the event on the falling edge. Info: Action will control GPIO outputs when a condition is met, for example detect a press of a button. You can use this to control any previous configured OUTPUTS, basically beeing able to control your lights / fan - / pritner using mechanical buttons buttons instead of the octoprint interface. You can only control REGULAR outputs. + / printer using mechanical buttons buttons instead of the octoprint interface. You can only control REGULAR outputs. @@ -658,7 +659,7 @@ Input GPIO that will detect the event that should trigger the action. For example if you have a filament sensor you put the GPIO pin that the sensor is connected. This can also be a press of a button or any other signal that - you want to detect. You can not use GPIO 4 here if you are using temeprature sensor DS18B20 + you want to detect. You can not use GPIO 4 here if you are using temperature sensor DS18B20
-- 2.39.5 From 9a6b727e40291c913fe50557eb2e0dea6a0fb07c Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 16:59:05 +0000 Subject: [PATCH 33/52] added debug message to clear_channel --- octoprint_enclosure/__init__.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index d12375b..d446981 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -842,6 +842,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP def clear_channel(self, channel): try: GPIO.cleanup(self.to_int(channel)) + self._logger.debug("Clearing channel %s", channel) except Exception as ex: self.log_error(ex) @@ -1116,7 +1117,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP old_pwm_value = pwm['duty_cycle'] if 'duty_cycle' in pwm else -1 if not self.to_int(old_pwm_value) == self.to_int(pwm_value): pwm['duty_cycle'] = pwm_value - pwm_object.start(pwm_value) + pwm_object.start(pwm_value) #should be changed back to pwm_object.ChangeDutyCycle() but this + # was causing errors. self._logger.debug("Writing PWM on gpio: %s value %s", gpio, pwm_value) self.update_ui() if queue_id is not None: -- 2.39.5 From cceb90ebdcb93db1729679c954154cfa8903e7e0 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Thu, 28 Mar 2019 17:53:08 +0000 Subject: [PATCH 34/52] constrain duty cycle to temp a -> 100 --- octoprint_enclosure/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index d446981..55eb548 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -695,6 +695,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP try: calculated_duty = ((current_temp - temp_a) * (duty_b - duty_a) / (temp_b - temp_a)) + duty_a + calculated_duty = self.constrain(calculated_duty, duty_a,100) except: calculated_duty = 0 -- 2.39.5 From 5b2766c1582b2b49a054c3e1989d8c4436aaa7cb Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Fri, 29 Mar 2019 13:18:14 +0000 Subject: [PATCH 35/52] fix logic error in temperature cut off --- octoprint_enclosure/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 55eb548..446852f 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -695,7 +695,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP try: calculated_duty = ((current_temp - temp_a) * (duty_b - duty_a) / (temp_b - temp_a)) + duty_a - calculated_duty = self.constrain(calculated_duty, duty_a,100) + if calculated_duty < temp_a: + calculated_duty = 0 except: calculated_duty = 0 -- 2.39.5 From 069aaa24c2f31a5114376d06d1068a6ee54ef4e4 Mon Sep 17 00:00:00 2001 From: Lonja Selter Date: Fri, 29 Mar 2019 13:19:27 +0000 Subject: [PATCH 36/52] fix logic error in temperature cut off --- octoprint_enclosure/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 446852f..9c1fc94 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -695,7 +695,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP try: calculated_duty = ((current_temp - temp_a) * (duty_b - duty_a) / (temp_b - temp_a)) + duty_a - if calculated_duty < temp_a: + + if current_temp < temp_a: calculated_duty = 0 except: calculated_duty = 0 -- 2.39.5 From de5aa9463f3d5981762b71a211b5ed266733d843 Mon Sep 17 00:00:00 2001 From: munzli Date: Sun, 29 Sep 2019 17:55:34 +0200 Subject: [PATCH 37/52] added support for mcp9808 temperature sensor --- README.md | 2 +- octoprint_enclosure/__init__.py | 19 ++++++ octoprint_enclosure/mcp9808.py | 61 +++++++++++++++++++ .../templates/enclosure_settings.jinja2 | 5 +- setup.py | 2 +- 5 files changed, 85 insertions(+), 4 deletions(-) create mode 100644 octoprint_enclosure/mcp9808.py diff --git a/README.md b/README.md index fc4f104..5e75eba 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ The response will either have YES or NO at the end of the first line. If it is y Copy the serial number, you will need to configure the plugin. Note that for the serial number includes the 28-, for example 28-0000069834ff. -* For the SI7021, BME280 and TMP102 sensors +* For the SI7021, BME280, TMP102 and MCP9808 sensors Enable I2C on your raspberry pi, depending on raspi-config version, step by step can be different: diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 9c1fc94..54b16c0 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -512,6 +512,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP elif sensor['temp_sensor_type'] == "max31855": temp = self.read_max31855_temp(sensor['temp_sensor_address']) hum = 0 + elif sensor['temp_sensor_type'] == "mcp9808": + temp = self.read_mcp_temp() + hum = 0 else: self._logger.info("temp_sensor_type no match") temp = None @@ -556,6 +559,22 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP return return_value, return_value + def read_mcp_temp(self): + try: + script = os.path.dirname(os.path.realpath(__file__)) + "/mcp9808.py" + args = ["python", script] + if self._settings.get(["debug_temperature_log"]) is True: + self._logger.debug("Temperature MCP9808 cmd: %s", " ".join(args)) + proc = Popen(args, stdout=PIPE) + stdout, _ = proc.communicate() + if self._settings.get(["debug_temperature_log"]) is True: + self._logger.debug("MCP9808 result: %s", stdout) + return self.to_float(stdout.strip()) + except Exception as ex: + self._logger.info("Failed to execute python scripts, try disabling use SUDO on advanced section.") + self.log_error(ex) + return 0 + def read_dht_temp(self, sensor, pin): try: script = os.path.dirname(os.path.realpath(__file__)) + "/getDHTTemp.py " diff --git a/octoprint_enclosure/mcp9808.py b/octoprint_enclosure/mcp9808.py new file mode 100644 index 0000000..d324b47 --- /dev/null +++ b/octoprint_enclosure/mcp9808.py @@ -0,0 +1,61 @@ +import smbus + +# default I2C address for device. +MCP9808_I2CADDR_DEFAULT = 0x18 + +# register addresses. +MCP9808_REG_CONFIG = 0x01 +MCP9808_REG_UPPER_TEMP = 0x02 +MCP9808_REG_LOWER_TEMP = 0x03 +MCP9808_REG_CRIT_TEMP = 0x04 +MCP9808_REG_AMBIENT_TEMP = 0x05 +MCP9808_REG_MANUF_ID = 0x06 +MCP9808_REG_DEVICE_ID = 0x07 +MCP9808_REG_RESOLUTION = 0x08 + +# configuration register values. +MCP9808_REG_CONFIG_CONTCONV = 0x0000 +MCP9808_REG_CONFIG_SHUTDOWN = 0x0100 +MCP9808_REG_CONFIG_CRITLOCKED = 0x0080 +MCP9808_REG_CONFIG_WINLOCKED = 0x0040 +MCP9808_REG_CONFIG_INTCLR = 0x0020 +MCP9808_REG_CONFIG_ALERTSTAT = 0x0010 +MCP9808_REG_CONFIG_ALERTCTRL = 0x0008 +MCP9808_REG_CONFIG_ALERTSEL = 0x0002 +MCP9808_REG_CONFIG_ALERTPOL = 0x0002 +MCP9808_REG_CONFIG_ALERTMODE = 0x0001 + + +def main(): + # get I2C bus + bus = smbus.SMBus(1) + + # MCP9808 address, 0x18(24) + # configuration register, 0x01(1) + # continuous conversion mode, power-up default + config = [MCP9808_REG_CONFIG_CONTCONV, 0x00] + bus.write_i2c_block_data(MCP9808_I2CADDR_DEFAULT, MCP9808_REG_CONFIG, config) + + # MCP9808 address, 0x18(24) + # select resolution rgister, 0x08(8) + # resolution = +0.0625 / C, 0x03(03) + bus.write_byte_data(MCP9808_I2CADDR_DEFAULT, MCP9808_REG_RESOLUTION, 0x03) + + # MCP9808 address, 0x18(24) + # read data back from 0x05(5), 2 bytes + # temp MSB, TEMP LSB + data = bus.read_i2c_block_data(MCP9808_I2CADDR_DEFAULT, MCP9808_REG_AMBIENT_TEMP, 2) + + # convert the data to 13-bits + ctemp = ((data[0] & 0x1F) * 256) + data[1] + if ctemp > 4095: + ctemp -= 8192 + ctemp = ctemp * 0.0625 + # ftemp = ctemp * 1.8 + 32 + + # output data + print('{0:0.2f}'.format(ctemp)) + + +if __name__ == "__main__": + main() diff --git a/octoprint_enclosure/templates/enclosure_settings.jinja2 b/octoprint_enclosure/templates/enclosure_settings.jinja2 index 7612751..29bdc5f 100644 --- a/octoprint_enclosure/templates/enclosure_settings.jinja2 +++ b/octoprint_enclosure/templates/enclosure_settings.jinja2 @@ -538,6 +538,7 @@ + Attention You need to install and configure the necessary libraries for the temperature sensor, check @@ -562,7 +563,7 @@
- +
@@ -604,7 +605,7 @@
- +
diff --git a/setup.py b/setup.py index 54921de..71166b0 100644 --- a/setup.py +++ b/setup.py @@ -14,7 +14,7 @@ plugin_package = "octoprint_enclosure" plugin_name = "OctoPrint-Enclosure" # The plugin's version. Can be overwritten within OctoPrint's internal data via __plugin_version__ in the plugin module -plugin_version = "4.12" +plugin_version = "4.13" # The plugin's description. Can be overwritten within OctoPrint's internal data via __plugin_description__ in the plugin # module -- 2.39.5 From 01e727cb94fc104e3b96e4f27a47aee917ec57fb Mon Sep 17 00:00:00 2001 From: munzli Date: Sun, 29 Sep 2019 19:00:31 +0200 Subject: [PATCH 38/52] configurable sensor address for mcp9808 --- octoprint_enclosure/__init__.py | 6 +++--- octoprint_enclosure/mcp9808.py | 18 ++++++++++++------ 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 54b16c0..51165b7 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -513,7 +513,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP temp = self.read_max31855_temp(sensor['temp_sensor_address']) hum = 0 elif sensor['temp_sensor_type'] == "mcp9808": - temp = self.read_mcp_temp() + temp = self.read_mcp_temp(sensor['temp_sensor_address']) hum = 0 else: self._logger.info("temp_sensor_type no match") @@ -559,10 +559,10 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP return return_value, return_value - def read_mcp_temp(self): + def read_mcp_temp(self, address): try: script = os.path.dirname(os.path.realpath(__file__)) + "/mcp9808.py" - args = ["python", script] + args = ["python", script, str(address)] if self._settings.get(["debug_temperature_log"]) is True: self._logger.debug("Temperature MCP9808 cmd: %s", " ".join(args)) proc = Popen(args, stdout=PIPE) diff --git a/octoprint_enclosure/mcp9808.py b/octoprint_enclosure/mcp9808.py index d324b47..672045b 100644 --- a/octoprint_enclosure/mcp9808.py +++ b/octoprint_enclosure/mcp9808.py @@ -1,3 +1,4 @@ +import sys import smbus # default I2C address for device. @@ -27,24 +28,29 @@ MCP9808_REG_CONFIG_ALERTMODE = 0x0001 def main(): + # get bus address if provided or use default address + address = MCP9808_I2CADDR_DEFAULT + if len(sys.argv) == 2: + address = int(sys.argv[1], 16) + # get I2C bus bus = smbus.SMBus(1) - # MCP9808 address, 0x18(24) + # MCP9808 address, default 0x18(24) # configuration register, 0x01(1) # continuous conversion mode, power-up default config = [MCP9808_REG_CONFIG_CONTCONV, 0x00] - bus.write_i2c_block_data(MCP9808_I2CADDR_DEFAULT, MCP9808_REG_CONFIG, config) + bus.write_i2c_block_data(address, MCP9808_REG_CONFIG, config) - # MCP9808 address, 0x18(24) + # MCP9808 address, default 0x18(24) # select resolution rgister, 0x08(8) # resolution = +0.0625 / C, 0x03(03) - bus.write_byte_data(MCP9808_I2CADDR_DEFAULT, MCP9808_REG_RESOLUTION, 0x03) + bus.write_byte_data(address, MCP9808_REG_RESOLUTION, 0x03) - # MCP9808 address, 0x18(24) + # MCP9808 address, default 0x18(24) # read data back from 0x05(5), 2 bytes # temp MSB, TEMP LSB - data = bus.read_i2c_block_data(MCP9808_I2CADDR_DEFAULT, MCP9808_REG_AMBIENT_TEMP, 2) + data = bus.read_i2c_block_data(address, MCP9808_REG_AMBIENT_TEMP, 2) # convert the data to 13-bits ctemp = ((data[0] & 0x1F) * 256) + data[1] -- 2.39.5 From e8237841dd3966c75541a170400c78a644bd98f9 Mon Sep 17 00:00:00 2001 From: UnchartedBull Date: Tue, 8 Oct 2019 23:28:27 +0200 Subject: [PATCH 39/52] Add Temperature GET API --- octoprint_enclosure/__init__.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 9c1fc94..103d176 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -174,6 +174,18 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP gpio_status.append(dict(index_id=index, status=val)) return flask.Response(json.dumps(gpio_status), mimetype='application/json') + @octoprint.plugin.BlueprintPlugin.route("/getTemperatureStatus", methods=["GET"]) + def get_temperature_status(self): + temperature_status = [] + for rpi_input in self.rpi_input: + if rpi_input['input_type'] == 'temperature_sensor': + temperature = self.to_int(rpi_input['temp_sensor_temp']) + humidity = self.to_int(rpi_input['temp_sensor_humidity']) + index = self.to_int(rpi_input['index_id']) + label = rpi_input['label'] + temperature_status.append(dict(index_id=index, label=label, temperature=temperature, humidity=humidity)) + return flask.Response(json.dumps(temperature_status), mimetype='application/json') + @octoprint.plugin.BlueprintPlugin.route("/setIO", methods=["GET"]) def set_io(self): index = flask.request.values["index_id"] -- 2.39.5 From 0983363b5f7c8a383cb179a0fb9285b0fd85aa2e Mon Sep 17 00:00:00 2001 From: Timon G Date: Wed, 9 Oct 2019 00:38:50 +0200 Subject: [PATCH 40/52] Update setup.py --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 54921de..71166b0 100644 --- a/setup.py +++ b/setup.py @@ -14,7 +14,7 @@ plugin_package = "octoprint_enclosure" plugin_name = "OctoPrint-Enclosure" # The plugin's version. Can be overwritten within OctoPrint's internal data via __plugin_version__ in the plugin module -plugin_version = "4.12" +plugin_version = "4.13" # The plugin's description. Can be overwritten within OctoPrint's internal data via __plugin_description__ in the plugin # module -- 2.39.5 From 5798beeeec51860a45a4aaed6478e646813a0cdc Mon Sep 17 00:00:00 2001 From: UnchartedBull Date: Wed, 9 Oct 2019 13:59:51 +0200 Subject: [PATCH 41/52] first draft for kind of RESTful API --- octoprint_enclosure/__init__.py | 62 +++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 22 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 103d176..e786d5d 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -142,6 +142,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.rpi_inputs = self._settings.get(["rpi_inputs"]) # ~~ Blueprintplugin mixin + ## POST /temperature/$id + ## maybe PATCH will be the more official way to do. Feedback? @octoprint.plugin.BlueprintPlugin.route("/setEnclosureTempHum", methods=["GET"]) def set_enclosure_temp_humidity(self): set_value = self.to_float(flask.request.values["set_temperature"]) @@ -153,27 +155,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.handle_temp_hum_control() return flask.jsonify(success=True) - @octoprint.plugin.BlueprintPlugin.route("/clearGPIOMode", methods=["GET"]) - def clear_gpio_mode(self): - GPIO.cleanup() - return flask.jsonify(success=True) - - @octoprint.plugin.BlueprintPlugin.route("/updateUI", methods=["GET"]) - def update_ui_requested(self): - self.update_ui() - return flask.jsonify(success=True) - - @octoprint.plugin.BlueprintPlugin.route("/getOutputStatus", methods=["GET"]) - def get_output_status(self): - gpio_status = [] - for rpi_output in self.rpi_outputs: - if rpi_output['output_type'] == 'regular': - pin = self.to_int(rpi_output['gpio_pin']) - val = GPIO.input(pin) if not rpi_output['active_low'] else (not GPIO.input(pin)) - index = self.to_int(rpi_output['index_id']) - gpio_status.append(dict(index_id=index, status=val)) - return flask.Response(json.dumps(gpio_status), mimetype='application/json') - + ## GET /temperature/$id might as well also GET /temperature @octoprint.plugin.BlueprintPlugin.route("/getTemperatureStatus", methods=["GET"]) def get_temperature_status(self): temperature_status = [] @@ -186,6 +168,32 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP temperature_status.append(dict(index_id=index, label=label, temperature=temperature, humidity=humidity)) return flask.Response(json.dumps(temperature_status), mimetype='application/json') + ## POST /clear + @octoprint.plugin.BlueprintPlugin.route("/clearGPIOMode", methods=["GET"]) + def clear_gpio_mode(self): + GPIO.cleanup() + return flask.jsonify(success=True) + + ## POST /update + @octoprint.plugin.BlueprintPlugin.route("/updateUI", methods=["GET"]) + def update_ui_requested(self): + self.update_ui() + return flask.jsonify(success=True) + + ## GET /output/$id might as well also GET /output + @octoprint.plugin.BlueprintPlugin.route("/getOutputStatus", methods=["GET"]) + def get_output_status(self): + gpio_status = [] + for rpi_output in self.rpi_outputs: + if rpi_output['output_type'] == 'regular': + pin = self.to_int(rpi_output['gpio_pin']) + val = GPIO.input(pin) if not rpi_output['active_low'] else (not GPIO.input(pin)) + index = self.to_int(rpi_output['index_id']) + gpio_status.append(dict(index_id=index, status=val)) + return flask.Response(json.dumps(gpio_status), mimetype='application/json') + + ## POST /output/$id + ## maybe PATCH will be the more official way to do. Feedback? @octoprint.plugin.BlueprintPlugin.route("/setIO", methods=["GET"]) def set_io(self): index = flask.request.values["index_id"] @@ -196,6 +204,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.write_gpio(self.to_int(rpi_output['gpio_pin']), val) return flask.jsonify(success=True) + ## POST /shell @octoprint.plugin.BlueprintPlugin.route("/sendShellCommand", methods=["GET"]) def send_shell_command(self): output_index = self.to_int(flask.request.values["index_id"]) @@ -206,6 +215,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.shell_command(command) return flask.jsonify(success=True) + ## Possibly include this into POST/PATCH /output/$id and make it into the JSON body? + ## or maybe PATCH/POST /output/$id/auto-startup @octoprint.plugin.BlueprintPlugin.route("/setAutoStartUp", methods=["GET"]) def set_auto_startup(self): index = flask.request.values["index_id"] @@ -222,6 +233,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self._settings.set(["rpi_outputs"], self.rpi_outputs) return flask.jsonify(success=True) + ## same as AutoStartup? @octoprint.plugin.BlueprintPlugin.route("/setAutoShutdown", methods=["GET"]) def set_auto_shutdown(self): index = flask.request.values["index_id"] @@ -239,6 +251,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self._settings.set(["rpi_outputs"], self.rpi_outputs) return flask.jsonify(success=True) + ## POST filament/$id + ## maybe think of a GET for this as well @octoprint.plugin.BlueprintPlugin.route("/setFilamentSensor", methods=["GET"]) def set_filament_sensor(self): index = flask.request.values["index_id"] @@ -250,6 +264,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self._settings.set(["rpi_inputs"], self.rpi_inputs) return flask.jsonify(success=True) + ## POST pwm/$id @octoprint.plugin.BlueprintPlugin.route("/setPWM", methods=["GET"]) def set_pwm(self): set_value = self.to_int(flask.request.values["new_duty_cycle"]) @@ -261,6 +276,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.write_pwm(gpio, set_value) return flask.jsonify(success=True) + ## POST gcode/$id + ## I think id might not even be needed here @octoprint.plugin.BlueprintPlugin.route("/sendGcodeCommand", methods=["GET"]) def requested_gcode_command(self): gpio_index = self.to_int(flask.request.values["index_id"]) @@ -268,6 +285,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.send_gcode_command(rpi_output['gcode']) return flask.jsonify(success=True) + ## POST neopixel/$id @octoprint.plugin.BlueprintPlugin.route("/setNeopixel", methods=["GET"]) def set_neopixel(self): """ set_neopixel method get request from octoprint and send the command to arduino or neopixel""" @@ -288,6 +306,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP return flask.jsonify(success=True) + ## POST rgb-led/$id @octoprint.plugin.BlueprintPlugin.route("/setLedstripColor", methods=["GET"]) def set_ledstrip_color(self): """ set_ledstrip_color method get request from octoprint and send the command to Open-Smart RGB LED Strip""" @@ -1363,7 +1382,6 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP queue_id = '{0!s}_{1!s}'.format(index_id, sufix) - self._logger.debug("Scheduling neopixel output id %s for on %s delay_seconds", queue_id, delay_seconds) thread = threading.Timer(delay_seconds, self.send_neopixel_command, -- 2.39.5 From 5023e08c77574a18b0039634629b244ac44569d1 Mon Sep 17 00:00:00 2001 From: UnchartedBull Date: Wed, 9 Oct 2019 15:04:04 +0200 Subject: [PATCH 42/52] started changing first apis --- .gitignore | 2 + octoprint_enclosure/__init__.py | 228 ++++++++++++++++++++++++++++++-- 2 files changed, 219 insertions(+), 11 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e75ccaa --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +venv +.vscode diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index e786d5d..c49f0cf 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -7,6 +7,8 @@ from .ledstrip import LEDStrip import octoprint.plugin import RPi.GPIO as GPIO import flask +from flask import jsonify, request, make_response, Response +from werkzeug.exceptions import BadRequest import time import sys import glob @@ -159,7 +161,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP @octoprint.plugin.BlueprintPlugin.route("/getTemperatureStatus", methods=["GET"]) def get_temperature_status(self): temperature_status = [] - for rpi_input in self.rpi_input: + for rpi_input in self.rpi_inputs: if rpi_input['input_type'] == 'temperature_sensor': temperature = self.to_int(rpi_input['temp_sensor_temp']) humidity = self.to_int(rpi_input['temp_sensor_humidity']) @@ -253,8 +255,211 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP ## POST filament/$id ## maybe think of a GET for this as well + @octoprint.plugin.BlueprintPlugin.route("/filament/", methods=["PATCH"]) + def set_filament_sensor(self, identifier): + if "application/json" not in request.headers["Content-Type"]: + return make_response("expected json", 400) + try: + data = request.json + except BadRequest: + return make_response("malformed request", 400) + + if 'status' not in data: + return make_response("missing status attribute", 406) + + value = data["status"] + + for sensor in self.rpi_inputs: + if identifier == self.to_int(sensor['index_id']): + sensor['filament_sensor_enabled'] = value + self._logger.info("Setting filament sensor for input %s to : %s", identifier, value) + self._settings.set(["rpi_inputs"], self.rpi_inputs) + return make_response('', 204) + + @octoprint.plugin.BlueprintPlugin.route("/filament/", methods=["GET"]) + def get_filament_sensor(self, identifier): + for sensor in self.rpi_inputs: + if identifier == self.to_int(sensor['index_id']): + return jsonify(sensor) + return make_response('', 404) + + @octoprint.plugin.BlueprintPlugin.route("/pwm/", methods=["PATCH"]) + def set_pwm(self, identifier): + if "application/json" not in request.headers["Content-Type"]: + return make_response("expected json", 400) + try: + data = request.json + except BadRequest: + return make_response("malformed request", 400) + + if 'dutyCycle' not in data: + return make_response("missing dutyCycle attribute", 406) + + set_value = self.to_int(data['dutyCycle']) + for rpi_output in [item for item in self.rpi_outputs if item['index_id'] == identifier]: + rpi_output['duty_cycle'] = set_value + rpi_output['new_duty_cycle'] = "" + gpio = self.to_int(rpi_output['gpio_pin']) + self.write_pwm(gpio, set_value) + return make_response('', 204) + + @octoprint.plugin.BlueprintPlugin.route("/gcode/", methods=["POST"]) + def requested_gcode_command(self, identifier): + rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == identifier].pop() + self.send_gcode_command(rpi_output['gcode']) + return make_response('', 204) + + @octoprint.plugin.BlueprintPlugin.route("/neopixel/", methods=["PATCH"]) + def set_neopixel(self, identifier): + """ set_neopixel method get request from octoprint and send the command to arduino or neopixel""" + if "application/json" not in request.headers["Content-Type"]: + return make_response("expected json", 400) + try: + data = request.json + except BadRequest: + return make_response("malformed request", 400) + + if 'red' not in data: + return make_response("missing red attribute", 406) + if 'green' not in data: + return make_response("missing green attribute", 406) + if 'blue' not in data: + return make_response("missing blue attribute", 406) + + red = data['red'] + green = data['green'] + blue = data['blue'] + + for rpi_output in self.rpi_outputs: + if identifier == self.to_int(rpi_output['index_id']): + led_count = rpi_output['neopixel_count'] + led_brightness = rpi_output['neopixel_brightness'] + address = rpi_output['microcontroller_address'] + + neopixel_dirrect = rpi_output['output_type'] == 'neopixel_direct' + + self.send_neopixel_command(self.to_int(rpi_output['gpio_pin']), led_count, led_brightness, red, green, + blue, address, neopixel_dirrect, identifier) + + return make_response('', 204) + + @octoprint.plugin.BlueprintPlugin.route("/rgb-led/", methods=["PATCH"]) + def set_ledstrip_color(self, identifier): + """ set_ledstrip_color method get request from octoprint and send the command to Open-Smart RGB LED Strip""" + if "application/json" not in request.headers["Content-Type"]: + return make_response("expected json", 400) + try: + data = request.json + except BadRequest: + return make_response("malformed request", 400) + + if 'rgb' not in data: + return make_response("missing rgb attribute", 406) + rgb = data['rgb'] + + for rpi_output in self.rpi_outputs: + if identifier == self.to_int(rpi_output['index_id']): + self.ledstrip_set_rgb(rpi_output, rgb) + + return make_response('', 204) + + + + + + """ + DEPRECATION + This API will be deprecated in a future version + """ + + # ~~ Blueprintplugin mixin + @octoprint.plugin.BlueprintPlugin.route("/setEnclosureTempHum", methods=["GET"]) + def set_enclosure_temp_humidity_old(self): + set_value = self.to_float(flask.request.values["set_temperature"]) + index_id = self.to_int(flask.request.values["index_id"]) + + for temp_hum_control in [item for item in self.rpi_outputs if item['index_id'] == index_id]: + temp_hum_control['temp_ctr_set_value'] = set_value + + self.handle_temp_hum_control() + return flask.jsonify(success=True) + + @octoprint.plugin.BlueprintPlugin.route("/clearGPIOMode", methods=["GET"]) + def clear_gpio_mode_old(self): + GPIO.cleanup() + return flask.jsonify(success=True) + + @octoprint.plugin.BlueprintPlugin.route("/updateUI", methods=["GET"]) + def update_ui_requested_old(self): + self.update_ui() + return flask.jsonify(success=True) + + @octoprint.plugin.BlueprintPlugin.route("/getOutputStatus", methods=["GET"]) + def get_output_status_old(self): + gpio_status = [] + for rpi_output in self.rpi_outputs: + if rpi_output['output_type'] == 'regular': + pin = self.to_int(rpi_output['gpio_pin']) + val = GPIO.input(pin) if not rpi_output['active_low'] else (not GPIO.input(pin)) + index = self.to_int(rpi_output['index_id']) + gpio_status.append(dict(index_id=index, status=val)) + return flask.Response(json.dumps(gpio_status), mimetype='application/json') + + @octoprint.plugin.BlueprintPlugin.route("/setIO", methods=["GET"]) + def set_io_old(self): + index = flask.request.values["index_id"] + value = True if flask.request.values["status"] == 'true' else False + for rpi_output in self.rpi_outputs: + if self.to_int(index) == self.to_int(rpi_output['index_id']): + val = (not value) if rpi_output['active_low'] else value + self.write_gpio(self.to_int(rpi_output['gpio_pin']), val) + return flask.jsonify(success=True) + + @octoprint.plugin.BlueprintPlugin.route("/sendShellCommand", methods=["GET"]) + def send_shell_command_old(self): + output_index = self.to_int(flask.request.values["index_id"]) + + rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == output_index].pop() + + command = rpi_output['shell_script'] + self.shell_command(command) + return flask.jsonify(success=True) + + @octoprint.plugin.BlueprintPlugin.route("/setAutoStartUp", methods=["GET"]) + def set_auto_startup_old(self): + index = flask.request.values["index_id"] + value = True if flask.request.values["status"] == 'true' else False + + if not value: + suffix = 'auto_startup' + queue_id = '{0!s}_{1!s}'.format(index, suffix) + self.stop_queue_item(queue_id) + for output in self.rpi_outputs: + if self.to_int(index) == self.to_int(output['index_id']): + output['auto_startup'] = value + self._logger.info("Setting auto startup for output %s to : %s", index, value) + self._settings.set(["rpi_outputs"], self.rpi_outputs) + return flask.jsonify(success=True) + + @octoprint.plugin.BlueprintPlugin.route("/setAutoShutdown", methods=["GET"]) + def set_auto_shutdown_old(self): + index = flask.request.values["index_id"] + value = True if flask.request.values["status"] == 'true' else False + + if not value: + suffix = 'auto_shutdown' + queue_id = '{0!s}_{1!s}'.format(index, suffix) + self.stop_queue_item(queue_id) + + for output in self.rpi_outputs: + if self.to_int(index) == self.to_int(output['index_id']): + output['auto_shutdown'] = value + self._logger.info("Setting auto shutdown for output %s to : %s", index, value) + self._settings.set(["rpi_outputs"], self.rpi_outputs) + return flask.jsonify(success=True) + @octoprint.plugin.BlueprintPlugin.route("/setFilamentSensor", methods=["GET"]) - def set_filament_sensor(self): + def set_filament_sensor_old(self): index = flask.request.values["index_id"] value = True if flask.request.values["status"] == 'true' else False for sensor in self.rpi_inputs: @@ -264,9 +469,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self._settings.set(["rpi_inputs"], self.rpi_inputs) return flask.jsonify(success=True) - ## POST pwm/$id @octoprint.plugin.BlueprintPlugin.route("/setPWM", methods=["GET"]) - def set_pwm(self): + def set_pwm_old(self): set_value = self.to_int(flask.request.values["new_duty_cycle"]) index_id = self.to_int(flask.request.values["index_id"]) for rpi_output in [item for item in self.rpi_outputs if item['index_id'] == index_id]: @@ -276,18 +480,15 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.write_pwm(gpio, set_value) return flask.jsonify(success=True) - ## POST gcode/$id - ## I think id might not even be needed here @octoprint.plugin.BlueprintPlugin.route("/sendGcodeCommand", methods=["GET"]) - def requested_gcode_command(self): + def requested_gcode_command_old(self): gpio_index = self.to_int(flask.request.values["index_id"]) rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == gpio_index].pop() self.send_gcode_command(rpi_output['gcode']) return flask.jsonify(success=True) - ## POST neopixel/$id @octoprint.plugin.BlueprintPlugin.route("/setNeopixel", methods=["GET"]) - def set_neopixel(self): + def set_neopixel_old(self): """ set_neopixel method get request from octoprint and send the command to arduino or neopixel""" gpio_index = self.to_int(flask.request.values["index_id"]) red = flask.request.values["red"] @@ -306,9 +507,8 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP return flask.jsonify(success=True) - ## POST rgb-led/$id @octoprint.plugin.BlueprintPlugin.route("/setLedstripColor", methods=["GET"]) - def set_ledstrip_color(self): + def set_ledstrip_color_old(self): """ set_ledstrip_color method get request from octoprint and send the command to Open-Smart RGB LED Strip""" gpio_index = self.to_int(flask.request.values["index_id"]) rgb = flask.request.values["rgb"] @@ -318,6 +518,12 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP return flask.jsonify(success=True) + # DEPREACTION END + + + + + def send_neopixel_command(self, led_pin, led_count, led_brightness, red, green, blue, address, neopixel_dirrect, index_id, queue_id=None): """Send neopixel command -- 2.39.5 From 0601d165591fb844976a70fe5e9f8f42e4bcec33 Mon Sep 17 00:00:00 2001 From: UnchartedBull Date: Wed, 9 Oct 2019 17:11:33 +0200 Subject: [PATCH 43/52] rewrote API to be kind of RESTful --- octoprint_enclosure/__init__.py | 247 ++++++++++++++++++-------------- 1 file changed, 142 insertions(+), 105 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index c49f0cf..7dc784d 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -144,46 +144,56 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.rpi_inputs = self._settings.get(["rpi_inputs"]) # ~~ Blueprintplugin mixin - ## POST /temperature/$id - ## maybe PATCH will be the more official way to do. Feedback? - @octoprint.plugin.BlueprintPlugin.route("/setEnclosureTempHum", methods=["GET"]) - def set_enclosure_temp_humidity(self): - set_value = self.to_float(flask.request.values["set_temperature"]) - index_id = self.to_int(flask.request.values["index_id"]) - - for temp_hum_control in [item for item in self.rpi_outputs if item['index_id'] == index_id]: - temp_hum_control['temp_ctr_set_value'] = set_value - - self.handle_temp_hum_control() - return flask.jsonify(success=True) - - ## GET /temperature/$id might as well also GET /temperature - @octoprint.plugin.BlueprintPlugin.route("/getTemperatureStatus", methods=["GET"]) + @octoprint.plugin.BlueprintPlugin.route("/temperature", methods=["GET"]) def get_temperature_status(self): temperature_status = [] for rpi_input in self.rpi_inputs: if rpi_input['input_type'] == 'temperature_sensor': - temperature = self.to_int(rpi_input['temp_sensor_temp']) - humidity = self.to_int(rpi_input['temp_sensor_humidity']) + temperature = self.to_float(rpi_input['temp_sensor_temp']) + humidity = self.to_float(rpi_input['temp_sensor_humidity']) index = self.to_int(rpi_input['index_id']) label = rpi_input['label'] temperature_status.append(dict(index_id=index, label=label, temperature=temperature, humidity=humidity)) - return flask.Response(json.dumps(temperature_status), mimetype='application/json') + return jsonify(temperature_status) - ## POST /clear - @octoprint.plugin.BlueprintPlugin.route("/clearGPIOMode", methods=["GET"]) + @octoprint.plugin.BlueprintPlugin.route("/temperature/", methods=["GET"]) + def get_single_temperature_status(self, identifier): + for rpi_input in self.rpi_inputs: + if identifier == self.to_int(rpi_input['index_id']): + return jsonify(rpi_input) + return make_response('', 404) + + @octoprint.plugin.BlueprintPlugin.route("/temperature/", methods=["PATCH"]) + def set_enclosure_temp_humidity(self, identifier): + if "application/json" not in request.headers["Content-Type"]: + return make_response("expected json", 400) + try: + data = request.json + except BadRequest: + return make_response("malformed request", 400) + + if 'temperature' not in data: + return make_response("missing temperature attribute", 406) + + set_value = data["temperature"] + + for temp_hum_control in [item for item in self.rpi_outputs if item['index_id'] == identifier]: + temp_hum_control['temp_ctr_set_value'] = set_value + + self.handle_temp_hum_control() + return make_response('', 204) + + @octoprint.plugin.BlueprintPlugin.route("/clear-gpio", methods=["POST"]) def clear_gpio_mode(self): GPIO.cleanup() - return flask.jsonify(success=True) + return make_response('', 204) - ## POST /update - @octoprint.plugin.BlueprintPlugin.route("/updateUI", methods=["GET"]) + @octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"]) def update_ui_requested(self): self.update_ui() - return flask.jsonify(success=True) + return make_response('', 204) - ## GET /output/$id might as well also GET /output - @octoprint.plugin.BlueprintPlugin.route("/getOutputStatus", methods=["GET"]) + @octoprint.plugin.BlueprintPlugin.route("/output", methods=["GET"]) def get_output_status(self): gpio_status = [] for rpi_output in self.rpi_outputs: @@ -192,69 +202,103 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP val = GPIO.input(pin) if not rpi_output['active_low'] else (not GPIO.input(pin)) index = self.to_int(rpi_output['index_id']) gpio_status.append(dict(index_id=index, status=val)) - return flask.Response(json.dumps(gpio_status), mimetype='application/json') + return jsonify(gpio_status) - ## POST /output/$id - ## maybe PATCH will be the more official way to do. Feedback? - @octoprint.plugin.BlueprintPlugin.route("/setIO", methods=["GET"]) - def set_io(self): - index = flask.request.values["index_id"] - value = True if flask.request.values["status"] == 'true' else False + @octoprint.plugin.BlueprintPlugin.route("/output/", methods=["GET"]) + def get_single_output_status(self, identifier): for rpi_output in self.rpi_outputs: - if self.to_int(index) == self.to_int(rpi_output['index_id']): + if identifier == self.to_int(rpi_output['index_id']): + return jsonify(rpi_output) + return make_response('', 404) + + @octoprint.plugin.BlueprintPlugin.route("/output/", methods=["PATCH"]) + def set_io(self, identifier): + if "application/json" not in request.headers["Content-Type"]: + return make_response("expected json", 400) + try: + data = request.json + except BadRequest: + return make_response("malformed request", 400) + + if 'status' not in data: + return make_response("missing status attribute", 406) + + value = data["status"] + + for rpi_output in self.rpi_outputs: + if identifier == self.to_int(rpi_output['index_id']): val = (not value) if rpi_output['active_low'] else value self.write_gpio(self.to_int(rpi_output['gpio_pin']), val) - return flask.jsonify(success=True) + return make_response('', 204) - ## POST /shell - @octoprint.plugin.BlueprintPlugin.route("/sendShellCommand", methods=["GET"]) - def send_shell_command(self): - output_index = self.to_int(flask.request.values["index_id"]) - - rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == output_index].pop() + @octoprint.plugin.BlueprintPlugin.route("/shell/", methods=["POST"]) + def send_shell_command(self, identifier): + rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == identifier].pop() command = rpi_output['shell_script'] self.shell_command(command) - return flask.jsonify(success=True) + return make_response('', 204) - ## Possibly include this into POST/PATCH /output/$id and make it into the JSON body? - ## or maybe PATCH/POST /output/$id/auto-startup - @octoprint.plugin.BlueprintPlugin.route("/setAutoStartUp", methods=["GET"]) - def set_auto_startup(self): - index = flask.request.values["index_id"] - value = True if flask.request.values["status"] == 'true' else False + @octoprint.plugin.BlueprintPlugin.route("/output//auto-startup", methods=["PATCH"]) + def set_auto_startup(self, identifier): + if "application/json" not in request.headers["Content-Type"]: + return make_response("expected json", 400) + try: + data = request.json + except BadRequest: + return make_response("malformed request", 400) + + if 'status' not in data: + return make_response("missing status attribute", 406) + + value = data["status"] if not value: suffix = 'auto_startup' - queue_id = '{0!s}_{1!s}'.format(index, suffix) + queue_id = '{0!s}_{1!s}'.format(str(identifier), suffix) self.stop_queue_item(queue_id) for output in self.rpi_outputs: - if self.to_int(index) == self.to_int(output['index_id']): + if identifier == self.to_int(output['index_id']): output['auto_startup'] = value - self._logger.info("Setting auto startup for output %s to : %s", index, value) + self._logger.info("Setting auto startup for output %s to : %s", str(identifier), value) self._settings.set(["rpi_outputs"], self.rpi_outputs) - return flask.jsonify(success=True) + return make_response('', 204) - ## same as AutoStartup? - @octoprint.plugin.BlueprintPlugin.route("/setAutoShutdown", methods=["GET"]) - def set_auto_shutdown(self): - index = flask.request.values["index_id"] - value = True if flask.request.values["status"] == 'true' else False + @octoprint.plugin.BlueprintPlugin.route("/output//auto-shutdown", methods=["PATCH"]) + def set_auto_shutdown(self, identifier): + if "application/json" not in request.headers["Content-Type"]: + return make_response("expected json", 400) + try: + data = request.json + except BadRequest: + return make_response("malformed request", 400) + + if 'status' not in data: + return make_response("missing status attribute", 406) + + value = data["status"] if not value: suffix = 'auto_shutdown' - queue_id = '{0!s}_{1!s}'.format(index, suffix) + queue_id = '{0!s}_{1!s}'.format(str(identifier), suffix) self.stop_queue_item(queue_id) for output in self.rpi_outputs: - if self.to_int(index) == self.to_int(output['index_id']): + if identifier == self.to_int(output['index_id']): output['auto_shutdown'] = value - self._logger.info("Setting auto shutdown for output %s to : %s", index, value) + self._logger.info("Setting auto shutdown for output %s to : %s", str(identifier), value) self._settings.set(["rpi_outputs"], self.rpi_outputs) - return flask.jsonify(success=True) + return make_response('', 204) + + @octoprint.plugin.BlueprintPlugin.route("/filament/", methods=["GET"]) + def get_filament_sensor(self, identifier): + for sensor in self.rpi_inputs: + if identifier == self.to_int(sensor['index_id']): + return jsonify(sensor) + return make_response('', 404) + + # TODO: maybe get all filament sensors via GET /filament. What would be they correct type here? - ## POST filament/$id - ## maybe think of a GET for this as well @octoprint.plugin.BlueprintPlugin.route("/filament/", methods=["PATCH"]) def set_filament_sensor(self, identifier): if "application/json" not in request.headers["Content-Type"]: @@ -272,17 +316,10 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP for sensor in self.rpi_inputs: if identifier == self.to_int(sensor['index_id']): sensor['filament_sensor_enabled'] = value - self._logger.info("Setting filament sensor for input %s to : %s", identifier, value) + self._logger.info("Setting filament sensor for input %s to : %s", str(identifier), value) self._settings.set(["rpi_inputs"], self.rpi_inputs) return make_response('', 204) - @octoprint.plugin.BlueprintPlugin.route("/filament/", methods=["GET"]) - def get_filament_sensor(self, identifier): - for sensor in self.rpi_inputs: - if identifier == self.to_int(sensor['index_id']): - return jsonify(sensor) - return make_response('', 404) - @octoprint.plugin.BlueprintPlugin.route("/pwm/", methods=["PATCH"]) def set_pwm(self, identifier): if "application/json" not in request.headers["Content-Type"]: @@ -375,24 +412,24 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP # ~~ Blueprintplugin mixin @octoprint.plugin.BlueprintPlugin.route("/setEnclosureTempHum", methods=["GET"]) def set_enclosure_temp_humidity_old(self): - set_value = self.to_float(flask.request.values["set_temperature"]) - index_id = self.to_int(flask.request.values["index_id"]) + set_value = self.to_float(request.values["set_temperature"]) + index_id = self.to_int(request.values["index_id"]) for temp_hum_control in [item for item in self.rpi_outputs if item['index_id'] == index_id]: temp_hum_control['temp_ctr_set_value'] = set_value self.handle_temp_hum_control() - return flask.jsonify(success=True) + return jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/clearGPIOMode", methods=["GET"]) def clear_gpio_mode_old(self): GPIO.cleanup() - return flask.jsonify(success=True) + return jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/updateUI", methods=["GET"]) def update_ui_requested_old(self): self.update_ui() - return flask.jsonify(success=True) + return jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/getOutputStatus", methods=["GET"]) def get_output_status_old(self): @@ -403,32 +440,32 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP val = GPIO.input(pin) if not rpi_output['active_low'] else (not GPIO.input(pin)) index = self.to_int(rpi_output['index_id']) gpio_status.append(dict(index_id=index, status=val)) - return flask.Response(json.dumps(gpio_status), mimetype='application/json') + return Response(json.dumps(gpio_status), mimetype='application/json') @octoprint.plugin.BlueprintPlugin.route("/setIO", methods=["GET"]) def set_io_old(self): - index = flask.request.values["index_id"] - value = True if flask.request.values["status"] == 'true' else False + index = request.values["index_id"] + value = True if request.values["status"] == 'true' else False for rpi_output in self.rpi_outputs: if self.to_int(index) == self.to_int(rpi_output['index_id']): val = (not value) if rpi_output['active_low'] else value self.write_gpio(self.to_int(rpi_output['gpio_pin']), val) - return flask.jsonify(success=True) + return jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/sendShellCommand", methods=["GET"]) def send_shell_command_old(self): - output_index = self.to_int(flask.request.values["index_id"]) + output_index = self.to_int(request.values["index_id"]) rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == output_index].pop() command = rpi_output['shell_script'] self.shell_command(command) - return flask.jsonify(success=True) + return jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/setAutoStartUp", methods=["GET"]) def set_auto_startup_old(self): - index = flask.request.values["index_id"] - value = True if flask.request.values["status"] == 'true' else False + index = request.values["index_id"] + value = True if request.values["status"] == 'true' else False if not value: suffix = 'auto_startup' @@ -439,12 +476,12 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP output['auto_startup'] = value self._logger.info("Setting auto startup for output %s to : %s", index, value) self._settings.set(["rpi_outputs"], self.rpi_outputs) - return flask.jsonify(success=True) + return jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/setAutoShutdown", methods=["GET"]) def set_auto_shutdown_old(self): - index = flask.request.values["index_id"] - value = True if flask.request.values["status"] == 'true' else False + index = request.values["index_id"] + value = True if request.values["status"] == 'true' else False if not value: suffix = 'auto_shutdown' @@ -456,44 +493,44 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP output['auto_shutdown'] = value self._logger.info("Setting auto shutdown for output %s to : %s", index, value) self._settings.set(["rpi_outputs"], self.rpi_outputs) - return flask.jsonify(success=True) + return jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/setFilamentSensor", methods=["GET"]) def set_filament_sensor_old(self): - index = flask.request.values["index_id"] - value = True if flask.request.values["status"] == 'true' else False + index = request.values["index_id"] + value = True if request.values["status"] == 'true' else False for sensor in self.rpi_inputs: if self.to_int(index) == self.to_int(sensor['index_id']): sensor['filament_sensor_enabled'] = value self._logger.info("Setting filament sensor for input %s to : %s", index, value) self._settings.set(["rpi_inputs"], self.rpi_inputs) - return flask.jsonify(success=True) + return jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/setPWM", methods=["GET"]) def set_pwm_old(self): - set_value = self.to_int(flask.request.values["new_duty_cycle"]) - index_id = self.to_int(flask.request.values["index_id"]) + set_value = self.to_int(request.values["new_duty_cycle"]) + index_id = self.to_int(request.values["index_id"]) for rpi_output in [item for item in self.rpi_outputs if item['index_id'] == index_id]: rpi_output['duty_cycle'] = set_value rpi_output['new_duty_cycle'] = "" gpio = self.to_int(rpi_output['gpio_pin']) self.write_pwm(gpio, set_value) - return flask.jsonify(success=True) + return jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/sendGcodeCommand", methods=["GET"]) def requested_gcode_command_old(self): - gpio_index = self.to_int(flask.request.values["index_id"]) + gpio_index = self.to_int(request.values["index_id"]) rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == gpio_index].pop() self.send_gcode_command(rpi_output['gcode']) - return flask.jsonify(success=True) + return jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/setNeopixel", methods=["GET"]) def set_neopixel_old(self): """ set_neopixel method get request from octoprint and send the command to arduino or neopixel""" - gpio_index = self.to_int(flask.request.values["index_id"]) - red = flask.request.values["red"] - green = flask.request.values["green"] - blue = flask.request.values["blue"] + gpio_index = self.to_int(request.values["index_id"]) + red = request.values["red"] + green = request.values["green"] + blue = request.values["blue"] for rpi_output in self.rpi_outputs: if gpio_index == self.to_int(rpi_output['index_id']): led_count = rpi_output['neopixel_count'] @@ -505,18 +542,18 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.send_neopixel_command(self.to_int(rpi_output['gpio_pin']), led_count, led_brightness, red, green, blue, address, neopixel_dirrect, gpio_index) - return flask.jsonify(success=True) + return jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/setLedstripColor", methods=["GET"]) def set_ledstrip_color_old(self): """ set_ledstrip_color method get request from octoprint and send the command to Open-Smart RGB LED Strip""" - gpio_index = self.to_int(flask.request.values["index_id"]) - rgb = flask.request.values["rgb"] + gpio_index = self.to_int(request.values["index_id"]) + rgb = request.values["rgb"] for rpi_output in self.rpi_outputs: if gpio_index == self.to_int(rpi_output['index_id']): self.ledstrip_set_rgb(rpi_output, rgb) - return flask.jsonify(success=True) + return jsonify(success=True) # DEPREACTION END @@ -1395,7 +1432,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self._logger.info("Error: Too many redirects") except requests.exceptions.RequestException as reqe: self._logger.info("Error: {e}".format(e=reqe)) - if res.status_code != requests.codes.ok: + if res.status_code != requests.codes['ok']: try: j = res.json() except ValueError: -- 2.39.5 From b62235af1581e211b7d960f4920feb826becc354 Mon Sep 17 00:00:00 2001 From: UnchartedBull Date: Wed, 9 Oct 2019 17:17:37 +0200 Subject: [PATCH 44/52] remove flask import --- octoprint_enclosure/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 7dc784d..50ae142 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -6,7 +6,6 @@ from subprocess import Popen, PIPE from .ledstrip import LEDStrip import octoprint.plugin import RPi.GPIO as GPIO -import flask from flask import jsonify, request, make_response, Response from werkzeug.exceptions import BadRequest import time -- 2.39.5 From 11897cdbbc5770c7bb4b875a3d4d2f12e9bc69fd Mon Sep 17 00:00:00 2001 From: UnchartedBull Date: Wed, 9 Oct 2019 22:28:17 +0200 Subject: [PATCH 45/52] Limit temperature outputs --- octoprint_enclosure/__init__.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 50ae142..3262fde 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -152,14 +152,25 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP humidity = self.to_float(rpi_input['temp_sensor_humidity']) index = self.to_int(rpi_input['index_id']) label = rpi_input['label'] - temperature_status.append(dict(index_id=index, label=label, temperature=temperature, humidity=humidity)) + temperature_status.append({'index_id': index, 'label': label, 'temperature': temperature, 'humidity': humidity}) return jsonify(temperature_status) @octoprint.plugin.BlueprintPlugin.route("/temperature/", methods=["GET"]) def get_single_temperature_status(self, identifier): for rpi_input in self.rpi_inputs: if identifier == self.to_int(rpi_input['index_id']): - return jsonify(rpi_input) + return jsonify({ + 'indexId': rpi_input['index_id'], + 'gpioPin': rpi_input['gpio_pin'], + 'type': rpi_input['temp_sensor_type'], + 'inputType': rpi_input['input_type'], + 'label': rpi_input['label'], + 'address': rpi_input['temp_sensor_address'], + 'humidity': self.to_float(rpi_input['temp_sensor_humidity']), + 'temperature': self.to_float(rpi_input['temp_sensor_temp']), + 'useFahrenheit': rpi_input['use_fahrenheit'], + 'showNavbar': rpi_input['temp_sensor_navbar'] + }) return make_response('', 404) @octoprint.plugin.BlueprintPlugin.route("/temperature/", methods=["PATCH"]) -- 2.39.5 From 6c36d4b924d26c0143b49d3aa9964af04b9da777 Mon Sep 17 00:00:00 2001 From: UnchartedBull Date: Wed, 9 Oct 2019 22:39:41 +0200 Subject: [PATCH 46/52] First idea for new API concept --- octoprint_enclosure/__init__.py | 32 ++++++++------------------------ 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 3262fde..1d3c76e 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -143,34 +143,18 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.rpi_inputs = self._settings.get(["rpi_inputs"]) # ~~ Blueprintplugin mixin - @octoprint.plugin.BlueprintPlugin.route("/temperature", methods=["GET"]) - def get_temperature_status(self): - temperature_status = [] + @octoprint.plugin.BlueprintPlugin.route("/input", methods=["GET"]) + def get_inputs(self): + inputs = [] for rpi_input in self.rpi_inputs: - if rpi_input['input_type'] == 'temperature_sensor': - temperature = self.to_float(rpi_input['temp_sensor_temp']) - humidity = self.to_float(rpi_input['temp_sensor_humidity']) - index = self.to_int(rpi_input['index_id']) - label = rpi_input['label'] - temperature_status.append({'index_id': index, 'label': label, 'temperature': temperature, 'humidity': humidity}) - return jsonify(temperature_status) + inputs.append(dict(index_id=rpi_input['index_id'], label=rpi_input['label'])) + return jsonify(inputs) - @octoprint.plugin.BlueprintPlugin.route("/temperature/", methods=["GET"]) - def get_single_temperature_status(self, identifier): + @octoprint.plugin.BlueprintPlugin.route("/input/", methods=["GET"]) + def get_input_status(self, identifier): for rpi_input in self.rpi_inputs: if identifier == self.to_int(rpi_input['index_id']): - return jsonify({ - 'indexId': rpi_input['index_id'], - 'gpioPin': rpi_input['gpio_pin'], - 'type': rpi_input['temp_sensor_type'], - 'inputType': rpi_input['input_type'], - 'label': rpi_input['label'], - 'address': rpi_input['temp_sensor_address'], - 'humidity': self.to_float(rpi_input['temp_sensor_humidity']), - 'temperature': self.to_float(rpi_input['temp_sensor_temp']), - 'useFahrenheit': rpi_input['use_fahrenheit'], - 'showNavbar': rpi_input['temp_sensor_navbar'] - }) + return jsonify(rpi_input) return make_response('', 404) @octoprint.plugin.BlueprintPlugin.route("/temperature/", methods=["PATCH"]) -- 2.39.5 From fad2581e016535009477f4bc45af21e9f8971890 Mon Sep 17 00:00:00 2001 From: UnchartedBull Date: Wed, 9 Oct 2019 23:16:01 +0200 Subject: [PATCH 47/52] should work now --- octoprint_enclosure/__init__.py | 99 ++++++++++++++++----------------- 1 file changed, 47 insertions(+), 52 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 1d3c76e..1203cf0 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -143,18 +143,20 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.rpi_inputs = self._settings.get(["rpi_inputs"]) # ~~ Blueprintplugin mixin - @octoprint.plugin.BlueprintPlugin.route("/input", methods=["GET"]) + @octoprint.plugin.BlueprintPlugin.route("/inputs", methods=["GET"]) def get_inputs(self): inputs = [] for rpi_input in self.rpi_inputs: - inputs.append(dict(index_id=rpi_input['index_id'], label=rpi_input['label'])) - return jsonify(inputs) + index = self.to_int(rpi_input['index_id']) + label = rpi_input['label'] + inputs.append(dict(index_id=index, label=label)) + return Response(json.dumps(inputs), mimetype='application/json') - @octoprint.plugin.BlueprintPlugin.route("/input/", methods=["GET"]) + @octoprint.plugin.BlueprintPlugin.route("/inputs/", methods=["GET"]) def get_input_status(self, identifier): for rpi_input in self.rpi_inputs: if identifier == self.to_int(rpi_input['index_id']): - return jsonify(rpi_input) + return Response(json.dumps(rpi_input), mimetype='application/json') return make_response('', 404) @octoprint.plugin.BlueprintPlugin.route("/temperature/", methods=["PATCH"]) @@ -177,32 +179,45 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.handle_temp_hum_control() return make_response('', 204) - @octoprint.plugin.BlueprintPlugin.route("/clear-gpio", methods=["POST"]) - def clear_gpio_mode(self): - GPIO.cleanup() + @octoprint.plugin.BlueprintPlugin.route("/filament/", methods=["PATCH"]) + def set_filament_sensor(self, identifier): + if "application/json" not in request.headers["Content-Type"]: + return make_response("expected json", 400) + try: + data = request.json + except BadRequest: + return make_response("malformed request", 400) + + if 'status' not in data: + return make_response("missing status attribute", 406) + + value = data["status"] + + for sensor in self.rpi_inputs: + if identifier == self.to_int(sensor['index_id']): + sensor['filament_sensor_enabled'] = value + self._logger.info("Setting filament sensor for input %s to : %s", str(identifier), value) + self._settings.set(["rpi_inputs"], self.rpi_inputs) return make_response('', 204) - @octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"]) - def update_ui_requested(self): - self.update_ui() - return make_response('', 204) - - @octoprint.plugin.BlueprintPlugin.route("/output", methods=["GET"]) - def get_output_status(self): + @octoprint.plugin.BlueprintPlugin.route("/outputs", methods=["GET"]) + def get_outputs(self): gpio_status = [] for rpi_output in self.rpi_outputs: if rpi_output['output_type'] == 'regular': - pin = self.to_int(rpi_output['gpio_pin']) - val = GPIO.input(pin) if not rpi_output['active_low'] else (not GPIO.input(pin)) index = self.to_int(rpi_output['index_id']) - gpio_status.append(dict(index_id=index, status=val)) - return jsonify(gpio_status) + label = rpi_output['label'] + gpio_status.append(dict(index_id=index, label=label)) + return Response(json.dumps(gpio_status), mimetype='application/json') - @octoprint.plugin.BlueprintPlugin.route("/output/", methods=["GET"]) - def get_single_output_status(self, identifier): + @octoprint.plugin.BlueprintPlugin.route("/outputs/", methods=["GET"]) + def get_output_status(self, identifier): for rpi_output in self.rpi_outputs: if identifier == self.to_int(rpi_output['index_id']): - return jsonify(rpi_output) + out = rpi_output.copy() + pin = self.to_int(rpi_output['gpio_pin']) + out['val'] = GPIO.input(pin) if not rpi_output['active_low'] else (not GPIO.input(pin)) + return Response(json.dumps(rpi_output), mimetype='application/json') return make_response('', 404) @octoprint.plugin.BlueprintPlugin.route("/output/", methods=["PATCH"]) @@ -225,6 +240,16 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.write_gpio(self.to_int(rpi_output['gpio_pin']), val) return make_response('', 204) + @octoprint.plugin.BlueprintPlugin.route("/clear-gpio", methods=["POST"]) + def clear_gpio_mode(self): + GPIO.cleanup() + return make_response('', 204) + + @octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"]) + def update_ui_requested(self): + self.update_ui() + return make_response('', 204) + @octoprint.plugin.BlueprintPlugin.route("/shell/", methods=["POST"]) def send_shell_command(self, identifier): rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == identifier].pop() @@ -284,36 +309,6 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self._settings.set(["rpi_outputs"], self.rpi_outputs) return make_response('', 204) - @octoprint.plugin.BlueprintPlugin.route("/filament/", methods=["GET"]) - def get_filament_sensor(self, identifier): - for sensor in self.rpi_inputs: - if identifier == self.to_int(sensor['index_id']): - return jsonify(sensor) - return make_response('', 404) - - # TODO: maybe get all filament sensors via GET /filament. What would be they correct type here? - - @octoprint.plugin.BlueprintPlugin.route("/filament/", methods=["PATCH"]) - def set_filament_sensor(self, identifier): - if "application/json" not in request.headers["Content-Type"]: - return make_response("expected json", 400) - try: - data = request.json - except BadRequest: - return make_response("malformed request", 400) - - if 'status' not in data: - return make_response("missing status attribute", 406) - - value = data["status"] - - for sensor in self.rpi_inputs: - if identifier == self.to_int(sensor['index_id']): - sensor['filament_sensor_enabled'] = value - self._logger.info("Setting filament sensor for input %s to : %s", str(identifier), value) - self._settings.set(["rpi_inputs"], self.rpi_inputs) - return make_response('', 204) - @octoprint.plugin.BlueprintPlugin.route("/pwm/", methods=["PATCH"]) def set_pwm(self, identifier): if "application/json" not in request.headers["Content-Type"]: -- 2.39.5 From f9e32d8e8b5fe02a37cd009468702547c314d9ad Mon Sep 17 00:00:00 2001 From: UnchartedBull Date: Wed, 9 Oct 2019 23:17:21 +0200 Subject: [PATCH 48/52] Rename --- octoprint_enclosure/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 1203cf0..26aa559 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -202,13 +202,13 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP @octoprint.plugin.BlueprintPlugin.route("/outputs", methods=["GET"]) def get_outputs(self): - gpio_status = [] + outputs = [] for rpi_output in self.rpi_outputs: if rpi_output['output_type'] == 'regular': index = self.to_int(rpi_output['index_id']) label = rpi_output['label'] - gpio_status.append(dict(index_id=index, label=label)) - return Response(json.dumps(gpio_status), mimetype='application/json') + outputs.append(dict(index_id=index, label=label)) + return Response(json.dumps(outputs), mimetype='application/json') @octoprint.plugin.BlueprintPlugin.route("/outputs/", methods=["GET"]) def get_output_status(self, identifier): -- 2.39.5 From c54219fd1af8392dabb48beb8acd307e78fcbb0c Mon Sep 17 00:00:00 2001 From: UnchartedBull Date: Wed, 9 Oct 2019 23:42:14 +0200 Subject: [PATCH 49/52] correct naming plus restructuring --- octoprint_enclosure/__init__.py | 42 ++++++++++++++++----------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 26aa559..80759b9 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -220,7 +220,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP return Response(json.dumps(rpi_output), mimetype='application/json') return make_response('', 404) - @octoprint.plugin.BlueprintPlugin.route("/output/", methods=["PATCH"]) + @octoprint.plugin.BlueprintPlugin.route("/outputs/", methods=["PATCH"]) def set_io(self, identifier): if "application/json" not in request.headers["Content-Type"]: return make_response("expected json", 400) @@ -240,25 +240,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.write_gpio(self.to_int(rpi_output['gpio_pin']), val) return make_response('', 204) - @octoprint.plugin.BlueprintPlugin.route("/clear-gpio", methods=["POST"]) - def clear_gpio_mode(self): - GPIO.cleanup() - return make_response('', 204) - - @octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"]) - def update_ui_requested(self): - self.update_ui() - return make_response('', 204) - - @octoprint.plugin.BlueprintPlugin.route("/shell/", methods=["POST"]) - def send_shell_command(self, identifier): - rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == identifier].pop() - - command = rpi_output['shell_script'] - self.shell_command(command) - return make_response('', 204) - - @octoprint.plugin.BlueprintPlugin.route("/output//auto-startup", methods=["PATCH"]) + @octoprint.plugin.BlueprintPlugin.route("/outputs//auto-startup", methods=["PATCH"]) def set_auto_startup(self, identifier): if "application/json" not in request.headers["Content-Type"]: return make_response("expected json", 400) @@ -283,7 +265,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self._settings.set(["rpi_outputs"], self.rpi_outputs) return make_response('', 204) - @octoprint.plugin.BlueprintPlugin.route("/output//auto-shutdown", methods=["PATCH"]) + @octoprint.plugin.BlueprintPlugin.route("/outputs//auto-shutdown", methods=["PATCH"]) def set_auto_shutdown(self, identifier): if "application/json" not in request.headers["Content-Type"]: return make_response("expected json", 400) @@ -309,6 +291,24 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self._settings.set(["rpi_outputs"], self.rpi_outputs) return make_response('', 204) + @octoprint.plugin.BlueprintPlugin.route("/clear-gpio", methods=["POST"]) + def clear_gpio_mode(self): + GPIO.cleanup() + return make_response('', 204) + + @octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"]) + def update_ui_requested(self): + self.update_ui() + return make_response('', 204) + + @octoprint.plugin.BlueprintPlugin.route("/shell/", methods=["POST"]) + def send_shell_command(self, identifier): + rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == identifier].pop() + + command = rpi_output['shell_script'] + self.shell_command(command) + return make_response('', 204) + @octoprint.plugin.BlueprintPlugin.route("/pwm/", methods=["PATCH"]) def set_pwm(self, identifier): if "application/json" not in request.headers["Content-Type"]: -- 2.39.5 From a9ef64eb23c379641d8a11a2cc8beb31e199d17d Mon Sep 17 00:00:00 2001 From: StefanCohen <33824565+StefanCohen@users.noreply.github.com> Date: Thu, 10 Oct 2019 00:40:43 +0200 Subject: [PATCH 50/52] First version of the new API documentation The new REST API documentation --- API.md | 169 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 API.md diff --git a/API.md b/API.md new file mode 100644 index 0000000..4daf5ed --- /dev/null +++ b/API.md @@ -0,0 +1,169 @@ +# API Reference v2.0 + +## List all Inputs. + +Method: GET + +http:///plugin/enclosure/inputs?apikey= + +Response: + +``` +[ + { + "index_id": 1, + "label": "Input 1" + } +] +``` + + +## List a specific input. + +Method: GET + +http:///plugin/enclosure/inputs/1?apikey= + +Response: +``` +{ + "controlled_io": null, + "filament_sensor_timeout": 120, + "filament_sensor_enabled": true, + "temp_sensor_address": "", + "printer_action": "filament", + "controlled_io_set_value": "low", + "temp_sensor_type": "11", + "temp_sensor_navbar": true, + "temp_sensor_humidity": 19, + "edge": "fall", + "ds18b20_serial": "", + "action_type": "output_control", + "input_pull_resistor": "input_pull_up", + "input_type": "temperature_sensor", + "temp_sensor_temp": 33, + "label": "Input 1", + "index_id": 1, + "use_fahrenheit": false, + "gpio_pin": "4" +} +``` + +## List all outputs + +Method: GET + +http:///plugin/enclosure/outputs?apikey= + +Response: +``` +[ + { + "index_id": 1, + "label": "Ouput 1" + } +] +``` + +## List a specific output + +Method: GET + +http:///plugin/enclosure/outputs/1?apikey= + +Response: +``` +{ + "linked_temp_sensor": "", + "ledstrip_gpio_dat": "", + "startup_time": 0, + "temp_ctr_deadband": 0, + "neopixel_brightness": 255, + "new_duty_cycle": "", + "gpio_pin": 0, + "default_duty_cycle": 0, + "neopixel_color": "rgb(0,0,0)", + "hide_btn_ui": false, + "temp_ctr_set_value": 0, + "temp_ctr_default_value": 0, + "default_neopixel_color": "", + "controlled_io_set_value": "Low", + "auto_shutdown": false, + "shell_script": "", + "label": "Ouput 1", + "default_ledstrip_color": "", + "duty_a": 0, + "toggle_timer_off": 0, + "alarm_set_temp": 0, + "ledstrip_gpio_clk": "", + "auto_startup": false, + "controlled_io": 0, + "shutdown_time": 0, + "temp_ctr_type": "heater", + "gcode": "M117 Test", + "shutdown_on_failed": false, + "temperature_b": 0, + "ledstrip_color": "rgb(0,0,0)", + "temperature_a": 0, + "neopixel_count": 0, + "duty_cycle": 0, + "toggle_timer_on": 0, + "show_on_navbar": false, + "duty_b": 0, + "toggle_timer": false, + "pwm_status": 50, + "gpio_status": false, + "pwm_frequency": 50, + "new_ledstrip_color": "", + "startup_with_server": true, + "active_low": true, + "temp_ctr_max_temp": 0, + "pwm_temperature_linked": false, + "temp_ctr_new_set_value": "", + "output_type": "regular", + "microcontroller_address": 0, + "index_id": 1, + "new_neopixel_color": "" +} +``` + +## Enable/Disable Output: + +http:///plugin/enclosure/outputs/1?apikey= + +Method: PATCH +Content-Type: application/json +Body: { "status": boolean } + +example: +``` +{ "status": true } +``` + + +## Enable/Disable Output auto-shutdown: + +http:///plugin/enclosure/outputs/1/auto-shutdown?apikey= + +Method: PATCH +Content-Type: application/json +Body: { "status": boolean } + +example: +``` +{ "status": true } +``` + + +## Enable/Disable Output auto-shutdown: + +http:///plugin/enclosure/outputs/1/auto-startup?apikey= + +Method: PATCH +Content-Type: application/json +Body: { "status": boolean } + +example: +``` +{ "status": true } +``` -- 2.39.5 From 893fb11463db940b137b84ae48b9213a22c4b185 Mon Sep 17 00:00:00 2001 From: UnchartedBull Date: Thu, 10 Oct 2019 15:29:48 +0200 Subject: [PATCH 51/52] Update docs --- API.md | 389 +++++++++++++++++++++++--------- octoprint_enclosure/__init__.py | 105 +++++---- 2 files changed, 347 insertions(+), 147 deletions(-) diff --git a/API.md b/API.md index 4daf5ed..e5ce300 100644 --- a/API.md +++ b/API.md @@ -1,169 +1,342 @@ # API Reference v2.0 -## List all Inputs. +The API is located at \/plugin/enclosure. This needs to be added before each endpoint in order for the API to function properly. The API either returns a `application/json` body or an empty body for a successful request. -Method: GET +A failed request will return an error code as well as a short error description. -http:///plugin/enclosure/inputs?apikey= +## List all inputs -Response: +Endpoint: **GET** `/inputs` + +Response (200): ``` [ { - "index_id": 1, - "label": "Input 1" + "index_id": number, + "label": string } ] ``` +Error Responses: + - none -## List a specific input. +## List a specific input -Method: GET +Endpoint: **GET** `/inputs/` -http:///plugin/enclosure/inputs/1?apikey= +*Note: id needs to be int (index_id)* -Response: +Response (200): ``` { "controlled_io": null, - "filament_sensor_timeout": 120, - "filament_sensor_enabled": true, - "temp_sensor_address": "", - "printer_action": "filament", - "controlled_io_set_value": "low", - "temp_sensor_type": "11", - "temp_sensor_navbar": true, - "temp_sensor_humidity": 19, - "edge": "fall", - "ds18b20_serial": "", - "action_type": "output_control", - "input_pull_resistor": "input_pull_up", - "input_type": "temperature_sensor", - "temp_sensor_temp": 33, - "label": "Input 1", - "index_id": 1, - "use_fahrenheit": false, - "gpio_pin": "4" + "filament_sensor_timeout": number, + "filament_sensor_enabled": boolean, + "temp_sensor_address": string, + "printer_action": string, + "controlled_io_set_value": string, + "temp_sensor_type": string, + "temp_sensor_navbar": boolean, + "temp_sensor_humidity": number, + "edge": string, + "ds18b20_serial": string, + "action_type": string, + "input_pull_resistor": string, + "input_type": string, + "temp_sensor_temp": number, + "label": string, + "index_id": number, + "use_fahrenheit": boolean, + "gpio_pin": string } ``` +Error Responses: + - 404 if specified id cannot be found + ## List all outputs -Method: GET +Endpoint: **GET** `/outputs` -http:///plugin/enclosure/outputs?apikey= - -Response: +Response (200): ``` [ { - "index_id": 1, - "label": "Ouput 1" + "index_id": number, + "label": string } ] ``` +Error Responses: + - none + ## List a specific output -Method: GET +Endpoint: **GET** `/outputs/` -http:///plugin/enclosure/outputs/1?apikey= +*Note: id needs to be int (index_id)* -Response: + +Response (200): ``` { - "linked_temp_sensor": "", - "ledstrip_gpio_dat": "", - "startup_time": 0, - "temp_ctr_deadband": 0, - "neopixel_brightness": 255, - "new_duty_cycle": "", - "gpio_pin": 0, - "default_duty_cycle": 0, - "neopixel_color": "rgb(0,0,0)", - "hide_btn_ui": false, - "temp_ctr_set_value": 0, - "temp_ctr_default_value": 0, - "default_neopixel_color": "", - "controlled_io_set_value": "Low", - "auto_shutdown": false, - "shell_script": "", - "label": "Ouput 1", - "default_ledstrip_color": "", - "duty_a": 0, - "toggle_timer_off": 0, - "alarm_set_temp": 0, - "ledstrip_gpio_clk": "", - "auto_startup": false, - "controlled_io": 0, - "shutdown_time": 0, - "temp_ctr_type": "heater", - "gcode": "M117 Test", - "shutdown_on_failed": false, - "temperature_b": 0, - "ledstrip_color": "rgb(0,0,0)", - "temperature_a": 0, - "neopixel_count": 0, - "duty_cycle": 0, - "toggle_timer_on": 0, - "show_on_navbar": false, - "duty_b": 0, - "toggle_timer": false, - "pwm_status": 50, - "gpio_status": false, - "pwm_frequency": 50, - "new_ledstrip_color": "", - "startup_with_server": true, - "active_low": true, - "temp_ctr_max_temp": 0, - "pwm_temperature_linked": false, - "temp_ctr_new_set_value": "", - "output_type": "regular", - "microcontroller_address": 0, - "index_id": 1, - "new_neopixel_color": "" + "linked_temp_sensor": string, + "ledstrip_gpio_dat": string, + "startup_time": number, + "temp_ctr_deadband": number, + "neopixel_brightness": number, + "new_duty_cycle": string, + "gpio_pin": number, + "default_duty_cycle": number, + "neopixel_color": string, + "hide_btn_ui": boolean, + "temp_ctr_set_value": number, + "temp_ctr_default_value": number, + "default_neopixel_color": string, + "controlled_io_set_value": string, + "auto_shutdown": boolean, + "shell_script": string, + "label": string, + "default_ledstrip_color": string, + "duty_a": number, + "toggle_timer_off": number, + "alarm_set_temp": number, + "ledstrip_gpio_clk": string, + "auto_startup": boolean, + "controlled_io": number, + "shutdown_time": number, + "temp_ctr_type": string, + "gcode": string, + "shutdown_on_failed": boolean, + "temperature_b": number, + "ledstrip_color": string, + "temperature_a": number, + "neopixel_count": number, + "duty_cycle": number, + "toggle_timer_on": number, + "show_on_navbar": boolean, + "duty_b": number, + "toggle_timer": boolean, + "pwm_status": number, + "gpio_status": boolean, + "pwm_frequency": number, + "new_ledstrip_color": string, + "startup_with_server": boolean, + "active_low": boolean, + "temp_ctr_max_temp": number, + "pwm_temperature_linked": boolean, + "temp_ctr_new_set_value": string, + "output_type": string, + "microcontroller_address": number, + "index_id": number, + "new_neopixel_color": string } ``` -## Enable/Disable Output: +Error Responses: + - 404 if specified id cannot be found -http:///plugin/enclosure/outputs/1?apikey= +## Control specific output -Method: PATCH -Content-Type: application/json -Body: { "status": boolean } +Endpoint: **PATCH** `/outputs/` -example: +*Note: id needs to be int (index_id)* + +Body (Content-Type: `application/json`): ``` -{ "status": true } +{ + "status": boolean +} ``` +Response (204): No-Content -## Enable/Disable Output auto-shutdown: +Error Responses: +- 400 - wrong Content-Type or malformed request +- 406 - missing information (missing attribute given in response body) -http:///plugin/enclosure/outputs/1/auto-shutdown?apikey= +## Enable/Disable Output auto-startup -Method: PATCH -Content-Type: application/json -Body: { "status": boolean } +Endpoint: **PATCH** `/outputs//auto-startup` -example: +*Note: id needs to be int (index_id)* + +Body (Content-Type: `application/json`): ``` -{ "status": true } +{ + "status": boolean +} ``` +Response (204): No-Content -## Enable/Disable Output auto-shutdown: +Error Responses: +- 400 - wrong Content-Type or malformed request +- 406 - missing information (missing attribute given in response body) -http:///plugin/enclosure/outputs/1/auto-startup?apikey= +## Control auto-shutdown for specific output -Method: PATCH -Content-Type: application/json -Body: { "status": boolean } +Endpoint: **PATCH** `/outputs//auto-shutdown` -example: +*Note: id needs to be int (index_id)* + +Body (Content-Type: `application/json`): ``` -{ "status": true } +{ + "status": boolean +} ``` + +Response (204): No-Content + +Error Responses: +- 400 - wrong Content-Type or malformed request +- 406 - missing information (missing attribute given in response body) + +## Control temperature + +Endpoint: **PATCH** `/temperature/` + +*Note: id needs to be int (index_id)* + +Body (Content-Type: `application/json`): +``` +{ + "temperature": number +} +``` + +Response (204): No-Content + +Error Responses: +- 400 - wrong Content-Type or malformed request +- 406 - missing information (missing attribute given in response body) + +## Control filament sensor + +Endpoint: **PATCH** `/filament/` + +*Note: id needs to be int (index_id)* + +Body (Content-Type: `application/json`): +``` +{ + "status": boolean +} +``` + +Response (204): No-Content + +Error Responses: +- 400 - wrong Content-Type or malformed request +- 406 - missing information (missing attribute given in response body) + +## Set PWM value + +Endpoint: **PATCH** `/pwm/` + +*Note: id needs to be int (index_id)* + +Body (Content-Type: `application/json`): +``` +{ + "duty_cycle": number +} +``` + +Response (204): No-Content + +Error Responses: +- 400 - wrong Content-Type or malformed request +- 406 - missing information (missing attribute given in response body) + +## Set RGB LED color + +Endpoint: **PATCH** `/rgb-led/` + +*Note: id needs to be int (index_id)* + +Body (Content-Type: `application/json`): +``` +{ + "rgb": string (rgb(r,g,b)) +} +``` + +Response (204): No-Content + +Error Responses: +- 400 - wrong Content-Type or malformed request +- 406 - missing information (missing attribute given in response body) + +## Set neopixel color + +Endpoint: **PATCH** `/neopixel/` + +*Note: id needs to be int (index_id)* + +Body (Content-Type: `application/json`): +``` +{ + "red": number, + "green": number, + "blue": number +} +``` + +Response (204): No-Content + +Error Responses: +- 400 - wrong Content-Type or malformed request +- 406 - missing information (missing attribute given in response body) + +## Clear GPIO Pins + +Endpoint: **POST** `/clear-gpio` + +Body: empty + +Response (204): No-Content + +Error Responses: +- none + +## Update UI + +Endpoint: **POST** `/update` + +Body: empty + +Response (204): No-Content + +Error Responses: +- none + +## Send shell command + +Endpoint: **POST** `/shell/` + +*Note: id needs to be int (index_id)* + +Body: empty + +Response (204): No-Content + +Error Responses: +- none + +## Send gcode command + +Endpoint: **POST** `/gcode/` + +*Note: id needs to be int (index_id)* + +Body: empty + +Response (204): No-Content + +Error Responses: +- none \ No newline at end of file diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 80759b9..ebcf5b8 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -7,6 +7,7 @@ from .ledstrip import LEDStrip import octoprint.plugin import RPi.GPIO as GPIO from flask import jsonify, request, make_response, Response +from octoprint.server.util.flask import restricted_access from werkzeug.exceptions import BadRequest import time import sys @@ -152,6 +153,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP inputs.append(dict(index_id=index, label=label)) return Response(json.dumps(inputs), mimetype='application/json') + @octoprint.plugin.BlueprintPlugin.route("/inputs/", methods=["GET"]) def get_input_status(self, identifier): for rpi_input in self.rpi_inputs: @@ -159,7 +161,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP return Response(json.dumps(rpi_input), mimetype='application/json') return make_response('', 404) + @octoprint.plugin.BlueprintPlugin.route("/temperature/", methods=["PATCH"]) + @restricted_access def set_enclosure_temp_humidity(self, identifier): if "application/json" not in request.headers["Content-Type"]: return make_response("expected json", 400) @@ -179,7 +183,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.handle_temp_hum_control() return make_response('', 204) + @octoprint.plugin.BlueprintPlugin.route("/filament/", methods=["PATCH"]) + @restricted_access def set_filament_sensor(self, identifier): if "application/json" not in request.headers["Content-Type"]: return make_response("expected json", 400) @@ -200,6 +206,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self._settings.set(["rpi_inputs"], self.rpi_inputs) return make_response('', 204) + @octoprint.plugin.BlueprintPlugin.route("/outputs", methods=["GET"]) def get_outputs(self): outputs = [] @@ -210,6 +217,7 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP outputs.append(dict(index_id=index, label=label)) return Response(json.dumps(outputs), mimetype='application/json') + @octoprint.plugin.BlueprintPlugin.route("/outputs/", methods=["GET"]) def get_output_status(self, identifier): for rpi_output in self.rpi_outputs: @@ -220,7 +228,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP return Response(json.dumps(rpi_output), mimetype='application/json') return make_response('', 404) + @octoprint.plugin.BlueprintPlugin.route("/outputs/", methods=["PATCH"]) + @restricted_access def set_io(self, identifier): if "application/json" not in request.headers["Content-Type"]: return make_response("expected json", 400) @@ -240,7 +250,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.write_gpio(self.to_int(rpi_output['gpio_pin']), val) return make_response('', 204) + @octoprint.plugin.BlueprintPlugin.route("/outputs//auto-startup", methods=["PATCH"]) + @restricted_access def set_auto_startup(self, identifier): if "application/json" not in request.headers["Content-Type"]: return make_response("expected json", 400) @@ -265,7 +277,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self._settings.set(["rpi_outputs"], self.rpi_outputs) return make_response('', 204) + @octoprint.plugin.BlueprintPlugin.route("/outputs//auto-shutdown", methods=["PATCH"]) + @restricted_access def set_auto_shutdown(self, identifier): if "application/json" not in request.headers["Content-Type"]: return make_response("expected json", 400) @@ -291,25 +305,9 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self._settings.set(["rpi_outputs"], self.rpi_outputs) return make_response('', 204) - @octoprint.plugin.BlueprintPlugin.route("/clear-gpio", methods=["POST"]) - def clear_gpio_mode(self): - GPIO.cleanup() - return make_response('', 204) - - @octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"]) - def update_ui_requested(self): - self.update_ui() - return make_response('', 204) - - @octoprint.plugin.BlueprintPlugin.route("/shell/", methods=["POST"]) - def send_shell_command(self, identifier): - rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == identifier].pop() - - command = rpi_output['shell_script'] - self.shell_command(command) - return make_response('', 204) @octoprint.plugin.BlueprintPlugin.route("/pwm/", methods=["PATCH"]) + @restricted_access def set_pwm(self, identifier): if "application/json" not in request.headers["Content-Type"]: return make_response("expected json", 400) @@ -318,10 +316,10 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP except BadRequest: return make_response("malformed request", 400) - if 'dutyCycle' not in data: - return make_response("missing dutyCycle attribute", 406) + if 'duty_cycle' not in data: + return make_response("missing duty_cycle attribute", 406) - set_value = self.to_int(data['dutyCycle']) + set_value = self.to_int(data['duty_cycle']) for rpi_output in [item for item in self.rpi_outputs if item['index_id'] == identifier]: rpi_output['duty_cycle'] = set_value rpi_output['new_duty_cycle'] = "" @@ -329,13 +327,30 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP self.write_pwm(gpio, set_value) return make_response('', 204) - @octoprint.plugin.BlueprintPlugin.route("/gcode/", methods=["POST"]) - def requested_gcode_command(self, identifier): - rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == identifier].pop() - self.send_gcode_command(rpi_output['gcode']) + @octoprint.plugin.BlueprintPlugin.route("/rgb-led/", methods=["PATCH"]) + @restricted_access + def set_ledstrip_color(self, identifier): + """ set_ledstrip_color method get request from octoprint and send the command to Open-Smart RGB LED Strip""" + if "application/json" not in request.headers["Content-Type"]: + return make_response("expected json", 400) + try: + data = request.json + except BadRequest: + return make_response("malformed request", 400) + + if 'rgb' not in data: + return make_response("missing rgb attribute", 406) + rgb = data['rgb'] + + for rpi_output in self.rpi_outputs: + if identifier == self.to_int(rpi_output['index_id']): + self.ledstrip_set_rgb(rpi_output, rgb) + return make_response('', 204) + @octoprint.plugin.BlueprintPlugin.route("/neopixel/", methods=["PATCH"]) + @restricted_access def set_neopixel(self, identifier): """ set_neopixel method get request from octoprint and send the command to arduino or neopixel""" if "application/json" not in request.headers["Content-Type"]: @@ -369,24 +384,36 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP return make_response('', 204) - @octoprint.plugin.BlueprintPlugin.route("/rgb-led/", methods=["PATCH"]) - def set_ledstrip_color(self, identifier): - """ set_ledstrip_color method get request from octoprint and send the command to Open-Smart RGB LED Strip""" - if "application/json" not in request.headers["Content-Type"]: - return make_response("expected json", 400) - try: - data = request.json - except BadRequest: - return make_response("malformed request", 400) - if 'rgb' not in data: - return make_response("missing rgb attribute", 406) - rgb = data['rgb'] + @octoprint.plugin.BlueprintPlugin.route("/clear-gpio", methods=["POST"]) + @restricted_access + def clear_gpio_mode(self): + GPIO.cleanup() + return make_response('', 204) - for rpi_output in self.rpi_outputs: - if identifier == self.to_int(rpi_output['index_id']): - self.ledstrip_set_rgb(rpi_output, rgb) + @octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"]) + @restricted_access + def update_ui_requested(self): + self.update_ui() + return make_response('', 204) + + + @octoprint.plugin.BlueprintPlugin.route("/shell/", methods=["POST"]) + @restricted_access + def send_shell_command(self, identifier): + rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == identifier].pop() + + command = rpi_output['shell_script'] + self.shell_command(command) + return make_response('', 204) + + + @octoprint.plugin.BlueprintPlugin.route("/gcode/", methods=["POST"]) + @restricted_access + def requested_gcode_command(self, identifier): + rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int(r_out['index_id']) == identifier].pop() + self.send_gcode_command(rpi_output['gcode']) return make_response('', 204) -- 2.39.5 From 046df7a51dcca706b1ea145dd7d85c40cc964a41 Mon Sep 17 00:00:00 2001 From: UnchartedBull Date: Thu, 10 Oct 2019 17:01:15 +0200 Subject: [PATCH 52/52] Fix output value not returned --- API.md | 1 + octoprint_enclosure/__init__.py | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/API.md b/API.md index e5ce300..dbee16d 100644 --- a/API.md +++ b/API.md @@ -110,6 +110,7 @@ Response (200): "shutdown_time": number, "temp_ctr_type": string, "gcode": string, + "current_value": boolean, "shutdown_on_failed": boolean, "temperature_b": number, "ledstrip_color": string, diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index ebcf5b8..129043d 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -20,6 +20,7 @@ import requests import inspect import threading import json +import copy class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.SettingsPlugin, @@ -222,10 +223,10 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplateP def get_output_status(self, identifier): for rpi_output in self.rpi_outputs: if identifier == self.to_int(rpi_output['index_id']): - out = rpi_output.copy() + out = copy.deepcopy(rpi_output) pin = self.to_int(rpi_output['gpio_pin']) - out['val'] = GPIO.input(pin) if not rpi_output['active_low'] else (not GPIO.input(pin)) - return Response(json.dumps(rpi_output), mimetype='application/json') + out['current_value'] = GPIO.input(pin) if not rpi_output['active_low'] else (not GPIO.input(pin)) + return Response(json.dumps(out), mimetype='application/json') return make_response('', 404) -- 2.39.5