forked from ndholmes/crnw-dispatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dispatch.py
663 lines (524 loc) · 18.6 KB
/
dispatch.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Start of CR&NW Dispatching Panel
Basic theory:
- Load pile of tiles from conf file
- Draw on screen, load up in array of objects
- Each object has various attributes
- Screen x,y
- Tile type
- Block
- LC handler
- RC handler
- Block Properties
- Name
- Left End
- Right End
- OS Point Name
- IsConnector
- Signal Properties
- Name
- Switch Properties
- Name
- Normal Left Block
- Normal Right Block
- Reverse Left Block
- Reverse Right Block
- When packets come in, come into a background thread
- Maps packet input to events
- Events get handled by gui
- When clicks comes in, localize to tile block
- Normal track does nothing
- Turnouts
"""
import sys
import wx
import wx.adv
import re
import json
import paho.mqtt.client as mqtt
import queue
import socket
from cells import TrackCell, SignalCell, SwitchCell, TextCell, TrackCellType
from mrbusUtils import MRBusBit, MRBusPacket
from switch import Switch
from block import Block
from signal import Signal
from controlpoint import ControlPoint
from controlpoint_cp3 import ControlPoint_CP3
from controlpoint_xo2 import ControlPoint_XO2
from controlpoint_xo3 import ControlPoint_XO3
import datetime
# This class is used to pass packets between the mrbus/mqtt thread and the master gui thread
class MqttMRBus:
incomingPkts = queue.Queue(maxsize=500)
def __init__(self):
pass
class DispatchConsole(wx.Frame):
cells = []
blocks = [ ]
signals = []
switches = []
controlpoints = []
clickables = { }
cellXY = { }
menuHeight = 0
currentBlockType = 0
gridOn = False
layoutData = None
pktTimer = None
terminate = False
timerCnt = 0
blinkCnt = 0
blinkState = False
fcAddress = 0
secondTicker = 0
pktsLastSecond = 0
def __init__(self, layoutDataFile, mqttMRBus, mqttClient):
super().__init__(None)
self.layoutData = None
self.mqttClient = mqttClient
self.mqttMRBus = mqttMRBus
icon = wx.EmptyIcon()
icon.CopyFromBitmap(wx.Bitmap("dispatch.ico", wx.BITMAP_TYPE_ANY))
self.SetIcon(icon)
if layoutDataFile != None:
self.load_layout_data(layoutDataFile)
self.InitUI()
self.pktTimer = wx.Timer(self, 1)
self.Bind(wx.EVT_TIMER, self.OnTimer)
self.pktTimer.Start(100)
print(wx.version())
def txPacket(self, pkt):
message = pkt.toJSON()
topic = 'crnw/send'
print("Sending [%s] [%s]" % (topic, message))
self.mqttClient.publish(topic=topic, payload=message)
print("Sent")
def doDisplayUpdate(self):
dc = wx.ClientDC(self)
# Since the cells all know if they changed since last time,
# just loop through them and call draw on the ones that changed
for i in self.cells:
if i.needsRedraw():
i.draw(dc)
def applyPacket(self, pkt):
for i in range(0, len(self.blocks)):
self.blocks[i].processPacket(pkt)
for i in range(0, len(self.switches)):
self.switches[i].processPacket(pkt)
for i in range(0, len(self.signals)):
self.signals[i].processPacket(pkt)
for i in range(0, len(self.controlpoints)):
self.controlpoints[i].processPacket(pkt)
if 0 != self.fcAddress and pkt.src == self.fcAddress:
self.fastClockUpdate(pkt)
self.doDisplayUpdate()
def updateBlinkyCells(self, blinkState):
blinkiesExist = False
for signal in self.signals:
if signal.cell.isBlinky():
blinkiesExist = True
signal.cell.setBlinkState(blinkState)
return blinkiesExist
def fastClockUpdate(self, pkt):
try:
self.realFastClockUpdate(pkt)
except Exception as e:
print(e)
def realFastClockUpdate(self, pkt):
#print("Doing FC Update")
if pkt.src != self.fcAddress or pkt.cmd != ord('T') or len(pkt.data) < 12:
return
flags = pkt.data[3]
try:
fastTime = datetime.time(pkt.data[4], pkt.data[5], pkt.data[6])
except Exception as e:
print(e)
fastTime = None
fastHold = False
if (flags & 0x02) != 0:
fastHold = True
fastFactor = pkt.data[7] * 256 + pkt.data[8]
inFastMode = flags & 0x01
displayRealAMPM = False;
if (flags & 0x04) != 0:
displayRealAMPM = True
displayFastAMPM = False;
if (flags & 0x08) != 0:
displayFastAMPM = True
try:
year = (pkt.data[9] * 16) + ((pkt.data[10]<<4) & 0xF0)
month = pkt.data[10] & 0x0F
day = pkt.data[11]
realTime = datetime.datetime(year, month, day, pkt.data[0], pkt.data[1], pkt.data[2])
except Exception as e:
print(e)
realTime = None
fastTimeStr = ""
if None != fastTime:
if fastHold:
fastTimeStr = fastTime.strftime("FAST: HOLD")
elif displayFastAMPM:
fastTimeStr = fastTime.strftime("FAST: %I:%M:%S%p")
else:
fastTimeStr = fastTime.strftime("FAST: %H:%M:%S")
if None != realTime:
fastTimeStr += " "
if displayRealAMPM:
fastTimeStr += realTime.strftime("REAL: %I:%M:%S%p")
else:
fastTimeStr += realTime.strftime("REAL: %H:%M:%S")
self.SetStatusText(fastTimeStr)
def panelToPNG(self):
#Create a DC for the whole screen area
dcScreen = wx.ClientDC(self)
w,h = dcScreen.GetSize()
#Create a Bitmap that will later on hold the screenshot image
#Note that the Bitmap must have a size big enough to hold the screenshot
#-1 means using the current default colour depth
bmp = wx.Bitmap(w,h)
#Create a memory DC that will be used for actually taking the screenshot
memDC = wx.MemoryDC()
#Tell the memory DC to use our Bitmap
#all drawing action on the memory DC will go to the Bitmap now
memDC.SelectObject(bmp)
#Blit (in this case copy) the actual screen on the memory DC
#and thus the Bitmap
memDC.Blit( 0, #Copy to this X coordinate
0, #Copy to this Y coordinate
w,h,
dcScreen, #From where do we copy?
0, 0
)
#Select the Bitmap out of the memory DC by selecting a new
#uninitialized Bitmap
memDC.SelectObject(wx.NullBitmap)
img = bmp.ConvertToImage()
fileName = "myImage.png"
img.SaveFile(fileName, wx.BITMAP_TYPE_PNG)
def OnTimer(self, event):
self.timerCnt += 1
self.blinkCnt += 1
self.secondTicker += 1
if self.blinkCnt > 5:
self.blinkCnt = 0
self.blinkState = not self.blinkState
blinkiesExist = self.updateBlinkyCells(self.blinkState)
if blinkiesExist: # don't do all the display update stuff if there are no blinking elements
self.doDisplayUpdate()
if self.secondTicker >= 10:
# Anything that happens once per second happens here
if self.mqttClient.is_connected():
self.SetStatusText("PPS: %d" % self.pktsLastSecond, 2)
else:
self.SetStatusText("Disconnected", 2)
self.secondTicker = 0
self.pktsLastSecond = 0
#self.panelToPNG()
if self.mqttMRBus is not None:
while not self.mqttMRBus.incomingPkts.empty():
try:
pkt = self.mqttMRBus.incomingPkts.get_nowait()
self.pktsLastSecond += 1
#print("pkt: %s" % (pkt))
self.applyPacket(pkt)
except:
pass
if self.terminate:
self.close()
def isSignalCell(self, cellType):
if cellType in ['signal_left', 'signal_right']:
return True
return False
def isSwitchCell(self, cellType):
if cellType in ['switch_left_up', 'switch_left_down', 'switch_right_up', 'switch_right_down']:
return True
return False
def isTrackCell(self, cellType):
if cellType in ['switch_left_up', 'switch_left_down', 'switch_right_up', 'switch_right_down']:
return True
return False
def getRailroadObject(self, objectType, objectName):
objectList = {'switch':self.switches, 'signal':self.signals, 'block':self.blocks}
if objectType not in objectList.keys():
return None
for i in range(0, len(objectList[objectType])):
if objectList[objectType][i].name == objectName:
return objectList[objectType][i]
return None
def InitUI(self):
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_SIZE, self.OnPaint)
self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
titleName = "MRBus Dispatch Console"
if self.layoutData is not None and 'layoutName' in self.layoutData:
titleName = self.layoutData['layoutName']
self.SetTitle(titleName)
self.SetSize((1200,900))
self.Centre()
self.Show(True)
# create a menu bar
self.makeMenuBar()
# and a status bar in a pear tree! :)
self.statusbar = self.CreateStatusBar(3)
self.statusbar.SetStatusWidths([-1,-1,200])
self.statusbar.SetStatusText("Field 1")
self.statusbar.SetStatusText("Field 2", 1)
self.statusbar.SetStatusText("Field 3", 2)
self.ReInitUI()
def ReInitUI(self):
if self.layoutData is None:
return
self.cells = []
self.blocks = [ ]
self.signals = []
self.switches = []
self.controlpoints = []
self.clickables = { }
self.cellXY = { }
if 'layoutName' in self.layoutData:
self.SetTitle(self.layoutData['layoutName'])
if "gridOn" in self.layoutData.keys():
if 1 == self.layoutData['gridOn']:
self.gridOn = True
if "fastClockAddress" in self.layoutData.keys():
self.fcAddress = int(str(self.layoutData['fastClockAddress']), 0)
for text in self.layoutData['text']:
newCell = TextCell()
newCell.setText(text['value'])
x = int(text['x'])
y = int(text['y'])
newCell.setXY(x, y)
if text['type'] == 'blockname':
newCell.setColor('#ccffff')
self.cells.append(newCell)
for signalconfig in self.layoutData['signals']:
newSignal = Signal(signalconfig, self.txPacket)
self.signals.append(newSignal)
self.cells = self.cells + newSignal.getCells()
self.clickables[newSignal.getClickXY()] = newSignal.onLeftClick
for switchconfig in self.layoutData['switches']:
newSwitch = Switch(switchconfig, self.txPacket)
self.switches.append(newSwitch)
self.cells = self.cells + newSwitch.getCells()
self.clickables[newSwitch.getClickXY()] = newSwitch.onLeftClick
for blockconfig in self.layoutData['blocks']:
newBlock = Block(blockconfig, self.txPacket, self.cellXY)
self.blocks.append(newBlock)
self.cells = self.cells + newBlock.getCells()
for cell in self.cells:
# Build a cell finder
self.cellXY[(cell.cell_x,cell.cell_y)] = cell
for cpconfig in self.layoutData['controlPoints']:
if cpconfig['type'] == 'cp3':
newCP = ControlPoint_CP3(cpconfig, self.txPacket, self.getRailroadObject)
elif cpconfig['type'] == 'xo2':
newCP = ControlPoint_XO2(cpconfig, self.txPacket, self.getRailroadObject)
elif cpconfig['type'] == 'xo3':
newCP = ControlPoint_XO3(cpconfig, self.txPacket, self.getRailroadObject)
else:
newCP = ControlPoint(cpconfig, self.txPacket, self.getRailroadObject)
self.controlpoints.append(newCP)
def OnLeftDown(self, e):
x,y = e.GetPosition()
block_x = x//16
block_y = y//16
ctrlState = wx.GetKeyState(wx.WXK_CONTROL)
m = (block_x, block_y)
if m in self.clickables:
self.clickables[m](ctrl=ctrlState)
# dc = wx.PaintDC(self)
# self.cells[0].setSwitchPosition([1,0][self.cells[0].getSwitchPosition()])
# self.cells[0].draw(wx.PaintDC(self))
def OnPaint(self, e):
dc = wx.ClientDC(self)
(size_x, size_y) = self.GetSize()
dc.SetBackground(wx.Brush('#000'))
dc.Clear()
dc.SetBrush(wx.Brush('#000'))
if self.gridOn:
dc.SetPen(wx.Pen("#AAA", width=1))
for x in range(0, size_x//16):
for y in range(0, size_y//16):
dc.DrawRectangle(x*16, y*16, 17, 17)
dc.SetPen(wx.Pen("#FFF", width=2))
for cell in self.cells:
cell.draw(dc)
def makeMenuBar(self):
"""
A menu bar is composed of menus, which are composed of menu items.
This method builds a set of menus and binds handlers to be called
when the menu item is selected.
"""
# Make a file menu with Hello and Exit items
fileMenu = wx.Menu()
# The "\t..." syntax defines an accelerator key that also triggers
# the same event
connectMenu = wx.Menu()
connect_item = connectMenu.Append(-1, "&Connect MQTT")
disconnect_item = connectMenu.Append(-1, "&Disconnect MQTT")
open_item = fileMenu.Append(-1, "&Open New Layout Config")
fileMenu.AppendSeparator()
# When using a stock ID we don't need to specify the menu item's
# label
exitItem = fileMenu.Append(wx.ID_EXIT)
# Now a help menu for the about item
helpMenu = wx.Menu()
aboutItem = helpMenu.Append(wx.ID_ABOUT)
# Make the menu bar and add the two menus to it. The '&' defines
# that the next letter is the "mnemonic" for the menu item. On the
# platforms that support it those letters are underlined and can be
# triggered from the keyboard.
menuBar = wx.MenuBar()
menuBar.Append(fileMenu, "&File")
menuBar.Append(connectMenu, "&Network")
# Give the menu bar to the frame
self.SetMenuBar(menuBar)
# Finally, associate a handler function with the EVT_MENU event for
# each of the menu items. That means that when that menu item is
# activated then the associated handler function will be called.
self.Bind(wx.EVT_MENU, self.OnMenuItemFileLoad, open_item)
self.Bind(wx.EVT_MENU, self.OnExit, exitItem)
self.Bind(wx.EVT_MENU, self.OnAbout, aboutItem)
self.Bind(wx.EVT_MENU, self.OnMenuItemMQTTConnect, connect_item)
self.Bind(wx.EVT_MENU, self.OnMenuItemMQTTDisconnect, disconnect_item)
def OnMenuItemMQTTConnect(self, event):
self.connect(True)
def OnMenuItemMQTTDisconnect(self, event):
self.disconnect()
def load_layout_data(self, file_name):
if self.mqttClient.is_connected():
self.mqttClient.disconnect()
try:
with open(file_name) as file:
self.layoutData = json.load(file)
except json.JSONDecodeError as e:
wx.MessageBox("Cannot load layout configuration file")
print(e)
print("Cannot load layout.json configuration file")
raise
self.connect()
def disconnect(self):
if self.mqttClient.is_connected():
self.mqttClient.disconnect()
self.mqttClient.loop_stop()
def connect(self, promptForInfo = False):
self.disconnect()
mqtt_host = "crnw.drgw.net"
mqtt_port = 1883
mqtt_user = None
mqtt_pass = None
if self.layoutData is not None:
print("Have layout data")
if 'mqttHost' in self.layoutData.keys():
mqtt_host = self.layoutData['mqttHost']
print("mqtt_host=[%s]" % (mqtt_host))
if 'mqttPort' in self.layoutData.keys():
mqtt_port = int(self.layoutData['mqttPort'])
if 'mqttUser' in self.layoutData.keys():
mqtt_user = int(self.layoutData['mqttUser'])
if 'mqttPass' in self.layoutData.keys():
mqtt_pass = int(self.layoutData['mqttPass'])
if promptForInfo:
dialog = wx.TextEntryDialog(self, "Host Name", caption="MQTT Connection Information", value=mqtt_host, style=wx.OK | wx.CANCEL)
if dialog.ShowModal() == wx.ID_OK:
mqtt_host = dialog.GetValue()
else:
return
dialog = wx.TextEntryDialog(self, "Host Port", caption="MQTT Connection Information", value=str(mqtt_port), style=wx.OK | wx.CANCEL)
if dialog.ShowModal() == wx.ID_OK:
mqtt_port = int(dialog.GetValue())
else:
return
dialog = wx.TextEntryDialog(self, "User Name", caption="MQTT Connection Information", value="", style=wx.OK | wx.CANCEL)
if dialog.ShowModal() == wx.ID_OK:
mqtt_user = dialog.GetValue()
else:
return
dialog = wx.TextEntryDialog(self, "Password", caption="MQTT Connection Information", value="", style=wx.OK | wx.CANCEL | wx.TE_PASSWORD)
if dialog.ShowModal() == wx.ID_OK:
mqtt_pass = dialog.GetValue()
else:
return
print("Starting MQTT connection user=[%s], pass=[%s], host=[%s], port=[%d]" % (mqtt_user, mqtt_pass, mqtt_host, mqtt_port))
if mqtt_user != None:
self.mqttClient.username_pw_set(mqtt_user, mqtt_pass)
self.mqttClient.connect(mqtt_host, mqtt_port, 60)
self.mqttClient.loop_start()
self.mqttClient.subscribe("crnw/raw")
def OnExit(self, event):
"""Close the frame, terminating the application."""
if self.mqttClient.is_connected():
self.mqttClient.disconnect()
self.Close(True)
def OnMenuItemFileLoad(self, event):
"""Load a new configuration file"""
with wx.FileDialog(self, "Open layout configuration file", wildcard="JSON files (*.json)|*.json",
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:
if fileDialog.ShowModal() == wx.ID_CANCEL:
return # the user changed their mind
pathname = fileDialog.GetPath()
try:
self.load_layout_data(pathname)
except Exception as e:
return
self.ReInitUI()
def OnHello(self, event):
"""Say hello to the user."""
wx.MessageBox("Hello again from wxPython")
def OnAbout(self, event):
"""Display an About Dialog"""
wx.MessageBox("This is a wxPython Hello World sample",
"About Hello World 2",
wx.OK|wx.ICON_INFORMATION)
def mqtt_onMessage(client, userdata, message):
contents = message.payload.decode()
mqttMRBus = userdata['mrbus']
pkt = MRBusPacket.fromJSON(contents)
if pkt is not None:
mqttMRBus.incomingPkts.put(pkt)
#print("Adding pkt %s" % (pkt))
else:
print("Packet failed")
def mqtt_onConnect(client, userdata, flags, rc):
# logger = userdata['logger']
print("In mqtt_onConnect")
if rc == 0:
# Successful Connection
#logger.info("Successful MQTT Connection")
print("Successful MQTT Connection")
client.connected_flag = True
elif rc == 1:
print("ERROR: MQTT Incorrect Protocol Version")
client.connected_flag = False
elif rc == 2:
print("ERROR: MQTT Invalid Client ID")
client.connected_flag = False
elif rc == 3:
print("ERROR: MQTT Broker Unavailable")
client.connected_flag = False
elif rc == 4:
print("ERROR: MQTT Bad Username/Password")
client.connected_flag = False
elif rc == 5:
print("ERROR: MQTT Not Authorized")
client.connected_flag = False
else:
print("ERROR: MQTT Other Failure %d" % (rc))
client.connected_flag = False
def main():
mqttMRBus = MqttMRBus()
user_data = {'mrbus': mqttMRBus}
client_name = socket.getfqdn()
mqtt_client = mqtt.Client(client_name, userdata=user_data)
mqtt_client.on_message = mqtt_onMessage
mqtt_client.on_connect = mqtt_onConnect
app = wx.App()
#ex = DispatchConsole(layoutData, mqttMRBus, mqttClient)
ex = DispatchConsole("layout.json", mqttMRBus, mqtt_client)
ex.Show()
app.MainLoop()
if __name__ == '__main__':
main()