-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathNationalBusesPy3.py
792 lines (659 loc) · 37.4 KB
/
NationalBusesPy3.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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
# This software was produced by Jonathan Foot (c) 2023, all rights reserved.
# Project Website : https://departureboard.jonathanfoot.com
# Documentation : https://jonathanfoot.com/Projects/DepartureBoard
# Description : This program allows you to display a live bus departure board for any UK bus stop nationally.
# Python 3 Required.
import time
import inspect,os
import sys
import json
import argparse
from urllib.request import urlopen
from PIL import ImageFont, Image, ImageDraw
from luma.core.render import canvas
from luma.core import cmdline
from datetime import datetime
from luma.core.image_composition import ImageComposition, ComposableImage
###
# Below Declares all the program optional and compulsory settings/ start up paramters.
###
## Start Up Paramarter Checks
# Checks value is greater than Zero.
def check_positive(value):
try:
ivalue = int(value)
if ivalue <= 0:
raise argparse.ArgumentTypeError("%s is invalid, value must be an integer value greater than 0." % value)
return ivalue
except:
raise argparse.ArgumentTypeError("%s is invalid, value must be an integer value greater than 0." % value)
# Checks string is a valid time range, in the format of "00:00-24:00"
def check_time(value):
try:
datetime.strptime(value.split("-")[0], '%H:%M').time()
datetime.strptime(value.split("-")[1], '%H:%M').time()
except:
raise argparse.ArgumentTypeError("%s is invalid, value must be in the form of XX:XX-YY:YY, where the values are in 24hr format." % value)
return [datetime.strptime(value.split("-")[0], '%H:%M').time(), datetime.strptime(value.split("-")[1], '%H:%M').time()]
## Defines all optional paramaters
parser = argparse.ArgumentParser(description='National Buses Live Departure Board, to run the program you will need to pass it all of the required paramters and you may wish to pass any optional paramters.')
parser.add_argument("-t","--TimeFormat", help="Do you wish to use 24hr or 12hr time format; default is 24hr.", type=int,choices=[12,24],default=24)
parser.add_argument("-v","--Speed", help="What speed do you want the text to scroll at on the display; default is 3, must be greater than 0.", type=check_positive,default=3)
parser.add_argument("-d","--Delay", help="How long the display will pause before starting the next animation; default is 30, must be greater than 0.", type=check_positive,default=30)
parser.add_argument("-r","--RecoveryTime", help="How long the display will wait before attempting to get new data again after previously failing; default is 100, must be greater than 0.", type=check_positive,default=100)
parser.add_argument("-n","--NumberOfCards", help="The maximum number of cards you will see before forcing a new data retrieval, a limit is recommend to prevent cycling through data which may become out of data or going too far into scheduled buses; default is 9, must be greater than 0.", type=check_positive,default=9)
parser.add_argument("-y","--Rotation", help="Defines which way up the screen is rendered; default is 0", type=int,default=0,choices=[0,2])
parser.add_argument("-l","--RequestLimit", help="Defines the minium amount of time the display must wait before making a new data request; default is 75(seconds)", type=check_positive,default=75)
parser.add_argument("-z","--StaticUpdateLimit", help="Defines the amount of time the display will wait before updating the expected arrival time (based upon it's last known predicted arrival time); default is 15(seconds), this should be lower than your 'RequestLimit'", type=check_positive,default=15)
parser.add_argument("-e","--EnergySaverMode", help="To save screen from burn in and prolong it's life it is recommend to have energy saving mode enabled. 'off' is default, between the hours set the screen will turn off. 'dim' will turn the screen brightness down, but not completely off. 'none' will do nothing and leave the screen on; this is not recommend, you can change your active hours instead.", type=str,choices=["none","dim","off"],default="off")
parser.add_argument("-i","--InactiveHours", help="The period of time for which the display will go into 'Energy Saving Mode' if turned on; default is '23:00-07:00'", type=check_time,default="23:00-07:00")
parser.add_argument("-u","--UpdateDays", help="The number of days for which the Pi will wait before rebooting and checking for a new update again during your energy saving period; default 1 day (every day check).", type=check_positive, default=1)
parser.add_argument("-x","--ExcludeServices", default="", help="List any services you do not wish to view. Make sure to capitalise correctly; default is nothing, ie show every service.", nargs='*')
parser.add_argument("-m","--ViaMessageMode", choices=["full", "shorten", "reduced", "fixed", "operator"], default="fixed", help="The Transport API does not specifically store a bus routes 'Via' message. This message can be created instead using one of the following methods. full-the longest message contains both the county and suburb for each location. shorten- contains only the suburb (default). reduced- contains every C suburb visited where C is the ReducedValue 'c'. operator- only contains the name of the operator running the service. fixed- show at max F, where 'F' is the FixedLocations. This will take F locations evenly between all locations. You can also completely turn off this animation using the '--ReducedAnimations' tag.")
parser.add_argument("-c","--ReducedValue", type=check_positive, default=2, help="If you are using a 'reduced' via message this value is for every n suburbs visited report it in the via; default is 2 ie every other suburb visited report.")
parser.add_argument("-o","--Destination", choices=["1","2"], default="1", help="Depending on the region the buses destination reported maybe a generic place holder location. If this is the case you can switch to mode 2 for the last stop name.")
parser.add_argument("-f","--FixedLocations",type=check_positive, default=3, help="If you are using 'fixed' via message this value will limit the max number of via destinations. Taking F locations evenly between a route.")
parser.add_argument("-g","--ServiceName", choices=["1","2"], default="1", help="Depending on the region the buses service number maybe different to the bus service name. If this is the case you can switch between bus service nummber or name to suit your preference.")
parser.add_argument("--ExtraLargeLineName", dest='LargeLineName', action='store_true', help="By default the service number/ name assumes it will be under 3 characters in length ie 0 - 999. Some regions may use words, such as 'Indigo' Service in Nottingham. Use this tag to expand the named region. When this is on you can not also have show index turned on.")
parser.add_argument("--ShowOperator", dest='ShowOperator', action='store_true', help="If at the start of the Via message you want to say both the operator of the service and the Via message use this to turn it on; by default it is off.")
parser.add_argument("--ReducedAnimations", help="If you wish to stop the Via animation and cycle faster through the services use this tag to turn the animation off.", dest='ReducedAnimations', action='store_true')
parser.add_argument("--UnfixNextToArrive",dest='FixToArrive', action='store_false', help="Keep the bus sonnest to next arrive at the very top of the display until it has left; by default true")
parser.add_argument('--no-splashscreen', dest='SplashScreen', action='store_false',help="Do you wish to see the splash screen at start up; recommended and on by default.")
parser.add_argument('--ShowIndex', dest='ShowIndex', action='store_true',help="Do you wish to see index position for each service due to arrive. This can not be turned on with 'ExtraLargeLineName'")
parser.add_argument("--Display", default="ssd1322", choices=['ssd1322','pygame','capture','gifanim'], help="Used for development purposes, allows you to switch from a physical display to a virtual emulated one; default 'ssd1322'")
parser.add_argument("--max-frames", default=60,dest='maxframes', type=check_positive, help="Used only when using gifanim emulator, sets how long the gif should be.")
parser.add_argument("--no-console-output",dest='NoConsole', action='store_true', help="Used to stop the program outputting anything to console that isn't an error message, you might want to do this if your logging the program output into a file to record crashes.")
parser.add_argument("--filename",dest='filename', default="output.gif", help="Used mainly for development, if using a gifanim display, this can be used to set the output gif file name, this should always end in .gif.")
# parser.add_argument("--no-pip-update",dest='NoPipUpdate', action='store_true', default=False, help="By default, the program will update any software dependencies/ pip libraries, this is to ensure your display still works correctly and has the required security updates. However, if you wish you can use this tag to disable pip updates and downloads. ")
# Defines the required paramaters
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument("-a","--APIID", help="The API ID code for the Transport API, get your own from: https://developer.transportapi.com/", type=str,required=True)
requiredNamed.add_argument("-k","--APIKey", help="The API Key code for the Transport API, get your own from: https://developer.transportapi.com/", type=str,required=True)
requiredNamed.add_argument("-s","--StopID", help="The Naptan Code for the specific bus stop you wish to display.", type=str,required=True)
requiredNamed.add_argument("-b","--NextBus", choices=['yes','no'],default='no', help="Some regions (mainly any region outside London) need the NextBus API to get live data, you are however limited to only 100 API calls per day (around 1.5hrs on normal request limit settings). Once you have exceeded this limit the display cannot get any more data. Instead we recommend only getting scheduled arrival times, not using the NextBus API for full *day usage. *Assuming Energy saving mode is enabled.", type=str,required=True)
Args = parser.parse_args()
## Defines all the programs "global" variables
# Defines the fonts used throughout most the program
BasicFontHeight = 14
BasicFont = ImageFont.truetype("%s/resources/lower.ttf" % (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))), BasicFontHeight)
SmallFont = ImageFont.truetype("%s/resources/lower.ttf" % (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))),12)
# To prevent unnecessary calls to the API we assume a service will always follow the same route throughout the day
# Once we have got the destination for that service and it's "Via" message we save it here to be looked up if needed again.
Vias = {"0":"Via London Bridge"}
Dest = {"0":"Central London"}
if Args.LargeLineName and Args.ShowIndex:
print("You can not have both '--ExtraLargeLineName' and '--ShowIndex' turned on at the same time.")
sys.exit()
if Args.NextBus == 'yes':
print("Warning : Any region covered by the NextBus API has a limit of 100 API calls per day, which will not last you a full day of usage.")
###
# Below contains the class which is used to reperesent one instance of a service record. It is also responsible for getting the information from the Transport API.
###
# Used to create a blank object, needed in start-up or when there are less than 3 services currently scheduled.
class LiveTimeStud():
def __init__(self):
self.ServiceNumber = " "
self.Destination = " "
self.DisplayTime = " "
self.SchArrival = " "
self.ExptArrival = " "
self.Via = " "
self.ID = "0"
def TimePassedStatic(self):
return False
# Used to get live data from the Transport API and represent a specific services and it's details.
class LiveTime(object):
# The last time an API call was made to get new data.
LastUpdate = datetime.now()
# * Change this method to implement your own API *
def __init__(self, Data, Index):
self.ID = str(Data['id'])
self.Operator = str(Data['operator_name'])
self.ServiceNumber = self.GetServiceNumber(Data, Index)
self.Destination = str(Data['direction'])
self.SchArrival = str(Data['aimed_departure_time'])
self.ExptArrival = str(Data['best_departure_estimate'])
# The "Via" message, which lists where the service will go through, if unknown use generic message.
self.Via = self.GetComplexVia(str(Data['line_name']) )
# The formated string containing the time of arrival, to be printed on the display screen.
self.DisplayTime = self.GetDisplayTime()
#Returns the value to display the time on the board.
def GetDisplayTime(self):
# Last time the display screen was updated to reflect the new time of arrival.
self.LastStaticUpdate = datetime.now()
Arrival = datetime.strptime(str(datetime.now().date()) + " " + self.ExptArrival, '%Y-%m-%d %H:%M')
# The difference between the time now and when it is predicted to arrive.
Diff = (Arrival - datetime.now()).total_seconds() / 60
if Diff <= 2:
return ' Due'
if Diff >=15 :
return ' ' + Arrival.time().strftime("%H:%M" if (Args.TimeFormat==24) else "%I:%M")
return ' %d min' % Diff
def GetServiceNumber(self, Data, Index):
if Args.ServiceName == "1":
return "%s.%s" % (Index + 1,str(Data['line'])) if Args.ShowIndex else str(Data['line'])
elif Args.ServiceName == "2":
return "%s.%s" % (Index + 1,str(Data['line_name'])) if Args.ShowIndex else str(Data['line_name'])
# The "Via" message is not given by the API, this method generates the Via message and returns it.
def GetComplexVia(self, Service):
Via = ""
if Args.ShowOperator or Args.ViaMessageMode == "operator":
Via = "This is a " + self.Operator + " Service"
#If the data has already been retrieved don't make another unended request.
if Service in Vias:
if Args.Destination == "2":
self.Destination = Dest[Service]
return Vias[Service]
#Else this is the first time finding this service so look it up.
ViasTemp = []
try:
tempLocs = json.loads(urlopen(self.ID).read())
if Args.Destination == "2":
Dest[Service] = tempLocs['stops'][-1]['stop_name']
self.Destination = Dest[Service]
if Args.ReducedAnimations or Args.ViaMessageMode == "operator":
Vias[Service] = Via + "."
return Vias[Service]
Via += " Via: "
for loc in tempLocs['stops']:
if Args.ViaMessageMode == "full":
if (loc['locality'] + ", ") not in Via:
Via += loc['locality'] + ", "
elif Args.ViaMessageMode =="shorten":
if (str(loc['locality'].split(',')[0]) + ", ") not in Via:
Via += (str(loc['locality'].split(',')[0]) + ", ")
elif Args.ViaMessageMode =="reduced" or Args.ViaMessageMode == "fixed":
if (str(loc['locality'].split(',')[0]) + ", ") not in ViasTemp:
ViasTemp.append(str(loc['locality'].split(',')[0]) + ", ")
if Args.ViaMessageMode =="reduced":
for i in range(len(ViasTemp)):
if i % Args.ReducedValue:
Via += ViasTemp[i]
if Args.ViaMessageMode =="fixed":
x = len(ViasTemp) // Args.FixedLocations if len(ViasTemp) // Args.FixedLocations != 0 else 1
z = 0
for i in range(1,len(ViasTemp)):
if i % x == 0:
Via += ViasTemp[i]
z += 1
Vias[Service] = Via[:-2] + "."
return Vias[Service]
except Exception as e:
print("GetComplexVia(service) ERROR")
print(str(e))
Vias[Service] = Via + "."
Dest[Service] = self.Destination
return Vias[Service]
# Returns true or false dependent upon if the last time an API data call was made was over the request limit; to prevent spamming the API feed.
@staticmethod
def TimePassed():
return (datetime.now() - LiveTime.LastUpdate).total_seconds() > Args.RequestLimit
# Return true or false dependent upon if the last time the display was updated was over the static update limit. This prevents updating the display to frequently to increase performance.
def TimePassedStatic(self):
return ("min" in self.DisplayTime) and (datetime.now() - self.LastStaticUpdate).total_seconds() > Args.StaticUpdateLimit
# Calls the API and gets the data from it, returning a list of LiveTime objects to be used in the program.
# * Change this method to implement your own API *
@staticmethod
def GetData():
LiveTime.LastUpdate = datetime.now()
services = []
try:
with urlopen("https://transportapi.com/v3/uk/bus/stop/%s/live.json?app_id=%s&app_key=%s&group=no&limit=%s&nextbuses=%s" % (Args.StopID, Args.APIID, Args.APIKey, max(3,Args.NumberOfCards),Args.NextBus)) as conn:
tempServices = json.loads(conn.read())
for service in tempServices['departures']['all']:
# If not in excluded services list, convert custom API object to LiveTime object and add to list.
if str(service['line']) not in Args.ExcludeServices:
services.append(LiveTime(service, len(services)))
return services
except Exception as e:
print("GetData() ERROR")
print(str(e))
return []
###
# Below contains everything for the drawing on the board.
# All text must be converted into Images, for the image to be displayed on the display.
###
# Used to create the time on the board or any other basic text box.
class TextImage():
def __init__(self, device, text):
self.image = Image.new(device.mode, (device.width, 16))
draw = ImageDraw.Draw(self.image)
draw.text((0, 0), text, font=BasicFont, fill="white")
self.width = 5 + int(draw.textlength(text, BasicFont))
self.height = 5 + BasicFontHeight
del draw
# Used to create the Service number text box, due to needing to adjust font size dynamically.
class TextImageServiceNumber():
def __init__(self, device, text):
self.image = Image.new(device.mode, (device.width, 16))
draw = ImageDraw.Draw(self.image)
draw.text((0, 0), text, font=BasicFont if len(text) <= 3 else SmallFont, fill="white")
self.width = 5 + int(draw.textlength(text, BasicFont))
self.height = 5 + BasicFontHeight
del draw
#Used to create the destination and via board.
class TextImageComplex():
def __init__(self, device, destination, via, startOffset):
self.image = Image.new(device.mode, (device.width*20, 16))
draw = ImageDraw.Draw(self.image)
draw.text((0, 0), destination, font=BasicFont, fill="white")
draw.text((max((device.width - startOffset), int(draw.textlength(destination, font=BasicFont)) + 6), 0), via, font=BasicFont, fill="white")
self.width = device.width + int(draw.textlength(via, BasicFont)) - startOffset
self.height = 16
del draw
#Used for the opening animation, creates a static two lines of the new and previous service.
class StaticTextImage():
def __init__(self, device, service, previous_service):
self.image = Image.new(device.mode, (device.width, 32))
draw = ImageDraw.Draw(self.image)
displayTimeTempPrevious = TextImage(device, previous_service.DisplayTime)
displayTimeTemp = TextImage(device, service.DisplayTime)
draw.text((0, 16), service.ServiceNumber, font=BasicFont if len(service.ServiceNumber) <= 3 else SmallFont, fill="white")
draw.text((device.width - displayTimeTemp.width, 16), service.DisplayTime, font=BasicFont, fill="white")
draw.text((45 if Args.ShowIndex or Args.LargeLineName else 30, 16), service.Destination, font=BasicFont, fill="white")
draw.text((45 if Args.ShowIndex or Args.LargeLineName else 30, 0), previous_service.Destination, font=BasicFont, fill="white")
draw.text((0, 0), previous_service.ServiceNumber, font=BasicFont if len(previous_service.ServiceNumber) <= 3 else SmallFont, fill="white")
draw.text((device.width - displayTimeTempPrevious.width, 0), previous_service.DisplayTime, font=BasicFont, fill="white")
self.width = device.width
self.height = 32
del draw
#Used to draw a black cover over hidden stuff.
class RectangleCover():
def __init__(self, device):
w = device.width
h = 16
self.image = Image.new(device.mode, (w, h))
draw = ImageDraw.Draw(self.image)
draw.rectangle((0, 0, device.width,16), outline="black", fill="black")
del draw
self.width = w
self.height = h
#Error message displayed when no data can be found.
class NoService():
def __init__(self, device):
w = device.width
h = 16
msg = "No Scheduled Services Found"
self.image = Image.new(device.mode, (w, h))
draw = ImageDraw.Draw(self.image)
draw.text((0, 0), msg, font=BasicFont, fill="white")
self.width = int(draw.textlength(msg, font=BasicFont))
self.height = h
del draw
###
## Synchronizer, used to keep track what is busy doing work and what is ready to do more work.
###
# Used to ensure that only 1 animation is playing at any given time, apart from at the start; where all three can animate in.
class Synchroniser():
def __init__(self):
self.synchronised = {}
def busy(self, task):
self.synchronised[id(task)] = False
def ready(self, task):
self.synchronised[id(task)] = True
def is_synchronised(self):
for task in self.synchronised.items():
if task[1] == False:
return False
return True
###
## Below contains the class which represents a single row on the bus display, a LiveTime object contains all the information on a service and is then wrapped up in a ScrollTime Object
## This object contains the state of the object, such as if it is in an animation and what should be displayed to the display.
###
class ScrollTime():
WAIT_OPENING = 0
OPENING_SCROLL = 1
OPENING_END = 2
SCROLL_DECIDER = 3
SCROLLING_WAIT = 4
SCROLLING = 5
WAIT_SYNC = 6
WAIT_STUD = 7
STUD_SCROLL = 8
STUD_END = 9
STUD = -1
def __init__(self, image_composition, service, previous_service, scroll_delay, synchroniser, device, position, controller):
self.speed = Args.Speed
self.position = position
self.Controller = controller
self.image_composition = image_composition
self.rectangle = ComposableImage(RectangleCover(device).image, position=(0,16 * position + 16))
self.CurrentService = service
self.generateCard(service)
self.IStaticOld = ComposableImage(StaticTextImage(device,service, previous_service).image, position=(0, (16 * position)))
self.image_composition.add_image(self.IStaticOld)
self.image_composition.add_image(self.rectangle)
self.max_pos = self.IDestination.width
self.image_y_posA = 0
self.image_x_pos = 0
self.device = device
self.partner = None
self.delay = scroll_delay
self.ticks = 0
self.state = self.OPENING_SCROLL if service.ID != 0 else self.STUD
self.synchroniser = synchroniser
self.render()
self.synchroniser.ready(self)
# Generates all the Images (Text boxes) to be drawn on the display.
def generateCard(self,service):
displayTimeTemp = TextImage(device, service.DisplayTime)
IDestinationTemp = TextImageComplex(device, service.Destination,service.Via, displayTimeTemp.width)
self.IDestination = ComposableImage(IDestinationTemp.image.crop((0,0,IDestinationTemp.width + 10,16)), position=(45 if Args.ShowIndex or Args.LargeLineName else 30, 16 * self.position))
self.IServiceNumber = ComposableImage(TextImageServiceNumber(device, service.ServiceNumber).image.crop((0,0,45 if Args.ShowIndex or Args.LargeLineName else 30,16)), position=(0, 16 * self.position))
self.IDisplayTime = ComposableImage(displayTimeTemp.image, position=(device.width - displayTimeTemp.width, 16 * self.position))
# Called when you have new/updated information from an API call and want to update the objects predicted arrival time.
def updateCard(self, newService, device):
self.state = self.SCROLL_DECIDER
self.synchroniser.ready(self)
self.image_composition.remove_image(self.IDisplayTime)
displayTimeTemp = TextImage(device, newService.DisplayTime)
self.IDisplayTime = ComposableImage(displayTimeTemp.image, position=(device.width - displayTimeTemp.width, 16 * self.position))
self.image_composition.add_image(self.IDisplayTime)
self.image_composition.refresh()
# Called when you want to change the row from one service to another.
def changeCard(self, newService, device):
if newService.ID == "0" and self.CurrentService.ID == "0":
self.state = self.STUD
self.synchroniser.ready(self)
return
self.synchroniser.busy(self)
self.IStaticOld = ComposableImage(StaticTextImage(device,newService, self.CurrentService).image, position=(0, (16 * self.position)))
self.image_composition.add_image(self.IStaticOld)
self.image_composition.add_image(self.rectangle)
if self.CurrentService.ID != "0":
self.image_composition.remove_image(self.IDestination)
self.image_composition.remove_image(self.IServiceNumber)
self.image_composition.remove_image(self.IDisplayTime)
del self.IDestination
del self.IServiceNumber
del self.IDisplayTime
if self.partner != None and self.partner.CurrentService.ID != "0":
self.partner.refresh()
self.image_composition.refresh()
self.generateCard(newService)
self.CurrentService = newService
self.max_pos = self.IDestination.width
self.state = self.WAIT_STUD if (newService.ID == "0") else self.WAIT_OPENING
# Used when you want to delete the row/object.
def delete(self):
try:
self.image_composition.remove_image(self.IStaticOld)
self.image_composition.remove_image(self.rectangle)
except:
pass
try:
self.image_composition.remove_image(self.IDestination)
self.image_composition.remove_image(self.IServiceNumber)
self.image_composition.remove_image(self.IDisplayTime)
except:
pass
self.image_composition.refresh()
# Called upon each time you want to get the next frame for the display.
def tick(self):
#Update X min till arrival.
if self.CurrentService.TimePassedStatic() and (self.state == self.SCROLL_DECIDER or self.state == self.SCROLLING_WAIT or self.state == self.SCROLLING or self.state == self.WAIT_SYNC):
self.image_composition.remove_image(self.IDisplayTime)
self.CurrentService.DisplayTime = self.CurrentService.GetDisplayTime()
displayTimeTemp = TextImage(device, self.CurrentService.DisplayTime)
self.IDisplayTime = ComposableImage(displayTimeTemp.image, position=(device.width - displayTimeTemp.width, 16 * self.position))
self.image_composition.add_image(self.IDisplayTime)
self.image_composition.refresh()
if self.state == self.WAIT_OPENING:
if not self.is_waiting():
self.state = self.OPENING_SCROLL
elif self.state == self.OPENING_SCROLL:
if self.image_y_posA < 16:
self.render()
self.image_y_posA += self.speed
else:
self.state = self.OPENING_END
elif self.state == self.OPENING_END:
self.image_x_pos = 0
self.image_y_posA = 0
self.image_composition.remove_image(self.IStaticOld)
self.image_composition.remove_image(self.rectangle)
del self.IStaticOld
self.image_composition.add_image(self.IDestination)
self.image_composition.add_image(self.IServiceNumber)
self.image_composition.add_image(self.IDisplayTime)
self.render()
self.synchroniser.ready(self)
self.state = self.SCROLL_DECIDER
elif self.state == self.SCROLL_DECIDER:
if self.synchroniser.is_synchronised():
if not self.is_waiting():
if self.synchroniser.is_synchronised():
self.synchroniser.busy(self)
if Args.ReducedAnimations:
self.state = self.WAIT_SYNC
elif self.CurrentService.ID == "0":
self.synchroniser.ready(self)
self.state = self.STUD
else:
self.state = self.SCROLLING_WAIT
elif self.state == self.SCROLLING_WAIT:
if not self.is_waiting():
self.state = self.SCROLLING
elif self.state == self.SCROLLING:
if self.image_x_pos < self.max_pos:
self.render()
self.image_x_pos += self.speed
else:
self.state = self.WAIT_SYNC
elif self.state == self.WAIT_SYNC:
if self.image_x_pos != 0:
self.image_x_pos = 0
self.render()
else:
if not self.is_waiting():
self.Controller.requestCardChange(self, self.position + 1)
elif self.state == self.WAIT_STUD:
if not self.is_waiting():
self.state = self.STUD_SCROLL
elif self.state == self.STUD_SCROLL:
if self.image_y_posA < 16:
self.render()
self.image_y_posA += self.speed
else:
self.state = self.STUD_END
elif self.state == self.STUD_END:
self.image_x_pos = 0
self.image_y_posA = 0
self.image_composition.remove_image(self.IStaticOld)
self.image_composition.remove_image(self.rectangle)
del self.IStaticOld
self.render()
self.synchroniser.ready(self)
self.state = self.STUD
elif self.state == self.STUD:
if not self.is_waiting():
self.Controller.requestCardChange(self, self.position + 1)
# Sets the image offest for the animation, telling it how to render.
def render(self):
if(self.state == self.SCROLLING or self.state == self.WAIT_SYNC):
self.IDestination.offset = (self.image_x_pos, 0)
if(self.state == self.OPENING_SCROLL or self.state == self.STUD_SCROLL):
self.IStaticOld.offset= (0,self.image_y_posA)
# Used to reset the image on the display.
def refresh(self):
if hasattr(self, 'IDestination') and hasattr(self, 'IServiceNumber') and hasattr(self, 'IDisplayTime'):
self.image_composition.remove_image(self.IDestination)
self.image_composition.remove_image(self.IServiceNumber)
self.image_composition.remove_image(self.IDisplayTime)
self.image_composition.add_image(self.IDestination)
self.image_composition.add_image(self.IServiceNumber)
self.image_composition.add_image(self.IDisplayTime)
# Used to add a partner; this is the row below it self. Used when needed to tell partner to redraw itself
# on top of the row above it (layering the text boxes correctly)
def addPartner(self, partner):
self.partner = partner
# Used to add a time delay between animations.
def is_waiting(self):
self.ticks += 1
if self.ticks > self.delay:
self.ticks = 0
return False
return True
###
## Board Controller
## Defines the board which controls what each off the rows in the display will show at any time.
###
class boardFixed():
def __init__(self, image_composition, scroll_delay, device):
self.Services = LiveTime.GetData()
self.synchroniser = Synchroniser()
self.scroll_delay = scroll_delay
self.image_composition = image_composition
self.device = device
self.ticks = 0
self.setInitalCards()
self.State = "alive"
NoServiceTemp = NoService(device)
self.NoServices = ComposableImage(NoServiceTemp.image, position=(int(device.width/2- NoServiceTemp.width/2),int(device.height/2-NoServiceTemp.height/2)))
self.top.addPartner(self.middel)
self.middel.addPartner(self.bottom)
# Set up the cards for the initial starting animation.
def setInitalCards(self):
self.top = ScrollTime(image_composition, len(self.Services) >= 1 and self.Services[0] or LiveTimeStud(),LiveTimeStud(), self.scroll_delay, self.synchroniser, device, 0, self)
self.middel = ScrollTime(image_composition, len(self.Services) >= 2 and self.Services[1] or LiveTimeStud(),LiveTimeStud(), self.scroll_delay, self.synchroniser, device, 1,self)
self.bottom = ScrollTime(image_composition, len(self.Services) >= 3 and self.Services[2] or LiveTimeStud(),LiveTimeStud(), self.scroll_delay, self.synchroniser, device, 2, self)
self.x = len(self.Services) < 3 and len(self.Services) or 3
# Called upon every time a new frame is needed.
def tick(self):
#If no data can be found.
if len(self.Services) == 0:
if self.ticks == 0:
self.image_composition.add_image(self.NoServices)
#Wait a period of time then try getting new data again.
if not self.is_waiting():
self.top.delete()
del self.top
self.middel.delete()
del self.middel
self.bottom.delete()
del self.bottom
self.image_composition.remove_image(self.NoServices)
self.State = "dead"
else:
# Tell all rows of the display next frame is wantted.
self.top.tick()
self.middel.tick()
self.bottom.tick()
# Called when a row has completed one cycle of it's states and requests to change card, here the program decides what to do.
def requestCardChange(self, card, row):
# If it has cycled through all cards, cycle from start again, unless enough time has passed for a new API request.
if (self.x > Args.NumberOfCards or self.x >len(self.Services)-1):
self.x = 1 if Args.FixToArrive else 0
if LiveTime.TimePassed():
self.Services = LiveTime.GetData()
print_safe("New Data Retrieved %s" % datetime.now().time())
# If there are more rows (3) than there is services scheduled show nothing.
if row > len(self.Services):
card.changeCard(LiveTimeStud(),device)
return
# If there is exactly 3 or less services the order in which they appear on the display is fixed to the order they will arrive in.
if len(self.Services) <= 3:
if self.Services[row-1].ID == card.CurrentService.ID:
card.updateCard(self.Services[row-1],device)
else:
card.changeCard(self.Services[row-1],device)
else:
# If not they will cycled around showing whatever card is next.
if Args.FixToArrive and row == 1:
if self.Services[0].ID == card.CurrentService.ID:
card.updateCard(self.Services[0],device)
else:
card.changeCard(self.Services[0],device)
else:
if self.Services[self.x % len(self.Services)].ID == card.CurrentService.ID:
card.updateCard(self.Services[self.x % len(self.Services)],device)
else:
card.changeCard(self.Services[self.x % len(self.Services)],device)
if not (Args.FixToArrive and row == 1):
self.x = self.x + 1
# Used to add a time delay if there was an error with the last API request (providing a back off and wait mechanism)
def is_waiting(self):
self.ticks += 1
if self.ticks > Args.RecoveryTime:
self.ticks = 0
return False
return True
# Used to work out if the current time is between the inactive hours.
def is_time_between():
# If check time is not given, default to current UTC time
check_time = datetime.now().time()
if Args.InactiveHours[0] < Args.InactiveHours[1]:
return check_time >= Args.InactiveHours[0] and check_time <= Args.InactiveHours[1]
else: # crosses midnight
return check_time >= Args.InactiveHours[0] or check_time <= Args.InactiveHours[1]
# Checks that the user has allowed outputting to console.
def print_safe(msg):
if not Args.NoConsole:
print(msg)
###
## Main
## Connects to the display and makes it update forever until ended by the user with a ctrl-c
###
DisplayParser = cmdline.create_parser(description='Dynamically connect to either a virtual or physical display.')
device = cmdline.create_device( DisplayParser.parse_args(['--display', str(Args.Display),'--interface','spi','--width','256','--rotate',str(Args.Rotation)]))
if Args.Display == 'gifanim':
device._filename = str(Args.filename)
device._max_frames = int(Args.maxframes)
image_composition = ImageComposition(device)
board = boardFixed(image_composition,Args.Delay,device)
FontTime = ImageFont.truetype("%s/resources/time.otf" % (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))),16)
device.contrast(255)
energyMode = "normal"
StartUpDate = datetime.now().date()
# Draws the clock and tells the rest of the display next frame wanted.
def display():
board.tick()
msgTime = str(datetime.now().strftime("%H:%M" if (Args.TimeFormat==24) else "%I:%M"))
with canvas(device, background=image_composition()) as draw:
image_composition.refresh()
draw.multiline_text(((device.width - int(draw.textlength(msgTime, FontTime)))/2, device.height-16), msgTime, font=FontTime, align="center")
# Draws the splash screen on start up
def Splash():
if Args.SplashScreen:
with canvas(device) as draw:
draw.multiline_text((64, 10), "Departure Board", font= ImageFont.truetype("%s/resources/Bold.ttf" % (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))),20), align="center")
draw.multiline_text((45, 35), "Version : 2.6.OT - By Jonathan Foot", font=ImageFont.truetype("%s/resources/Skinny.ttf" % (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))),15), align="center")
time.sleep(30) #Wait such a long time to allow the device to startup and connect to a WIFI source first.
try:
Splash()
# Run the program forever
while True:
time.sleep(0.02)
if 'board' in globals() and board.State == "dead":
del board
board = boardFixed(image_composition,Args.Delay,device)
device.clear()
# Turns the display into one of the energy saving modes if in the correct time and enabled.
if Args.EnergySaverMode != "none" and is_time_between():
# Check for program updates and restart the pi every 'UpdateDays' Days.
# if (datetime.now().date() - StartUpDate).days >= Args.UpdateDays:
# print_safe("Checking for updates and then restarting Pi.")
# os.system("sudo git -C %s pull; sudo reboot" % (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))))
# sys.exit()
if Args.EnergySaverMode == "dim":
if energyMode == "normal":
device.contrast(15)
energyMode = "dim"
display()
elif Args.EnergySaverMode == "off":
if energyMode == "normal":
del board
device.clear()
device.hide()
energyMode = "off"
else:
if energyMode != "normal":
device.contrast(255)
if energyMode == "off":
device.show()
Splash()
board = boardFixed(image_composition,Args.Delay,device)
energyMode = "normal"
display()
except KeyboardInterrupt:
pass