def __init__(self, socket): #print("initializing receiver") self.socket = socket self.connected = False self.observe = None self.observed = [] self.inMsgs = {} self.outMsgs = {} self.puback = MQTTSN.Pubacks() self.pubrec = MQTTSN.Pubrecs() self.pubrel = MQTTSN.Pubrels() self.pubcomp = MQTTSN.Pubcomps()
def publish(self, topic, payload, qos=0, retained=False): publish = MQTTSN.Publishes() publish.Flags.QoS = qos publish.Flags.Retain = retained self.puback_flag = False #reset flag if type(topic) == str and len(topic) > 2: print("invalid topic") return None if qos in [-1, 0]: #qos 0 or -1 publish.MsgId = 0 else: publish.MsgId = self.__nextMsgid() print("MsgId=", publish.MsgId) if type(topic) == int: publish.Flags.TopicIdType = MQTTSN.TOPIC_NORMAL publish.TopicId = topic if type(topic) == str and len(topic) <= 2: publish.Flags.TopicIdType = MQTTSN.TOPIC_SHORTNAME publish.TopicId = topic ######### publish.Data = payload a = publish.pack() self.sock.send(a.encode()) self.__receiver.outMsgs[publish.MsgId] = publish #self.lookfor(MQTTSN.PUBACK) #return(self.waitfor(MQTTSN.PUBACK)) return publish.MsgId
def __init__(self, socket,client): #print("creating receiver object") self.socket = socket self.client=client self.connected = False self.running_loop = False self.observe = None self.observed = [] self.inMsgs = {} self.outMsgs = {} self.puback = MQTTSN.Pubacks() self.pubrec = MQTTSN.Pubrecs() self.pubrel = MQTTSN.Pubrels() self.pubcomp = MQTTSN.Pubcomps()
def publish(self, topic, payload, qos=1, retained=False): if isinstance(payload, str) or isinstance(payload, bytes): pass else: raise TypeError('Payload must be str or bytes.') publish = MQTTSN.Publishes() publish.Flags.QoS = qos publish.Flags.Retain = retained if isinstance(topic, str): publish.Flags.TopicIdType = MQTTSN.TOPIC_SHORTNAME publish.TopicName = topic else: publish.Flags.TopicIdType = MQTTSN.TOPIC_NORMAL publish.TopicId = topic #print('Topico =', topic) #print('Id_de_topico =', msg.TopicId) if qos in [-1, 0]: publish.MsgId = 0 else: publish.MsgId = self.__nextMsgid() #print("MsgId", publish.MsgId) self.__receiver.outMsgs[publish.MsgId] = publish publish.Data = payload self.sock.send(publish.pack()) return publish.MsgId
def connect(self, cleansession=True): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #self.sock.settimeout(5.0) self.sock.connect((self.host, self.port)) connect = MQTTSN.Connects() connect.ClientId = self.clientid connect.CleanSession = cleansession connect.KeepAliveTimer = 0 self.sock.send(connect.pack()) response, address = MQTTSN.unpackPacket(MQTTSN.getPacket(self.sock)) assert response.mh.MsgType == MQTTSN.CONNACK self.startReceiver()
def disconnect(self): disconnect = MQTTSN.Disconnects() if self.__receiver: self.__receiver.lookfor(MQTTSN.DISCONNECT) self.sock.send(disconnect.pack()) msg = self.waitfor(MQTTSN.DISCONNECT) self.stopReceiver()
def publish(topic, payload, retained=False, port=1883, host="localhost"): publish = MQTTSN.Publishes() publish.Flags.QoS = 3 publish.Flags.Retain = retained if isinstance(payload, str): pass elif isinstance(payload, bytes): payload = payload.decode() if isinstance(topic, str): if len(topic) > 2: publish.Flags.TopicIdType = MQTTSN.TOPIC_NORMAL publish.TopicId = len(topic) payload = topic + payload else: publish.Flags.TopicIdType = MQTTSN.TOPIC_SHORTNAME publish.TopicName = topic else: publish.Flags.TopicIdType = MQTTSN.TOPIC_NORMAL publish.TopicId = topic publish.MsgId = 0 #print("payload", payload) publish.Data = payload sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(publish.pack(), (host, port)) sock.close() return
def subscribe(self, topic, qos=2): self.suback_flag = False self.sub_topicid = "" self.sub_msgid = "" self.sub_rc = "" subscribe = MQTTSN.Subscribes() subscribe.MsgId = self.__nextMsgid() if type(topic) is str: #print("topic is string ",topic) subscribe.TopicName = topic if len(topic) > 2: subscribe.Flags.TopicIdType = MQTTSN.TOPIC_NORMAL else: subscribe.Flags.TopicIdType = MQTTSN.TOPIC_SHORTNAME else: subscribe.TopicId = topic # should be int subscribe.Flags.TopicIdType = MQTTSN.TOPIC_PREDEFINED subscribe.Flags.QoS = qos self.sock.send(subscribe.pack().encode()) self.lookfor(MQTTSN.SUBACK) msg = self.waitfor(MQTTSN.SUBACK, subscribe.MsgId) if msg != None: if subscribe.MsgId == msg.MsgId: print("received suback for msgid", msg.MsgId) print("topicid= ", msg.TopicId) return msg.ReturnCode, msg.TopicId else: raise SystemExit("Subscription failed quitting") return (None, None) else: return (None, None)
def connect(self, cleansession=True): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.settimeout(5.0) self.sock.connect((self.host, self.port)) connect = MQTTSN.Connects() connect.ClientId = self.clientid connect.CleanSession = cleansession connect.KeepAliveTimer = 0 self.sock.send(connect.pack()) response, address = MQTTSN.unpackPacket(MQTTSN.getPacket(self.sock)) assert response.mh.MsgType == MQTTSN.CONNACK self.startReceiver()
def register(self, topicName): register = MQTTSN.Registers() register.TopicName = topicName if self.__receiver: self.__receiver.lookfor(MQTTSN.REGACK) self.sock.send(register.pack()) msg = self.waitfor(MQTTSN.REGACK, register.MsgId) return msg.TopicId
def unsubscribe(self, topics): unsubscribe = MQTTSN.Unsubscribes() unsubscribe.MsgId = self.__nextMsgid() unsubscribe.data = topics if self.__receiver: self.__receiver.lookfor(MQTTSN.UNSUBACK) self.sock.send(unsubscribe.pack()) msg = self.waitfor(MQTTSN.UNSUBACK, unsubscribe.MsgId)
def gwinfo(self, multicast_port, multicast_group): gwinfo = MQTTSN.GWInfos() if self.host != "": print("adding host ", type(gwinfo.GwAdd)) gwinfo.GwAdd = self.host m = gwinfo.pack() m = m.encode() #turn to bytes print(type(m)) print("address type ", type(gwinfo.GwAdd)) print("sending GW packet ", gwinfo) self.sock.sendto(m, (multicast_group, multicast_port))
def Search_GWs(self, multicast_port, multicast_group): if not self.multicast_flag: self.create_multicast_socket(multicast_port, multicast_group) searchgw = MQTTSN.SearchGWs() #print(type(searchgw)) m = searchgw.pack() #print(type(m)) m = m.encode() #turn to bytes #print(type(m)) print("sending GW packet ", searchgw) #sock2.sendto(m,(s_group, s_port)) sock2.sendto(m, group)
def connect(self, host, port=1883, keepalive=60): self.host = host self.port = port self.bad_connect_flag = False self.connected_flag = False self.keepalive = keepalive self.sock.connect((self.host, self.port)) connect = MQTTSN.Connects() connect.ClientId = self.clientid connect.CleanSession = self.cleansession connect.KeepAliveTimer = self.keepalive self.sock.send(connect.pack().encode())
def register(self, topicName): register = MQTTSN.Registers() register.TopicName = topicName if self.__receiver: #this uses callbacks self.__receiver.lookfor(MQTTSN.REGACK) #print("\n\nsending register ",register.pack(),"\n\n") self.sock.send(register.pack().encode()) self.lookfor(MQTTSN.REGACK) msg = self.waitfor(MQTTSN.REGACK, register.MsgId) if msg: return msg.TopicId else: return None
def subscribe(self, topic, qos=2): subscribe = MQTTSN.Subscribes() subscribe.MsgId = self.__nextMsgid() if type(topic) == types.StringType: subscribe.TopicName = topic if len(topic) > 2: subscribe.Flags.TopicIdType = MQTTSN.TOPIC_NORMAL else: subscribe.Flags.TopicIdType = MQTTSN.TOPIC_SHORTNAME else: subscribe.TopicId = topic # should be int subscribe.Flags.TopicIdType = MQTTSN.TOPIC_PREDEFINED subscribe.Flags.QoS = qos if self.__receiver: self.__receiver.lookfor(MQTTSN.SUBACK) self.sock.send(subscribe.pack()) msg = self.waitfor(MQTTSN.SUBACK, subscribe.MsgId) return msg.ReturnCode, msg.TopicId
def publish(self, topic, payload, qos=0, retained=False): publish = MQTTSN.Publishes() publish.Flags.QoS = qos publish.Flags.Retain = retained if type(topic) == types.StringType: publish.Flags.TopicIdType = MQTTSN.TOPIC_SHORTNAME publish.TopicName = topic else: publish.Flags.TopicIdType = MQTTSN.TOPIC_NORMAL publish.TopicId = topic if qos in [-1, 0]: publish.MsgId = 0 else: publish.MsgId = self.__nextMsgid() print "MsgId", publish.MsgId self.__receiver.outMsgs[publish.MsgId] = publish publish.Data = payload self.sock.send(publish.pack()) return publish.MsgId
def subscribe(self, topic, qos=1): subscribe = MQTTSN.Subscribes() subscribe.MsgId = self.__nextMsgid() if isinstance(topic, str): subscribe.TopicName = topic if len(topic) > 2: subscribe.Flags.TopicIdType = MQTTSN.TOPIC_NORMAL else: subscribe.Flags.TopicIdType = MQTTSN.TOPIC_SHORTNAME else: subscribe.TopicId = topic # should be int subscribe.Flags.TopicIdType = MQTTSN.TOPIC_PREDEFINED subscribe.Flags.QoS = qos if self.__receiver: self.__receiver.lookfor(MQTTSN.SUBACK) self.sock.send(subscribe.pack()) msg = self.waitfor(MQTTSN.SUBACK, subscribe.MsgId) #print('Id_de_topico =',msg.TopicId) #print('Topico =',topic) self.topicmap.register(msg.TopicId, topic) return msg.ReturnCode, msg.TopicId
def publish(topic, payload, retained=False, port=1884, host="192.168.137.150"): publish = MQTTSN.Publishes() publish.Flags.QoS = 3 publish.Flags.Retain = retained if type(topic) == types.StringType: if len(topic) > 2: publish.Flags.TopicIdType = MQTTSN.TOPIC_NORMAL publish.TopicId = len(topic) payload = topic + payload else: publish.Flags.TopicIdType = MQTTSN.TOPIC_SHORTNAME publish.TopicName = topic else: publish.Flags.TopicIdType = MQTTSN.TOPIC_NORMAL publish.TopicId = topic publish.MsgId = 0 print "payload", payload publish.Data = payload sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(publish.pack(), (host, port)) sock.close() return
def publish(topic, payload, retained=False, port=1883, host="localhost"): publish = MQTTSN.Publishes() publish.Flags.QoS = 3 publish.Flags.Retain = retained if type(topic) == bytes: if len(topic) > 2: publish.Flags.TopicIdType = MQTTSN.TOPIC_NORMAL publish.TopicId = len(topic) payload = topic + payload else: publish.Flags.TopicIdType = MQTTSN.TOPIC_NORMAL publish.TopicName = topic if type(topic) == str and len(topic) <= 2: publish.Flags.TopicIdType = MQTTSN.TOPIC_SHORTNAME publish.TopicId = topic publish.MsgId = 0 publish.Data = payload a = publish.pack() sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(a.encode(), (host, port)) sock.close() return
def testFlags(self): flags = MQTTSN.Flags() outflags = MQTTSN.Flags() buf = flags.pack() outflags.unpack(buf[0]) assert flags == outflags
def receive(self, topicmap, callback=None): packet = None try: packet, address = MQTTSN.unpackPacket(MQTTSN.getPacket( self.socket)) except: if sys.exc_info()[0] != socket.timeout: #print("unexpected exception", sys.exc_info()) raise sys.exc_info() if packet == None: time.sleep(0.1) return elif debug: print(packet) if self.observe == packet.mh.MsgType: #print("observed", packet) self.observed.append(packet) elif packet.mh.MsgType == MQTTSN.ADVERTISE: if hasattr(callback, "advertise"): callback.advertise(address, packet.GwId, packet.Duration) elif packet.mh.MsgType == MQTTSN.REGISTER: topicmap.register(packet.TopicId, packet.TopicName) elif packet.mh.MsgType == MQTTSN.PUBACK: "check if we are expecting a puback" if packet.MsgId in self.outMsgs and \ self.outMsgs[packet.MsgId].Flags.QoS == 1: del self.outMsgs[packet.MsgId] if hasattr(callback, "published"): callback.published(packet.MsgId) else: raise Exception("No QoS 1 message with message id " + str(packet.MsgId) + " sent") elif packet.mh.MsgType == MQTTSN.PUBREC: if packet.MsgId in self.outMsgs: self.pubrel.MsgId = packet.MsgId self.socket.send(self.pubrel.pack()) else: raise Exception("PUBREC received for unknown msg id "+ \ str(packet.MsgId)) elif packet.mh.MsgType == MQTTSN.PUBREL: "release QOS 2 publication to client, & send PUBCOMP" msgid = packet.MsgId if packet.MsgId not in self.inMsgs: pass # what should we do here? else: pub = self.inMsgs[packet.MsgId] topicname = topicmap.registered[pub.TopicId] if callback == None or \ callback.messageArrived(topicname, pub.Data, 2, pub.Flags.Retain, pub.MsgId): del self.inMsgs[packet.MsgId] self.pubcomp.MsgId = packet.MsgId self.socket.send(self.pubcomp.pack()) if callback == None: return (topicname, pub.Data, 2, pub.Flags.Retain, pub.MsgId) elif packet.mh.MsgType == MQTTSN.PUBCOMP: "finished with this message id" if packet.MsgId in self.outMsgs: del self.outMsgs[packet.MsgId] if hasattr(callback, "published"): callback.published(packet.MsgId) else: raise Exception("PUBCOMP received for unknown msg id "+ \ str(packet.MsgId)) elif packet.mh.MsgType == MQTTSN.PUBLISH: "finished with this message id" if packet.Flags.QoS in [0, 3]: qos = packet.Flags.QoS topicname = topicmap.registered[packet.TopicId] data = packet.Data if qos == 3: qos = -1 if packet.Flags.TopicIdType == MQTTSN.TOPICID: topicname = packet.Data[:packet.TopicId] data = packet.Data[packet.TopicId:] if callback == None: return (topicname, data, qos, packet.Flags.Retain, packet.MsgId) else: callback.messageArrived(topicname, data, qos, packet.Flags.Retain, packet.MsgId) elif packet.Flags.QoS == 1: topicname = topicmap.registered[packet.TopicId] if callback == None: return (topicname, packet.Data, 1, packet.Flags.Retain, packet.MsgId) else: if callback.messageArrived(topicname, packet.Data, 1, packet.Flags.Retain, packet.MsgId): self.puback.MsgId = packet.MsgId self.socket.send(self.puback.pack()) elif packet.Flags.QoS == 2: self.inMsgs[packet.MsgId] = packet self.pubrec.MsgId = packet.MsgId self.socket.send(self.pubrec.pack()) else: raise Exception("Unexpected packet" + str(packet)) return packet
def disconnect(self): disconnect = MQTTSN.Disconnects() self.sock.send(disconnect.pack().encode()) self.lookfor(MQTTSN.DISCONNECT) msg = self.waitfor(MQTTSN.DISCONNECT) return msg
def receive(self, callback=None): packet = None try: packet, address = MQTTSN.unpackPacket(MQTTSN.getPacket(self.socket)) #print("getting packet",packet,"\n") except Exception as e: if sys.exc_info()[0] != socket.timeout: print("getting packet unexpected exception", sys.exc_info()) raise Exception("Packet receive error ",e) if packet == None: return elif debug: print("\nReceived packet data =",packet,"\n") return if self.observe == packet.mh.MsgType: #print("found what we were looking for",self.observe) self.observed.append(packet) return if packet.mh.MsgType == MQTTSN.CONNACK: if hasattr(callback, "on_connect"): print("found on connect") callback.on_connect(self.client,address,packet.ReturnCode) elif packet.mh.MsgType == MQTTSN.DISCONNECT: if hasattr(callback, "on_disconnect"): callback.on_disconnect(self.client,packet.Duration) elif packet.mh.MsgType == MQTTSN.SUBACK: ##added by me if hasattr(callback, "on_subscribe"): callback.on_subscribe(self.client,packet.TopicId,packet.MsgId,packet.ReturnCode) elif packet.mh.MsgType == MQTTSN.ADVERTISE: if hasattr(callback, "advertise"): callback.advertise(self.client,address, packet.GwId, packet.Duration) elif packet.mh.MsgType == MQTTSN.REGISTER: if callback and hasattr(callback, "register"): callback.register(self.client,packet.TopicId, packet.TopicName) elif packet.mh.MsgType == MQTTSN.REGACK: if callback and hasattr(callback, "regack"): print("received regack") callback.regack(self.client,packet.TopicId) elif packet.mh.MsgType == MQTTSN.PUBACK: "check if we are expecting a puback" if packet.MsgId in self.outMsgs and \ self.outMsgs[packet.MsgId].Flags.QoS == 1: del self.outMsgs[packet.MsgId] if hasattr(callback, "published"): callback.published(self.client,packet.MsgId) else: raise Exception("No QoS 1 message with message id "+str(packet.MsgId)+" sent") elif packet.mh.MsgType == MQTTSN.PUBREC: if packet.MsgId in self.outMsgs: self.pubrel.MsgId = packet.MsgId self.socket.send(self.pubrel.pack()) else: raise Exception("PUBREC received for unknown msg id "+ \ str(packet.MsgId)) elif packet.mh.MsgType == MQTTSN.PUBREL: "release QOS 2 publication to self.client, & send PUBCOMP" msgid = packet.MsgId if msgid not in self.inMsgs: pass # what should we do here? else: pub = self.inMsgs[packet.MsgId] if callback == None or \ callback.messageArrived(self.client,pub.TopicId, pub.Data, 2, pub.Flags.Retain, pub.MsgId): del self.inMsgs[packet.MsgId] self.pubcomp.MsgId = packet.MsgId self.socket.send(self.pubcomp.pack()) if callback == None: return (pub.pub.TopicId, pub.Data, 2, pub.Flags.Retain, pub.MsgId) elif packet.mh.MsgType == MQTTSN.PUBCOMP: #"finished with this message id" if packet.MsgId in self.outMsgs: del self.outMsgs[packet.MsgId] if hasattr(callback, "published"): callback.published(self.client,packet.MsgId) else: raise Exception("PUBCOMP received for unknown msg id "+ \ str(packet.MsgId)) elif packet.mh.MsgType == MQTTSN.PUBLISH: #"finished with this message id ?" #print("here ",packet) qos = packet.Flags.QoS topicname = packet.TopicName TopicId=packet.TopicId data = packet.Data #print("here ",TopicId) if packet.Flags.QoS in [0, 3]: if qos == 3: qos = -1 if packet.Flags.TopicIdType == MQTTSN.TOPICID: topicname = packet.Data[:packet.TopicId] data = packet.Data[packet.TopicId:] if callback == None: return (TopicId, data, qos, packet.Flags.Retain, packet.MsgId) else: callback.messageArrived(self.client,TopicId, data, qos, packet.Flags.Retain, packet.MsgId) elif packet.Flags.QoS == 1: if callback == None: return (packet.TopicId, packet.Data, 1, packet.Flags.Retain, packet.MsgId) else: if callback.messageArrived(self.client,TopicId,data, 1, packet.Flags.Retain, packet.MsgId): self.puback.MsgId = packet.MsgId self.socket.send(self.puback.pack().encode()) elif packet.Flags.QoS == 2: self.inMsgs[packet.MsgId] = packet self.pubrec.MsgId = packet.MsgId self.socket.send(self.pubrec.pack()) elif packet.mh.MsgType == MQTTSN.SEARCHGW: ##added by me print(" Searching Gateway ") if hasattr(callback, "searchgw"): callback.searchgw(self.client,packet) elif packet.mh.MsgType == MQTTSN.ADVERTISE: ##added by me print(" Advertise info is ") if hasattr(callback, "advertise"): callback.advertise(self.client,packet) elif packet.mh.MsgType == MQTTSN.GWINFO: ##added by me print(" Search Gateway info is ") if hasattr(callback, "gwinfo"): print(" Search Gateway callback ") callback.gwinfo(self.client,packet) else: print("unexpected packet",packet) #raise Exception("Unexpected packet"+str(packet)) return "" return packet
def receive(self, callback=None): packet = None try: packet, address = MQTTSN.unpackPacket(MQTTSN.getPacket(self.socket)) except: if sys.exc_info()[0] != socket.timeout: print "unexpected exception", sys.exc_info() raise sys.exc_info() if packet == None: time.sleep(0.1) return elif debug: print packet if self.observe == packet.mh.MsgType: print "observed", packet self.observed.append(packet) elif packet.mh.MsgType == MQTTSN.ADVERTISE: if hasattr(callback, "advertise"): callback.advertise(address, packet.GwId, packet.Duration) elif packet.mh.MsgType == MQTTSN.REGISTER: if callback and hasattr(callback, "register"): callback.register(packet.TopicId, packet.Topicname) elif packet.mh.MsgType == MQTTSN.PUBACK: "check if we are expecting a puback" if self.outMsgs.has_key(packet.MsgId) and \ self.outMsgs[packet.MsgId].Flags.QoS == 1: del self.outMsgs[packet.MsgId] if hasattr(callback, "published"): callback.published(packet.MsgId) else: raise Exception("No QoS 1 message with message id "+str(packet.MsgId)+" sent") elif packet.mh.MsgType == MQTTSN.PUBREC: if self.outMsgs.has_key(packet.MsgId): self.pubrel.MsgId = packet.MsgId self.socket.send(self.pubrel.pack()) else: raise Exception("PUBREC received for unknown msg id "+ \ str(packet.MsgId)) elif packet.mh.MsgType == MQTTSN.PUBREL: "release QOS 2 publication to client, & send PUBCOMP" msgid = packet.MsgId if not self.inMsgs.has_key(msgid): pass # what should we do here? else: pub = self.inMsgs[packet.MsgId] if callback == None or \ callback.messageArrived(pub.TopicName, pub.Data, 2, pub.Flags.Retain, pub.MsgId): del self.inMsgs[packet.MsgId] self.pubcomp.MsgId = packet.MsgId self.socket.send(self.pubcomp.pack()) if callback == None: return (pub.TopicName, pub.Data, 2, pub.Flags.Retain, pub.MsgId) elif packet.mh.MsgType == MQTTSN.PUBCOMP: "finished with this message id" if self.outMsgs.has_key(packet.MsgId): del self.outMsgs[packet.MsgId] if hasattr(callback, "published"): callback.published(packet.MsgId) else: raise Exception("PUBCOMP received for unknown msg id "+ \ str(packet.MsgId)) elif packet.mh.MsgType == MQTTSN.PUBLISH: "finished with this message id" if packet.Flags.QoS in [0, 3]: qos = packet.Flags.QoS topicname = packet.TopicName data = packet.Data if qos == 3: qos = -1 if packet.Flags.TopicIdType == MQTTSN.TOPICID: topicname = packet.Data[:packet.TopicId] data = packet.Data[packet.TopicId:] if callback == None: return (topicname, data, qos, packet.Flags.Retain, packet.MsgId) else: callback.messageArrived(topicname, data, qos, packet.Flags.Retain, packet.MsgId) elif packet.Flags.QoS == 1: if callback == None: return (packet.topicName, packet.Data, 1, packet.Flags.Retain, packet.MsgId) else: if callback.messageArrived(packet.TopicName, packet.Data, 1, packet.Flags.Retain, packet.MsgId): self.puback.MsgId = packet.MsgId self.socket.send(self.puback.pack()) elif packet.Flags.QoS == 2: self.inMsgs[packet.MsgId] = packet self.pubrec.MsgId = packet.MsgId self.socket.send(self.pubrec.pack()) else: raise Exception("Unexpected packet"+str(packet)) return packet