/
main.py
executable file
·497 lines (435 loc) · 14.2 KB
/
main.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
#!/usr/bin/python
# -*- coding: latin-1 -*-
import pygame
import pygame.gfxdraw
import math
import time
import calendar
import mygauge
import myplot
import mywatergauge
import mynimbus
import readMaxim
import readMaximSPI
import readHSR
import multithreadTemp
import multithreadHum
import multithreadRange
import multithreadPID
import multithreadScale
import SSRControl
import signal
import sys
from subprocess import call
#Debug file (user interface will crash after ramfile is full, use with caution)
DEBUGFILE = 0
#Temperature file backup
TEMPBACKUP = '/home/pi/pygame/settings'
#enable nimbus or not?
NIMBUS_ENABLED = 0
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREY = ( 127, 127, 127)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
BLUE = ( 0, 0, 255)
BLEUNEST = ( 0, 60, 236) #bleu roi nest
BLEUINT = ( 164, 202, 255) #bleu clair
PLOT1 = ( 124, 181, 236) #bleu pastel
PLOT2 = ( 144, 237, 125) #vert pastel
PLOT3 = ( 247, 163, 97) #orange pastel
GREYL = ( 229, 229, 229) #gris clair
#init pygame lib
pygame.init()
# Set the width and height of the screen [width, height]
size = (800, 480)
screen = pygame.display.set_mode(size, pygame.FULLSCREEN | pygame.DOUBLEBUF | pygame.HWSURFACE | pygame.NOFRAME )
#load logo image
rlogo = pygame.image.load("/home/pi/pygame/logov4.gif")
rcommande = pygame.image.load("/home/pi/pygame/plusmoins.gif")
#hide mouse cursor
#pygame.mouse.set_visible( False )
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# value for test
rot = -10
lasttct = 0
# global values for data handling
maximT1 = readMaxim.MaximData(0)
maximT2 = readMaxim.MaximData(0)
maximT3 = readMaxim.MaximData(0)
maximT4SPI = readMaxim.MaximData(0)
dhtData = readMaxim.MaximData(0)
hsrData = readHSR.HSRData(0)
scaleData = readMaxim.MaximData(0)
#nimbus for special display
nimbus = mynimbus.NimbusMaster()
#launch thread to update the temp values and other (hum, range etc)
task1 = multithreadTemp.TaskPrintTemp(0,maximT1)
#task2 = multithreadTemp.TaskPrintTemp(1,maximT2)
#task3 = multithreadTemp.TaskPrintTemp(2,maximT3)
task4 = multithreadHum.TaskPrintHum(3,dhtData)
task5 = multithreadRange.TaskPrintRange(4,hsrData)
task7 = multithreadTemp.TaskPrintTemp(5,maximT4SPI)
task8 = multithreadScale.TaskPrintScale(7,scaleData)
#**** PID setup: *****
#maximT1 is the group temperature (for boost algorithm), maximT4SPI is the boiler temp sensor, default target value = 115C
temptarget=115
task6PID = multithreadPID.TaskControlPID(6,maximT1,maximT4SPI,temptarget)
consigneSpecialePID = 0
lastTargetTemp = temptarget
task1.start()
#task2.start()
#task3.start()
task4.start()
task5.start()
task7.start()
task6PID.start()
task8.start()
#how to quit application nicely
def quitApplicationNicely():
done = True
#be sure to shut down the boiler as well
SSRControl.setBoilerPWM(0)
saveSettings()
task1.stop()
# task2.stop()
# task3.stop()
task4.stop()
task5.stop()
task7.stop()
task6PID.stop()
task8.stop()
time.sleep(0.1)
pygame.quit()
sys.exit(0)
#signal handler
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
quitApplicationNicely()
#current flow counter (handle deltas)
deltaFlow = 0
currentFlow = 0
realFlVal = 0
scl = 0
scloffset = 0
#get current flow counter
def getFlow():
global currentFlow,deltaFlow
device_file = '/sys/kernel/flow/flow'
try:
f = open(device_file, 'r')
lines = f.read()#lines()
f.close()
currentFlow = int(lines)
return currentFlow - deltaFlow
except IOError as e:
print "Erreur fichier ", device_file," (ouverture, lecture ou fermeture)"
print "I/O error({0}): {1}".format(e.errno, e.strerror)
return -1
except:
print "Erreur fichier ", device_file," (ouverture, lecture ou fermeture)", sys.exc_info()[0]
return -1
#intercept control c for nice quit
signal.signal(signal.SIGINT, signal_handler)
chronoRuning = False
topdepart = 0.0
finchrono = 0.0
fontChrono = pygame.font.SysFont('dejavusans', 22, True, False)
fontSmall = pygame.font.SysFont('dejavusans', 12, True, False)
def startChrono(ndfl):
global currentFlow,deltaFlow
global chronoRuning, topdepart, finchrono, realFlVal
global scl, scloffset
if(chronoRuning == False):
chronoRuning = True
topdepart = time.time()
realFlVal = 0
scloffset = scl
#deltaFlow = ndfl
#deltaFlow = currentFlow
def stopChrono():
global chronoRuning, topdepart, finchrono
if(chronoRuning == True):
chronoRuning = False
finchrono = time.time()
def getChrono():
global chronoRuning, topdepart, finchrono
if(chronoRuning == True):
return time.time() - topdepart
else:
return finchrono - topdepart
def drawChrono():
global screen,fontChrono
# display chrono
buf = "%.1f s" % getChrono()
ctext = fontChrono.render(buf, True, WHITE)
stext = fontSmall.render("Chrono:",True,WHITE)
# blit to screen
screen.blit(stext,(500,25))
screen.blit(ctext,(500,40))
def getTempTarget():
print "getTemp"
try:
tfile = open(TEMPBACKUP, "r")
line = tfile.readline()
tfile.close()
#conversion en entier
ttarget = int(line)
except IOError as e:
print "Erreur fichier ", TEMPBACKUP," (ouverture, lecture ou fermeture)"
print "I/O error({0}): {1}".format(e.errno, e.strerror)
ttarget = 0
except:
print "Erreur fichier ", TEMPBACKUP," (ouverture, lecture ou fermeture)", sys.exc_info()[0]
ttarget = 0
return ttarget
def loadSettings():
global temptarget
print "loadsettings"
val = getTempTarget()
#default: 115C
if(val == 0):
temptarget = 115
print "Load settings: using default temptarget value of 115C"
else:
temptarget = val
print "Load settings: temptarget value is now ",temptarget,"C"
#apply settings immediately
task6PID.setTargetTemp(temptarget)
def saveSettings():
#recuperation de la consigne reelle
if(consigneSpecialePID == 1):
temptosave = lastTargetTemp
else:
temptosave = temptarget
#a-t-on vraiment besoin d'ecrire dans la flash? (abime)
val = getTempTarget()
if ((val > 0) and (val == temptosave)):
print "pas besoin d'ecrire dans la flash"
return
#nouvelle valeur: ecriture dans un fichier
buf = "%d" % temptosave
buf = buf + "\n"
print "Saving temptarget", buf, "ok?"
try:
tfile = open(TEMPBACKUP, "w")
tfile.write(buf)
tfile.close()
except IOError as e:
print "Erreur fichier ", TEMPBACKUP," (ouverture, lecture ou fermeture)"
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except:
print "Erreur fichier ", TEMPBACKUP," (ouverture, lecture ou fermeture)", sys.exc_info()[0]
#init vars
FLOWAJUST = 5.0 #4.4115 #4.2
fl = getFlow() / FLOWAJUST
deltaFlow = currentFlow
loadSettings()
flLastTs = time.time()
cPIDload = 0
lastPIDload = -1
#init nimbus
if( NIMBUS_ENABLED ):
nimbus.nimbus_init()
nimbus.setGaugeMinMaxVal(0,15,140) #boiler
nimbus.setGaugeMinMaxVal(1,15,100) #group
nimbus.setGaugeMinMaxVal(2,20,60) #hygro
nimbus.setGaugeMinMaxVal(3,0,100) #water
# -------- Main Program Loop -----------
while not done:
#try to respect as much as possible the time slot
timestamp = time.time()
#event loop
for event in pygame.event.get():
# Case user click exit button (never happen we are fullscreen)
if event.type == pygame.QUIT:
done = True
#did we clicked somewhere?
if (event.type == pygame.MOUSEBUTTONDOWN) :
mpx,mpy = event.pos
print "Mouse click detected at", mpx, ",", mpy
if( (mpx > 700) and (mpy < 100) ):
print "mouse click exiting..."
done = True
if( (mpx > 700) and (mpy > 400) ):
print "reset flow"
deltaFlow = currentFlow
#ajust boiler temp
if( (mpx > 650) and (mpx < 700) and (mpy > 200) and (mpy < 250) ):
print "click on ROCKET"
if(consigneSpecialePID == 0):
lastTargetTemp = temptarget
consigneSpecialePID = 1
temptarget = 124
task6PID.setTargetTemp(temptarget)
if( (mpx > 600) and (mpx < 650) and (mpy > 250) and (mpy < 300) ):
print "click on MOINS"
if(consigneSpecialePID == 1):
temptarget = lastTargetTemp
consigneSpecialePID = 0
else:
temptarget -= 1
task6PID.setTargetTemp(temptarget)
if( (mpx > 700) and (mpx < 750) and (mpy > 250) and (mpy < 300) ):
print "click on PLUS"
if(consigneSpecialePID == 1):
temptarget = lastTargetTemp
consigneSpecialePID = 0
else:
temptarget += 1
task6PID.setTargetTemp(temptarget)
if( (mpx > 650) and (mpx < 700) and (mpy > 300) and (mpy < 350) ):
print "click on STOP"
if(consigneSpecialePID == 0):
lastTargetTemp = temptarget
consigneSpecialePID = 1
temptarget = 90
task6PID.setTargetTemp(temptarget)
# Clear the screen and set the screen background
screen.fill(BLACK)
rquit = pygame.Rect(750,0,50,50)
screen.fill(RED,rquit)
screen.blit(rlogo,(800-rlogo.get_width(), 0))
screen.blit(rcommande,(600,200))
#display the current time
if(int(time.time())%2 == 0):
bufTime=time.strftime('%H:%M')
else:
bufTime=time.strftime('%H %M')
ctext = fontChrono.render(bufTime, False, GREYL)
screen.blit(ctext,(675,150))
#add plus/minus buttons
# rplus = pygame.Rect(675,200,50,50)
# screen.fill(RED,rplus)
# rmoins = pygame.Rect(675,300,50,50)
# screen.fill(GREEN,rmoins)
#display current target temp
buf = "%d" % temptarget
buf = buf + chr(176) #"c"
ctext = fontChrono.render(buf, False, WHITE)
screen.blit(ctext,(650,260))
#display current PID load
cPIDload = task6PID.getCurrentDrive()
buf2 = " %d" % cPIDload
buf2 = buf2 + "%"
stext = fontSmall.render(buf2,False,GREY)
screen.blit(stext,(650,285))
#affiche les jauges
t1 = maximT1.getTemp()
# t2 = maximT2.getTemp()
# t3 = maximT3.getTemp()
t4,h4 = dhtData.getTempHum()
r5 = hsrData.getRange()
t6 = maximT4SPI.getTemp()
oldfl = fl
fl = getFlow() / FLOWAJUST
scl,isScaleHere = scaleData.getTempHum()
mygauge.drawGauge("Groupe E61",chr(176), 100,400, t1,-10,100,False,False,PLOT1)
# mygauge.drawGauge("TuyauHx", chr(176),250,400, (t2+t3)/2,-10,100,False,False,PLOT2)
if(isScaleHere == 1):
mygauge.drawGauge("Poids", "g.",250,400, scl-scloffset ,0,60,False,False,PLOT2)
else:
mygauge.drawGauge("Poids (offline)", "g.",250,400, 99 ,0,60,False,False,PLOT2)
mygauge.drawGauge("Chaudiere",chr(176),400,400, t6,-10,100,False,False,PLOT3)
buf = "Humidite (Temp=%d" % t4
buf = buf +chr(176)+")"
mygauge.drawGauge(buf,"%", 550,400, h4,20,150,False,False,WHITE)
# mygauge.drawGauge("Flow"," ml", 700,400, fl ,0,60,False,False,WHITE)
#affiche la jauge niveau d'eau
mywatergauge.drawRGauge(500+10,85,240,24,r5,224.0,50.0)
#gestion du chrono
if(fl > oldfl):
startChrono(oldfl)
flLastTs = timestamp
#on attend au moins 2 secondes avant d'arreter le chrono (on a des valeurs nulles parfois en pleine extraction)
if(fl == oldfl) and ((timestamp - flLastTs) > 2):
stopChrono()
drawChrono()
#adaptation du flowmeter au groupe e61
tfl=fl-oldfl
if(tfl < 0):
tfl=0
if(tfl > 0):
if(tfl > 1.5):
isHighValueFlow = True
if(tfl < 1.5) and (isHighValueFlow == True):
realFlVal += tfl
else:
#attende d'au moins 2 secondes avant reset
if((timestamp - flLastTs) > 2):
isHighValueFlow = False
#affichage valeur reele debitmetre
buf = "Flow %.1f ml" % fl
mygauge.drawGauge(buf," ml", 700,400, realFlVal ,0,60,False,False,WHITE)
#ajoute les valeurs au graphique
# myplot.addGraphVal(t1,(t2+t3)/2,t6,tfl)
myplot.addGraphVal(t1,t1,t6,tfl)
#genere et affiche les courbes sur le graphique a l'ecran
myplot.drawGraph(50,25,400,300,85,100)
#*** NIMBUS CODE HERE ***********************************
if ( NIMBUS_ENABLED ):
#update nimbus display no1 : boiler
buf = "CH%3.1f/%d" % (t6,temptarget)
nimbus.printText(0,buf)
nimbus.setGaugeValue(0,int(t6))
#update nimbus display no2 : group
buf = "Group:%3.1f" % (t1)
nimbus.printText(1,buf)
nimbus.setGaugeValue(1,int(t1))
#update nimbus display no3 : hygro/temp
buf = "T%2.1f/H%d" % (t4,h4)
buf += "%"
nimbus.printText(2,buf)
nimbus.setGaugeValue(2,int(h4))
#update nimbus display no4 : water/time
wpc=mywatergauge.getWaterPercent(r5,224.0,50.0)
buf = bufTime + ("/ %d" % wpc)
buf += "%"
nimbus.printText(3,buf)
nimbus.setGaugeValue(3,int(wpc))
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second (unused)
#clock.tick(60)
rot = rot + 3
if(rot > 100):
rot = 0
#log to file
if(DEBUGFILE == 1):
#add values to our database
tct = int(time.time())
if( tct != lasttct ):
# ligne = "%d:%0.1f:%0.1f:%0.1f:%0.1f:%0.1f:%0.2f:%0.1f\n" % (tct,t1,t2,t3,t4,h4,tfl,t6)
if(lastPIDload >= 0):
cPIDload = (cPIDload + lastPIDload) / 2
lastPIDload = -1
ligne = "%d:%0.1f:%0.1f:%0.1f:%0.2f:%0.1f:%d\n" % (tct,t1,t2,t3,tfl,t6,cPIDload)
try:
#file to log temperatures
tfile = open("/var/tmp/temp.data", "a")
tfile.write(ligne)
tfile.close()
except IOError as e:
print "Erreur fichier ", device_file," (ouverture, lecture ou fermeture)"
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except:
print "Erreur fichier ", device_file," (ouverture, lecture ou fermeture)", sys.exc_info()[0]
lasttct = tct
else:
lastPIDload = cPIDload
#only sleep the time we need to respect the clock
remainingTimeToSleep = time.time() - timestamp
remainingTimeToSleep = 0.5 - remainingTimeToSleep
if(remainingTimeToSleep > 0):
time.sleep(remainingTimeToSleep)
# time.sleep(0.1)
#end the tasks nicely
quitApplicationNicely()
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()