Skip to content
28 changes: 16 additions & 12 deletions scene_common/src/scene_common/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# SPDX-License-Identifier: Apache-2.0

import json
import uuid
from jsonschema import FormatChecker
from fastjsonschema import compile

Expand All @@ -16,12 +17,17 @@ def __init__(self, schema_path, is_multi_message=False):
return

def compileValidators(self):
checker = FormatChecker()
formats = {}
for key in checker.checkers:
formatType = checker.checkers[key][0]
if key not in formats:
formats[key] = formatType
def validate_uuid(instance):
"""Validate UUID format (accepts UUIDv1-v5)"""
try:
uuid.UUID(instance)
return True
except (ValueError, AttributeError, TypeError):
raise ValueError(f"Invalid UUID format: {instance}")

formats = {
'uuid': validate_uuid,
}

if not self.mqtt_schema:
raise Exception("Schema not available")
Expand All @@ -35,20 +41,18 @@ def compileValidators(self):
defs_key: self.mqtt_schema[defs_key]
}
self.validator[key] = compile(sub_schema, formats=formats)
self.validator_no_format[key] = compile(sub_schema)
self.validator_no_format[key] = compile(sub_schema, formats=formats, use_formats=False)
else:
self.validator[None] = compile(self.mqtt_schema, formats=formats)
self.validator_no_format[None] = compile(self.mqtt_schema)
self.validator_no_format[None] = compile(self.mqtt_schema, formats=formats, use_formats=False)
return

def loadSchema(self, schema_path):
print("Loading schema file..")
try:
with open(schema_path) as schema_fd:
self.mqtt_schema = json.load(schema_fd)
print("Schema file loaded - {}".format(schema_path))
except:
print("Invalid schema file / could not open {}".format(schema_path))
except Exception as e:
print(f"Invalid schema file / could not open {schema_path}: {e}")
return

def validateMessage(self, msg_type, msg, check_format=False):
Expand Down
Loading