Commit 15fd924c authored by Jiahang Chen's avatar Jiahang Chen
Browse files

fix setup problem

parent da94ac43
Pipeline #338815 passed with stage
in 16 seconds
{"thingId": "s3i:feb857f1-3058-4ed4-8826-bbf182cbb16e", "policyId": "s3i:feb857f1-3058-4ed4-8826-bbf182cbb16e", "attributes": {"class": "ml40::Thing", "name": "dt test", "roles": [{"class": "fml40::Harvester"}], "features": [{"class": "fml40::ProvidesProductionData"}, {"class": "fml40::AcceptsFellingJobs"}]}}
\ No newline at end of file
{"thingId": "s3i:b4a0ec9b-66be-4390-b786-9c70b1c017e6", "policyId": "s3i:b4a0ec9b-66be-4390-b786-9c70b1c017e6", "attributes": {"class": "ml40::Thing", "name": "dt test", "roles": [{"class": "fml40::Harvester"}], "features": [{"class": "fml40::ProvidesProductionData"}, {"class": "fml40::AcceptsFellingJobs"}]}}
\ No newline at end of file
{"thingId": "s3i:b4f72a11-fb3d-47a3-b499-e7a88eaa5fe1", "policyId": "s3i:b4f72a11-fb3d-47a3-b499-e7a88eaa5fe1", "attributes": {"class": "ml40::Thing", "name": "my HMI", "roles": [{"class": "ml40::HMI"}], "features": []}}
\ No newline at end of file
{"thingId": "s3i:de59a481-dd97-429f-a0ca-fab013b6bfbc", "policyId": "s3i:de59a481-dd97-429f-a0ca-fab013b6bfbc", "attributes": {"class": "ml40::Thing", "name": "test", "roles": [{"class": "fml40::Harvester"}], "features": [{"class": "fml40::ProvidesProductionData"}, {"class": "fml40::AcceptsFellingJobs"}]}}
\ No newline at end of file
import s3i
import json
import jwt
from ml.tools import load_config, get_s3i_broker, get_receiver_callback_func
import requests
from ml.tools import load_config, get_s3i_broker, get_receiver_callback_func, make_config_file
from ml.dt_factory import create_dt_ref
from ml.fml40.features.functionalities.accepts_felling_jobs import AcceptsFellingJobs
from ml.app_logger import APP_LOGGER, setup_logger
dt_creation_app_id = "s3i:a44bd6dc-c607-4574-9b16-cf8579819356"
dt_creation_app_secret = "970ebe57-7dfb-4090-8c38-4b44111d5288"
print("KWH application to create a dt, please log in!")
#username = input('[S3I]: Please enter your username:').strip('," ')
#password = input('[S3I]: Please enter your password:')
username = "KWH-Team"
password = "V4yuJ31izh0GCH36954O"
print("Your credentials are sent to S3I IdentityProvider.")
username = "chen"
password = "8810515"
s3i_identity_provider = s3i.IdentityProvider(grant_type='password',
identity_provider_url="https://idp.s3i.vswf.dev/",
realm='KWH',
......@@ -26,13 +25,33 @@
''' decode the access token'''
parsed_username = jwt.decode(access_token, verify=False)["preferred_username"]
print("Token received, " + parsed_username + " logged in.")
### create identity of digital twin
dt_secret = "c49e4050-d194-4f08-90c5-e17fd5befba5"
# TODO class for config api in master to merge
# create a thing identity for the dt
create_thing_resp = requests.post(url="https://config.s3i.vswf.dev/things/",
headers={"Authorization": "Bearer {}".format(access_token),
"Content-Type": "application/json"},
data=json.dumps({}))
print(create_thing_resp.json())
dt_id = create_thing_resp.json().get("identifier", None)
print(dt_id)
create_cloud_copy_resp = requests.post(url="https://config.s3i.vswf.dev/things/{}/repository".format(dt_id),
headers={"Authorization": "Bearer {}".format(access_token),
"Content-Type": "application/json"})
create_endpoint_resp = requests.post(url="https://config.s3i.vswf.dev/things/{}/broker".format(dt_id),
headers={"Authorization": "Bearer {}".format(access_token),
"Content-Type": "application/json"},
data=json.dumps({"encrypted": False})
)
dt_model = load_config('configs/config_dt.json')
dt_secret = create_thing_resp.json().get("secret", None)
#dt_secret = "c49e4050-d194-4f08-90c5-e17fd5befba5"
dt_name = "test"
config_file_name = make_config_file(dt_id=dt_id, name=dt_name, roles="fml40::Harvester", features=["fml40::ProvidesProductionData",
"fml40::AcceptsFellingJobs"])
setup_logger(dt_name)
dt_model = load_config('configs/{}'.format(config_file_name))
dt_ref = create_dt_ref(model=dt_model, grant_type="password", secret=dt_secret, username=username, password=password,
is_broker=True, is_repo=False)
dt_proxy = dt_ref.proxy()
......@@ -40,12 +59,10 @@
class AcceptsFellingJobsImpl(AcceptsFellingJobs):
def acceptJob(self, job):
print("i have accepted a job {}".format(job))
return True
def my_accept_job_func(self, job):
APP_LOGGER.info("I am checking if the felling job can be accepted.")
return self.add_to_job_list(job)
dt_proxy.add_function_impl(AcceptsFellingJobsImpl, "AcceptsFellingJobs")
import s3i
import jwt
import uuid
from ml.tools import find_broker_endpoint, make_config_file, load_config
from ml.dt_factory import create_dt_ref
from ml.fml40.features.properties.values.documents.jobs.felling_job import FellingJob
import requests
import json, time
username = "chen"
password = "8810515"
client_id = "s3i:b4f72a11-fb3d-47a3-b499-e7a88eaa5fe1"
client_secret = "84df6340-9d64-4ae6-9076-86c224ec484a"
s3i_identity_provider = s3i.IdentityProvider(grant_type='password',
identity_provider_url="https://idp.s3i.vswf.dev/",
realm='KWH',
client_id=client_id,
client_secret=client_secret,
username=username,
password=password)
access_token = s3i_identity_provider.get_token(s3i.TokenType.ACCESS_TOKEN)
''' decode the access token'''
parsed_username = jwt.decode(access_token, verify=False)["preferred_username"]
print("Token received, " + parsed_username + " logged in.")
s3i_dir = s3i.Directory(s3i_dir_url="https://dir.s3i.vswf.dev/api/2/", token=access_token)
hmi_json = s3i_dir.queryThingIDBased(thingID=client_id)
hmi_id = "s3i:b4f72a11-fb3d-47a3-b499-e7a88eaa5fe1"
hmi_secret = "84df6340-9d64-4ae6-9076-86c224ec484a"
config_file_name = make_config_file(dt_id=hmi_id, name="my HMI", roles="ml40::HMI")
hmi_model = load_config('configs/{}'.format(config_file_name))
hmi_ref = create_dt_ref(model=hmi_model, grant_type="password", secret=hmi_secret,
username=username, password=password, is_broker=True, is_repo=False)
hmi_proxy = hmi_ref.proxy()
hmi_proxy.run_forever()
s3i_dir = s3i.Directory(s3i_dir_url="https://dir.s3i.vswf.dev/api/2/", token=hmi_proxy.access_token.get())
hmi_json = s3i_dir.queryThingIDBased(thingID=hmi_id)
hmi_endpoints = hmi_json["attributes"].get("allEndpoints", None)
hmi_s3ib_ep = ""
for hmi_ep in hmi_endpoints:
if "s3ib" in hmi_ep:
hmi_s3ib_ep = hmi_ep
messageIds = list()
serv_req = s3i.messages.ServiceRequest()
receiver = input("[S³I]: Please enter the id of your digital twin: ")
job = FellingJob("", hmi_ref)
serv_req.fillServiceRequest(
senderUUID=client_id, receiverUUID=["s3i:bea74f50-fa6c-4aba-b7f8-90153b401ffc"], sender_endpoint=hmi_s3ib_ep,
serviceType="AcceptsFellingJob/acceptJob",
senderUUID=hmi_id, receiverUUID=[receiver], sender_endpoint=hmi_s3ib_ep,
serviceType="AcceptsFellingJobs/my_accept_job_func",
parameters={"job": "fml40::FellingJob"},
msgUUID=str(uuid.uuid4())
)
my_dt_json = s3i_dir.queryThingIDBased(thingID="s3i:bea74f50-fa6c-4aba-b7f8-90153b401ffc")
dt_endpoints = my_dt_json["attributes"].get("allEndpoints", None)
dt_ep = ""
for temp in dt_endpoints:
if "s3ib" in temp:
dt_ep = temp
receiver_endpoint = find_broker_endpoint(s3i_dir, thing_id=receiver)
service_req_response = requests.post(url="https://broker.s3i.vswf.dev/{}".format(receiver_endpoint),
data=json.dumps(serv_req.msg),
headers={'Content-Type': 'application/json',
'Authorization': 'Bearer ' + hmi_proxy.access_token.get()}
)
print(service_req_response.text)
"""Store the message id into message storage"""
messageIds.append(serv_req.msg["identifier"])
time.sleep(1)
response = requests.get(url="https://broker.s3i.vswf.dev/{}".format(hmi_s3ib_ep), headers={'Content-Type': 'application/json',
'Authorization': 'Bearer ' + hmi_proxy.access_token.get()})
print(response.text)
"""
def receive(msg_type):
access_token = s3i_identity_provider.get_token(s3i.TokenType.ACCESS_TOKEN)
headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + access_token}
response = requests.get(url="https://broker.s3i.vswf.dev/{}".format(hmi_id), headers=headers)
msg_json = ""
value_json = ""
json_acceptable_string = response.text.replace("'", "\"")
if json_acceptable_string:
if check_message_encryption(response.text.strip('"')) == "pgp":
print_with_timestamp(
"You received a PGP message but this notebook can not decrypt PGP messages. Use the 03_inbox notebook to receive PGP messages.")
print_with_timestamp("PGP Message: " + response.text)
repeat(msg_type)
else:
msg_json = json.loads(json_acceptable_string)
if msg_json["replyingToMessage"] in messageIds and msg_json["messageType"] == msg_type:
if msg_type == "serviceReply":
value_json = msg_json["results"]
elif msg_type == "getValueReply":
value_json = msg_json["value"]
elif msg_type == "setValueReply":
value_json = msg_json["ok"]
messageIds.remove(msg_json["replyingToMessage"])
else:
repeat(msg_type)
else:
print_with_timestamp("The harvester did not respond yet.")
repeat(msg_type)
return msg_json, value_json
s3i_broker = s3i.Broker(auth_form="Username/Password", username=" ", password=access_token,
host="rabbitmq.s3i.vswf.dev")
s3i_broker.send([dt_ep], serv_req.msg.__str__())
def repeat(msg_type):
decision = input("[S3I] Do you want to check for new messages again? [j/n]")
if decision in yes:
receive(msg_type)
elif decision in no:
print_with_timestamp(
"You do not want to check for more messages. If you want to check for new messages, just execute this cell again (Run button or SHIFT+RETURN)")
else:
print_with_timestamp(
"I could not understand your response. If you want to check for new messages, just execute this cell again (Run button or SHIFT+RETURN)")
"""
\ No newline at end of file
......@@ -20,6 +20,13 @@
install_requires= [
"Pykka==2.0.2",
"pylint==2.4.4"
"https://git.rwth-aachen.de/kwh40/s3i/-/jobs/artifacts/master/raw/public/s3i-0.4-py3-none-any.whl?job=wheel",
"websocket",
"pynput",
"opcua",
"requests",
"asyncio",
"pylint==2.4.4"
],
classifiers=[
"Programming Language :: Python :: 3",
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment