Skip to content

Commit cafc137

Browse files
authored
Merge pull request #41 from techman83/feat/mqtt
Add MQTT Support
2 parents 66bc142 + 2b62bcf commit cafc137

File tree

9 files changed

+142
-51
lines changed

9 files changed

+142
-51
lines changed

.github/workflows/commitlint.yml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
name: Lint Commit Messages
2+
3+
on:
4+
pull_request:
5+
6+
jobs:
7+
commitlint:
8+
runs-on: ubuntu-latest
9+
steps:
10+
- uses: actions/checkout@v3
11+
with:
12+
fetch-depth: 0
13+
- uses: wagoid/commitlint-github-action@v5

.github/workflows/release.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,14 @@ jobs:
1010
generate-release:
1111
runs-on: ubuntu-latest
1212
steps:
13-
- uses: actions/checkout@v2
13+
- uses: actions/checkout@v3
1414
- name: Set package version
1515
run: |
1616
export VERSION=$(echo $GITHUB_REF | sed 's/refs\/tags\/v//')
1717
echo "VERSION set to $VERSION"
1818
echo VERSION = \'$VERSION\' > filament_scale_enhanced/fse_version.py
1919
- name: Setup Python
20-
uses: actions/setup-python@v2
20+
uses: actions/setup-python@v4
2121
with:
2222
python-version: 3.8
2323
- name: Install OctoPrint
@@ -39,4 +39,4 @@ jobs:
3939
draft: false
4040
files: |
4141
LICENSE.txt
42-
dist/Filament_Scale_Enhanced.zip
42+
dist/Filament_Scale_Enhanced.zip

.github/workflows/test.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ jobs:
1010
test:
1111
runs-on: ubuntu-latest
1212
steps:
13-
- uses: actions/checkout@v2
13+
- uses: actions/checkout@v3
1414
- name: Setup Python
15-
uses: actions/setup-python@v2
15+
uses: actions/setup-python@v4
1616
with:
1717
python-version: 3.8
1818
- name: Install OctoPrint

README.md

Lines changed: 10 additions & 1 deletion
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`

commitlint.config.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const Configuration = {
2+
extends: ['@commitlint/config-conventional'],
3+
rules: {
4+
'subject-case': [1, 'never'],
5+
},
6+
}
7+
8+
module.exports = Configuration

filament_scale_enhanced/__init__.py

Lines changed: 93 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -7,60 +7,115 @@
77
from .hx711 import HX711
88

99
try:
10-
import RPi.GPIO as GPIO
10+
from RPi import GPIO
1111
except (ModuleNotFoundError, RuntimeError):
12-
import Mock.GPIO as GPIO # noqa: F401
12+
from Mock import GPIO # noqa: F401
1313

1414

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

2123
hx = None
2224
t = None
25+
tq = None
2326

2427
@staticmethod
25-
def get_template_configs():
26-
return [
27-
dict(type="settings", custom_bindings=True)
28-
]
28+
def get_template_configs(): # pylint: disable=arguments-differ
29+
return [{"type": "settings", "custom_bindings": True}]
2930

3031
@staticmethod
31-
def get_settings_defaults():
32-
return dict(
33-
tare=8430152,
34-
reference_unit=-411,
35-
spool_weight=200,
36-
clockpin=21,
37-
datapin=20,
38-
lastknownweight=0
39-
)
32+
def get_settings_defaults(): # pylint: disable=arguments-differ
33+
return {
34+
"tare": 8430152,
35+
"reference_unit": -411,
36+
"spool_weight": 200,
37+
"clockpin": 21,
38+
"datapin": 20,
39+
"lastknownweight": 0,
40+
}
4041

4142
@staticmethod
42-
def get_assets():
43-
return dict(
44-
js=["js/filament_scale.js"],
45-
css=["css/filament_scale.css"],
46-
less=["less/filament_scale.less"]
47-
)
43+
def get_assets(): # pylint: disable=arguments-differ
44+
return {
45+
"js": ["js/filament_scale.js"],
46+
"css": ["css/filament_scale.css"],
47+
"less": ["less/filament_scale.less"],
48+
}
49+
50+
def __init__(self):
51+
super().__init__()
52+
self.mqtt_publish = lambda *args, **kwargs: None
53+
self.mqtt = False
54+
self.mqtt_topic = ''
55+
self.last_weight = 0
56+
self.last_sent_weight = -1
4857

4958
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()
59+
try:
60+
self.hx = HX711(20, 21)
61+
self.hx.set_reading_format("LSB", "MSB")
62+
self.hx.reset()
63+
self.hx.power_up()
64+
self.t = octoprint.util.RepeatedTimer(3.0, self.check_weight)
65+
self.t.start()
66+
self.tq = octoprint.util.RepeatedTimer(10.0, self.send_weight_mqtt)
67+
self.tq.start()
68+
except Exception as err: # pylint: disable=broad-exception-caught
69+
self._logger.exception(err)
70+
71+
def on_after_startup(self):
72+
helpers = self._plugin_manager.get_helpers("mqtt", "mqtt_publish")
73+
if not helpers or "mqtt_publish" not in helpers:
74+
self._logger.debug(
75+
"MQTT plugin helpers not found scale value will not be published"
76+
)
77+
return
5678

57-
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()
79+
base_topic = self._settings.global_get(
80+
["plugins", "mqtt", "publish", "baseTopic"]
81+
)
82+
self.mqtt_topic = f"{base_topic.rstrip('/')}/plugin/{self._identifier}"
83+
self._logger.debug("Topic: %s", self.mqtt_topic)
6284

63-
# pylint: disable=line-too-long
85+
self.mqtt_publish = helpers["mqtt_publish"]
86+
self.mqtt = True
87+
self._logger.debug(
88+
"MQTT plugIn Helpers Found. Scale value will be published"
89+
)
90+
91+
def real_weight(self) -> int:
92+
tare = self._settings.get(["tare"])
93+
reference = self._settings.get(["reference_unit"])
94+
spool = self._settings.get(["spool_weight"])
95+
weight = (self.last_weight - tare) / reference
96+
return int(weight) - int(spool)
97+
98+
def send_weight_mqtt(self):
99+
if not self.mqtt:
100+
return
101+
real_weight = self.real_weight()
102+
if real_weight == self.last_sent_weight:
103+
return
104+
self.last_sent_weight = real_weight
105+
self.mqtt_publish(f'{self.mqtt_topic}/filament_weight', str(real_weight))
106+
107+
def check_weight(self):
108+
self._logger.debug("Begin hxRead")
109+
try:
110+
self.hx.power_up()
111+
v = self.hx.read_average()
112+
self.last_weight = v
113+
self._plugin_manager.send_plugin_message(self._identifier, v)
114+
self.hx.power_down()
115+
except Exception as err: # pylint: disable=broad-exception-caught
116+
self._logger.exception(err)
117+
118+
# pylint: disable=line-too-long,use-dict-literal
64119
def get_update_information(self):
65120
# Define the configuration for your plugin to use with the
66121
# Software Update Plugin here.
@@ -70,15 +125,13 @@ def get_update_information(self):
70125
filament_scale=dict(
71126
displayName="Filament Scale Plugin",
72127
displayVersion=self._plugin_version,
73-
74128
# version check: github repository
75129
type="github_release",
76130
user="techman83",
77131
repo="Filament-Scale-Enhanced",
78132
current=self._plugin_version,
79-
80133
# update method: pip
81-
pip="https://github.com/techman83/Filament-Scale-Enhanced/releases/latest/download/Filament_Scale_Enhanced.zip" # noqa: E501
134+
pip="https://github.com/techman83/Filament-Scale-Enhanced/releases/latest/download/Filament_Scale_Enhanced.zip", # noqa: E501
82135
)
83136
)
84137

filament_scale_enhanced/hx711.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
import statistics
33

44
try:
5-
import RPi.GPIO as GPIO
5+
from RPi import GPIO
66
except (ModuleNotFoundError, RuntimeError):
7-
import Mock.GPIO as GPIO
7+
from Mock import GPIO
88

99

1010
def bitsToBytes(a):

pytest.ini

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
11
[pytest]
22
python_files = tests/__init__.py
33
addopts = -p no:cacheprovider --mypy --pylint --flake8
4+
filterwarnings =
5+
ignore
6+
default:::filament_scale.*
7+
default:::tests.*

setup.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from setuptools import setup
55

66
version = {}
7-
with open("filament_scale_enhanced/fse_version.py") as fp:
7+
with open("filament_scale_enhanced/fse_version.py", encoding="utf8") as fp:
88
exec(fp.read(), version) # pylint: disable=exec-used
99

1010
try:
@@ -38,7 +38,9 @@
3838
'pytest-pylint',
3939
'pylint',
4040
'pytest-flake8',
41-
'Mock.GPIO'
41+
'Mock.GPIO',
42+
# Flake8 is likely a dead end
43+
'flake8<5',
4244
],
4345
'test': [
4446
'pytest',
@@ -47,7 +49,9 @@
4749
'pytest-pylint',
4850
'pylint',
4951
'pytest-flake8',
50-
'Mock.GPIO'
52+
'Mock.GPIO',
53+
# Flake8 is likely a dead end
54+
'flake8<5',
5155
]
5256
}
5357

0 commit comments

Comments
 (0)