Mqtt_To_Action : Meross Plug, 2e version. Working.

This commit is contained in:
ThomasFransolet 2019-06-20 21:44:36 +02:00
parent 1dca5ab112
commit 95c4cb69e9
6 changed files with 729 additions and 2 deletions

View File

@ -0,0 +1,153 @@
#!/usr/bin/env python
import requests
import signal
import time
import json
import paho.mqtt.client as mqtt
import datetime
import sys
#from meross_iot.api import MerossHttpClient
#from meross_iot.supported_devices.power_plugs import Mss310
from MerossIot.meross_iot.manager import MerossManager
from MerossIot.meross_iot.meross_event import MerossEventType
from MerossIot.meross_iot.cloud.devices.power_plugs import GenericPlug
# Init variables
broker="localhost"
#username="oilkfgjy"
#password="lEyZb90q49Rf"
EMAIL = "thomas.fransolet@hotmail.be"
PASSWORD = "Coconuts07"
manager = MerossManager(meross_email=EMAIL, meross_password=PASSWORD)
gardenPlugStatus = False
#def event_handler(eventobj):
# if eventobj.event_type == MerossEventType.DEVICE_ONLINE_STATUS:
# print("Device online status changed: %s went %s" % (eventobj.device.name, eventobj.status))
# pass
# elif eventobj.event_type == MerossEventType.DEVICE_SWITCH_STATUS:
# print("Switch state changed: Device %s (channel %d) went %s" % (eventobj.device.name, eventobj.channel_id,
# eventobj.switch_state))
# else:
# print("Unknown event!")
def actOnSmartPlug(namePlug, toggle):
global manager
global smart3DPrinterPlug
#global smartGardenPlug
#global gardenPlugStatus
# Register event handlers for the manager...
#manager.register_event_handler(event_handler)
# Starts the manager
manager.start()
plugs = manager.get_devices_by_kind(GenericPlug)
# ---------------------------
# Let's play with smart plugs
# ---------------------------
for p in plugs: # type: GenericPlug
if not p.online or p.name != namePlug:
print("The plug %s seems to be offline. Or it's not the one I try to find. " % p.name)
continue
print("Just found the right one ! Trying to toggle it")
#print(p.get_status())
#if (p.get_status() != toggle):
if toggle :
p.turn_on_channel(0)
else :
p.turn_off_channel(0)
if p.supports_electricity_reading():
print("Current consumption is: %s" % str(p.get_electricity()))
#else :
#print("The smart plug %s is already at the state I want !" % p.name)
#continue
manager.stop()
def on_message(mosq, obj, msg):
print("Topic = " + msg.topic)
date_time = datetime.datetime.now()
timeCheck = date_time.time()
print(timeCheck.hour)
# Extracting data in json format
#data = r.json()
if msg.topic == 'SmartGarden' :
msgPayload = str(msg.payload, "utf-8")
print("SmartGardenMessage = PayLoad : " + msgPayload)
data = json.loads(msgPayload)
try :
print(data['Light'])
except Exception as e:
print(e)
print("SmartGardenMessage = Got an error in parsing message")
if (data['Light'] > 8000 and (timeCheck.hour>=19 or timeCheck.hour<6)):
try:
print('Test to turn on the smart garden light plug')
time.sleep(5)
actOnSmartPlug('Potager',True)
except Exception as e:
print(e)
print("SmartGardenMessage = error in action")
elif (data['Light'] <= 8000 and (6<=timeCheck.hour<19)):
try:
print('Test to turn off the smart garden light plug')
time.sleep(2)
actOnSmartPlug('Potager',False)
except Exception as e:
print(e)
print("SmartGardenMessage = error in action")
elif msg.topic == '3DPrinter/event/PrintDone' :
msgPayload = str(msg.payload, "utf-8")
data = json.loads(msgPayload)
try :
print(data['_event'])
except Exception as e:
print(e)
print("3DPrinter = Got an error in parsing message")
if data['_event'] == "PrintDone":
try:
print('Test to turn off the 3D Printer plug')
time.sleep(10)
actOnSmartPlug('Imprimante 3D',False)
except Exception as e:
print(e)
print("3DPrinterMessage = error in action")
else:
print("Unknown topic")
print(msg.topic)
def on_connect(client, userdata, flags, rc):
print("HELLOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO from broker, it's connected !")
client.connected_flag=True
########## MAIN CODE ##########
mqttc = mqtt.Client('Mqtt_To_Action_Interceptor')
#mqttc.username_pw_set(username, password)
print("connecting to broker : ",broker)
mqttc.connect(broker, 1883)
print("Initialize smart plugs info")
mqttc.on_connect= on_connect
mqttc.on_message= on_message
#####
mqttc.loop_start() #start loop to process received messages
print("subscribing ")
mqttc.subscribe("SmartGarden")#subscribe
mqttc.subscribe("3DPrinterSensors")#subscribe
mqttc.subscribe("3DPrinter/#")#subscribe
signal.pause()
mqttc.loop_forever()

View File

@ -0,0 +1,135 @@
from meross_iot.manager import MerossManager
from meross_iot.meross_event import MerossEventType
from meross_iot.cloud.devices.light_bulbs import GenericBulb
from meross_iot.cloud.devices.power_plugs import GenericPlug
from meross_iot.cloud.devices.door_openers import GenericGarageDoorOpener
import time
import os
EMAIL = "thomas.fransolet@hotmail.be"
PASSWORD = "Coconuts07"
def event_handler(eventobj):
if eventobj.event_type == MerossEventType.DEVICE_ONLINE_STATUS:
print("Device online status changed: %s went %s" % (eventobj.device.name, eventobj.status))
pass
elif eventobj.event_type == MerossEventType.DEVICE_SWITCH_STATUS:
print("Switch state changed: Device %s (channel %d) went %s" % (eventobj.device.name, eventobj.channel_id,
eventobj.switch_state))
else:
print("Unknown event!")
if __name__=='__main__':
# Initiates the Meross Cloud Manager. This is in charge of handling the communication with the remote endpoint
manager = MerossManager(meross_email=EMAIL, meross_password=PASSWORD)
# Register event handlers for the manager...
manager.register_event_handler(event_handler)
# Starts the manager
manager.start()
# You can retrieve the device you are looking for in various ways:
# By kind
bulbs = manager.get_devices_by_kind(GenericBulb)
plugs = manager.get_devices_by_kind(GenericPlug)
door_openers = manager.get_devices_by_kind(GenericGarageDoorOpener)
all_devices = manager.get_supported_devices()
# Print some basic specs about the discovered devices
print("All the bulbs I found:")
for b in bulbs:
print(b)
print("All the plugs I found:")
for p in plugs:
print(p)
print("All the garage openers I found:")
for g in door_openers:
print(g)
print("All the supported devices I found:")
for d in all_devices:
print(d)
# You can also retrieve devices by the UUID/name
# a_device = manager.get_device_by_name("My Plug")
# a_device = manager.get_device_by_uuid("My Plug")
# Or you can retrieve all the device by the HW type
# all_mss310 = manager.get_devices_by_type("mss310")
# ------------------------------
# Let's play the garage openers.
# ------------------------------
for g in door_openers:
if not g.online:
print("The garage controller %s seems to be offline. Cannot play with that..." % g.name)
continue
print("Opening door %s..." % g.name)
g.open_door()
print("Closing door %s..." % g.name)
g.close_door()
# ---------------------
# Let's play with bulbs
# ---------------------
for b in bulbs: # type: GenericBulb
if not b.online:
print("The bulb %s seems to be offline. Cannot play with that..." % b.name)
continue
print("Let's play with bulb %s" % b.name)
if not b.supports_light_control():
print("Too bad bulb %s does not support light control %s" % b.name)
else:
# Let's make it red!
b.set_light_color(rgb=(255, 0, 0))
b.turn_on()
time.sleep(1)
b.turn_off()
# ---------------------------
# Let's play with smart plugs
# ---------------------------
for p in plugs: # type: GenericPlug
if not p.online:
print("The plug %s seems to be offline. Cannot play with that..." % p.name)
continue
print("Let's play with smart plug %s" % p.name)
channels = len(p.get_channels())
print("The plug %s supports %d channels." % (p.name, channels))
for i in range(0, channels):
print("Turning on channel %d of %s" % (i, p.name))
p.turn_on_channel(i)
time.sleep(1)
print("Turning off channel %d of %s" % (i, p.name))
p.turn_off_channel(i)
usb_channel = p.get_usb_channel_index()
if usb_channel is not None:
print("Awesome! This device also supports USB power.")
p.enable_usb()
time.sleep(1)
p.disable_usb()
if p.supports_electricity_reading():
print("Awesome! This device also supports power consumption reading.")
print("Current consumption is: %s" % str(p.get_electricity()))
# At this point, we are all done playing with the library, so we gracefully disconnect and clean resources.
print("We are done playing. Cleaning resources...")
manager.stop()
print("Bye bye!")

View File

@ -62,6 +62,7 @@ def on_message(mosq, obj, msg):
global smartGardenPlug
date_time = datetime.datetime.now()
timeCheck = date_time.time()
print(timeCheck.hour)
# Extracting data in json format
#data = r.json()
if msg.topic == 'SmartGarden' :
@ -74,7 +75,7 @@ def on_message(mosq, obj, msg):
print(e)
print("SmartGardenMessage = Got an error in parsing message")
if (data['Light'] > 8000 and 19<=timeCheck.hour<6):
if true :#(data['Light'] > 8000 and (timeCheck.hour>=19 or timeCheck.hour<6)):
try:
print('Test to turn on the smart garden light plug')
time.sleep(5)
@ -82,7 +83,7 @@ def on_message(mosq, obj, msg):
except Exception as e:
print(e)
print("SmartGardenMessage = error in action")
elif (data['Light'] <= 8000 and 6<=timeCheck.hour<19):
elif (data['Light'] <= 8000 and (6<=timeCheck.hour<19)):
try:
print('Test to turn off the smart garden light plug')
time.sleep(5)

View File

@ -0,0 +1,150 @@
#!/usr/bin/env python
import requests
import signal
import time
import datetime
import json
import paho.mqtt.client as mqtt
import datetime
import sys
from meross_iot.api import MerossHttpClient
from meross_iot.supported_devices.power_plugs import Mss310
# Init variables
broker="localhost"
#username="oilkfgjy"
#password="lEyZb90q49Rf"
httpHandler = MerossHttpClient(email="thomas.fransolet@hotmail.be", password="Coconuts07")
devices = httpHandler.list_supported_devices()
smartGardenPlugUUID = "1809010176291225180434298f165e27"
smart3DPrinterUUID = "1809016169329025180434298f16641d"
delay = 5000
smart3DPrinterPlug = Mss310
smartGardenPlug = Mss310
def init_SmartPlug():
global smart3DPrinterPlug
global smartGardenPlug
for counter, device in enumerate(devices):
if isinstance(device, Mss310):
#self.device = device
#print(device.get_power_consumptionX())
print("SYSTEM DATA = "+str(device.get_sys_data()))
#print(device.get_electricity())
print("DEVICE ID = "+str(device.device_id()))
if (str(device.device_id()) == smartGardenPlugUUID):
print("HOURRA It's smartGarden !")
smartGardenPlug = device
smartGardenPlugStatus = device.get_sys_data()['all']['digest']['togglex'][0]['onoff']
print("DEVICE STATUS = "+str(smartGardenPlugStatus))
smartGardenPlugElecticity = device.get_electricity()
print(smartGardenPlugElecticity)
if (str(device.device_id()) == smart3DPrinterUUID) :
print("HOURRA It's smart3DPrinter !")
smart3DPrinterPlug = device
def on_message(mosq, obj, msg):
print("Topic = " + msg.topic)
global smart3DPrinterPlug
global smartGardenPlug
# Extracting data in json format
#data = r.json()
if msg.topic == 'SmartGarden' :
msgPayload = str(msg.payload, "utf-8")
print("SmartGardenMessage = PayLoad : " + msgPayload)
data = json.loads(msgPayload)
try :
print(data['Light'])
except Exception as e:
print(e)
print("SmartGardenMessage = Got an error in parsing message")
if data['Light'] > 7000:
try:
print('Test to turn on the smart garden light plug')
time.sleep(5)
smartGardenPlug.turn_on();
except Exception as e:
print(e)
print("SmartGardenMessage = error in action")
elif data['Light'] <= 7000:
try:
print('Test to turn off the smart garden light plug')
time.sleep(5)
smartGardenPlug.turn_off();
except Exception as e:
print(e)
print("SmartGardenMessage = error in action")
elif msg.topic == '3DPrinter/event/PrintDone' :
msgPayload = str(msg.payload, "utf-8")
data = json.loads(msgPayload)
try :
print(data['_event'])
except Exception as e:
print(e)
print("3DPrinter = Got an error in parsing message")
if data['_event'] == "PrintDone":
try:
print('Test to turn off the 3D Printer plug')
time.sleep(10)
smart3DPrinterPlug.turn_off();
except Exception as e:
print(e)
print("3DPrinterMessage = error in action")
else:
print("Unknown topic")
print(msg.topic)
def on_connect(client, userdata, flags, rc):
print("HELLOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO from broker, it's connected !")
client.connected_flag=True
init_SmartPlug()
########## MAIN CODE ##########
mqttc = mqtt.Client('Mqtt_To_Action_Interceptor')
#mqttc.username_pw_set(username, password)
print("connecting to broker : ",broker)
mqttc.connect(broker, 1883)
print("Initialize smart plugs info")
#init_SmartPlug()
mqttc.on_connect= on_connect
mqttc.on_message= on_message
#####
mqttc.loop_start() #start loop to process received messages
print("subscribing ")
mqttc.subscribe("SmartGarden")#subscribe
mqttc.subscribe("3DPrinterSensors")#subscribe
mqttc.subscribe("3DPrinter/#")#subscribe
date_time = datetime.datetime.now()
date = date_time.date() # Gives the date
time = date_time.time() # Gives the time
print date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond
signal.pause()
mqttc.loop_forever()

View File

@ -0,0 +1,153 @@
#!/usr/bin/env python
import requests
import signal
import time
import json
import paho.mqtt.client as mqtt
import datetime
import sys
#from meross_iot.api import MerossHttpClient
#from meross_iot.supported_devices.power_plugs import Mss310
from MerossIot.meross_iot.manager import MerossManager
from MerossIot.meross_iot.meross_event import MerossEventType
from MerossIot.meross_iot.cloud.devices.power_plugs import GenericPlug
# Init variables
broker="localhost"
#username="oilkfgjy"
#password="lEyZb90q49Rf"
EMAIL = "thomas.fransolet@hotmail.be"
PASSWORD = "Coconuts07"
manager = MerossManager(meross_email=EMAIL, meross_password=PASSWORD)
gardenPlugStatus = False
#def event_handler(eventobj):
# if eventobj.event_type == MerossEventType.DEVICE_ONLINE_STATUS:
# print("Device online status changed: %s went %s" % (eventobj.device.name, eventobj.status))
# pass
# elif eventobj.event_type == MerossEventType.DEVICE_SWITCH_STATUS:
# print("Switch state changed: Device %s (channel %d) went %s" % (eventobj.device.name, eventobj.channel_id,
# eventobj.switch_state))
# else:
# print("Unknown event!")
def actOnSmartPlug(namePlug, toggle):
global manager
global smart3DPrinterPlug
#global smartGardenPlug
#global gardenPlugStatus
# Register event handlers for the manager...
#manager.register_event_handler(event_handler)
# Starts the manager
manager.start()
plugs = manager.get_devices_by_kind(GenericPlug)
# ---------------------------
# Let's play with smart plugs
# ---------------------------
for p in plugs: # type: GenericPlug
if not p.online or p.name != namePlug:
print("The plug %s seems to be offline. Or it's not the one I try to find. " % p.name)
continue
print("Just found the right one ! Trying to toggle it")
#print(p.get_status())
#if (p.get_status() != toggle):
if toggle :
p.turn_on_channel(0)
else :
p.turn_off_channel(0)
if p.supports_electricity_reading():
print("Current consumption is: %s" % str(p.get_electricity()))
#else :
#print("The smart plug %s is already at the state I want !" % p.name)
#continue
manager.stop()
def on_message(mosq, obj, msg):
print("Topic = " + msg.topic)
date_time = datetime.datetime.now()
timeCheck = date_time.time()
print(timeCheck.hour)
# Extracting data in json format
#data = r.json()
if msg.topic == 'SmartGarden' :
msgPayload = str(msg.payload, "utf-8")
print("SmartGardenMessage = PayLoad : " + msgPayload)
data = json.loads(msgPayload)
try :
print(data['Light'])
except Exception as e:
print(e)
print("SmartGardenMessage = Got an error in parsing message")
if (data['Light'] > 8000 and (timeCheck.hour>=19 or timeCheck.hour<6)):
try:
print('Test to turn on the smart garden light plug')
time.sleep(5)
actOnSmartPlug('Potager',True)
except Exception as e:
print(e)
print("SmartGardenMessage = error in action")
elif (data['Light'] <= 8000 and (6<=timeCheck.hour<19)):
try:
print('Test to turn off the smart garden light plug')
time.sleep(2)
actOnSmartPlug('Potager',False)
except Exception as e:
print(e)
print("SmartGardenMessage = error in action")
elif msg.topic == '3DPrinter/event/PrintDone' :
msgPayload = str(msg.payload, "utf-8")
data = json.loads(msgPayload)
try :
print(data['_event'])
except Exception as e:
print(e)
print("3DPrinter = Got an error in parsing message")
if data['_event'] == "PrintDone":
try:
print('Test to turn off the 3D Printer plug')
time.sleep(10)
actOnSmartPlug('Imprimante 3D',False)
except Exception as e:
print(e)
print("3DPrinterMessage = error in action")
else:
print("Unknown topic")
print(msg.topic)
def on_connect(client, userdata, flags, rc):
print("HELLOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO from broker, it's connected !")
client.connected_flag=True
########## MAIN CODE ##########
mqttc = mqtt.Client('Mqtt_To_Action_Interceptor')
#mqttc.username_pw_set(username, password)
print("connecting to broker : ",broker)
mqttc.connect(broker, 1883)
print("Initialize smart plugs info")
mqttc.on_connect= on_connect
mqttc.on_message= on_message
#####
mqttc.loop_start() #start loop to process received messages
print("subscribing ")
mqttc.subscribe("SmartGarden")#subscribe
mqttc.subscribe("3DPrinterSensors")#subscribe
mqttc.subscribe("3DPrinter/#")#subscribe
signal.pause()
mqttc.loop_forever()

View File

@ -0,0 +1,135 @@
from meross_iot.manager import MerossManager
from meross_iot.meross_event import MerossEventType
from meross_iot.cloud.devices.light_bulbs import GenericBulb
from meross_iot.cloud.devices.power_plugs import GenericPlug
from meross_iot.cloud.devices.door_openers import GenericGarageDoorOpener
import time
import os
EMAIL = "thomas.fransolet@hotmail.be"
PASSWORD = "Coconuts07"
def event_handler(eventobj):
if eventobj.event_type == MerossEventType.DEVICE_ONLINE_STATUS:
print("Device online status changed: %s went %s" % (eventobj.device.name, eventobj.status))
pass
elif eventobj.event_type == MerossEventType.DEVICE_SWITCH_STATUS:
print("Switch state changed: Device %s (channel %d) went %s" % (eventobj.device.name, eventobj.channel_id,
eventobj.switch_state))
else:
print("Unknown event!")
if __name__=='__main__':
# Initiates the Meross Cloud Manager. This is in charge of handling the communication with the remote endpoint
manager = MerossManager(meross_email=EMAIL, meross_password=PASSWORD)
# Register event handlers for the manager...
manager.register_event_handler(event_handler)
# Starts the manager
manager.start()
# You can retrieve the device you are looking for in various ways:
# By kind
bulbs = manager.get_devices_by_kind(GenericBulb)
plugs = manager.get_devices_by_kind(GenericPlug)
door_openers = manager.get_devices_by_kind(GenericGarageDoorOpener)
all_devices = manager.get_supported_devices()
# Print some basic specs about the discovered devices
print("All the bulbs I found:")
for b in bulbs:
print(b)
print("All the plugs I found:")
for p in plugs:
print(p)
print("All the garage openers I found:")
for g in door_openers:
print(g)
print("All the supported devices I found:")
for d in all_devices:
print(d)
# You can also retrieve devices by the UUID/name
# a_device = manager.get_device_by_name("My Plug")
# a_device = manager.get_device_by_uuid("My Plug")
# Or you can retrieve all the device by the HW type
# all_mss310 = manager.get_devices_by_type("mss310")
# ------------------------------
# Let's play the garage openers.
# ------------------------------
for g in door_openers:
if not g.online:
print("The garage controller %s seems to be offline. Cannot play with that..." % g.name)
continue
print("Opening door %s..." % g.name)
g.open_door()
print("Closing door %s..." % g.name)
g.close_door()
# ---------------------
# Let's play with bulbs
# ---------------------
for b in bulbs: # type: GenericBulb
if not b.online:
print("The bulb %s seems to be offline. Cannot play with that..." % b.name)
continue
print("Let's play with bulb %s" % b.name)
if not b.supports_light_control():
print("Too bad bulb %s does not support light control %s" % b.name)
else:
# Let's make it red!
b.set_light_color(rgb=(255, 0, 0))
b.turn_on()
time.sleep(1)
b.turn_off()
# ---------------------------
# Let's play with smart plugs
# ---------------------------
for p in plugs: # type: GenericPlug
if not p.online:
print("The plug %s seems to be offline. Cannot play with that..." % p.name)
continue
print("Let's play with smart plug %s" % p.name)
channels = len(p.get_channels())
print("The plug %s supports %d channels." % (p.name, channels))
for i in range(0, channels):
print("Turning on channel %d of %s" % (i, p.name))
p.turn_on_channel(i)
time.sleep(1)
print("Turning off channel %d of %s" % (i, p.name))
p.turn_off_channel(i)
usb_channel = p.get_usb_channel_index()
if usb_channel is not None:
print("Awesome! This device also supports USB power.")
p.enable_usb()
time.sleep(1)
p.disable_usb()
if p.supports_electricity_reading():
print("Awesome! This device also supports power consumption reading.")
print("Current consumption is: %s" % str(p.get_electricity()))
# At this point, we are all done playing with the library, so we gracefully disconnect and clean resources.
print("We are done playing. Cleaning resources...")
manager.stop()
print("Bye bye!")