-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemulator.py
320 lines (295 loc) · 12.9 KB
/
emulator.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# Class of home IoT devices (emulators) like: DHT, Elec meter, water meter and etc.
import sys
import random
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from init import *
from agent import Mqtt_client
from icecream import ic
from datetime import datetime
import logging
from pathlib import Path
# Gets or creates a logger
logger = logging.getLogger(__name__)
# set log level
logger.setLevel(logging.DEBUG)
# define file handler and set formatter
file_handler = logging.FileHandler('logfile_emulator.log')
formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(name)s : %(message)s')
file_handler.setFormatter(formatter)
# add file handler to logger
logger.addHandler(file_handler)
##
font_t = QFont("Bahnschrift", 10, QFont.Bold)
font = QFont("Bahnschrift", 10)
##
def time_format():
return f'{datetime.now()} Emulator|> '
ic.configureOutput(prefix=time_format)
ic.configureOutput(includeContext=False) # use True for including script file context file
# Creating Client name - should be unique
global clientname, tmp_upd
r=random.randrange(1,10000000)
clientname="IOT_clYT-Id-"+str(r)
class MC(Mqtt_client):
def __init__(self):
super().__init__()
def on_message(self, client, userdata, msg):
topic=msg.topic
m_decode=str(msg.payload.decode("utf-8","ignore"))
ic("message from:"+topic, m_decode)
try:
mainwin.connectionDock.update_btn_state(m_decode)
except:
ic("fail in update button state")
class ConnectionDock(QDockWidget):
"""Main """
def __init__(self, mc, name, topic_sub, topic_pub):
QDockWidget.__init__(self)
self.name = name
self.topic_sub = topic_sub
self.topic_pub = topic_pub
self.mc = mc
##
self.setFont(font)
##
self.mc.set_on_connected_to_form(self.on_connected)
self.eHostInput=QLineEdit()
self.eHostInput.setInputMask('999.999.999.999')
self.eHostInput.setText(broker_ip)
self.ePort=QLineEdit()
self.ePort.setValidator(QIntValidator())
self.ePort.setMaxLength(4)
self.ePort.setText(broker_port)
self.eClientID=QLineEdit()
global clientname
self.eClientID.setText(clientname)
self.eUserName=QLineEdit()
self.eUserName.setText(username)
self.ePassword=QLineEdit()
self.ePassword.setEchoMode(QLineEdit.Password)
self.ePassword.setText(password)
self.eKeepAlive=QLineEdit()
self.eKeepAlive.setValidator(QIntValidator())
self.eKeepAlive.setText("60")
self.eSSL=QCheckBox()
self.eCleanSession=QCheckBox()
self.eCleanSession.setChecked(True)
self.eConnectbtn=QPushButton("Enable/Connect", self)
self.eConnectbtn.setToolTip("click me to connect")
self.eConnectbtn.clicked.connect(self.on_button_connect_click)
self.eConnectbtn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #ff0000, stop:0.5 #ff4d4d, stop:1 #b30000)")
formLayot=QFormLayout()
if 'DHT' in self.name:
self.ePublisherTopic=QLineEdit()
self.ePublisherTopic.setText(self.topic_pub)
self.Temperature=QLineEdit()
self.Temperature.setText('')
self.Humidity=QLineEdit()
self.Humidity.setText('')
formLayot.addRow("Turn On/Off",self.eConnectbtn)
formLayot.addRow("Pub topic",self.ePublisherTopic)
formLayot.addRow("Temperature",self.Temperature)
formLayot.addRow("Humidity",self.Humidity)
elif 'Air' in self.name:
self.eSubscribeTopic=QLineEdit()
self.eSubscribeTopic.setText(self.topic_sub)
self.ePushtbtn=QPushButton("", self)
self.ePushtbtn.setToolTip("Push me")
self.ePushtbtn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #007bff, stop:0.5 #4d8fff, stop:1 #003cb3)")
self.Temperature=QLineEdit()
self.Temperature.setText('')
formLayot.addRow("Turn On/Off",self.eConnectbtn)
formLayot.addRow("Sub topic",self.eSubscribeTopic)
formLayot.addRow("Status",self.ePushtbtn)
formLayot.addRow("Temperature",self.Temperature)
elif 'Elec' in self.name:
self.ePublisherTopic=QLineEdit()
self.ePublisherTopic.setText(self.topic_pub)
self.Temperature=QLineEdit()
self.Temperature.setText('')
self.Humidity=QLineEdit()
self.Humidity.setText('')
formLayot.addRow("Turn On/Off",self.eConnectbtn)
formLayot.addRow("Pub topic",self.ePublisherTopic)
formLayot.addRow("Electricity",self.Temperature)
formLayot.addRow("Water",self.Humidity)
else:
self.eSubscribeTopic=QLineEdit()
self.eSubscribeTopic.setText(self.topic_sub)
self.ePushtbtn=QPushButton("", self)
self.ePushtbtn.setToolTip("Push me")
self.ePushtbtn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #007bff, stop:0.5 #4d8fff, stop:1 #003cb3)")
self.Temperature=QLineEdit()
self.Temperature.setText('')
formLayot.addRow("Turn On/Off",self.eConnectbtn)
formLayot.addRow("Sub topic",self.eSubscribeTopic)
formLayot.addRow("Status",self.ePushtbtn)
formLayot.addRow("Temperature",self.Temperature)
widget = QWidget(self)
widget.setLayout(formLayot)
self.setTitleBarWidget(widget)
self.setWidget(widget)
self.setWindowTitle("IoT Emulator")
def on_connected(self):
self.eConnectbtn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #00FF00, stop:0.5 #66FF66, stop:1 #00CC00)")
def on_button_connect_click(self):
self.mc.set_broker(self.eHostInput.text())
self.mc.set_port(int(self.ePort.text()))
self.mc.set_clientName(self.eClientID.text())
self.mc.set_username(self.eUserName.text())
self.mc.set_password(self.ePassword.text())
self.mc.connect_to()
self.mc.start_listening()
def push_button_click(self):
self.mc.publish_to(self.ePublisherTopic.text(), '"value":1')
def update_btn_state(self,messg):
global tmp_upd
if 'Set' in messg:
tmp='12'
self.ePushtbtn.setStyleSheet("background-color: purple")
try:
tmp=messg.split('Set temperature to: ')[1]
self.Temperature.setText(tmp)
except:
ic("failure in parsing temperature")
tmp_upd=tmp
# elif 'OFF' in messg:
# self.ePushtbtn.setStyleSheet("background-color: gray")
class MainWindow(QMainWindow):
def __init__(self, args, parent=None):
QMainWindow.__init__(self, parent)
# Parse sys arg values
global tmp_upd
self.name = args[1]
self.units = args[2]
self.topic_sub = comm_topic+args[3]+'/sub'
self.topic_pub = comm_topic+args[3]+'/pub'
self.update_rate = args[4]
# Init of Mqtt_client class
self.mc=MC()
if 'DHT' in self.name:
tmp_upd = 22
# Creating timer for update rate support
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.create_data)
self.timer.start(int(self.update_rate)*1000) # in msec
elif 'Meter' in self.name:
# Creating timer for update rate support
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.create_data_EW)
self.timer.start(int(self.update_rate)*1000) # in msec
elif 'Airconditioner' in self.name:
# Creating timer for update rate support
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.create_data_Air)
self.timer.start(int(self.update_rate)*1000) # in msec
elif 'Freezer' in self.name:
tmp_upd = -5
# Creating timer for update rate support
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.create_data_Fr)
self.timer.start(int(self.update_rate)*1000) # in msec
elif 'Boiler' in self.name:
tmp_upd = 80
# Creating timer for update rate support
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.create_data_Bo)
self.timer.start(int(self.update_rate)*1000) # in msec
elif 'Refrigerator' in self.name:
tmp_upd = 4
# Creating timer for update rate support
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.create_data_Ref)
self.timer.start(int(self.update_rate)*1000) # in msec
# general GUI settings
self.setUnifiedTitleAndToolBarOnMac(True)
# set up main window
self.setGeometry(30, 600, 350, 200)
self.setWindowTitle(self.name)
# Init QDockWidget objects
self.connectionDock = ConnectionDock(self.mc, self.name, self.topic_sub, self.topic_pub)
self.addDockWidget(Qt.TopDockWidgetArea, self.connectionDock)
def create_data(self):
global tmp_upd
ic('Next update')
temp=tmp_upd+random.randrange(1,10)
hum=74+random.randrange(1,25)
current_data= 'From: ' + self.name+ ' Temperature: '+str(temp)+' Humidity: '+str(hum)
self.connectionDock.Temperature.setText(str(temp))
self.connectionDock.Humidity.setText(str(hum))
if not self.mc.connected:
self.connectionDock.on_button_connect_click()
self.mc.publish_to(self.topic_pub,current_data)
def create_data_EW(self):
ic('Electricity-Water data update')
hour_delta_w = 0.42/24
hour_delta_el = (670/17)/24
elec= format(hour_delta_el+random.randrange(-100,100)/300, '.2f')
water=format(hour_delta_w +random.randrange(-10,10)/1000, '.3f')
current_data= 'From: ' + self.name + ' Electricity: '+str(elec)+' Water: '+str(water)
self.connectionDock.Temperature.setText(str(elec))
self.connectionDock.Humidity.setText(str(water))
if not self.mc.connected:
self.connectionDock.on_button_connect_click()
self.mc.publish_to(self.topic_pub,current_data)
def create_data_Air(self):
ic('Airconditioner data update')
if not self.mc.connected:
self.connectionDock.on_button_connect_click()
if not self.mc.subscribed:
self.mc.subscribe_to(self.topic_sub)
def create_data_Fr(self):
global tmp_upd
ic('Freezer data update')
if not self.mc.connected:
self.connectionDock.on_button_connect_click()
if not self.mc.subscribed:
self.mc.subscribe_to(self.topic_sub)
temp=tmp_upd+random.randrange(-10,-5)/10
current_data= 'Temperature: '+str(temp)
self.connectionDock.Temperature.setText(str(temp))
self.mc.publish_to(self.topic_pub,current_data)
def create_data_Ref(self):
global tmp_upd
ic('Refrigerator data update')
if not self.mc.connected:
self.connectionDock.on_button_connect_click()
if not self.mc.subscribed:
self.mc.subscribe_to(self.topic_sub)
temp=tmp_upd+random.randrange(-10,-5)/10
current_data= 'Temperature: '+str(temp)
self.connectionDock.Temperature.setText(str(temp))
self.mc.publish_to(self.topic_pub,current_data)
def create_data_Bo(self):
global tmp_upd
ic('Boiler data update')
if not self.mc.connected:
self.connectionDock.on_button_connect_click()
if not self.mc.subscribed:
self.mc.subscribe_to(self.topic_sub)
temp=tmp_upd+random.randrange(1,20)/2
current_data= 'Temperature: '+str(temp)
self.connectionDock.Temperature.setText(str(temp))
self.mc.publish_to(self.topic_pub,current_data)
if __name__ == '__main__':
try:
app = QApplication(sys.argv)
argv=sys.argv
#app.setStyle("Windows") #####
#
app.setStyleSheet(Path('clean.css').read_text())
#
if len(sys.argv)==1:
argv.append('Airconditioner')
argv.append('Celsius')
argv.append('air-1')
argv.append('7')
mainwin = MainWindow(argv)
#mainwin.setStyleSheet("background-color: #AED6F1;")
mainwin.show()
app.exec_()
except:
logger.exception("Crash!")