#!/usr/bin/env python3 # -*- coding: utf-8 -*- """用车订阅提醒:按规则定时统计某停车点附近的可用电动车,可选自动开锁。 - 每用户最多 5 条规则;规则 = 停车点(下拉) + 星期 + 时间(HH:MM) - 命中时发邮件:附近可用车辆数 + 可自动开锁的具体车辆编号 - auto_unlock:真实开锁链路(扫码 → 下单 → 开锁),带筛选/排序/冲突重试: * 车型筛选:小车 / 大车 / 红车(可多选) * 电量区间:min_electric ~ max_electric * 排序:电量从高到低(默认)/ 低到高 / 距离最近 * 冲突避让:所选车若被别人同时开走,自动换下一个候选,重试次数可配(默认 3) - 判定用最近 20 分钟内的采集点(每车取最新一条),坐标系与车辆一致(GCJ02)。 """ import datetime as dt import math import sqlite3 import random import threading import time from campus import bike_kind, bikes_near_parking, load_locations, parking_candidates from db import get_db from email_utils import send_email CHECK_INTERVAL = 30 # 调度精度:30 秒扫一次规则 CATCHUP_WINDOW_MIN = 5 # 补发窗口:超过这么久就不再补(避免晚上补发早上的提醒) SCAN_FRESH_MINUTES = 20 # 采集点新鲜度 MAX_RULES_PER_USER = 5 AUTO_UNLOCK_ENABLED = True # 自动开锁总开关(规则勾选 + 本开关同时为真才执行) VALID_KINDS = ("small", "big", "red") SORT_OPTIONS = { "electric_desc": "电量从高到低", "electric_asc": "电量从低到高", "distance_asc": "距离最近优先", } WEEKDAY_NAMES = {0: "每天", 1: "周一", 2: "周二", 3: "周三", 4: "周四", 5: "周五", 6: "周六", 7: "周日"} # ========== 规则校验 ========== def normalize_rule(data: dict) -> dict: """校验并标准化订阅规则输入(含自动开锁的筛选/排序/重试配置)。非法抛 ValueError。""" if not isinstance(data, dict): raise ValueError("规则格式不正确") try: location_id = int(data.get("location_id")) except (TypeError, ValueError): raise ValueError("请选择停车点") try: weekday = int(data.get("weekday", 0)) except (TypeError, ValueError): raise ValueError("星期格式不正确") if weekday not in WEEKDAY_NAMES: raise ValueError("星期仅支持 0(每天) 与 1-7") time_str = str(data.get("time", "")).strip() try: hh, mm = time_str.split(":") hour, minute = int(hh), int(mm) except (ValueError, TypeError): raise ValueError("时间格式应为 HH:MM") if not (0 <= hour <= 23 and 0 <= minute <= 59): raise ValueError("时间不在有效范围内") minute_of_day = hour * 60 + minute def _bool(name, default=False): v = data.get(name, default) if isinstance(v, bool): return v if v in (0, 1, "0", "1"): return str(v) == "1" if isinstance(v, str) and v.lower() in ("true", "false"): return v.lower() == "true" raise ValueError(f"{name} 必须是布尔值") # 车型筛选:小车/大车/红车(small/big/red),空=不限制(存全量) raw_kinds = data.get("kinds") if raw_kinds in (None, ""): kinds = ["small", "big", "red"] else: if isinstance(raw_kinds, str): raw_kinds = [k.strip() for k in raw_kinds.replace(",", ",").split(",") if k.strip()] kinds = [str(k).strip().lower() for k in raw_kinds if str(k).strip()] invalid = [k for k in kinds if k not in VALID_KINDS] if invalid: raise ValueError("车型仅支持 小车/大车/红车") if not kinds: kinds = ["small", "big", "red"] def _int_range(name, default, lo, hi): v = data.get(name, default) if v in (None, ""): return default try: v = int(float(v)) except (TypeError, ValueError): raise ValueError(f"{name} 必须是数字") if v < lo or v > hi: raise ValueError(f"{name} 须在 {lo} 到 {hi} 之间") return v min_e = _int_range("min_electric", 0, 0, 100) max_e = _int_range("max_electric", 100, 0, 100) if min_e > max_e: raise ValueError("电量下限不能大于上限") sort_by = str(data.get("sort_by") or "electric_desc").strip() if sort_by not in SORT_OPTIONS: raise ValueError("排序方式不支持") try: retry_times = int(data.get("retry_times", 3)) except (TypeError, ValueError): raise ValueError("重试次数必须是数字") retry_times = max(1, min(10, retry_times)) return { "location_id": location_id, "weekday": weekday, "minute_of_day": minute_of_day, "notify_enabled": _bool("notify_enabled", True), "auto_unlock": _bool("auto_unlock", False), "enabled": _bool("enabled", True), "kinds": ",".join(kinds), "min_electric": min_e, "max_electric": max_e, "sort_by": sort_by, "retry_times": retry_times, } def rule_filters(rule: dict) -> dict: """从库里的规则行解析出筛选参数(容错:老数据缺列时用默认值)。""" raw = str(rule.get("kinds") or "").strip() kinds = [k for k in raw.split(",") if k in VALID_KINDS] or ["small", "big", "red"] try: retry_times = max(1, min(10, int(rule.get("retry_times") or 3))) except (TypeError, ValueError): retry_times = 3 sort_by = str(rule.get("sort_by") or "electric_desc") if sort_by not in SORT_OPTIONS: sort_by = "electric_desc" try: min_e = int(rule.get("min_electric") if rule.get("min_electric") is not None else 0) except (TypeError, ValueError): min_e = 0 try: max_e = int(rule.get("max_electric") if rule.get("max_electric") is not None else 100) except (TypeError, ValueError): max_e = 100 return {"kinds": kinds, "min_electric": min_e, "max_electric": max_e, "sort_by": sort_by, "retry_times": retry_times} def count_user_rules(user_id: int) -> int: conn = get_db() row = conn.execute("SELECT COUNT(*) AS c FROM subscribe_rules WHERE user_id = ?", (user_id,)).fetchone() conn.close() return row["c"] if row else 0 # ========== 车辆统计 ========== def latest_bike_points(): """每辆车最近一条采集点(限定新鲜度窗口)。""" conn = get_db() try: rows = conn.execute(""" SELECT b.bike_code, b.latitude, b.longitude, b.state, b.status, b.electric FROM bike_history b JOIN ( SELECT bike_code, MAX(recorded_at) AS m FROM bike_history WHERE recorded_at >= datetime('now', '+8 hours', ?) GROUP BY bike_code ) x ON b.bike_code = x.bike_code AND b.recorded_at = x.m """, (f"-{SCAN_FRESH_MINUTES} minutes",)).fetchall() except Exception: rows = [] finally: conn.close() return [dict(r) for r in rows] def refresh_bike_points(user_id=None): """判定前拉一次最新地图(**只用 type=3 电动车**,别把单车混进候选)。 取数顺序:共享快照(60 秒,省上游) → 失败才用用户凭据直连一次。 `type=1` 是共享单车,它的车牌号段也会被判成「小车」,混进来会导致 「自动开锁开了一辆单车」和「附近有 12 辆其实 8 辆是单车」。 字段名用 `electric_quantity`(上游真实字段);写成 `electric` 会永远是 None,电量筛选就全部落空(≥50% 的规则会报「附近暂无符合条件的车辆」)。 """ from wechat import request_with_user_auth, request_api def _fetch(use_snapshot_only=False): try: res = request_api("GET", "/project/map", params={"type": "3"}) if isinstance(res, dict) and res.get("rtn_code") == 0: return res except Exception as exc: print(f"[订阅提醒] 快照读地图失败: {exc}") if use_snapshot_only or not user_id: return None try: res = request_with_user_auth(user_id, "GET", "/project/map", params={"type": "3"}, _silent=True) return res if isinstance(res, dict) and res.get("rtn_code") == 0 else None except Exception as exc: print(f"[订阅提醒] 用户凭据刷新地图失败: {exc}") return None res = _fetch() if res is None: time.sleep(0.6) # 上游 503/抖动:等半秒再试一次 res = _fetch() if res is None: return None rows = [] for st in ((res.get("data") or {}).get("bicycleStation") or []): lat, lng = st.get("latitude"), st.get("longitude") if lat is None or lng is None: continue electric = st.get("electric_quantity") if electric is None: electric = st.get("electricQuantity") if electric is None: electric = st.get("electric") rows.append({ "bike_code": str(st.get("code") or ""), "latitude": lat, "longitude": lng, "state": st.get("state"), "status": st.get("status"), "electric": electric, "bike_type": "3", }) return rows or None def stat_location(loc, user_id=None, fresh=True): """统计某个停车点附近的车辆。返回 None 表示该地点没有可用判定(缺坐标)。""" if loc is None: return None try: if loc.get("latitude") is None or loc.get("longitude") is None: return None except Exception: return None points = None if fresh: points = refresh_bike_points(user_id) if not points: points = latest_bike_points() return bikes_near_parking(points, loc) # ========== 自动开锁(真实链路) ========== def _near_coord(lat, lng, jitter=0.0001): """车辆坐标附近加随机抖动,模拟真实定位(避免每次上报同一精确点被判远程操作)。""" try: lat, lng = float(lat), float(lng) except (TypeError, ValueError): lat, lng = 36.67, 116.98 return (lat + random.uniform(-jitter, jitter), lng + random.uniform(-jitter, jitter)) def _live_coord(user_id: int, code: str, btype=None): """实时抓该车坐标(车会被骑走),返回 (lat, lng) 或 None。""" from wechat import request_with_user_auth types = [] if btype: types.append(str(btype)) for t in ("3", "1", "6"): if t not in types: types.append(t) for t in types: try: res = request_with_user_auth(user_id, "GET", "/project/map", params={"type": t}, _silent=True) except Exception: continue if res.get("rtn_code") != 0: continue for st in ((res.get("data") or {}).get("bicycleStation") or []): if str(st.get("code")) == str(code) and st.get("latitude") and st.get("longitude"): return st["latitude"], st["longitude"] return None def _discard_pending_order(user_id: int, order_id, code: str, lat=None, lng=None) -> bool: """下单成功但开锁失败:把这张半成品订单关掉。 不清理的话,下一次重试会再叠一张新订单 —— 上游会同时挂着几张 没人骑的订单,用户还可能被算未支付。 """ from wechat import request_with_user_auth data = {"order_id": order_id} if lat is not None and lng is not None: data.update({"latitude": lat, "longitude": lng, "code": code}) for path in ("/record/return", "/record/orderClose"): try: res = request_with_user_auth(user_id, "POST", path, data=data, _silent=True) except Exception as exc: print(f"[订阅开锁] 清理半成品订单 {order_id} 调 {path} 异常: {exc}") continue if isinstance(res, dict) and res.get("rtn_code") == 0: print(f"[订阅开锁] 半成品订单 {order_id} 已通过 {path} 关闭") return True msg = (res or {}).get("message") if isinstance(res, dict) else None print(f"[订阅开锁] 清理半成品订单 {order_id} 失败({path}): {msg}") return False def _try_auto_unlock(user_id: int, bike_code: str) -> dict: """真实自动开锁:扫码 → 创建订单 → 开锁(全部使用订阅人自己的凭据)。 返回 {"success": bool, "occupied": bool, "order_id": str|None, "message": str} occupied=True 表示「这辆车已被别人抢先」,调用方可换下一个候选重试。 """ from wechat import request_with_user_auth if not AUTO_UNLOCK_ENABLED: return {"success": False, "occupied": False, "message": "自动开锁总开关未开启"} code = str(bike_code or "").strip() if not code: return {"success": False, "occupied": False, "message": "车辆编号为空"} # 1) 扫码查车(同时判断车是否还在/是否已被占用) bike = request_with_user_auth(user_id, "POST", "/project/bicycle", data={"code": code}, _silent=True) if bike.get("rtn_code") != 0: msg = bike.get("message") or "查询车辆失败" occupied = any(k in msg for k in ("使用中", "占用", "已被", "骑行")) return {"success": False, "occupied": occupied, "message": msg} bike_data = bike.get("data") or {} if str(bike_data.get("status")) == "1": return {"success": False, "occupied": True, "message": "该车已被他人开锁(使用中)"} # 2) 下单坐标:优先实时地图坐标,取不到退回扫码坐标;两者都加抖动 live = _live_coord(user_id, code, bike_data.get("type")) if live: lat, lng = _near_coord(live[0], live[1]) else: lat, lng = _near_coord(bike_data.get("latitude", 36.67), bike_data.get("longitude", 116.98)) order = request_with_user_auth( user_id, "POST", "/record/order", data={"code": code, "start_longitude": lng, "start_latitude": lat}, _silent=True) if order.get("rtn_code") != 0 or not (order.get("data") or {}).get("order_id"): msg = order.get("message") or "创建订单失败" # 有未支付订单:尝试用月卡/周卡自动支付后重下一次 if "未支付" in msg or "待支付" in msg: try: from routes.rental import _try_card_pay_auto info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True) unpaid = (info.get("data") or {}).get("nonDealOrder") or {} if unpaid.get("order_id"): pay = _try_card_pay_auto(user_id, unpaid["order_id"], unpaid.get("code") or code) if pay.get("success"): order = request_with_user_auth( user_id, "POST", "/record/order", data={"code": code, "start_longitude": lng, "start_latitude": lat}, _silent=True) msg = order.get("message") or msg except Exception as exc: print(f"[订阅开锁] 自动卡支付异常: {exc}") if order.get("rtn_code") != 0 or not (order.get("data") or {}).get("order_id"): occupied = any(k in msg for k in ("使用中", "占用", "已被", "骑行", "锁定")) if order.get("rtn_code") == 102001: msg = "微信凭据已失效,请重新配置后再用自动开锁" return {"success": False, "occupied": occupied, "message": msg} order_id = order["data"]["order_id"] # 3) 开锁 opened = request_with_user_auth(user_id, "POST", "/record/qrOrder", data={"order_id": order_id}, _silent=True) if opened.get("rtn_code") != 0: # 半成品订单必须撤销,否则下一次重试会再叠一张 cleaned = _discard_pending_order(user_id, order_id, code, lat, lng) msg = opened.get("message") or "开锁指令失败" if cleaned: msg += "(已撤销本次下单)" else: msg += "(本次下单可能残留在上游,请稍后在订单页检查)" return {"success": False, "occupied": False, "order_id": str(order_id), "message": msg} # 4) 本地落单 + 计时器 + 起点位置(与手动开锁一致,source='subscribe') try: from db import get_user_rental_settings from timer import start_rental_timer settings = get_user_rental_settings(user_id) duration = int(settings["rental_duration_minutes"]) tz = dt.timezone(dt.timedelta(hours=8)) now = dt.datetime.now(tz) end = now + dt.timedelta(minutes=duration) conn = get_db() email = "" row = conn.execute("SELECT email FROM users WHERE id = ?", (user_id,)).fetchone() if row: email = row["email"] or "" try: conn.execute(""" INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time, duration, expired, source, renewal_round) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1) """, (int(order_id), str(order_id), code, email, user_id, now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"), duration)) except sqlite3.IntegrityError: # id 与历史行冲突(极少见):改用自增 id,order_id 仍记录真实订单号 conn.execute(""" INSERT INTO rentals (order_id, bike_code, email, user_id, start_time, end_time, duration, expired, source, renewal_round) VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1) """, (str(order_id), code, email, user_id, now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"), duration)) conn.commit() conn.close() start_rental_timer(rental_id=int(order_id), email=email, bike_code=code, duration_minutes=duration, user_id=user_id) try: from routes.rental import _record_rental_start _record_rental_start(int(order_id), lat, lng) except Exception as exc: print(f"[订阅开锁] 回填起点失败: {exc}") except Exception as exc: # 上游已开锁成功,本地记录失败不影响结果,但要留痕 print(f"[订阅开锁] 本地落单失败(上游已开锁): {exc}") return {"success": True, "occupied": False, "order_id": str(order_id), "lat": lat, "lng": lng, "message": "开锁成功"} def auto_unlock_with_retry(rule: dict, candidates: list, retry_times: int) -> dict: """按候选顺序尝试开锁:被他人抢先就换下一个,最多 retry_times 次。 返回 {"success": bool, "bike": dict|None, "attempts": [...], "message": str} """ attempts = [] tries = min(max(1, int(retry_times or 1)), max(1, min(len(candidates), 10))) for idx, cand in enumerate(candidates[:tries], start=1): code = cand["bike_code"] res = _try_auto_unlock(rule["user_id"], code) attempts.append({ "n": idx, "bike_code": code, "kind_label": cand.get("kind_label"), "electric": cand.get("electric"), "distance": cand.get("distance"), "success": bool(res.get("success")), "occupied": bool(res.get("occupied")), "message": res.get("message") or "", }) if res.get("success"): print(f"[订阅开锁] 成功: rule={rule['id']} 第{idx}次 车辆={code}") return {"success": True, "bike": cand, "attempts": attempts, "order_id": res.get("order_id"), "message": f"第 {idx} 次尝试成功"} # 非「被占用」类失败(如凭据失效/网络)没必要继续换车 if not res.get("occupied"): print(f"[订阅开锁] 中止: rule={rule['id']} 车辆={code} 原因={res.get('message')}") return {"success": False, "bike": None, "attempts": attempts, "message": res.get("message") or "开锁失败"} print(f"[订阅开锁] 避让: rule={rule['id']} 车辆={code} 被占用,换下一个候选") return {"success": False, "bike": None, "attempts": attempts, "message": "候选车辆均被他人抢先" if attempts else "没有符合条件的车辆"} # ========== 邮件 ========== def _render_html(title, lead, details): import html as _html rows = "".join( '
这是你订阅的定时车辆播报。