Skip to content

Commit

Permalink
remove even more stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Voigt committed Nov 15, 2024
1 parent 7f86b8d commit 5764795
Show file tree
Hide file tree
Showing 6 changed files with 28 additions and 252 deletions.
60 changes: 0 additions & 60 deletions simulators/.vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,66 +9,6 @@
"envFile": "${workspaceFolder}/.vscode/.env",
"cwd": "${workspaceFolder}/main/",
"console": "integratedTerminal"
},
{
"name": "create profiles",
"type": "python",
"request": "launch",
"program": "profile_generator.py",
"console": "integratedTerminal",
"envFile": "${workspaceFolder}/.vscode/.env",
"cwd": "${workspaceFolder}/main/",
"args": [
"--create-profiles"
]
},
{
"name": "remove simulator profiles via OEE API",
"type": "python",
"request": "launch",
"program": "profile_generator.py",
"console": "integratedTerminal",
"envFile": "${workspaceFolder}/.vscode/.env",
"cwd": "${workspaceFolder}/main/",
"args": [
"--remove-simulator-profiles-via-oee"
]
},
{
"name": "delete simulator profiles",
"type": "python",
"request": "launch",
"program": "profile_generator.py",
"console": "integratedTerminal",
"envFile": "${workspaceFolder}/.vscode/.env",
"cwd": "${workspaceFolder}/main/",
"args": [
"--delete-simulator-profiles"
]
},
{
"name": "create calculation categories",
"type": "python",
"request": "launch",
"program": "profile_generator.py",
"console": "integratedTerminal",
"envFile": "${workspaceFolder}/.vscode/.env",
"cwd": "${workspaceFolder}/main/",
"args": [
"--create-categories"
]
},
{
"name": "delete calculation categories",
"type": "python",
"request": "launch",
"program": "profile_generator.py",
"console": "integratedTerminal",
"envFile": "${workspaceFolder}/.vscode/.env",
"cwd": "${workspaceFolder}/main/",
"args": [
"--delete-categories"
]
}
]
}
48 changes: 0 additions & 48 deletions simulators/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

OEE-simulators offers these main features in [main](main):
- the **oee-simulators microservice** which creates devices and sends data into Cumulocity.
- the **profile generator** to create/delete OEE calculation profiles from the command line.

There are extra features in [extras](extras):
- the **export profile data** to export Measurements or/and Alarms from OEE profiles into json data files.
Expand Down Expand Up @@ -133,15 +132,6 @@ zip oee-simulators.zip image.tar cumulocity.json
```
This zip file can then be uploaded as a Microservice to Cumulocity IoT.
### Creating profiles automatically
The creation of profiles can be configured using the Tenant Options on the given Cumulocity tenant. See the [Cumulocity REST API](https://cumulocity.com/api/10.14.0/#tag/Options) documentation for details. The Tenant Options must use the category: "simulators"
Some Options can be configured:
- LOG_LEVEL - sets the used logging-level of the simulator. Choose between INFO and DEBUG. DEBUG does give a more detailed output of the Simulator's configuration and decisions. Default: 'INFO'
Note: A profile will be created and activated only if no other profiles are already defined for the particular device.
### Deployment
To deploy this project, upload the zip file to the Cumulocity as Microservice. The zip file can be created locally as described above or downloaded from the [releases](https://github.com/SoftwareAG/oee-simulators/releases) section.
Expand All @@ -165,44 +155,6 @@ C8Y_PASSWORD=yourpassword
Additionally the following optional/debug variables can be set:
```
MOCK_C8Y_REQUESTS=false
PROFILES_PER_DEVICE=1
```
- if MOCK_C8Y_REQUESTS is set to true, no requests to the C8Y tenant are executed, but you can see what would have been executed in the log
- if PROFILES_PER_DEVICE is increased, more than one profile is created for each simulator; this might be useful when doing performance/scalability tests
### Execution
There are two ways to execute the profile generation. You can run it from the development environment [Visual Studio Code](#visual-studio-code) or from the command line.
#### Execution from command line
To execute the scripts from command line, open a command prompt and the *oee-simulators\simulators* folder.
To create profiles, execute:
```
python .\main\profile_generator.py -c
```
To remove profiles using the OEE API, execute:
```
python .\main\profile_generator.py -r
```
To remove profiles using the standard Cumulocity IoT API (e.g. if OEE is not installed on the tenant), execute:
```
python .\main\profile_generator.py -d
```
#### Execution in Visual Studio Code
- Open *simulators* folder in the VSC
- Install python plugin: ms-python.python
- adjust environment variables in [.vscode/.env](.vscode/.env)
- click at the big run/debug icon in the left toolbar
- select the configuration that you want to use from the dropdown: `create profiles`, `remove simulator profiles via OEE API`, `delete simulator profiles`
- click the small green run/debug icon left of the dropdown in the top area to execute the configuration
20 changes: 0 additions & 20 deletions simulators/main/arguments_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,11 @@
credentials.add_argument('--username', '-u', type=str, help='C8Y Username')
credentials.add_argument('--test', '-test', action='store_true', help='Flag to enable test mode')

# profile_generator arguments
profile_generator_mode = parser.add_argument_group('Profile_generator')
profile_generator_mode.add_argument("--create-profiles", "-c", action="store_true", dest="create_profiles",help="create profiles")
profile_generator_mode.add_argument("--remove-simulator-profiles-via-oee", "-r", action="store_true", dest="remove_simulator_profiles_via_oee", help="remove all simulator profiles using the OEE API provided by oee-bundle")
profile_generator_mode.add_argument("--delete-simulator-profiles", "-d", action="store_true", dest="delete_simulator_profiles", help="delete all simulator profiles using the C8Y inventory API (useful if oee-bundle is not working/available")
profile_generator_mode.add_argument("--create-categories", "-cat", action="store_true", dest="create_categories", help="create or update calculation categories")
profile_generator_mode.add_argument("--delete-categories", "-dcat", action="store_true", dest="delete_categories", help="delete all calculation categories")

args = parser.parse_args()
print(args)
def get_credentials():
return args.baseurl, args.tenant_id, args.username, args.password, args.test

def get_profile_generator_mode():
if args.create_profiles:
return 'createProfiles'
elif args.remove_simulator_profiles_via_oee:
return 'removeSimulatorProfilesViaOee'
elif args.delete_simulator_profiles:
return 'deleteSimulatorProfiles'
elif args.create_categories:
return 'createCalculationCategories'
elif args.delete_categories:
return 'deleteCalculationCategories'

def check_credentials_availability(C8Y_BASEURL, C8Y_TENANT, C8Y_USER, C8Y_PASSWORD):
# Get credentials from argument inputs
base_url, tenant, user, password, test_flag = get_credentials()
Expand Down
91 changes: 2 additions & 89 deletions simulators/main/cumulocityAPI.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,10 @@
'Authorization': 'Basic ' + user_and_pass
}


class CumulocityAPI:

C8Y_SIMULATORS_GROUP = "c8y_EventBasedSimulator"
OEE_CALCULATION_PROFILE_TYPE = "OEECalculationProfile"
OEE_CALCULATION_CATEGORY = "OEECategoryConfiguration"

def __init__(self) -> None:
self.mocking = MOCK_REQUESTS.lower() == 'true'
Expand Down Expand Up @@ -162,39 +161,7 @@ def get_or_create_device(self, sim_id, label):

# Check if device already created
return self.get_device_by_external_id(sim_id) or self.__create_device(sim_id, label)
def count_all_profiles(self):
return self.__count_all(self.OEE_CALCULATION_PROFILE_TYPE)

def count_all_categories(self):
return self.__count_all(self.OEE_CALCULATION_CATEGORY)
def __count_all(self, oee_type):
if self.mocking:
log.info(f'mock: count_all types({oee_type})')
return 5

request_query = f'{C8Y_BASEURL}/inventory/managedObjects/count?type={oee_type}'
repsonse = requests.get(request_query, headers=C8Y_HEADERS)
if repsonse.ok:
return repsonse.json()

def count_profiles(self, device_id):
''' count all profiles for the given device id.
'''
if self.mocking:
log.info(f'mock: count_profiles(${device_id})')
return 10
request_query = f'{C8Y_BASEURL}/inventory/managedObjects/count?type={self.OEE_CALCULATION_PROFILE_TYPE}&text={device_id}'
response = requests.get(request_query, headers=C8Y_HEADERS)
if response.ok:
try:
return int(response.text)
except Exception as e:
log.warning(f'cannot convert "${response.text}" to number. exception: {e}')
return 0
else:
self.log_warning_on_bad_response(response)
return 0

def create_managed_object(self, fragment: str):
if self.mocking:
log.info(f'mock: create_managed_object()')
Expand All @@ -216,16 +183,6 @@ def get_managed_object(self, id: str):
self.log_warning_on_bad_response(response)
#TODO: check for errors
return {}

def get_calculation_categories(self):
if self.mocking:
log.info(f'mock: get_managed_object()')
return [{'id': '0'}]
response = requests.get(C8Y_BASEURL + f'/inventory/managedObjects?type={self.OEE_CALCULATION_CATEGORY}', headers=C8Y_HEADERS)
if response.ok:
return response.json()['managedObjects']
self.log_warning_on_bad_response(response)
return {}

def delete_managed_object(self, id: str):
if self.mocking:
Expand Down Expand Up @@ -318,48 +275,4 @@ def get_tenant_option_by_category(self, category):
if response.ok:
return response.json()
log.warning(f'Could not get any tenant options for category {category}. Response status code is: {response}, content: {response.text}')
return {}

def get_profile_id(self, deviceID):
request_query = f'{C8Y_BASEURL}/inventory/managedObjects?type={self.OEE_CALCULATION_PROFILE_TYPE}&text={deviceID}'
response = requests.get(request_query, headers=C8Y_HEADERS)
if response.ok:
try:
return response.json()['managedObjects'][0]['id']
except Exception as e:
log.warning(f'Cannot get id of profile: "{response.text}". exception: {e}')
return ""
else:
self.log_warning_on_bad_response(response)
return ""

def createISAType(self, type, hierarchy, description, oeetarget):
isaObjectRequestBody = {
"hierarchy": hierarchy,
"isISAObject":{},
"description": description,
"detailedDescription": description,
"type": type,
"oeetarget": oeetarget,
"orderByIndex":0,
}
return self.create_managed_object(json.dumps(isaObjectRequestBody))

def updateISAType(self, id, type, hierarchy, description, oeetarget):
isaObjectRequestBody = {
"hierarchy": hierarchy,
"isISAObject":{},
"description": description,
"detailedDescription": description,
"type": type,
"oeetarget": oeetarget,
"orderByIndex":0,
}
return self.update_managed_object(id, json.dumps(isaObjectRequestBody))

def getISAObjects(self):
request_query = f'{C8Y_BASEURL}/inventory/managedObjects?pageSize=1000&withTotalPages=false&fragmentType=isISAObject'
response = requests.get(request_query, headers=C8Y_HEADERS)
if response.ok:
return response.json()['managedObjects']
return []
return {}
7 changes: 2 additions & 5 deletions test/export_import_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,10 @@ def test_export_import_profile_data(self, mock_error):
os.chdir("test")

try:
# Create new simulator and oee profile
# Create new simulator
Utils.setup_model(self)
device_id = Utils.create_device(self.device_model_with_events)
external_device_id = self.device_model_with_events.get('id')
profile_id = self.oee_api.create_and_activate_profile(external_id=external_device_id).get('id')
filename = f"{external_device_id}_profile"
data_file_path = f"export_data/{filename}.json"

Expand Down Expand Up @@ -79,7 +78,7 @@ def test_export_import_profile_data(self, mock_error):
# Change work dir to extras
Utilities.change_working_dir_between_extras_and_test()
# Run the ExportProfileData.py script
call(["python", "ExportProfileData.py", "--device-ids", f"{profile_id}", "--username", f"{C8Y_USER}", "--password", f"{C8Y_PASSWORD}", "--tenant-id", f"{C8Y_TENANT}", "--baseurl", f"{C8Y_BASEURL}", "--test"])
call(["python", "ExportProfileData.py", "--device-ids", f"{device_id}", "--username", f"{C8Y_USER}", "--password", f"{C8Y_PASSWORD}", "--tenant-id", f"{C8Y_TENANT}", "--baseurl", f"{C8Y_BASEURL}", "--test"])

# Change work dir to test dir
Utilities.change_working_dir_between_extras_and_test()
Expand All @@ -94,8 +93,6 @@ def test_export_import_profile_data(self, mock_error):
finally:
# Change back to the original working directory
os.chdir(current_dir)
# Delete test device and profile
Utils.delete_oee_profile_and_device(self=self, profile_id=profile_id, device_id=device_id)

class Utilities:
@staticmethod
Expand Down
Loading

0 comments on commit 5764795

Please sign in to comment.