Skip to content

Commit 450138a

Browse files
committed
decorator based subscription
1 parent 0bccaf5 commit 450138a

File tree

4 files changed

+73
-0
lines changed

4 files changed

+73
-0
lines changed

examples/decorator.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class IoTCore:
2+
def __init__(self):
3+
self.subs = {} # Dictionary to store topic-callback function pairs
4+
5+
def accept(self, topic):
6+
def decorator(func):
7+
self.subs[topic] = func # Store the topic and callback function in the dictionary
8+
9+
def wrapper(request):
10+
func(request)
11+
12+
return wrapper
13+
14+
return decorator
15+
16+
def temp(self):
17+
print("do something")
18+
19+
20+
iot = IoTCore()
21+
22+
23+
@iot.accept(topic="request/temperature/data")
24+
def temperature_data_handler(request):
25+
print("Handling temperature data request:", request)
26+
27+
28+
# Simulate a temperature data request
29+
request_data = {
30+
'topic': 'request/temperature/data',
31+
'data': {
32+
'temperature': 25.5
33+
}
34+
}
35+
36+
37+
def main():
38+
temperature_data_handler(request_data)
39+
iot.temp()
40+
41+
42+
if __name__ == "__main__":
43+
main()

examples/fastapi/main.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,7 @@ def pub():
3434
iot.publish("iot", "test")
3535
return {"response": "published"}
3636

37+
38+
@iot.accept(topic="request/temperature/data")
39+
def temperature_data(request):
40+
print(request)

iotcore/mqtt.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,15 @@ def iot_core_callback(self, topic, data):
4343
subscription.callback(data)
4444
except KeyError:
4545
print(f"invalid topic : {topic}")
46+
47+
def accept(self, topic):
48+
def decorator(func):
49+
self.subscribed_topics[hash(topic)] = func # Store the topic and callback function in the dictionary
50+
51+
def wrapper(request):
52+
func(request)
53+
54+
return wrapper
55+
56+
return decorator
57+

iotcore/request.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
2+
class Request(object):
3+
4+
def __int__(self, topic, data):
5+
self._topic = topic
6+
self._data = data
7+
8+
def raw(self):
9+
return self._data
10+
11+
def data(self):
12+
data_array = bytes(self._data)
13+
data_string = data_array.decode('utf-8')
14+
return data_string

0 commit comments

Comments
 (0)