Welcome to the world of MicroStation Python! In our previous wikis, we delved into creating, attaching, and detaching Item Types. Now, let us take it a step further. In this wiki, you will learn how to update the "RoomDetails" Item Type values from a JSON file hosted on a web server.
To set up a local JSON server, refer to this comprehensive tutorial: Set Up JSON Server
Update Item Type
To get started, refer to the Python Manager wiki for instructions on creating and loading a new Python project. Name your project "ItemType_UpdateItem.py" and save it in a convenient location. Once created, open the project in your preferred code editor to begin writing your Python script.
The script retrieves the 'RoomDetails' values from a JSON server, scans the DGN file for Shape elements, and updates the attached Item Types with the fetched values.
We use the requests library to retrieve the 'RoomDetails' values from a JSON server. To install the requests library, open a command prompt (CMD.exe), navigate to the folder C:\ProgramData\Bentley\PowerPlatformPython\python\, and key-in “python -m pip install requests”.
Here is the complete script.
import requests from MSPyBentley import * from MSPyBentleyGeom import * from MSPyECObjects import * from MSPyDgnPlatform import * from MSPyMstnPlatform import * from MSPyDgnView import * g_room_data_dict = [] # Get data from dictionary. def getRoomData(room_id): return next((room for room in g_room_data_dict if room["room_id"] == room_id), None) # Scan Room Shapes def scanRoomsUpdateData(): dgnFile = ISessionMgr.GetActiveDgnFile() if dgnFile is None: return False dgnModel = ISessionMgr.ActiveDgnModel if dgnModel is None: return False graphicalElements = dgnModel.GetGraphicElements() for elmRef in graphicalElements: eeh = EditElementHandle(elmRef, dgnModel) msElement = eeh.GetElement() isGraphics = msElement.ehdr.isGraphics isVisible = not(msElement.hdr.dhdr.props.b.invisible) eleType = eeh.GetElementType() if (isGraphics and isVisible and eleType == 6): itemHost = CustomItemHost(eeh, False) if (itemHost == None): print ("itemHost is null...") return False dgnecinstance_0 = itemHost.GetCustomItem("Project_001", "RoomDetails") if (dgnecinstance_0 == None): print ("dgnecinstance_0 is null...") return False if None == dgnecinstance_0: print ('ERROR in retrieving item type from element...\n') else: # Update Data here propValue = ECValue() dgnecinstance_0.GetValue(propValue, 'ID') #print('Room ID :' + str(propValue.GetInteger()) + '\n') r_id = propValue.GetInteger() room_info = getRoomData(r_id) #print (room_info) dgnecinstance_0.SetValue('Description', ECValue(room_info["description"])) date_string = room_info["date_time"] date_part, time_part = date_string.split() MO, DD, YY = date_part.split('-') HH, MM = time_part.split(':') SS = 0 updateDate = BeDateTime (BeDateTime.Kind.eUnspecified, int(YY),
int(MO), int(DD), int(HH), int(MM), SS) dgnecinstance_0.SetValue('Date', ECValue(updateDate)) temp = float(room_info["temperature"]) dgnecinstance_0.SetValue('Temperature', ECValue(temp)) humi = float(room_info["humidity"]) dgnecinstance_0.SetValue('Humidity', ECValue(humi)) occ = int(room_info["occupied"]) if (occ == 1): dgnecinstance_0.SetValue('Occupied', ECValue(True, occ)) else: dgnecinstance_0.SetValue('Occupied', ECValue(False, occ)) dgnecinstance_0.WriteChanges() print ("Data updated to elements...") return True # Get Data from Server def getDataFromServer(): global g_room_data_dict url = 'http://localhost:8000/RoomDetails' try: response = requests.get(url) response.raise_for_status() #print ("Response Code : ") #print (response.status_code) if response.status_code == 404: print("Page Not found...") return False elif response.status_code == 500: print("Internal server error...") return False elif response.status_code == 200: data = response.json() if isinstance(data, list): print("*** Room Details ***") for item in data: new_room = {"room_id": item["room_id"], "description": item["description"],
"temperature": item["temperature"], "humidity": item["humidity"],
"date_time": item["date_time"], "occupied": item["occupied"]} g_room_data_dict.append(new_room) #print (new_room) pass else: print("Other error...") #return False except requests.exceptions.ConnectionError as e: print("Server Connection error...", e) return False except requests.exceptions.Timeout as e: print("Server Request timed out...", e) return False except requests.exceptions.RequestException as e: print("Server Request error...", e) return False return True # Main function def main(): PyCadInputQueue.SendKeyin("set view wireframe; selview all") if (True != getDataFromServer()): print ("Data extraction failed...") else: print ("Data extracted from local JSON server...") if (True == scanRoomsUpdateData()): print ("Applying Display Style...") PyCadInputQueue.SendKeyin("Change view custom RoomTempThematic 1; selview all") # Main if __name__ == "__main__": print ("**** Update Item Type values from Server/JSON ****") main()
Load the project “ItemType_UpdateItem.py” from the Python Manager dialog and Run/Execute the python script.
Download “RoomDetails” JSON file, “Building_Update.dgn” DGN file.
Item Type “RoomDetails” values are updated to all Shape elements as illustrated below.
Before
After
A display style is applied to add color to the Temperature values.
Happy coding!
Python: Documentation | API Presentations | FAQs | GitHub | Samples | Wikis | Blogs