#!/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 秒扫一次规则 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 stat_location(loc): """统计某个停车点附近的车辆。返回 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 = 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 _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: return {"success": False, "occupied": False, "order_id": str(order_id), "message": opened.get("message") or "开锁指令失败"} # 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( '{}' '{}'.format( _html.escape(str(k)), _html.escape(str(v))) for k, v in details) return f"""
小白超人 · 车辆订阅

{_html.escape(title)}

{_html.escape(lead)}

{rows}

这是你订阅的定时车辆播报。

""" def _user_email(user_id): from db import get_user_alert_email return get_user_alert_email(user_id) def record_rule_result(rule_id, status, message): conn = get_db() conn.execute("UPDATE subscribe_rules SET last_run_at=datetime('now','+8 hours'), last_run_status=?, last_run_message=? WHERE id=?", (status, str(message)[:500], rule_id)) conn.commit() conn.close() def fire_rule(rule: dict): """执行一条规则:按筛选条件统计候选车辆;需要时自动开锁并邮件汇报。""" from db import get_user_alert_email locs = load_locations() loc = next((l for l in locs if l["id"] == rule["location_id"]), None) to_email = get_user_alert_email(rule["user_id"]) if rule.get("notify_enabled") and not to_email: record_rule_result(rule["id"], "failed", "未配置提醒邮箱") return False if loc is None: record_rule_result(rule["id"], "failed", "订阅停车点已删除") return False flt = rule_filters(rule) points = latest_bike_points() stat = bikes_near_parking(points, loc) # 候选:只含「符合车型/电量筛选」的空闲可用车,已按排序规则排好 candidates = parking_candidates( points, loc, kinds=flt["kinds"], min_electric=flt["min_electric"], max_electric=flt["max_electric"], sort_by=flt["sort_by"], limit=max(10, flt["retry_times"] + 5)) tz = dt.timezone(dt.timedelta(hours=8)) now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M") rule_desc = (f"每周{WEEKDAY_NAMES.get(rule['weekday'], '')} " if rule["weekday"] else "每天 ") + \ f"{rule['minute_of_day'] // 60:02d}:{rule['minute_of_day'] % 60:02d}" kind_desc = "/".join({"small": "小车", "big": "大车", "red": "红车"}[k] for k in flt["kinds"]) filter_desc = f"{kind_desc} · 电量 {flt['min_electric']}%-{flt['max_electric']}% · " \ f"{SORT_OPTIONS.get(flt['sort_by'], flt['sort_by'])}" unlock_result = None n_cand = len(candidates) if rule.get("auto_unlock") and candidates: unlock_result = auto_unlock_with_retry(rule, candidates, flt["retry_times"]) # ---------- 组邮件 ---------- if unlock_result and unlock_result.get("success"): bike = unlock_result["bike"] title = f"已自动开锁 #{bike['bike_code']}({bike.get('kind_label')})" lead = (f"你订阅的时刻到了,{loc['name']}附近符合条件的有 {n_cand} 辆," f"系统已按「{SORT_OPTIONS.get(flt['sort_by'])}」为你开锁 " f"#{bike['bike_code']}。到点会自动还车并用优惠卡支付。") elif unlock_result: title = f"{loc['name']}附近自动开锁未成功" lead = (f"符合条件的有 {n_cand} 辆,但本次自动开锁失败:" f"{unlock_result.get('message')}。可手动到页面开锁。") elif n_cand > 0: title = f"{loc['name']}附近有 {n_cand} 辆符合条件" lead = f"你订阅的时刻到了:{loc['name']}附近有 {n_cand} 辆符合你的筛选条件,快去开锁吧。" else: title = f"{loc['name']}附近暂无符合条件的车辆" lead = (f"你订阅的时刻到了:{loc['name']}附近最近 {SCAN_FRESH_MINUTES} 分钟内共 " f"{stat['total']} 辆车,但没有符合「{filter_desc}」的空闲车。") details = [("订阅地点", loc["name"]), ("规则", rule_desc), ("筛选条件", filter_desc), ("播报时间", now_str), ("符合条件", f"{n_cand} 辆"), ("附近总数", f"{stat['total']} 辆(可用 {stat['available']})")] if candidates: top = candidates[:5] details.append(("候选车辆", "、".join( f"#{c['bike_code']}({c['kind_label']} {c['electric']:.0f}% {c['distance']}m)" for c in top))) if unlock_result: if unlock_result.get("success"): bike = unlock_result["bike"] details.append(("已开锁车辆", f"#{bike['bike_code']}({bike['kind_label']})")) details.append(("车辆电量", f"{bike['electric']:.0f}%")) details.append(("距停车点", f"{bike['distance']} 米")) if unlock_result.get("order_id"): details.append(("订单号", str(unlock_result["order_id"]))) attempts = unlock_result.get("attempts") or [] if len(attempts) > 1 or not unlock_result.get("success"): detail_lines = [] for a in attempts: flag = "成功" if a["success"] else ("被占用,已避让" if a["occupied"] else "失败") detail_lines.append(f"第{a['n']}次 #{a['bike_code']}:{flag}" + ("" if a["success"] else f"({a['message']})")) details.append(("尝试记录", ";".join(detail_lines))) plain = f"{title}\n\n{lead}\n\n" + "\n".join(f"{k}:{v}" for k, v in details) html_body = _render_html(title, lead, details) delivered = send_email(to_email, f"【小白超人】{title}", plain, html_body) if rule.get("notify_enabled") else True status = "failed" if (unlock_result and not unlock_result.get("success")) or not delivered else "success" if candidates else "no_match" message = title + (";邮件发送失败,请检查提醒邮箱和服务配置" if not delivered else "") record_rule_result(rule["id"], status, message) return status != "failed" # ========== 调度 ========== def _scheduler_loop(): while True: try: _tick() except Exception as e: print(f"[订阅提醒] 调度异常: {e}") time.sleep(CHECK_INTERVAL) def _tick(): tz = dt.timezone(dt.timedelta(hours=8)) now = dt.datetime.now(tz) today = now.strftime("%Y-%m-%d") weekday = now.isoweekday() minute_of_day = now.hour * 60 + now.minute conn = get_db() rules = conn.execute(""" SELECT * FROM subscribe_rules WHERE enabled = 1 AND weekday IN (0, ?) AND minute_of_day = ? AND last_fired_on != ? """, (weekday, minute_of_day, today)).fetchall() if not rules: conn.close() return # 先占位再发送,避免重试窗口内重复触发 for r in rules: conn.execute("UPDATE subscribe_rules SET last_fired_on = ? WHERE id = ?", (today, r["id"])) conn.commit() conn.close() for r in rules: rule = dict(r) if not rule.get("notify_enabled") and not rule.get("auto_unlock"): continue try: record_rule_result(rule["id"], "running", "正在检查符合条件的车辆") ok = fire_rule(rule) except Exception as e: ok = False record_rule_result(rule["id"], "failed", "执行失败,请检查凭证有效期和网络后重试") print(f"[订阅提醒] 规则 {rule['id']} 执行失败: {type(e).__name__}") print(f"[订阅提醒] 规则 {rule['id']} 已触发 (user={rule['user_id']}, 发送={ok})") def start_subscribe_scheduler(): t = threading.Thread(target=_scheduler_loop, daemon=True, name="subscribe-scheduler") t.start() print(f"[订阅提醒] 调度已启动(每 {CHECK_INTERVAL}s 扫描一次)")