الدفيئة الذكية في برقية

مساء الخير على موقعنا يوجد دفيئة. مشكلتها الرئيسية هي ارتفاع درجة الحرارة في الطقس الحار ، مثل صمم في المقام الأول لربيع سيبيريا. المخرج الوحيد هو فتح / إغلاق الأبواب والنوافذ باستمرار للحفاظ على درجة الحرارة. لكن هذا ليس ممكنًا دائمًا. وإذا لم يتم ذلك ، ترتفع درجة الحرارة إلى +50 درجة ، وهو أمر غير جيد بشكل واضح. وفي المساء يمكن تجميد كل شيء. وهكذا بدأ التشغيل الآلي لها.

image

بادئ ذي بدء ، اشترينا Raspberry Pi 2. بعد أن تعاملنا معه ، قمنا بتوصيل مستشعر DS18B20 لهذه المقالة . ثم تم شراء نافذتين للسيارات المستعملة. مثل جميع محركات التيار المستمر ، تتحرك وفقًا للقطبية. لذلك ، نقوم بتوصيل مرحلين لكل محرك: أحدهما للفتح والآخر للإغلاق. نحن بالفعل نربط هذه المرحلات من خلال الترانزستورات بمنافذ GPIO نفسها. ونطعم هذا الأمر كله ببطارية 12 فولت. أيضًا ، حتى لا تحرق المحركات ، تم تثبيت مفاتيح الحد في المواضع المتطرفة للنافذة ، وإذا تم فتح / إغلاق النافذة ، فإن الشبكة ممزقة تمامًا.

image

image

وللتواصل ، نستخدم محول واي فاي TP-LINK مع هوائي مزدوج مربع متقدم لاستقبال موثوق به لشبكة WIFI المجاورةجهاز التوجيه WIFI المنزلي ، والذي يقع على مسافة 40 مترًا.

image

الآن نكتب برنامجًا للتحكم في محركات الأقراص هذه. تم اختيار Python ، لأنه يحتوي على دعم عادي لمنافذ Raspberry Pi ومنافذ GPIO على وجه التحديد. من أجل فتح النافذة ، نحتاج إلى تطبيق + 3.3V على الترانزستور ، الذي ينشط التتابع ، ومن ثم سيبدأ في فتح النافذة. لإغلاقه ، نفعل الشيء نفسه ، فقط في هذه الحالة يتم توصيل مرحلتنا مقابل محرك الأقراص. ولكن في Raspberry ، نقوم ببساطة بتطبيق التيار على منفذ واحد أو آخر. قررنا أنه إذا كانت درجة الحرارة أكثر من 26 ، فإننا نفتح النافذة لمدة ثانية واحدة. ثم ننتظر 3 دقائق. إذا كانت ساخنة مرة أخرى ، فافتح النافذة الثانية في غضون ثانية. نحن ننتظر مرة أخرى لمدة 3 دقائق ، ونفعل ذلك مرة أخرى. الشيء نفسه مع الإغلاق ، هنا فقط يجب أن تكون درجة الحرارة أقل من 24 درجة. وإليك الرمز:

temp.py
import RPi.GPIO as GPIO
import time
import os
import datetime

GPIO.setmode(GPIO.BOARD)
GPIO.cleanup()
GPIO.setup(31, GPIO.OUT)
GPIO.setup(33, GPIO.OUT)
GPIO.setup(35, GPIO.OUT)
GPIO.setup(37, GPIO.OUT)

# 
def gettemp():
  if os.path.isdir("id "): #  ,   
    tfile2=open("/sys/bus/w1/devices/id ")
    ttext2=tfile2.read()
    tfile2.close()
    temp2=ttext2.split("\n")[1].split(" ")[9]
    t2=float(temp2[2:])/1000
    print t2
  else: # ,   
    print ('File not found')
    t2==24
  return t2

t2=24 #    
while True:  
t2=gettemp()
  if    t2<24: #   24,      
 
        GPIO.output(37, 1)
        print ("close1")
        time.sleep(1)
        GPIO.output(37, 0)

  elif  t2>26: #  26,      
        GPIO.output(35, 1)
        print ("open1")
        time.sleep(2)
        GPIO.output(35, 0)
        
  else: #   
        print ("none1")
  time.sleep(180)# 3 

#  
t2=gettemp()

#   ,    .
  if    t2<24:
        GPIO.output(33, 1)
        print ("close2")
        time.sleep(1)
        GPIO.output(33, 0)

  elif  t2>26:
  
        GPIO.output(31, 1)
        print ("open2")
        time.sleep(1)
        GPIO.output(31, 0)
     

  else:
        print ("none2")


#  3 
  time.sleep(180)



, .

بعد تثبيت Apache على توزيع Raspbian ، لم نتمكن من الوصول إلى الصفحة من الإنترنت لمدة شهر. ما لم يفعل ذلك. قم بإعداد المنافذ ، افتحها ، لا شيء ساعد. علاوة على ذلك ، عمل كل شيء على الشبكة المحلية. ثم تعلمنا الحقيقة المحزنة: نحن وراء NAT. ولا يقدم مشغلنا خدمات IP مخصصة (مرحبًا لموظفي منطقة الاتصالات). تم فرزها من خلال العديد من الحلول البديلة ، ولكن لم يتمخض عنها شيء. حاولت إنشاء واجهة ويب على الاستضافة ، ولكني أحتاج أيضًا إلى IP لمزامنة قاعدة البيانات. كان وسيط IPv6 قد أغلق بالفعل بحلول ذلك الوقت. وإنشاء VPN أمر مكلف ، لأنك تريد كل شيء مجانًا. ثم قرروا استخدام روبوت Telegram. كما اتضح ، فإنه يحتوي على وضعين: الاستقصاء المستمر للخادم وإرسال الرسائل إلينا مباشرة. كان الخيار الأول مناسبًا ، لأنه لا يتطلب منا عنوان IP. البحث عن طريق الإنترنت وجدت مكتبة:pytelegrambotapi. وتعيين حول كتابة التعليمات البرمجية. صحيح ، كانت هناك مشاكل. رفضت مكتبة MySQL التي تم العثور عليها بالكاد الكتابة إلى قاعدة البيانات ، ولكن قراءة كل شيء منها بشكل طبيعي. اضطررت إلى عمل عكاز: نقل البيانات إلى ملف مخزن في ذاكرة الوصول العشوائي ، ثم تشغيل نص bash يقرأ البيانات ويخزنها في قاعدة البيانات.

نقوم بعمل ملف config.ini ، نرميه هناك:

[mysql]
host = localhost
database = telegram
user = root
password = secret

لا تنس استبدال البيانات ببياناتك الخاصة.

قم بإنشاء ملف python_mysql_dbconfig.py بالمحتويات التالية:

from configparser import ConfigParser
 
def read_db_config(filename='config.ini', section='mysql'):
    """ Read database configuration file and return a dictionary object
    :param filename: name of the configuration file
    :param section: section of database configuration
    :return: a dictionary of database parameters
    """
    # create parser and read ini configuration file
    parser = ConfigParser()
    parser.read(filename)
 
    # get section, default to mysql
    db = {}
    if parser.has_section(section):
        items = parser.items(section)
        for item in items:
            db[item[0]] = item[1]
    else:
        raise Exception('{0} not found in the {1} file'.format(section, filename))
 
    return db

نحتاج أيضًا إلى إنشاء ملف python_mysql_connect2.py ، مع هذا المحتوى:

from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config

def connect():
    """ Connect to MySQL database """

    db_config = read_db_config()

    try:
        print('Connecting to MySQL database...')
        conn = MySQLConnection(**db_config)

        if conn.is_connected():
            print('connection established.')
        else:
            print('connection failed.')

    except Error as error:
        print(error)

    finally:
        conn.close()
        print('Connection closed.')

if __name__ == '__main__':
    connect()

الآن لدينا كل شيء جاهز للعمل مع قاعدة البيانات.

دعونا نتطرق قليلا من قاعدة البيانات وننتقل مباشرة إلى التواصل مع الروبوت. حسنًا ، كالمعتاد ، اكتبBotFather ، وأخذ رمزًا منه. قم بإنشاء ملف config.py واكتب سطرين فيه:

# -*- coding: utf-8 -*-
token = ' '

قررت تنفيذ ثلاث وظائف في البوت:

  • الحصول على درجة الحرارة
  • أخذ لقطات
  • إدارة النوافذ

مع الأول ، كل شيء بسيط ، عند الطلب نقرأ ملف درجة الحرارة ، ونرسله إلى المستخدم.

مع صور أكثر صعوبة. أنا أستخدم أداة الحركة. في معلماته ، اطلب وضع الصور في مجلد في ذاكرة الوصول العشوائي ، حسنًا ، دعنا نقول كل 30 ثانية. وننشئ ملفات بأسماء متطابقة ، ويستبدلون بعضهم البعض ببساطة. وبعد ذلك ، عند الطلب ، نرسل الملف إلى المستخدم.

حسنًا ، الوحدة الثالثة والأكثر تعقيدًا: إدارة النوافذ. مهمتي الرئيسية: أن تعمل الأتمتة ، ولكن إذا لزم الأمر ، يمكننا إيقاف تشغيلها. لقد فعلتها هكذا إنشاء ملف آخر في ذاكرة الوصول العشوائي. عندما نرسل طلبًا لفتح / إغلاق ، أو فتح قليلاً ، أو إغلاق النافذة أو تشغيل / إيقاف التشغيل الآلي ، يكتب البوت رقم الأمر إلى هذا الملف. كل خمس ثوانٍ ، يقرأ برنامج إدارة النوافذ هذا الملف ، وإذا تعرّف على الأمر ، ينفذه. بعد التنفيذ ، يكتب في نفس الملف أن كل شيء سار على ما يرام. يقرأ البوت الملف مرة أخرى ويبلغنا أنه تم إكمال الأمر.

حسنا ، الآن كود المصدر. أولاً ، نفس البرنامج لفتح النوافذ ، يتم إعادة بنائه فقط لبرنامج الروبوت (temp.py):

temp.py
import RPi.GPIO as GPIO
import time
import os
import datetime

GPIO.setmode(GPIO.BOARD)
GPIO.cleanup()
GPIO.setup(31, GPIO.OUT)
GPIO.setup(33, GPIO.OUT)
GPIO.setup(35, GPIO.OUT)
GPIO.setup(37, GPIO.OUT)

#  ,    
f = open('/mnt/raw/wind', 'w')
f.write('OK')
f.close()

#,   
f = open('/mnt/raw/pos', 'w')
f.write('1')
f.close()

# 
def gettemp():
  if os.path.isdir("/sys/bus/w1/devices/id "): #  ,   
    tfile2=open("/sys/bus/w1/devices/id /w1_slave")
    ttext2=tfile2.read()
    tfile2.close()
    temp2=ttext2.split("\n")[1].split(" ")[9]
    t2=float(temp2[2:])/1000
    print t2
  else: # ,   
    print ('File not found')
    t2==24
  return t2

#   
i=1
# 
t2=24

#   
def info():
    f = open('/mnt/raw/wind')
    com = f.read()
    f.close()
    return com

# ,   
def ans():
    f = open('/mnt/raw/wind', 'w')
    f.write('OK')
    f.close()
    print ("OK")

# 
def rob():
    c = info()
    if c=="10":
        GPIO.output(37, 1)
        print ("close1")
        time.sleep(3)
        GPIO.output(37, 0)
        ans()
    elif c=="11":
        GPIO.output(35, 1)
        print ("open1")
        time.sleep(2)
        GPIO.output(35, 0)
        ans()
    elif c=="12":
        GPIO.output(37, 1)
        print ("close1")
        time.sleep(3)
        GPIO.output(37, 0)
        ans()
    elif c=="13":
        GPIO.output(35, 1)
        print ("open1")
        time.sleep(1)
        GPIO.output(35, 0)
        ans()
    elif c=="20":
        GPIO.output(33, 1)
        print ("close2")
        time.sleep(3)
        GPIO.output(33, 0)
        ans()
    elif c=="21":
        GPIO.output(31, 1)
        print ("open2")
        time.sleep(3)
        GPIO.output(31, 0)
        ans()
    elif c=="22":
        GPIO.output(33, 1)
        print ("close2")
        time.sleep(1)
        GPIO.output(33, 0)
        ans()
    elif c=="23":
        GPIO.output(31, 1)
        print ("open2")
        time.sleep(1)
        GPIO.output(31, 0)
        ans()
    elif c=="30":
        global i
        i=0
        ans()
        f = open('/mnt/raw/pos', 'w')
        f.write('0')
        f.close()
        print('30')
        global i
        i=0
        ans()
    elif c=="31":
        f = open('/mnt/raw/pos', 'w')
        f.write('1')
        f.close()
        print('31')
        global i
        i=1
        ans()
        
while True:

#   
 rob()

#,   
 if i==1:

  gettemp()

  if    t2<24:
 
        GPIO.output(37, 1)
        print ("close1")
        time.sleep(1)
        GPIO.output(37, 0)

  elif  t2>26:

        GPIO.output(35, 1)
        print ("open1")
        time.sleep(2)
        GPIO.output(35, 0)

  else:
        print ("none1")
       
  # 3 ,       
  j=0
  while(j<36):
      rob()
      time.sleep(5)
      j=j+1
      if i==0:
          break
  gettemp()

  if    t2<24:
        GPIO.output(33, 1)
        print ("close2")
        time.sleep(1)
        GPIO.output(33, 0)
       
  elif  t2>26:
  
        GPIO.output(31, 1)
        print ("open2")
        time.sleep(1)
        GPIO.output(31, 0)

  else:

        print ("none2")

  j=0
  while(j<36):
      rob()
      time.sleep(5)
      j=j+1
      if i==0:
          break



ولكن الآن دعونا نتحدث عن البوت نفسه. كما قلت ، أستخدم مكتبة PyTelegramBotApi. إذا انتقلت إلى الوثائق الموجودة على GitHub ، يمكنك أن تفهم أن البوت يستخدم معالجات لمعالجة الأوامر. معالج هو حدث في برنامجنا يحدد العمل. في حالتنا ، هذه عبارة محددة في الرسالة. والعمل هو كل ما يمكننا القيام به في بيثون. في هذه الحالة ، سوف نرسل المستخدم بعض المعلومات إلى المستخدم أو كتابة أوامر للنوافذ إلى ملف. في الأساس ، يتكون برنامجنا من هذه المعالجات وأمر اقتراع الخادم.

ولكني كتبت وأضفت شيئًا آخر مثيرًا للاهتمام: حظر التفويض. حسنًا ، كما يوحي الاسم ، فقد تم تصميمه لحماية البيوت الزجاجية من الوصول غير المصرح به. يعمل ببساطة. في المرة الأولى التي تتصل فيها بالبوت ، يطلب منا كلمة مرور. إذا أدخلناها بشكل صحيح ، فسيضيفنا البوت إلى قاعدة البيانات ، وفي الاتصالات التالية لم نعد بحاجة إلى تسجيل الدخول. يتعرف البوت علينا باستخدام معرف الدردشة. نقوم بتخزين معرف الدردشة لآخر مستخدم في متغير حتى لا يتم سحب قاعدة البيانات طوال الوقت.

الآن قم بإنشاء ملف daba.py واكتب ما يلي:

daba.py
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
import time

def getkey(): #   
    try:
        dbconfig = read_db_config()
        conn = MySQLConnection(**dbconfig)
        cursor = conn.cursor()
        cursor.execute("SELECT key2 FROM tkey where id=0")

        row = cursor.fetchone()

        return row
        print(row)
  

    except Error as e:
        print(e)

    finally:
        cursor.close()
        conn.close()
def sendup(): #    ( )
    stime=time.time()
    query = "INSERT INTO uptime(datetime, also) " \
    "VALUES(now(), 20)"
    args=(stime)
    try:
        dbconfig = read_db_config()
        conn = MySQLConnection(**dbconfig)
        cursor = conn.cursor()
        cursor.execute(query)

        row = cursor.fetchone()

        return(row)
        print(row)
  

    except Error as e:
        print(e)

    finally:
        cursor.close()
        conn.close()
def getid(idi): #   id   
    query="SELECT accecpt FROM users WHERE chatid ='"+str(idi)+"'"
    try:
        dbconfig = read_db_config()
        conn = MySQLConnection(**dbconfig)
        cursor = conn.cursor()
        cursor.execute(query)

        row = cursor.fetchone()
        #print (str(row))
        if str(row)=="None":
            return 0;
            print (0)
        else:
            return 20;

  

    except Error as e:
        print(e)

    #finally:
        #cursor.close()
        #conn.close()
def newuser(idi): #    
    query = ("INSERT INTO users SET `chatid`='12345'")
    try:
        dbconfig = read_db_config()
        conn = MySQLConnection(**dbconfig)
        cursor = conn.cursor()
        cursor.execute(query)

        row = cursor.fetchone()

        print(row)
  

    except Error as e:
        print(e)
        return(e)

    finally:
        cursor.close()
        conn.close()

if __name__ == '__main__':
    query_with_fetchone()



أيضًا ، دعنا نقوم ببعض البرامج النصية المساعدة على الفور. قم بإنشاء ملف newuser.sh واكتب إليه:

#!/bin/bash
a=`cat /mnt/raw/user`
cat /dev/null > /mnt/raw/user

mysql -u root -pkoshak << EOF
use telegram;
INSERT INTO users(chatid) VALUES('$a');
EOF

وإنشاء نصين لإطلاق البوت وبرنامج الويندوز:

#!/bin/bash
i=0
while [ $i = 0 ]
do
echo New python
sleep 5
python3 bot.py
done

وآخر:

#!/bin/bash
i=0
while [ $i = 0 ]
do
echo New python
sleep 5
python3 temp.py
done

"لماذا نفعل ذلك؟" تسأل. وهنا الحقيقة أنه في بعض الأحيان بسبب عدم استقرار اتصال الإنترنت ، أو خطأ في خادم Telegram ، قد يتعطل البرنامج. ويدفعه البرنامج النصي في دورة أبدية: طار - بدأ بعد 5 ثوانٍ مرة أخرى. وبالنسبة للنوافذ ، قمت بذلك لكل رجل إطفاء: فجأة ، بسبب عطل ، سيتعطل البرنامج ، لكننا لسنا في الدفيئة ، سنعود وسنحصل على حساء الطماطم أو آيس كريم الطماطم.

حسنًا ، والأهم الآن هو نص البوت نفسه:

bot.py
# -*- coding: utf-8 -*-
import config
import telebot
import subprocess
import time
from telebot import types
import datetime
import os
from daba import getkey
from daba import sendup
from daba import getid
#from daba import newuser
#from temp import tep
import os

# 
f = open('/mnt/raw/user', 'tw', encoding='utf-8')
f.close()

global par
par=0

#   
global a
a="  .    /auth []"

#  
def get_temp():
  if os.path.isdir("/sys/bus/w1/devices/id "):

    tfile2=open("/sys/bus/w1/devices/id /w1_slave")
    ttext2=tfile2.read()
    tfile2.close()
    temp2=ttext2.split("\n")[1].split(" ")[9]
    t2=float(temp2[2:])/1000
    return t2

  else:
    print ('File not found')
  
#
keyword=str(getkey())[2:-3]

# 
bot = telebot.TeleBot(config.token)
print (sendup())
#  

######################### ##########################################
markup2 = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True) #, ,     
markdown = types.ReplyKeyboardHide() #
itembtn5 = types.KeyboardButton(' ') #  5
markup2.add(itembtn5) #   
######################### ##########################################


#########################  ##########################################
markup = types.ReplyKeyboardMarkup(row_width=3, resize_keyboard=True) #, ,     
itembtn1 = types.KeyboardButton('  ') #  1
itembtn4 = types.KeyboardButton('  ')
itembtn2 = types.KeyboardButton('  ') #  2
markup.add(itembtn1, itembtn4, itembtn2) #   
#########################  ##########################################


######################### ##########################################

markup3 = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) #, ,     
itembtn10 = types.KeyboardButton('   ') #  10
itembtn11 = types.KeyboardButton('️  ')
itembtn12 = types.KeyboardButton(' ')
markup3.add(itembtn10, itembtn11, itembtn12) #   

markup4 = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) #, ,     
itembtn13 = types.KeyboardButton('   ') #  13
markup4.add(itembtn13, itembtn11, itembtn12) #   

markup5 = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) #, ,     
itembtn14 = types.KeyboardButton('  ') #  14
itembtn15 = types.KeyboardButton('  ') #  15
itembtn16 = types.KeyboardButton('️ ') #  16
markup5.add(itembtn14, itembtn15, itembtn16) #   

markup6 = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) #, ,     
itembtn17 = types.KeyboardButton('️   ') #  17
itembtn18 = types.KeyboardButton('️   ') #  18
itembtn19 = types.KeyboardButton('   ') #  19
itembtn20 = types.KeyboardButton('   ') # 20
itembtn21 = types.KeyboardButton('️ ') #  21
markup6.add(itembtn17, itembtn18, itembtn19, itembtn20, itembtn21) #   

markup7 = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) #, ,     
itembtn22 = types.KeyboardButton('️   ') #  22
itembtn23 = types.KeyboardButton('️   ') #  23
itembtn24 = types.KeyboardButton('   ') # 24
itembtn25 = types.KeyboardButton('   ') # 25
markup7.add(itembtn22, itembtn23, itembtn24, itembtn25, itembtn21) #   
######################### ##########################################
bot.send_message(45215125, "")#   chat-id


    
#   
def pos():
    f = open('/mnt/raw/pos')
    com = f.read()
    f.close()
    return com

#
def avtor(idi):
    global par#      
    if par==idi:
            return 0
    else:#    ,    ,  0
            if getid(str(idi))==20:
                par=idi#   
                return 0
            else:#     
                bot.send_message(idi, "  .    /auth []", reply_markup=markup2)
                return 1    
        


@bot.message_handler(regexp=" ")
def auth(message):
    bot.send_message(message.chat.id, " /auth []")

# 
@bot.message_handler(commands=['auth'])
def start2(message):
    if message.text[6:]==keyword:#   
      if getid(str(message.chat.id))==20:#    ,         20
        bot.send_message(message.chat.id, "  ")
      else:
        global par
        bot.send_message(message.chat.id, "", reply_markup=markup)
        par=message.chat.id
        # chat-id   
        f = open('/mnt/raw/user', 'w')
        f.write(str(message.chat.id))
        f.close()
        os.system('newuser.sh')
        print (message.chat.id)
        print (par)
    else:
        bot.send_message(message.chat.id, "")
        print (keyword)
        print (message.text[6:])
        print (message.chat.id)


#  /start
@bot.message_handler(commands=['start'])
def start(message):
     global par
     if avtor(message.chat.id)!=0:
         print (par)
         bot.send_message(message.chat.id, "   .    /auth []", reply_markup=markup2)
     else:
	     bot.send_message(message.chat.id, "   .  /help,  ,    .")



#   - /help
@bot.message_handler(commands=['help'])
def help(message):
  if avtor(message.chat.id)==0:
     mas='       . \n    ,    :  \n   - /help \n       :)'
     bot.send_message(message.chat.id, mas, reply_markup=markup)
     print (message.chat.id, message.text)

	
 
#     
@bot.message_handler(commands=['show'])
def show(message):
  if avtor(message.chat.id)==0:
     mas=' '
     bot.send_message(message.chat.id, mas, reply_markup=markup)
     print (message.chat.id, message.text)



# 
@bot.message_handler(regexp="  ")
def temp(message):
  if avtor(message.chat.id)==0:
     tp=get_temp()
     mas='    : '+str(tp)+'°C'
     bot.send_message(message.chat.id, mas)
     print (message.chat.id, message.text)
    

# 
@bot.message_handler(regexp="  ")
def photo(message): 
     if avtor(message.chat.id)==0: 
         path='/mnt/raw/photo/foto.jpg' #    
         try:
             f = open(path, 'rb') #  - 
             bot.send_photo(message.chat.id, f) # 
             print (message.chat.id, message.text)
         except:
             bot.send_message(message.chat.id, "  :(")


#   
@bot.message_handler(regexp="  ")
def windows(message):
   if avtor(message.chat.id)==0:
       print ("window")
       print (pos())
       if str(pos())[0]=='1':
           bot.send_message(message.chat.id, "", reply_markup=markup3)#  ,      « »
       else: 
           bot.send_message(message.chat.id, "", reply_markup=markup4)#     

# 
@bot.message_handler(regexp=" ")
def windows(message):
   if avtor(message.chat.id)==0:
       bot.send_message(message.chat.id, "",  reply_markup=markup)

# 
@bot.message_handler(regexp="   ")
def windows(message):
   if avtor(message.chat.id)==0:
       f = open('/mnt/raw/wind', 'w')# 
       f.write('30')#   ,     30
       f.close()# 
       k="No"#  
       while k[0:2]!="OK":#  
           time.sleep(5)# 5 
           f = open('/mnt/raw/wind')# 
           k = f.read()# 
           f.close()#
           print(k[0:2])
       bot.send_message(message.chat.id, "",  reply_markup=markup4)

@bot.message_handler(regexp="   ")
def windows(message):
   if avtor(message.chat.id)==0:
       f = open('/mnt/raw/wind', 'w')
       f.write('31')
       f.close()
       k="No"
       while k[0:2]!="OK":
           time.sleep(5)           
           f = open('/mnt/raw/wind')
           k = f.read()
           f.close()
           print(k[0:2])
       bot.send_message(message.chat.id, "",  reply_markup=markup3)

@bot.message_handler(regexp="️  ")
def windows(message):
   if avtor(message.chat.id)==0:
       bot.send_message(message.chat.id, "",  reply_markup=markup5)

@bot.message_handler(regexp="️ ")
def windows(message):
   if avtor(message.chat.id)==0:
       if str(pos())[0]=='1':
           bot.send_message(message.chat.id, "", reply_markup=markup3)
       else: 
           bot.send_message(message.chat.id, "", reply_markup=markup4)

@bot.message_handler(regexp="️ ")
def windows(message):
   if avtor(message.chat.id)==0:
       bot.send_message(message.chat.id, "",  reply_markup=markup5)

#  
@bot.message_handler(regexp="  ")
def windows(message):
   if avtor(message.chat.id)==0:
       bot.send_message(message.chat.id, "",  reply_markup=markup6)
@bot.message_handler(regexp="  ")
def windows(message):
   if avtor(message.chat.id)==0:
       bot.send_message(message.chat.id, "",  reply_markup=markup7)

@bot.message_handler(regexp="️   ")
def windows(message):
   if avtor(message.chat.id)==0:
       f = open('/mnt/raw/wind', 'w')
       f.write('11')
       f.close()
       k="No"
       while k[0:2]!="OK":
           time.sleep(5)           
           f = open('/mnt/raw/wind')
           k = f.read()
           f.close()
           print(k[0:2])
       bot.send_message(message.chat.id, "",  reply_markup=markup6)

@bot.message_handler(regexp="️   ")
def windows(message):
   if avtor(message.chat.id)==0:
       f = open('/mnt/raw/wind', 'w')
       f.write('10')
       f.close()
       k="No"
       while k[0:2]!="OK":
           time.sleep(5)           
           f = open('/mnt/raw/wind')
           k = f.read()
           f.close()
           print(k[0:2])
       bot.send_message(message.chat.id, "",  reply_markup=markup6)

@bot.message_handler(regexp="   ")
def windows(message):
   if avtor(message.chat.id)==0:
       f = open('/mnt/raw/wind', 'w')
       f.write('13')
       f.close()
       k="No"
       while k[0:2]!="OK":
           time.sleep(5)           
           f = open('/mnt/raw/wind')
           k = f.read()
           f.close()
           print(k[0:2])
       bot.send_message(message.chat.id, "",  reply_markup=markup6)

@bot.message_handler(regexp="   ")
def windows(message):
   if avtor(message.chat.id)==0:
       f = open('/mnt/raw/wind', 'w')
       f.write('12')
       f.close()
       k="No"
       while k[0:2]!="OK":
           time.sleep(5)           
           f = open('/mnt/raw/wind')
           k = f.read()
           f.close()
           print(k[0:2])
       bot.send_message(message.chat.id, "",  reply_markup=markup6)

@bot.message_handler(regexp="️   ")
def windows(message):
   if avtor(message.chat.id)==0:
       f = open('/mnt/raw/wind', 'w')
       f.write('21')
       f.close()
       k="No"
       while k[0:2]!="OK":
           time.sleep(5)           
           f = open('/mnt/raw/wind')
           k = f.read()
           f.close()
           print(k[0:2])
       bot.send_message(message.chat.id, "",  reply_markup=markup7)

@bot.message_handler(regexp="️   ")
def windows(message):
   if avtor(message.chat.id)==0:
       f = open('/mnt/raw/wind', 'w')
       f.write('20')
       f.close()
       k="No"
       while k[0:2]!="OK":
           time.sleep(5)           
           f = open('/mnt/raw/wind')
           k = f.read()
           f.close()
           print(k[0:2])
       bot.send_message(message.chat.id, "",  reply_markup=markup7)

@bot.message_handler(regexp="   ")
def windows(message):
   if avtor(message.chat.id)==0:
       f = open('/mnt/raw/wind', 'w')
       f.write('23')
       f.close()
       k="No"
       while k[0:2]!="OK":
           time.sleep(5)           
           f = open('/mnt/raw/wind')
           k = f.read()
           f.close()
           print(k[0:2])
       bot.send_message(message.chat.id, "",  reply_markup=markup7)

@bot.message_handler(regexp="   ")
def windows(message):
   if avtor(message.chat.id)==0:
       f = open('/mnt/raw/wind', 'w')
       f.write('22')
       f.close()
       k="No"
       while k[0:2]!="OK":
           time.sleep(5)           
           f = open('/mnt/raw/wind')
           k = f.read()
           f.close()
           print(k[0:2])
       bot.send_message(message.chat.id, "",  reply_markup=markup7)

#  ,   
@bot.message_handler(content_types=["text"])
def repeat_all_messages(message):
   if avtor(message.chat.id)==0:
         bot.send_message(message.chat.id, "    .  /help,    ")
         print (message.chat.id, message.text)

#     
if __name__ == '__main__':
        bot.polling()




لا تنس أن تشير هنا إلى معرف المستشعر ومعرف الدردشة والمسار إلى القسم في ذاكرة الوصول العشوائي. الآن لدينا كل شيء جاهز تقريبًا. نقوم بتنزيل هذا التفريغ ، وملء قاعدة البيانات على الخادم الخاص بنا ، ولا ننسى تركيب القسم في ذاكرة الوصول العشوائي ، أعتقد أن 10 ميجابايت كافية للرقبة. نطلق اثنين من نصوصنا المبدئية ونفرح. كلمة المرور الافتراضية هي telbot. قم بتغييره في جدول مفتاح قاعدة البيانات.

إعلام SMS


وكذلك أبلغت الرسائل القصيرة في حالة ارتفاع درجة الحرارة. قم بإنشاء ملف sms.py:

sms.py
#!/usr/bin/env python
# -*- coding: utf8 -*-
 
"""   .. t_aleksandr_v@inbox.ru 17.02.2015 """
 
"""        sms.ru """
"""   :"""
 
""" -i  --idsender - id   sms.ru"""
""" -t  --to -      79219996660"""
""" -s  --subject -    """
 
 
from urllib2 import urlopen
from optparse import OptionParser
 
 
def sendsms(idsender,subject,to):
 
    subject = subject.replace(" ","+")
    url="http://sms.ru/sms/send?api_id=%s&text=%s&to=%s" %(idsender,subject,to)
    res=urlopen(url)
 
if __name__ == '__main__':
 
    parser = OptionParser()
 
    parser.add_option("-i", "-- ", dest="idsender", default=" ", help="ID user on sms.ru", metavar="IDSENDER")
    parser.add_option("-t", "-- ", dest="to", default=" ", help="to telephone number", metavar="TO")
    parser.add_option("-s", "--temperatyra 32", dest="subject", default="Jara tut, otkroy okno", help="Name of subject", metavar="SUBJECT")
 
    (options, args) = parser.parse_args()
 
    sendsms(options.idsender,options.subject,options.to)




نسجل في sms.ru ونأخذ مفتاح API هناك في القسم للمبرمجين. ولا تنس أيضًا الإشارة إلى رقم هاتفك في البرنامج النصي.

في برنامج إدارة النوافذ ، نعلن متغير:

Vr=0

ثم أدخل هذا الرمز في الحلقة الدائمة:

d = datetime.today()
V = d.strftime('%H')
V = int(V)
 if    (t2>32 and Vr!=V): 
        print (V)
        Vr=V
        os.system('/home/samba/sms.py')

في الوقت الحالي ، تكون درجة حرارة العتبة 32 ، سيتم إرسال الرسائل القصيرة في حالة ارتفاع درجة الحرارة مرة واحدة في الساعة ، حتى تنخفض. خطط

PS للمستقبل لتركيب سخان التحكم والقيام بالري التلقائي.

شكرا لجميع الذين قرأوا حتى النهاية.

Source: https://habr.com/ru/post/ar400499/


All Articles