Skip to content

Commit

Permalink
Merge pull request #16 from telefonicaid/task/third
Browse files Browse the repository at this point in the history
Task/third
  • Loading branch information
XavierVal committed Sep 24, 2015
2 parents 3b646a4 + 0dd2b5b commit 3782bde
Showing 1 changed file with 83 additions and 34 deletions.
117 changes: 83 additions & 34 deletions iotqatools/simulators/thirdPartySimulator.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
#!/usr/bin/python


__author__ = 'macs'

from flask import Flask, request, Response
from flask import Flask, request, Response, g
from sys import argv
from time import sleep
import threading
import random
import json
import requests

app = Flask(__name__)

# Default arguments
port = 7010
host = '0.0.0.0'
port = 6500
host = '127.0.0.1'

# Arguments from command line
if len(argv) > 1:
Expand All @@ -20,40 +24,80 @@

@app.route('/sync/request', methods=['POST'])
def treat_sync_request():
global lastRequest, myResponse, cont
global last_request, cont, delay

my_result = {}
app.logger.info("Received sync request")
# Increase the number of requests
cont += 1
lastRequest = request.data
jdata = json.loads(request.data)
my_result["result"] = 'action-' + jdata['action'] + ', extra-' + jdata['extra']
resp = Response()
return Response(response=json.dumps(my_result), status=200, content_type='application/json', headers=resp.headers)

# Store the last request
last_request = request.data
app.logger.info('Request data received: ' + last_request)

# Set delay if needed
if delay is not '':
app.logger.info("Delay stated")
sleep(int(delay))
delay = ''

# Retrieve request information
service = request.headers['fiware-service']
subservice = request.headers['fiware-servicepath']
button_id = json.loads(request.data)['button']
headers = {'Accept': 'application/json', 'content-type': 'application/json', 'fiware-service': service,
'fiware-servicepath': subservice}

# Generate sync response
sync_response = {'externalId': generate_uid(), 'buttonId': button_id, 'details': {}}
sync_response['details']['rgb'] = '66CCDD'
sync_response['details']['t'] = '2'
app.logger.info('Response sent: ' + json.dumps(sync_response))

return Response(response=json.dumps(sync_response), status=200, headers=headers)


@app.route('/async/create', methods=['POST'])
def treat_async_create():
global asyncRequest
global last_request

uid = str(random.randint(1, 999))
asyncRequest[uid] = '{"state": "P"}'
print asyncRequest
myresp = '{"id": ' + uid + ', "details": {"rgb" : "66CCDD", "t": 2}}'
return Response(response=myresp, status=200, content_type='application/json')
app.logger.info("Recived async create")
# Store the last request
last_request = request.data
app.logger.info('Request data received: ' + last_request)

# Retrieve callback url and buttonId from request
service = request.headers['fiware-service']
subservice = request.headers['fiware-servicepath']
url_callback = json.loads(request.data)['callback']
button_id = json.loads(request.data)['button']

@app.route('/async/requests', methods=['POST','GET'])
def treat_async_request_all():
global asyncRequest
# Compose the async response
async_response = {'externalId': str(generate_uid()), 'buttonId': str(button_id), 'details': {}}
async_response['details']['rgb'] = '66CCDD'
async_response['details']['t'] = '2'

return Response(response=str(asyncRequest), status=200)
# Invoke callback response
t = threading.Thread(target=invoke_ca, args=(async_response, url_callback, service, subservice))
t.start()
return Response(response='Create Received OK', status=200)


@app.route('/async/request/<uid>', methods=['POST','GET'])
def treat_async_request(uid):
global asyncRequest
def invoke_ca(async_response, url_callback, service, subservice):
# Wait until request is finished
sleep(3)

return Response(response=asyncRequest[uid], status=200, content_type='application/json')
# Send data to urlCallback
headers = {'Accept': 'application/json', 'content-type': 'application/json', 'fiware-service': service,
'fiware-servicepath': subservice}
app.logger.info('Response sent to ' + url_callback + ' is: ' + json.dumps(async_response))
r = requests.post(url_callback, data=json.dumps(async_response), headers=headers)
return r


def generate_uid():
uid = str(random.randint(1, 9999999))
app.logger.info('Generated uid: ' + uid)
return uid


@app.route('/setResponseToError', methods=['GET'])
Expand All @@ -72,12 +116,19 @@ def treat_set_response_to_ok():
return Response(response='Simulator set to OK', status=200)


@app.route('/setDelayToSync', methods=['GET'])
def treat_set_delay_to_sync():
global delay

delay = request.args.get('delay')
return Response(response='Delay to next sync request set to ' + delay, status=200)


@app.route('/last', methods=['GET'])
def treat_last():
global lastRequest
global last_request

resp_last = Response()
return Response(response=lastRequest, status=200, content_type='application/json', headers=resp_last.headers)
return Response(response=last_request, status=200)


@app.route('/count', methods=['GET'])
Expand All @@ -88,19 +139,17 @@ def count():

@app.route('/reset', methods=['GET'])
def reset():
global lastRequest, asyncRequest, cont
lastRequest = ''
asyncRequest = {}
global last_request, cont
last_request = ''
cont = 0
return Response(status=200)


# Globals
lastRequest = ''
last_request = ''
responseError = ''
myResponse = '{"details": {"rgb":"66CC00","t":2}}'
cont = 0
asyncRequest = {}
delay = ''

if __name__ == '__main__':
app.run(host=host, port=port)
app.run(host=host, port=port, debug=True)

0 comments on commit 3782bde

Please sign in to comment.