Example #1
0
class XmppFederationProtocol(FederationProtocol):
    """
    Gestion des échanges sur le réseau fédéré avec le protocole XMPP
    
    Implémentation XMPP du FederationProtocol 
    """
    def __init__(self):
        """
        PostConstruct
        """
        self.configService = None
        self.appService = None
        self.xmpp = None
        self.messageHandler = None
        MonkeyPatch().patch_fromisoformat()

    def start(self):
        """
        Démarre le service
        """
        xmppDomain = self.configService.value("XMPP_DOMAIN_NAME")
        xmppUser = self.configService.value("XMPP_USERNAME")
        self.xmpp = ClientXMPP(xmppUser,
                               self.configService.value("XMPP_PASSWORD"))

        # ajout des listeners et plugins
        self.xmpp.add_event_handler("session_start", self.session_start)
        self.xmpp.register_plugin('XmppMessagePlugin', module=xmpp)
        self.xmpp.register_handler(
            Callback(
                'SEN1 Message',
                MatchXPath('{%s}message/{http://xmpp.rocks}Sen1Message' %
                           self.xmpp.default_ns), self.receiveMessage))
        register_stanza_plugin(Message, XmppMessageStanza)

        if (not self.xmpp.connect(address=(xmppDomain, 5222))):
            raise Exception("Cannot bind XMPP session to {}".format(xmppUser))

        self.logger.info(
            "Start XMPP protocol : bind session {}...".format(xmppUser))

        self.xmpp.process()

    def stop(self):
        """
        Stoppe le service
        """
        self.logger.info("Stop XMPP protocol...")
        self.xmpp.disconnect()

    def session_start(self, event):
        """
        
        """
        self.logger.info("XMPP session is started")
        self.xmpp.send_presence()
        self.xmpp.get_roster()

    def receiveMessage(self, stanza):
        """
        Réception d'un message XMPP
        
        :param stanza: xmpp message
        """
        self.logger.info("Receive SEN1 message from {}...".format(
            stanza['from']))

        try:
            message = XmppMessageStanza.parse_xmpp_message(stanza)
            self.messageHandler.handle(message)
        except Exception as ex:
            self.logger.error("Receive SEN1 message : {}".format(ex))

    def sendMessage(self, message):
        """
        Envoi d'un message
        
        :param message: Message
        """

        # vérifie la conformité du message avant envoi
        message.asserts()

        # recherche du JID de l'application destinataire
        app = self.appService.findByName(message.applicationDst)
        self.logger.info("Sending SEN1 message to {}...".format(app.jid))

        # construction d'un message
        xmppMessage = self.xmpp.make_message(app.jid)
        XmppMessageStanza.build_xmpp_message(xmppMessage, message).send()
Example #2
0
class WylioXMPP:
	def __init__(self, email, db):
		self.connection = None
		self.email = email
		self.db = db
		self.jid = ""
	def connect(self,jid,password):
		self.jid = jid
		if self.connection == None:
			self.connection = ClientXMPP(jid, password)
		register_stanza_plugin (Message, WylioStanza)	
		register_stanza_plugin (WylioStanza, ValueStanza)	
		self.connection.add_event_handler("connected", self.connected)
		self.connection.add_event_handler("session_start", self.start)
		self.connection.add_event_handler("failed_auth", self.failed)
		self.connection.add_event_handler("disconnected", self.disconnected)
		self.connection.add_event_handler("message", self.message)
		self.connection.register_handler (Callback ("Wylio", StanzaPath("message/wylio"), self.message_wylio))
		self.connection.connect(('talk.google.com', 5222))
		self.connection.process ()
		
	def connected(self,event):
		log ("WylioXMPP connected")
		
	def start(self, event):
		log ("WylioXMPP start")
		self.connection	.send_presence()
		log ("Wylio presence")
		#self.run_program ("source", "[email protected]/raspy")
		
	def disconnect (self):
		self.connection.disconnect ()
		
	def message_wylio (self, msg):
		if msg["wylio"]["value"]:
			#print msg	
			signal = msg["wylio"]["value"]["signal"]
			value = nr(msg["wylio"]["value"]["value"])
			
			#print signal, " ", value
			print self.email
			if self.db.values.find ({"email":self.email, "signal":signal}).count () == 0:
				print "insert"
				self.db.values.insert ({"email":self.email, "signal":signal, "values":[value]})
			else:
				try:
					self.db.values.update ({"email":self.email, "signal":signal}, {"$push": {"values":value}})
					print "update"
				except:
					traceback.print_exc()
		
	def message(self, event):
		print event
		
	def failed(self,event):
		log ("WylioXMPP failed")
	
	def disconnected(self,event):
		log("WylioXMPP disconnected")
		
	def send_value(self, signal, value, jid):
		msg = self.connection.Message (sto=jid, stype="normal")
		msg["wylio"]["value"]["signal"] = signal
		msg["wylio"]["value"]["value"] = value
		print msg
		msg.send()
		
	def run_source (self, source, jid):
		print "fsdafasd"
		msg = self.connection.Message (sto=jid, stype="normal")
		print msg
		msg["wylio"]["run"] = source
		#msg["wylio"]["value"]="4082374"
		#msg["wylio"]["value"]["timestamp"]="4082374"
		#msg["wylio"]["value"]["signal"]="some name"
		#msg["wylio"]["value"]["value"]="478923"
		print "message"
		print msg
		msg.send()
Example #3
0
class WylioXMPP:
    def __init__(self, email, db):
        self.connection = None
        self.email = email
        self.db = db
        self.jid = ""

    def connect(self, jid, password):
        self.jid = jid
        if self.connection == None:
            self.connection = ClientXMPP(jid, password)
        register_stanza_plugin(Message, WylioStanza)
        register_stanza_plugin(WylioStanza, ValueStanza)
        self.connection.add_event_handler("connected", self.connected)
        self.connection.add_event_handler("session_start", self.start)
        self.connection.add_event_handler("failed_auth", self.failed)
        self.connection.add_event_handler("disconnected", self.disconnected)
        self.connection.add_event_handler("message", self.message)
        self.connection.register_handler(
            Callback("Wylio", StanzaPath("message/wylio"), self.message_wylio))
        self.connection.connect(('talk.google.com', 5222))
        self.connection.process()

    def connected(self, event):
        log("WylioXMPP connected")

    def start(self, event):
        log("WylioXMPP start")
        self.connection.send_presence()
        log("Wylio presence")
        #self.run_program ("source", "[email protected]/raspy")

    def disconnect(self):
        self.connection.disconnect()

    def message_wylio(self, msg):
        if msg["wylio"]["value"]:
            #print msg
            signal = msg["wylio"]["value"]["signal"]
            value = nr(msg["wylio"]["value"]["value"])

            #print signal, " ", value
            print self.email
            if self.db.values.find({
                    "email": self.email,
                    "signal": signal
            }).count() == 0:
                print "insert"
                self.db.values.insert({
                    "email": self.email,
                    "signal": signal,
                    "values": [value]
                })
            else:
                try:
                    self.db.values.update(
                        {
                            "email": self.email,
                            "signal": signal
                        }, {"$push": {
                            "values": value
                        }})
                    print "update"
                except:
                    traceback.print_exc()

    def message(self, event):
        print event

    def failed(self, event):
        log("WylioXMPP failed")

    def disconnected(self, event):
        log("WylioXMPP disconnected")

    def send_value(self, signal, value, jid):
        msg = self.connection.Message(sto=jid, stype="normal")
        msg["wylio"]["value"]["signal"] = signal
        msg["wylio"]["value"]["value"] = value
        print msg
        msg.send()

    def run_source(self, source, jid):
        print "fsdafasd"
        msg = self.connection.Message(sto=jid, stype="normal")
        print msg
        msg["wylio"]["run"] = source
        #msg["wylio"]["value"]="4082374"
        #msg["wylio"]["value"]["timestamp"]="4082374"
        #msg["wylio"]["value"]["signal"]="some name"
        #msg["wylio"]["value"]["value"]="478923"
        print "message"
        print msg
        msg.send()
Example #4
0
class WylioServer:
	def __init__(self):
		self.connection = None
		log("WylioServer initialised")
	def connected(self,event):
		log("WylioServer connected")
	def disconnected(self,event):
		log("WylioServer disconnected")
	def failed_auth(self,event):
		log("WylioServer failed authentification")
	def message(self, event):
		log("WylioServer message received")
		print event
	def send_value_signal(self,jid,timestamp,name,value):
		msg = self.connection.Message (sto=jid, stype="normal")
		msg["wylio"]["value"]["timestamp"]=timestamp
		msg["wylio"]["value"]["signal"]=name
		msg["wylio"]["value"]["value"]=value
		#print "message"
		#print msg
		msg.send()
	def send_signal_out(self,jid,value):
		msg = self.connection.Message (sto=jid, stype="normal")
		msg["wylio"]["out"]=value
		#print "message"
		#print msg
		msg.send()
	def send_signal_err(self,jid,value):
		msg = self.connection.Message (sto=jid, stype="normal")
		msg["wylio"]["err"]=value
		#print "message"
		#print msg
		msg.send()
	def message_wylio(self, event):
		global program
		try:
			log("WylioServer message wylio received")
			print event['wylio']
			if event['wylio']['run']:
				#print "run in wylio"
				code = event['wylio']['run']
				file = open('received_program.py', 'w')
				file.write(code)
				file.close()
				if program != None:
					program.stop()
				program = Program(1,'received_program.py')
				try:
					thread.start_new_thread(program.run,(self,event['from']))
					print "created thread"
				except:
					traceback.print_exc()
					log("Error creating thread")
			if event['wylio']['value']:
				signal = event['wylio']['value']['signal']
				value = event['wylio']['value']['value']
				if program != None:
					program.sendSensorInput(signal,value)
		except:
			traceback.print_exc()
			
	def connect(self,jid,password):
		if self.connection == None:
			self.connection = ClientXMPP(jid, password)
		register_stanza_plugin (Message, WylioStanza)
		register_stanza_plugin (WylioStanza, ValueStanza)
		self.connection.add_event_handler("connected", self.connected)
		self.connection.add_event_handler("disconnected", self.disconnected)
		self.connection.add_event_handler("failed_auth", self.failed_auth)
		self.connection.add_event_handler("session_start", self.start)
		self.connection.add_event_handler("message", self.message)
		self.connection.register_handler(Callback("Wylio", StanzaPath("message/wylio"), self.message_wylio))
		print "connect"
		self.connection.connect()
		self.connection.process(block=True)
		print "connected"
		
	def start(self,event):
		log("WylioServer started")
		self.connection.send_presence()
		print "presence sent"
		self.connection.get_roster()