models.py 63.6 KB
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
##from __future__ import unicode_literals

# (EP 21/9/22) To allow autoreferencing (ex: AgentCmd.create() returns a AgentCmd)
from __future__ import annotations

# Stdlib imports
from src.device_controller.abstract_component.device_controller import DeviceCmd
from datetime import datetime, timedelta, date
from dateutil.relativedelta import relativedelta
import os
import sys
from typing import Any, List, Tuple, Optional
import re

# Django imports
from django.core.validators import MaxValueValidator, MinValueValidator

# DJANGO imports
from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models
from django.db.models import Q, Max
from django.core.validators import MaxValueValidator, MinValueValidator
#from django.db.models.deletion import DO_NOTHING
from django.db.models.expressions import F
from django.db.models.query import QuerySet
from model_utils import Choices
from django.utils import timezone
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.db.models.signals import post_save
from django.dispatch import receiver
# Project imports
from user_manager.models import PyrosUser
# DeviceCommand is used by class Command
sys.path.append("../../..")




"""
STYLE RULES
===========
https://simpleisbetterthancomplex.com/tips/2018/02/10/django-tip-22-designing-better-models.html
https://steelkiwi.com/blog/best-practices-working-django-models-python/

- Model name => singular
    Call it Company instead of Companies. 
    A model definition is the representation of a single object (the object in this example is a company), 
    and not a collection of companies
    The model definition is a class, so always use CapWords convention (no underscores)
    E.g. User, Permission, ContentType, etc.

- For the model’s attributes use snake_case.
    E.g. first_name, last_name, etc

- Blank and Null Fields (https://simpleisbetterthancomplex.com/tips/2016/07/25/django-tip-8-blank-or-null.html)
    - Null: It is database-related. Defines if a given database column will accept null values or not.
    - Blank: It is validation-related. It will be used during forms validation, when calling form.is_valid().
    Do not use null=True for text-based fields that are optional.
    Otherwise, you will end up having two possible values for “no data”, that is: None and an empty string.
    Having two possible values for “no data” is redundant.
    The Django convention is to use the empty string, not NULL.
    Example:
        # The default values of `null` and `blank` are `False`.
        class Person(models.Model):
            name = models.CharField(max_length=255)  # Mandatory
            bio = models.TextField(max_length=500, blank=True)  # Optional (don't put null=True)
            birth_date = models.DateField(null=True, blank=True) # Optional (here you may add null=True)
    The default values of null and blank are False.
    Special case, when you need to accept NULL values for a BooleanField, use NullBooleanField instead.

- Choices : you can use Choices from the model_utils library. Take model Article, for instance:
    from model_utils import Choices
    class Article(models.Model):
        STATUSES = Choices(
            (0, 'draft', _('draft')),
            (1, 'published', _('published'))   )
        status = models.IntegerField(choices=STATUSES, default=STATUSES.draft)

- Reverse Relationships

    - related_name :
    Rule of thumb: if you are not sure what would be the related_name, 
    use the plural of the model holding the ForeignKey.
    ex:
        class Company:
            name = models.CharField(max_length=30)
        class Employee:
            first_name = models.CharField(max_length=30)
            last_name = models.CharField(max_length=30)
            company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='employees')
    usage:
        google = Company.objects.get(name='Google')
        google.employees.all()
        You can also use the reverse relationship to modify the company field on the Employee instances:
        vitor = Employee.objects.get(first_name='Vitor')
        google = Company.objects.get(name='Google')
        google.employees.add(vitor)

    - related_query_name :
        This kind of relationship also applies to query filters. 
        For example, if I wanted to list all companies that employs people named ‘Vitor’, I could do the following:
        companies = Company.objects.filter(employee__first_name='Vitor')
        If you want to customize the name of this relationship, here is how we do it:
            class Employee:
                first_name = models.CharField(max_length=30)
                last_name = models.CharField(max_length=30)
                company = models.ForeignKey(
                    Company,
                    on_delete=models.CASCADE,
                    related_name='employees',
                    related_query_name='person'
                )
        Then the usage would be:
        companies = Company.objects.filter(person__first_name='Vitor')

    To use it consistently, related_name goes as plural and related_query_name goes as singular.


GENERAL EXAMPLE
=======

from django.db import models
from django.urls import reverse

class Company(models.Model):
    # CHOICES
    PUBLIC_LIMITED_COMPANY = 'PLC'
    PRIVATE_COMPANY_LIMITED = 'LTD'
    LIMITED_LIABILITY_PARTNERSHIP = 'LLP'
    COMPANY_TYPE_CHOICES = (
        (PUBLIC_LIMITED_COMPANY, 'Public limited company'),
        (PRIVATE_COMPANY_LIMITED, 'Private company limited by shares'),
        (LIMITED_LIABILITY_PARTNERSHIP, 'Limited liability partnership'),
    )

    # DATABASE FIELDS
    name = models.CharField('name', max_length=30)
    vat_identification_number = models.CharField('VAT', max_length=20)
    company_type = models.CharField('type', max_length=3, choices=COMPANY_TYPE_CHOICES)

    # MANAGERS
    objects = models.Manager()
    limited_companies = LimitedCompanyManager()

    # META CLASS
    class Meta:
        verbose_name = 'company'
        verbose_name_plural = 'companies'

    # TO STRING METHOD
    def __str__(self):
        return self.name

    # SAVE METHOD
    def save(self, *args, **kwargs):
        do_something()
        super().save(*args, **kwargs)  # Call the "real" save() method.
        do_something_else()

    # ABSOLUTE URL METHOD
    def get_absolute_url(self):
        return reverse('company_details', kwargs={'pk': self.id})

    # OTHER METHODS
    def process_invoices(self):
        do_something()

"""


# ---
# --- Utility functions
# ---

def printd(*args, **kwargs):
    if os.environ.get('PYROS_DEBUG', '0') == '1':
        print('(MODEL)', *args, **kwargs)

'''
def get_or_create_unique_row_from_model(model: models.Model):
    # return model.objects.get(id=1) if model.objects.exists() else model.objects.create(id=1)
    return model.objects.first() if model.objects.exists() else model.objects.create(id=1)
'''





"""
------------------------
   BASE MODEL CLASSES
------------------------
"""

"""
------------------------
   OTHER MODEL CLASSES
------------------------
"""

class AgentLogs(models.Model):
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    name = models.CharField(max_length=50)
    message = models.TextField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'agent_logs'

    def __str__(self):
        return (f"{self.created} {self.name} {self.message}")


class AgentSurvey(models.Model):
    """
    | id | name | created | updated | validity_duration (default=1mn) | mode (active/idle) | status (launch/init/loop/exit/...) |
    """

    # --- MODES ---
    '''
    In all modes, the Agent listens to commands sent to him and executes Agent level GENERAL ones.
    - MODE_IDLE : "idle" mode, does nothing, only executes Agent level GENERAL commands (DO_RESTART, DO_EXIT, DO_ABORT, DO_FLUSH, SET_ACTIVE, ...)
    - MODE_ROUTINE : idem IDLE + executes routine process (before & after)
    - MODE_ATTENTIVE : idem ROUTINE + executes Agent level SPECIFIC commands (commands specific to this agent, that only this agent understands and can execute)
    Default mode is MODE_ATTENTIVE (most active mode)
    '''
    MODE_CHOICES = Choices(
        "IDLE",  
        "ROUTINE",  
        "ATTENTIVE",
    )

    # --- STATUSES ---
    ''' Agent steps '''
    STATUS_CHOICES = Choices(
        'LAUNCHED',
        'INITIALIZING',
        'IN_MAIN_LOOP_START',
        'IN_MAIN_LOOP_ROUTINE_ITER_START',
        'IN_MAIN_LOOP_GET_NEXT_CMD',
        'IN_MAIN_LOOP_ROUTINE_ITER_END',
        'EXITING',      # STOP or HARD restart
        'RESTARTING',   # SOFT restart
    )

    name = models.CharField(max_length=50, unique=True)
    #name = models.CharField(max_length=50, blank=True, null=True, unique=True)
    #created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    validity_duration = models.PositiveIntegerField(default=90)
    #validity_duration = models.DurationField(default=90)
    mode = models.CharField('agent mode', max_length=15,
                            blank=True, choices=MODE_CHOICES,
                            #default = MODE_CHOICES.ATTENTIVE
    )
    status = models.CharField(
        max_length=40, blank=True, choices=STATUS_CHOICES)
    iteration = models.IntegerField(blank=True, null=True)
    nb_restart_max = models.IntegerField(blank=True,null=True,default=3)
    current_nb_restart = models.IntegerField(blank=True,null=True,default=0)
    class Meta:
        managed = True
        db_table = 'agent_survey'
        #verbose_name = "agent survey"
        #verbose_name_plural = "agents survey"

    def __str__(self):
        return (f"Agent {self.name} at {self.updated} in mode {self.mode} and status {self.status}")

    # Testing agent status
    
    def is_launched(self): return self.status == self.STATUS_CHOICES.LAUNCHED
    def is_initializing(self): return self.status == self.STATUS_CHOICES.INITIALIZING
    
    def is_in_main_loop_start(self): return self.status == self.STATUS_CHOICES.IN_MAIN_LOOP
    def is_in_routine_bef(self): return self.status == self.STATUS_CHOICES.IN_ROUTINE_BEF
    def is_in_get_next_cmd(self): return self.status == self.STATUS_CHOICES.IN_GET_NEXT_CMD
    def is_in_routine_aft(self): return self.status == self.STATUS_CHOICES.IN_ROUTINE_AFT
    def is_in_main_loop(self): 
        return self.is_in_main_loop_start() or self.is_in_routine_bef() or self.is_in_get_next_cmd() or self.is_in_routine_aft()
    
    def is_stopping(self): return self.status == self.STATUS_CHOICES.EXITING
    def is_restarting(self): return self.status == self.STATUS_CHOICES.RESTARTING
    def is_stopping_or_restarting(self): return self.is_stopping() or self.is_restarting()




class AgentCmd(models.Model):
    """
    Command sent to an Agent

    Can be either :
    - an "agent level" (general or specific) command
    OR
    - a "device level" command

    | id | sender | recipient | name | validity_duration (default=60) | s_deposit_time | r_read_time

    See doc/models_Command_state_diag.pu for PlantUML state diagram
    """


    ###
    # =================================================================
    #    EXCEPTIONS classes
    # =================================================================
    ###

    class CmdException(Exception):
        ''' Base class for all Agent command exceptions '''
        # pass
        def __init__( self, cmd:Union[AgentCmd,str], msg:str=None):
            self.cmd = cmd
            self._msg = msg
            self.cmd_name = cmd if isinstance(cmd,str) else cmd.name
        @property
        def msg(self):
            msg = "EXCEPTION on command "+self.cmd_name
            return msg if not self._msg else msg+': '+self._msg
        # Default message if print exception
        def __str__(self):
            return self.msg
            '''
            msg = "EXCEPTION on command "+self.cmd_name
            return msg if not self.msg else msg+': '+self.msg
            '''
        '''
        def __str__(self):
            return f"The Agent command '{self.cmd.name}' is unknown to the agent"
            #return f"({type(self).__name__}): Device Generic command has no implementation in the controller"
        '''

    # --- CMD PENDING (non running) EXCEPTIONS ---

    # @Override
    class CmdExceptionUnknown(CmdException):
        ''' Raised when a PENDING (non running) Agent (specific) cmd is NOT known by the agent '''
        # @Override
        def __init__( self, cmd, msg:str=None):
            super().__init__(cmd, msg if msg else "Unknown command")
        #def __str__(self): return self.msg if self.msg else f"The Agent command '{self.cmd_name}' is unknown to the agent"

    # @Override
    class CmdExceptionUnimplemented(CmdException):
        ''' Raised when a PENDING (non running) Agent Specific cmd is known by the agent but not implemented '''
        # @Override
        def __init__( self, cmd, msg:str=None):
            super().__init__(cmd, msg if msg else "Command is known by the agent but not implemented")
        #def __str__(self): return f"The Agent command '{self.cmd_name}' is known by the agent but not implemented"

    # @Override
    class CmdExceptionBadArgs(CmdException):
        ''' Raised when a PENDING (non running) Agent cmd has bad, missing, or too many argument(s) '''
        # @Override
        def __init__( self, cmd, msg:str=None):
            super().__init__(cmd, msg if msg else "Command has bad, missing, or too many argument(s)")
        #def __str__(self): return f"The Agent command '{self.cmd_name}' has bad, missing, or too many argument(s)"


    # --- CMD RUNNING EXCEPTIONS ---

    # @Override
    class CmdExceptionExecError(CmdException):
        ''' Raised when a RUNNING Agent cmd has had a running error  '''
        # @Override
        def __init__( self, cmd, msg:str=None):
            super().__init__(cmd, msg if msg else "Error during Execution")
        #def __str__(self): return f"The running Agent command '{self.cmd_name}' has had an error (during execution)"

    # @Override
    class CmdExceptionExecTimeout(CmdException):
        ''' Raised when a RUNNING Agent cmd is timeout  '''
        # @Override
        def __init__( self, cmd, msg:str=None):
            super().__init__(cmd, msg if msg else "Execution is TIMEOUT")
        #def __str__(self): return f"The running Agent command '{self.cmd_name}' is timeout"

    # @Override
    class CmdExceptionExecKilled(CmdException):
        ''' Raised when a RUNNING Agent cmd has been aborted (by another agent)  '''
        # @Override
        def __init__( self, cmd, msg:str=None):
            super().__init__(cmd, msg if msg else "Command was KILLED during Execution (by another agent")
        #def __str__(self): return f"The running Agent command '{self.cmd_name}' has been killed (by another agent)"



    # -------------- Command CONSTANTS --------------

    # Command status codes
    CMD_STATUS_CODES = Choices(
        
        # Cmd is pending, waiting for execution
        "CMD_PENDING",  


        ### 1 - ERRORS BEFORE EVEN BEING RUN ###

        # Cmd is invalid (unknown or bad args)
        "CMD_INVALID",

        # Cmd is not yet implemented (by recipient agent)
        "CMD_UNIMPLEMENTED",

        # Cmd was skipped (not run, because the agent is IDLE (or in a mode which does not allow execution of this command)
        "CMD_SKIPPED",

        # Cmd is out of date (expired)
        # because it has been pending for too long
        #"CMD_OUTOFDATE",
        "CMD_EXPIRED",


        ### 2 - RUNNING ###
        # Cmd is running (after having been "read")
        "CMD_RUNNING",  


        ### 3 - ERRORS WHILE RUNNING ###

        # - Cmd was run and finished ok 
        # ( simulé par un sleep(3) dans AgentX.core_process() )
        "CMD_EXECUTED",

        # - Cmd was running, but then an error occured
        "CMD_EXEC_ERROR",  

        # - Cmd was running, but took too much time and timeout was reached
        "CMD_EXEC_TIMEOUT",  

        # - Cmd was aborted, killed by another agent
        #"CMD_KILLED",
        "CMD_EXEC_KILLED",

    )

    # Command default validity duration (from sending time) BEFORE execution, before being perempted (in sec)
    # => Each command validity can be set by SENDER when sending command, it will then be managed by RECIPIENT
    # => From the time a command was sent (cmd.s_deposit_time), it is still valid during DEFAULT_VALIDITY_DURATION sec.
    # => After that, it is considered as "expired" (obsolete) and must be marked as "CMD_OUTOFDATE" and not be executed anymore (and can be purged)
    # => Thus, a command is expired FROM time = s_deposit_time + VALIDITY_DURATION
    # (except if it is RUNNING, i.e. in state CMD_RUNNING)
    DEFAULT_VALIDITY_DURATION = 1 * 3600 # s

    # Command default execution timeout (in sec)
    # => Each command timeout is set by RECIPIENT (in AGENT_SPECIFIC_COMMANDS), and it will be managed by RECIPIENT
    # => Execution of a command MUST NOT last more than EXEC_TIMEOUT seconds (from execution start time cmd.r_start_time)
    # => Otherwise the (recipient) agent executing the command is responsible to abort it and mark it as "CMD_KILLED"
    DEFAULT_EXEC_TIMEOUT = 60 # s

    # -------------- Command FIELDS --------------

    #sender = models.CharField(max_length=50, blank=True, null=True, unique=True)
    # Sender and Recipient agents
    sender = models.CharField(max_length=50, help_text='sender agent name', null=False)
    recipient = models.CharField(max_length=50, help_text='recipient agent name', null=False)
    ##name = models.CharField(max_length=400, help_text='command name', null=False)
    full_name = models.CharField(max_length=400, help_text='command full name (with type and args)', null=False)
    
    validity_duration = models.PositiveIntegerField('(in sec)', default=DEFAULT_VALIDITY_DURATION)
    exec_timeout = models.PositiveIntegerField('(in sec)', default=DEFAULT_EXEC_TIMEOUT)
    
    #state = models.CharField(choices = CMD_STATUS_CODES, default=CMD_STATUS_CODES.CMD_PENDING, max_length=20)
    state = models.CharField(choices=CMD_STATUS_CODES, default=CMD_STATUS_CODES.CMD_PENDING, max_length=20)
    #state = models.IntegerField(choices=CMD_STATUS_CODES, default=RSCODE_PENDING)
    
    # TODO: maybe à mettre au format json (key:value)
    ##result = models.CharField(max_length=1000, blank=True)
    result = models.TextField(blank=True, null=False)

    # - on creation: (AUTO) Automatically set at table line creation (line created by the sender)
    s_deposit_time = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    # - on reading:
    r_read_time = models.DateTimeField(null=True)
    # - on launching:
    r_start_time = models.DateTimeField(null=True)
    # - on end (after execution started or not)
    #end_time = models.DateTimeField(null=True)
    r_end_time = models.DateTimeField(null=True)

    # Other agent (than sender or recipient) that set this command to KILLED or EXPIRED
    killer_agent_name = models.CharField(max_length=50, help_text='sender agent name', null=True)

    # Intern field, not saved in DB
    _device_command = None

    class Meta:
        managed = True
        db_table = 'command'
        #verbose_name = "agent survey"
        #verbose_name_plural = "agents survey"

    _AGENT_GENERAL_COMMANDS = [
        
        # DO commands
        # -----------
        
        # - Evaluate the expression given (ex: do_eval 4+3)
        "do_eval",
                
        # GET commands
        # ------------

        # - Get agent current STATUS or STEP (IN_MAIN_LOOP, ...)
        "get_status",
        
        # - Get mode + status + iteration num
        "get_state",
        
        # - Get agent current MODE (idle, routine, attentive)
        "get_mode",
        
        # SET commands
        # -----------

        # - Set agent current STATE (IN_MAIN_LOOP, ...) => forbidden
        #"set_state",
        
        # - Set agent current MODE (idle, routine, attentive)
        ##"set_current_mode", # + value to set
        "set_mode", # + value to set

        
        # -----------
        # ### (PRIORITY) DO Commands => executed in priority (even if other pending commands exist) ###
        # -----------
        
        # - Finish your current command and then make a normal clean stop
        # ARGS (optional) :
        #   - "asap" (default) (wait for agent to finish its current processing, then exit)
        #   - "now" (abort agent current processing + exit)
        #   - "noprio" (not priority) (priority by default)
        "do_stop",
        # TODO: a virer => do_stop asap
        # @deprecated
        ##"do_exit",
        # TODO: a virer => do_stop now
        # @deprecated
        ##"do_abort",

        #FIXME: à implémenter
        # - 
        # ARGS :
        #   - "stop" : Temporaly stop execution of new commands (let them accumulate)
        #   - "resume" : Resume execution of commands (accumulated since "do_exec_commands stop")
        #   - "noprio" : not priority (by default => priority)        
        "do_exec_commands",

        # - Stop currently running command or/and routine
        # ARGS :
        #   - "cmd" : stop currently running specific command
        #   - "routine" : stop currently running routine process
        #   - "both" (default) : stop currently running current cmd and routine process
        "do_stop_current", # + arg "cmd" or "routine"
        # TODO: a virer => do_stop_current now
        # @deprecated
        ##"do_abort_current_command",
        
        # - Delete all your pending commands
        "do_flush_pending_commands", 
        # @deprecated
        ##"do_flush_commands", 
        
        # - Restart your global loop (starting with init())
        # ARGS (optional) :
        #   - "asap" (default) (wait for agent to finish its current processing, then restart loop)
        #   - "now" (abort agent current processing + restart loop)
        #   - "noprio" (not priority, priority by default)
        "do_restart", # + arg "asap" (default) or "now"

        "get_all_cmds",
        # @deprecated
        "get_specific_cmds",

    ]

    # Priority commands, executed as soon as in the received commands list (BEFORE any other pending command)
    # NB : must be a subset of _AGENT_GENERAL_COMMANDS
    _AGENT_GENERAL_PRIORITY_COMMANDS = [
        
        # 1 - NO STOP commands => will not stop the Agent or any running cmd
        "get_all_cmds",
        # @deprecated
        "get_specific_cmds",
        "do_flush_pending_commands", 
        "do_exec_commands"
        
        # 2 - PARTIAL STOP command => will just stop current running cmd (and routine)
        "do_stop_current",
        
        # 3 - (TOTAL) STOP commands => will stop the Agent (waiting or not for it to finish what it is doing)
        #"do_exit",
        "do_stop",
        "do_restart",
        # @deprecated
        ###"do_restart_loop",
    ]

    # -------------- Command CLASS (static) METHODS --------------

    @staticmethod
    def is_generic_name(cmd_name:str)->bool:
        '''
        Generic if starts with get_, set_, or do_
        '''
        return cmd_name.startswith( ('get_', 'set_', 'do_') )

    # Avoid to override the Model __init__ method
    # See https://docs.djangoproject.com/en/stable/ref/models/instances/#creating-objects
    @classmethod
    def create(cls, agent_from:str, agent_to:str, cmd_name:str, cmd_args:str=None, cmd_validity:int=None) -> AgentCmd :
        #print(agent_to)
        if '.' in agent_to:
            agent_to, component_name = agent_to.split('.')
            cmd_name = component_name+'.'+cmd_name
        # remove all excessive spaces
        print(cmd_args)
        if cmd_args:
            cmd_args = re.sub(r"\s+", " ", cmd_args).strip()
            cmd_name += ' ' + cmd_args
        # cls._device_command=DeviceCommand(cmd_name)
        if cmd_validity is None: cmd_validity = cls.DEFAULT_VALIDITY_DURATION
        #if cmd_timeout is None: cmd_timeout = cls.DEFAULT_EXEC_TIMEOUT
        return cls(
            sender=agent_from,
            recipient=agent_to,
            full_name=cmd_name,
            validity_duration=cmd_validity,
            #exec_timeout=cmd_timeout,
        )

    """
    @classmethod
    def send(cls, cmd:Command):
        cls.objects.create(sender=cmd.name, recipient=cmd.recipient, name=cmd.name)
    """

    @classmethod
    def send_cmd_from_to(cls, agent_from, agent_to, cmd_name, cmd_args=None, cmd_validity:int=None)->AgentCmd:
        """ Create and send a command, then return it """
        # def send(cls, from_agent, to_agent, cmd_name, cmd_args=None):
        """
        ex: send("AgentA",“AgentB”,"EVAL”,“3+4”)
        """
        '''
        if cmd_args: cmd_name += ' '+cmd_args
        #Command.objects.create(sender=self.name, recipient=r_agent, name=cmd_name)
        cmd = cls(sender=from_agent, recipient=to_agent, name=cmd_name)
        '''
        cmd = cls.create(agent_from, agent_to, cmd_name, cmd_args, cmd_validity)
        cmd.send()
        # cmd.set_as_pending()
        # cmd.save()
        return cmd

    @classmethod
    def max_deposit_date_for_peremption(cls):
        return datetime.now(tz=timezone.utc) - timedelta(seconds=cls.DEFAULT_VALIDITY_DURATION)
        #return datetime.utcnow().astimezone() - timedelta(seconds=cls.DEFAULT_VALIDITY_DURATION)
        #return datetime.utcnow().astimezone() - timedelta(hours=cls.DEFAULT_VALIDITY_DURATION)

    @classmethod
    #def delete_commands_with_running_status_for_agent(cls, agent_name):
    def kill_false_running_cmd_if_exists_for_agent(cls, agent_name):
        #FIXME: check that this command is not REALLY running (ex: cmd sent to device), and if so, kill it (or let it finish ?)
        printd("Kill (false) 'running' command if exists:")
        running_commands = cls.objects.filter(
            # only commands for agent agent_name
            recipient=agent_name,
            # only running commands
            state=cls.CMD_STATUS_CODES.CMD_RUNNING,
            # only not expired commands
            #s_deposit_time__gte = cls.max_deposit_date_for_peremption(),
        )
        if running_commands:
            #AgentCmd.show_commands(running_commands)
            cls.show_commands(running_commands)
            #running_commands.delete()
            for cmd in running_commands:
                cmd.set_as_pending()
                cmd.set_as_skipped("Skip this cmd because false running cmd (at agent start)")
        else:
            printd("<None>")

    @classmethod
    def delete_pending_commands_for_agent(cls, agent_name):
        """
        Delete all pending commands sent to agent_name,
        except very recent commands.
        This (exception) is to avoid a "data race" where for example agentB is executing a "flush" command 
        while agentA is sending command to agentB... :
        - agentB will then delete the command just sent by agentA
        - agentA will check regularly the status of its sent command, and this will crash as this command exists no more !!
        """
        printd("Delete all pending command(s) if exists (except very recent ones, less than 2 sec ago):")
        #now_minus_2sec = datetime.utcnow().astimezone() - timedelta(seconds=2)
        now_minus_2sec = datetime.now(tz=timezone.utc) - timedelta(seconds=2)
        #print("now_minus_2sec", now_minus_2sec)
        pending_commands = cls.objects.filter(
            # only commands for agent agent_name
            recipient=agent_name,
            # only running commands
            state=cls.CMD_STATUS_CODES.CMD_PENDING,
            # except very recent commands : take only commands that are more than 2 sec old
            s_deposit_time__lt=now_minus_2sec
        )
        if pending_commands:
            AgentCmd.show_commands(pending_commands)
            pending_commands.delete()
        else:
            printd("<None>")

    @classmethod
    def get_pending_commands_for_agent(cls, agent_name)->QuerySet:
        #print("peremption date", COMMAND_PEREMPTION_DATE_FROM_NOW)
        return cls.objects.filter(
            # only pending commands
            state=cls.CMD_STATUS_CODES.CMD_PENDING,
            # only commands for agent agent_name
            recipient=agent_name,
            # recipient__startswith=agent_name,
            # Q(recipient.split('.')[0] = agent_name),
            # only not expired commands
            #s_deposit_time__gte = cls.max_deposit_date_for_peremption(),
        ).order_by("s_deposit_time")

    @classmethod
    def get_pending_and_running_commands_for_agent(cls, agent_name)->QuerySet:
        #print("peremption date", COMMAND_PEREMPTION_DATE_FROM_NOW)
        return cls.objects.filter(
            # only pending or running commands
            Q(state=cls.CMD_STATUS_CODES.CMD_PENDING) | Q(state=cls.CMD_STATUS_CODES.CMD_RUNNING),
            # only commands for agent agent_name
            recipient=agent_name,
            # recipient__startswith=agent_name,
            # Q(recipient.split('.')[0] = agent_name),
            # only not expired commands
            #s_deposit_time__gte = cls.max_deposit_date_for_peremption(),
        ).order_by("s_deposit_time")

    @classmethod
    def get_commands_sent_to_agent(cls, agent_name):
        return cls.objects.filter(recipient=agent_name)

    @classmethod
    def get_commands_sent_by_agent(cls, agent_name):
        return cls.objects.filter(sender=agent_name)

    @classmethod
    def get_last_N_commands_sent_to_agent(cls, agent_name, N):
        # filter(since=since)
        # return cls.objects.all()[:nb_cmds]
        #commands = cls.objects.filter(recipient = agent_name).order_by('-id')[:N]
        commands = cls.get_commands_sent_to_agent(
            agent_name).order_by('-id')[:N]
        return list(reversed(commands))

    @classmethod
    def get_last_N_commands_sent_by_agent(cls, agent_name, N):
        # filter(since=since)
        # return cls.objects.all()[:nb_cmds]
        #commands = cls.objects.filter(recipient = agent_name).order_by('-id')[:N]
        commands = cls.get_commands_sent_by_agent(
            agent_name).order_by('-id')[:N]
        return list(reversed(commands))

    @classmethod
    def purge_old_commands_sent_to_agent(cls, agent_name):
        """
        Delete commands (which agent_name is recipient of) older than VALIDITY_DURATION (like 1h)
        ATTENTION !!! EXCEPT the RUNNING command !!!
        NB: datetime.utcnow() is equivalent to datetime.now(timezone.utc)
        """
        printd(
            f"(Looking for commands sent to me that are not executing and perempted - i.e. older than {cls.DEFAULT_VALIDITY_DURATION/60} minute(s))")
        #COMMAND_PEREMPTION_DATE_FROM_NOW = datetime.utcnow() - timedelta(hours = cls.COMMANDS_PEREMPTION_HOURS)
        #print("peremption date", COMMAND_PEREMPTION_DATE_FROM_NOW)
        old_commands = cls.objects.filter(
            # only commands for agent agent_name
            recipient=agent_name,
            # only expired commands
            s_deposit_time__lt=cls.max_deposit_date_for_peremption(),
        ).exclude(
            state=cls.CMD_STATUS_CODES.CMD_RUNNING
        )
        if old_commands.exists():
            printd("Found old commands to delete:")
            #for cmd in old_commands: print(cmd)
            cls.show_commands(old_commands)
            old_commands.delete()
        else:
            printd("<None>")

    @staticmethod
    # def show_commands(cls, commands:models.query):
    def show_commands(commands, do_it: bool = False):
        # def show_commands(cls, commands:List[Commmand]):
        #if not commands.exists(): print("<No command>")
        commands = list(commands)
        if len(commands) == 0:
            print("<None>")
            #if do_it: print("<None>")
            #else: printd("<None>")
        for cmd in commands:
            print("-", cmd.name, cmd)
            #if do_it: print("-", cmd.name, cmd)
            #else: printd("-", cmd.name, cmd)

    # -------------- AgentCmd INSTANCE METHODS --------------

    def __str__(self):
        # return (f"Commmand '{self.name}' ({self.state}) sent by agent {self.sender} to agent {self.recipient} at {self.s_deposit_time}")
        cmd_sent_time = f" at {self.s_deposit_time}" if self.s_deposit_time else ''
        return (f"Commmand '{self.full_name}' ({self.state}) sent to agent {self.recipient}{cmd_sent_time} (validity={self.validity_duration}s,timeout={self.exec_timeout}s) [by agent {self.sender}]")

    @property
    def device_command(self) -> DeviceCmd :
        if not self._device_command:
            self._device_command = DeviceCmd(self.full_name)
            #dc = self._device_command
            #print("...DEVICE CMD:", dc.full_name, dc.name, dc.devtype, dc.args)
        return self._device_command

    @property
    #def name_and_args(self) -> Tuple[str, str] :
    def name_and_args(self) -> Tuple[str, List] :
        ###return self.device_command.name_and_args
        '''
        cmd_name_and_args = self.full_name
        if '.' in cmd_name_and_args:
            cmd_name_and_args = cmd_name_and_args.split('.')[1]
        return cmd_name_and_args
        '''
        ''' Return command name and args if exist '''
        # By default, no args
        #cmd_args = None
        cmd_args = []
        '''
        cmd_name = self.full_name
        if ' ' in cmd_name:
        '''
        cmd_name, *cmd_args = self.full_name.split(' ')
        return cmd_name, cmd_args


    #def get_full_name_parts(self) -> list :
    def get_full_name_parts(self) -> Tuple[str, str, str] :
        ''' Return command device type, name, and args from any command type (agent or device level) '''

        # No device type by default for an Agent command
        # cmd_type ?
        dev_type = None
        
        # By default, no args
        cmd_args = None

        cmd_name = self.full_name
        
        # Device command with device component type (dev_type)
        if '.' in cmd_name: 
            return self.device_command.get_full_name_parts()

        # Simple command with args (no dev_type)
        if ' ' in cmd_name:
            cmd_name, *cmd_args = self.name_and_args

        return dev_type, cmd_name, cmd_args


    @property
    def name(self):
        ###return self.device_command.name
        #_,cmd_name,_ = self.get_full_name_parts()
        cmd_name,_ = self.name_and_args
        return cmd_name

    @property
    def args(self):
        ###return self.device_command.args
        #_,_,cmd_args = self.get_full_name_parts()
        _,cmd_args = self.name_and_args
        return cmd_args

    @property
    def device_type(self): return self.device_command.devtype

    def send(self):
        # self.save()
        self.set_as_pending()

    '''
    def tokenize(self):
        cmd_name, *cmd_args = self.full_name.split(' ')
        return cmd_name, cmd_args
    '''

    # --- BOOLEAN (test) functions ---

    def is_generic(self)->bool:
        '''
        Generic if starts with get_, set_, or do_
        '''
        return self.is_generic_name(self.name)

    def is_agent_general_cmd(self)->bool:
        """
        Is this a general command ?
        It is the case if command is of style "do_set:state:idle" or "do_restart" or "do_flush"...
        """
        ##name = self.name
        ##if " " in name: name,args = name.split()
        ##name = self.name.split(' ')[0]
        ##cmd_name, _ = self.tokenize()
        # return cmd_name in self.GENERIC_COMMANDS
        #print("**********************CMD NAME is", self.name, "in ???", self._AGENT_GENERAL_COMMANDS)
        return self.name in self._AGENT_GENERAL_COMMANDS
        # "CMD_OUTOFDATE" # cde périmée

    def is_agent_general_priority_cmd_name(self)->bool:
        return self.name in self._AGENT_GENERAL_PRIORITY_COMMANDS

    def is_agent_general_priority_cmd(self)->bool:
        #return AgentCmd._is_agent_general_priority_cmd(self.name)
        #return self.__class__._is_agent_general_priority_cmd(self.name)
        #return type(self)._is_agent_general_priority_cmd(self.name)
        #return type(self)._is_agent_general_priority_cmd(self.full_name)
        return type(self)._is_agent_general_priority_cmd(self.name, self.args)

    @classmethod
    #def _is_agent_general_priority_cmd(cls, cmd_name_and_args=[])->bool:
    def _is_agent_general_priority_cmd(cls, cmd_name, cmd_args=[])->bool:
        #print(cmd_name_and_args)
        #cmd_name, cmd_args = re.sub(r"\s+", " ", cmd_name_and_args).strip().split(' ')
        #print(cmd_name, cmd_args)
        if cmd_name not in cls._AGENT_GENERAL_PRIORITY_COMMANDS: return False
        if cmd_args and cmd_args[0] == 'noprio': return False
        #return cmd_name in cls._AGENT_GENERAL_PRIORITY_COMMANDS and cmd_args and cmd_args[0] != 'noprio'
        return True


    def is_read(self)->bool:
        return self.r_read_time is not None

    #
    # CMD status management
    #

    def get_status(self):
        return self.state

    # 1 - pending
    def is_pending(self):
        return self.state == self.CMD_STATUS_CODES.CMD_PENDING

    # 2 - ERROR cases (from PENDING)
    def is_invalid(self): return self.state == self.CMD_STATUS_CODES.CMD_INVALID
    def is_unimplemented(self): return self.state == self.CMD_STATUS_CODES.CMD_UNIMPLEMENTED
    def is_skipped(self): return self.state == self.CMD_STATUS_CODES.CMD_SKIPPED
    def is_expired(self):
        if self.state == self.CMD_STATUS_CODES.CMD_EXPIRED: return True
        # Must NOT be running
        if self.is_running(): return False
        # return (datetime.utcnow() - self.s_deposit_time) > timedelta(seconds = self.validity_duration)
        #elapsed_time = (datetime.utcnow().astimezone() - self.s_deposit_time)
        elapsed_time = ( datetime.now(tz=timezone.utc) - self.s_deposit_time )
        printd("elapsed_time", elapsed_time)
        return elapsed_time > timedelta(seconds=self.validity_duration)
        """
        elapsed_time = cmd.r_read_time - cmd.s_deposit_time
        max_time = timedelta(seconds = cmd.validity_duration)
        print(f"Elapsed time is {elapsed_time}, (max is {max_time})")
        if elapsed_time > max_time:
        """
    # finished with issue (from pending)
    def is_pending_issue(self): return self.is_invalid() or self.is_unimplemented() or self.is_skipped() or self.is_expired()

    # 3 - running
    def is_running(self):
        return self.state == self.CMD_STATUS_CODES.CMD_RUNNING

    # 4 - ERROR cases (from RUNNING)
    def is_exec_error(self): return self.state == self.CMD_STATUS_CODES.CMD_EXEC_ERROR
    def is_exec_killed(self): return self.state == self.CMD_STATUS_CODES.CMD_EXEC_KILLED
    # alias
    def is_killed(self): return self.is_exec_killed()
    # alias
    def is_timeout(self): return self.is_exec_timeout()
    def is_exec_timeout(self):
        if self.state == self.CMD_STATUS_CODES.CMD_EXEC_TIMEOUT: return True
        # Must be running
        if not self.is_running(): return False
        # return (datetime.utcnow() - self.s_deposit_time) > timedelta(seconds = self.validity_duration)
        #elapsed_time = (datetime.utcnow().astimezone() - self.r_start_time)
        elapsed_time = (datetime.now(tz=timezone.utc) - self.r_start_time)
        printd("elapsed_time since exec", elapsed_time)
        return elapsed_time > timedelta(seconds=self.exec_timeout)
    # finished with any execution issue
    def is_exec_issue(self): return self.state.startswith("CMD_EXEC_")

    # 5 - Execution finished
    # Cmd is finished if not pending or running
    def is_finished(self):
        return not (self.is_pending() or self.is_running())
    # Cmd is finished with error : finished but NOT executed (= ALL except : CMD_PENDING, CMD_RUNNING, or CMD_EXECUTED)
    def is_finished_with_error(self):
        return self.is_finished() and not self.is_executed()
    # Cmd is finished without error (normal case)
    def is_executed(self):
        return self.state == self.CMD_STATUS_CODES.CMD_EXECUTED



    # --- GETTERS/SETTERS functions ---

    def get_result(self):
        return self.result

    def get_updated_result(self):
        self.refresh_from_db()
        return self.result

    def set_result(self, result: str, do_save:bool=True):
        self.result = result
        if do_save: self.save()

    def set_read_time(self, do_save:bool=True):
        #self.r_read_time = datetime.utcnow().astimezone()
        self.r_read_time = datetime.now(tz=timezone.utc)
        # Optimization: update only 1 field
        if do_save: self.save(update_fields=["r_read_time"])

    #
    # Set cmd status
    #

    # - From None
    def set_as_pending(self):
        self.set_state_to(self.CMD_STATUS_CODES.CMD_PENDING)

    # - from PENDING
    def set_as_unimplemented(self, result:str=None):
        #assert self.is_pending(), "An Unimplemented Command must have been PENDING"
        self.set_state_to(self.CMD_STATUS_CODES.CMD_UNIMPLEMENTED, result=result)
    def set_as_invalid(self, result:str=None):
        #assert self.is_pending()
        self.set_state_to(self.CMD_STATUS_CODES.CMD_INVALID, result=result)
    def set_as_skipped(self, result:str=None):
        #assert self.is_pending()
        self.set_state_to(self.CMD_STATUS_CODES.CMD_SKIPPED, result=result)
    def set_as_expired(self):
        #assert self.is_pending()
        #print(f"- Set this command as expired (older than its validity duration of {self.validity_duration}s): {self}")
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXPIRED)
    def set_as_running(self):
        #FIXMD: log.info() au lieu de print()
        print('-'*6 + " STARTING COMMAND EXEC")
        #assert self.is_pending()
        printd(f"- Set command {self.name} as running")
        self.set_state_to(self.CMD_STATUS_CODES.CMD_RUNNING)

    '''
    def set_as_executed(self):
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXECUTED)
    '''
    # - from RUNNING
    def set_as_processed(self, result:str=None):
       # assert self.is_running(), "a PROCESSED command must have been RUNNING"
        printd(f"- Set command {self.name} as processed")
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXECUTED, result=result)
        # print(self)
        """
        self.state = self.CMD_STATUS_CODES.CMD_EXECUTED
        self.r_processed_time = datetime.utcnow().astimezone()
        self.save()
        """
        # Optimization: update the related fields, but does not work, why ?
        ##self.save(update_fields=["state", "r_processed_time"])
    #def set_as_outofdate(self):
    def set_as_exec_error(self, result:str=None):
        assert self.is_running()
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXEC_ERROR, result=result)
    def set_as_exec_timeout(self, result:str=None):
        assert self.is_running()
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXEC_TIMEOUT, result=result)
    def set_as_exec_timeout(self, result:str=None):
        assert self.is_running()
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXEC_TIMEOUT, result=result)
    def set_as_killed_by(self, author_agent_name:str, result:str=None):
        #assert self.is_running()
        printd(f"- Set command {self.name} as killed")
        #print(f"- Set this command as killed: {self}")
        self.set_state_to(self.CMD_STATUS_CODES.CMD_EXEC_KILLED, author_agent_name=author_agent_name, result=result)

    # General method to change state
    def set_state_to(self, status_new: str, author_agent_name: str = None, result:str=None):
        '''
        If result is present it will be set in the "result" field
        '''
        #now_time = datetime.utcnow().astimezone()
        now_time = datetime.now(tz=timezone.utc)
        
        # result can be "0" which is false...
        if result is not None: 
            self.set_result(result, False)
        
        '''
        # - Changing state to PENDING (from None)
        if status_new == self.CMD_STATUS_CODES.CMD_PENDING:
            self.s_deposit_time = now_time
        '''

        # - Changing state from PENDING
        #if status_new in (self.CMD_STATUS_CODES.CMD_RUNNING, self.CMD_STATUS_CODES.CMD_SKIPPED, self.CMD_STATUS_CODES.CMD_EXPIRED):
        if status_new in (
            # Errors cases
            self.CMD_STATUS_CODES.CMD_INVALID,
            self.CMD_STATUS_CODES.CMD_UNIMPLEMENTED,
            self.CMD_STATUS_CODES.CMD_SKIPPED, 
            self.CMD_STATUS_CODES.CMD_EXPIRED,
            # Normal case
            self.CMD_STATUS_CODES.CMD_RUNNING
        ):
            assert self.is_pending()
            # - go RUNNING => set start time
            if status_new == self.CMD_STATUS_CODES.CMD_RUNNING:
                self.r_start_time = now_time
            # - go in error => set end time
            else:
                self.r_end_time = now_time
                # EXPIRED
                if status_new == self.CMD_STATUS_CODES.CMD_EXPIRED:
                    self.killer_agent_name = author_agent_name
        
        # - Changing state from RUNNING (CMD_EXECUTED, CMD_EXEC_...)
        #elif status_new in (self.CMD_STATUS_CODES.CMD_EXECUTED, self.CMD_STATUS_CODES.CMD_EXEC_KILLED):
        elif status_new != self.CMD_STATUS_CODES.CMD_PENDING:
            assert self.is_running()
            self.r_end_time = now_time
            if status_new == self.CMD_STATUS_CODES.CMD_EXEC_KILLED:
                self.killer_agent_name = author_agent_name
        # Update command status
        self.state = status_new
        self.save()
        # Optimization, but does not work, why ?...
        # self.save(update_fields=["state"])

    # override save to use websocket
    # def save(self, *args, **kwargs):
    #     super().save(*args, **kwargs)
    #     try:
    #         if self.pk == None:
    #             action = "create"
    #         else:
    #             action = "update"
    #         agent_survey = AgentSurvey.objects.all().values_list("name",flat=True)
    #         # initialize value, there is always a sender
    #         agent_name = self.sender
    #         if self.sender in agent_survey:
    #             agent_name = self.sender 
    #             # send to agentcmd_observers group a message to execute function new_agentcmd_agent_name_instance
    #         if self.recipient in agent_survey:
    #             agent_name = self.recipient
    #         # send to agentcmd_observers group a message to execute function new_agentcmd_agent_name_instance
    #         async_to_sync(get_channel_layer().group_send)(
    #             f'agentcmd_{agent_name}_observers', {"type": f"send_agentcmd_instance","data":self.id,"action":action}
    #         )
    #     except Exception as e:
    #         print(e)

# signals decorator to trigger function after Model AgentCmd call save()
@receiver(post_save, sender=AgentCmd)
def send_agentcmd_to_websocket(sender, instance, created, **kwargs):
    agent_survey = AgentSurvey.objects.all().values_list("name",flat=True)
    if instance.sender in agent_survey:
        agent_name = instance.sender
        # send to agentcmd_observers group a message to execute function new_agentcmd_agent_name_instance
        async_to_sync(get_channel_layer().group_send)(
            f'agentcmd_{agent_name}_observers', {"type": f"send_agentcmd_instance","action":"list"}
        )
    elif instance.recipient in agent_survey:
        agent_name = instance.recipient
        # send to agentcmd_observers group a message to execute function new_agentcmd_agent_name_instance
        async_to_sync(get_channel_layer().group_send)(
            f'agentcmd_{agent_name}_observers', {"type": f"send_agentcmd_instance","action":"list"}
        )
    # if created:
    #     action = "create"
    # else:
    #     action = "update"
    # agent_survey = AgentSurvey.objects.all().values_list("name",flat=True)
    # # initialize value, there is always a sender
    # agent_name = instance.sender
    # if instance.sender in agent_survey:
    #     agent_name = selinstancef.sender 
    #     # send to agentcmd_observers group a message to execute function new_agentcmd_agent_name_instance
    # if instance.recipient in agent_survey:
    #     agent_name = instance.recipient
    # # send to agentcmd_observers group a message to execute function new_agentcmd_agent_name_instance
    # async_to_sync(get_channel_layer().group_send)(
    #     f'agentcmd_{agent_name}_observers', {"type": f"send_agentcmd_instance","data":instance.id,"action":action}
    # )


@receiver(post_save, sender=AgentSurvey)
def send_agentsurvey_to_websocket(sender, instance, created, **kwargs):
    agent_name = instance.name
    # send to agentsurvey_observers group a message to execute function new_agentcmd_agent_name_instance
    async_to_sync(get_channel_layer().group_send)(
            f'agentsurvey_{agent_name}_observers', {"type": f"send_agentsurvey_instance"}
    )
    async_to_sync(get_channel_layer().group_send)(
            f'agentsurvey_observers', {"type": f"send_agentsurvey_instance"}
    )


# TODO: OLD Config : à virer (mais utilisé dans dashboard/templatetags/tags.py)
class Config(models.Model):
    PYROS_STATE = ["Starting", "Passive", "Standby",
                   "Remote", "Startup", "Scheduler", "Closing"]

    id = models.IntegerField(default='1', primary_key=True)
    #latitude = models.FloatField(default=1)
    latitude = models.DecimalField(
        max_digits=4, decimal_places=2,
        default=1,
        validators=[
            MaxValueValidator(90),
            MinValueValidator(-90)
        ]
    )
    local_time_zone = models.FloatField(default=1)
    #longitude = models.FloatField(default=1)
    longitude = models.DecimalField(
        max_digits=5, decimal_places=2,
        default=1,
        validators=[
            MaxValueValidator(360),
            MinValueValidator(-360)
        ]
    )
    altitude = models.FloatField(default=1)
    horizon_line = models.FloatField(default=1)
    row_data_save_frequency = models.IntegerField(default='300')
    request_frequency = models.IntegerField(default='300')
    analysed_data_save = models.IntegerField(default='300')
    telescope_ip_address = models.CharField(max_length=45, default="127.0.0.1")
    camera_ip_address = models.CharField(max_length=45, default="127.0.0.1")
    plc_ip_address = models.CharField(max_length=45, default="127.0.0.1")

    # TODO: changer ça, c'est pas clair du tout...
    # True = mode Scheduler-standby, False = mode Remote !!!!
    global_mode = models.BooleanField(default='True')

    ack = models.BooleanField(default='False')
    bypass = models.BooleanField(default='True')
    lock = models.BooleanField(default='False')
    pyros_state = models.CharField(max_length=25, default=PYROS_STATE[0])
    force_passive_mode = models.BooleanField(default='False')
    plc_timeout_seconds = models.PositiveIntegerField(default=60)
    majordome_state = models.CharField(max_length=25, default="")
    ntc = models.BooleanField(default='False')
    majordome_restarted = models.BooleanField(default='False')

    class Meta:
        managed = True
        db_table = 'config'
        verbose_name_plural = "Config"

    def __str__(self):
        return (str(self.__dict__))



class Log(models.Model):
    agent = models.CharField(max_length=45, blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    message = models.TextField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'log'

    def __str__(self):
        return (str(self.agent))


# TODO: à virer car utilisé pour Celery (ou bien à utiliser pour les agents)
'''
class TaskId(models.Model):
    task = models.CharField(max_length=45, blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    task_id = models.CharField(max_length=45, blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'task_id'

    def __str__(self):
        return (str(self.task) + " - " + str(self.task_id))
'''


class Version(models.Model):
    module_name = models.CharField(max_length=45, blank=True, null=True)
    version = models.CharField(max_length=15, blank=True, null=True)
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)

    class Meta:
        managed = True
        db_table = 'version'

    def __str__(self):
        return (str(self.module_name) + " - " + str(self.version))


class Majordome(models.Model):
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    # Software Modes
    AUTO_MODE = "AUTO"
    MANUAL_MODE = "MANUAL"
    SOFT_MODE_CHOICES = (
        (AUTO_MODE, 'Auto mode'),
        (MANUAL_MODE, 'Manual mode'),
    )
    DAY_MODE = "DAY"
    NIGHT_MODE = "NIGHT"
    OBS_MODE_CHOICES = (
        (DAY_MODE, "Day mode"),
        (NIGHT_MODE, "Night mode")
    )
    soft_mode = models.CharField(
        choices=SOFT_MODE_CHOICES,
        default=MANUAL_MODE,
        max_length=15
    )
    
    obs_mode = models.CharField(
        choices = OBS_MODE_CHOICES,
        default = DAY_MODE,
        max_length=15
    )
    class Meta:
        managed = True
        db_table = 'majordome'

    @classmethod
    def object(cls):
        return cls._default_manager.first() 

    def save(self, *args, **kwargs):
        self.pk = self.id = 1
        return super().save(*args, **kwargs)
    
class Tickets(models.Model):
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    end =  models.DateTimeField(blank=True, null=True)
    title =  models.TextField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    resolution = models.TextField(blank=True, null=True)
    pyros_user = models.ForeignKey(PyrosUser, on_delete=models.DO_NOTHING, related_name="tickets", blank=True, null=True)
    last_modified_by =  models.ForeignKey(PyrosUser, on_delete=models.DO_NOTHING, related_name="tickets_modified_by", blank=True, null=True)
    LEVEL_ONE = "ONE"
    LEVEL_TWO = "TWO"
    LEVEL_THREE = "THREE"
    LEVEL_FOUR = "FOUR"
    LEVEL_FIVE = "FIVE"
    SECURITY_LEVEL_CHOICES = (
        (LEVEL_ONE,"Warning non compromising for the operation of the system"),
        (LEVEL_TWO,"Known issue which can be solved by operating the software remotely"),
        (LEVEL_THREE,"Known issue which can be solved by an human remotely"),
        (LEVEL_FOUR,"Known issue without immediate solution"),
        (LEVEL_FIVE,"Issue not categorized until it happened")
    )
    security_level =  models.TextField(choices=SECURITY_LEVEL_CHOICES, default=LEVEL_ONE)

    class Meta:
        managed = True
        db_table = 'tickets'
        verbose_name_plural = "tickets"



#
# ENVIRONMENT MONITORING
# - External => Weather
# - Internal => Site
#

class Sensors_data_last_value(models.Model):
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    key = models.CharField(max_length=255, blank=True, null=True)
    value = models.CharField(max_length=255, blank=True, null=True)
    model = models.CharField(max_length=255, blank=True, null=True)
    serial_number = models.CharField(max_length=255, blank=True, null=True)
    monitoring_name = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'sensors_data_last_value'

class Sensors_data(models.Model):
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    key = models.CharField(max_length=255, blank=True, null=True)
    value = models.CharField(max_length=255, blank=True, null=True)
    model = models.CharField(max_length=255, blank=True, null=True)
    serial_number = models.CharField(max_length=255, blank=True, null=True)
    monitoring_name = models.CharField(max_length=255, blank=True, null=True)
    class Meta:
        managed = True
        db_table = 'sensors_data'

class Env_data(models.Model):
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    monitoring_name = models.CharField(max_length=255, blank=True, null=True)
    value = models.CharField(max_length=255, blank=True, null=True)
    label = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'Env_data'

class Env_data_hist(models.Model):
    created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    monitoring_name = models.CharField(max_length=255, blank=True, null=True)
    value = models.CharField(max_length=255, blank=True, null=True)
    label = models.CharField(max_length=255, blank=True, null=True)
    
    class Meta:
        managed = True
        db_table = 'Env_data_hist'
class SiteWatch(models.Model):
    OPEN = "OPEN"
    CLOSE = "CLOSE"
    ON = "ON"
    OFF = "OFF"

    global_status = models.CharField(max_length=255, blank=True, null=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    lights = models.CharField(max_length=45, blank=True, null=True)
    dome = models.CharField(max_length=45, blank=True, null=True)
    doors = models.CharField(max_length=45, blank=True, null=True)
    temperature = models.FloatField(blank=True, null=True)
    shutter = models.FloatField(blank=True, null=True)
    pressure = models.FloatField(blank=True, null=True)
    humidity = models.FloatField(blank=True, null=True)
    power_input = models.IntegerField(blank=True, null=True)
    
    class Meta:
        managed = True
        db_table = 'sitewatch'
        verbose_name_plural = "Site watches"

    def __str__(self):
        return (str(self.__dict__))

    # TODO
    def setGlobalStatus(self):
        self.global_status = ""
        if self.doors and self.doors.find("open") != -1:
            self.global_status += "DOOR_OPEN "
        if self.lights and self.lights == "on":
            self.global_status += "LIGHTS_ON "
        if self.temperature and float(self.temperature) > 40:
            self.global_status += "TOO_HOT "
        if self.humidity and float(self.humidity) > 80:
            self.global_status += "HUMIDITY_TOO_HIGH "
        if self.global_status == "":
            self.global_status = "OK"
        return 0

    # TODO HANDLE FLAT LAMPS ...
    def setAttribute(self, key, value):
        self.doors = ""
        if key == "InsideHumidity":
            self.humidity = value
        elif key == "Pressure":
            self.pressure = value
        elif key == "InsideTemp":
            self.temperature = value
        elif key == "Roof_state":
            self.dome = value
        elif key == "Power_input":
            self.power_input = value
        else:
            return 1
        return 0

class SiteWatchHistory(models.Model):
    id = models.IntegerField(primary_key=True)

    class Meta:
        managed = True
        db_table = 'sitewatchhistory'
        verbose_name_plural = "Site watch histories"


class WeatherWatch(models.Model):
    WIND_LIMIT = 100
    RAIN_LIMIT = 5

    global_status = models.CharField(max_length=255, blank=True, null=True)
    updated = models.DateTimeField(blank=True, null=True, auto_now=True)
    humidity = models.FloatField(blank=True, null=True)
    wind = models.FloatField(blank=True, null=True)
    wind_dir = models.CharField(max_length=45, blank=True, null=True)
    temperature = models.FloatField(blank=True, null=True)
    pressure = models.FloatField(blank=True, null=True)
    rain = models.FloatField(blank=True, null=True)
    cloud = models.FloatField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'weatherwatch'
        verbose_name_plural = "Weather watches"

    def __str__(self):
        return (str(self.__dict__))

    # TODO
    def setGlobalStatus(self):
        # print(self.rain)
        self.global_status = ""
        if self.rain and float(self.rain) > 0:
            self.global_status += "RAINING "
        if self.wind and float(self.wind) > 80:
            self.global_status += "WIND_TOO_STRONG "
        if self.humidity and float(self.humidity) > 80:
            self.global_status += "HUMIDITY_TOO_HIGH "
        if self.cloud and float(self.cloud) > 10:
            self.global_status += "TOO_MUCH_CLOUDY "
        if self.global_status == "":
            self.global_status = "OK"
        return 0

    def setAttribute(self, key, value):
        if key == "Rain_boolean":
            self.rain = value
        elif key == "_CloudRate":
            self.cloud = value
        elif key == "Wind_speed":
            self.wind = value
        elif key == "Wind_direction":
            self.wind_dir = value
        elif key == "Temperature_outside":
            self.temperature = value
        elif key == "Humidity_outside":
            self.humidity = value
        elif key == "_Pressure":
            self.pressure = value
        else:
            return 1
        return 0


class WeatherWatchHistory(models.Model):
    weather = models.ForeignKey('WeatherWatch', on_delete=models.DO_NOTHING, related_name="weatherhistory", null=True, blank=True)
    datetime = models.DateTimeField(blank=True, null=True, auto_now_add=True)
    humid_int = models.FloatField(blank=True, null=True)
    humid_ext = models.CharField(max_length=45, blank=True, null=True)
    wind = models.CharField(max_length=45, blank=True, null=True)
    wind_dir = models.CharField(max_length=45, blank=True, null=True)
    temp_int = models.CharField(max_length=45, blank=True, null=True)
    temp_ext = models.CharField(max_length=45, blank=True, null=True)
    pressure = models.CharField(max_length=45, blank=True, null=True)
    rain = models.CharField(max_length=45, blank=True, null=True)
    dwn = models.CharField(max_length=45, blank=True, null=True)

    humidity = models.FloatField(blank=True, null=True)
    wind = models.FloatField(blank=True, null=True)
    wind_dir = models.CharField(max_length=45, blank=True, null=True)
    temperature = models.FloatField(blank=True, null=True)
    cloud = models.FloatField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'weatherwatchhistory'
        verbose_name_plural = "Weather watch histories"

    def __str__(self):
        return (str(self.datetime))

    def setAttribute(self, key, value):
        if key == "Rain_boolean":
            self.rain = value
        elif key == "_CloudRate":
            self.cloud = value
        elif key == "Wind_speed":
            self.wind = value
        elif key == "Wind_direction":
            self.wind_dir = value
        elif key == "Temperature_outside":
            self.temperature = value
        elif key == "Humidity_outside":
            self.humidity = value
        elif key == "_Pressure":
            self.pressure = value
        else:
            return 1
        return 0