This repository has been archived by the owner on Jun 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
swapmanager.py
194 lines (161 loc) · 6.27 KB
/
swapmanager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
from swap.SwapInterface import SwapInterface
from MQTT import MQTT
DEBUG = True
import sys
import os
import json
import random
import mosquitto
import time
class SwapManager(SwapInterface):
"""
SWAP Management Class
"""
def getEndPts(self, register):
"""
Returns the list of end points from the register.
Helper function for registerValueChanged
"""
status = []
# For every endpoint contained in this register
for endp in register.parameters:
strval = endp.getValueInAscii()
if endp.valueChanged:
if DEBUG:
if endp.unit is not None:
strval += " " + endp.unit.name
print endp.name + " in address " + str(endp.getRegAddress()) + " changed to " + strval
if endp.display:
endp_data = endp.dumps()
if endp_data is not None:
status.append(endp_data)
return status
def registerValueChanged(self, register):
"""
Register value changed
@param register: register object having changed
"""
# Skip config registers
if register.isConfig():
return
# Check if debugging is on
if DEBUG:
print "Register addr= " + str(register.getAddress()) + " id=" + str(register.id) + " changed to " + register.value.toAsciiHex()
# Get the list of end pts
status = self.getEndPts(register)
if len(status) > 0:
# Publish data onto the server LIB/level4/climate_raw
pub_data = json.dumps(status)[1:-1]
pub_data = pub_data[:-1] + ", 'pi_id' : " + str(MQTT.pi_id) + pub_data[-1]
data = status[0]
try:
if (str(MQTT.config[str(data["id"])]) == str(MQTT.pi_id)):
(result, mid) = self.mqttc.publish(MQTT.topic_temp+"/"+MQTT.pi_id, str(pub_data), retain = True)
# Check if mosquito accepted the publish or not.
if (result == 0):
print "PUBLISH SUCCESS: " + str(pub_data)
else:
print "PUBLISH FAILED: " + str(pub_data)
self.reconnect_loop(MQTT.topic_temp, str(pub_data))
except:
e = sys.exc_info()[0]
print ("<publishData> Error: %s" % e )
self.shell_command("sudo svc -t /etc/service/lib/")
exit(-2)
def reconnect_loop(self, topic, data):
result = -1
while result!=0:
self.shell_command("sudo /home/pi/CEIT_Sensors_PiModem/wifi_persist.sh")
time.sleep(8)
try:
self.mqttc.connect(MQTT.server, 1883)
(result, mid) = self.mqttc.publish(topic, data, retain = True)
except:
e = sys.exc_info()[0]
print("<reconnect_loop> Error: %s" % e)
def shell_command(self, command):
"""
Sends command to bash shell
"""
import subprocess
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
print output
def on_publish(self, mosq, userdata, mid):
"""
Callback when a message was sent to the broker using publish.
"""
print("PUBLISHED: MID: "+str(mid))
def on_message(self, mosq, obj, msg):
"""
Callback when a message has been recieved from the broker on a topic.
"""
print("Message received on topic "+msg.topic+" with QoS "+str(msg.qos)+" and payload "+msg.payload)
if (msg.topic == "github/craigknott/CEIT_Sensors_PiModem"):
cmd = os.path.join(MQTT.directory, "gitpull.sh")
print "On message command fired: " + cmd
self.shell_command(cmd)
self.shell_command("sudo svc -t /etc/service/lib/")
exit(0)
def on_connect(self, mosq, userdata, rc):
"""
Callback when client connects to mqtt server.
"""
self.mqttc.subscribe("github/craigknott/CEIT_Sensors_PiModem")
print("CONNECTED: RC: "+str(rc))
def on_disconnect(self, obj, rc):
"""
Callback when client disconnects from mqtt server successfully.
"""
print "DISCONNECTED: RC: " + str(rc)
def __init__(self, swap_settings=None):
"""
Class constructor
@param swap_settings: path to the main SWAP configuration file
"""
# MAin configuration file
self.swap_settings = swap_settings
# Print SWAP activity
DEBUG = False
#Setup MQTT client
self.mqttc = mosquitto.Mosquitto("LIB-PI_"+str(MQTT.pi_id)+str(random.randrange(10000)))
self.mqttc.on_connect = self.on_connect
self.mqttc.on_publish = self.on_publish
self.mqttc.on_message = self.on_message
flag = 1
while(flag == 1):
try:
self.mqttc.connect(MQTT.server, 1883)
flag = 0
except:
flag = 1
e = sys.exc_info()[0]
print("<__init__><mqtt.connect> Error: %s" % e)
self.shell_command("sudo /home/pi/CEIT_Sensors_PiModem/wifi_persist.sh")
try:
# Superclass call
SwapInterface.__init__(self, swap_settings)
# Start MQTT client loop
self.mqttc.loop_forever()
except:
e = sys.exc_info()[0]
print ("<__init__> Error: %s" % e )
self.shell_command("sudo svc -t /etc/service/lib/")
exit(-3)
if __name__ == '__main__':
"""
Function run if this script is the main script being run.
"""
if (len(sys.argv) < 2):
print "Usage: python pyswapmanager.py PI_ID"
exit(0)
MQTT.pi_id = sys.argv[1]
MQTT.directory = os.path.dirname(os.path.realpath(__file__))
print "INIT DIRECTORY SET : " + MQTT.directory
settings = os.path.join(MQTT.directory, "config", "settings.xml")
try:
sm = SwapManager(settings)
except:
e = sys.exc_info()[0]
print ("<__main__> Error: %s" % e )
exit(-1)