91 lines
3.8 KiB
Python
91 lines
3.8 KiB
Python
import json
|
||
from jsonschema import validate, Draft7Validator, FormatChecker
|
||
|
||
class ConfigValidator:
|
||
"""配置文件验证器"""
|
||
|
||
SCHEMA = {
|
||
"type": "object",
|
||
"properties": {
|
||
"plcs": {
|
||
"type": "array",
|
||
"minItems": 1,
|
||
"items": {
|
||
"type": "object",
|
||
"properties": {
|
||
"name": {"type": "string", "minLength": 1},
|
||
"ip": {"type": "string", "format": "ipv4"},
|
||
"rack": {"type": "integer", "minimum": 0},
|
||
"slot": {"type": "integer", "minimum": 0},
|
||
"refresh_interval": {
|
||
"type": "number",
|
||
"minimum": 0.01,
|
||
"default": 0.5
|
||
},
|
||
"areas": {
|
||
"type": "array",
|
||
"minItems": 1,
|
||
"items": {
|
||
"type": "object",
|
||
"properties": {
|
||
"name": {"type": "string", "minLength": 1},
|
||
"type": {"type": "string", "enum": ["read", "write", "read_write"]},
|
||
"db_number": {"type": "integer", "minimum": 1},
|
||
"offset": {"type": "integer", "minimum": 0},
|
||
"size": {"type": "integer", "minimum": 1},
|
||
"structure": {
|
||
"type": "array",
|
||
"items": {
|
||
"type": "object",
|
||
"properties": {
|
||
"name": {"type": "string"},
|
||
"type": {"type": "string", "enum": ["bool", "byte", "int", "dint", "real", "word", "dword"]},
|
||
"offset": {"type": "integer", "minimum": 0},
|
||
"bit": {"type": "integer", "minimum": 0, "maximum": 7} # 修复了这里
|
||
},
|
||
"required": ["name", "type", "offset"]
|
||
}
|
||
}
|
||
},
|
||
"required": ["name", "type", "db_number", "offset", "size"]
|
||
}
|
||
}
|
||
},
|
||
"required": ["name", "ip", "rack", "slot", "areas"]
|
||
}
|
||
}
|
||
},
|
||
"required": ["plcs"]
|
||
}
|
||
|
||
"""
|
||
@staticmethod:静态方法装饰器,使validate_config不依赖于类的实例,可以通过类直接调用
|
||
如ConfigValidator.validate_config(config)
|
||
"""
|
||
@staticmethod
|
||
def validate_config(config):
|
||
"""使用JSONSchema验证配置是否符合规范"""
|
||
try:
|
||
# 添加IPv4格式验证
|
||
validator = Draft7Validator(
|
||
ConfigValidator.SCHEMA,
|
||
format_checker=FormatChecker(["ipv4"])
|
||
)
|
||
validator.validate(config)
|
||
return True, None
|
||
except Exception as e:
|
||
return False, str(e)
|
||
|
||
@staticmethod
|
||
def is_valid_ip(ip):
|
||
"""验证IP地址格式"""
|
||
parts = ip.split('.')
|
||
if len(parts) != 4:
|
||
return False
|
||
for part in parts:
|
||
if not part.isdigit():
|
||
return False
|
||
num = int(part)
|
||
if num < 0 or num > 255:
|
||
return False
|
||
return True |