-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathbrokerMySQL.py
65 lines (57 loc) · 1.85 KB
/
brokerMySQL.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import logging
import asyncio
from hbmqtt.broker import Broker
from hbmqtt.client import MQTTClient, ClientException
from hbmqtt.mqtt.constants import QOS_1
import pymysql
logger = logging.getLogger(__name__)
config = {
'listeners': {
'default': {
'type': 'tcp',
'bind': 'localhost:9999' # 0.0.0.0:1883
}
},
'sys_interval': 10,
'topic-check': {
'enabled': False
}
}
broker = Broker(config)
@asyncio.coroutine
def startBroker():
yield from broker.start()
@asyncio.coroutine
def brokerGetMessage():
C = MQTTClient()
yield from C.connect('mqtt://localhost:9999/')
yield from C.subscribe([
("LINTANGtopic/test", QOS_1)
])
logger.info('Subscribed!')
try:
for i in range(1,100):
message = yield from C.deliver_message()
packet = message.publish_packet
print(packet.payload.data.decode('utf-8'))
con = pymysql.connect(
host = 'localhost',
user = 'lintang',
password = '12345',
db = 'mqttpy',
cursorclass = pymysql.cursors.DictCursor
)
kursor = con.cursor()
sql = '''insert into mqttpy (message) values (%s)'''
val = str(packet.payload.data.decode('utf-8'))
kursor.execute(sql, val)
con.commit()
print(kursor.rowcount, 'Data saved!')
except ClientException as ce:
logger.error("Client exception : %s" % ce)
if __name__ == '__main__':
formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s"
logging.basicConfig(level=logging.INFO, format=formatter)
asyncio.get_event_loop().run_until_complete(startBroker())
asyncio.get_event_loop().run_until_complete(brokerGetMessage())
asyncio.get_event_loop().run_forever()