Skip to content

Commit 30fb21c

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

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

MissionPlanning/StateMachine/state_machine.py

Lines changed: 41 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 requests
13+
import string
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,17 @@ 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+
response = requests.get(
282+
f"http://www.plantuml.com/plantuml/img/{deflate_and_encode(plant_uml_text)}"
283+
)
284+
285+
plt.imshow(imread(BytesIO(response.content), format="png"))
286+
plt.axis("off")
287+
plt.show()
288+
except Exception as e:
289+
print(f"Error showing PlantUML: {e}")
290+
291+
return plant_uml_text

0 commit comments

Comments
 (0)