cd ~
-git clone https://github.com/adafruit/Adafruit_Python_DHT.git
-cd Adafruit_Python_DHT
-sudo apt-get update
-sudo apt-get install build-essential python-dev python-openssl
-sudo python setup.py install
-
-You can test the library by using:
-
-cd examples
-sudo ./AdafruitDHT.py 2302 4
-
-Note that the first argument is the temperature sensor (11, 22, or 2302), and the second argument is the GPIO that the sensor was connected.
-
-* For the DS18B20 sensor:
-
-Follow the wiring diagram on the pictures on thingiverse. The DS18B20 uses "1-wire" communication protocol, you need to use 4.7K to 10K resistor from the data pin to VCC, DS18B20 only works on GPIO pin number 4. You also need to add OneWire support for your raspberry pi.
-
-Start by adding the following line to /boot/config.txt
-
-dtoverlay=w1-gpio
-
-You should be able to test your sensor by rebooting your system with sudo reboot. When the Pi is back up and you're logged in again, type the commands you see below into a terminal window. When you are in the 'devices' directory, the directory starting '28-' may have a different name, so cd to the name of whatever directory is there.
-
-sudo modprobe w1-gpio
-sudo modprobe w1-therm
-cd /sys/bus/w1/devices
-ls
-cd 28-xxxx (change this to match what serial number pops up)
-cat w1_slave
-
-The response will either have YES or NO at the end of the first line. If it is yes, then the temperature will be at the end of the second line, in 1/000 degrees C.
-
-* 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.
-
-**Hardware**
-
-You can use relays / mosfets to control you lights, heater, lockers etc... If toy want to control mains voltage I recomend using PowerSwitch Tail II.
-
-* Relay
-
-The relays module that I used can be found [here](https://www.amazon.com/gp/product/B0057OC6D8?psc=1&redirect=true&ref_=oh_aui_search_detailpage). Those relays are active low, that means that they will turn on when you put LOW on the output of your pin. In order to not fry your Raspberry Pi pay attention on your wiring connection: remove the jumper link and connect 3.3v to VCC, 5V to JD-VCC and Ground to GND.
-
-* Heater
-
-For heating my enclosure I got a $15 lasko inside my enclosure. I opened it and added a relay to the mains wire. If you’re uncomfortable soldering or dealing with high voltage, please check out the [PowerSwitch Tail II](http://www.powerswitchtail.com/Pages/default.aspx) . The PowerSwitch Tail II is fully enclosed, making it a lot safer.
-
-**CAUTION: VOLTAGE ON MAINS WIRE CAN KILL YOU, ONLY ATTEMPT TO DO THIS IF YOU KNOW WHAT YOU ARE DOING, AND DO AT YOUR OWN RISK**
-
-**CAUTION 2: THIS HEATER IS NOT INTENDED TO FUNCTION THIS WAY AND IT MIGHT BE A FIRE HAZARD. DO IT AT YOUR OWN RISK**
-
-* Cooler
-
-You can get a [5V small fan](https://www.amazon.com/gp/product/B003FO0LG6/ref=oh_aui_search_detailpage?ie=UTF8&psc=1) and control it over a relay.
-
-* Filament sensor
-
-You have the ability to add a filament sensor to the enclosure, it will automatically pause the print and run a gcode command to change the filament if you run out of filament, I can be any type of filament sensor, the sensor should connect to ground if is set as an "active low" when the filament run out or 3.3v if the sensor is set as "active high" when detected the end of filament, it does not matter if it is normally open or closed, that will only interfere on your wiring. I'm using the following sensor:
-
-http://www.thingiverse.com/thing:1698397
-
-**Configuration**
-
-You need to enable what do you want the plugin to control.
-
-Open the setting screen and find the plugin configuration. You can enable temperature reading and temperature control, You must select the type of sensor that you are using and the GPIO pin that is connected to.
-
-For temperature control you can enable automatically starting up the temperature control once the print starts with a set temperature.
-
-Outputs are meant to control anything, lights, locker, extra enclosure fans etc... You can even use a PowerSwitch Tail II and completely shut down your printer after the print job is done. You can add delays and automatically start and shutdown the GPIO.
-
-Inputs have basically three different types:
-
-* Temperature
-* Printer
-* GPIO
-
-Temperature inputs will control a GPIO output after a certain temperature is met. This is useful if you want to add some sort of alarm near your printer, or even build some fire extinguisher on your enclosure. Note that I'm not responsible for any damage caused by fires, you should have proper smoke detectors on your house installed by professionals.
-
-Printer inputs will trigger Printer actions when the configured GPIO receives a signal. The actions can be Resume and Pause a print job or Change Filament. You can use the "change filament" action and set up the input GPIO according to your filament sensor, for example, if your filament 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.
-You can also add mechanical buttons to pause, resume and change filaments near or printer for convenience.
-
-GPIO events 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 being able to control your lights / fan using mechanical buttons instead of the octoprint interface.
-
-**Road map**
-There are still SOME features that I'll add to this plugin:
-* Control neopixels \ dotstart
-* Enable GCODE control for each setting
-
-Let me know about improvements that you might think.
-
-**Tab Order**
-
-I often use more this plugin than the time lapse tab, so having the plugin appear before the timelapse is better for me.
-
-You can do this by changing the config.yaml file as instructed on [octoprint documentation ](http://docs.octoprint.org/en/master/configuration/config_yaml.html). Unless defined differently via the command line config.yaml is located at ~/.octoprint.
-
-You just need to add the following section:
-
-```
-appearance:
- components:
- order:
- tab:
- - temperature
- - control
- - gcodeviewer
- - terminal
- - plugin_enclosure
- - timelapse
-```
-
-
-
-
+# OctoPrint-Enclosure
+
+**Control pretty much everything that you might want to do on your raspberry pi / octoprint / enclosure**
+
+Here is a list of possibilities:
+* Add temperature sensors on your enclosure or near your printer
+* Add active heaters on your enclosure and keep the temperature nice and high for large ABS
+* PWM controlled outputs
+* PWM controlled outputs based on temperature sensor
+* Active cooling for good PLA printing
+* Schedule GPIO's to turn on and off with a fixed period of time during printing.
+* Mechanical buttons to pause and resume printer jobs
+* Mechanical buttons to send GCODE to the printer
+* Mechanical buttons to control raspberry pi GPIO
+* Multiple filament sensors for dual or more extruders
+* Alarm when enclosure temperature reaches some sort of value
+* Notifications using IFTTT when events happen (temperature trigger / print events / etc)
+* Add sub-menus on navbar to quick access outputs and temperature sensors
+
+Find the plugin useful? Buy me a coffee
+[](https://www.paypal.me/VitorHenrique/2)
+
+Having problems with the plugin? check the [troubleshooting guide](https://github.com/vitormhenrique/OctoPrint-Enclosure/wiki/Troubleshooting-Guide)
+
+Check pictures on thingiverse: http://www.thingiverse.com/thing:2245493
+
+**Software**
+
+Install the plugin using the Plugin Manager bundled with OctoPrint, you can search for the Enclosure plugin or just use the url: https://github.com/vitormhenrique/OctoPrint-Enclosure/archive/master.zip.
+
+To control the encosure temperature or get temperature trigged events, you need to install and configure a temperature sensor. This plugin can support DHT11, DHT22, AM2302, DS18B20, SI7021, BME280 and TMP102 temperature sensors.
+
+* For the DHT11, DHT22 and AM2302 follow this steps:
+
+Wire the sensor following the wiring diagram on the pictures on thingiverse, you can use any GPIO pin.
+
+For DHT11 and DHT22 sensors, don't forget to connect a 4.7K - 10K resistor from the data pin to VCC. Also, be aware that DHT sensors some times can not work reliably on linux, this is a limitation of reading DHT sensors from Linux--there's no guarantee the program will be given enough priority and time by the Linux kernel to reliably read the sensor. Another common issue is the power supply. you need a constant and good 3.3V, sometimes a underpowered raspberry pi will not have a solid 3.3V power supply, so you could try powering the sensor with 5V and using a level shifter on the read pin.
+
+You need to install Adafruit library to use the temperature sensor on raspberry pi.
+
+Open raspberry pi terminal and type:
+
+cd ~
+git clone https://github.com/adafruit/Adafruit_Python_DHT.git
+cd Adafruit_Python_DHT
+sudo apt-get update
+sudo apt-get install build-essential python-dev python-openssl
+sudo python setup.py install
+
+You can test the library by using:
+
+cd examples
+sudo ./AdafruitDHT.py 2302 4
+
+Note that the first argument is the temperature sensor (11, 22, or 2302), and the second argument is the GPIO that the sensor was connected.
+
+* For the DS18B20 sensor:
+
+Follow the wiring diagram on the pictures on thingiverse. The DS18B20 uses "1-wire" communication protocol, you need to use 4.7K to 10K resistor from the data pin to VCC, DS18B20 only works on GPIO pin number 4 by default. You also need to add OneWire support for your raspberry pi.
+
+Start by adding the following line to /boot/config.txt
+
+dtoverlay=w1-gpio
+
+You should be able to test your sensor by rebooting your system with sudo reboot. When the Pi is back up and you're logged in again, type the commands you see below into a terminal window. When you are in the 'devices' directory, the directory starting '28-' may have a different name, so cd to the name of whatever directory is there.
+
+sudo modprobe w1-gpio
+sudo modprobe w1-therm
+cd /sys/bus/w1/devices
+ls
+cd 28-xxxx (change this to match what serial number pops up)
+cat w1_slave
+
+The response will either have YES or NO at the end of the first line. If it is yes, then the temperature will be at the end of the second line, in 1/000 degrees C.
+
+Copy the serial number, you will need to configure the plugin
+
+* For the SI7021, BME280 and TMP102 sensors
+
+Enable I2C on your raspberry pi, depending on raspi-config version, step by step can be different:
+
+Run sudo raspi-config
+Use the down arrow to select 9 Advanced Options
+Arrow down to A7 I2C
+Select yes when it asks you to enable I2C
+Also select yes when it asks about automatically loading the kernel module
+Use the right arrow to select the button
+Select yes when it asks to reboot
+
+
+Install some packages:
+
+sudo apt-get install i2c-tools python-pip
+
+Find the address of the sensor:
+
+i2cdetect -y 1
+
+* 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.
+
+**Hardware**
+
+You can use relays / mosfets to control you lights, heater, lockers etc... If you want to control mains voltage I recommend using PowerSwitch Tail II.
+
+* Relay
+
+The relays module that I used can be found [here](https://www.amazon.com/gp/product/B0057OC6D8?psc=1&redirect=true&ref_=oh_aui_search_detailpage). Those relays are active low, that means that they will turn on when you put LOW on the output of your pin. In order to not fry your Raspberry Pi pay attention on your wiring connection: remove the jumper link and connect 3.3v to VCC, 5V to JD-VCC and Ground to GND.
+
+* Heater
+
+For heating my enclosure I got a $15 lasko inside my enclosure. I opened it and added a relay to the mains wire. If you’re uncomfortable soldering or dealing with high voltage, please check out the [PowerSwitch Tail II](http://www.powerswitchtail.com/Pages/default.aspx) . The PowerSwitch Tail II is fully enclosed, making it a lot safer.
+
+**CAUTION: VOLTAGE ON MAINS WIRE CAN KILL YOU, ONLY ATTEMPT TO DO THIS IF YOU KNOW WHAT YOU ARE DOING, AND DO AT YOUR OWN RISK**
+
+**CAUTION 2: THIS HEATER IS NOT INTENDED TO FUNCTION THIS WAY AND IT MIGHT BE A FIRE HAZARD. DO IT AT YOUR OWN RISK**
+
+* Cooler
+
+You can get a [5V small fan](https://www.amazon.com/gp/product/B003FO0LG6/ref=oh_aui_search_detailpage?ie=UTF8&psc=1) and control it over a relay.
+
+* Filament sensor
+
+You have the ability to add a filament sensor to the enclosure, it will automatically pause the print and run a gcode command to change the filament if you run out of filament, I can be any type of filament sensor, the sensor should connect to ground if is set as an "active low" when the filament run out or 3.3v if the sensor is set as "active high" when detected the end of filament, it does not matter if it is normally open or closed, that will only interfere on your wiring. I'm using the following sensor:
+
+http://www.thingiverse.com/thing:1698397
+
+**Configuration**
+
+You need to enable what do you want the plugin to control. Settings from plugin version < 3.6 are not compatible anymore, you will loose all settings after upgrading the plugin.
+
+There are mainly two types of configuration on the plugin, Inputs and Outputs.
+
+Outputs are meant to control THINGS (temperature, lights, locker, extra enclosure fans etc...) You can even use a PowerSwitch Tail II and completely shut down your printer after the print job is done.
+
+Outputs can be set to the following types:
+
+* Regular GPIO
+* PWM GPIO
+* Neopixel Control via Microcontroler
+* Neopixel Control directly from raspberry pi
+* Temperature and Humidity Control
+* Temperature Alarm
+* Gcode Output
+
+Most outputs create UI elements on enclosure plugin tab that let you set values / turn on or off gpios etc. You have the ability to automatically turn on or off outputs when the printer starts or finishes. You can even specify a hour on HH:MM 24 hour format, events will only be schedule when the print starts, and will only be triggered for the very next time that hour occur.
+
+Temperature Alarm will control another GPIO output after a certain temperature is met. This is useful if you want to add some sort of alarm near your printer, or even build some fire extinguisher on your enclosure. Note that I'm not responsible for any damage caused by fires, you should have proper smoke detectors on your house installed by professionals.
+
+Inputs are methods that trigger actions or input values to the plugin (temperature sensor, GPIO trigger)
+
+Inputs can be of two different types:
+
+* Temperature Sensors
+* GPIO
+
+Temperature Sensors will be used to input temperature and humidity data, they can be linked to a especial output like temperature control and temperature alarm.
+
+GPIO inputs will trigger events for the plugin, this feature can be used to add buttons to the enclosure and cause pressing those buttons to act on the printer or other pre-configured outputs.
+
+After selecting GPIO for the input type, and selecting output control on the action type, the button will be able to turn on / off or toggle linked regular outputs, basically being able to control your lights / fan using mechanical buttons instead of the octoprint interface. You can also use buttons to send g-code commands.
+
+Selecting print control on the action type will trigger printer actions when the configured GPIO receives a signal. The actions can be Resume and Pause a print job or Change Filament. You can use the "change filament" action and set up the input GPIO according to your filament sensor, for example, if your filament 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.
+You can also add mechanical buttons to pause, resume and change filaments near your printer for convenience.
+
+**Advanced Area**
+
+If you want to enable notifications check the following [issue](https://github.com/vitormhenrique/OctoPrint-Enclosure/issues/36)
+
+You can control outputs using a simple [API](https://github.com/vitormhenrique/OctoPrint-Enclosure/wiki/API-Control)
+
+Or use [g-code](https://github.com/vitormhenrique/OctoPrint-Enclosure/wiki/G-CODE-Control) commands
+
+**Tab Order**
+
+I often use more this plugin than the time-lapse tab, so having the plugin appear before the timelapse is better for me.
+
+You can do this by changing the config.yaml file as instructed on [octoprint documentation ](http://docs.octoprint.org/en/master/configuration/config_yaml.html). Unless defined differently via the command line config.yaml is located at ~/.octoprint.
+
+You just need to add the following section:
+
+```
+appearance:
+ components:
+ order:
+ tab:
+ - temperature
+ - control
+ - gcodeviewer
+ - terminal
+ - plugin_enclosure
+ - timelapse
+```
+
+
+
+
diff --git a/extras/octoprint_neopixel/octoprint_neopixel.ino b/extras/octoprint_neopixel/octoprint_neopixel.ino
index 67ecd8e..d35c4a1 100644
--- a/extras/octoprint_neopixel/octoprint_neopixel.ino
+++ b/extras/octoprint_neopixel/octoprint_neopixel.ino
@@ -30,7 +30,7 @@ bool gotData = false;
int command = 0;
int neopixelPin = 0;
int neopixelLeds = 0;
-int neopixelBrightness = 0;
+int neopixel_brightness = 0;
int redValue = 0;
int greenValue = 0;
int blueValue = 0;
@@ -51,8 +51,8 @@ void receiveEvent(int byteCount){
DEBUG_PRINTLN(neopixelLeds);
DEBUG_PRINT("BRIGHTNESS ");
- neopixelBrightness = Wire.read();
- DEBUG_PRINTLN(neopixelBrightness);
+ neopixel_brightness = Wire.read();
+ DEBUG_PRINTLN(neopixel_brightness);
DEBUG_PRINT("RED ");
redValue = Wire.read();
@@ -75,7 +75,7 @@ void setup() {
Wire.begin(I2CADDRESS);
#ifdef DEBUG
Serial.begin(115200);
- while (!Serial) ;
+ while (!Serial);
Serial.println("Debuging...");
#endif
Wire.onReceive(receiveEvent);
@@ -85,7 +85,7 @@ void loop() {
if(gotData){
strip.setPin(neopixelPin);
- strip.setBrightness(neopixelBrightness);
+ strip.setBrightness(neopixel_brightness);
strip.updateLength(neopixelLeds);
strip.updateType(LED_TYPE);
strip.begin();
diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py
index 1355134..c12cadc 100644
--- a/octoprint_enclosure/__init__.py
+++ b/octoprint_enclosure/__init__.py
@@ -6,615 +6,1064 @@ from subprocess import Popen, PIPE
import octoprint.plugin
import RPi.GPIO as GPIO
import flask
-import sched
import time
import sys
import glob
import os
-import datetime
+from datetime import datetime
+from datetime import timedelta
import octoprint.util
import requests
+import inspect
+import threading
+import json
-scheduler = sched.scheduler(time.time, time.sleep)
class EnclosurePlugin(octoprint.plugin.StartupPlugin,
- octoprint.plugin.TemplatePlugin,
- octoprint.plugin.SettingsPlugin,
- octoprint.plugin.AssetPlugin,
- octoprint.plugin.BlueprintPlugin,
- octoprint.plugin.EventHandlerPlugin):
-
- previousTempControlStatus = False
- currentTempControlStatus = False
- enclosureSetTemperature=0.0
- enclosureCurrentTemperature=0.0
- enclosureCurrentHumidity=0.0
- lastFilamentEndDetected=0
- temperature_reading = []
- temperature_control = []
+ octoprint.plugin.TemplatePlugin,
+ octoprint.plugin.SettingsPlugin,
+ octoprint.plugin.AssetPlugin,
+ octoprint.plugin.BlueprintPlugin,
+ octoprint.plugin.EventHandlerPlugin):
rpi_outputs = []
rpi_inputs = []
- previous_rpi_outputs = []
+ waiting_temperature = []
+ rpi_outputs_not_changed = []
notifications = []
+ pwm_intances = []
+ event_queue = []
+ temp_hum_control_status = []
+ temperature_sensor_data = []
+ last_filament_end_detected = []
+ print_complete = False
- PWM_INSTANCES = []
- disable_temeprature_log = True
+ def start_timer(self):
+ """
+ Function to start timer that checks enclosure temperature
+ """
- def startTimer(self):
- self._checkTempTimer = RepeatedTimer(10, self.checkEnclosureTemp, None, None, True)
- self._checkTempTimer.start()
+ self._check_temp_timer = RepeatedTimer(
+ 10, self.check_enclosure_temp, None, None, True)
+ self._check_temp_timer.start()
+
+ @staticmethod
+ def to_float(value):
+ """Converts value to flow
+
+ Arguments:
+ value {any} -- value to be
+
+ Returns:
+ float -- value converted
+ """
- def toFloat(self, value):
try:
val = float(value)
return val
except:
return 0
- def toInt(self, value):
+ @staticmethod
+ def to_int(value):
try:
val = int(value)
return val
except:
return 0
- #~~ StartupPlugin mixin
- def on_after_startup(self):
+ @staticmethod
+ def is_hour(value):
+ try:
+ datetime.strptime(value, '%H:%M')
+ return True
+ except:
+ return False
- self.PWM_INSTANCES = []
- self.temperature_reading = self._settings.get(["temperature_reading"])
- self.temperature_control = self._settings.get(["temperature_control"])
+ @staticmethod
+ def create_date(value):
+ temp_string = datetime.now().strftime(
+ '%m/%d/%Y') + " " + value
+ return datetime.strptime(temp_string, '%m/%d/%Y %H:%M')
+
+ @staticmethod
+ def constrain(n, minn, maxn):
+ return max(min(maxn, n), minn)
+
+ @staticmethod
+ def get_gcode_value(command_string, gcode):
+ semicolon = command_string.find(';')
+ if not semicolon == -1:
+ command_string = command_string[:semicolon]
+
+ for command in command_string.split(' '):
+ index = command.upper().find(gcode.upper())
+ if not index == -1:
+ return command.replace(gcode, '').upper()
+ return -1
+
+ # ~~ StartupPlugin mixin
+ def on_after_startup(self):
+ self.pwm_intances = []
+ self.event_queue = []
+ self.rpi_outputs_not_changed = []
self.rpi_outputs = self._settings.get(["rpi_outputs"])
self.rpi_inputs = self._settings.get(["rpi_inputs"])
self.notifications = self._settings.get(["notifications"])
- self.fixData()
- self.previous_rpi_outputs = []
- self.startTimer()
- self.startGPIO()
- # self.clearGPIO()
- self.configureGPIO()
- self.updateOutputUI()
+ self.generate_temp_hum_control_status()
+ self.setup_gpio()
+ self.configure_gpio()
+ self.update_ui()
+ self.start_outpus_with_server()
+ self.start_timer()
+ self.print_complete = False
- #~~ Blueprintplugin mixin
- @octoprint.plugin.BlueprintPlugin.route("/setEnclosureTemperature", methods=["GET"])
- def setEnclosureTemperature(self):
- self.enclosureSetTemperature = flask.request.values["enclosureSetTemp"]
- if self._settings.get(["debug"]) == True:
- self._logger.info("DEBUG -> Seting enclosure temperature: %s",self.enclosureSetTemperature)
- self.handleTemperatureControl()
- return flask.jsonify(enclosureSetTemperature=self.enclosureSetTemperature,enclosureCurrentTemperature=self.enclosureCurrentTemperature)
+ def get_settings_version(self):
+ return 4
- @octoprint.plugin.BlueprintPlugin.route("/getEnclosureSetTemperature", methods=["GET"])
- def getEnclosureSetTemperature(self):
- return str(self.enclosureSetTemperature)
+ def on_settings_migrate(self, target, current=None):
+ self._logger.warn("######### settings not compatible #########")
+ self._logger.warn("######### current settings version %s target settings version %s #########",
+ current, target)
+ self._settings.set(["rpi_outputs"], [])
+ self._settings.set(["rpi_inputs"], [])
+ self.rpi_outputs = self._settings.get(["rpi_outputs"])
+ self.rpi_inputs = self._settings.get(["rpi_inputs"])
+
+ # ~~ 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"])
+ 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 clearGPIOMode(self):
+ def clear_gpio_mode(self):
GPIO.cleanup()
return flask.jsonify(success=True)
- @octoprint.plugin.BlueprintPlugin.route("/getUpdateBtnStatus", methods=["GET"])
- def getUpdateBtnStatus(self):
- self.updateOutputUI()
- return flask.make_response("Ok.", 200)
+ @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 getOutputStatus(self):
- getOutputStatusresult = ''
+ def get_output_status(self):
+ gpio_status = []
for rpi_output in self.rpi_outputs:
- pin = self.toInt(rpi_output['gpioPin'])
- if rpi_output['outputType']=='regular':
- val = GPIO.input(pin) if not rpi_output['activeLow'] else (not GPIO.input(pin))
- if getOutputStatusresult:
- getOutputStatusresult = getOutputStatusresult + ', '
- getOutputStatusresult = getOutputStatusresult + '"' + str(pin) + '": ' + str(val).lower()
- return '{' + getOutputStatusresult + '}'
-
-
- @octoprint.plugin.BlueprintPlugin.route("/getEnclosureTemperature", methods=["GET"])
- def getEnclosureTemperature(self):
- return str(self.enclosureCurrentTemperature)
+ 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'])
+ # result.append(dict(index_id=rpi_output['index_id'], value=val))
+ 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 setIO(self):
- io = flask.request.values["io"]
- value = True if flask.request.values["status"] == "on" else False
+ def set_io(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.toInt(io) == self.toInt(rpi_output['gpioPin']):
- val = (not value) if rpi_output['activeLow'] else value
- self.writeGPIO(self.toInt(io), val)
+ 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("/setAutoStartUp", methods=["GET"])
+ def set_auto_startup(self):
+ index = flask.request.values["index_id"]
+ 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)
+ 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(self):
+ index = flask.request.values["index_id"]
+ 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)
+ 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):
+ index = flask.request.values["index_id"]
+ value = True if flask.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)
@octoprint.plugin.BlueprintPlugin.route("/setPWM", methods=["GET"])
- def setPWM(self):
- io = flask.request.values["io"]
- pwmVal = flask.request.values["pwmVal"]
- self.writePWM(self.toInt(io),self.toInt(pwmVal))
- return flask.make_response("Ok.", 200)
+ def set_pwm(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]:
+ 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)
+
+ @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()
+ self.send_gcode_command(rpi_output['gcode'])
+ return flask.jsonify(success=True)
@octoprint.plugin.BlueprintPlugin.route("/setNeopixel", methods=["GET"])
- def setNeopixel(self):
- io = flask.request.values["io"]
+ def set_neopixel(self):
+ """ set_neopixel method get request from octoprint and send the comand 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"]
for rpi_output in self.rpi_outputs:
- if self.toInt(io) == self.toInt(rpi_output['gpioPin']) and rpi_output['outputType']=='neopixel':
- ledCount = rpi_output['neopixelCount']
- ledBrightness = rpi_output['neopixelBrightness']
- address = rpi_output['microAddress']
- self.sendNeopixelCommand(io,ledCount,ledBrightness,red,green,blue,address)
- return flask.make_response("Ok.", 200)
+ if gpio_index == self.to_int(rpi_output['index_id']):
+ led_count = rpi_output['neopixel_count']
+ led_brightness = rpi_output['neopixel_brightness']
+ address = rpi_output['microcontroller_address']
- #~~ Plugin Internal methods
- def fixData(self):
- for rpi_output in self.rpi_outputs:
- if not 'outputType' in rpi_output:
- rpi_output['outputType'] = 'regular'
- if not 'frequency' in rpi_output:
- rpi_output['frequency'] = 50
- if not 'dutycycle' in rpi_output:
- rpi_output['dutycycle'] = 0
- if not 'color' in rpi_output:
- rpi_output['color'] = 'rgb(255,0,0)'
- if not 'neopixelCount' in rpi_output:
- rpi_output['neopixelCount'] = 0
- if not 'microAddress' in rpi_output:
- rpi_output['microAddress'] = 0
- if not 'neopixelBrightness' in rpi_output:
- rpi_output['neopixelBrightness'] = 255
+ neopixel_dirrect = rpi_output['output_type'] == 'neopixel_direct'
- for temp_reader in self.temperature_reading:
- if not 'sensorAddress' in temp_reader:
- temp_reader['sensorAddress'] = 0
+ self.send_neopixel_command(
+ self.to_int(rpi_output['gpio_pin']),
+ led_count, led_brightness, red, green, blue, address, neopixel_dirrect, gpio_index)
- self._settings.set(["rpi_outputs"],self.rpi_outputs)
- self._settings.set(["temperature_reading"],self.temperature_reading)
+ 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):
+ """Send neopixel command
+
+ Arguments:
+ led_pin {int} -- GPIO number
+ 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
+ blue {int} -- blue value from 0 to 255
+ address {int} -- i2c address from microcontroler
+ """
- def sendNeopixelCommand(self,ledPin,ledCount,ledBrightness,red,green,blue,address):
try:
- script = os.path.dirname(os.path.realpath(__file__)) + "/neopixel.py "
- cmd ="sudo python " +script +str(ledPin)+" "+str(ledCount)+" "+str(ledBrightness)+" "+str(red)+" "+str(green)+" "+str(blue)+" "+str(address)
- if self._settings.get(["debug"]) == True:
+
+ 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)
+
+ if address == '':
+ address = 0
+
+ if neopixel_dirrect:
+ script = os.path.dirname(
+ os.path.realpath(__file__)) + "/neopixel_direct.py "
+ else:
+ script = os.path.dirname(
+ os.path.realpath(__file__)) + "/neopixel_indirect.py "
+
+ if self._settings.get(["use_sudo"]):
+ sudo_str = "sudo "
+ else:
+ sudo_str = ""
+
+ cmd = sudo_str + "python " + script + str(led_pin) + " " + str(led_count) + " " + str(
+ led_brightness) + " " + str(red) + " " + str(green) + " " + str(blue) + " " + str(address)
+ if self._settings.get(["debug"]) is True:
self._logger.info("Sending neopixel cmd: %s", cmd)
- stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read()
+ Popen(cmd, shell=True)
+ if queue_id is not None:
+ self.stop_queue_item(queue_id)
except Exception as ex:
- template = "An exception of type {0} occurred on sendNeopixelCommand. Arguments:\n{1!r}"
- message = template.format(type(ex).__name__, ex.args)
- self._logger.warn(message)
- pass
+ self.log_error(ex)
- def checkEnclosureTemp(self):
+ def check_enclosure_temp(self):
try:
- for temp_reader in self.temperature_reading:
- if temp_reader['isEnabled']:
- if temp_reader['sensorType'] in ["11", "22", "2302"]:
- self._logger.info("sensorType dht")
- temp, hum = self.readDhtTemp(temp_reader['sensorType'],temp_reader['gpioPin'])
- elif temp_reader['sensorType'] == "18b20":
- temp = self.read18b20Temp()
- hum = 0
- elif temp_reader['sensorType'] == "bme280":
- temp, hum = self.readBME280Temp(temp_reader['sensorAddress'])
- elif temp_reader['sensorType'] == "si7021":
- temp, hum = self.readSI7021Temp(temp_reader['sensorAddress'])
- elif temp_reader['sensorType'] == "tmp102":
- temp = self.readTmp102Temp(temp_reader['sensorAddress'])
- hum = 0
- else:
- self._logger.info("sensorType no match")
- temp = 0
- hum = 0
-
- if temp != -1 and hum != -1:
- self.enclosureCurrentTemperature = round(self.toFloat(temp),1) if not temp_reader['useFahrenheit'] else round(self.toFloat(temp)*1.8 + 32,1)
- self.enclosureCurrentHumidity = round(self.toFloat(hum),1)
-
- if self._settings.get(["debug"]) == True and not self.disable_temeprature_log:
- self._logger.info("Temperature: %s humidity %s", self.enclosureCurrentTemperature,self.enclosureCurrentHumidity)
-
- self._plugin_manager.send_plugin_message(self._identifier, dict(enclosuretemp=self.enclosureCurrentTemperature,enclosureHumidity=self.enclosureCurrentHumidity))
- self.handleTemperatureControl()
- self.handleTemperatureEvents()
+ 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:
+ self._logger.info(
+ "Sensor %s Temperature: %s humidity %s", sensor['label'], temp, 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()
+ self.handle_pwm_linked_temperature()
+ self.update_ui()
except Exception as ex:
- template = "An exception of type {0} occurred on checkEnclosureTemp. Arguments:\n{1!r}"
- message = template.format(type(ex).__name__, ex.args)
- self._logger.warn(message)
- pass
+ self.log_error(ex)
- def handleTemperatureEvents(self):
- for rpi_input in self.rpi_inputs:
- if self.toFloat(rpi_input['setTemp']) == 0:
+ def toggle_output(self, output_index, first_run=False):
+ for output in [item for item in self.rpi_outputs if item['index_id'] == output_index]:
+ gpio_pin = self.to_int(output['gpio_pin'])
+ index_id = self.to_int(output['index_id'])
+
+ if output['output_type'] == 'regular':
+ if first_run:
+ current_value = False
+ else:
+ 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'])
+ else:
+ time_delay = self.to_int(output['toggle_timer_on'])
+
+ 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.start()
+ else:
+ off_value = True if output['active_low'] else False
+ self.write_gpio(gpio_pin, off_value)
+ self.update_ui_outputs()
+ return
+
+ if output['output_type'] == 'pwm':
+ for pwm in self.pwm_intances:
+ 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)
+ else:
+ current_pwm_value = 0
+
+ if not current_pwm_value == 0:
+ 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'])
+
+ if not self.print_complete:
+ self.write_pwm(gpio_pin, write_value)
+ thread = threading.Timer(time_delay,
+ self.toggle_output,
+ args=[index_id])
+ thread.start()
+ else:
+ self.write_pwm(self.to_int(output['gpio_pin']), 0)
+ self.update_ui_outputs()
+ return
+
+ def update_ui(self):
+ self.update_ui_outputs()
+ self.update_ui_current_temperature()
+ self.update_ui_set_temperature()
+ 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))
+
+ 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))
+ result.append(set_temperature)
+ self._plugin_manager.send_plugin_message(
+ self._identifier, dict(set_temperature=result))
+
+ def stop_queue_item(self, queue_id):
+ for task in self.event_queue:
+ if task['queue_id'] == queue_id:
+ task['thread'].cancel()
+ self.event_queue.remove(task)
+
+ def update_ui_outputs(self):
+ try:
+ regular_status = []
+ pwm_status = []
+ neopixel_status = []
+ temp_control_status = []
+ for output in self.rpi_outputs:
+ index = self.to_int(output['index_id'])
+ pin = self.to_int(output['gpio_pin'])
+ startup = output['auto_startup']
+ shutdown = output['auto_shutdown']
+
+ if output['output_type'] == 'regular':
+ 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':
+ temp_control_status.append(
+ dict(index_id=index, auto_startup=startup, auto_shutdown=shutdown))
+ if output['output_type'] == 'neopixel_indirect' or output['output_type'] == 'neopixel_direct':
+ val = output['neopixel_color']
+ 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:
+ if pin in pwm:
+ if 'duty_cycle' in pwm:
+ pwm_val = pwm['duty_cycle']
+ val = self.to_int(pwm_val)
+ else:
+ 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))
+ except Exception as ex:
+ self.log_error(ex)
+
+ def update_ui_inputs(self):
+ 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':
+ 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))
+ except Exception as ex:
+ self.log_error(ex)
+
+ def get_sensor_data(self, sensor):
+ try:
+ if sensor['temp_sensor_type'] in ["11", "22", "2302"]:
+ self._logger.info("temp_sensor_type dht")
+ 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'])
+ elif sensor['temp_sensor_type'] == "si7021":
+ 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'])
+ hum = 0
+ else:
+ self._logger.info("temp_sensor_type no match")
+ temp = 0
+ hum = 0
+ 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)
+ hum = round(self.to_float(hum), 1)
+ return temp, hum
+ return 0, 0
+ except Exception as ex:
+ self.log_error(ex)
+
+ 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'])
+ if int(set_temperature) is 0:
continue
- if rpi_input['eventType']=='temperature' and (self.toFloat(rpi_input['setTemp']) < self.toFloat(self.enclosureCurrentTemperature)):
- for rpi_output in self.rpi_outputs:
- if self.toInt(rpi_input['controlledIO']) == self.toInt(rpi_output['gpioPin']):
- val = GPIO.LOW if rpi_output['activeLow'] else GPIO.HIGH
- self.writeGPIO(self.toInt(rpi_output['gpioPin']), val)
+ 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']):
+ val = GPIO.LOW if rpi_controlled_output['active_low'] else GPIO.HIGH
+ 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 " +rpi_input['setTemp']
- self.sendNotification(msg)
+ msg = ("Temperature action: enclosure temperature exceed " +
+ temperature_alarm['alarm_set_temp'])
+ self.send_notification(msg)
- def readDhtTemp(self,sensor,pin):
+ def read_dht_temp(self, sensor, pin):
try:
- script = os.path.dirname(os.path.realpath(__file__)) + "/getDHTTemp.py "
- cmd ="sudo python " +script+str(sensor)+" "+str(pin)
- if self._settings.get(["debug"]) == True and not self.disable_temeprature_log:
+ 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)
stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read()
- if self._settings.get(["debug"]) == True and not self.disable_temeprature_log:
+ if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True:
self._logger.info("Dht result: %s", stdout)
- temp,hum = stdout.split("|")
- return (self.toFloat(temp.strip()),self.toFloat(hum.strip()))
+ temp, hum = stdout.split("|")
+ return (self.to_float(temp.strip()), self.to_float(hum.strip()))
except Exception as ex:
- template = "An exception of type {0} occurred on readDhtTemp. Arguments:\n{1!r}"
- message = template.format(type(ex).__name__, ex.args)
- self._logger.warn(message)
+ self.log_error(ex)
return (0, 0)
- def readBME280Temp(self,address):
+ def read_bme280_temp(self, address):
try:
- script = os.path.dirname(os.path.realpath(__file__)) + "/BME280.py "
- cmd ="sudo python " +script +str(address)
- if self._settings.get(["debug"]) == True and not self.disable_temeprature_log:
+ 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)
stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read()
- if self._settings.get(["debug"]) == True and not self.disable_temeprature_log:
+ if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True:
self._logger.info("BME280 result: %s", stdout)
- temp,hum = stdout.split("|")
- return (self.toFloat(temp.strip()),self.toFloat(hum.strip()))
+ temp, hum = stdout.split("|")
+ return (self.to_float(temp.strip()), self.to_float(hum.strip()))
except Exception as ex:
- template = "An exception of type {0} occurred on readBME280Temp. Arguments:\n{1!r}"
- message = template.format(type(ex).__name__, ex.args)
- self._logger.warn(message)
+ self.log_error(ex)
return (0, 0)
- def readSI7021Temp(self,address):
+ def read_si7021_temp(self, address):
try:
- script = os.path.dirname(os.path.realpath(__file__)) + "/SI7021.py "
- cmd ="sudo python " +script +str(address)
- if self._settings.get(["debug"]) == True and not self.disable_temeprature_log:
+ 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)
stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read()
- if self._settings.get(["debug"]) == True and not self.disable_temeprature_log:
+ if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True:
self._logger.info("SI7021 result: %s", stdout)
- temp,hum = stdout.split("|")
- return (self.toFloat(temp.strip()),self.toFloat(hum.strip()))
+ temp, hum = stdout.split("|")
+ return (self.to_float(temp.strip()), self.to_float(hum.strip()))
except Exception as ex:
- template = "An exception of type {0} occurred on readSI7021Temp. Arguments:\n{1!r}"
- message = template.format(type(ex).__name__, ex.args)
- self._logger.warn(message)
+ self.log_error(ex)
return (0, 0)
- def read18b20Temp(self):
+ def read_18b20_temp(self, serial_number):
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
- lines = self.readraw18b20Temp()
+ lines = self.read_raw_18b20_temp(serial_number)
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
- lines = self.readraw18b20Temp()
+ lines = self.read_raw_18b20_temp(serial_number)
equals_pos = lines[1].find('t=')
if equals_pos != -1:
- temp_string = lines[1][equals_pos+2:]
- temp_c = float(temp_string) / 1000.0
+ 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)
return '{0:0.1f}'.format(temp_c)
return 0
- def readraw18b20Temp(self):
+ def read_raw_18b20_temp(self, serial_number):
base_dir = '/sys/bus/w1/devices/'
- device_folder = glob.glob(base_dir + '28*')[0]
+ device_folder = glob.glob(base_dir + str(serial_number) + '*')[0]
device_file = device_folder + '/w1_slave'
- f = open(device_file, 'r')
- lines = f.readlines()
- f.close()
+ device_file_result = open(device_file, 'r')
+ lines = device_file_result.readlines()
+ device_file_result.close()
return lines
- def readTmp102Temp(self, address):
+ def read_tmp102_temp(self, address):
try:
script = os.path.dirname(os.path.realpath(__file__)) + "/tmp102.py"
args = ["python", script, str(address)]
- if self._settings.get(["debug"]) == True and not self.disable_temeprature_log:
+ 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))
proc = Popen(args, stdout=PIPE)
stdout, _ = proc.communicate()
- if self._settings.get(["debug"]) == True and not self.disable_temeprature_log:
+ if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True:
self._logger.info("TMP102 result: %s", stdout)
- return self.toFloat(stdout.strip())
+ return self.to_float(stdout.strip())
except Exception as ex:
- template = "An exception of type {0} occurred on readTmp102Temp. Arguments:\n{1!r}"
- message = template.format(type(ex).__name__, ex.args)
- self._logger.warn(message)
+ self.log_error(ex)
return 0
-
- def handleTemperatureControl(self):
- for control in self.temperature_control:
- if control['isEnabled'] == True:
- if control['controlType'] == 'heater':
- self.currentTempControlStatus = self.toFloat(self.enclosureCurrentTemperature)