Skip to content

Commit 8b3ce10

Browse files
committed
state machine generate_plantuml() can show diagram by using https://www.plantuml.com/plantuml/
1 parent 4ef4e22 commit 8b3ce10

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

MissionPlanning/StateMachine/state_machine.py

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,34 @@
99
(https://en.wikipedia.org/wiki/Finite-state_machine)
1010
"""
1111

12+
import string
13+
from urllib.request import urlopen, Request
14+
from base64 import b64encode
15+
from zlib import compress
16+
from io import BytesIO
1217
from collections.abc import Callable
18+
from matplotlib.image import imread
19+
from matplotlib import pyplot as plt
20+
21+
22+
def deflate_and_encode(plantuml_text):
23+
"""
24+
zlib compress the plantuml text and encode it for the plantuml server.
25+
26+
Ref: https://plantuml.com/en/text-encoding
27+
"""
28+
plantuml_alphabet = (
29+
string.digits + string.ascii_uppercase + string.ascii_lowercase + "-_"
30+
)
31+
base64_alphabet = (
32+
string.ascii_uppercase + string.ascii_lowercase + string.digits + "+/"
33+
)
34+
b64_to_plantuml = bytes.maketrans(
35+
base64_alphabet.encode("utf-8"), plantuml_alphabet.encode("utf-8")
36+
)
37+
zlibbed_str = compress(plantuml_text.encode("utf-8"))
38+
compressed_string = zlibbed_str[2:-4]
39+
return b64encode(compressed_string).translate(b64_to_plantuml).decode("utf-8")
1340

1441

1542
class State:
@@ -248,4 +275,20 @@ def generate_plantuml(self) -> str:
248275
plant_uml.append(transition)
249276

250277
plant_uml.append("@enduml")
251-
return "\n".join(plant_uml)
278+
plant_uml_text = "\n".join(plant_uml)
279+
280+
try:
281+
url = f"http://www.plantuml.com/plantuml/img/{deflate_and_encode(plant_uml_text)}"
282+
headers = {"User-Agent": "Mozilla/5.0"}
283+
request = Request(url, headers=headers)
284+
285+
with urlopen(request) as response:
286+
content = response.read()
287+
288+
plt.imshow(imread(BytesIO(content), format="png"))
289+
plt.axis("off")
290+
plt.show()
291+
except Exception as e:
292+
print(f"Error showing PlantUML: {e}")
293+
294+
return plant_uml_text

0 commit comments

Comments
 (0)