main.py 1.4 KB

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