Encender y apagar led mediante telegram
Publicado: 24 Abr 2018, 11:43
Bien, básicamente lo que quiero es que cuando le de a un botón(abrepuertas) desde mi móvil se encienda un LED durante 5 segundos y que luego se apague. Es simple pero me aparece un problema, que cuando le doy al botón abrepuertas, me aparece el mensaje que he definido (abriendo puertas) pero no se enciende el LED, para encenderlo tengo que darle otra vez y lo que quiero es que funcione a la primera pulsación. Ademas solo se enciende como 1segundo cuando yo le tengo puesto 5.
El problema esta en el apartado #MENU CAMERA (#ABREPUERTAS) y luego que lo redirijo al sub-bloque de abajo #ABREPUERTAS
Creo que tengo mal el código claro...
Aqui os dejo el codigo entero:
El problema esta en el apartado #MENU CAMERA (#ABREPUERTAS) y luego que lo redirijo al sub-bloque de abajo #ABREPUERTAS
Creo que tengo mal el código claro...
Aqui os dejo el codigo entero:
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 puerta")
bot.register_next_step_handler(m, abrepuertas)
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])
# ABREPUERTAS
def abrepuertas(m):
GPIO.setmode(GPIO.BCM)
GPIO.setup(4,GPIO.OUT)
GPIO.setwarnings(False)
GPIO.output(4, True)
time.sleep(5)
GPIO.output(4, False)
GPIO.cleanup()
# 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)