Skip to content

Commit

Permalink
adding code to run a script in async with the keyboard ctrl-c handler…
Browse files Browse the repository at this point in the history
… as a base to help create scripts without having to repeat boilerplate code
  • Loading branch information
ChristianTremblay committed Sep 2, 2024
1 parent a01fdfa commit 7f3cb56
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
7 changes: 7 additions & 0 deletions BAC0/scripts/Lite.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,3 +496,10 @@ async def __aexit__(self, exc_type, exc_val, exc_tb):
self._log.info(
f"{self.localObjName}|{self.Boid} disconnected. Exiting context manager."
)

def get_device_by_id(self, id):
for each in self.registered_devices:
if each.properties.device_id == id:
return each
self._log.error(f"Device {id} not found")
raise ValueError('Device not found')
34 changes: 34 additions & 0 deletions BAC0/scripts/script_runner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import BAC0
import asyncio
from signal import SIGINT, SIGTERM, signal
import click
from BAC0.tools.jci_tec_points_list import tec_short_point_list
from BAC0.tasks.RecurringTask import RecurringTask
import os

def run(main_task, bacnet):
global loop

def handler(sig, sig2):
bacnet._log.info(f"Got signal: {sig!s}, shutting down.")
bacnet.disconnect()
loop.stop()

try:
loop = asyncio.get_running_loop() #we also could have chosen get_event_loop(), and if we did we would not have needed to set_event_loop() and create a new event loop
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# for sig in (SIGINT, SIGTERM):
# loop.add_signal_handler(sig, handler)
signal(SIGINT, handler)
signal(SIGTERM, handler)

loop.create_task(main_task())
loop.run_forever()
tasks = asyncio.all_tasks(loop=loop)
for t in tasks:
t.cancel()
group = asyncio.gather(*tasks, return_exceptions=True)
loop.run_until_complete(group)
loop.close()

0 comments on commit 7f3cb56

Please sign in to comment.