Skip to content

Commit 039ab4b

Browse files
jcasseltechman83
authored andcommitted
feat: MQTT Support
Building on @jcassel's work in #40, this publishes scale changes to mqtt via the Octoprint-MQTT plugin. closes #39
1 parent e1cafe0 commit 039ab4b

File tree

2 files changed

+86
-23
lines changed

2 files changed

+86
-23
lines changed

README.md

+10-1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ or manually using this URL:
2424

2525
Once you have wired up the HX711, it must be calibrated. This is a pretty straightforward process, and all you will need is an object of known weight. Attach the load cell to your printer with the printed bracket, then follow the instructions on the plugin's settings page.
2626

27+
## MQTT
28+
29+
If you would like weight messages published via MQTT, install and configure [Octoprint-MQTT](https://plugins.octoprint.org/plugins/mqtt/)
30+
31+
Once it's configured correctly, this library will automatically detect it and start publishing messages in the following format:
32+
```
33+
baseTopic/plugin/filament_scale/filament_weight 171
34+
```
35+
2736
## Troubleshooting
2837

2938
`NaN` may be occasionally displayed in the interface when the weight can't be read correctly. The cheap boards vary in quality and are a little sensitive to vibration/power stability. Ensure the cabling is secure, you have a sufficiently sized load cell, and a good power supply.
@@ -39,4 +48,4 @@ pip install OctoPrint Mock.GPIO
3948
pip install ".[development]"
4049
```
4150

42-
Running Tests: `pytest -v`
51+
Running Tests: `pytest -v`

filament_scale_enhanced/__init__.py

+76-22
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# coding=utf-8
22
from __future__ import absolute_import
33

4+
import flask
45
import octoprint.plugin
56

67
from .fse_version import VERSION as __version__ # noqa: F401
@@ -13,19 +14,20 @@
1314

1415

1516
# pylint: disable=too-many-ancestors
16-
class FilamentScalePlugin(octoprint.plugin.SettingsPlugin,
17-
octoprint.plugin.AssetPlugin,
18-
octoprint.plugin.TemplatePlugin,
19-
octoprint.plugin.StartupPlugin):
17+
class FilamentScalePlugin(
18+
octoprint.plugin.SettingsPlugin,
19+
octoprint.plugin.AssetPlugin,
20+
octoprint.plugin.TemplatePlugin,
21+
octoprint.plugin.StartupPlugin,
22+
):
2023

2124
hx = None
2225
t = None
26+
tq = None
2327

2428
@staticmethod
2529
def get_template_configs():
26-
return [
27-
dict(type="settings", custom_bindings=True)
28-
]
30+
return [dict(type="settings", custom_bindings=True)]
2931

3032
@staticmethod
3133
def get_settings_defaults():
@@ -35,30 +37,84 @@ def get_settings_defaults():
3537
spool_weight=200,
3638
clockpin=21,
3739
datapin=20,
38-
lastknownweight=0
40+
lastknownweight=0,
3941
)
4042

4143
@staticmethod
4244
def get_assets():
4345
return dict(
4446
js=["js/filament_scale.js"],
4547
css=["css/filament_scale.css"],
46-
less=["less/filament_scale.less"]
48+
less=["less/filament_scale.less"],
4749
)
4850

51+
def __init__(self):
52+
super().__init__()
53+
self.mqtt_publish = lambda *args, **kwargs: None
54+
self.mqtt = False
55+
self.mqtt_topic = ''
56+
self.last_weight = 0
57+
self.last_sent_weight = -1
58+
4959
def on_startup(self, host, port): # pylint: disable=unused-argument
50-
self.hx = HX711(20, 21)
51-
self.hx.set_reading_format("LSB", "MSB")
52-
self.hx.reset()
53-
self.hx.power_up()
54-
self.t = octoprint.util.RepeatedTimer(3.0, self.check_weight)
55-
self.t.start()
60+
try:
61+
self.hx = HX711(20, 21)
62+
self.hx.set_reading_format("LSB", "MSB")
63+
self.hx.reset()
64+
self.hx.power_up()
65+
self.t = octoprint.util.RepeatedTimer(3.0, self.check_weight)
66+
self.t.start()
67+
self.tq = octoprint.util.RepeatedTimer(10.0, self.send_weight_mqtt)
68+
self.tq.start()
69+
except Exception as err: # pylint: disable=broad-exception-caught
70+
self._logger.exception(err)
71+
72+
def on_after_startup(self):
73+
helpers = self._plugin_manager.get_helpers("mqtt", "mqtt_publish")
74+
if not helpers or "mqtt_publish" not in helpers:
75+
self._logger.debug(
76+
"MQTT plugin helpers not found scale value will not be published"
77+
)
78+
return
79+
80+
base_topic = self._settings.global_get(
81+
["plugins", "mqtt", "publish", "baseTopic"]
82+
)
83+
self.mqtt_topic = f"{base_topic.rstrip('/')}/plugin/{self._identifier}"
84+
self._logger.debug("Topic: %s", self.mqtt_topic)
85+
86+
self.mqtt_publish = helpers["mqtt_publish"]
87+
self.mqtt = True
88+
self._logger.debug(
89+
"MQTT plugIn Helpers Found. Scale value will be published"
90+
)
91+
92+
def real_weight(self) -> int:
93+
tare = self._settings.get(["tare"])
94+
reference = self._settings.get(["reference_unit"])
95+
spool = self._settings.get(["spool_weight"])
96+
weight = (self.last_weight - tare) / reference
97+
return int(weight) - int(spool)
98+
99+
def send_weight_mqtt(self):
100+
if not self.mqtt:
101+
return
102+
real_weight = self.real_weight()
103+
if real_weight == self.last_sent_weight:
104+
return
105+
self.last_sent_weight = real_weight
106+
self.mqtt_publish(f'{self.mqtt_topic}/filament_weight', str(real_weight))
56107

57108
def check_weight(self):
58-
self.hx.power_up()
59-
v = self.hx.read()
60-
self._plugin_manager.send_plugin_message(self._identifier, v)
61-
self.hx.power_down()
109+
self._logger.debug("Begin hxRead")
110+
try:
111+
self.hx.power_up()
112+
v = self.hx.read()
113+
self.last_weight = v
114+
self._plugin_manager.send_plugin_message(self._identifier, v)
115+
self.hx.power_down()
116+
except Exception as err:
117+
self._logger.exception(err)
62118

63119
# pylint: disable=line-too-long
64120
def get_update_information(self):
@@ -70,15 +126,13 @@ def get_update_information(self):
70126
filament_scale=dict(
71127
displayName="Filament Scale Plugin",
72128
displayVersion=self._plugin_version,
73-
74129
# version check: github repository
75130
type="github_release",
76131
user="techman83",
77132
repo="Filament-Scale-Enhanced",
78133
current=self._plugin_version,
79-
80134
# update method: pip
81-
pip="https://github.com/techman83/Filament-Scale-Enhanced/releases/latest/download/Filament_Scale_Enhanced.zip" # noqa: E501
135+
pip="https://github.com/techman83/Filament-Scale-Enhanced/releases/latest/download/Filament_Scale_Enhanced.zip", # noqa: E501
82136
)
83137
)
84138

0 commit comments

Comments
 (0)