async def async_setup_usb(self) -> None: """Attempt setup of a Crownstone usb dongle.""" # Trace by-id symlink back to the serial port serial_port = await self.hass.async_add_executor_job( get_port, self.config_entry.options[CONF_USB_PATH]) if serial_port is None: return self.uart = CrownstoneUart() # UartException is raised when serial controller fails to open try: await self.uart.initialize_usb(serial_port) except UartException: self.uart = None # Set entry options for usb to null updated_options = self.config_entry.options.copy() updated_options[CONF_USB_PATH] = None updated_options[CONF_USB_SPHERE] = None # Ensure that the user can configure an USB again from options self.hass.config_entries.async_update_entry( self.config_entry, options=updated_options) # Show notification to ensure the user knows the cloud is now used persistent_notification.async_create( self.hass, f"Setup of Crownstone USB dongle was unsuccessful on port {serial_port}.\n \ Crownstone Cloud will be used to switch Crownstones.\n \ Please check if your port is correct and set up the USB again from integration options.", "Crownstone", "crownstone_usb_dongle_setup", ) return setup_uart_listeners(self)
class UartThreadExample(threading.Thread): def __init__(self): self.loop = None self.uart = None threading.Thread.__init__(self) def run(self): self.loop = asyncio.new_event_loop() self.uart = CrownstoneUart() # choose either sync, or async operation self.loop.run_until_complete(self.runIt()) # self.runIt_sync() async def runIt(self): await self.uart.initialize_usb() def runIt_sync(self): self.uart.initialize_usb_sync() def stop(self): self.uart.stop()
class UartThreadExample(threading.Thread): def __init__(self): self.loop = None self.uart = None threading.Thread.__init__(self) def run(self): self.loop = asyncio.new_event_loop() self.uart = CrownstoneUart() # choose either sync, or async operation self.loop.run_until_complete(self.runIt()) # self.runIt_sync() async def runIt(self): await self.uart.initialize_usb() self.switch_crownstone() def runIt_sync(self): self.uart.initialize_usb_sync() self.switch_crownstone() def switch_crownstone(self): turnOn = True for i in range(0, 10): if not self.uart.running: break if turnOn: print("Switching Crownstone on (iteration: ", i, ")") else: print("Switching Crownstone off (iteration: ", i, ")") self.uart.switch_crownstone(targetCrownstoneId, on=turnOn) turnOn = not turnOn time.sleep(2) def stop(self): self.uart.stop()
class CrownstoneEntryManager: """Manage a Crownstone config entry.""" uart: CrownstoneUart | None = None cloud: CrownstoneCloud sse: CrownstoneSSEAsync def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None: """Initialize the hub.""" self.hass = hass self.config_entry = config_entry self.listeners: dict[str, Any] = {} self.usb_sphere_id: str | None = None async def async_setup(self) -> bool: """ Set up a Crownstone config entry. Returns True if the setup was successful. """ email = self.config_entry.data[CONF_EMAIL] password = self.config_entry.data[CONF_PASSWORD] self.cloud = CrownstoneCloud( email=email, password=password, clientsession=aiohttp_client.async_get_clientsession(self.hass), ) # Login & sync all user data try: await self.cloud.async_initialize() except CrownstoneAuthenticationError as auth_err: _LOGGER.error( "Auth error during login with type: %s and message: %s", auth_err.type, auth_err.message, ) return False except CrownstoneUnknownError as unknown_err: _LOGGER.error("Unknown error during login") raise ConfigEntryNotReady from unknown_err # A new clientsession is created because the default one does not cleanup on unload self.sse = CrownstoneSSEAsync( email=email, password=password, access_token=self.cloud.access_token, websession=aiohttp_client.async_create_clientsession(self.hass), ) # Listen for events in the background, without task tracking asyncio.create_task(self.async_process_events(self.sse)) setup_sse_listeners(self) # Set up a Crownstone USB only if path exists if self.config_entry.options[CONF_USB_PATH] is not None: await self.async_setup_usb() # Save the sphere where the USB is located # Makes HA aware of the Crownstone environment HA is placed in, a user can have multiple self.usb_sphere_id = self.config_entry.options[CONF_USB_SPHERE] self.hass.data.setdefault(DOMAIN, {})[self.config_entry.entry_id] = self self.hass.config_entries.async_setup_platforms(self.config_entry, PLATFORMS) # HA specific listeners self.config_entry.async_on_unload( self.config_entry.add_update_listener(_async_update_listener)) self.config_entry.async_on_unload( self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.on_shutdown)) return True async def async_process_events(self, sse_client: CrownstoneSSEAsync) -> None: """Asynchronous iteration of Crownstone SSE events.""" async with sse_client as client: async for event in client: if event is not None: # Make SSE updates, like ability change, available to the user self.hass.bus.async_fire(f"{DOMAIN}_{event.type}", event.data) async def async_setup_usb(self) -> None: """Attempt setup of a Crownstone usb dongle.""" # Trace by-id symlink back to the serial port serial_port = await self.hass.async_add_executor_job( get_port, self.config_entry.options[CONF_USB_PATH]) if serial_port is None: return self.uart = CrownstoneUart() # UartException is raised when serial controller fails to open try: await self.uart.initialize_usb(serial_port) except UartException: self.uart = None # Set entry options for usb to null updated_options = self.config_entry.options.copy() updated_options[CONF_USB_PATH] = None updated_options[CONF_USB_SPHERE] = None # Ensure that the user can configure an USB again from options self.hass.config_entries.async_update_entry( self.config_entry, options=updated_options) # Show notification to ensure the user knows the cloud is now used persistent_notification.async_create( self.hass, f"Setup of Crownstone USB dongle was unsuccessful on port {serial_port}.\n \ Crownstone Cloud will be used to switch Crownstones.\n \ Please check if your port is correct and set up the USB again from integration options.", "Crownstone", "crownstone_usb_dongle_setup", ) return setup_uart_listeners(self) async def async_unload(self) -> bool: """Unload the current config entry.""" # Authentication failed if self.cloud.cloud_data is None: return True self.sse.close_client() for sse_unsub in self.listeners[SSE_LISTENERS]: sse_unsub() if self.uart: self.uart.stop() for subscription_id in self.listeners[UART_LISTENERS]: UartEventBus.unsubscribe(subscription_id) unload_ok = await self.hass.config_entries.async_unload_platforms( self.config_entry, PLATFORMS) if unload_ok: self.hass.data[DOMAIN].pop(self.config_entry.entry_id) return unload_ok @callback def on_shutdown(self, _: Event) -> None: """Close all IO connections.""" self.sse.close_client() if self.uart: self.uart.stop()
# from util import path from crownstone_uart.topics.DevTopics import DevTopics from crownstone_uart import CrownstoneUart, UartEventBus import sys, time, logging # from util.util import programCrownstone, findUsbBleDongleHciIndex, findUartAddress logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) uart = CrownstoneUart() def initLibs(): # import traceback # try: # address = findUartAddress() # if address == False: # print("Could not find Crownstone") # else: uart.initialize_usb_sync() # except: # print("----- ----- Error in settings UART Address", sys.exc_info()[0]) # traceback.print_exc() # print("tester not working, reboot test") def enableUart(): # enable UART print("----- Enabling UART...") uart._usbDev.setUartMode(3)
#!/usr/bin/env python3 import signal from crownstone_uart import CrownstoneUart, UartEventBus, UartTopics from crownstone_uart.topics.DevTopics import DevTopics from BluenetWebSocket import WebSocketServer from BluenetWebSocket.lib.connector.BluenetConnector import BluenetConnector from parser.WSParser import WSParser # Create new bluenet instance bluenet = CrownstoneUart() # Start up the USB bridge bluenet.initialize_usb_sync("/dev/ttyACM0") # start the websocket server server = WebSocketServer(9000) # connect the websocket server to bluenet lib server.connectToBluenet(bluenet, UartEventBus, UartTopics) connector = BluenetConnector() connector.connect(UartEventBus, DevTopics) # add our custom parser customParser = WSParser() customParser.connectToBluenet(bluenet) server.loadCustomParser(customParser.receiveWebSocketCommand)
# change it to match the Crownstone Id you want to switch! targetCrownstoneId = 3 def showNewData(data): global targetCrownstoneId if data.crownstoneId == targetCrownstoneId: print("New data received!") if data.type == AdvType.CROWNSTONE_STATE or data.type == AdvType.EXTERNAL_STATE: print( f"PowerUsage of crownstone {data.crownstoneId} is {data.powerUsageReal}W" ) print("-------------------") uart = CrownstoneUart() # Start up the USB bridge. uart.initialize_usb_sync() # you can alternatively do this async by # await uart.initialize_usb() # Set up event listeners UartEventBus.subscribe(UartTopics.newDataAvailable, showNewData) # Switch this Crownstone on and off. turnOn = True # The try except part is just to catch a control+c, time.sleep does not appreciate being killed. try: for i in range(0, 10):
from crownstone_core.packets.debug.RamStatsPacket import RamStatsPacket from crownstone_core.protocol.BlePackets import ControlStateGetPacket, ControlStateGetResultPacket, ControlPacket from crownstone_core.protocol.BluenetTypes import StateType, ResultValue, ControlType from crownstone_core.protocol.ControlPackets import ControlPacketsGenerator from crownstone_uart import CrownstoneUart, UartEventBus, UartTopics from crownstone_uart.core.dataFlowManagers.UartWriter import UartWriter from crownstone_uart.core.uart.UartTypes import UartMessageType, UartTxType from crownstone_uart.core.uart.uartPackets.UartCrownstoneHelloPacket import UartCrownstoneHelloPacket from crownstone_uart.core.uart.uartPackets.UartMessagePacket import UartMessagePacket from crownstone_uart.core.uart.uartPackets.UartWrapperPacket import UartWrapperPacket from crownstone_uart.topics.DevTopics import DevTopics #logging.basicConfig(format='%(levelname)-7s: %(message)s', level=logging.DEBUG) logging.basicConfig(format='%(levelname)-7s: %(message)s', level=logging.INFO) uart = CrownstoneUart() # Keep up the operation mode. stoneHasBeenSetUp = False def handleHello(data): helloResult = data logging.log(logging.DEBUG, f"flags={helloResult.status.flags}") global stoneHasBeenSetUp stoneHasBeenSetUp = helloResult.status.hasBeenSetUp logging.log(logging.DEBUG, f"stoneHasBeenSetUp={stoneHasBeenSetUp}") UartEventBus.subscribe(UartTopics.hello, handleHello)
#!/usr/bin/env python3 """An example that sets the current time in the Crownstone mesh.""" import asyncio import time from crownstone_core.util.Timestamp import getCorrectedLocalTimestamp from crownstone_uart import CrownstoneUart uart = CrownstoneUart() # Start up the USB bridge. async def run_example(): # create a connection with the crownstone usb dongle. await uart.initialize_usb() # In the Crownstone app, we usually set the local time, which is the timestamp with correction for the timezone # The only important thing is that you use the same timezone when you set certain time-related things as you use here. timestamp = time.time() local_timestamp = getCorrectedLocalTimestamp(timestamp) formattedtime = time.strftime("%Y/%m/%d %H:%M:%S",time.gmtime(local_timestamp)) print(F"setting time to: {local_timestamp}, (i.e. {formattedtime})") await uart.mesh.set_time(int(local_timestamp)) # stop the connection to the dongle uart.stop()
#!/usr/bin/env python3 """An example that switches a Crownstone, and prints the power usage of all Crownstones.""" import time # Create new instance of uart from crownstone_uart import CrownstoneUart, UartEventBus, UartTopics uart = CrownstoneUart() # Start up the USB bridge. uart.initialize_usb_sync() # you can alternatively do this async by # await uart.initialize_usb() # Function that's called when the power usage is updated. def showUartMessage(data): print("Received payload", data) # Set up event listeners UartEventBus.subscribe(UartTopics.uartMessage, showUartMessage) # the try except part is just to catch a control+c, time.sleep does not appreciate being killed. try: uart.uart_echo("HelloWorld") time.sleep(0.2) uart.uart_echo("HelloWorld") time.sleep(0.2)
def run(self): self.loop = asyncio.new_event_loop() self.uart = CrownstoneUart() # choose either sync, or async operation self.loop.run_until_complete(self.runIt())
from crownstone_uart import CrownstoneUart from bluenet_logs import BluenetLogs # Change this to the path with the extracted log strings on your system. logStringsFile = "/opt/bluenet-workspace/bluenet/build/default/extracted_logs.json" # Init bluenet logs, it will listen to events from the Crownstone lib. bluenetLogs = BluenetLogs() # Set the dir containing the bluenet source code files. bluenetLogs.setLogStringsFile(logStringsFile) # Init the Crownstone UART lib. uart = CrownstoneUart() uart.initialize_usb_sync(port="/dev/ttyACM0") # The try except part is just to catch a control+c to gracefully stop the UART lib. try: # Simply keep the program running. print(f"Listening for logs and using \"{logStringsFile}\" to find the log formats.") while True: time.sleep(1) except KeyboardInterrupt: pass finally: print("\nStopping UART..") uart.stop() print("Stopped")
# Keep up the operation mode. stoneHasBeenSetUp = False def handleHello(data): helloResult = data logging.log(logging.DEBUG, f"flags={helloResult.status.flags}") global stoneHasBeenSetUp stoneHasBeenSetUp = helloResult.status.hasBeenSetUp logging.log(logging.INFO, f"stoneHasBeenSetUp={stoneHasBeenSetUp}") UartEventBus.subscribe(UartTopics.hello, handleHello) # Start up the USB bridge. uart = CrownstoneUart() uart.initialize_usb_sync(port=args.device, writeChunkMaxSize=64) # Sphere specific settings: adminKey = "adminKeyForCrown" memberKey = "memberKeyForHome" basicKey = "basicKeyForOther" serviceDataKey = "MyServiceDataKey" localizationKey = "aLocalizationKey" meshAppKey = "MyGoodMeshAppKey" meshNetworkKey = "MyGoodMeshNetKey" ibeaconUUID = "1843423e-e175-4af0-a2e4-31e32f729a8a" sphereId = 1 # Stone specific settings: crownstoneId = 200
#!/usr/bin/env python3 """An example that prints all Crownstone IDs seen on the mesh.""" import time, json from crownstone_uart import CrownstoneUart, UartEventBus, UartTopics uart = CrownstoneUart() # Start up the USB bridge. uart.initialize_usb_sync() def showNewData(data): print("New data received!") print(json.dumps(data, indent=2)) print("-------------------") print("PING!") uart.uart_echo("PONG!") def showUartMessage(data): print("Received Uart Message " + data["string"]) # Set up event listeners UartEventBus.subscribe(UartTopics.newDataAvailable, showNewData) UartEventBus.subscribe(UartTopics.uartMessage, showUartMessage) print("Listening for Crownstones on the mesh, this might take a while.")
metavar='path', type=str, default=None, help='The UART device to use, for example: /dev/ttyACM0') args = argParser.parse_args() sourceFilesDir = args.sourceFilesDir # Init bluenet logs, it will listen to events from the Crownstone lib. bluenetLogs = BluenetLogs() # Set the dir containing the bluenet source code files. bluenetLogs.setSourceFilesDir(sourceFilesDir) # Init the Crownstone UART lib. uart = CrownstoneUart() uart.initialize_usb_sync(port=args.device) # The try except part is just to catch a control+c to gracefully stop the UART lib. try: # Simply keep the program running. print( f"Listening for logs and using files in \"{sourceFilesDir}\" to find the log formats." ) while True: time.sleep(1) except KeyboardInterrupt: pass finally: print("\nStopping UART..") uart.stop()
#!/usr/bin/env python3 """An example that prints all Crownstone IDs seen on the mesh.""" import time # Create new instance of Bluenet from crownstone_uart import CrownstoneUart uart = CrownstoneUart() # Start up the USB bridge. uart.initialize_usb_sync() # you can alternatively do this async by # await uart.initialize_usb() # List the ids that have been seen print("Listening for Crownstones on the mesh, this might take a while.") # the try except part is just to catch a control+c, time.sleep does not appreciate being killed. initial_time = time.time() try: while uart.running: time.sleep(2) ids = uart.get_crownstone_ids() print("Crownstone IDs seen so far:", ids, "after", round(time.time() - initial_time), "seconds") except KeyboardInterrupt: print("\nClosing example.... Thank you for your time!") except: print("\nClosing example.... Thank you for your time!") uart.stop()