Skip to content

Commit

Permalink
Encode in json before sending first websocket message as well as extr…
Browse files Browse the repository at this point in the history
…a logging.
  • Loading branch information
GravySeal committed Apr 24, 2024
1 parent aacb468 commit 90defdd
Show file tree
Hide file tree
Showing 8 changed files with 34 additions and 20 deletions.
4 changes: 2 additions & 2 deletions bacnetinterface_dev/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<!-- https://developers.home-assistant.io/docs/add-ons/presentation#keeping-a-changelog -->

# 1.4.1b6
17/04/2024
# 1.4.1b7
24/04/2024

If there are any issues, please report on GitHub!

Expand Down
4 changes: 3 additions & 1 deletion bacnetinterface_dev/config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# https://developers.home-assistant.io/docs/add-ons/configuration#add-on-config

Check warning on line 1 in bacnetinterface_dev/config.yaml

View workflow job for this annotation

GitHub Actions / Lint add-on bacnetinterface_dev

'map' contains the 'config' folder, which has been replaced by 'homeassistant_config'. See: https://developers.home-assistant.io/blog/2023/11/06/public-addon-config

Check warning on line 1 in bacnetinterface_dev/config.yaml

View workflow job for this annotation

GitHub Actions / Lint add-on bacnetinterface_dev

'map' contains the 'config' folder, which has been replaced by 'homeassistant_config'. See: https://developers.home-assistant.io/blog/2023/11/06/public-addon-config

Check warning on line 1 in bacnetinterface_dev/config.yaml

View workflow job for this annotation

GitHub Actions / Lint add-on bacnetinterface_dev

'map' contains the 'config' folder, which has been replaced by 'homeassistant_config'. See: https://developers.home-assistant.io/blog/2023/11/06/public-addon-config

Check warning on line 1 in bacnetinterface_dev/config.yaml

View workflow job for this annotation

GitHub Actions / Lint add-on bacnetinterface_dev

'map' contains the 'config' folder, which has been replaced by 'homeassistant_config'. See: https://developers.home-assistant.io/blog/2023/11/06/public-addon-config

Check warning on line 1 in bacnetinterface_dev/config.yaml

View workflow job for this annotation

GitHub Actions / Lint add-on bacnetinterface_dev

'map' contains the 'config' folder, which has been replaced by 'homeassistant_config'. See: https://developers.home-assistant.io/blog/2023/11/06/public-addon-config
name: Bepacom BACnet/IP Interface Development Version
version: "1.4.1b6"
version: "1.4.1b7"
slug: bacnetinterface_dev
description: Bepacom BACnet/IP interface for the Bepacom EcoPanel. Allows BACnet/IP devices to be available to Home Assistant through an API
url: "https://github.com/Bepacom-Raalte/bepacom-HA-Addons/tree/main/bacnetinterface"
Expand Down Expand Up @@ -41,6 +41,7 @@ options:
slow_poll_list:
- all
entity_list: []
api_accessible: false
loglevel: WARNING
segmentation: segmentedBoth
schema:
Expand All @@ -62,6 +63,7 @@ schema:
- str?
entity_list:
- str?
api_accessible: bool?
foreignBBMD: str?
foreignTTL: str?
vendorID: int?
Expand Down
6 changes: 5 additions & 1 deletion bacnetinterface_dev/rootfs/etc/nginx/templates/ingress.gtpl
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ server {
allow {{ . }};
{{ end }}

# deny all;
{{if .accessible}}
allow all;
{{else}}
deny all;
{{end}}

# forward request to backend
location / {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ done
bashio::log.info "Allowed addresses for NGINX: ${ip_array[@]}"

bashio::var.json \
accessible "$(bashio::config 'api_accessible')" \
port "$(bashio::addon.port 80)" \
ip_array "^$(printf '%s\n' "${ip_array[@]}" | jq -R . | jq -s .)" \
| tempio \
Expand Down
6 changes: 0 additions & 6 deletions bacnetinterface_dev/rootfs/usr/bin/BACnetIOHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1153,8 +1153,6 @@ async def end_subscription_tasks(self):
async def do_ConfirmedCOVNotificationRequest(
self, apdu: ConfirmedCOVNotificationRequest
) -> None:
if _debug:
ChangeOfValueServices._debug("do_ConfirmedCOVNotificationRequest %r", apdu)

address = apdu.pduSource
subscriber_process_identifier = apdu.subscriberProcessIdentifier
Expand All @@ -1169,8 +1167,6 @@ async def do_ConfirmedCOVNotificationRequest(
if (not scm) or (
apdu.monitoredObjectIdentifier != scm.monitored_object_identifier
):
if _debug:
ChangeOfValueServices._debug(" - scm not found")
raise ServicesError(errorCode="unknownSubscription")

# queue the property values
Expand All @@ -1179,8 +1175,6 @@ async def do_ConfirmedCOVNotificationRequest(

# success
resp = SimpleAckPDU(context=apdu)
if _debug:
ChangeOfValueServices._debug(" - resp: %r", resp)

# return the result
await self.response(resp)
Expand Down
27 changes: 17 additions & 10 deletions bacnetinterface_dev/rootfs/usr/bin/webAPI.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,8 @@ async def webapp(request: Request):
for file in EDE_files:
dict_to_send = deep_update(dict_to_send, file)

dict_to_send = jsonable_encoder(dict_to_send)

return templates.TemplateResponse(
"index.html", {"request": request, "bacnet_devices": dict_to_send}
)
Expand Down Expand Up @@ -510,6 +512,8 @@ async def unsubscribe_objectid(deviceid: str, objectid: str):
async def websocket_endpoint(websocket: WebSocket):
"""This function will be called whenever a new client connects to the server."""
await websocket.accept()

LOGGER.debug(f"Accepted websocket: {websocket.url}")

# Start a task to write data to the websocket
write_task = asyncio.create_task(websocket_writer(websocket))
Expand All @@ -519,6 +523,7 @@ async def websocket_endpoint(websocket: WebSocket):
while True:
try:
data = await websocket.receive()
LOGGER.debug(f"Data received: {data}")
if data["type"] == "websocket.disconnect":
raise WebSocketDisconnect

Expand Down Expand Up @@ -565,20 +570,20 @@ async def websocket_endpoint(websocket: WebSocket):
else:
LOGGER.warning(f"message: {message} is not processed")

except (RuntimeError, asyncio.CancelledError) as error:
except (RuntimeError, asyncio.CancelledError) as err:
write_task.cancel()
activeSockets.remove(websocket)
LOGGER.error("Disconnected with RuntimeError or CancelledError...")
LOGGER.error(f"Disconnected with Exception... {err}")
return
except WebSocketDisconnect:
except WebSocketDisconnect as err:
write_task.cancel()
activeSockets.remove(websocket)
LOGGER.info("Disconnected websocket")
LOGGER.info(f"Disconnected websocket: {err}")
return
except Exception as e:
except Exception as err:
write_task.cancel()
activeSockets.remove(websocket)
LOGGER.error("Disconnected with Exception" + str(e) + "...")
LOGGER.error(f"Disconnected with Exception {err}")


async def websocket_writer(websocket: WebSocket):
Expand All @@ -588,7 +593,9 @@ async def websocket_writer(websocket: WebSocket):
if not is_valid_json(bacnet_device_dict):
LOGGER.warning(f"Websocket dict isn't converted to JSON'!")
else:
await websocket.send_json(bacnet_device_dict)
data_to_send = jsonable_encoder(bacnet_device_dict)
await websocket.send_json(data_to_send)
LOGGER.debug("Passed send_json test")
while True:
if events.val_updated_event.is_set():
dict_to_send = bacnet_device_dict
Expand All @@ -609,11 +616,11 @@ async def websocket_writer(websocket: WebSocket):
else:
await asyncio.sleep(1)

except asyncio.CancelledError as error:
LOGGER.debug(f"Websocket writer cancelled: {error}")
except asyncio.CancelledError as err:
LOGGER.debug(f"Websocket writer cancelled: {err}")

except WebSocketDisconnect as err:
LOGGER.info("Websocket disconnected")
LOGGER.info(f"Websocket disconnected: {err}")

except Exception as err:
LOGGER.error(f"Error during writing: {err}")
Expand Down
3 changes: 3 additions & 0 deletions bacnetinterface_dev/translations/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ configuration:
devices_setup:
name: Device Setup
description: Set up any devices you want to be treated differently. See docs for usage.
api_accessible:
name: Allow API access
description: Allow API access from outside of Home Assistant.
network:
47808/udp: BACnet port.
80/tcp: Port which the integration should connect to. If you leave this empty, the integration should connect to port 8099.
3 changes: 3 additions & 0 deletions bacnetinterface_dev/translations/nl.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ configuration:
devices_setup:
name: Apparaat configuratie
description: Configureer apparaten die appart behandeld moeten worden. Zie documentatie over hoe deze optie gebruikt moet worden.
api_accessible:
name: Toegang tot API toestaan
description: Sta toe dat de API toegankelijk is buiten Home Assistant.
network:
47808/udp: BACnet poort.
80/tcp: Poort waarmee de integration moet verbinden. Wanneer je deze poort leeg laat, moet de integration met poort 8099 verbinden.

0 comments on commit 90defdd

Please sign in to comment.