Commit f91be628 authored by lenekaethe's avatar lenekaethe
Browse files

Initial commit

parents
#import sys, os
#sys.path.append(os.path.abspath(os.path.join("..", "config")))
#from config.config import *
from digitalTwin.messageDistributer import MessageDistributer
from digitalTwin.services import Services
from digitalTwin.secretary import Secretary
#from digitalTwin.internalData import DATA, CLIENT_SECRET
from digitalTwin.tools import service_request, print_ts, input_ts, service_reply
\ No newline at end of file
DATA = {
"thingID": "s3i:6c77d7a9-1add-4751-8930-f4733ca5a2f4",
"policyID": "s3i:6c77d7a9-1add-4751-8930-f4733ca5a2f4",
"attributes": {
"class": "ml40::Thing",
"name": "WZL-Demo-Forwarder",
"roles": [{"class": "ml40::Forwarder"}],
"components": [
{
"class": "ml40::Scale",
"currentWeight": 300
},
{
"class": "fml40::LogLoadingArea",
"maWeight": 10000
},
{
"class": "ml40::Dimensions",
"weight": 15000
},
{"class": "fml40::Forwarding"}
]
}
}
CLIENT_SECRET = "9a353553-c637-4b9b-9e6d-1661fdf98e4f"
SACHVERSTAENDIGER_ENDPOINT = "s3ib://s3i:a6884008-d55a-4fd0-896d-2220490bcc25"
\ No newline at end of file
from s3i import IdentityProvider, Directory, Broker, GetValueRequest, ServiceReply, ServiceRequest, TokenType
import pykka
import uuid
import json
import jwt
import base64
import time
import os
import requests
import threading
import digitalTwin
class MessageDistributer(pykka.ThreadingActor):
"""This actor class distributes the Messages of the digital twin (dt) to the respective actor in charge. The actor in charge is determined based on the message and service types of the incoming messages.
Implementing this as an actor allowes an independant handling of the incoming messages. Otherwise the dt's services might stop each time a messages comes in.
"""
def __init__(self, idp, service = None, secretary = None):
"""All the dt's actors are instanciated here.
"""
super().__init__()
self.idp = idp
if service:
self.dt_proxy = service.start(self.idp).proxy() #digitalTwin.Services.start(self.idp).proxy()
if secretary:
self.secretary_proxy = secretary.start(self.idp, self.dt_proxy).proxy() #digitalTwin.Secretary.start(self.idp,self.dt_proxy).proxy()
def on_stop(self):
pykka.ActorRegistry.get_by_class_name("Services")[0].stop()
pykka.ActorRegistry.get_by_class_name("Secretary")[0].stop()
import pykka
import json
import time
class Secretary(pykka.ThreadingActor):
"""This is the secretary of the forwarder. It receives the service replys which are addressed to the forwarder and schedules the further forwarder actions when all necessary replys have arrived.
"""
def __init__(self, idp, ref_dt):
super().__init__()
self.idp = idp
self.ref = ref_dt
self.ref.registerSecretary(self)
def on_receive(self, msg):
print("Hello, I'm a secretary")
print("You send me a message: ", msg)
\ No newline at end of file
import pykka
class Services(pykka.ThreadingActor):
def __init__(self, idp):
super().__init__()
self.idp = idp
self.secretary = None
def registerSecretary(self, secretary):
self.secretary = secretary
def on_receive(self, msg):
print("Hello, I'm the digital twin")
print("You send me a message: ", msg)
import datetime
import time
import uuid
from s3i import IdentityProvider, Directory, Broker, GetValueRequest, ServiceReply, ServiceRequest, TokenType
import sys, os
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
import config
import importlib
#configData = importlib.import_module("config."+"ponsse_harvester")
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 print_ts(msg, end='\n'):
"""
prints the given message in the s3i style
:param msg: message to print
:type msg: string
"""
global console_no_new_line
trail = ""
if end == "\r":
console_no_new_line = True
elif console_no_new_line:
console_no_new_line = False
trail = "\n"
print(trail+"[S³I][" + datetime.datetime.fromtimestamp(time.time()
).strftime('%H:%M:%S.%f')[:-3]+"] " + msg, end=end)
def input_ts(msg):
return input("[S³I][" + datetime.datetime.fromtimestamp(time.time()
).strftime('%H:%M:%S.%f')[:-3]+"] " + msg)
def service_request(idp, config, serviceType, receiver_endpoints, parameter = None):
configData = importlib.import_module("config."+config)
senderUUID = configData.DATA["thingId"]
receiverUUID = [item.split('//')[1] for item in receiver_endpoints]
msgUUID = "s3i:" + str(uuid.uuid4())
req = ServiceRequest()
req.fillServiceRequest(senderUUID, receiverUUID, "s3ib://" +
configData.DATA["thingId"], serviceType, parameter, msgUUID=msgUUID)
#print("Send: ", req.msg)
access_token = idp.get_token(TokenType.ACCESS_TOKEN)
s3i_broker = Broker(
auth_form='Username/Password', username=" ", password=access_token, host="rabbitmq.s3i.vswf.dev")
s3i_broker.send(receiver_endpoints, req.msg.__str__())
print("Service Request: ", req.msg["messageType"], ":", req.msg["serviceType"])
def service_reply(idp, config, serviceType, receiver_endpoints, results, id):
configData = importlib.import_module("config."+config)
senderUUID = configData.DATA["thingId"]
receiverUUID = [item.split('//')[1] for item in receiver_endpoints]
msgUUID = "s3i:" + str(uuid.uuid4())
req = ServiceReply()
req.fillServiceReply(senderUUID, receiverUUID, serviceType, results, msgUUID=msgUUID, replyingToUUID=id)
access_token = idp.get_token(TokenType.ACCESS_TOKEN)
s3i_broker = Broker(
auth_form='Username/Password', username=" ", password=access_token, host="rabbitmq.s3i.vswf.dev")
s3i_broker.send(receiver_endpoints, req.msg.__str__())
print("Service Reply send: ", req.msg["messageType"], ":", req.msg["serviceType"])
def dir_search_with_name(idp, name):
s3i_directory = Directory(s3i_dir_url="https://dir.s3i.vswf.dev/api/2/", token=idp.get_token(TokenType.ACCESS_TOKEN))
try:
id = s3i_directory.queryAttributeBased("name", name)[0]["thingId"]
except:
id = []
return id
def dir_id_to_defualtEndpoints(idp, id):
s3i_directory = Directory(s3i_dir_url="https://dir.s3i.vswf.dev/api/2/", token=idp.get_token(TokenType.ACCESS_TOKEN))
try:
endpoint = s3i_directory.queryThingIDBased(id+"/attributes/defaultEndpoints")
except:
endpoint = []
return endpoint
\ No newline at end of file
from s3i import IdentityProvider, Directory, Broker, GetValueRequest, ServiceReply, ServiceRequest, TokenType
import uuid
import json
import jwt
import base64
import time
data = {
"thingID": "s3i:a8b7da14-9e43-47f0-a876-cfd1ca38a9e1",
"policyID": "s3i:a8b7da14-9e43-47f0-a876-cfd1ca38a9e1",
"attributes": {
"class": "ml40::Thing",
"name": "WZL-Demo Wald",
"roles": [{"class": "fml40::Forest"}],
"components": [
{
"class": "fml40::InventoryData",
"data": {"class": "fml::AbstractInventory"}
},
"s3i:...",
"s3i:..."
]
}
}
def sendRequest():
senderUUID = data["thingID"]
receiverUUID = ["s3i:5e83b933-331f-4278-b318-b7fdcb0e4872"]
receiver_endpoint = "s3ibs://s3i:5e83b933-331f-4278-b318-b7fdcb0e4872" #s3i:c5d5cd58-8786-40b2-8079-5f2de443de36"
receiver_endpoints = list()
receiver_endpoints.append(receiver_endpoint)
serviceType = "fml40::FellingJob"
msgUUID = "s3i:" + str(uuid.uuid4())
req = ServiceRequest()
req.fillServiceRequest(senderUUID, receiverUUID, "s3ib://" +
data["thingID"], serviceType, None, msgUUID=msgUUID)
s3i_broker = Broker(
auth_form='Username/Password', username=" ", password=access_token, host="rabbitmq.s3i.vswf.dev")
s3i_broker.send(receiver_endpoints, req.msg.__str__())
print("I asked the forwarder to forward the stem segments.")
if __name__ == "__main__":
client_secret = "d48971ab-2c22-47d5-a8dc-86079a2c4cb6"
idp = IdentityProvider(grant_type='client_credentials', identity_provider_url="https://idp.s3i.vswf.dev/",
realm='KWH', client_id=data["thingID"], client_secret=client_secret)
access_token = idp.get_token(TokenType.ACCESS_TOKEN)
sendRequest()
https://git.rwth-aachen.de/kwh40/s3i/-/jobs/artifacts/master/raw/public/s3i-0.4-py3-none-any.whl?job=wheel
Pykka
#https://git.rwth-aachen.de/kwh40/s3i/-/jobs/758151/artifacts/raw/public/s3i-0.4-py3-none-any.whl
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