ESP32设备——监测股票交易价格拨打电话提醒(后附代码)

功能概述:

**事件:**监控沪深两市某股票的实时交易情况

(确保该股票在列表http://api.biyingapi.com/hslt/list/biyinglicence里,ctrl+f查询关键词)

以**"国华网安"** 为例,"dm":"000004","mc":"国华网安","jys":"sz"

https://api.biyingapi.com/hsrl/ssjy/**000004**/52F1AC58-A19D-4C24-BDAA-2C8506610C93

**时间间隔:**5分钟(代码运行,每隔5分钟自动发送http请求查询相关数据)

**返回值:**每查询一次就返回一次该时间的p值(当前价格)

4G模自动拨打电话**条件:**当前返回p值>上一次返回p值


代码的一个概要(大佬可忽略这部分):

1.导入库:导入python的requests库(http客户端库),用于发送各种http请求

2.发送请求:使用requests库的get方法向指定的URL(API接口)发送一个HTTP GET请求

定义一个变量response来存储这个请求响应

3.获取响应内容:发送http请求返回格式为标准json格式

将响应内容赋值给变量jsstr

4.打印响应内容:打印获取的原始字符串数据jsstr

5.json 格式转换:将JSON格式的字符串jsstr转换为Python的字典对象,赋值给变量data,使用Python的json模块中的loads函数

6.获取p :打印出字典对象data中键为'p'的值

7.循环该请求操作间隔时间为5分钟

8.每次获取的当前p值与上次进行比较,如果当前p值大于上次p值,则自动拨打电话号为111****1111的11位电话号,拨打过去持续十秒然后挂断电话。

9.一次循环操作操作:查询p,比较p,符合条件拨打电话,拨打未接听状态时间持续十秒,然后自动挂断。


功能实现步骤:

  1. 连接板子
  2. 修改代码中的json内容:路由器账号及密码,拨打的手机号等内容,修改完成保存
  3. 给4G模块上传文件中的代码
  4. 使用串口调试工具,连接后,可查看每次返回的数据,达到上述指定条件将自动拨打电话,响铃6s后自动挂断
  5. 可根据自己需求修改代码

代码

主程序main.py

python 复制代码
#main.py

import requests
import json
import time
from machine import UART
from wificonnect import wifi_connect

uart1 = UART(2, baudrate=115200, tx=16, rx=17, timeout=10)

def load_config():
    with open('config.json', 'r') as f:
        return json.load(f)

config = load_config()
PHONE_NUMBER = config['phone_number']
STOCK_API_URL = config['stock_api_url']

def send_cmd(command):
    print(f"Sending command: {command}")
    uart1.write(command + '\r\n')

def ping():
    send_cmd('AT')

def call_phone(phnum=PHONE_NUMBER):
    if len(phnum) != 11:
        print("Wrong phone number, not 11 digits long")
        return
    print(f"Making a call to: {phnum}")
    send_cmd(f'ATD{phnum};')
    time.sleep(30)
    off_call()

def off_call():
    send_cmd('AT+CHUP')
    print("Phone call ended")

def fetch_stock_price():
    try:
        response = requests.get(STOCK_API_URL)
        data = response.json()
        p_value = float(data['p'])
        print(f"Current price: {p_value}")
        return p_value
    except Exception as e:
        print(f"Error fetching stock price: {e}")
        return None

last_p_value = None

def monitor_stock():
    global last_p_value
    while True:
        current_p_value = fetch_stock_price()
        if current_p_value is not None:
            if last_p_value is not None and current_p_value > last_p_value:
                call_phone()
            last_p_value = current_p_value
        time.sleep(300)

if __name__ == "__main__":
    print("Connecting to Wi-Fi...")
    if wifi_connect():
        print("Wi-Fi connected. Monitoring stock prices...")
        ping()
        monitor_stock()
    else:
        print("Wi-Fi connection failed.")

联网代码wificonnect.py

python 复制代码
#联网
# wificonnect.py


import network
import time
import json

def load_config():
    with open('config.json', 'r') as f:
        return json.load(f)

def wifi_connect():
    config = load_config()
    ssid = config['wifi_ssid']
    password = config['wifi_password']

    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)

    if not wlan.isconnected():
        print(f'Connecting to network {ssid}...')
        wlan.connect(ssid, password)
        start_time = time.time()

        while not wlan.isconnected():
            if time.time() - start_time > 10:
                print("WiFi connection timeout")
                return False
            time.sleep(1)

    print('Network connected:', wlan.ifconfig())
    return True

if __name__ == "__main__":
    wifi_connect()

配置文件config.json

javascript 复制代码
{
    "wifi_ssid": "wifi名字",
    "wifi_password": "wifi密码",
    "phone_number": "接收来电提醒的手机号",
    "stock_api_url": "https://api.biyingapi.com/hsrl/ssjy/000004/52F1AC58-A19D-4C24-BDAA-2C8506610C93"
}

Gitee 源码地址:

mage (woodcol) - Gitee.com

相关推荐
呱牛do it1 天前
企业级门户网站设计与实现:基于SpringBoot + Vue3的全栈解决方案(Day 3)
java·vue
神の愛1 天前
左连接查询数据 left join
java·服务器·前端
大龄程序员狗哥1 天前
第25篇:Q-Learning算法解析——强化学习中的经典“价值”学习(原理解析)
人工智能·学习·算法
陶陶然Yay1 天前
神经网络常见层Numpy封装参考(5):其他层
人工智能·神经网络·numpy
极客老王说Agent1 天前
2026实战指南:如何用智能体实现药品不良反应报告的自动录入?
人工智能·ai·chatgpt
imbackneverdie1 天前
本科毕业论文怎么写?需要用到什么工具?
人工智能·考研·aigc·ai写作·学术·毕业论文·ai工具
南境十里·墨染春水1 天前
linux学习进展 线程同步——互斥锁
java·linux·学习
雨奔1 天前
Kubernetes 联邦 Deployment 指南:跨集群统一管理 Pod
java·容器·kubernetes
杨凯凡1 天前
【021】反射与注解:Spring 里背后的影子
java·后端·spring
lulu12165440781 天前
Claude Code项目大了响应慢怎么办?Subagents、Agent Teams、Git Worktree、工作流编排四种方案深度解析
java·人工智能·python·ai编程