-
Notifications
You must be signed in to change notification settings - Fork 0
/
PastoWeb.py
executable file
·3491 lines (3125 loc) · 168 KB
/
PastoWeb.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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
#TODO:
le compteur de remplissage des seaux d’entrée/sortie n’est pas juste: lors d’un flush, le décompte du seau de sortie diminue lorsque la pompe tourne à l’envers hors il devrait continuer à augmenter car de l’eau arrive toujours en provenance de la conduite.
lors du cyclage d’un nettoyage, le schéma montre comme si le seau se vidait et se remplissait alors que les tuyaux d’entrée/sortie sont dans le même seau
dans le seau d’entrée, à la place d’indiquer la formule complète, par exemple 19,8-5,3=14,5L, indiquer juste ce qui est enlever du seau, -5,3L.
si on lance par exemple un pasteurisation et qu’on l’arrête directement car fausse manipulation, le pasteurisateur croit quand même que l’action a été faite
- Seau de désinfectant: 15L noir (couvercle)
- Seau de détergent: 15L bleu (couvercle)
- Seau de récup "A": 20L blanc
- Seau de récup "B": 15L blanc
- Rinçages: suivre le nombre et permettre de choisir une configuration de réutilisation de seaux
Désinfection:
Si pas d'utilisation pendant plus qu'un jour, SIMPLE FLUSH:
Entrée+Sortie=seau de recup "A" -- remplir la machine d'eau du robinet (5L), faire un flush d'eau potable (5L) (FLUSH doit-il faire 10L si le circuit est vide?)
Entrée+Sortie=seau de désinfectant -- lancer la désinfection qui va au besoin remplir la machine (5L)
puis faire un flush (5L) pour pouvoir diluer le désinfectant.
Cyclage, délai d'action de 15 minutes (paramètre?),
flush d'évacuation (5L) donc 10L dans le seau de désinfectant
DOUBLE FLUSH:
Entrée+Sortie=seau de recup "A" -- faire deux flush (10L) (donc total 10 à 15L dans le seau de recup "A")
Pasteurisation: CHAUFFE (le circuit doit être rempli d'eau)
Entrée=lait cru
Sortie=seau de recup "B" = 5L d'eau qui sorte au début corrompue par du lait (donc total 10L dans le seau de recup "B")
Sortie = lait pasteurisé
Entrée = seau de recup "B", faire la pousse à l'eau (rajouter un ou deux litres d'eau dans le seau B au besoin)
ASPI DOUBLE+DOUBLE FLUSH:
Entrée = au dessus de l'égout (rejet), Sortie(aspirée!)=seau de recup "A" -- faire deux flush "récupérant" INVERSE, jeter la fin du seau "A" (rincer des seaux sales)
Puis deux flush d'eau potable (10L) + VIDER donc 10L restent récupérables dans le seau "A"
Nettoyage caustique:
Entrée+Sortie = seau de caustique -- lancer le nettoyage qui va remplir (5L) puis faire un flush (5L) pour pouvoir diluer le détergent.
Cyclage avec chauffe, plateau de 15 minutes
flush d'évacuation (5L) donc 10L dans le seau de détergent
ASPI DOUBLE+DOUBLE FLUSH:
Sortie = seau de recup "A", faire deux flush INVERSE (donc Entrée au dessus de l'égout), jeter la fin du seau "A" (rincer des seaux sales)
Puis deux flush d'eau potable (10L) + VIDER donc 10L restent récupérables dans le seau "A"
- Prendre la durée de pasteurisation à la température de pasteurisation pour calculer un ratio supplémentaire de réduction de la souche bactérienne retenue à cette température là.
Utiliser ce ratio pour toutes les souches. A TESTER !
- Ne jamais accélérer (décélérer) quand on n'est pas en pasteurisation (quand ce n'est pas une régulation sur la courbe de survie d'un microbe)
- Arrêter de chauffer quand la pompe tourne déjà bien vite
- Ne pas aller trop vite quand on pousse l'eau ou qu'on pousse à l'eau.
- Intégrer les Mélanges de produits laitiers congelés, lait de poule :
soumettre à une température de 80°C pendant 25 secondes ou à une température de 83°C pendant 15 secondes
- Vider le tuyau avant ou après un rinçage pour rendre le suivant plus efficace
- Démarrer lentement une pasteurisation.
- Pousse-à-l'eau : vérifier le paramétrage en relation avec la nouvelle régulation
- Lavage: assurer un minimum de 50 en entrée et non de "cuve - 13". Pour celà, la chauffe de la cuve pourrait être OK pour "bouger" dès 50°C et pour arrêter de chauffer 20°C (paramétrable?) plus haut (gradient nettoyage).
Pour une pasteurisation, ce pourrait être idem avec un gradient de 3°C (paramétré)
ATTENTION: CHANGEMENT a moitié fait.
"""
import socket
import sys
import os
import signal
import argparse
import json
import time
import web # pip install web.py
from datetime import datetime
from enum import Enum
import tty
import termios
import subprocess
import traceback
import ml # Not unused !!!
import datafiles
import pyownet
import term # pip install py-term
import threading
import hardConf
import report
import sensor
#import pump
import pump_pwm
import cohort
import Heating_Profile
import Dt_line
from thermistor import Thermistor
from pressure import Pressure
from solenoid import Solenoid
from LED import LED
from button import button, ThreadButtons
from sensor import Sensor
from valve import Valve
from menus import Menus
from state import State
from report import Report
from TimeTrigger import TimeTrigger
global render, _lock_socket
DEBUG = True
KEY_ADMIN = "[email protected]" # Omnipotent user
PWD = "past0.NET"
HEAT_EXCHANGER = True
display_pause = False
lines = 25
WebExit = False
def isnull(v, n):
if v is None:
return n
else:
return v
def zeroIsNone(v):
if not v:
return None
elif v == 0.0:
return None
else:
return v
def getch():
ch = None
fd = sys.stdin.fileno()
try:
old_settings = termios.tcgetattr(fd)
tty.setraw(fd)
except: #ioctl
old_settings = None
try:
ch = sys.stdin.read(1)
except:
traceback.print_exc()
finally:
if old_settings:
termios.tcsetattr(fd,termios.TCSADRAIN,old_settings)
return ch
def termSize():
if term and term.getSize():
return term.getSize()
else:
return (25,80)
def tell_message(message):
global display_pause,lines,columns
prec_disp = display_pause
display_pause = True
time.sleep(0.01)
(lines, columns) = termSize()
term.pos(lines,1)
term.writeLine("",term.bgwhite) # scroll the whole display by one line
term.pos(lines-4,1)
term.write(message,term.blue,term.bold,term.bgblack)
term.clearLineFromPos()
term.pos(lines-3,1)
term.clearLineFromPos()
display_pause = prec_disp
typeOneWire = 1
typeRMeter = 11
Buzzer = None
RedLED = None
RedConfirmationDelay = 4.5 # secondes pour confirmer un arrêt ou un shutdown
YellowLED = None
GreenLED = None
RedButton = None
YellowButton = None
GreenButton = None
EmergencyButton = None
#configuration of output pins
if hardConf.Out_Buzzer:
Buzzer = LED('buzzer',hardConf.Out_Buzzer)
Buzzer.on()
if hardConf.Out_Red:
RedLED = LED('red',hardConf.Out_Red) #BCM=24
if hardConf.Out_Yellow:
YellowLED = LED('yellow',hardConf.Out_Yellow) #BCM=24
if hardConf.Out_Green:
GreenLED = LED('green',hardConf.Out_Green) #BCM=23
#configuration of input pins
if hardConf.In_Red:
RedButton = button('red',hardConf.In_Red, RedLED)
if hardConf.In_Yellow:
YellowButton = button('yellow',hardConf.In_Yellow, YellowLED)
if hardConf.In_Green:
GreenButton = button('green',hardConf.In_Green, GreenLED)
if hardConf.In_Emergency:
EmergencyButton = button('emergency',hardConf.In_Emergency)
#BATH_TUBE = 4.6 # degrees Celsius. Margin between temperature in bath and temperature wished in the tube
CLEAN_TIME = 900.0 #seconds= 15 minutes. Was 1800 but now we wait for input heating before beginning
ACID_TIME = 600.0 #seconds= 10 minutes. Was 900 but now we wait for input heating before beginning
DISINF_PAUSE_TIME = 900.0 #seconds= 15 minutes, pause to leave disinfectant to act
STAY_CLEAN_TIME = 2*3600 #seconds = 2 hours
DEFAULT_FORCING_TIME = 30 #seconds. Each time the user forces pumping forward, normal operation resumes after this delay
HYSTERESIS = 0.2 # degrees below / over setpoint to open / close heating
#FLOOD_TIME = 60.0 # 90 seconds of hot water tap flushing (when a pump is in the way. 60 if not) to FILL an EMPTY machine
#floodLitersMinute = 3.5 # 4.0 si pas de pompe dans le chemin; 3 sinon DEPEND DE LA PRESSION, PAS UTILISABLE
FLOOD_PER_MINUTE = 4.0 # liters in a one minute flood from the tap (also used with water coming from a bucket)
TANK_NOT_FILLED = 1.5 # If heating time remaining is decreasing more than expected (ratio above 1.3 and not 3), the tank may not be filled correctly...
TANK_EMPTY_LIMIT = 60 #seconds. If heating time has not diminished in this delay, the heating tank may be empty...
PUMP_LOOP_DELAY = 0.2
menus = Menus.singleton
menus.options = {'G':['G',ml.T("Gradient°","Gradient°","Gradient°") \
,ml.T("Gradient de température","Temperature Gradient","Gradient van Temperatuur") \
,3.0,3.0,"°C",False,7,0.1,"number"], # Gradient de Température
#'g':['g',ml.T("Produit Gras","Fatty Product","Vet Product") \
# ,ml.T("Nécessite de la soude(1) Pas toujours(0)","Needs Soda Cleaning(1) Not always(0)","Soda-reiniging nodig(1) Niet altijd(0)") \
# ,1,1,"-",False,1,1,'range'], # Faux=0, 1=Vrai
# 'F':['F',ml.T("Profil Bact.","Profile Bact.","Profiel Bact.") \
# ,ml.T("Courbe de réduction des bactéries","Bacteria reduction curve","Bacterie reductiecurve") \
# ,'L','L',"",True,None,None,"text"], # Gradient de Température
'P':['P',ml.T("Pasteurisation°","Pasteurization°","Pasteurisatie°") \
,ml.T("Température de pasteurisation","Pasteurisation Temperature","Pasteurisatie Temperatuur") \
,72.0,72.0,"°C",False,90,0.1,"number"], # Température normale de pasteurisation
'w':['w',ml.T("Pause maximale","Max Pause","Max Pauze") \
,ml.T("Temps d'arrêt maximum autorisé","Maximum process stop duration","Maximaal toegestane uitvaltijd") \
,STAY_CLEAN_TIME,STAY_CLEAN_TIME,"hh:mm",False,3600*2,600,"time"], # Durée où un tuyau propre le reste sans rinçage (le double avant de tout re-nettoyer)
'R':['R',ml.T("Rinçage°","Rinse°","Spoelen°") \
,ml.T("Température de rinçage","Rinse Temperature","Spoelen Temperatuur") \
,25.0,25.0,"°C",False,90,0.1,"number"], # Température du Bassin pour le prélavage
'r':['r',ml.T("Rinçage\"","Rinse\"","Spoelen\"") \
,ml.T("Durée du dernier Rinçage","Last Rinse duration","Laatste spoelduur") \
,0.0,60.0,'\"',False,300,1,"number",60], # Volume du dernier flush pour calcul du Temps d'admission de l'eau courante (TOTAL_VOL à mettre par défaut)
'u':['u',ml.T("Rinçage(L)","Rinse(L)","Spoelen(L)") \
,ml.T("Volume du dernier Rinçage","Last Rinse Volume","Laatste spoelvolume") \
,0.0,0.0,'L',False,20,0.01,"number",4.0], # Volume du dernier flush pour calcul du Temps d'admission de l'eau courante (TOTAL_VOL à mettre par défaut)
's':['s',ml.T("Seau pour l'Eau","Bucket for Water","Emmer voor water\"") \
,ml.T("Eau courante(0) ou amenée dans un seau(1)","Running water(0) or brought in a bucket(1)","Stromend water(0) of gebracht in een emmer(1)") \
,0,1,"-",False,1,1,'range'], # Faux=0, 1=Vrai
'C':['C',ml.T("net.Caustique°","Caustic cleaning°","Bijtende schoonmaak°") \
,ml.T("Température de nettoyage","Cleaning Temperature","Schoonmaak Temperatuur") \
,50.0,50.0,"°C",False,60,0.1,"number"], # Température pour un passage au détergent
'c':['c',ml.T("net.Caustique\"","Caustic cleaning\"","Bijtende schoonmaak\"") \
,ml.T("Durée de nettoyage","Cleaning Duration","Schoonmaak Tijd") \
,CLEAN_TIME,CLEAN_TIME,"hh:mm",False,3600*2,60,"time"],
'D': ['D', ml.T("Désinfection°""Disinfection°", "Desinfectie°") \
, ml.T("Température de désinfection", "Disinfection Temperature", "Desinfectie Temperatuur") \
, 25.0, 25.0, "°C", False, 30, 0.1, "number"], # Température normale de désinfection vinaigre + peroxyde
'd': ['d', ml.T("Désinfection \"", "Disinfection \"", "Desinfectie \"") \
, ml.T("Durée de désinfection", "Disinfection Duration", "Desinfectie Tijd") \
, DISINF_PAUSE_TIME, DISINF_PAUSE_TIME, "hh:mm", False, 3600, 60, "time"], # Temps d'action pour un traitement à l'acide ou au percarbonate de soude
'A':['A',ml.T("net.Acide°""Acidic cleaning°","Zuur schoonmaak°") \
,ml.T("Température de nettoyage acide","Acidic cleaning Temperature","Zuur schoomaak Temperatuur") \
,40.0,40.0,"°C",False,60,0.1,"number"], # Température pour un traitement à l'acide ou au percarbonate de soude
'a':['a', ml.T("net.Acide\"","Acidic cleaning\"","Zuur schoonmaak\"") \
, ml.T("Durée de nettoyage acide","Acidic cleaning Duration","Zuur schoomaak Tijd") \
, ACID_TIME, ACID_TIME, "hh:mm", False, 3600 * 2, 60, "time"], # Température pour un traitement à l'acide ou au percarbonate de soude
'M':['M',ml.T("Minimum","Minimum","Minimum") \
,ml.T("Durée minimale de pasteurisation","Minimum pasteurization time","Minimale pasteurisatietijd") \
,12.0,12.0,'"',False,120,1,"number"], # Durée minimale de pasteurisation
# 'T':['T',ml.T("Tempérisation Max°","Tempering Max°","Temperen Max°") \
# ,ml.T("Température d'ajout d'eau de refroidissement","Cooling water addition temperature","Koelwatertoevoegings Temperatuur") \
# ,0.0,0.0,"°C",True,90.0,0.1], # Température à laquelle on ajoute de l'eau de refroidissement,ZeroIsNone=True
# 't':['t',ml.T("Tempérisation Min°","Tempering Min°","Temperen Min°") \
# ,ml.T("Réchauffement à la sortie","Output Heating","Opwarmen") \
# ,18.0,18.0,"°C",True,90.0,0.1], # Température à laquelle on chauffe la cuve de sortie,ZeroIsNone=True
# 'K':['K',ml.T("Quantité Froid","Quantity Cold","Koel Aantal") \
# ,ml.T("Quantité d'eau de refroidissement","Cooling Water Quantity","Koelwater Aantal") \
# ,midTemperTank,midTemperTank,"L",False,19.9,0.1], # Quantité d'eau froide à mettre dans le bassin de refroidissement
# 'Q':['Q',ml.T("Quantité","Quantity","Aantal") \
# ,ml.T("Quantité de lait à entrer","Amount of milk to input","Aantal melk voor invoor") \
# ,0.0,0.0,"L",True,9999.9,0.1,"number"], # Quantité de lait à traiter,ZeroIsNone=True
'H':['H',ml.T("Démarrage","Start","Start") \
,ml.T("Heure de démarrage","Start Time","Starttijd") \
,0.0,0.0,"hh:mm",True,84000,600,"time"], # Hour.minutes (as a floating number, by 10 minutes),ZeroIsNone=True
'E':['E',ml.T("Amont(mL)","Upstream(mL)","StroomOPwaarts(mL)") \
,ml.T("Volume des tuyaux en amont(cm*0,7854*d²)","Upstream Pipes Volume(cm*0,7854*d²)","StroomOPwaarts leidingvolume(cm*0,7854*d²)") \
,0.0,0.0,'mL',False,2000,1,"number"], # Volume des tuyaux en entrée du pasteurisateur
'S':['S',ml.T("Aval(mL)","Downstream(mL)","StroomAFwaarts(mL)") \
,ml.T("Volume des tuyaux en aval(cm*0,7854*d²)","Downstream Pipes Volume(cm*0,7854*d²)","StroomAFwaarts leidingvolume(cm*0,7854*d²)") \
,0.0,0.0,'mL',False,15000,1,"number"], # Volume des tuyaux en sortie du pasteurisateur
'z':['z',ml.T("Pré-configuration","Pre-configuration","Pre-configuratie") \
,ml.T("Code de pré-configuration","Pre-configuration code","Pre-configuratiecode") \
,'L','L',"hh:mm",True,None,None,"text"]}
# 'Z':['Z',ml.T("Défaut","Default","Standaardwaarden") \
# ,ml.T("Retour aux valeurs par défaut","Back to default values","Terug naar standaardwaarden")] }
menus.sortedOptions = "FPMGwDdHRrusCcAaZES" #T
menus.cleanOptions = "PMGH" #TtK
menus.dirtyOptions = "RrusCcAawDdHES" #Cc
menus.loadCurrent()
reportPasteur = Report(menus) # Initialized when initializing the pump...
trigger_w = TimeTrigger('w',menus)
#(options['P'][3] + BATH_TUBE) = 75.0 # Température du Bassin de chauffe
##reject = 71.7 # Température minimum de pasteurisation
kCalWatt = 1.16 # watts per kilo calories
WATT_LOSS = 10 # watts lost per 1°C difference with room temperature
# MITIG_POWER = 1500.0 # watts per hour (puissance du bac de mitigation)
ROOM_TEMP = 20.0 # degrees: should be measured...
PUMP_SLOWDOWN = 1.0 # Slowing factor from speed calculated by temperature difference
# durationDump = Time to open or close the dump valve: look at Valve module...
periodicity = 3 # 3 seconds intervall between cohort data
depth = 100 # 100 x 3 seconds of data kept
cohorts = cohort.Cohort(periodicity,depth)
calibrating = False
temp_ref_calib = []
def manage_cmdline_arguments():
parser = argparse.ArgumentParser(description='AKUINO: Pasteurisateur accessible')
# Est interprété directement par WebPY
parser.add_argument('port', type=int, help='Port number of the internal \
web server')
return parser.parse_args()
# restart_program()
args = manage_cmdline_arguments()
if hardConf.operatingSystem == 'Linux':
_lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) # pour Linux
try:
_lock_socket.bind('\0AKUINOpast')
print('Socket AKUINOpast now locked')
except socket.error:
print('AKUINOpast lock exists')
sys.exit()
else: # Other operating systems like MAC
import socklocks
try:
_lock_socket = socklocks.SocketLock('AKUINOpast')
print('Socket AKUINOpast now locked for '+hardConf.operatingSystem)
except socket.error:
print('AKUINOpast lock exists for '+hardConf.operatingSystem)
sys.exit()
datafiles.goto_application_root()
PI = 3.141592 # Yes, we run on a Raspberry !
# mL Volume of a tube based on ID(mm) and length(mm)
def vol_tube(internal_diameter,long): # retourne le volume d'un cylindre sur base de son diamètre et de sa longeur en mm, en cm3 (=mL)
rad = internal_diameter/2.0
return PI*rad*rad*long/1000.0 # cubic mm to cubic cm (mL)
# mL Volume of a tube based on ID(mm) of outer tube, OD of inner tube and length(mm)
def vol_outer_tube(OD_inner,ID_outer,long): # retourne le volume d'un cylindre creux(pour volume du tube externe de l'échangeur)
return vol_tube(ID_outer,long) - vol_tube(OD_inner,long)
# mL Volume of a coil based on ID(mm) and coil middle diam(mm) and number of spires
def vol_coil(diamT,diamS,nbS):
long = diamS*PI*nbS
return vol_tube(diamT,long)
def mL_L(mL): # milli Liters to Liters...
return mL / 1000.0
def L_mL(L): #Liters to milli Liters...
return L * 1000.0
tank = mL_L(hardConf.vol_heating)
start_volume = 0.0
total_volume = 0.0
safe_total_volume = 0.0
dry_volume = 0.0
def init_volumes():
global menus, cohorts, start_volume, total_volume, safe_total_volume, dry_volume
# Volumes for the different parts of the pasteurizer circuit
#hardConf.holding_volume = vol_tube(9.5,hardConf.holding_length) # = 625mL = 15 seconds for 150L / hour. Should be 833mL for 200L 11757
if hardConf.tubing == "horizontal":
#Amorçage=2330mL, Pasteurisation=625mL, Total=3587mL (new config system)
#exchanger_tube = vol_tube(8,8*1800)
up_to_solenoid = vol_tube(8, 1800) + vol_tube(8, 600)
heating_tube = vol_tube(10.5,500)+vol_coil(10.5,220,18)+vol_tube(8,200)+vol_coil(7,250,20)
up_to_thermistor = 2330.0
total_tubing = 3587.0
else:
#Amorçage=3031mL, Pasteurisation=625mL, Total=4989mL
#exchanger_tube = 2.0*712.6 #mL
up_to_solenoid = vol_tube(8, 2000) + vol_tube(9.5, 577) # Calculated: 317
heating_tube = vol_tube(9.5,500)+5127-3860 #1302 1444-336=1108 Calculated: 1407
up_to_thermistor = 3031.0 # Calculated: 2706
total_tubing = 4989.0 # Calculated: 5215
up_to_heating_tank = up_to_thermistor - heating_tube # Calculated: 1259
if hardConf.vol_intake:
up_to_solenoid = hardConf.vol_intake
if hardConf.vol_input:
up_to_heating_tank = hardConf.vol_input
if hardConf.vol_warranty:
up_to_thermistor = hardConf.vol_warranty
if hardConf.vol_total:
total_tubing = hardConf.vol_total
up_to_extra = total_tubing
if hardConf.vol_extra:
up_to_extra = hardConf.vol_extra
up_to_solenoid = up_to_solenoid - 100 + menus.val('E')
up_to_heating_tank = up_to_heating_tank - 100 + menus.val('E')
up_to_thermistor = up_to_thermistor - 100 + menus.val('E')
up_to_extra = up_to_extra - 200 + menus.val('E') + menus.val('S')
total_tubing = total_tubing - 200 + menus.val('E') + menus.val('S')
cohorts.sequence = [ # Tubing and Sensor Sequence of the Pasteurizer
[up_to_solenoid, 'intake'], # apres la pompe
[up_to_heating_tank - up_to_solenoid,'input'], #input de la chauffe
[up_to_thermistor - up_to_heating_tank, 'warranty'], # Garantie
[up_to_extra - up_to_thermistor, 'extra'] ]
# ,[total_tubing - up_to_extra, 'total']] # Sortie TO BE IMPLEMENTED WHEN EXTRA THERMISTOR WILL BE AVAILABLE
tell_message("Entrée=%dmL, avant Cuve=%dmL, Garantie=%dmL, Sortie=%dmL" % (cohorts.mL('intake'), cohorts.mL('input'), cohorts.mL('warranty'), cohorts.mL('extra')))
# Parameterized volumes are in Liters and not milliliters...
start_volume = mL_L(up_to_thermistor) # 1.9L
total_volume = mL_L(total_tubing) # 3.5L
safe_total_volume = total_volume - 0.1 #100ml is about the content of the output pipe
menus.options['u'][Menus.INI] = total_volume # Flush quantity
dry_volume = total_volume * 1.5 # (air) liters to pump to empty the tubes...
tell_message("Amorçage=%dmL, Pasteurisation=%dmL : %.1fL/h, Total=%dmL" % (int(up_to_thermistor), int(hardConf.holding_volume), (mL_L(hardConf.holding_volume) / 15.0) * 3600.0, int(total_tubing)))
init_volumes()
#Amorçage=1941mL, Pasteurisation=538mL, Total=3477mL
#Amorçage=2031mL, Pasteurisation=538mL, Total=3676mL
#Amorçage=2034mL, Pasteurisation=325mL, Total=3346mL
#Amorçage=2300mL, Pasteurisation=400mL, Total=3840mL MESURE
#Amorçage=2330mL, Pasteurisation=625mL, Total=3587mL (new config system)
#New exchanger:
#Amorçage=3031mL, Pasteurisation=625mL, Total=4989mL
KICKBACK = 13 # Haw many seconds the pump turns toward input after a flush in order to rinse the input pipe
DILUTE_VOL = 2.0 #L added in the bucket to dilute the cleaning products
#i=input(str(START_VOL*1000.0)+"/"+str(hardConf.holding_volume)+"/"+str(vol_tube(8,400)+vol_coil(8,250,10)+vol_tube(8,2000)))
SHAKE_QTY = mL_L(hardConf.holding_volume) / 4 # liters
SHAKE_TIME = 10.0 # seconds shaking while cleaning, rincing or disinfecting
GRADIENT_FOR_INTAKE = 20.0 # How many degrees do we heat the tank more than the desired temperature just after the pump
class ThreadOneWire(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
try:
self.owproxy = pyownet.protocol.proxy(host="localhost", port=4304)
except:
traceback.print_exc()
def sensorParam(self,address,param):
global cohorts
if address not in cohorts.catalog:
cohorts.addSensor(address,sensor.Sensor(typeOneWire,address,param))
cohorts.readCalibration(address)
return cohorts.catalog[address]
def run(self):
global cohorts
last = 0
loop = True
while loop:
try:
time.sleep(0.2)
now = time.perf_counter()
if now > (last+2.5):
last = now
if self.owproxy:
try:
status = self.owproxy.write("/simultaneous/temperature", b'1')
except:
traceback.print_exc()
if self.owproxy or hardConf.Rmeter:
for (address,aSensor) in cohorts.catalog.items():
#print (address)
if self.owproxy and aSensor.sensorType == typeOneWire and aSensor.param:
time.sleep(0.02)
try:
value = float(self.owproxy.read("/"+aSensor.param+"/temperature"))
if value != 85.0: # Can be invalid value...
aSensor.set(value)
except KeyboardInterrupt:
loop = False
break
except:
traceback.print_exc()
if hardConf.Rmeter and aSensor.sensorType == typeRMeter:
try:
r,v = hardConf.Rmeter.r_meter_get_ohms(0)
if r > 0:
aSensor.set(r)
except:
traceback.print_exc()
#print(r)
except KeyboardInterrupt:
loop = False
break
except:
traceback.print_exc()
# #####################################################################################
# BATT_ADC = 8 # ADC port for battery
# BATT_R1 = 46600.0 # Divider bridge to measure battery (top resistor)
# BATT_R2 = 5510.0 # bottom resistor
#def vari(adc_channel):
# moy = t[adc_channel] / n[adc_channel]
# s = (t2[adc_channel] / n[adc_channel]) - (moy * moy)
# if s < 0.0:
# s = - s
# s = s ** 0.5
# return ", M=%6.0f, s=%6.1f" % (moy,s)
class ThreadThermistor(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def sensorParam(self,address,param,beta,ohm25, A, B, C):
global cohorts
if param and address not in cohorts.catalog:
new_sensor = Thermistor(address,param)
if beta:
new_sensor.bResistance = beta
if ohm25:
new_sensor.t25Resistance = ohm25
if A:
new_sensor.A = A
if B:
new_sensor.B = B
if C:
new_sensor.C = C
cohorts.addSensor(address, new_sensor)
cohorts.readCalibration(address)
return cohorts.catalog[address]
def pressureSensorParam(self,address,param, flag):
global cohorts
if param and flag and address not in cohorts.catalog:
cohorts.addSensor(address,Pressure(address,param,flag))
cohorts.readCalibration(address)
return cohorts.catalog[address]
def run(self):
global cohorts
while True:
try:
time.sleep(1.0)
for (address, aSensor) in cohorts.catalog.items():
if aSensor.sensorType == Pressure.typeNum:
aSensor.get()
if aSensor.sensorType == Thermistor.typeNum:
aSensor.get()
if not hardConf.MICHA_device: # Average of 3 measures needed
time.sleep(0.01)
for (address, aSensor) in cohorts.catalog.items():
if aSensor.sensorType == Thermistor.typeNum:
aSensor.get()
time.sleep(0.01)
for (address, aSensor) in cohorts.catalog.items():
if aSensor.sensorType == Thermistor.typeNum:
aSensor.get()
value = aSensor.avg3()
if value is not None:
aSensor.set(value)
except KeyboardInterrupt:
break
except:
traceback.print_exc()
menus.actionName = { 'X':['X',ml.T("eXit","eXit","eXit") \
,ml.T("Ranger le matériel...","Put equipment back in place...","Berg de apparatuur op ..") \
,ml.T("Quitter l'application","Exit the application","Verlaat de applicatie")],
# 'U':['U',ml.T("pUrge","pUrge","zUiver") \
# ,ml.T("","Purge Output Tank...","Ontlucht de uitvoertank...") \
# ,ml.T("Purger le tampon de sortie...","Purge Output Tank...","Ontlucht de uitvoertank...")],
# 'C':['C',ml.T("Complet","full","vol") \
# ,ml.T("Entrée à la soupape, Sortie à la vanne bleue.","Inlet at the valve, Outlet at the blue valve.","Inlaat bij de klep, uitlaat bij de blauwe klep.") \
# ,ml.T("Cycle complet de nettoyage","Complete cleaning cycle","Volledige reinigingscyclus")],
'F':['F',ml.T("Flush","Flush","Flush") \
,ml.T("Entrée et Sortie dans un seau. Récupération?","Inlet and Outlet in the same bucket. Recycling?","Inlaat en uitlaat in dezelfde emmer. Recyclen?") \
,ml.T("Rinçage à l'eau de ville","Rinse with city water","Spoelen met stadswater")], \
'H':['H',ml.T("Eau pasteurisée","Pasteurized Water","Flush") \
,ml.T("Sortie là où rincer","Outlet where to rince","Uitlaat waar spoelen") \
,ml.T("Pasteuriser de l'eau de ville","Pasteurize city water","Pasteur stadswater")], \
# 'K':['K',ml.T("eau froide","Kooling","Kool") \
# ,ml.T("Spécifier AVANT la Quantité et la Température dans Options","Specify BEFORE Quantity and Temperature in Options","Specificeer VOOR hoeveelheid en temperatuur in Opties") \
# ,ml.T("Ajouter de l'eau froide dans la Tempérisation","Add cold water to Mitigation","Voeg koud water toe aan Mitigation")],
'V':['V',ml.T("Vider","Purge","Purge") \
,ml.T("Entrée hors de l'eau, Vidange...","Inlet out of water, Drain ...","Inlaat uit het water, Afvoer ...") \
,ml.T("Vidange maximale des tuyaux","Maximum emptying of pipes","Maximale lediging van leidingen")],
#'A':['A',ml.T("Amorc.","initiAte","Aanzet.") \
# ,ml.T("Entrée et Sortie connectés et dans un seau, Pré-chauffage...","Inlet and Outlet connected and in a bucket, Pre-heating ...","Input en output aangesloten en in een emmer, Voorverwarmen ...") \
# ,ml.T("Amorçage de la Pasteurisation","Initiating Pasteurization","Pasteurisatie initiëren")],
'B':['B',ml.T("caliB.","caliB.","caliB.") \
,ml.T("Seau d'eau en entrée+sortie","Water Bucket","Water Emmer") \
,ml.T("Calibration","Calibration","Calibratie")],
'P':['P',ml.T("Pasteur.","Pasteur.","Pasteur.") \
,ml.T("Lait de la traite en entrée; Récipient pasteurisé en sortie. Jeter l'eau","Milking milk at inlet; Pasteurized container at the outlet. Discard water","Melk melken als voorgerecht; Gepasteuriseerde container bij de uitlaat. Gooi water") \
,ml.T("Pasteurisation","Pasteurization","Pasteurisatie")],
'I':['I',ml.T("reprIse","resume","resume") \
,ml.T("Lait de la traite en entrée et un récipient pasteurisé en sortie","Milking milk at inlet and pasteurized container at outlet","Melk bij binnenkomst en gepasteuriseerde container bij vertrek") \
,ml.T("Reprise d'une pasteurisation interrompue","Resume an interrupted pasteurization","Hervatting van onderbroken pasteurisatie")],
'E':['E',ml.T("Eau","watEr","watEr") \
,ml.T("Eau en entrée et un récipient pasteurisé en sortie","Water inlet and a pasteurized container outlet","Waterinlaat en een gepasteuriseerde containeruitlaat") \
,ml.T("Pousser le lait qui reste d'une pasteurisation","Push the milk left over from pasteurization","Schuif de melk die overblijft na pasteurisatie")],
'M':['M',ml.T("Multi","Multi","Multi") \
,ml.T("Nouveau lait entrée et un récipient pasteurisé en sortie","New milk inlet and a pasteurized container outlet","Nieuwe melk bij de inlaat en een gepasteuriseerde container bij de uitlaat") \
,ml.T("Passer à un autre lait","Switch to another milk","Overschakelen naar een andere melk")],
'R':['R',ml.T("Rinçage avec Réemploi","Rinse with Reuse","Spoelen met Hergebruik") \
,ml.T("Entrée dans le seau de Récupération. Sortie à l'égout","Inlet in the recycling bucket. Outlet over sewer","Inlaat in het opvangemmer. Uitlaat naar riool") \
,ml.T("Rincer à fond le circuit","Rinse the circuit thoroughly","Spoel de leidingen grondig af")],
'C':['C',ml.T("net.Caustique","Caustic clean","Bijtend Schoon") \
,ml.T("Entrée et Sortie dans un même seau, Ajouter le Détergent...","Inlet and Outlet in a bucket, Add Detergent ...","Inlaat en uitlaat in dezelfde emmer. Wasmiddel toevoegen ...") \
,ml.T("Nettoyer avec un détergent (caustique)","Clean with detergent (caustic)","Reinig met afwasmiddel (bijtend)")],
'D':['D',ml.T("Désinfection","Disinfct","Desinfect.") \
,ml.T("Entrée et Sortie dans un même seau","Inlet and Outlet in a bucket","Inlaat en uitlaat in dezelfde emmer.") \
,ml.T("Désinfecter avec le produit approprié","Disinfect with sanitizer","Desinfecteren met ontsmettingsmiddel")], \
'A':['A',ml.T("net.Acide","Acidic clean","Zuur") \
,ml.T("Entrée et Sortie dans un même seau, Ajouter le nettoyant acide...","Inlet and Outlet in the same bucket, Add Acidic cleaner...","Inlaat en uitlaat in dezelfde emmer. Zuur wasmiddel toevoegen ...") \
,ml.T("Désinfecter les tuyaux (acide)","Disinfect pipes (acid)","Desinfecteer leidingen (zuur)")], \
'S':['S',ml.T("pauSe","pauSe","pause") \
,ml.T("Pause: bouton vert pour redémarrer","Pause: Green button to restart","Groene knop om opnieuw te starten") \
,ml.T("Suspendre ou arrêter l'opération en cours","Suspend or stop the current operation","Onderbreek of stop de huidige bewerking")],
'O':['O',ml.T("Options","Options","Opties") \
,ml.T("Paramètres de fonctionnement","Operating parameters","Bedrijfsparameters") \
,ml.T("Changement de paramètres","Change of parameters","Wijziging van parameters")],
'N':['N',ml.T("net.Options","Clng Options","Schoon.Opties") \
,ml.T("Paramètres de Nettoyage","Cleaning parameters","Schoon Bedrijfsparameters") \
,ml.T("Changement de paramètres","Change of parameters","Wijziging van parameters")],
'Y':['Y',ml.T("Yaourt","Yogurt","Yoghurt") \
,ml.T("Pasteuriser pour Yaourt","Pasteurize for Yogurt","Pasteuriseren voor yoghurt") \
,ml.T("Température pour Yaourt","Temperature for Yogurt","Temperatuur voor yoghurt")],
'J':['J',ml.T("Jus/Crème","Juice/Cream","Saap/Room") \
,ml.T("Pasteuriser du Jus ou de la Crème","Pasteurize for Juice or cream","Pasteuriseren voor saap of room") \
,ml.T("Température pour Jus ou Crème","Temperature for Juice or cream","Temperatuur voor saap of room")],
'K':['K',ml.T("Décongelé","Thawed","Ontdooid") \
,ml.T("Pasteuriser prod.décongelés","Pasteurize thawed products","Pasteuriseren ontdooid produc.") \
,ml.T("Température pour décongelés","Temperature for Thawed prod.","Temperatuur voor ontdooid produc.")],
'L':['L',ml.T("Lait","miLk","meLk") \
,ml.T("Pasteuriser du Lait","Pasteurize for Milk","Pasteuriseren voor melk") \
,ml.T("Température pour Lait","Temperature for Milk","Temperatuur voor melk")],
'T':['T',ml.T("Therm","Therm","Therm") \
,ml.T("Thermiser","Thermize","Thermis.") \
,ml.T("Température pour Thermiser","Temperature for Thermizing","Temperatuur voor thermisering")],
'Z':['Z',ml.T("STOP","STOP","STOP") \
,ml.T("Pas d'opération en cours.","No operation in progress.","Er wordt geen bewerking uitgevoerd.") \
,ml.T("Arrêt complet de l'opération en cours","Complete stop of the current operation","Volledige stopzetting van de huidige bewerking")],
'!':['!',ml.T("Seau fourni","Bucket provided","Emmer voorzien") \
,ml.T("Seau pour fournir l'eau ou le mélange.","Bucket providing water or mix.","Emmer om water of mengsel aan te voeren.") \
,ml.T("Prenez soin d'avoir au moins 7 litres.","You need at least 7 liters.","Zorg dat je minstens 7 liter hebt.")],
'+':['+',ml.T("Ajouté","Added","Toegevoegd") \
,ml.T("Produit chimique ajouté.","Chemical product added.","Chemisch product toegevoegd.") \
,ml.T("L'opération en cours ne doit plus s'interrompre","Current operation does not have to stop.","Huidige bewerking hoeft niet te stoppen.")],
'>':['>',ml.T("Forcer>","Force>","Kracht>") \
,ml.T("Avancer","Advance","Vooruit") \
#,ml.T("Surmonter une bulle d'air / Augmenter l'eau de lavage","Overcome an air bubble / Increase wash water","Overwin een luchtbel / verhoog het waswater")],
,ml.T("Surmonter une bulle d'air","Overcome an air bubble","Overwin een luchtbel")],
'_':['_',ml.T("Redémar.","Restart","Herstart") \
,ml.T("Redémarrage de l'opération en cours.","Restart of the current operation.","Herstart van de huidige bewerking.") \
,ml.T("Redémarrer l'opération en cours","Restart the current operation","Herstart de huidige bewerking")]}
menus.sortedActions1 = "PIMERDCAH"
menus.sortedActions2 = "FVOLYJKTZSXB" #K
menus.cleanActions = "LYJKTPIMEHV" #K
menus.dirtyActions = "RFDCAV"
menus.sysActions = "ZX"
menus.operName = { 'HEAT':ml.T('chauffer','heating','verwarm') \
,'PUMP':ml.T('pomper','pump','pomp') \
,'EMPT':ml.T('vider','purge','purge') \
,'TRAK':ml.T('débiter','trace','trace') \
,'SHAK':ml.T('brasser','shake','schud') \
,'REVR':ml.T('reculer','pump back','pomp terug') \
,'FILL':ml.T('remplir','fill','vullen') \
,'FLOO':ml.T('eau courante','running water','lopend water') \
,'RFLO':ml.T('rincer entrée','input rince','invoer rins') \
,'HOTW':ml.T('eau pasteurisée','pasteurized water','gepasteurde water') \
,'PAUS':ml.T('attendre','wait','wacht') \
,'SEAU':ml.T('seau','bucket','emmer') \
,'MESS':ml.T('signaler','message','bericht') \
,'SUBR':ml.T('processer','process','werkwijze') \
,'SUBS':ml.T('procéder','proceed','doorgan') }
# R + Pasteuriser Gras = G
# R + Pasteuriser Maigre = P
# R + Vider = A
# R + delay = O
# A + delay = B
# O + Flush x 2 = R
# O + Vider = B
# B + Flush = S
# R + longer delay = S
# P + Flush x 2 (P1,P2) = S
# G + Flush x 2 (G1,G2) = T
# T + Nettoyer = N au début, N0 quand complet
# S + Nettoyer = N au début, N0 quand complet
# Nx + Flush x 4 (N1,N2,N3,N4) = R
# S + Acide = D au début, D0 quand complet
# T + Acide INTERDIT
# Dx + Flush x 4 (D1,D2,D3,D4) = R
StateLessActions = "JYLT" # TO BE DUPLICATED in index.js !
# Empty sub state is managed by underlying operations
# Greasy sub state must be set
State('r',ml.T('Propre','Clean','Schoon'),'aqua', \
[ ('A',['r',['a',None,False]]),('P','p'),('D',['','d','d']),('H',''),('F',''),('V',''),('B',''),('w','o') ] )
State('o',ml.T('Eau','Water','Waser'),'navy', \
[ ('A',['o',['a',None,False]]),('F',''),('V',''),('B',''),('D',['','d','d']),('H',['','r']),('w','v') ] )
State('v',ml.T('Eau vieille','Old Water','Oude Waser'),'darkcyan', \
[ ('A',['v',['a',None,False]]),('C',['v',['c',None,False]]),('F',''),('V',''),('B',''),('D',['','d','d']),('w','') ] )
State('c',ml.T('Soude','Soda','Natrium'),'blue', \
[ ('R',['','r']),('F',['','r']),('V',''),('w','') ] )
State('a',ml.T('Acide','Acid','Zuur'),'red', \
[ ('R',['','r']),('F',['','r']),('V',''),('w','') ] )
State('d',ml.T('Désinfectant','Sanitizer','ontsmettingsmiddel'),'fuchsia', \
[ ('F',['','r']),('V',''),('w','') ] )
#State('p',ml.T('Produit Gras','Greasy Product','Vet Product'), \
# [ ('I',[['',None,True]]),('M',[['',None,True]]),('E','e'), ('C',['e','e',['c',None,False]]),('F','e'),('V','') ]
# , [False,True],[True] )
State('p',ml.T('Produit','Product','Product'),'orange', \
[ ('I',''),('M',''),('E',''),('R',['','e']),('F',['','e']),('V','') ] )
#State('e',ml.T('Eau+Produit Gras','Water+Greasy Product','Water+Vet Product'), \
# [ ('C',['e','e',['c',None,False]]),('P','p'),('F',''),('V',''),('w','s') ]
# , [False,True],[True] )
State('e',ml.T('Eau+Produit','Water+Product','Water+Product'),'darkorange', \
[ ('C',['e',['c',None,False]]),('P','p'),('R',''),('F',''),('V',''),('B',''),('w','s') ] )
#State('s',ml.T('Sale+Gras','Dirty+Greasy','Vies+Vet'), \
# [ ('C',['s','s',['c',None,False]]), ('F',''),('V',''),('w','') ]
# , [False,True],[True])
State('s',ml.T('Sale','Dirty','Vies'),'brown', \
[ ('C',['s','s',['c',None,False]]), ('R',''),('F',''),('V',''),('B',''),('w','') ] )
State('?','...','black', \
[ ('A',['a']),('C',['c']),('D',['d']), ('H','o'),('R','o'),('F','o'),('V','v'),('w','v'),('M','p'),('E','e'),('P','p'),('I','p'),['Z',''],('B','o'), ] )
def menu_confirm(choice,delay=None):
global display_pause, lines
prec_disp = display_pause
display_pause = True
time.sleep(0.05)
term.pos(lines-2,1)
choice = choice.upper()
term.write(str(menus.actionName[choice][1]), term.bgwhite, term.white, term.bold)
term.write(": "+str(menus.actionName[choice][Menus.VAL]), term.bgwhite, term.yellow, term.bold)
term.clearLineFromPos()
term.writeLine("", term.bgwhite, term.blue)
term.write(str(menus.actionName[choice][2])+": ", term.bgwhite, term.blue)
term.write(choice, term.bgwhite, term.red)
term.write("?", term.bgwhite, term.blue)
term.clearLineFromPos()
term.writeLine("", term.bgwhite, term.blue)
if not delay:
stopWait = time.time()*2 # a.k.very far in the future!
else:
stopWait = time.time() + delay
while time.time() < stopWait :
time.sleep(0.05)
conf = str(getch())
if conf:
conf = conf.upper()
term.pos(lines-1,1)
term.clearLineFromPos()
display_pause = prec_disp
if (conf == choice) or (conf == 'Z') or (conf == 'V'):
term.write(menus.actionName[choice][1], term.bgwhite, term.green,term.bold)
term.clearLineFromPos()
term.writeLine("", term.bgwhite, term.blue)
return conf
elif delay:
return ' '
term.pos(lines-1,1)
term.clearLineFromPos()
display_pause = prec_disp
return ' '
menu_choice = "?"
hotTapSolenoid = None # initialized further below
def option_confirm(delay=8.0):
global display_pause,lines
prec_disp = display_pause
display_pause = True
time.sleep(0.05)
term.pos(lines,1)
for choice in menus.sortedOptions:
term.write(choice, term.bgwhite, term.red)
term.write(": "+str(menus.options[choice][1]), term.bgwhite, term.blue)
if len(menus.options[choice]) > 3:
term.write("=", term.bgwhite, term.blue)
term.write(str(menus.val(choice))+(" L" if choice in ['K','Q'] else (" sec." if choice == 'M' else "°C")), term.bgwhite, term.yellow)
term.write(" "+str(menus.options[choice][2]), term.bgwhite, term.blue)
if len(menus.options[choice]) > 3:
term.write(" ("+str(menus.ini(choice))+")", term.bgwhite, term.blue)
term.clearLineFromPos()
term.writeLine("", term.bgwhite, term.blue)
term.clearLineFromPos()
term.writeLine("", term.bgwhite, term.blue)
term.clearLineFromPos()
term.writeLine("", term.bgwhite, term.blue)
stopWait = time.time() + delay
while time.time() < stopWait :
time.sleep(0.05)
conf = str(getch())
if conf:
conf = conf.upper()
term.pos(lines-1,1)
term.clearLineFromPos()
if conf == 'Z':
for choice in menus.options:
if len(menus.options[choice]) > 3:
menus.options[choice][Menus.VAL] = menus.options[choice][Menus.INI]
term.write(menus.options[conf][2], term.bgwhite, term.green,term.bold)
term.clearLineFromPos()
term.writeLine("", term.bgwhite, term.blue)
menus.save()
elif conf in menus.options.keys():
val = input(term.format(str(menus.options[conf][2])+"? ", term.bgwhite, term.white, term.bold))
try:
val = float(val)
menus.store(conf,val)
menus.save()
except:
pass
break
reloadPasteurizationSpeed()
display_pause = prec_disp
# returns clock time formatted as a floating number h.m
def floating_time(some_time):
return float(some_time.strftime("%H.%M"))
class ThreadDAC(threading.Thread):
#global coldTapSolenoid
def __init__(self):
global cohorts
threading.Thread.__init__(self)
self.dacSetting = Solenoid('DAC1',hardConf.DAC1)
#self.dacSetting = ssr.ssr('DAC1',0)
cohorts.addSensor(self.dacSetting.address,self.dacSetting)
#self.dacSetting2 = Solenoid('DAC2',hardConf.DAC2)
#cohorts.addSensor(self.dacSetting2.address,self.dacSetting2)
self.running = False
self.setpoint = None
self.refpoint = None
#self.setpoint2 = None
#self.coldpoint = None
self.T_Pump = None
self.totalWatts = 0.0
self.totalWatts2 = 0.0
self.currLog = None
self.empty_tank = False
self.danger = False
def set_temp(self,setpoint=None, refpoint=None):
if refpoint:
self.refpoint = float(refpoint)
else:
self.refpoint = None
if setpoint:
self.setpoint = float(setpoint)
else:
self.setpoint = None
self.dacSetting.set(0) # Arrêter net
# if setpoint2:
# self.setpoint2 = float(setpoint2)
# else:
# self.setpoint2 = None
# self.dacSetting2.set(0) # Arrêter net
# def set_cold(self,setpoint):
# if setpoint:
# self.coldpoint = float(setpoint)
# else:
# self.coldpoint = None
# coldTapSolenoid.set(0) # Arrêter net
def run(self):
global cohorts, display_pause,tank,ROOM_TEMP, lines, columns
self.running = True
lastLoop = time.perf_counter()
lastWatt = 0
prec_heating = None
some_heating = False
has_heated = False
# TODO: allow to balance both heating tanks to reduce power demand
while self.running:
time.sleep(0.01)
now = time.perf_counter()
if now > (lastLoop+cohorts.periodicity):
delay = now - lastLoop
lastLoop = now
cohorts.nextPeriod()
try:
wattHour = False
flooding = False
# if self.setpoint is not None and (cohorts.catalog['heating'].value <= self.setpoint):
# kCal = (self.setpoint-cohorts.catalog['heating'].value)*tank
# wattHour = (kCal * kCalWatt) * 60.0
# # refroidissement prévu (perte générale par les parois)
# wattHour += (self.setpoint-ROOM_TEMP)*240.0/37.0
# # injection de lait prévue
# if self.T_Pump.pump.speed > 0.0:
# wattHour += (self.setpoint-cohorts.catalog['input'].value)*self.T_Pump.pump.liters()*kCalWatt
# if wattHour <= 1.0:
# wattHour = 0.0
# elif wattHour >= hardConf.power_heating:
# wattHour = hardConf.power_heating
if self.setpoint and cohorts.catalog['heating'].value:
currHeat = int(self.dacSetting.value)
#print("%d %f / %f" % (currHeat, cohorts.catalog['heating'].value , self.setpoint) )
heating = cohorts.getCalibratedValue('heating')
if currHeat > 0: # ON
if self.T_Pump.pasteurizationOverSpeed:
wattHour = heating < (self.refpoint+HYSTERESIS)
elif heating < (self.setpoint+HYSTERESIS):
wattHour = True
else: # Off
if self.T_Pump.pasteurizationOverSpeed:
wattHour = heating < (self.refpoint-HYSTERESIS)
elif heating < (self.setpoint-HYSTERESIS):
wattHour = True
if wattHour and not self.empty_tank:
self.dacSetting.set(1)
self.totalWatts += (hardConf.power_heating/3600.0 * delay)
if not lastWatt or self.T_Pump.pump.speed != 0.0:
lastWatt = now
prec_heating = heating
some_heating = False
else:
if heating > (prec_heating + 0.3):
has_heated = True
if heating > (prec_heating + 0.1):
some_heating = True
if (now - lastWatt) > TANK_EMPTY_LIMIT:
if not has_heated and some_heating:
self.empty_tank = True
print("EMPTY TANK, stop heating!")
self.dacSetting.set(0)
else:
lastWatt = now
prec_heating = heating
some_heating = False
else:
self.dacSetting.set(0)
lastWatt = 0
prec_heating = None
some_heating = False
else:
self.dacSetting.set(0)
lastWatt = 0
prec_heating = None
some_heating = False
#self.dacSetting.set(wattHour)
#self.totalWatts += (wattHour/3600.0 * delay)