hausbrand/xmpp.py

99 lines
3.1 KiB
Python

import logging
from slixmpp import ClientXMPP
from slixmpp.exceptions import IqError, IqTimeout
import os
from dotenv import load_dotenv
import RPi.GPIO as GPIO
import time
from threading import Thread
import asyncio
class EchoBot(ClientXMPP):
def __init__(self, jid, password):
ClientXMPP.__init__(self, jid, password)
self.add_event_handler("session_start", self.session_start)
self.add_event_handler("message", self.message)
# If you wanted more functionality, here's how to register plugins:
# self.register_plugin('xep_0030') # Service Discovery
# self.register_plugin('xep_0199') # XMPP Ping
# Here's how to access plugins once you've registered them:
# self['xep_0030'].add_feature('echo_demo')
# If you are working with an OpenFire server, you will
# need to use a different SSL version:
# import ssl
# self.ssl_version = ssl.PROTOCOL_SSLv3
def session_start(self, event):
self.send_presence()
self.get_roster()
# Most get_*/set_* methods from plugins use Iq stanzas, which
# can generate IqError and IqTimeout exceptions
#
# try:
# self.get_roster()
# except IqError as err:
# logging.error('There was an error getting the roster')
# logging.error(err.iq['error']['condition'])
# self.disconnect()
# except IqTimeout:
# logging.error('Server is taking too long to respond')
# self.disconnect()
def message(self, msg):
if msg['type'] in ('chat', 'normal'):
print (msg['body'])
if msg['body'] == "open":
buzz()
msg.reply("Buzzing").send()
else:
msg.reply("Not Understood").send()
def sendRing():
global xmpp
recipient = os.getenv("NOTIFY")
print ("sent message to ")
print (recipient)
#loop = asyncio.get_event_loop(xmpp)
#asyncio.run_coroutine_threadsafe(asyncio.to_thread(xmpp.send_message(mto=recipient, mbody="Klingelt!", mtype='chat')),loop)
xmpp.send_message(mto=recipient, mbody="Klingelt!", mtype='chat')
def ringLoop():
GPIO.setmode(GPIO.BCM) # GPIO Numbers instead of board numbers
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
timer = 100
while True:
print (GPIO.input(23))
time.sleep(0.1)
timer = timer - 1
if (GPIO.input(23) == 0 or timer == 0):
sendRing()
print ("ringing")
print ("ringing")
print ("ringing")
print ("ringing")
print ("ringing")
if __name__ == '__main__':
# Ideally use optparse or argparse to get JID,
# password, and log level.
load_dotenv()
password = os.getenv("PASS")
jid = os.getenv("JID")
logging.basicConfig(level=logging.DEBUG, format='%(levelname)-8s %(message)s')
xmpp = EchoBot(jid, password)
Thread(name="GPIO_INPUT", target=ringLoop).start()
#asyncio.run_coroutine_threadsafe(self.waiting_queue.put((data, use_filters)), self.loop)
xmpp.connect()
xmpp.process(forever=True)