#!/usr/bin/env python3 # -*- coding: utf-8 -*- """模拟下级平台(红山区平台 CF-HS)向本平台上报数据,验证批 1 + 批 2 的接入链路。 覆盖: 1. 车场基本信息 3 条(路侧 1 + 封闭 2) 2. 封闭车场车位汇总 1 条 3. 路侧泊位 100 条 4. 批 2:设备 20 台、出入口 6 条、收费 2 条、设备-泊位关联 10 条 5. 批 2 错误路径:泊位冲突 4002、解绑缺时间 4003、收费改挂 5001、字段非法 5002、 撤回 6002;出入口条数与 5.1 不一致 → 告警 2004 6. 同 requestId 重复提交 → 幂等回放(响应逐字节一致) 7. 签名用了别的路径 → 401 + 9003 用法: python3 scripts/dsp-smoke.py # 默认 http://127.0.0.1:48083 python3 scripts/dsp-smoke.py http://host:port 密钥只在进程内存里流转,不打印、不落盘。脚本可重复执行: 平台已存在时走一次「重置密钥」拿到新密钥,旧密钥保留 7 天双轨期。 """ import base64 import hashlib import hmac import json import sys import time import uuid import urllib.error import urllib.request BASE = (sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:48083").rstrip("/") ADMIN = BASE + "/admin-api" PREFIX = "/open-api/dsp/v1" PLATFORM_CODE = "CF-HS" PLATFORM_NAME = "红山区停车平台" def http(method, url, body=None, headers=None, timeout=20): data = None hdrs = dict(headers or {}) if body is not None: data = body if isinstance(body, bytes) else json.dumps(body, ensure_ascii=False).encode("utf-8") hdrs.setdefault("Content-Type", "application/json") req = urllib.request.Request(url, data=data, headers=hdrs, method=method) try: with urllib.request.urlopen(req, timeout=timeout) as resp: return resp.status, resp.read() except urllib.error.HTTPError as e: return e.code, e.read() def admin_call(method, path, token=None, body=None): headers = {"Authorization": "Bearer " + token} if token else {} status, raw = http(method, ADMIN + path, body, headers) payload = json.loads(raw.decode("utf-8")) if raw else {} if status != 200 or payload.get("code") != 0: raise SystemExit(f"管理端调用失败 {method} {path}: http={status} {payload.get('msg')}") return payload.get("data") def login(): data = admin_call("POST", "/system/auth/login", body={"username": "admin", "password": "admin123"}) return data["accessToken"] def ensure_platform(token): page = admin_call("GET", "/park/dsp-platform/page?platformCode=" + PLATFORM_CODE + "&pageSize=10", token) rows = page.get("list") or [] if rows: platform_id = rows[0]["id"] secret = admin_call("PUT", f"/park/dsp-platform/reset-key?id={platform_id}", token)["secretKey"] print(f" 平台已存在(id={platform_id}),已重置密钥取得双轨期新密钥") return platform_id, secret created = admin_call("POST", "/park/dsp-platform/create", token, { "platformCode": PLATFORM_CODE, "platformName": PLATFORM_NAME, "platformType": 1, "contactName": "红山区联系人", "contactPhone": "0476-0000000", "ipWhitelist": "127.0.0.1", "dataScope": "150402", "remark": "冒烟脚本创建", }) print(f" 已创建平台 id={created['id']}") return created["id"], created["secretKey"] def sign(secret, method, path, platform_code, timestamp, nonce, body_bytes): source = "\n".join([method, path, platform_code, timestamp, nonce, hashlib.sha256(body_bytes).hexdigest()]) key = base64.b64decode(secret) return hmac.new(key, source.encode("utf-8"), hashlib.sha256).hexdigest() def post_object(secret, path, request_id, items, sign_path=None): envelope = { "platformCode": PLATFORM_CODE, "requestId": request_id, "version": "1.1", "list": items, } body = json.dumps(envelope, ensure_ascii=False, separators=(",", ":")).encode("utf-8") ts = str(int(time.time() * 1000)) nonce = uuid.uuid4().hex signed_path = sign_path or (PREFIX + path) signature = sign(secret, "POST", signed_path, PLATFORM_CODE, ts, nonce, body) status, raw = http("POST", BASE + PREFIX + path, body, { "X-Platform-Code": PLATFORM_CODE, "X-Timestamp": ts, "X-Nonce": nonce, "X-Sign": signature, }) return status, raw def parks(): now = time.strftime("%Y-%m-%d %H:%M:%S") base = { "districtCode": "150402", "streetName": "西屯街道", "coordType": "WGS84", "availableBerthNum": 20, "specificBerthNum": 0, "shareBerthNum": 0, "deformBerthNum": 2, "chargePileNum": 4, "entranceNum": 1, "exitNum": 1, "openTime": "07:00-21:30", "serviceType": 1, "manageUnitName": "红山区智慧停车运营有限公司", "manageUnitCode": "91150402MA0XXXXXX1", "maintainUnit": "红山区城管局", "ownerName": "红山区人民政府", "ownType": 1, "staffNum": 6, "dataSource": 1, "infoServiceName": "赤峰中智", "infoServiceCode": "91150400MA0YYYYYY2", "updateTime": now, } park1 = dict(base, parkSn="HS-PL-0001", parkName="钢铁街路侧停车场", parkType=1, address="红山区钢铁街北侧", roadName="钢铁街", lon=118.887712, lat=42.267845, berthNum=100, contact="张三", contactPhone="13800000001", servicePhone="0476-1111111", feeSn="HS-FEE-01") park2 = dict(base, parkSn="HS-PL-0002", parkName="赤峰万达广场地下停车场", parkType=2, address="红山区迎宾大街 1 号", lon=118.901233, lat=42.269911, berthNum=300, contact="李四", contactPhone="13800000002", feeSn="HS-FEE-02", pictureUrl="https://park.example.com/p2.jpg") park3 = dict(base, parkSn="HS-PL-0003", parkName="红山区医院配建停车场", parkType=3, address="红山区解放街 9 号", lon=118.895001, lat=42.271002, berthNum=120, contact="王五", contactPhone="13800000003", ownType=2, rentEndDate="2029-12-31") return [park1, park2, park3] def summary(): return { "parkSn": "HS-PL-0002", "surfacePlaneNum": 100, "landPlaneNum": 180, "surfaceMechanicNum": 0, "landMechanicNum": 0, "selfWalkNum": 0, "operationalNum": 20, "berthNum": 300, "smallCarNum": 280, "largeCarNum": 20, "disabledBerthNum": 4, "newEnergyNum": 20, "chargePileNum": 10, "quickChargePileNum": 4, "slowChargePileNum": 6, "chargePileOperationUnit": "国网赤峰", "updateTime": time.strftime("%Y-%m-%d %H:%M:%S"), } def berths(): now = time.strftime("%Y-%m-%d %H:%M:%S") items = [] for i in range(1, 101): items.append({ "parkSn": "HS-PL-0001", "berthSn": f"GTB-{i:03d}", "areaCode": "HS-PL-0001-A01", "areaName": "钢铁街北侧 001-020", "berthType": 1 if i % 10 else 2, "berthStatus": 1, "roadPosition": "北侧", "direction": "车头朝东", "parkMode": "平行", "lon": 118.887700 + i * 0.00001, "lat": 42.267845, "isCharge": 1, "updateTime": now, }) return items def devices(): now = time.strftime("%Y-%m-%d %H:%M:%S") items = [] # 路侧 15 台地磁(不直接挂泊位,绑定关系走 5.7) for i in range(1, 16): items.append({ "parkSn": "HS-PL-0001", "deviceSn": f"HS-DV-{i:04d}", "deviceType": 1, "vendorName": "深圳中磁", "deviceName": f"钢铁街地磁 {i:02d}", "deviceModel": "DC-200", "installPosition": f"GTB-{i:03d} 车位中央", "relateStatus": 1, "workStatus": 1, "workTemperature": 26.5, "uploadInterval": 30, "threshold": 20, "reconnectInterval": 60, "reconnectNum": 3, "version": "1.2.3", "onlineTime": now, "updateTime": now, }) # 封闭车场 5 台高位视频(视频类必须有安装高度) for i in range(1, 6): items.append({ "parkSn": "HS-PL-0002", "deviceSn": f"HS-DV-01{i:02d}", "deviceType": 6, "vendorName": "杭州海康", "deviceName": f"万达地库高位视频 {i}", "deviceModel": "HK-V400", "installPosition": "B1 层入口通道", "installHeight": 4.5, "relateStatus": 1, "workStatus": 1, "version": "2.0.1", "updateTime": now, }) return items def entrances(): now = time.strftime("%Y-%m-%d %H:%M:%S") items = [ {"parkSn": "HS-PL-0002", "crSn": "CR-E01", "crName": "万达广场北入口", "crType": 1, "relateRoad": "迎宾大街", "lon": 118.901200, "lat": 42.269900, "deviceSn": "HS-DV-0101", "updateTime": now}, {"parkSn": "HS-PL-0002", "crSn": "CR-E02", "crName": "万达广场南出口", "crType": 2, "relateRoad": "迎宾大街", "lon": 118.901260, "lat": 42.269880, "deviceSn": "HS-DV-0102", "updateTime": now}, ] # HS-PL-0003 报文入口/出口各报 1 个(合计 2),这里报 4 条 → 一致性告警 2004 for i in range(1, 5): items.append({ "parkSn": "HS-PL-0003", "crSn": f"CR-N{i:02d}", "crName": f"医院出入口 {i}", "crType": 3, "relateRoad": "解放街", "lon": 118.895000, "lat": 42.271000, "updateTime": now, }) return items def rates(): now = time.strftime("%Y-%m-%d %H:%M:%S") return [ {"parkSn": "HS-PL-0001", "feeSn": "HS-FEE-01", "feeStandardType": "政府定价", "billingPeriod": "07:00-21:30,21:30-07:00", "timingUnit": "元/30分钟", "smallCarPrice": 2, "bigCarPrice": 3, "countPrice": 1, "freeMinutes": 15, "capDay": 20, "capOnce": 20, "singlePayDuration": 0, "singlePayPrice": 0, "detailed": "首 15 分钟免费,日间 2 元/30 分钟", "updateTime": now}, {"parkSn": "HS-PL-0002", "feeSn": "HS-FEE-02", "feeStandardType": "市场调节价", "billingPeriod": "00:00-24:00", "timingUnit": "元/小时", "smallCarPrice": 5, "bigCarPrice": 8, "freeMinutes": 30, "capDay": 50, "updateTime": now}, ] def device_berths(): now = time.strftime("%Y-%m-%d %H:%M:%S") items = [] for i in range(1, 11): items.append({ "parkSn": "HS-PL-0001", "deviceSn": f"HS-DV-{i:04d}", "berthSn": f"GTB-{i:03d}", "bindStatus": 1, "bindTime": now, "updateTime": now, }) return items def report(name, secret, path, request_id, items): status, raw = post_object(secret, path, request_id, items) payload = json.loads(raw.decode("utf-8")) data = payload.get("data") or {} print(f" {name:<14} http={status} code={payload.get('code')} " f"total={data.get('total')} success={data.get('success')} failed={data.get('failed')}") if payload.get("code") != 0: print(" msg:", payload.get("msg")) for item in (data.get("items") or [])[:5]: if item.get("code") != 0: print(f" ⚠ {item.get('bizKey')}: {item.get('code')} {item.get('msg')}") return status, raw, payload def main(): print("== 1. 登录与平台准入 ==") token = login() platform_id, secret = ensure_platform(token) stamp = time.strftime("%Y%m%d-%H%M%S") park_items = parks() park_request_id = f"hs-{stamp}-park-001" print("== 2. 上报静态数据 ==") report("车场 3 条", secret, "/park", park_request_id, park_items) report("车位汇总 1 条", secret, "/park-berth-summary", f"hs-{stamp}-summary-001", [summary()]) report("泊位 100 条", secret, "/berth", f"hs-{stamp}-berth-001", berths()) print("== 3. 批 2:设备 / 出入口 / 收费 / 关联 / 撤回 ==") report("设备 20 台", secret, "/device", f"hs-{stamp}-device-001", devices()) report("出入口 6 条", secret, "/entrance", f"hs-{stamp}-entrance-001", entrances()) report("收费 2 条", secret, "/rate", f"hs-{stamp}-rate-001", rates()) report("关联 10 条", secret, "/device-berth", f"hs-{stamp}-rel-001", device_berths()) # 冲突:GTB-001 已被 HS-DV-0001 占用,再绑 HS-DV-0011 → 4002 _, _, conflict = report("泊位冲突", secret, "/device-berth", f"hs-{stamp}-rel-conflict-001", [{ "parkSn": "HS-PL-0001", "deviceSn": "HS-DV-0011", "berthSn": "GTB-001", "bindStatus": 1, "updateTime": time.strftime("%Y-%m-%d %H:%M:%S"), }]) conflict_code = ((conflict.get("data") or {}).get("items") or [{}])[0].get("code") # 解绑缺 unbindTime → 4003 _, _, unbind_bad = report("解绑缺时间", secret, "/device-berth", f"hs-{stamp}-rel-unbind-bad-001", [{ "parkSn": "HS-PL-0001", "deviceSn": "HS-DV-0010", "berthSn": "GTB-010", "bindStatus": 0, "updateTime": time.strftime("%Y-%m-%d %H:%M:%S"), }]) unbind_bad_code = ((unbind_bad.get("data") or {}).get("items") or [{}])[0].get("code") # feeSn 改挂别的车场 → 5001 _, _, rate_mismatch = report("收费改挂", secret, "/rate", f"hs-{stamp}-rate-mismatch-001", [{ "parkSn": "HS-PL-0002", "feeSn": "HS-FEE-01", "smallCarPrice": 2, "freeMinutes": 15, "updateTime": time.strftime("%Y-%m-%d %H:%M:%S"), }]) rate_mismatch_code = ((rate_mismatch.get("data") or {}).get("items") or [{}])[0].get("code") # capDay < smallCarPrice → 5002 _, _, rate_invalid = report("收费字段非法", secret, "/rate", f"hs-{stamp}-rate-invalid-001", [{ "parkSn": "HS-PL-0001", "feeSn": "HS-FEE-03", "smallCarPrice": 5, "capDay": 1, "freeMinutes": 0, "updateTime": time.strftime("%Y-%m-%d %H:%M:%S"), }]) rate_invalid_code = ((rate_invalid.get("data") or {}).get("items") or [{}])[0].get("code") today = time.strftime("%Y-%m-%d") _, _, withdraw_ok = report("撤回车场", secret, "/park/withdraw", f"hs-{stamp}-withdraw-001", [{ "parkSn": "HS-PL-0003", "reason": "车场改造停运", "effectiveDate": today, "updateTime": time.strftime("%Y-%m-%d %H:%M:%S"), }]) withdraw_ok_code = ((withdraw_ok.get("data") or {}).get("items") or [{}])[0].get("code") _, _, withdraw_old = report("撤回日期过早", secret, "/park/withdraw", f"hs-{stamp}-withdraw-old-001", [{ "parkSn": "HS-PL-0001", "reason": "测试", "effectiveDate": "2026-01-01", "updateTime": time.strftime("%Y-%m-%d %H:%M:%S"), }]) withdraw_old_code = ((withdraw_old.get("data") or {}).get("items") or [{}])[0].get("code") print("== 4. 幂等回放 ==") first = post_object(secret, "/park", park_request_id, park_items) second = post_object(secret, "/park", park_request_id, park_items) same = first[1] == second[1] print(f" 同 requestId 两次响应一致:{same}(http={second[0]})") print("== 5. 签名路径不一致 ==") status, raw = post_object(secret, "/berth", f"hs-{stamp}-berth-bad-001", berths()[:1], sign_path="/open-api/dsp/v1/park") payload = json.loads(raw.decode("utf-8")) print(f" 改路径后验签:http={status} code={payload.get('code')} msg={payload.get('msg')}") print("== 6. 结论 ==") expect = { "泊位冲突 4002": (conflict_code, 4002), "解绑缺时间 4003": (unbind_bad_code, 4003), "收费改挂 5001": (rate_mismatch_code, 5001), "收费字段非法 5002": (rate_invalid_code, 5002), "撤回成功 0": (withdraw_ok_code, 0), "撤回日期过早 6002": (withdraw_old_code, 6002), } ok = same and status == 401 and payload.get("code") == 9003 for name, (actual, want) in expect.items(): hit = actual == want ok = ok and hit print(f" {name:<16} {'✓' if hit else '✗'} 期望 {want},实际 {actual}") print(" 幂等与签名行为符合预期" if ok else " ⚠️ 存在不符合预期的行为,请查 /tmp/yudao-server.log") return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())