82 lines
3.3 KiB
Python
82 lines
3.3 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},
|
||
|
|
"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
|
||
|
|
def validate_config(config):
|
||
|
|
"""验证配置是否符合规范"""
|
||
|
|
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
|