博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
esp8266 + dht11 + 两路继电器 实现pc远程控制开关机温度监控.并配置zabbix监控
阅读量:4311 次
发布时间:2019-06-06

本文共 8087 字,大约阅读时间需要 26 分钟。

事因:翻了翻自己之前的硬件小箱子,几年前买的一些小东西,想用用起来.

正好我有些数据放在机器上,有时候需要机器启动,我使用完成后在断开. 其实网络唤醒也能做到,但是机器一直给电也不好,在说家里有小孩AQA

设计思路.

使用双路继电器的一路控制主机AC220V电源的通断.ps[可以用一个GPIO读取pc电源的12v/5v供电来判断pc电源是否被断开.]

使用双路继电器的另一路模拟主机开机按钮. 用来开机和关机

硬件列表

esp8266 1个

dht11 1个

双路继电器 1个

杜邦线若干

改造电源线1个

git仓库地址:[之后有空重新写下代码]

915999-20190919182610604-46356520.png

其它在之后有空在补充吧.

mqtt 安装请参考:

在阿里云上安装Mosquitto

代码 [有若干逻辑bug,临时写的.]

//#define _TASK_SLEEP_ON_IDLE_RUN // Enable 1 ms SLEEP_IDLE powerdowns between tasks if no callback methods were invoked during the pass //#define _TASK_TIMEOUT#include 
#include
#include
#include "Adafruit_MQTT.h"#include "Adafruit_MQTT_Client.h"//**** dht initconst int pinDHT11 = 2;SimpleDHT11 dht11(pinDHT11);const int POWERPIN = 4;const int OPENBTPIN = 5;uint8_t poweroffTimeout=0;/************************* WiFi Access Point *********************************/#define WLAN_SSID "HOME"#define WLAN_PASS "HOME++++"/************************* Adafruit.io Setup *********************************/#define AIO_SERVER "ip"#define AIO_SERVERPORT 1883 // use 8883 for SSL#define AIO_USERNAME "user"#define AIO_KEY "pass"/************ Global State (you don't need to change this!) ******************/// Create an ESP8266 WiFiClient class to connect to the MQTT server.WiFiClient client;// or... use WiFiFlientSecure for SSL//WiFiClientSecure client;// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);/****************************** Feeds ***************************************/// Setup a feed called 'photocell' for publishing.// Notice MQTT paths for AIO follow the form:
/feeds/
Adafruit_MQTT_Publish temperaturePS = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/temperature");// Setup a feed called 'onoff' for subscribing to changes.Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/poweronoff");Adafruit_MQTT_Subscribe openbt = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/btonoff");int get_temperature();void pushTemperature();void clickBtStop();void set_powerOff();//void t2disable();// Task initScheduler runner;Task t1(1000,TASK_FOREVER,&pushTemperature);//Task t2(100,1,&clickBtStop,&runner,false,NULL,&set_powerOff);/*************************** Sketch Code ************************************/void clickBtStart(){ set_powerOn(); digitalWrite(OPENBTPIN,HIGH); delay(1300); digitalWrite(OPENBTPIN,LOW);}void clickBtStop(){ digitalWrite(OPENBTPIN,HIGH);// delay(8000); delay(1000); digitalWrite(OPENBTPIN,LOW); poweroffTimeout=90;// delay(120000L);// set_powerOff();// delay(200);// digitalWrite(OPENBTPIN,HIGH);// delay(8000);// digitalWrite(OPENBTPIN,LOW);}void set_powerOn(){ digitalWrite(POWERPIN,LOW); Serial.println("called set_powerOn "); poweroffTimeout=0;}void set_powerOff(){ digitalWrite(POWERPIN,HIGH); Serial.println("called set_poweroff "); poweroffTimeout=0;}int get_temperature() { byte temperature = 0; byte humidity = 0; int err = SimpleDHTErrSuccess; if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) { Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000); return 0; } Serial.print("Sample OK: "); Serial.print((int)temperature); Serial.print(" *C, "); Serial.print((int)humidity); Serial.println(" H"); return (int)temperature;}void pushTemperature(){ uint8_t t=0; for (int i=0;i<10;i++){ t=get_temperature(); if(t<=0){ t=0; }else { break; } } if (! temperaturePS.publish(t)) { Serial.println(F("Temperature publish Failed")); } else { Serial.println(F("Temperature publish OK!")); } if (poweroffTimeout>1){ poweroffTimeout--; Serial.println((int)poweroffTimeout); }else if (poweroffTimeout==1){ poweroffTimeout=0; set_powerOff(); }}// Bug workaround for Arduino 1.6.6, it seems to need a function declaration// for some reason (only affects ESP8266, likely an arduino-builder bug).void MQTT_connect();void setup() { pinMode(POWERPIN,OUTPUT); pinMode(OPENBTPIN,OUTPUT); Serial.begin(115200); delay(10); //digitalWrite(OPENBTPIN,HIGH);//init state Serial.println(F("Adafruit MQTT demo")); // Connect to WiFi access point. Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(WLAN_SSID); WiFi.begin(WLAN_SSID, WLAN_PASS); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); //task runner.init(); delay(50); runner.addTask(t1); // runner.addTask(t2);// delay(100); // Setup MQTT subscription for onoff feed. mqtt.subscribe(&onoffbutton); mqtt.subscribe(&openbt); t1.enable();}void loop() { // Ensure the connection to the MQTT server is alive (this will make the first // connection and automatically reconnect when disconnected). See the MQTT_connect // function definition further below. MQTT_connect(); // this is our 'wait for incoming subscription packets' busy subloop // try to spend your time here Adafruit_MQTT_Subscribe *subscription; int onoffstatus=0; while ((subscription = mqtt.readSubscription(5000))) { if (subscription == &onoffbutton) { Serial.print(F("Got onoffbutton: ")); onoffstatus=atoi((char *)onoffbutton.lastread); Serial.println(onoffstatus); if (onoffstatus >= 1){ set_powerOn(); }else { set_powerOff(); } }else if (subscription == &openbt) { Serial.print(F("Got openbt: ")); onoffstatus=0; onoffstatus=atoi((char *)openbt.lastread); Serial.println(onoffstatus); if (onoffstatus >= 1){ clickBtStart(); }else { clickBtStop();// t2.setTimeout(120 * TASK_SECOND);// t2.enable(); } } delay(100); } // Now we can publish stuff! runner.execute(); // ping the server to keep the mqtt connection alive // NOT required if you are publishing once every KEEPALIVE seconds /* if(! mqtt.ping()) { mqtt.disconnect(); } */}// Function to connect and reconnect as necessary to the MQTT server.// Should be called in the loop function and it will take care if connecting.void MQTT_connect() { int8_t ret; // Stop if already connected. if (mqtt.connected()) { return; } Serial.print("Connecting to MQTT... "); uint8_t retries = 3; while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected Serial.println(mqtt.connectErrorString(ret)); Serial.println("Retrying MQTT connection in 5 seconds..."); mqtt.disconnect(); delay(5000); // wait 5 seconds retries--; if (retries == 0) { // basically die and wait for WDT to reset me while (1); } } Serial.println("MQTT Connected!");}

arduino 模块

915999-20190919182626610-1542576216.png

使用arduino有问题.请参考https://blog.csdn.net/solar_lan/article/category/9277412

python push 温度数据到zabbix中

要安装paho-mqtt模块
pip install paho-mqtt

import paho.mqtt.client as mqttimport osMQTTHOST = "xxx.com"MQTTPORT = 1883mqttClient = mqtt.Client()mqttClient.username_pw_set('makeit', password='xxxx') # 连接MQTT服务器def on_mqtt_connect():    mqttClient.connect(MQTTHOST, MQTTPORT, 60)    mqttClient.loop_start()# publish 消息def on_publish(topic, payload, qos):    mqttClient.publish(topic, payload, qos)# 消息处理函数def on_message_come(lient, userdata, msg):    os.system('zabbix_sender -c "C:\Program Files\Zabbix Agent\zabbix_agentd.conf" -k hwtemp -o'+str(int(msg.payload)))    #print(msg.topic + " " + ":" + str(msg.payload))# subscribe 消息def on_subscribe():    mqttClient.subscribe("makeit/#", 1)    mqttClient.on_message = on_message_come # 消息到来处理函数def main():    on_mqtt_connect()    #on_publish("makeit/server", "Hello Python!", 1)    on_subscribe()    while True:        passif __name__ == '__main__':    main()

915999-20190921004252484-206630572.png

zabbix设置请参考

转载于:https://www.cnblogs.com/lovesKey/p/11551614.html

你可能感兴趣的文章
内存泄露调试之 visual leak detector 工具【转】...
查看>>
vmware converter linux p2v lvm
查看>>
js正则表达式中的exec
查看>>
官方文档-----》
查看>>
MySql的数据库文件
查看>>
找出一组数里出现频率最高的3个数(1.3)
查看>>
BigDecimal默认用四舍五入方式
查看>>
基于注解的SpringMVC
查看>>
Html+Css实现九大行星动画效果
查看>>
【20190405】JavaScript-整理一些常用正则式
查看>>
git 常用命令
查看>>
【光影魔术手】简单使用
查看>>
关于sqoop与datax。 和sqoop to oracle插件OraOop
查看>>
国内其他的maven库
查看>>
关于 控制反转与依赖注入 对初学者的一点帮助
查看>>
MySQL学习笔记(一)Ubuntu16.04中MySQL安装配置(5.6优化、错误日志、DNS解决)
查看>>
解决NLPIR汉语分词系统init failed问题
查看>>
袖珍C库
查看>>
深入理解JavaScript系列(10):JavaScript核心(晋级高手必读篇)
查看>>
Angularjs演示Service功能
查看>>