Package: crownstone-sse
crownstone-python-lib-sseAsynchronous Python library that listens to Crownstone SSE events.FunctionalityAsync: using asyncio and aiohttp, easy to integrate in existing projects.Multi-functional: Library provides an extra thread wrapper to run the client in sync context.Complete: Fully integrated event bus that can be used to listen to events, and run callbacks.RequirementsPython 3.8 or higherAiohttp 3.7Standard installationcd to the project folder and run:$pythonsetup.pyinstallInstall in a virtual environmentTo install the library execute the following command:$python-mvenvvenvActivate your venv using:$sourcevenv/bin/activateOnce activated, the venv is used to executed python files, and libraries will be installed in the venv.To install this library, cd to the project folder and run:$pythonsetup.pyinstallGetting startedAsynchronous exampleimportasyncioimportloggingfromcrownstone_sseimportCrownstoneSSEAsync# enable logginglogging.basicConfig(format='%(levelname)s:%(message)s',level=logging.DEBUG)asyncdefmain():# Create a new instance of Crownstone SSE client.# parameters:# email (string): your Crownstone account email.# password (string): your Crownstone account password.# access_token (string) [optional]: Access token from a previous login to skip the login step.# websession (aiohttp.ClientSession): provide the websession used in a project this is integrated in.# reconnection_time (int): time to wait before reconnection on connection loss.# project_name (string) [optional]: name of the project this is integrated in. This provides context to SSE logs in case of an error.client=CrownstoneSSEAsync(email="example@example.com",password="CrownstoneRocks",project_name="MyProject")# wait for the client to finish (means: blocking, run forever).awaitprocess_events(client)# to use this concurrently in an asyncio project, run this instead:# asyncio.create_task(process_events(client))asyncdefprocess_events(sse_client:CrownstoneSSEAsync):asyncwithsse_clientasclient:asyncforeventinclient:# prints string representation of the event.print(event)# optionally you can use the provided eventbus.# event_bus.fire(event.sub_type, event)# or access specific event details.# for example a switch state update:# print(event.switch_state)try:asyncio.run(main())exceptKeyboardInterrupt:passfinally:print("Crownstone SSE client finished. Thanks for your time!")The async client is meant to be used in an existing asyncio project. You can pass an existingaiohttp.ClientSessionobject to the client, and schedule the receiving of events in the running event loop by using:asyncio.create_task()as shown in the example above.Using an event busCrownstone SSE library provides a very complete event bus that can be used to schedule coroutines as well as callbacks.
Make sure to initiate the event bus within the event loop.
The eventbus can be initiated like so:fromcrownstone_sseimportEventBusbus=EventBus()Then you can create a coroutine to be executed upon receiving a specific event:asyncdefasync_update_local_switch_state(event:SwitchStateUpdateEvent):# exampleawaitcrownstone.update_state(event.switch_state)bus.add_event_listener(EVENT_CROWNSTONE_SWITCH_STATE_UPDATE,async_update_local_switch_state)The usage of the eventbus is optional here. You can also use an existing eventbus in your project.Synchronous exampleimportloggingfromcrownstone_sseimportCrownstoneSSEfromcrownstone_sse.eventsimport(SwitchStateUpdateEvent,SystemEvent,PresenceEvent,AbilityChangeEvent,DataChangeEvent,)fromcrownstone_sseimport(EVENT_ABILITY_CHANGE,EVENT_DATA_CHANGE,EVENT_PRESENCE,EVENT_PRESENCE_ENTER_LOCATION,EVENT_SWITCH_STATE_UPDATE,EVENT_SWITCH_STATE_UPDATE_CROWNSTONE,EVENT_SYSTEM,OPERATION_CREATE,OPERATION_DELETE,OPERATION_UPDATE,)# enable logging.logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.DEBUG)defswitch_update(event:SwitchStateUpdateEvent):ifevent.sub_type==EVENT_SWITCH_STATE_UPDATE_CROWNSTONE:print("Crownstone{}switch state changed to{}".format(event.cloud_id,event.switch_state))defnotify_stream_start(event:SystemEvent):print(event.message)defnotify_presence_changed(event:PresenceEvent):ifevent.sub_type==EVENT_PRESENCE_ENTER_LOCATION:print("User{}has entered location{}".format(event.user_id,event.location_id))defnotify_ability_changed(event:AbilityChangeEvent):print("Ability{}changed to{}".format(event.ability_type,event.ability_enabled))defnotify_data_changed(event:DataChangeEvent):ifevent.operation==OPERATION_CREATE:print("New data is available:{}".format(event.changed_item_name))ifevent.operation==OPERATION_UPDATE:print("Name of id{}has been updated to{}".format(event.changed_item_id,event.changed_item_name))ifevent.operation==OPERATION_DELETE:print("Data{}has been deleted".format(event.changed_item_name))# Create a new instance of Crownstone SSE client.# email (string): your Crownstone account email.# password (string): your Crownstone account password.# access_token (string) [optional]: Access token from a previous login to skip the login step.# reconnection_time (int): time to wait before reconnection on connection loss.# project_name (string) [optional]: name of the project this is integrated in. This provides context to SSE logs in case of an error.sse_client=CrownstoneSSE(email="example@example.com",password="CrownstoneRocks",project_name="MyProject")# Add listeners for event types of your liking, and the desired callback to be executed. see above.sse_client.add_event_listener(EVENT_SYSTEM,notify_stream_start)sse_client.add_event_listener(EVENT_SWITCH_STATE_UPDATE,switch_update)sse_client.add_event_listener(EVENT_PRESENCE,notify_presence_changed)sse_client.add_event_listener(EVENT_ABILITY_CHANGE,notify_ability_changed)sse_client.add_event_listener(EVENT_DATA_CHANGE,notify_data_changed)# Wait until the thread finishes.# You can terminate the thread by using SIGINT (ctrl + c or stop button in IDE).try:sse_client.join()exceptKeyboardInterrupt:sse_client.stop()This library can be used in synchronous context, and the example above will likely be the go-to option for most users.
You can use the Thread next to other synchronous Python code.If you want to let the client run forever, you can use:sse_client.join()As shown above. This will make the main thread wait till the sse_client thread is finished.
You should however always build in  a way to stop the client, you can do so by stopping onKeyboardInterruptas shown above.Creating callbacksCallbacks are functions that will be executed everytime an event comes in of an specific event type.The standard format for a callback is:defcallback(event:EventTypeClass):# do somethingEach event has it's own fields. It is recommended to provide the event type class hint to keep better track of which event it is, and what fields it has.For example:defcallback(event:PresenceEvent):print(event.user_id)print(event.location_id)You can add the listener like so:unsub=sse_client.add_event_listener(event_type,callback)This returns an unsubscribe function in case you want to remove the listener again. To do that, simply call:unsub()Event typesCurrently, there are 7 different event types:System eventCommand eventData change eventPresence eventSwitch state update eventAbility change eventPing eventSystem eventA system event is represented as:Typetypesub_typeSystemcodemessageSwitch command eventA switch command event is represented as:Typetypesub_typeSpheresphere_idCrownstonecloud_idunique_idswitch_val (as SwitchCommandValue)Multi Switch command eventA multi switch command event is represented as:Typetypesub_typeSpheresphere_idCrownstone listcrownstone_listEach crownstone in the list:cloud_idunique_idswitch_val (as SwitchCommandValue)Data change eventA data change event is represented as:operation (update | delete | create)Typetypesub_typeSpheresphere_idItemchanged_item_idchanged_item_namePresence eventA presence event is represented as:Typetypesub_typeSpheresphere_idLocationlocation_idUseruser_idSwitch state update eventA switch state update event is represented as:Typetypesub_typeSpheresphere_idCrownstonecloud_idunique_idswitch_state (percentage)Ability change eventAn ability change event is represented as:Typetypesub_typeSpheresphere_idCrownstonecloud_idunique_idAbilityability_typeability_enabledability_synced_to_crownstonePing eventA ping event is represented as:TypetypeCountercounterelapsed_time (in seconds)The ping event exists to notify the client that the connection is still alive, internally.You can however use it to check how long the connection has been alive as well.TestingTests are not available yet for this version. The client has however been live tested on the following:Logging in with Crownstone credentials.Establishing a connection to the Crownstone SSE server.Tested the connection staying alive for longer than 10 minutes (no total timeout).Tested client reconnection by manually disabling internet, waiting over 35 seconds, and turning it back on.Tested access token renewal by providing a short TTL on the access token when logging in.Safely closing the connection and exiting the loop after a manual stop is called, both and running and reconnecting state.