Necesito ayuda para hacer una cosa de mi proyecto

¿Algo falla o no sabes como funciona? Pide ayuda aquí!
Responder
Ivan10fcb
Pi Newbie
Pi Newbie
Mensajes: 6
Registrado: 20 Abr 2018, 13:00
Agradecido: 0
Agradecimiento recibido: 0

Hola, estoy tratando de hacer un portero automatico con raspberry pi y telegram. Ya estoy bastante avanzado, de momento puedo ver quien es a traves de la camara y puedo abrirle la puerta. Todo esto a traves de telegram. Aqui os dejo el codigo:

Código: Seleccionar todo

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import telebot
from telebot import types
import time
import os
import telegram
import picamera
import RPi.GPIO as GPIO

TOKEN = "493789599:AAFm0Z-AB7C3rI9YWbEEQAAeEjHAvtjicUk"  # SUSTITUIR

userStep = {}
knownUsers = []

commands = {
              'start': 'Arranca el bot',
              'ayuda': 'Comandos disponibles',
              'exec': 'Ejecuta un comando'
              
}

menu = types.ReplyKeyboardMarkup()
menu.add("RPinfo", "Camara")

cam_menu = types.ReplyKeyboardMarkup()
cam_menu.add("Foto", "Abrepuertas")
cam_menu.add("Atras")

info_menu = types.ReplyKeyboardMarkup()
info_menu.add("TEMP", "HD")
info_menu.add("CPU")
info_menu.add("Atras")


# COLOR TEXTO
class color:
    RED = '\033[91m'
    BLUE = '\033[94m'
    GREEN = '\033[32m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


# USER STEP
def get_user_step(uid):
    if uid in userStep:
        return userStep[uid]
    else:
        knownUsers.append(uid)
        userStep[uid] = 0
        print(color.RED + " [¡] ¡¡NUEVO USUARIO!!" + color.ENDC)


# LISTENER
def listener(messages):
    for m in messages:
        if m.content_type == 'text':
            print("[" + str(m.chat.id) + "] " + str(m.chat.first_name) + ": " + m.text)

bot = telebot.TeleBot(TOKEN)
bot.set_update_listener(listener)

# START
@bot.message_handler(commands=['start'])
def command_start(m):
    cid = m.chat.id
    userStep[cid] = 0
    bot.send_message(cid, "Hola " + str(m.chat.first_name) + "...")
    time.sleep(1)
    bot.send_message(cid, "Bienvenido al menu principal")
    time.sleep(1)
    bot.send_message(cid, "¿En que puedo ayudarte?", reply_markup=menu)


# AYUDA
@bot.message_handler(commands=['ayuda'])
def command_help(m):
    cid = m.chat.id
    help_text = "Grabar sesion: TermRecord -o /tmp/botlog.html\n"
    help_text += "Comandos disponibles: \n"
    for key in commands:
        help_text += "/" + key + ": "
        help_text += commands[key] + "\n"
    bot.send_message(cid, help_text)


# EXEC COMANDO
@bot.message_handler(commands=['exec'])
def command_exec(m):
    cid = m.chat.id
    if cid == "186626418":  # SUSTITUIR
        bot.send_message(cid, "Ejecutando: " + m.text[len("/exec"):])
        bot.send_chat_action(cid, 'typing')
        time.sleep(2)
        f = os.popen(m.text[len("/exec"):])
        result = f.read()
        bot.send_message(cid, "Resultado: " + result)
    else:
        bot.send_message(cid, " ¡¡PERMISO DENEGADO!!")
        print(color.RED + " ¡¡PERMISO DENEGADO!! " + color.ENDC)


# MENU PRINCIPAL
@bot.message_handler(func=lambda message: get_user_step(message.chat.id) == 0)
def main_menu(m):
    cid = m.chat.id
    text = m.text
    if text == "RPinfo":  # RPINFO
        bot.send_message(cid, "Informacion disponible:", reply_markup=info_menu)
        userStep[cid] = 1
    elif text == "Camara":  # CAMARA
        bot.send_message(cid, "Opciones de la camara:", reply_markup=cam_menu)
        userStep[cid] = 2
    elif text == "Atras":  # ATRAS
        userStep[cid] = 0
        bot.send_message(cid, "Menu Principal:", reply_markup=menu)
    else:
        command_text(m)


# MENU INFO
@bot.message_handler(func=lambda message: get_user_step(message.chat.id) == 1)
def info_opt(m):
        cid = m.chat.id
        txt = m.text
        if txt == "TEMP":  # TEMP
            bot.send_message(cid, "[+] TEMPERATURAS")
            print(color.BLUE + "[+] TEMPERATURAS" + color.ENDC)
            # cpu temp
            tempFile = open( "/sys/class/thermal/thermal_zone0/temp" )
            cpu_temp = tempFile.read()
            tempFile.close()
            cpu_temp = round(float(cpu_temp)/1000)
            bot.send_message(cid, "  [i]   CPU: %s" % cpu_temp)
            print(color.GREEN + " [i] CPU: %s" % cpu_temp + color.ENDC)
            # gpu temp
            gpu_temp = os.popen('/opt/vc/bin/vcgencmd measure_temp').read().split("=")[1][:-3]
            bot.send_message(cid, "  [i]   GPU: %s" % gpu_temp)
            print(color.GREEN + " [i] GPU: %s" % gpu_temp + color.ENDC)
        elif txt == "HD":  # HD
            bot.send_message(cid, "[+] DISCO DURO")
            print(color.BLUE + "[+] DISCO DURO" + color.ENDC)
            bot.send_message(cid, "  [i]   Total: %s" % diskSpace()[0])
            print(color.GREEN + " [i] Total: %s" % diskSpace()[0] + color.ENDC)
            bot.send_message(cid, "  [i]   Usado: %s" % diskSpace()[1])
            print(color.GREEN + " [i] Usado: %s" % diskSpace()[1] + color.ENDC)
            bot.send_message(cid, "  [i]   Disponible: %s" % diskSpace()[2])
            print(color.GREEN + " [i] Disponible: %s" % diskSpace()[2] + color.ENDC)
        elif txt == "CPU":  # CPU
            bot.send_message(cid, "[+] CPU")
            print(color.BLUE + "[+] CPU" + color.ENDC)
            cpu = os.popen('mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " \'{print 100 - $ 12}\'a').read()
            bot.send_message(cid, "  [i]   Usado: %s" % cpu)
            print(color.GREEN + " [i] Usado: %s" % cpu + color.ENDC)
        elif txt == "Atras":  # ATRAS
            userStep[cid] = 0
            bot.send_message(cid, "Menu Principal:", reply_markup=menu)
        else:
            command_text(m)

# MENU CAMARA
@bot.message_handler(func=lambda message: get_user_step(message.chat.id) == 2)
def cam_opt(m):
    cid = m.chat.id
    text = m.text
    if text == "Foto":  # FOTO
        bot.send_message(cid, "Tomando foto ...")
        bot.send_chat_action(cid, 'upload_photo')
        foto = "/home/pi/Pictures" + (time.strftime("%H%M%S-%d%m%y")) + ".jpg"
        os.system('raspistill -w 1024 -h 768 -rot 180 -o %s' % foto)
        bot.send_photo(cid, open(foto, 'rb'))
        print(color.BLUE + " [i] Foto enviada!!" + color.ENDC)
    elif text == "Abrepuertas":  # ABREPUERTAS
        bot.send_message(cid, "Abriendo la puerta")
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(17,GPIO.OUT)
        GPIO.output(17, True)
        time.sleep (5)
        GPIO.output (17, False)
        GPIO.cleanup()
    elif text == "Atras":  # ATRAS
        userStep[cid] = 0
        bot.send_message(cid, "Menu Principal:", reply_markup=menu)
    else:
        command_text(m)

# INFO HD
def diskSpace():
    p = os.popen("df -h /")
    i = 0
    while 1:
        i += 1
        line = p.readline()
        if i == 2:
            return(line.split()[1:5])

# FILTRAR MENSAJES
@bot.message_handler(func=lambda message: True, content_types=['text'])
def command_text(m):
    cid = m.chat.id
    if (m.text.lower() in ['hola', 'hi', 'buenas', 'buenos dias']):
        bot.send_message(cid, 'Muy buenas, ' + str(m.from_user.first_name) + '. Me alegra verte de nuevo.', parse_mode="Markdown")
    elif (m.text.lower() in ['adios', 'aios', 'adeu', 'ciao']):
        bot.send_message(cid, 'Hasta luego, ' + str(m.from_user.first_name) + '. Te echaré de menos.', parse_mode="Markdown")


print 'Corriendo...'
bot.polling(none_stop=True)
Ahora lo que quiero hacer es conectar un pulsador a la raspberry y que cuando se pulse me envie una notificacion a traves de telegram para que yo sepa que me estan llamando. Aqui os dejo un codigo de como creo que seria

Código: Seleccionar todo

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(2, GPIO.IN)
GPIO.setup(17, GPIO.OUT)
GPIO.setwarnings(False)

while True:
    if GPIO.input(2):
        GPIO.output(17, GPIO.LOW)
    else:
        GPIO.output(17, GPIO.HIGH)
        
El problema es ese, que no se como meter esa función en el programa que ya tengo echo para que me envié la notificativo y todo. Un saludo
Avatar de Usuario
drewdty
Pi Destroyer
Pi Destroyer
Mensajes: 753
Registrado: 05 Dic 2016, 22:47
Agradecido: 0
Agradecimiento recibido: 4 veces

huuuuu demasiado para mi
te felicito si ya has llegado hasta aqui con tu proyecto
creo que este tema no se ha tocado mucho en este foro (igual me equivoco :ouch )
no te puedo ayudar
Imagen
La madre de todas las ciencias es la paCIENCIA
milor
Pi Newbie
Pi Newbie
Mensajes: 7
Registrado: 05 Jun 2017, 08:30
Agradecido: 0
Agradecimiento recibido: 0

Hablo desde el desconocimiento (tengo que empezar ahora con python y gpio), porque necesitas integrarlo en el principal? Arrancarlo como otro script...

Sino lo que veo que el while debería pasar a ser un IF, los import van arriba (lo que no estén) y el codigo abajo del todo antes de print "corriendo"
Responder