python send alarm_info

本文介绍了一个使用Python进行数据库操作并发送HTTP请求的例子。该程序通过pymysql库连接数据库,读取alarm表中的数据,并使用requests库向本地服务器发送POST请求。文章展示了如何构建动态URL参数及处理响应。
#!/usr/bin/python3

import pymysql
import requests


# 访问请求的方法
def requestUrl(result):
    id = str(result['id'])
    entName = str(result['entName'])
    warnType = str(result['warnType'])
    headers = {'Content-Type': 'application/json'}
    #datas = json.dumps({"id":"202009151111","entName": "织里安木童衣有限公司","entChartered": "","warnType": "2","supervisorName": "韦云飞","phoneNumber": "18868213106","address": "","warnInfo":"测试","areaStreet": "","areaCountry": "","occurTime": "2020-09-15 15:26:55"})
    param="id="+id+"&entName="+entName+"&entChartered&warnType="+warnType+"&supervisorName=韦云飞&phoneNumber=119&address&warnInfo=电流过大&areaStreet&areaCountry&occurTime=2020-07-28 20:30:21"
    url="http://localhost:8080/park/insert?"+param
    r = requests.post(url,headers=headers)
    print(r.text)



#主函数用法
if __name__ == '__main__':
    # 打开数据库连接
    db = pymysql.connect("xxx.xx.xxx.xxx", "xxx", "xxx+", "xxx")
    # 使用cursor()方法获取操作游标
    cursor = db.cursor(cursor = pymysql.cursors.DictCursor)
    # SQL 查询语句
    sql = "SELECT * FROM alarm "
    try:
        # 执行SQL语句
        cursor.execute(sql)
        # 获取所有记录列表
        results = cursor.fetchall()
        for result in results:
            requestUrl(result)
            id = result[0]
            entName = result[1]
            # 打印结果
            print("id=%s,entName=%s" % \
              (id, entName))
        total = cursor.rowcount
        print("总数: %s" % \
              (total))
        print("处理完成")
    except Exception as e:
        print(e)
        print("Error: unable to fetch data")
    # 关闭数据库连接
    db.close()


from machine import Pin, I2C, PWM, Timer import time import network import socket import onewire import ds18x20 from ssd1306 import SSD1306_I2C # OLED驱动库 # 硬件初始化(保持不变) led1 = Pin(3, Pin.OUT, Pin.PULL_DOWN) ds18b20 = ds18x20.DS18X20(onewire.OneWire(Pin(15))) i2c = I2C(0, scl=Pin(18), sda=Pin(19), freq=400000) oled = SSD1306_I2C(128, 64, i2c) buzzer = PWM(Pin(22)) alarm_led = Pin(23, Pin.OUT, value=0) motor = Pin(21, Pin.OUT, value=1) # WiFi配置(保持不变) ssid = "PRECHIN" password = "12345678" # 新增全局变量:系统启动状态(默认未启动) system_started = False # 关键修改① # 温度阈值等(保持不变) TEMP_THRESHOLD = 30.0 alarm_active = False led_blink_state = False # 报警LED闪烁定时器(保持不变) def toggle_alarm_led(timer): global led_blink_state if alarm_active and system_started: # 仅在系统启动时触发报警 led_blink_state = not led_blink_state alarm_led.value(led_blink_state) else: alarm_led.value(0) alarm_timer = Timer(1) alarm_timer.init(period=500, mode=Timer.PERIODIC, callback=toggle_alarm_led) def read_ds_sensor(): global alarm_active if not system_started: # 系统未启动时不读取传感器 buzzer.duty_u16(0) motor.value(1) return 0.0 # 原读取逻辑(保持不变) roms = ds18b20.scan() if not roms: print("未检测到DS18B20传感器") alarm_active = False return 0.0 ds18b20.convert_temp() time.sleep_ms(750) for rom in roms: temp = ds18b20.read_temp(rom) if isinstance(temp, float): temp_rounded = round(temp, 2) alarm_active = temp_rounded > TEMP_THRESHOLD if alarm_active: buzzer.freq(1000) buzzer.duty_u16(32768) else: buzzer.duty_u16(0) motor.value(0 if alarm_active else 1) return temp_rounded alarm_active = False return 0.0 def update_oled(temp): oled.fill(0) oled.text("Temp: {:.1f}C".format(temp), 0, 10) # 新增:显示系统启动状态 status = "STARTED" if system_started else "STOPPED" # 关键修改② oled.text("System: " + status, 0, 20) alarm_status = "ALARM!" if alarm_active else "Normal" oled.text("Alarm: " + alarm_status, 0, 30) oled.show() def wifi_connect(): # 保持不变 ... # 关键修改③:新增网页按钮生成逻辑 def web_page(): temp = read_ds_sensor() # 根据系统状态动态生成按钮文本和链接 button_text = "停止系统" if system_started else "启动系统" button_action = "stop" if system_started else "start" html = f"""<!DOCTYPE HTML><html><head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css"> <style> html {{ font-family: Arial; text-align: center; }} h2 {{ font-size: 2.0rem; }} p {{ font-size: 1.5rem; }} .alarm {{ color: red; font-weight: bold; }} .button {{ padding: 10px 20px; font-size: 1.2rem; background: {'#ff4444' if system_started else '#00C851'}; color: white; border-radius: 5px; text-decoration: none; }} </style></head><body> <h2>ESP32 温度监测系统</h2> <p>温度: {temp}°C</p> <p class="alarm">报警状态: {"ALARM!" if alarm_active else "正常"}</p> <a href="/?action={button_action}" class="button">{button_text}</a> <!-- 按钮链接 --> </body></html>""" return html if __name__ == "__main__": if wifi_connect(): my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) my_socket.bind(('', 80)) my_socket.listen(5) print("HTTP服务器启动,等待连接...") while True: try: temp = read_ds_sensor() update_oled(temp) client, addr = my_socket.accept() print(f"新连接: {addr}") request = client.recv(1024) # 关键修改④:解析请求中的启动/停止命令 if "GET /?action=start" in str(request): system_started = True print("系统已启动") elif "GET /?action=stop" in str(request): system_started = False print("系统已停止") response = web_page() client.send('HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close\n\n') client.sendall(response) client.close() except OSError as e: print(f"连接错误: {e}") if 'client' in locals(): client.close() time.sleep_ms(100) 加入在oled屏上显示WiFiIP
07-05
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

科学的N次方

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值