-
Notifications
You must be signed in to change notification settings - Fork 3
/
controller.py.save
executable file
·656 lines (517 loc) · 22.3 KB
/
controller.py.save
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
#!/usr/bin/python3
# Hybrid Powertrain Controller
# Copyright (C) 2014 Simon Howroyd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#############################################################################
# Import libraries
import argparse, sys, time, select
from display import h100Display
from h100Controller import H100
from switch import switch
from tdiLoadbank import loadbank
from scheduler import scheduler
from esc import esc
from timer import timer
# Inspect user input arguments
def _parse_commandline():
# Define the parser
parser = argparse.ArgumentParser(description='Fuel Cell Controller by Simon Howroyd 2014')
# Define aguments
parser.add_argument('--out', type=str, default='', help='Save my data to USB stick')
parser.add_argument('--purge', type=str, default='horizon', help='Change purge controller')
parser.add_argument('--verbose', type=int, default=0, help='Print log to screen')
parser.add_argument('--profile', type=str, default='', help='Name of flight profile file')
parser.add_argument('--timer', type=int, default=0, help='Performance monitor timer')
# Return what was argued
return parser.parse_args()
# Function to write list data
def _writer(function, data):
try:
function("{0:.1f}".format(data) + '\t', end='')
except (ValueError, TypeError): # Not a print function
function(str(data) + '\t')
return data
# Function to print the header
def _display_header(*destination):
header = ("\n\n\n"
+ "Hybrid Powertrain Controller \n"
+ "with PEMFC Control \n"
+ "for the Horizon H-100 Fuel Cell \n"
+ "(c) Simon Howroyd and Jason James 2014 \n"
+ "Loughborough University \n"
+ "\n"
+ "This program is distributed in the hope that it will be useful, \n"
+ "but WITHOUT ANY WARRANTY; without even the implied warranty of \n"
+ "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n"
+ "GNU General Public License for more details. \n\n"
+ str(time.asctime())
+ "\n\n")
# Write the data to destination
for write in destination:
_writer(write, header),
# Return the data
return header
# Function to print the time
def _print_time(my_time, *destination):
# Get the time data
delta = [
time.time(),
time.time() - timeStart,
my_time.delta,
]
# Write the data to destination
for write in destination:
for cell in delta:
_writer(write, cell)
# Return the data
return delta
# Function to print the state
def _print_state(h100, *destination):
# Get the state from the controller
state = h100.state
# Convert state to code for Matlab compatibility
if "off" iRn state:
state = 1
elif "startup" in state:
state = 2
elif "on" in state:
state = 3
elif "shutdown" in state:
state = 4
elif "error" in state:
state = -1
else:
state = 999
# Write the data to destination
for write in destination:
_writer(write, state),
# Return the data
return state
# Function to print the electrical data
def _print_electric(h100, load='', *destination):
# Get the data from the controller
electric = [
h100.voltageHybrid[0], # FC output
h100.voltage[0],
h100.currentHybrid[0],
h100.current[0],
# h100.power[0],
h100.voltageHybrid[1], # Battery output
h100.voltage[1],
h100.currentHybrid[1],
h100.current[1],
# h100.power[1],
h100.voltageHybrid[2], # System output
h100.voltage[2],
h100.currentHybrid[2],
h100.current[2],
# h100.power[2]
]
# If there is a digital loadbank connected get that data
if load:
# Convert mode to a code for Matlab compatibility
if "CURRENT" in load.mode:
mode_code = "1 " + load.mode.split()[1]
elif "VOLTAGE" in load.mode:
mode_code = "2 " + load.mode.split()[1]
elif "POWER" in load.mode:
mode_code = "3 " + load.mode.split()[1]
else:
mode_code = 999
# Add the load data to the controller data
electric = electric + [mode_code,
load.voltage,
load.current,
load.power]
# Write the data to destination
for write in destination:
for cell in electric:
_writer(write, cell)
# Return the data
return electric
# Function to print the electrical data
def _print_voltage(h100, load='', *destination):
# Get the data from the controller
voltage = [
h100.voltageHybrid[0], # FC output
h100.voltage[0],
h100.voltageHybrid[1], # Battery output
h100.voltage[1],
h100.voltageHybrid[2], # System output
h100.voltage[2],
]
# If there is a digital loadbank connected get that data
if load:
# Add the load data to the controller data
voltage = voltage + [load.voltage]
# Write the data to destination
for write in destination:
for cell in voltage:
_writer(write, cell)
# Return the data
return voltage
# Function to print the electrical data
def _print_current(h100, load='', *destination):
# Get the data from the controller
current = [
h100.currentHybrid[0], # FC output
h100.current[0],
h100.currentHybrid[1], # Battery output
h100.current[1],
h100.currentHybrid[2], # System output
h100.current[2],
]
# If there is a digital loadbank connected get that data
if load:
# Add the load data to the controller data
current = current + [load.current]
# Write the data to destination
for write in destination:
for cell in current:
_writer(write, cell)
# Return the data
return current
# Function to print the energy data
def _print_energy(h100, *destination):
# Write the data to destination
for write in destination:
for cell in h100.energy:
_writer(write, cell)
# Return the data
return h100.energy
# Function to print the temperature
def _print_temperature(h100, *destination):
# Get the data from the controller
temperature = [h100.temperature[0],
h100.temperature[1],
h100.temperature[2],
h100.temperature[3],
h100.temperature[4],
h100.temperature[5]]
# Write the data to destination
for write in destination:
for cell in temperature:
_writer(write, cell)
# Return the data
return temperature
# Function to print the purge data
def _print_purge(h100, *destination):
# Get the data from the controller
purge = [h100.flow_rate,
h100.flow_moles,
h100.purge_frequency,
h100.purge_time]
# Write the data to destination
for write in destination:
for cell in purge:
_writer(write, cell)
# Return the data
return purge
# Function to print the throttle
def _print_throttle(motor, *destination):
# Get the throttle from the motor controller
throttle = motor.throttle
# Write the data to destination
for write in destination:
_writer(write, throttle)
# Return the data
return throttle
# Function to read user input while running (stdin)
def _reader():
# Get data from screen
__inputlist = [sys.stdin]
# Parse the typed in characters
while __inputlist:
__ready = select.select(__inputlist, [], [], 0.001)[0]
# If no data has been typed then return blank
if not __ready:
return ''
# Otherwise parse line
else:
# Read the line
for __file in __ready:
__line = __file.readline()
# If there is nothing it is the end of the line
if not __line:
__inputlist.remove(__file)
# Otherwise return line with no whitespace and all letters in lowercase
elif __line.rstrip(): # optional: skipping empty lines
return __line.lower().strip()
# If we get here something went wrong so return blank
return ''
# Funtion to moitor performance of individual functions
def _performance_monitor(is_active, performance_timer, function_name):
if is_active:
# Calculate dt
dt = int((time.time()-performance_timer) * 1000000.0) # Microseconds
# Display the time taken to run the function
print(function_name + '\t' + str(dt) + 'us')
# Update the performance monitor timer
performance_timer=time.time()
return performance_timer
# Shutdown routine
def _shutdown(motor, h100, load, log, display):
try:
print("\nShutting down...")
# Set motor throttle to zero
motor.throttle = 0
print('...Throttle set to {:d}'.format(motor.throttle))
# Shutdown fuel cell
h100.shutdown()
# Shutdown loadbank
if load:
print('...Loadbank disconnected')
if load.shutdown(): print('Done\n')
# Shutdown datalog
if log:
print('...Datalogger closed')
if log.close(): print('Done\n')
# Shutdown LED display
if display:
display.on = False
print('...Display off')
except KeyboardInterrupt:
if input("Force close? [y/n]: ") is "y":
print("FORCED CLOSE. TURN OFF DEVICES MANUALLY!")
return
else:
_shutdown(motor, h100, load, log, display) # RECURSION
# End
print('Programme successfully exited and closed down\n\n')
# Main run function
if __name__ == "__main__":
try:
## Command line arguments
# Get user arguments from command line
args = _parse_commandline()
# If user asked for a logfile then open this
if args.out:
log = open(("/media/usb/" + time.strftime("%y%m%d-%H%M%S") + "-controller-" + args.out + ".tsv"), 'w')
# Otherwise open nothing to prevent errors
else:
log = open("/dev/null", 'w')
## Initialise classes
# Initialise controller
h100 = H100(args.purge)
# Initialise LED display
display = h100Display.FuelCellDisplay()
# If we cannot connect to the display, make the variable blank
if display.connect() is -1:
display = ''
# Otherwise turn it on
else:
display.on = True
# Initialise Digital loadbank
load = loadbank.TdiLoadbank('158.125.152.225', 10001, 'fuelcell')
# If we cannot connect to the loadbank, make the variable blank
if load.connect() == 0:
load = ''
# Otherwise zero it and set safety limits
else:
load.zero()
time.sleep(0.2)
load.mode = 'CURRENT'
time.sleep(0.2)
load.range = '4'
time.sleep(0.2)
load.current_limit = '60.0'
time.sleep(0.2)
load.voltage_limit = '35.0'
time.sleep(0.2)
load.voltage_minimum = '5.0'
# Initialise profile scheduler if argued
if args.profile:
profile = scheduler.Scheduler(args.profile)
# If a loadbank is connected then define this as the output
if load:
output = "loadbank"
# Otherwise assume a motor is connected via an ESC
else:
output = "esc"
# Otherwise make the variable blank
else:
profile = ''
# Initiaise the ESC
motor = esc.esc()
# Zero the throttle for safety
motor.throttle = 0
# Start timers
my_time = timer.My_Time()
timeStart = time.time() # todo
# Print the header to the screen
_display_header(print)
# If there is an LED screen conencted...
if display:
# Set the fuel cell name
display.name = "H100"
# Display a list of available user commands
print("Type command: [time, throttle, fc, elec, v, i, energy, temp, purg, fly] ")
# Start a timer
performance_timer = time.time()
# Try to run the main code loop
try:
while True:
## Handle the background processes
# Run the fuel cell controller
h100.run()
# Update the performance monitor timer
performance_timer = _performance_monitor(args.timer, performance_timer, H100.__name__)
# Run the timer TODO
my_time.run()
# Update the performance monitor timer
performance_timer = _performance_monitor(args.timer, performance_timer, timer.My_Time.__name__)
# If we are running a scheduled profile...
if profile:
# Get the programmed setpoint
setpoint = profile.run()
# If the output is the digital loadbank...
if "loadbank" in output and load:
# and the setpoint is not in an error mode...
if setpoint >= 0:
# Turn the loadbank on
load.load = True
# Set the type of electrical profile we are running
mode = load.mode
# Set the setpoint for the electrical profile for now
if "VOLTAGE" in mode:
load.voltage_constant = str(setpoint)
elif "CURRENT" in mode:
load.current_constant = str(setpoint)
elif "POWER" in mode:
load.power_constant = str(setpoint)
# Setpoint is in an error mode (eg profile finished) so turn off
else:
load.load = False
# Otherwise assume a throttle profile, send this to the motor
else:
motor.throttle = setpoint
# Update the performance monitor timer
performance_timer = _performance_monitor(args.timer, performance_timer, scheduler.Scheduler.__name__)
# If there is a loadbank connected, update the sensor values
if load:
load.update()
# Update the performance monitor timer
performance_timer = _performance_monitor(args.timer, performance_timer, loadbank.TdiLoadbank.__name__)
## Handle the user interface
# Read typed in user data on the screen
request = _reader()
# If something was typed in...
if request:
# Split the argument from the value
request = request.split(' ')
# Determine the number of pieces of information
req_len = len(request)
# Strip away any whitespace
for x in range(req_len):
request[x] = request[x].strip()
# If only one piece of information, it is a request for data
if req_len is 1:
if request[0].startswith("time?"):
_print_time(my_time, print)
elif request[0].startswith("throttle?"):
_print_throttle(motor, print)
elif request[0].startswith("fc?"):
_print_state(h100, print)
elif request[0].startswith("elec?"):
_print_electric(h100, load, print)
elif request[0].startswith("v?"):
_print_voltage(h100, load, print)
elif request[0].startswith("i?"):
_print_current(h100, load, print)
elif request[0].startswith("energy?"):
_print_energy(h100, print)
elif request[0].startswith("temp?"):
_print_temperature(h100, print)
elif request[0].startswith("purg?"):
_print_purge(h100, print)
elif request[0].startswith("fly?"):
if profile and profile.running:
print("Currently flying")
else:
print("In the hangar")
# If there are two pieces of information it is a command to change something
elif req_len is 2:
if request[0].startswith("fc"):
_new_state = request[1]
print('Changing state to', _new_state)
h100.state = _new_state
elif request[0].startswith("fly"):
profile.running = request[1]
elif request[0].startswith("throttle"):
if request[1].startswith("calibration"):
motor.calibration()
else:
motor.throttle = request[1]
# Print a new line to the screen
print()
# Update the performance monitor timer
performance_timer = _performance_monitor(args.timer, performance_timer, "UI")
## Handle the logfile
# Log time
_print_time(my_time, log.write)
# Update the performance monitor timer
performance_timer = _performance_monitor(args.timer, performance_timer, "log_time")
# Log state
state = _print_state(h100, log.write)
# Send state to LED display if connected
if display:
display.state = state
# Update the performance monitor timer
performance_timer = _performance_monitor(args.timer, performance_timer, "log_state")
# Log electrical data
electric = _print_electric(h100, load, log.write)
# Send electrical data to LED display if connected
if display:
display.voltage = electric[0]
display.current = electric[1]
display.power = electric[2]
# Update the performance monitor timer
performance_timer = _performance_monitor(args.timer, performance_timer, "log_electrical")
# Log energy data
_print_energy(h100, log.write)
# Update the performance monitor timer
performance_timer = _performance_monitor(args.timer, performance_timer, "energy")
# Log temperature data
temp = _print_temperature(h100, log.write)
# Send temperature data to LED display if connected
if display:
display.temperature = max(temp)
# Update the performance monitor timer
performance_timer = _performance_monitor(args.timer, performance_timer, "log_temp")
# Log purge controller data
_print_purge(h100, log.write)
# Update the performance monitor timer
performance_timer = _performance_monitor(args.timer, performance_timer, "log_purge")
# Log a new line, end of this timestep
if log:
log.write("\n")
# If verbose is argued then print all data to screen
if args.verbose and not args.timer:
_print_time(my_time, print)
_print_state(h100, print)
_print_electric(h100, load, print)
_print_energy(h100, print)
_print_temperature(h100, print)
_print_purge(h100, print)
print()
# Do the folowing it code crashes or keyboard exception is raised (Ctrl+C)
finally:
# Code crashed
pass
except KeyboardInterrupt:
_shutdown(motor, h100, load, log, display)
#######
# End #
#######