Skip to content

Commit 2ad00da

Browse files
authored
Fix postback (#2)
* Fixes for mqtt posback and signal handling * Remove unused signalhandler function
1 parent 122048c commit 2ad00da

File tree

1 file changed

+37
-29
lines changed

1 file changed

+37
-29
lines changed

app/main.py

+37-29
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@
1414
import paho.mqtt.publish as publish
1515
import paho.mqtt.client as mqtt
1616

17+
1718
def msg(text):
18-
print("%s : %s" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),text))
19+
print("%s : %s" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"), text))
20+
1921

2022
def getenv():
2123
conf = {
@@ -54,7 +56,7 @@ def getenv():
5456

5557
class Ec133:
5658

57-
def __init__(self, serconf, ecconf , callback=False):
59+
def __init__(self, serconf, ecconf, callback=False):
5860
self.serconf = serconf
5961
self.ecconf = ecconf
6062
self.ser = False
@@ -64,15 +66,15 @@ def __init__(self, serconf, ecconf , callback=False):
6466
self.brightness = [255, 255, 255]
6567
self.register = [255, 255, 255]
6668
self.lock = threading.Lock()
67-
69+
6870
def __del__(self):
6971
msg("Closing serial device")
7072
if bool(self.rtu):
7173
del self.rtu
7274
if bool(self.ser):
7375
del self.ser
7476

75-
def set_callback(self,callback):
77+
def set_callback(self, callback):
7678
self.callback = callback
7779

7880
def connect(self):
@@ -102,28 +104,29 @@ def connect(self):
102104
raise e
103105

104106
def set_channel(self, client, userdata, message):
107+
105108
ch = int(userdata['channel'])
106109

107-
payload_str = str(message.payload.decode("utf-8"))
108-
109110
try:
110-
payload = json.loads(payload_str)
111+
payload = json.loads(message.payload.decode("utf-8"))
111112
except Exception as e:
112-
msg("Channel%s : Malformed json message : %s" % (ch,e))
113+
msg("Channel%s : Malformed json message : %s" % (ch, e))
113114
return
114115

115116
if type(payload) is not dict:
116-
msg("Channel%s : mqtt_json format expected , got %s!" % (ch,type(payload)))
117+
msg("Channel%s : mqtt_json format expected , got %s!" % (ch, type(payload)))
117118
return
118119

119120
self.lock.acquire(blocking=True, timeout=-1)
120121

121-
msg("Channel%s: %s" % (ch,payload))
122-
123-
if payload.get("brightness",False):
122+
msg("Channel%s command: %s" % (ch, payload))
123+
124+
if payload.get("brightness", False):
124125
self.brightness[ch] = int(payload['brightness'])
126+
else:
127+
payload['brightness'] = int(self.brightness[ch])
125128

126-
if payload.get('state','ON') == 'ON':
129+
if payload.get('state', 'ON') == 'ON':
127130
self.register[ch] = int(self.brightness[ch])
128131
else:
129132
self.register[ch] = int(0)
@@ -143,7 +146,8 @@ def set_channel(self, client, userdata, message):
143146
else:
144147
time.sleep(0.02)
145148
if bool(self.callback):
146-
self.callback(ch,payload_str)
149+
150+
self.callback(ch, json.dumps(payload))
147151
self.lock.release()
148152

149153

@@ -177,33 +181,37 @@ def consume_all(self):
177181
for ch, topic in self.ctopics.items():
178182
self._consume_topic(ch)
179183

180-
def postback(self,ch,payload):
184+
def postback(self, ch, payload):
181185
auth = None
182186
if self.mqconf['username'] != None:
183-
auth = { 'username': self.mqconf['username'],
187+
auth = {'username': self.mqconf['username'],
184188
'password': self.mqconf['password']
185-
}
189+
}
186190

187191
try:
188192
publish.single(self.stopics[str(ch)],
189-
hostname = self.mqconf['address'],
190-
port=self.mqconf['port'],
191-
auth=auth,
192-
payload=payload,
193-
qos=self.mqconf['qos'],
194-
keepalive=15,
195-
retain=True)
193+
hostname=self.mqconf['address'],
194+
port=self.mqconf['port'],
195+
auth=auth,
196+
payload=payload,
197+
qos=self.mqconf['qos'],
198+
keepalive=15,
199+
retain=True)
196200
except Exception as e:
197-
msg("Unable to send channel%s state update : %s" % (ch,e))
201+
msg("Unable to send channel%s state update : %s" % (ch, e))
198202
else:
199-
msg("Channel%s state update sent" % ch)
203+
msg("Channel%s state: %s" % (ch, payload))
200204

201205

202206
def main():
203207
"""
204208
Main routine
205209
"""
206-
210+
211+
# signals are only used to break out of signal.pause()
212+
signal.signal(signal.SIGINT, (lambda signum, frame: None))
213+
signal.signal(signal.SIGTERM, (lambda signum, frame: None))
214+
207215
msg("Start ...")
208216
conf = getenv()
209217

@@ -212,7 +220,8 @@ def main():
212220
ec.connect()
213221

214222
msg("Consume mqtt topics")
215-
mq = Mqtt(conf['mqtt'], conf['ec133']['command_topics'], conf['ec133']['state_topics'], ec.set_channel)
223+
mq = Mqtt(conf['mqtt'], conf['ec133']['command_topics'],
224+
conf['ec133']['state_topics'], ec.set_channel)
216225
mq.consume_all()
217226
ec.set_callback(mq.postback)
218227

@@ -225,4 +234,3 @@ def main():
225234

226235
if __name__ == "__main__":
227236
main()
228-

0 commit comments

Comments
 (0)