main.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/env python3
  2. import asyncio
  3. import datetime
  4. from async_realtime_environment import AsyncRealtimeEnvironment
  5. from nicegui import ui
  6. start_time = datetime.datetime.now()
  7. def clock(env):
  8. while True:
  9. simulation_time = start_time + datetime.timedelta(seconds=env.now)
  10. clock_label.text = simulation_time.strftime('%H:%M:%S')
  11. yield env.timeout(1)
  12. def traffic_light(env):
  13. while True:
  14. light.classes('bg-green-500', remove='bg-red-500')
  15. yield env.timeout(30)
  16. light.classes('bg-yellow-500', remove='bg-green-500')
  17. yield env.timeout(5)
  18. light.classes('bg-red-500', remove='bg-yellow-500')
  19. yield env.timeout(20)
  20. async def run_simpy():
  21. env = AsyncRealtimeEnvironment(factor=0.1) # fast forward simulation with 1/10th of realtime
  22. env.process(traffic_light(env))
  23. env.process(clock(env))
  24. try:
  25. await env.run(until=300) # run until 300 seconds of simulation time have passed
  26. except asyncio.CancelledError:
  27. return
  28. ui.notify('Simulation completed')
  29. content.classes('opacity-0') # fade out the content
  30. # define the UI
  31. with ui.column().classes('absolute-center items-center transition-opacity duration-500') as content:
  32. ui.label('SimPy Traffic Light Demo').classes('text-2xl mb-6')
  33. light = ui.element('div').classes('w-10 h-10 rounded-full shadow-lg transition')
  34. clock_label = ui.label()
  35. # start the simpy simulation as an async task in the background as soon as the UI is ready
  36. ui.timer(0, run_simpy, once=True)
  37. ui.run()