WNS Web Notification Service

the WNS is a service gathering data from an istSOS database and sending a notification to the users after testing the retrieved data to meet some conditions. The systems is divided in three parts: a database for storing the information about the notifications, the users and the registrations of the users to the notifications; a database of the istSOS service storing the actual data received from external sensors; and a scheduler that periodically runs the functions to retrieve the data, test it and send the notifications to the registered users. The system also do a notification on a twitter account.

WNS database schema

The wns schema is represented below.

_images/wnsSchema.png

Activation of WNS

To activate the IWNS (istSOS Web Notification Service) you shall provide same configuration setting (unfortunately a GUI is not yet available). To configure the service you have to open the default.cfg file under your services folder (..istSOS/services/default.cfg) with a text editor and add the following mandatory parameters:

[connectionWns]
dbname = istsos
host = 127.0.0.1
user = postgres
password = postgres
port = 5432

And at least one of mail and twitter parameters as follows:

[mail]
usermail = mail@notifier.com
password =

[twitter]
oauth_token = ""
oauth_secret = ""
consumer_key = ""
consumer_secret = ""

Warning

Actually the system update the status on twitter and can send notification via email.

After saving the modified configuration file, to setup the Web Service execute this POST request:

http://localhost/istsos/wns/setup

This will create a notification.asp file under the service/ folder (where the notification functions are stored) and create a schema in the WNS database.

Create a notification

It’s possible to create two type of notification, a simple notification, that execute a getObservation, and a complex observation, where the user can write a specific request.

Method 1: simple notification

Do a POST request to:

http://localhost/istsos/wns/notification

with the following parameters:

  • name: the notification event name [mandatory]
  • description: an explicative sentence on what this notification is about [mandatory]
  • period: expressed in hours, if present is the interval over witch the getObservation will be performed, starting from NOW i.e. the last 2 hours. [optional]
  • interval: the interval used to perform observation checks expressed in minutes [mandatory]
  • service: the service name [mandatory]
  • condition: the condition describes in which case the notification will be performed. Every element retrived with the getObservation is tested again this contion, and as soon one element satisfies it the notification is triggered.
  • params: this is used to build a getObservation request. The offering, observedPropertiy and procedure are mandatory.

Example:

{
    "name": "functionName",
    "description": "do getObservation and check condition",
    "interval": 20,
    "params": {
        "offering":"desired_offering",
        "observedProperty":"desired_property",
        "procedure":"desired_procedure"
    },
    "condition": "< 5",
    "service": "service_name",
    "period": 2
}

Method 2: complex notification

create a python function with the following constraint:

  1. The content of the function must have the structure of the extract below, retrieving the data, handling it and checking a condition to send out notifications.

  2. Pay attention to the function name you choose, because the exact name has to be used in the next step. The name also has to be unique, to avoid potential overriding.

  3. The if block at the end of the method is the one triggering the notification, if the given condition is met. The two lines specified in the extract should be copied in your method, to make sure you import the correct file.

  4. The ns.notify() method takes three arguments:
    1. functionName of the method you defined [Mandatory]
    2. a python dict containing the message to send via twitter or mail [Mandatory]
    3. Status: the last parameter is a flag, if True, the Notifier update the status of the twitter account [Optional, default True].

Example:

def meanTemp():
    import datetime
    import time
    from lib.pytz import timezone
    now = datetime.datetime.now().replace(tzinfo=timezone(time.tzname[0]))
    endDate = now.strftime('%Y-%m-%dT%H:%M:%S%z')
    eventTime = now - datetime.timedelta(hours=5)
    startDate = eventTime.strftime('%Y-%m-%dT%H:%M:%S%z')

    startDate = datetime.datetime(2015,7,12,15,00,0, tzinfo=timezone(time.tzname[0])).strftime('%Y-%m-%dT%H:%M:%S%z')
    endDate = datetime.datetime(2015,7,12,16,00,0, tzinfo=timezone(time.tzname[0])).strftime('%Y-%m-%dT%H:%M:%S%z')

    rparams = {"service": "SOS", "offering": "temporary", "request": "GetObservation",
                "version": "1.0.0", "responseFormat": "application/json",
                "observedProperty": "air", "procedure": "T_BELLINZONA"}
    rparams['eventTime'] = str(startDate) + "/" +str(endDate)

    import lib.requests as requests
    res = requests.get('http://localhost/istsos/demo', params=rparams )

    result = res.json()['ObservationCollection']['member'][0]['result']['DataArray']['values']

    mean = 0
    count = 0

    for el in result:
        if float(el[1]) != -999.9:
            mean += float(el[1])
            count += 1

    if len(result) == 0:
        message = "Cannot make mean with no data"
    else:
        mean = mean / count
        message = "The mean temp in Bellinzona in the last hour: "  + str(mean)

    notify = {
        "twitter": {
            "public": message,
            "private": message
        },
        "mail":{
            "subject": "mean temp from T_BELLINZONA",
            "message": message
        }
    }

    import wnslib.notificationScheduler as nS
    nS.notify('meanTemp',notify, True)

do this post request:

http://localhost/istsos/wns/notification
with the following params:
  • name: function name [mandatory]
  • description: a little function description
  • interval: interval [mandatory]
  • function: path to function file [mandatory]

Example:

{
        "name": "meanTemp",
        "description": "last hour temp in Bellinzona",
        "interval": 60,
        "function": "path/to/function.py"
}

Delete notification

It’s possible delete a notification with this DELETE request:

http://localhost/istsos/wns/notification/<notification_id>

Warning

You can delete a notification only if no user are subscribed

Register a user

to subscribe to a notification and receive update you must create a user and provide some information to contact you. do this POST request:

http://localhost/istsos/wns/user

with the following params:

  1. username: is the name that will be used to recognise the user [mandatory]
  2. email: a user email [mandatory]
  3. twitter: twitter id, mandatory if you will recieve notification via twitter private message
  4. tel: mobile phone number, mandatory if you will recieve notification via mobile phone (actually not supported)
  5. fax, address, zip, city, state, country: additional info about the user

Example:

{
        "username": "userName",
        "email": "user.name@provider.com",
        "twitter": "userTwitter",
        "tel": "+41123456789",
        "fax": "+41123456080",
        "address": "via test",
        "zip": "1234",
        "city": "",
        "state": "",
        "country": "",
}

Delete a user

It’s possible to remove user with this DELETE request:

http://localhost/istsos/wns/user/<user_id>

Warning

When you delete a user it automatically unsubscribe from notifications

Subscribe to a notification

To receive notification you must subscribe to an existing notification, do this POST request

http://localhost/istsos/wns/user/<user_id>/notification/<notification_id>
with the following params
  1. data: array of how would you like to receive the notification [mandatory]
::
{
“data”: [“mail”, “twitter”]

}

Unsubscribe to a notification

Unsubscribe a user from notification with this DELETE request

http://localhost/istsos/wns/user/<user_id>/notification/<notification_id>

Activate the scheduler

To activate the scheduler move to istsos root filder and run the scheduler script

cd path_to_istsos
python scheduler.py