Python: add EventAgentSample
[smartapi.git] / Examples / Python / EventAgentSample / server.py
1 #!/usr/bin/python
2
3
4 import paho.mqtt.publish as publish
5
6 from SmartAPI.factory.NotificationFactory import NotificationFactory
7 from SmartAPI.factory.ResponseFactory import ResponseFactory
8 from SmartAPI.common.Tools import Tools
9 from SmartAPI.common.SERIALIZATION import SERIALIZATION
10 from SmartAPI.common.NS import NS
11 from SmartAPI.model.Status import Status
12 from SmartAPI.model.Activity import Activity
13 from SmartAPI.model.Entity import Entity
14
15 use_jsonld = True
16
17 mqtt_server = "broker.asema.com"
18
19 calculation_id = 1
20
21 delay_min_time_seconds = 10
22 delay_max_time_seconds = 20
23
24 import web
25
26 class SampleServer():
27     def __init__(self):
28         pass
29
30     # Creates a dummy result in RDF format and sends it over MQTT
31     # to listeners
32     def notify_ready(self, id):
33         notification = NotificationFactory().create("http://www.calculator.com/example")
34         notification.setMessageId(id)
35         status = Status()
36         status.setPercentage(100)
37         notification.setStatus(status)
38         activity = Activity()
39         entity = Entity("http://www.calculator.com/calculatedentity")
40         activity.addEntity(entity)
41         notification.addActivity(activity)
42     
43         payload, content_type = Tools().serializeNotification(notification)
44         publish.single("sample/result/youcom/calculations", payload, hostname=mqtt_server)
45     
46     def POST(self):
47         # parse request message into Smart API Request Object     
48         req_str = rawRequest(web.ctx.env) 
49         content_type = web.ctx.env.get('Content-Type')
50         request = Tools().parseRequest(req_str, content_type)
51
52         response = ResponseFactory().create("http://talk.asema.com/demo/smart/demoresponder")
53         activity = Activity()
54         response.addActivity(activity)
55         status = Status()
56         status.setPercentage(100)
57         response.setStatus(status)
58         
59         payload, content_type = Tools().serializeResponse(response)
60         
61         self.notify_ready(1)
62         return payload
63
64
65 def rawRequest(env):
66     req = env['wsgi.input'].read(int(env['CONTENT_LENGTH']))
67     return req    
68
69 if __name__ == "__main__":
70     # the url for this tiny Smart API server will be: 
71     # http://0.0.0.0:8080/demo/smart/v1.0e1.0/access
72     app = web.application(('/smart/v1.0e1.0/access', 'SampleServer'), globals())
73     web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", 3333))
74