Пример #1
0
	def __init__(self, client, broker, port, endpoints):
		self.client = client
		self.ep = endpoints
		self.broker = broker
		self.port = port
		self.myMqttClient = MyMQTT(self.client, self.broker, self.port, self)
		self.lastTimeSensor = 0
Пример #2
0
 def __init__(self, code, lat, lon, client, broker, port, topic):
     self.client = client
     self.topic = topic
     threading.Thread.__init__(self)
     self.myMqttClient = MyMQTT(self.client, broker, port, self)
     self.lastCheckSun = 0
     self.lastCheckWeather = 0
     self.code = code
     self.lat = lat
     self.lon = lon
     self.exit = 0
     self.lastUpdate = 0
     #The final values for the 3 config
     self.sun = [240, 60, 0]
     self.cloud = [60, 240, 180]
     self.rain = [0, 60, 240]
     #Starting color
     self.color = [0, 0, 0]
     self.map = {
         'Snow': 2,
         'Sleet': 2,
         'Hail': 2,
         'Thunderstorm': 2,
         'Heavy Rain': 2,
         'Light Rain': 1,
         'Showers': 1,
         'Heavy Cloud': 1,
         'Light Cloud': 0,
         'Clear': 0
     }
Пример #3
0
    def __init__(self, client, broker, port, endpoints):
        self.client = client
        self.ep = endpoints
        self.broker = broker
        self.port = port
        self.myMqttClient = MyMQTT(self.client, self.broker, self.port, self)
        self.temp = 0
        #Valori di base dei set points
        self.FTEMP_MIN = [15.0, 20.0]
        self.FTEMP_MAX = [30.0, 25.0]
        self.LTEMP_MIN = [10.0, 15.0]
        self.LTEMP_MAX = [15.0, 20.0]
        self.presence = 0
        self.timeStartMovement = 0
        self.PIR_timeout = 1800  # 30 minutes in seconds
        self.PIR_presence = 0

        self.SOUND_presence = 0
        self.min_n_events = 5
        self.vetSounds = [0 for l in range(self.min_n_events - 1)]
        self.startFlag = 0
        self.SOUND_interval = 600  # 10 minutes in seconds
        self.SOUND_timeout = 3600  # 1h in seconds
        self.lastTime = 0
        self.lastTimeSensor = 0
        self.sel = 0
        self.thread = ""
Пример #4
0
 def __init__(self, buildingID, floorID, roomID, sensorID, broker, port):
     self.buildingID = buildingID
     self.floorID = floorID
     self.roomID = roomID
     self.sensorID = str(sensorID)
     self.topic = '/'.join(
         [self.buildingID, self.floorID, self.roomID, self.sensorID])
     self.client = MyMQTT(self.sensorID, broker, port, None)
     self.__message = {
         'buildingID':
         self.buildingID,
         'floorID':
         self.floorID,
         'roomID':
         self.roomID,
         'bn':
         self.sensorID,
         'e': [{
             'n': 'temperature',
             'value': '',
             'timestamp': '',
             'unit': 'C'
         }, {
             'n': 'humidity',
             'value': '',
             'timestamp': '',
             'unit': '%'
         }]
     }
Пример #5
0
class TempSensor:
    def __init__(self, sensorID, mu, sigma, broker, port, topic):
        self.mu = mu
        self.sigma = sigma
        self.topic = topic
        self.__message = {
            "bn": sensorID,
            "e": [{
                "n": "temperature",
                "u": "Cel",
                "t": 0,
                "v": 0
            }]
        }
        self.client = MyMQTT(sensorID, broker, port, None)
        self.client.start()

    def getData(self):
        return np.random.normal(mu, sigma, 1)[0]

    def sendData(self):
        message = self.__message.copy()
        message["e"][0]["v"] = self.getData()
        message["e"][0]["t"] = time.time()
        self.client.myPublish(self.topic, message)
Пример #6
0
 def __init__(self,clientID,broker,port,topic,apikey):
     self.apikey=apikey
     self.baseUrl="https://api.thingspeak.com/update?api_key="+self.apikey+"&"
     self.client=MyMQTT(clientID,broker,port,self)
     self.topic=topic
     self.client.start()
     self.client.mySubscribe(topic)
Пример #7
0
    def __init__(self, clientID, topic, broker, port):

        #self.regManager=RegManager()
        self.clientID = clientID
        self.port = port
        self.topic = topic
        self.broker = broker
        self.client = MyMQTT(clientID, self.broker, self.port, self)
        self.zone = {'zone1': 0, 'zone2': 0, 'zone3': 0, 'zone4': 0}
    def __init__(self, clientID, topic, broker, port):

        #self.regManager=RegManager()
        self.clientID = clientID
        self.port = port
        self.topic = topic
        self.broker = broker
        self.client = MyMQTT(clientID, self.broker, self.port, self)
        self.zone = {'zone1': 0, 'zone2': 0, 'zone3': 0, 'zone4': 0}
        #getdata=self.regManager.get_data()
        self.light = {'light1': 0, 'light2': 0, 'light3': 0, 'light4': 0}
Пример #9
0
 def __init__(self, clientID, topic, broker, port):
     self.client = MyMQTT(clientID, broker, port, self)
     self.topic = topic
     self.status = None
     self.__message = {
         "clientID": clientID,
         "n": "switch",
         "value": None,
         "timestamp": "",
         "unit": "bool"
     }
Пример #10
0
    def __init__(self, clientID, topic, broker, port):
        self.topic = topic
        self.__message = {
            'client': clientID,
            'n': 'switch',
            'value': None,
            'timestamp': '',
            'unit': "bool"
        }

        self.client = MyMQTT(clientID, broker, port, None)
        self.statusToBool = {"on": 1, "off": 0}
Пример #11
0
 def start_MyMQTT(self, broker, port):
     self.client = MyMQTT(self.deviceID, broker, port, None)
     self.__message = {
         'bn': self.deviceID,
         'e': [{
             'n': 'Oxygen Level',
             'u': '%',
             't': None,
             'v': None
         }]
     }
     self.client.start()
Пример #12
0
 def start_MyMQTT(self, broker, port):
     self.client = MyMQTT(self.deviceID, broker, port, None)
     self.__message = {
         'bn': self.deviceID,
         'e': [{
             'n': 'temperature',
             'u': 'Cel',
             't': None,
             'v': None
         }]
     }
     self.client.start()
Пример #13
0
class ThingSpeakGateway():
    def __init__(self,clientID,broker,port,topic,apikey):
        self.apikey=apikey
        self.baseUrl="https://api.thingspeak.com/update?api_key="+self.apikey+"&"
        self.client=MyMQTT(clientID,broker,port,self)
        self.topic=topic
        self.client.start()
        self.client.mySubscribe(topic)
    def notify(self,topic,payload):
        jsonPayload=json.loads(payload)
        value=jsonPayload["e"][0]["v"]
        r=requests.get(self.baseUrl+"field1="+str(value))
        print(r.text)
Пример #14
0
 def __init__(self, clientID, topic, broker, port):
     self.client = MyMQTT(clientID, broker, port, self)
     self.topic = topic
     self.status = None
     self.__message = {
         "bn": "sensor1",
         "e": [{
             "n": "heartrate",
             "u": "bpm",
             "t": "",
             "v": 0
         }]
     }
Пример #15
0
class Client():
    def __init__(self,user,chat):
        self.clientID=user
        self.answer=False
        self.topic=chat
        self.client=MyMQTT(self.clientID,'localhost',1883,self)
    def notify(self,topic,msg):
        payload=json.loads(msg)
        sent_from=payload['user']
        text=payload['text']
        if sent_from!= self.clientID:
            self.answer=True
            print('{}: {}'.format(sent_from,text))
    def publish(self,text):
        message={'user':self.clientID,'text':text}
        self.answer=False
        self.client.myPublish(self.topic,json.dumps(message))
    def run(self):
        self.client.start()
        print('{} has started'.format(self.clientID))
    
    def end(self):
        self.client.stop()
        print('{} has stopped'.format(self.clientID))
    def subscribe(self):
        self.client.mySubscribe(self.topic)
Пример #16
0
class SwitchBot:
    def __init__(self, token, broker, port, topic):
        # Local token
        self.tokenBot = token
        # Catalog token
        # self.tokenBot=requests.get("http://catalogIP/telegram_token").json()["telegramToken"]
        self.bot = telepot.Bot(self.tokenBot)
        self.client = MyMQTT("telegramBot", broker, port, None)
        self.client.start()
        self.topic = topic
        self.__message = {
            'bn': "telegramBot",
            'e': [
                {
                    'n': 'switch',
                    'v': '',
                    't': '',
                    'u': 'bool'
                },
            ]
        }
        MessageLoop(self.bot, {
            'chat': self.on_chat_message,
            'callback_query': self.on_callback_query
        }).run_as_thread()

    def on_chat_message(self, msg):
        content_type, chat_type, chat_ID = telepot.glance(msg)
        message = msg['text']
        if message == "/switch":
            buttons = [[
                InlineKeyboardButton(text=f'ON 🟡', callback_data=f'on'),
                InlineKeyboardButton(text=f'OFF ⚪', callback_data=f'off')
            ]]
            keyboard = InlineKeyboardMarkup(inline_keyboard=buttons)
            self.bot.sendMessage(chat_ID,
                                 text='What do you want to do',
                                 reply_markup=keyboard)
        else:
            self.bot.sendMessage(chat_ID, text="Command not supported")

    def on_callback_query(self, msg):
        query_ID, chat_ID, query_data = telepot.glance(msg,
                                                       flavor='callback_query')

        payload = self.__message.copy()
        payload['e'][0]['v'] = query_data
        payload['e'][0]['t'] = time.time()
        self.client.myPublish(self.topic, payload)
        self.bot.sendMessage(chat_ID, text=f"Led switched {query_data}")
Пример #17
0
class WeightControl(threading.Thread):
    def __init__(self, serviceID, topic, broker, port, publicURL):
        threading.Thread.__init__(self)
        self.serviceID = serviceID
        self.topic = topic
        self.broker = broker
        self.port = port
        self.payload = {
            "serviceID": self.serviceID,
            "Topic": f"{self.topic}/{self.serviceID}/weightControl",
            "Resource": "WeightControl",
            "Timestamp": None
        }
        self.client = MyMQTT(self.serviceID, self.broker, self.port, self)
        self.client.start()
        conf2 = json.load(open("settingsboxcatalog.json"))
        self.timerequestTopic = conf2["timerequestTopic"]
        self.timerequest = conf2["timerequest"]
        self.count = 6
        self.url = publicURL

    def request(self):
        # Sottoscrizione al boxcatalog
        self.payload["Timestamp"] = time.time()
        requests.put(self.url+"/Service", json=self.payload)  #

    def topicRequest(self):
        # Richiesta GET per topic
        for i in range(5):
            try:
                r = requests.get(self.url+"/GetMass")
            except:
                print("!!! except -> GetMass !!!")
                time.sleep(5)
        jsonBody = json.loads(r.content)
        listatopicSensor = jsonBody["topics"]
        for topic in listatopicSensor:
            self.client.mySubscribe(topic)

    def run(self):
        while True:
            self.topicRequest()
            if self.count % (self.timerequest/self.timerequestTopic) == 0:
                self.request()
                self.count=0
            self.count += 1
            time.sleep(self.timerequestTopic)

    def notify(self, topic, msg):
        payload = json.loads(msg)
        print(f"\nWeight Control Service received a message")
        if payload['e'][0]['v'] == 0:
            messaggio = {'Mass':1, "DeviceID": payload['bn']}       # CODICE PER DIRE CHE ORGANO NON è INSERITO NELLA SCATOLA
        else:
            messaggio = {'Mass': 0, "DeviceID":payload['bn']}      # CODICE PER DIRE CHE ORGANO è INSERITO NELLA SCATOLA
        self.client.myPublish(f"{self.topic}/{self.serviceID}/weightControl", messaggio)

    def stop_MyMQTT(self):
        self.client.stop()
        print('{} has stopped'.format(self.serviceID))
Пример #18
0
 def __init__(self, sensorID, mu, sigma, broker, port, topic):
     self.mu = mu
     self.sigma = sigma
     self.topic = topic
     self.__message = {
         "bn": sensorID,
         "e": [{
             "n": "temperature",
             "u": "Cel",
             "t": 0,
             "v": 0
         }]
     }
     self.client = MyMQTT(sensorID, broker, port, None)
     self.client.start()
Пример #19
0
 def start_MyMQTT(self, broker, port):
     self.client = MyMQTT(self.deviceID, broker, port, None)
     self.__message = {
         'bn':
         self.deviceID,
         'e': [{
             'n': 'GPS',
             'u': 'DD',
             't': None,
             'v_lat': None,
             'v_lon': None,
             'v_time': None
         }]
     }
     self.client.start()
Пример #20
0
 def start_MyMQTT(self, broker, port):
     self.client = MyMQTT(self.deviceID, broker, port, None)
     self.__message = {
         'bn':
         self.deviceID,
         'e': [{
             'n': 'acceleration',
             'u': 'm/s^2',
             't': None,
             'v_xaxis':
             None,  #accelerometri misurano accelerazione in tutte e tre le direzioni spaziali
             'v_yaxis': None,
             'v_zaxis': None
         }]
     }
     self.client.start()
Пример #21
0
 def __init__(self, token):
     # Local token
     self.tokenBot = token
     # Catalog token
     # self.tokenBot=requests.get("http://catalogIP/telegram_token").json()["telegramToken"]
     self.bot = telepot.Bot(self.tokenBot)
     MessageLoop(self.bot, {'chat': self.on_chat_message}).run_as_thread()
     self.client = MyMQTT("telegramBot", broker, port, None)
Пример #22
0
class Customermanager():
    def __init__(self, clientID, topic, broker, port):

        #self.regManager=RegManager()
        self.clientID = clientID
        self.port = port
        self.topic = topic
        self.broker = broker
        self.client = MyMQTT(clientID, self.broker, self.port, self)
        self.zone = {'zone1': 0, 'zone2': 0, 'zone3': 0, 'zone4': 0}
        #getdata=self.regManager.get_data()

    def start(self):
        self.client.start()
        self.client.mySubscribe(self.topic)

    def stop(self):
        self.client.stop()

    def notify(self, topic, msg):

        payload = json.loads(msg)

        laserID = payload["laserID"]
        enter = int(
            payload['enter']
        )  # add int due to joson only transmit string,can not do +- calculation
        leaving = int(payload['leaving'])

        if laserID == "laser0":
            self.zone['zone1'] += enter
            self.zone['zone1'] -= leaving
        elif laserID == "laser1":
            self.zone['zone2'] += enter
            self.zone['zone2'] -= leaving
            self.zone['zone1'] -= enter
            self.zone['zone1'] += leaving
        elif laserID == "laser2":
            self.zone['zone3'] += enter
            self.zone['zone3'] -= leaving
            self.zone['zone2'] -= enter
            self.zone['zone2'] += leaving
        elif laserID == "laser3":
            self.zone['zone4'] += enter
            self.zone['zone4'] -= leaving
            self.zone['zone3'] -= enter
            self.zone['zone3'] += leaving
        else:
            pass

        print("Received: " + json.dumps(payload, indent=4))
        print("Processed: " + json.dumps(self.zone, indent=4))

        self.client.myPublish("yourtopic",
                              json.dumps(self.zone))  #传输topic需要跟thinkspeak
Пример #23
0
 def __init__(self, serviceID, topic, broker, port, publicURL):
     threading.Thread.__init__(self)
     self.serviceID = serviceID
     self.topic = topic
     self.broker = broker
     self.port = port
     self.payload = {
         "serviceID": self.serviceID,
         "Topic": f"{self.topic}/{self.serviceID}/weightControl",
         "Resource": "WeightControl",
         "Timestamp": None
     }
     self.client = MyMQTT(self.serviceID, self.broker, self.port, self)
     self.client.start()
     conf2 = json.load(open("settingsboxcatalog.json"))
     self.timerequestTopic = conf2["timerequestTopic"]
     self.timerequest = conf2["timerequest"]
     self.count = 6
     self.url = publicURL
Пример #24
0
 def __init__(self, speakerID, boxID, broker, port, publicURL):
     threading.Thread.__init__(self)
     self.speakerID = f"{boxID}{speakerID}"
     self.boxID = boxID
     self.broker = broker
     self.port = port
     self.payload = {
         "deviceID": self.speakerID,
         "Resource": "Speaker",
         "Timestamp": None
     }
     self.client = MyMQTT(self.speakerID, self.broker, self.port, self)
     self.client.start()
     self.d = {'Temperature': [0,"ON"], 'Acceleration': [0,"ON"], 'Oxygen': [0,"ON"], 'Mass': 1}
     # Dati utili per timing
     conf2 = json.load(open("settingsboxcatalog.json"))
     self.timerequestTopic = conf2["timerequestTopic"]
     self.timerequest = conf2["timerequest"]
     self.count = 6
     self.url = publicURL
Пример #25
0
    def __init__(self, token, broker, port):
        threading.Thread.__init__(self)
        # Local token
        self.tokenBot = token

        # Catalog token
        self.bot = telepot.Bot(self.tokenBot)
        self.chatIDs = []
        self.client = MyMQTT("telegramBotIoT", broker, port, self)
        self.client.start()
        MessageLoop(self.bot, {
            'chat': self.on_chat_message,
            'callback_query': self.on_callback_query
        }).run_as_thread()

        # Data for the timing
        conf2 = json.load(open("settingsboxcatalog.json"))
        self.timerequestTopic = conf2["timerequestTopic"]
        self.timerequest = conf2["timerequest"]

        # Catalog public url request
        conf = json.load(open("settings.json"))
        apikey = conf["publicURL"]["publicURL_read"]
        cid = conf["publicURL"]["publicURL_channelID"]
        r = requests.get(
            f"https://api.thingspeak.com/channels/{cid}/fields/1.json?api_key={apikey}&results=1"
        )
        jsonBody = json.loads(r.text)
        self.url_catalog = jsonBody['feeds'][0]['field1']

        # Message sent to the actuator
        self.topic = conf["baseTopic"]
        self.payload = {
            "serviceID": "06_TelegramBot",
            "Topic": f"{self.topic}/06_TelegramBot/telegramBot",
            "Resource": "TelegramBot",
            "Timestamp": None
        }
        r = requests.get(self.url_catalog +
                         "/GetUserData")  # Richiesta elenco utenti WebApp
        self.usersData = json.loads(r.content)
Пример #26
0
 def __init__(self, token, broker, port, topic):
     # Local token
     self.tokenBot = token
     # Catalog token
     # self.tokenBot=requests.get("http://catalogIP/telegram_token").json()["telegramToken"]
     self.bot = telepot.Bot(self.tokenBot)
     self.client = MyMQTT("telegramBot", broker, port, None)
     self.client.start()
     self.topic = topic
     self.__message = {
         'bn': "telegramBot",
         'e': [
             {
                 'n': 'switch',
                 'v': '',
                 't': '',
                 'u': 'bool'
             },
         ]
     }
     MessageLoop(self.bot, {'chat': self.on_chat_message}).run_as_thread()
Пример #27
0
class Client():
	def __init__(self, client, broker, port, endpoints):
		self.client = client
		self.ep = endpoints
		self.broker = broker
		self.port = port
		self.myMqttClient = MyMQTT(self.client, self.broker, self.port, self)
		self.lastTimeSensor = 0

	def start(self):
		self.myMqttClient.start()
		self.myMqttClient.mySubscribe(self.ep["tmp"])

	def stop(self):
		self.myMqttClient.stop()

	def notify(self, topic, payload):
		p={}
		p = json.loads(payload)
		#Ottiene ogni 30 secondi un nuovo valore di temperatura
		if(time.time()-self.lastTimeSensor > 30):
			if topic == self.ep['tmp']:
				self.temp = actualTemp(p['e'][0]['v'])
				self.lastTimeSensor=time.time()
				Y.append(self.temp)
Пример #28
0
class myPublisher():
    def __init__(self, clientID, topic, broker, port):
        self.client = MyMQTT(clientID, broker, port, self)
        self.topic = topic
        self.status = None
        self.__message = {
            "bn": "sensor1",
            "e": [{
                "n": "heartrate",
                "u": "bpm",
                "t": "",
                "v": 0
            }]
        }

    def start(self):
        self.client.start()

    def stop(self):
        self.client.stop()

    def publish(self, value):
        message = self.__message
        message["e"][0]["v"] = value
        message["e"][0]["t"] = str(time.time())
        self.client.myPublish(self.topic, message)
Пример #29
0
class Sensor(MyPublisher):
	"""docstring for Sensor"""
	def __init__(self,buildingID,floorID,roomID,sensorID,broker,port):
		self.buildingID=buildingID
		self.floorID=floorID
		self.roomID=roomID
		self.sensorID=str(sensorID)
		self.topic='/'.join([self.buildingID,self.floorID,self.roomID,self.sensorID])
		self.client=MyMQTT(self.sensorID,broker,port,None)
		self.__message={
			'buildingID':self.buildingID,
			'floorID':self.floorID,
			'roomID':self.roomID,
			'bn':self.sensorID,
			'e':
				[
					{'n':'temperature','value':'', 'timestamp':'','unit':'C'},
					{'n':'humidity','value':'', 'timestamp':'','unit':'%'}
					]
			}


	def sendData(self):
		message=self.__message
		message['e'][0]['value']=random.randint(10,30)
		message['e'][1]['value']=random.randint(50,90)
		message['e'][0]['timestamp']=str(time.time())
		message['e'][1]['timestamp']=str(time.time())
		self.client.myPublish(self.topic,message)

	def start (self):
		self.client.start()

	def stop (self):
		self.client.stop()
Пример #30
0
class mySubscriber():
    def __init__(self, clientID, topic, broker, port):
        self.client = MyMQTT(clientID, broker, port, self)
        self.topic = topic
        self.status = None

    def start(self):
        self.client.start()
        self.client.mySubscribe(self.topic)

    def stop(self):
        self.client.stop()

    def notify(self, topic, payload):
        payload = json.loads(payload)
        new_status = payload["e"][0]["v"]
        self.status = new_status
        pubID = payload["bn"]
        timestamp = payload["e"][0]["t"]
        print(
            f"The led has been set to {new_status} at {timestamp} by {pubID}")

        if (os.path.isfile("hr_log.json")):
            json_log = json.load(open("hr_log.json", "r"))
        else:
            json_log = {"bn": payload["bn"], "e": []}

        json_log["e"].append(payload["e"][0])
        #json_log[payload["bn"]].append(payload["e"])
        json.dump(json_log, open("hr_log.json", "w"))