hmi.py 7.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
import ml
import os
import json
import s3i
import uuid

"""
Configure the HMI. 
The credentials file named hmi_cred.json must be located in the folder configs.
The configuration file named hmi.json must also be located in the same folder 
"""
Jiahang Chen's avatar
Jiahang Chen committed
12
ml.setup_logger("hmi")
Jiahang Chen's avatar
Jiahang Chen committed
13
config_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "configs"))
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
cred_path = os.path.join(config_path, "hmi_cred.json")
with open(cred_path) as file:
    hmi_cred = json.load(file)


class bcolors:
    """colors for the console log"""
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


def prepare_service_request():
    """
    Prepare a S³I-B Service Request

    :return: S³I-B Service Request
    :rtype: dict
    """
    available_services = ["fml40::AcceptsFellingJobs", "fml40::ProvidesProductionData"]
    print("[S³I]: Following services are available: {0}{1}{2}".format(bcolors.UNDERLINE, available_services,
                                                                      bcolors.ENDC))
    class_name = input("[S³I]: Please enter one of these services: ")
    serv_req = s3i.messages.ServiceRequest()

    while class_name not in available_services:
        print("[S³I]: service {0}{1}{2} is not available".format(bcolors.FAIL, class_name, bcolors.ENDC))
        print("[S³I]: Following services are available: {0}{1}{2}".format(bcolors.UNDERLINE, available_services,
                                                                          bcolors.ENDC))
        class_name = input("[S³I]: Please enter one of these services: ")

    if class_name == "fml40::AcceptsFellingJobs":
        available_methods = ["acceptJob", "queryJobStatus", "removeJob"]
        method = input("[S³I]: which method should be called? {0}{1}{2} ".format(bcolors.UNDERLINE, available_methods,
                                                                           bcolors.ENDC))
        while method not in available_methods:
            method = input(
                "[S³I]: which method should be called? {0}{1}{2} ".format(bcolors.UNDERLINE, available_methods,
                                                                          bcolors.ENDC))
        if method == "acceptJob":
            subFeatures = [{
                "class": "fml40::Assortment",
                "grade": "fl",
                "name": "Stammholz Abschnitte",
                "subFeatures": [
                    {
                        "class": "fml40::ThicknessClass",
                        "name": ">"
                    },
                    {
                        "class": "fml40::WoodQuality",
                        "name": "B-C"
                    },
                    {
                        "class": "fml40::HarvestingParameters",
                        "cuttingLengths": 20
                    },
                    {
                        "class": "fml40::TreeType",
                        "name": "Spruce",
                        "conifer": True
                    },
                    {
                        "class": "fml40::HarvestedVolume",
                        "volume": 140
                    }
                ]
            }]
            feature_config_json = ml.make_feature_config(class_name="fml40::FellingJob", subFeatures=subFeatures,
                                                         name="my_felling_job")
            felling_job = ml.build_feature(feature=feature_config_json)
            felling_job_json = felling_job.to_json()
Jiahang Chen's avatar
Jiahang Chen committed
91
92
            job_id = input("[S³I]: Please enter a id for your felling job: ")
            felling_job_json["identifier"] = job_id
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
            parameter = {"job": felling_job_json}

        elif method == "queryJobStatus":
            job_id = input("[S³I]: Please enter the job id: ")
            parameter = {"identifier": job_id}

        elif method == "removeJob":
            job_id = input("[S³I]: Please enter the job id: ")
            parameter = {"identifier": job_id}

    elif class_name == "fml40::ProvidesProductionData":
        available_methods = ["getProductionData"]
        method = input("[S³I]: which method should be called? {0}{1}{2} ".format(bcolors.UNDERLINE, available_methods,
                                                                                bcolors.ENDC))
        while method not in available_methods:
            method = input(
                "[S³I]: which method should be called? {0}{1}{2} ".format(bcolors.UNDERLINE, available_methods,
                                                                         bcolors.ENDC))
        if method == "getProductionData":
            name = input("[S³I]: Please enter the name of your production data: [Stammsegment 4711, Stammsegment 4712] ")
            parameter = {"name": name}

    serv_req.fillServiceRequest(
Jiahang Chen's avatar
Jiahang Chen committed
116
        senderUUID=hmi_cred.get("identifier"), receiverUUIDs=[receiver], sender_endpoint=hmi_endpoint,
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
        serviceType="{}/{}".format(class_name, method),
        parameters=parameter,
        msgUUID="s3i:{}".format(uuid.uuid4())
    )
    return serv_req.msg


def prepare_get_value_request():
    """
    Prepare a S³I-B GetValueRequest

    :return: S³I-B GetValueRequest
    :rtype: dict
    """
    getv_req = s3i.GetValueRequest()
    attribute_path = input("[S³I]: Please enter the attribute path: ["
                           "attributes/features/ml40::Composite/targets/ml40::Engine/features/ml40::RotationalSpeed"
                           "/rpm]")
    getv_req.fillGetValueRequest(
Jiahang Chen's avatar
Jiahang Chen committed
136
        senderUUID=hmi_cred.get("identifier"), receiverUUIDs=[receiver], sender_endpoint=hmi_endpoint,
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
        attributePath=attribute_path, msgUUID="s3i:{}".format(uuid.uuid4())
    )
    return getv_req.msg


if __name__ == "__main__":
    """
    Configure and run the HMI 
    """
    config_file_name = ml.make_thing_config(thing_id=hmi_cred.get("identifier"), name="hmi",
                                            roles=[{"class": "ml40::HMI"}],
                                            config_path=config_path)
    hmi_model = ml.load_config(config_filepath=os.path.join(config_path, config_file_name))
    hmi = ml.create_thing(model=hmi_model, grant_type="password", secret=hmi_cred.get("secret"),
                          username=hmi_cred.get("username"), password=hmi_cred.get("password"),
                          is_broker_rest=False, is_broker=True, is_repo=False)
    hmi.run_forever()
    hmi_endpoint = ml.find_broker_endpoint(hmi.dir, hmi_cred.get("identifier"))
    receiver = "s3i:b6d1cc6d-896c-40fe-9403-b5b7682b1d03"

    """
    While loop to edit S³I messages and then send it to the Digital Twin 
    """
    while True:
        print("[S³I]: You can send following messages to forwarder a by entering 1 or 2")
        request_type = input(" {0}[1]: service request, [2]: get value request:{1} ".format(
            bcolors.OKBLUE, bcolors.ENDC
        ))
        if request_type == "1":
            msg = prepare_service_request()
            if msg is None:
                continue
        elif request_type == "2":
            msg = prepare_get_value_request()
            if msg is None:
                continue
        else:
            continue
        receiver_endpoint = ml.find_broker_endpoint(hmi.dir, thing_id=receiver)
        resp = hmi.broker.send([receiver_endpoint], json.dumps(msg))