-
Notifications
You must be signed in to change notification settings - Fork 0
/
SugarCubes.py
737 lines (687 loc) · 25.2 KB
/
SugarCubes.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
#
# SugarCubes.py
# Auteur du modèle théorique : Jean-Ferdy Susini
# Auteur de l'implémentation python : Claude Lion
# Date création : 04/06/2018
# Copyright : © Claude Lion 2018
#
from SugarCubesUtils import *
# avancements
PAS_FINI = 0
FINI = 1
forever = -1
gListStr_operatorsBin = ['add', 'sub', 'mul', 'truediv', 'floordiv', 'mod', 'divmod', 'pow', 'lshift', 'rshift', 'and', 'or', 'xor', 'lt', 'le', 'eq', 'ne', 'gt', 'ge']
class ListeValInfo:
def __init__(self, pList_val):
self.aList_val = pList_val
def __iter__(self):
return iter(self.aList_val)
def __str__(self):
# return '\n'.join([str(val.evaluate() if hasattr(val, 'evaluate') else val) for val in self.aList_val])
return '\n'.join([str(val) for val in self.aList_val])
def __bool__(self):
return all(self.aList_val)
@classmethod
def addOperToListeValInfo(cls, ps_operator):
def tempOper(self, pListeValInfo):
import operator
return self.__class__(
[
getattr(operator, '__' + ps_operator + '__')(val1, val2)
for val1 in self
for val2 in pListeValInfo
]
)
setattr(cls, '__' + ps_operator + '__', tempOper)
@classmethod
def addListeOperToListeValInfo(cls, pListeStr_operator):
for ls_operator in pListeStr_operator:
cls.addOperToListeValInfo(ls_operator)
ListeValInfo.addListeOperToListeValInfo(gListStr_operatorsBin)
class Info:
def __init__(self, ps_type, p_valeur):
self.as_type = ps_type
self.a_valeur = p_valeur
def isSensor(self):
return self.as_type[0] == '$'
def getValeur(self):
if isinstance(self.a_valeur, LiveProgram) and hasattr(self.a_valeur, 'evaluate'):
return self.a_valeur.evaluate()
elif callable(self.a_valeur):
return self.a_valeur()
else:
return self.a_valeur
def addToDictInfo(self, pDictInfo):
try:
pDictInfo[self.as_type]
except KeyError:
pDictInfo[self.as_type] = []
if self.a_valeur != None:
pDictInfo[self.as_type].append(self.a_valeur)
class Instant:
def __init__(self, p_instant):
self.an_num = p_instant.an_num + 1 if isinstance(p_instant, Instant) else 0
self.aDict_configOuString__typesInfoAttendu = {} # clé : id(await), valeur : config
self.aDictInfo_pourInstantSuivant = {}
self.aSetLiveProg_finiPourLInstant = set()
try:
self.aDictInfo_diffusees = p_instant.aDictInfo_pourInstantSuivant
except AttributeError:
self.aDictInfo_diffusees = {}
try:
self.aDictInfo_diffuseesPrecedemment = p_instant.aDictInfo_diffusees
except AttributeError:
self.aDictInfo_diffuseesPrecedemment = {}
self.aListFun_actionAtomique = []
self.aListFun_actionAtomiqueOnConfig = []
self.aDictList_nouvellesBranches = {} # clé : id(par), valeur : listes des nouvelles branches
def evalVal(self, ps_typeInfo__pLiveProgram_boolean):
try:
return ps_typeInfo__pLiveProgram_boolean.evaluate()
except AttributeError:
return self.aDictInfo_diffuseesPrecedemment[ps_typeInfo__pLiveProgram_boolean]
def evalConfig(self, ps_typeInfo__pLiveProgram_boolean):
try:
return ps_typeInfo__pLiveProgram_boolean.evaluate()
except AttributeError:
return ps_typeInfo__pLiveProgram_boolean in self.aDictInfo_diffusees
class Processeur:
def __init__(self):
self.aProgParallel = ProgParallel()
self.aLiveProgParallel = self.aProgParallel.getLive()
self.aLiveProgParallel.aProcesseur = self
self.aInstant = Instant(None)
def generateEvent(self, ps_typeInfo, p_valInfo=None):
lDictInfo_suiv = self.aInstant.aDictInfo_pourInstantSuivant
Info(ps_typeInfo, p_valInfo).addToDictInfo(lDictInfo_suiv)
def addProgram(self, pProg):
self.aProgParallel.add(pProg)
self.aLiveProgParallel.add(pProg.getLive())
def isThereSomethingToUnblock(self):
lDict_typesInfoAttendu = self.aInstant.aDict_configOuString__typesInfoAttendu
return any(
[
self.aInstant.evalConfig(lDict_typesInfoAttendu[idInstrAwait])
for idInstrAwait in lDict_typesInfoAttendu
]
)
def doMacroEtape(self):
# Mise en place nouvel instant
#---------------------------------
self.aInstant = Instant(self.aInstant)
# Exécution normale
#---------------------------------
# printErr('---------------------------------------------------------------------')
# printErr('--> num instant : ' + str(self.aInstant.an_num))
# printErr('---------------------------------------------------------------------')
while not self.aLiveProgParallel.isFiniPourMacroEtape():
self.aLiveProgParallel.doMicroEtape()
if not self.isThereSomethingToUnblock(): break
# Exécution spéciale "fin d'instant"
#-----------------------------------
self.aLiveProgParallel.doMicroEtapeDeFinDInstant()
# Exécution ActionOnConfig
#-----------------------------------
lInstant = self.aInstant
for lFunOnConfig in self.aInstant.aListFun_actionAtomiqueOnConfig:
if lInstant.evalConfig(lFunOnConfig['config']):
lFunOnConfig['action'](lInstant.aDictInfo_diffusees)
else:
lFunOnConfig['defaut'](lInstant.aDictInfo_diffusees)
# Exécution Action
#-----------------------------------
for lFun in self.aInstant.aListFun_actionAtomique:
lFun()
# Ajout branches
#-----------------------------------
for lLiveParId in lInstant.aDictList_nouvellesBranches:
for lLiveProg_branche in lInstant.aDictList_nouvellesBranches[lLiveParId]:
getObjectById(lLiveParId).add(lLiveProg_branche)
class Program: # abstract
niv_tab = 0
def __init__(self, *args, **kwargs):
self.aList_args = list(args)
self.aDict_kwargs = dict(kwargs)
self.aDict_localsCaller = getLocalsCaller()
def getClassNameLive(self, pClass):
try:
return getGlobalByName(__name__, 'Live' + pClass.__name__)
except AttributeError:
for lClass_base in pClass.__bases__:
ls_rep = self.getClassNameLive(lClass_base)
if ls_rep != None: return ls_rep
def getLive(self):
lClass_live = self.getClassNameLive(self.__class__)
lList_liveArgs = [
arg.getLive() if isinstance(arg, Program) else arg
for arg in self.aList_args
]
lLiveProg = lClass_live(*lList_liveArgs, **self.aDict_kwargs)
lLiveProg.aProg = self
return lLiveProg
def __str__(self):
ls_nom = self.__class__.__name__
if 'Prog' in ls_nom:
ls_nom = ls_nom[4:]
ls_debut = ls_nom + '(\n'
ls_fin = ')'
ls_milieu = ',\n'.join( [ str(arg) for arg in self.aList_args ] ) + '\n'
self.__class__.niv_tab += 1
ls_milieu = getAvecTab(ls_milieu, self.__class__.niv_tab)
self.__class__.niv_tab -= 1
return ls_debut + ls_milieu + ls_fin
initUtils(__name__, Program)
class LiveProgram: # abstract
def __init__(self, *args):
self.ai_avancement = PAS_FINI
self.aList_args = list(args)
setParent(args, self)
def getPropriete(self, ps_nomPropriete):
try:
return getattr(self.aProg, ps_nomPropriete)
except AttributeError:
if not hasattr(self, 'a_parent'):
printErr('target not found : ' + ps_nomPropriete)
import sys
sys.exit()
return self.a_parent.getPropriete(ps_nomPropriete)
def getProcesseur(self):
try:
return self.aProcesseur
except AttributeError:
return self.a_parent.getProcesseur()
def isFiniPourMacroEtape(self):
return self.isTerminee() or id(self) in self.getProcesseur().aInstant.aSetLiveProg_finiPourLInstant
def isTerminee(self):
return self.ai_avancement == FINI
def copyAvancement(self, pLiveProg):
self.ai_avancement = pLiveProg.ai_avancement
lSetLiveProg_fini = self.getProcesseur().aInstant.aSetLiveProg_finiPourLInstant
if pLiveProg.isFiniPourMacroEtape():
self.setFiniPourMacroEtape()
else:
lSetLiveProg_fini.discard(id(self))
def copyMinAvancement(self, pListLiveProg):
lList_avancement = [ lLiveProg.ai_avancement for lLiveProg in pListLiveProg ]
self.ai_avancement = min( lList_avancement ) if len(lList_avancement) else FINI
lSetLiveProg_fini = self.getProcesseur().aInstant.aSetLiveProg_finiPourLInstant
if all( [
lLiveProg.isFiniPourMacroEtape() or lLiveProg.isTerminee()
for lLiveProg in pListLiveProg
] ):
self.setFiniPourMacroEtape()
def setFiniPourMacroEtape(self):
lSetLiveProg_fini = self.getProcesseur().aInstant.aSetLiveProg_finiPourLInstant
lSetLiveProg_fini.add(id(self))
def terminer(self):
self.ai_avancement = FINI
def doMicroEtape(self):
if not self.isFiniPourMacroEtape():
self.doTransition()
def doMicroEtapeDeFinDInstant(self):
self.doTransitionFinale()
def doTransitionFinale(self):
pass
@deLive('double')
class LiveProgExecWithStop(LiveProgram):
def __init__(self, p_configEvent, pLiveProg, pLiveProg_lastWill=None):
super().__init__(p_configEvent, pLiveProg, pLiveProg_lastWill)
self.a_configEvent = p_configEvent
self.aLiveProg = pLiveProg
self.aLiveProg_lastWill = pLiveProg_lastWill
self.ab_killable = True
def doTransition(self):
self.aLiveProg.doMicroEtape()
self.copyAvancement(self.aLiveProg)
def doTransitionFinale(self):
self.aLiveProg.doMicroEtapeDeFinDInstant()
lInstant = self.getProcesseur().aInstant
if self.ab_killable and lInstant.evalConfig(self.a_configEvent):
if self.aLiveProg_lastWill != None:
self.aLiveProg = self.aLiveProg_lastWill
self.aLiveProg_lastWill = None
self.ab_killable = False
else:
self.terminer()
@deLive('double')
class LiveProgWhen(LiveProgram):
def __init__(self, p_configEvent, pLiveProg, pLiveProg_else=None):
super().__init__(p_configEvent, pLiveProg, pLiveProg_else)
self.a_configEvent = p_configEvent
self.aLiveProg = pLiveProg
self.aLiveProg_else = pLiveProg_else
self.aLiveProg_courant = None
def doTransition(self):
if self.aLiveProg_courant == None:
lInstant = self.getProcesseur().aInstant
if lInstant.evalConfig(self.a_configEvent):
try:
del lInstant.aDict_configOuString__typesInfoAttendu[id(self)]
except KeyError: pass
self.aLiveProg_courant = self.aLiveProg
else:
lInstant.aDict_configOuString__typesInfoAttendu[id(self)] = self.a_configEvent
if self.aLiveProg_courant != None:
self.aLiveProg_courant.doMicroEtape()
self.copyAvancement(self.aLiveProg_courant)
def doTransitionFinale(self):
if self.aLiveProg_courant != None:
self.aLiveProg_courant.doMicroEtapeDeFinDInstant()
self.copyAvancement(self.aLiveProg_courant)
else:
self.aLiveProg_courant = self.aLiveProg_else
if self.aLiveProg_else == None:
self.terminer()
@deLive('double')
class LiveProgTest(LiveProgram):
def __init__(self, p_condition, pLiveProg, pLiveProg_else=None):
super().__init__(p_condition, pLiveProg, pLiveProg_else)
self.a_condition = p_condition
self.aLiveProg = pLiveProg
self.aLiveProg_else = pLiveProg_else
self.aLiveProg_courant = None
def doTransition(self):
if self.aLiveProg_courant == None:
if isinstance(self.a_condition, bool):
lb_condition = self.a_condition
else:
lb_condition = self.a_condition()
if lb_condition:
self.aLiveProg_courant = self.aLiveProg
else:
self.aLiveProg_courant = self.aLiveProg_else
if self.aLiveProg_courant != None:
self.aLiveProg_courant.doMicroEtape()
self.copyAvancement(self.aLiveProg_courant)
else:
self.terminer()
@deLive('double')
class LiveProgMatch(LiveProgram):
def __init__(self, p_condition, *pList_LiveProg):
super().__init__(p_condition, *pList_LiveProg)
self.a_condition = p_condition
self.aList_LiveProg = pList_LiveProg
self.aLiveProg_courant = None
def doTransition(self):
if self.aLiveProg_courant == None:
if isinstance(self.a_condition, int):
ln_num = self.a_condition
else:
ln_num = getattr(self.a_condition[0], self.a_condition[1], -1)
try:
self.aLiveProg_courant = self.aList_LiveProg[ln_num]
except IndexError: pass
if self.aLiveProg_courant != None:
self.aLiveProg_courant.doMicroEtape()
self.copyAvancement(self.aLiveProg_courant)
else:
self.terminer()
@deLive('double')
class LiveProgNothing(LiveProgram):
def __init__(self, *args):
super().__init__(*args)
self.terminer()
def doTransition(self):
pass
def doTransitionFinale(self):
pass
@deLive('double')
class LiveProgAnd(LiveProgram):
def __init__(self, *args):
super().__init__(*args)
def doTransition(self):
self.terminer()
def evaluate(self):
lProcesseur = self.getProcesseur()
return all([
lProcesseur.aInstant.evalConfig(arg)
for arg in self.aList_args
])
@deLive('double')
class LiveProgOr(LiveProgram):
def __init__(self, *args):
super().__init__(*args)
def doTransition(self):
self.terminer()
def evaluate(self):
lProcesseur = self.getProcesseur()
return any([
lProcesseur.aInstant.evalConfig(arg)
for arg in self.aList_args
])
def addOperatorBin(ps_operator):
class tempLiveProgOperBin(LiveProgram):
def __init__(self, *args):
super().__init__(*args)
def doTransition(self):
self.terminer()
def evaluate(self):
lProcesseur = self.getProcesseur()
l_arg0_orig = self.aList_args[0]
l_arg1_orig = self.aList_args[1]
l_arg0 = l_arg0_orig.evaluate() if hasattr(l_arg0_orig, 'evaluate') else ListeValInfo([l_arg0_orig])
l_arg1 = l_arg1_orig.evaluate() if hasattr(l_arg1_orig, 'evaluate') else ListeValInfo([l_arg1_orig])
import operator
return getattr(operator, '__' + ps_operator + '__')(l_arg0, l_arg1)
ls_nomClasse = 'LiveProg' + ps_operator[0].upper() + ps_operator[1:] + 'Bin'
tempLiveProgOperBin.__name__ = ls_nomClasse
tempLiveProgOperBin = deLive('double')(tempLiveProgOperBin)
globals()[ls_nomClasse] = tempLiveProgOperBin
def addListeOperatorBin(pListStr_operator):
for ls_operator in pListStr_operator:
addOperatorBin(ls_operator)
addListeOperatorBin(gListStr_operatorsBin)
@deLive('double')
class LiveProgGetval(LiveProgram):
def __init__(self, *args):
super().__init__(*args)
self.as_typeInfo = self.aList_args[0]
if len(args) == 2:
self.aFunc_aggreg = self.aList_args[1]
else:
self.aFunc_aggreg = lambda x:x
if len(args) > 2: raise TypeError("Trop d'argument : Getval prend un ou deux argument")
def doTransition(self):
self.terminer()
def evaluate(self):
lDict_localsCaller = self.aProg.aDict_localsCaller
# printErr(lDict_localsCaller)
if self.as_typeInfo in lDict_localsCaller:
return ListeValInfo( [lDict_localsCaller[self.as_typeInfo]] )
else:
lProcesseur = self.getProcesseur()
lListeValInfo = ListeValInfo( self.aFunc_aggreg( lProcesseur.aInstant.evalVal(self.as_typeInfo) ) )
return lListeValInfo
@deLive('double')
class LiveProgSequentialFunction(LiveProgram):
def __init__(self, *args):
super().__init__(*args)
self.aFunc_fonction = self.aList_args[0]
self.aList_argumentsFonction = self.aList_args[1:]
def doTransition(self):
self.terminer()
def evaluate(self):
return ListeValInfo([ self.aFunc_fonction(*[
arg.evaluate() if hasattr(arg, 'evaluate') else arg
for arg in self.aList_argumentsFonction
]) ])
@deLive('double')
class LiveProgDiffuse(LiveProgram):
def __init__(self, ps_typeInfo, p_valeurInfo=None):
super().__init__(ps_typeInfo, p_valeurInfo)
self.aInfo = Info(ps_typeInfo, p_valeurInfo)
if self.aInfo.isSensor(): raise TypeError('Les sensors ne peuvent pas être diffusés')
def doTransition(self):
lProcesseur = self.getProcesseur()
lDictInfo_diffusees = lProcesseur.aInstant.aDictInfo_diffusees
l_valeur = self.aInfo.getValeur()
if isinstance(l_valeur, ListeValInfo):
# printErr(l_valeur.aList_val)
for val in l_valeur:
# printErr(val)
lInfo_updated = Info(self.aInfo.as_type, val)
lInfo_updated.addToDictInfo(lDictInfo_diffusees)
else:
lInfo_updated = Info(self.aInfo.as_type, l_valeur)
lInfo_updated.addToDictInfo(lDictInfo_diffusees)
self.terminer()
@deLive('simple')
class LiveProgFilter(LiveProgram):
def __init__(self, ps_typeSensor, ps_typeInfo, pFunc_filtre):
super().__init__(ps_typeSensor, ps_typeInfo, pFunc_filtre)
self.as_typeSensor = ps_typeSensor
self.as_typeInfo = ps_typeInfo
self.aFunc_filtre = pFunc_filtre
if ps_typeSensor[0] != '$': raise TypeError('Seuls les sensors peuvent être filtrés')
if ps_typeInfo[0] == '$': raise TypeError('Les sensors ne peuvent pas être diffusés')
def doTransition(self):
lProcesseur = self.getProcesseur()
lDictInfo_diffusees = lProcesseur.aInstant.aDictInfo_diffusees
if self.as_typeSensor in lDictInfo_diffusees:
l_valRet = self.aFunc_filtre(lDictInfo_diffusees[self.as_typeSensor])
if l_valRet != None:
Info(self.as_typeInfo, l_valRet).addToDictInfo(lDictInfo_diffusees)
self.terminer()
@deLive('double')
class LiveProgAwait(LiveProgram):
def __init__(self, p_typesInfoAttendue):
super().__init__(p_typesInfoAttendue)
self.a_typesInfoAttendue = p_typesInfoAttendue
def doTransition(self):
lProcesseur = self.getProcesseur()
if lProcesseur.aInstant.evalConfig(self.a_typesInfoAttendue):
try:
del lProcesseur.aInstant.aDict_configOuString__typesInfoAttendu[id(self)]
except KeyError: pass
self.terminer()
else:
lProcesseur.aInstant.aDict_configOuString__typesInfoAttendu[id(self)] = self.a_typesInfoAttendue
def doTransitionFinale(self):
pass
@deLive('double')
class LiveProgControl(LiveProgram):
def __init__(self, p_typesInfoAttendue, pLiveProg):
super().__init__(p_typesInfoAttendue, pLiveProg)
self.a_typesInfoAttendue = p_typesInfoAttendue
self.aLiveProg = pLiveProg
def doTransition(self):
lProcesseur = self.getProcesseur()
if lProcesseur.aInstant.evalConfig(self.a_typesInfoAttendue):
try:
del lProcesseur.aInstant.aDict_configOuString__typesInfoAttendu[id(self)]
except KeyError: pass
self.aLiveProg.doMicroEtape()
self.copyAvancement(self.aLiveProg)
else:
lProcesseur.aInstant.aDict_configOuString__typesInfoAttendu[id(self)] = self.a_typesInfoAttendue
def doTransitionFinale(self):
lProcesseur = self.getProcesseur()
if lProcesseur.aInstant.evalConfig(self.a_typesInfoAttendue):
self.aLiveProg.doMicroEtapeDeFinDInstant()
self.copyAvancement(self.aLiveProg)
@deLive('double')
class LiveProgPause(LiveProgram):
def __init__(self, pn_nombreFois=1):
super().__init__(pn_nombreFois)
self.ai_pausesRestantes = pn_nombreFois
def doTransition(self):
if self.ai_pausesRestantes == 0:
self.terminer()
else:
self.ai_pausesRestantes -= 1
self.setFiniPourMacroEtape()
def setNouvelleMacroEtape(self):
self.setPlusFiniPourMacroEtape()
@deLive('simple')
class LiveProgramAtom(LiveProgram): # abstract
def doTransition(self):
self.getProcesseur().aInstant.aListFun_actionAtomique.append(self.doIt)
self.terminer()
class ProgAtomPrint(ProgramAtom): pass
class LiveProgAtomPrint(LiveProgramAtom):
def doIt(self):
l_argOrig = self.aList_args[0]
l_arg = l_argOrig.evaluate() if hasattr(l_argOrig, 'evaluate') else l_argOrig
print(l_arg)
Print = ProgAtomPrint
class ProgAtomAction(ProgramAtom): pass
class LiveProgAtomAction(LiveProgramAtom):
def doIt(self):
if isinstance(self.aList_args[0], str):
lFun = self.getPropriete(self.aList_args[0])
else:
lFun = self.aList_args[0]
lFun()
def fonctionVide(pDict_info): pass
@deLive('double')
class LiveProgActionOnConfig(LiveProgramAtom):
def doTransition(self):
try:
if self.aList_args[2] == None:
self.aList_args[2] = fonctionVide
except IndexError:
self.aList_args.append(fonctionVide)
self.getProcesseur().aInstant.aListFun_actionAtomiqueOnConfig.append({
'config': self.aList_args[0],
'action': self.aList_args[1],
'defaut': self.aList_args[2]
})
self.terminer()
class ProgParallel(Program):
def add(self, pProg):
self.aList_args.append(pProg)
class LiveProgParallel(LiveProgram):
def __init__(self, *args, channel=None):
super().__init__(*args)
self.as_typeInfo_channel = channel
def add(self, pLiveProg):
self.aList_args.append(pLiveProg)
pLiveProg.a_parent = self
def __str__(self):
return ' || '.join( [ str(arg) for arg in self.aList_args ] )
def doTransition(self):
for l_instr in self.aList_args:
l_instr.doMicroEtape()
self.copyMinAvancement(self.aList_args)
def doTransitionFinale(self):
for l_instr in self.aList_args:
l_instr.doMicroEtapeDeFinDInstant()
self.copyMinAvancement(self.aList_args)
if self.as_typeInfo_channel != None:
lInstant = self.getProcesseur().aInstant
if self.as_typeInfo_channel in lInstant.aDictInfo_diffusees:
lDict_nouvBranch = lInstant.aDictList_nouvellesBranches
try:
lDict_nouvBranch[id(self)]
except KeyError:
lDict_nouvBranch[id(self)] = []
for lLiveProg in lInstant.aDictInfo_diffusees[self.as_typeInfo_channel]:
lDict_nouvBranch[id(self)].append(lLiveProg)
self.ai_avancement = PAS_FINI
ProgPar = ProgParallel
Par = ProgParallel
class LiveProgSeq_(LiveProgram):
def __init__(self, pIter_instr):
super().__init__()
self.aIter_instr = pIter_instr
lList_elemSupplementaires = next(self.aIter_instr)
setParent(lList_elemSupplementaires, self)
def doTransition(self):
while True:
try:
if not hasattr(self, 'aProg_courante') or self.aProg_courante.isTerminee():
self.aProg_courante = next(self.aIter_instr)
setParent([self.aProg_courante], self)
except StopIteration:
break
self.aProg_courante.doMicroEtape()
if not self.aProg_courante.isTerminee():
self.copyAvancement(self.aProg_courante)
return
self.terminer()
def doTransitionFinale(self):
try:
self.aProg_courante.doMicroEtapeDeFinDInstant()
if not self.aProg_courante.isTerminee():
self.copyAvancement(self.aProg_courante)
except AttributeError: pass
@deLive('simple')
class LiveProgSequence(LiveProgram):
def __new__(cls, *args):
lList_elemsSupplementaires = []
return LiveProgSeq_( iter( [lList_elemsSupplementaires] + list(args) ) )
def __str__(self):
return '; '.join( [ str(arg) for arg in self.aList_args ] )
ProgSeq = ProgSequence
Seq = ProgSequence
@deLive('double')
class LiveProgLoop(LiveProgram):
def __new__(cls, pLiveProgram_corps, pn_nombreFois=1, pFunc_cond=None, pb_conditionPartout=False):
def getNewIter(pLiveProgram_corps, pn_nombreFois):
lList_elemsSupplementaires = [pFunc_cond]
yield lList_elemsSupplementaires
if pn_nombreFois == 0: return
ln_nombreProgDejaFaite = 0
while True:
# verif condition si pb_conditionPartout
#---------------------------------------
if pb_conditionPartout and pFunc_cond != None:
if not pFunc_cond: break
if hasattr(pFunc_cond, 'evaluate') and not pFunc_cond.evaluate(): break
# exec corps
#-----------
yield pLiveProgram_corps
# reset corps
#------------
ln_nombreProgDejaFaite += 1
lParent = pLiveProgram_corps.a_parent
pLiveProgram_corps = pLiveProgram_corps.aProg.getLive()
pLiveProgram_corps.a_parent = lParent
# verif condition
#----------------
if pFunc_cond != None:
if hasattr(pFunc_cond, 'evaluate'):
lb_res = pFunc_cond.evaluate()
# printErr('--------------> ' + str(type(lb_res)))
if not lb_res: break
elif callable(pFunc_cond) and not pFunc_cond(): break
elif not pFunc_cond: break
# printErr(pn_nombreFois)
# verif nombre de tour
#---------------------
if ln_nombreProgDejaFaite >= pn_nombreFois*2 - 1 and pn_nombreFois != -1: break
# exec pause
#-----------
lLivePause = Pause().getLive()
lLivePause.a_parent = lParent
yield lLivePause
ln_nombreProgDejaFaite += 1
# printErr('+++++++++++++++++++++++++++++')
return
return LiveProgSeq_( getNewIter(pLiveProgram_corps, pn_nombreFois) )
# Instruction composée
#---------------------
def DiffuseMulti(ps_typeInfo, p_valInfo=None, pn_nombreFois=1):
return Loop(Diffuse(ps_typeInfo, p_valInfo), pn_nombreFois)
def ActionOnMulti(p_configEvent, pFun_reaction, pFun_default=None, pn_nombreFois=1):
return Loop(ActionOnConfig(p_configEvent, pFun_reaction, pFun_default), pn_nombreFois)
def ActionMulti(pFun, pn_nombreFois=1):
return Loop( ProgAtomAction(pFun), pn_nombreFois )
def Repeat(pn_nombreFois, *args):
return Loop( Seq(*args), pn_nombreFois )
RepeatS = Repeat
def RepeatForever(*args):
return Repeat(-1, *args)
def IfRepeat(pFunc_condition, *args):
return Loop( Seq(*args), -1, pFunc_condition )
def While(pFunc_condition, *args):
return Loop( Seq(*args), -1, pFunc_condition, True )
def IfRepeatLabel(ps_label, pFunc_condition, *args):
lProg = IfRepeat(pFunc_condition, *args)
lProg.as_label = ps_label
return lProg
def Filter(ps_typeSensor, ps_typeInfo, pFunc_filtre, pn_nombreFois=1):
return Loop( ProgFilter(ps_typeSensor, ps_typeInfo, pFunc_filtre), pn_nombreFois )
def ControlS(p_configEvent, *args):
return ProgControl(p_configEvent, Seq(*args))
def KillS(p_configEvent, *args):
return ExecWithStop(p_configEvent, Seq(*args))
def PauseForever():
return Pause(forever)
def Parex(ps_typeInfo_channel, *args):
return Par(*args, channel=ps_typeInfo_channel)
# Alias
#--------
Generate = DiffuseMulti
GenerateM = DiffuseMulti
ActionOn = ActionOnMulti
ActionOnM = ActionOnMulti
Action = ActionMulti
Write = Print
Kill = ExecWithStop
Processeur.react = Processeur.doMacroEtape
# Modélisation Monde, Acteur
#---------------------------
Monde = Processeur
Actor = Par
Processeur.addActor = Processeur.addProgram