Fixes on the RPi API and modifications for MQTT Communication for RPi

revert-dabc3590
Shabirmean 9 years ago
parent 84daf6216b
commit 39a1020ef4

@ -157,7 +157,7 @@ public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService
@Path("devices/download")
@GET
@Produces("application/zip")
public Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketch_type") String sketchType) {
public Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));

@ -65,7 +65,7 @@
<div class="controls">
<input class="new-device-name" style="color:#3f3f3f;padding:5px"
type="text"
placeholder="Ex. Lobby_DigitalDisplay"
placeholder="Ex. Lobby_RaspberryPi"
name="deviceName" size="60" required>
<br/>
<input type="hidden" class="deviceType" name="deviceType"

@ -20,6 +20,8 @@ owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
controller-context=/raspberrypi/controller
mqtt-sub-topic=wso2/{owner}/raspberrypi/{deviceId}
mqtt-pub-topic=wso2/{owner}/raspberrypi/{deviceId}/publisher
https-ep=${HTTPS_EP}
http-ep=${HTTP_EP}
apim-ep=${APIM_EP}

@ -81,7 +81,8 @@ if args.interval:
if args.mode:
running_mode.RUNNING_MODE = args.mode
iotUtils = __import__('iotUtils')
httpServer = __import__('httpServer') # python script used to start a http-server to listen for operations
mqttSubscriber = __import__('mqttConnector')
# httpServer = __import__('httpServer') # python script used to start a http-server to listen for operations
# (includes the TEMPERATURE global variable)
if running_mode.RUNNING_MODE == 'N':
@ -92,16 +93,16 @@ if args.mode:
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Endpoint specific settings to which the data is pushed
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DC_ENDPOINT = iotUtils.HTTPS_EP.split(":")
DC_IP = DC_ENDPOINT[1].replace('//', '')
DC_PORT = int(DC_ENDPOINT[2])
DC_ENDPOINT_CONTEXT = iotUtils.CONTROLLER_CONTEXT
PUSH_ENDPOINT = str(DC_ENDPOINT_CONTEXT) + '/push_temperature/'
REGISTER_ENDPOINT = str(DC_ENDPOINT_CONTEXT) + '/register'
HOST = iotUtils.getDeviceIP()
HOST_HTTP_SERVER_PORT = iotUtils.getHTTPServerPort()
HOST_AND_PORT = str(HOST)+ ":" + str(HOST_HTTP_SERVER_PORT)
# DC_ENDPOINT = iotUtils.HTTPS_EP.split(":")
# DC_IP = DC_ENDPOINT[1].replace('//', '')
# DC_PORT = int(DC_ENDPOINT[2])
# DC_ENDPOINT_CONTEXT = iotUtils.CONTROLLER_CONTEXT
# PUSH_ENDPOINT = str(DC_ENDPOINT_CONTEXT) + '/push_temperature/'
# REGISTER_ENDPOINT = str(DC_ENDPOINT_CONTEXT) + '/register'
# HOST = iotUtils.getDeviceIP()
# HOST_HTTP_SERVER_PORT = iotUtils.getHTTPServerPort()
# HOST_AND_PORT = str(HOST)+ ":" + str(HOST_HTTP_SERVER_PORT)
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -142,32 +143,32 @@ def configureLogger(loggerName):
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This method registers the DevieIP in the Device-Cloud
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def registerDeviceIP():
ssl.wrap_socket = sslwrap(ssl.wrap_socket) # using the overridden sslwrap that uses TLSv1
if sys.version_info<(2,7,9):
dcConncection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT)
else:
dcConncection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT, context=ssl._create_unverified_context())
#TODO need to get server certificate when initializing https connection
dcConncection.set_debuglevel(1)
dcConncection.connect()
registerURL = str(REGISTER_ENDPOINT) + '/' + str(iotUtils.DEVICE_OWNER) + '/' + str(iotUtils.DEVICE_ID) + '/' + \
str(HOST) + '/' + str(HOST_HTTP_SERVER_PORT) + '/'
dcConncection.putrequest('POST', registerURL)
dcConncection.putheader('Authorization', 'Bearer ' + iotUtils.AUTH_TOKEN)
dcConncection.endheaders()
dcResponse = dcConncection.getresponse()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print ('RASPBERRY_STATS: ' + str(registerURL))
print ('RASPBERRY_STATS: ' + str(dcResponse.status))
print ('RASPBERRY_STATS: ' + str(dcResponse.reason))
print ('RASPBERRY_STATS: Response Message')
print str(dcResponse.msg)
dcConncection.close()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
# def registerDeviceIP():
# ssl.wrap_socket = sslwrap(ssl.wrap_socket) # using the overridden sslwrap that uses TLSv1
# if sys.version_info<(2,7,9):
# dcConncection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT)
# else:
# dcConncection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT, context=ssl._create_unverified_context())
# #TODO need to get server certificate when initializing https connection
# dcConncection.set_debuglevel(1)
# dcConncection.connect()
#
# registerURL = str(REGISTER_ENDPOINT) + '/' + str(iotUtils.DEVICE_OWNER) + '/' + str(iotUtils.DEVICE_ID) + '/' + \
# str(HOST) + '/' + str(HOST_HTTP_SERVER_PORT) + '/'
# dcConncection.putrequest('POST', registerURL)
# dcConncection.putheader('Authorization', 'Bearer ' + iotUtils.AUTH_TOKEN)
# dcConncection.endheaders()
# dcResponse = dcConncection.getresponse()
#
# print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
# print ('RASPBERRY_STATS: ' + str(registerURL))
# print ('RASPBERRY_STATS: ' + str(dcResponse.status))
# print ('RASPBERRY_STATS: ' + str(dcResponse.reason))
# print ('RASPBERRY_STATS: Response Message')
# print str(dcResponse.msg)
#
# dcConncection.close()
# print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -175,6 +176,11 @@ def registerDeviceIP():
# This method connects to the Device-Cloud and pushes data
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def connectAndPushData():
if sys.version_info<(2,7,9):
dcConnection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT)
else:
@ -282,6 +288,19 @@ class ListenHTTPServerThread(object):
httpServer.main()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This is a Thread object for connecting and subscribing to an MQTT Queue
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class SubscribeToMQTTQueue(object):
def __init__(self):
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
mqttSubscriber.main()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# When sysvinit sends the TERM signal, cleanup before exiting
@ -303,9 +322,10 @@ def main():
if running_mode.RUNNING_MODE == 'N':
iotUtils.setUpGPIOPins()
UtilsThread()
registerDeviceIP() # Call the register endpoint and register Device IP
# registerDeviceIP() # Call the register endpoint and register Device IP
TemperatureReaderThread() # initiates and runs the thread to continuously read temperature from DHT Sensor
ListenHTTPServerThread() # starts an HTTP Server that listens for operational commands to switch ON/OFF Led
# ListenHTTPServerThread() # starts an HTTP Server that listens for operational commands to switch ON/OFF Led
SubscribeToMQTTQueue() # connects and subscribes to an MQTT Queue that receives MQTT commands from the server
while True:
try:
if iotUtils.LAST_TEMP > 0: # Push data only if there had been a successful temperature read

@ -1,33 +0,0 @@
#
# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
[Device-Configurations]
server-name=${SERVER_NAME}
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
controller-context=/raspberrypi/controller
https-ep=${HTTPS_EP}
http-ep=${HTTP_EP}
apim-ep=${APIM_EP}
mqtt-ep=${MQTT_EP}
xmpp-ep=${XMPP_EP}
auth-method=token
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15

@ -58,6 +58,8 @@ MQTT_EP = configParser.get('Device-Configurations', 'mqtt-ep')
XMPP_EP = configParser.get('Device-Configurations', 'xmpp-ep')
AUTH_TOKEN = configParser.get('Device-Configurations', 'auth-token')
CONTROLLER_CONTEXT = configParser.get('Device-Configurations', 'controller-context')
MQTT_SUB_TOPIC = configParser.get('Device-Configurations', 'mqtt-sub-topic').format(owner = DEVICE_OWNER, deviceId = DEVICE_ID)
MQTT_PUB_TOPIC = configParser.get('Device-Configurations', 'mqtt-pub-topic').format(owner = DEVICE_OWNER, deviceId = DEVICE_ID)
DEVICE_INFO = '{"owner":"' + DEVICE_OWNER + '","deviceId":"' + DEVICE_ID + '","reply":'
HTTPS_EP = configParser.get('Device-Configurations', 'https-ep')
HTTP_EP = configParser.get('Device-Configurations', 'http-ep')

@ -0,0 +1,118 @@
#!/usr/bin/env python
"""
/**
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
"""
import time
import iotUtils
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("MQTT_LISTENER: Connected with result code " + str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
print ("MQTT_LISTENER: Subscribing with topic " + TOPIC)
client.subscribe(TOPIC)
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print( "MQTT_LISTENER: " + msg.topic + " " + str(msg.payload) )
request = str(msg.payload)
resource = request.split(":")[0].upper()
state = request.split(":")[1].upper()
print "MQTT_LISTENER: Resource- " + resource
if resource == "TEMP":
pass
#request.send_response(200)
#request.send_header("Content-type", "text/plain")
#request.end_headers()
#request.wfile.write(LAST_TEMP)
# return
elif resource == "BULB":
iotUtils.switchBulb(state)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# The Main method of the server script
# This method is invoked from RaspberryStats.py on a new thread
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def main():
MQTT_ENDPOINT = iotUtils.MQTT_EP.split(":")
MQTT_IP = MQTT_ENDPOINT[1].replace('//','')
MQTT_PORT = int(MQTT_ENDPOINT[2])
DEV_OWNER = iotUtils.DEVICE_OWNER
DEV_ID = iotUtils.DEVICE_ID
global TOPIC
TOPIC = "wso2/" + DEV_OWNER + "/raspberrypi/" + DEV_ID
print ("MQTT_LISTENER: MQTT_ENDPOINT is " + str(MQTT_ENDPOINT))
print ("MQTT_LISTENER: MQTT_TOPIC is " + TOPIC)
mqttClient = mqtt.Client()
mqttClient.on_connect = on_connect
mqttClient.on_message = on_message
mqttClient.username_pw_set(iotUtils.AUTH_TOKEN, password = "")
mqttClient.connect(MQTT_IP, MQTT_PORT, 60)
print "MQTT_LISTENER: " + time.asctime(), "Connected to MQTT Broker - %s:%s" % (MQTT_IP, MQTT_PORT)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
mqttClient.loop_forever()
# while True:
# try:
# mqttClient.connect(MQTT_IP, MQTT_PORT, 60)
# print "MQTT_LISTENER: " + time.asctime(), "Connected to MQTT Broker - %s:%s" % (MQTT_IP, MQTT_PORT)
#
# # Blocking call that processes network traffic, dispatches callbacks and
# # handles reconnecting.
# # Other loop*() functions are available that give a threaded interface and a
# # manual interface.
# mqttClient.loop_forever()
#
# except (KeyboardInterrupt, Exception) as e:
# print "MQTT_LISTENER: Exception in MQTTServerThread (either KeyboardInterrupt or Other)"
# print ("MQTT_LISTENER: " + str(e))
#
# mqttClient.disconnect()
# print "MQTT_LISTENER: " + time.asctime(), "Connection to Broker closed - %s:%s" % (MQTT_IP, MQTT_PORT)
# print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
# pass
if __name__ == '__main__':
iotUtils.setUpGPIOPins()
main()
Loading…
Cancel
Save