Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Week8_Control_devices/device1.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
193 lines (164 sloc)
5.76 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! python3.4 | |
###demo code provided by Steve Cope at www.steves-internet-guide.com | |
##sensor uses loop and standard reconnect | |
##email steve@steves-internet-guide.com | |
###Free to use for any purpose | |
import paho.mqtt.client as mqtt | |
import json | |
import os | |
import time | |
import random,os | |
import sys | |
options=dict() | |
broker="192.168.1.33" | |
port=1883 | |
username="" | |
password="" | |
cname="" | |
##May want to change topics | |
cmnd_topic="house/cmnd/#" | |
response_topic="house/response/" | |
connected_topic="house/connected/" | |
status_topic="house/status/" | |
keepalive=120 | |
## Sensor names | |
states=["ON","OFF"] | |
device_name= "111111" | |
device_friendly_name= "lounge-light" | |
group_names =["lights","main-lights"] | |
QOS0=0 | |
mqttclient_log=False | |
## | |
####### | |
def on_message(client,userdata, msg): | |
topic=msg.topic | |
m_decode=str(msg.payload.decode("utf-8","ignore")) | |
message_handler(client,topic,m_decode) | |
def message_handler(client,topic,msg): | |
topics=topic.split("/") | |
topic_len= len(topics) | |
print("in message handler") | |
if topics[1]=="cmnd": | |
sensor_name=topics[2] | |
print("command for device ",sensor_name) | |
ret=check_name(sensor_name) | |
if not ret: | |
return | |
if topic_len==4: | |
command_value=topics[3].upper() | |
print("command value is ",command_value) | |
do_command("power",sensor_name,command_value) | |
if topic_len==5: | |
command_value=topics[4] | |
print("command value is ",command_value) | |
command=topics[3] | |
print("command is ",command) | |
do_command(command,sensor_name,command_value) | |
#update_status(client,sensor_name,command_value) | |
#send_response(client,sensor_name,command_value) | |
def update_status(client,sensor_name,command_value): | |
client.sensor_status_old=client.sensor_status #save | |
client.sensor_status=command_value | |
topic=status_topic+sensor_name | |
client.publish(topic,command_value) | |
return True | |
def send_response(client,sensor_name,command): | |
topic=response_topic+sensor_name | |
client.publish(topic,command) | |
def check_name(sensor_name): | |
match_flag=False | |
if sensor_name==device_name or sensor_name==device_friendly_name: | |
print("sensor name match") | |
match_flag=True | |
for i in range(len(group_names)): | |
if sensor_name==group_names[i]: | |
print("sensor group name match " +sensor_name) | |
match_flag=True | |
break | |
return match_flag | |
def do_command(sensor_cmd,sensor_name,command_value): | |
print("check command "+sensor_cmd) | |
if sensor_cmd in commands: | |
commands[sensor_cmd](sensor_name,command_value) | |
return | |
def power(sensor_name,command_value): | |
print("setting Power") | |
if command_value.upper()==client.states[0] or command_value.upper()==client.states[1]: | |
update_status(client,sensor_name,command_value) | |
send_response(client,sensor_name,command_value) | |
return | |
def status(sensor_name,command_value):#dummy function not yet implemented | |
print("getting Status") | |
return | |
def change_name(sensor_name,command_value): | |
global device_friendly_name | |
#this shouldn't work if using group names as it doesn't make sense | |
if sensor_name==device_name or sensor_name==device_friendly_name: | |
device_friendly_name=command_value | |
print("changing name to " +device_friendly_name) | |
send_response(client,sensor_name,command_value) | |
def on_connect(client, userdata, flags, rc): | |
if rc==0: | |
client.connected_flag=True | |
client.publish(connected_topic,1,retain=True) | |
client.subscribe(cmnd_topic) | |
else: | |
client.bad_connection_flag=True | |
def on_disconnect(client, userdata, rc): | |
client.connected_flag=False | |
client.disconnect_flag=True | |
####### | |
def Initialise_client_object(): | |
mqtt.Client.last_pub_time=time.time() | |
mqtt.Client.running_loop=False | |
mqtt.Client.states=states | |
mqtt.Client.subscribe_flag=False | |
mqtt.Client.sensor_status=states[1] | |
mqtt.Client.sensor_status_old=None | |
mqtt.Client.bad_connection_flag=False | |
mqtt.Client.connected_flag=False | |
mqtt.Client.disconnect_flag=False | |
def Initialise_clients(cname): | |
#flags set | |
client= mqtt.Client(cname) | |
if mqttclient_log: #enable mqqt client logging | |
client.on_log=on_log | |
client.on_connect= on_connect #attach function to callback | |
client.on_message=on_message #attach function to callback | |
client.on_disconnect=on_disconnect | |
#client.on_subscribe=on_subscribe | |
#client.on_publish=on_publish | |
return client | |
############### | |
##### | |
commands={"power":power,"change_name":change_name,"status":status} | |
if __name__ == "__main__" : | |
r=random.randrange(1,10000) | |
cname="sensor-"+str(r) | |
connected_topic=connected_topic+cname | |
Initialise_client_object() # add extra flags | |
client=Initialise_clients(cname)#create and initialise client object | |
if username!="": | |
client.username_pw_set(username,password) | |
client.will_set(connected_topic,0, qos=0, retain=True) #set will | |
print("Connecting to broker") | |
run_flag=True | |
try: | |
client.connect(broker,port,keepalive) | |
except: | |
print("connection failed so Quitting") | |
run_flag=False | |
client.loop_start() | |
while not client.connected_flag and run_flag: | |
print("waiting for connect") | |
time.sleep(0.5) | |
try: #start loop to listen for commands | |
print("starting main loop") | |
while run_flag: | |
time.sleep(1) | |
except KeyboardInterrupt: | |
print("interrrupted by keyboard") | |
client.disconnect() | |
time.sleep(2) | |
client.loop_stop() | |
time.sleep(1) | |