WVA datastream to device cloud

From Digi Developer

Jump to: navigation, search

Example: WVA to Device Cloud

This a simple example to show how to collect data from the WVA, format it and upload the data as DataStream to Device Cloud.

To run the example bellow

  • Upload the script to the WVA under the name simple_wva.py.
  • Dropdown to the shell, Enter the command python simple_wva.py and Hit Enter.


############################################################################
#                                                                          #
# Copyright (c)2015, Digi International (Digi). All Rights Reserved.       #
#                                                                          #
# Permission to use, copy, modify, and distribute this software and its    #
# documentation, without fee and without a signed licensing agreement, is  #
# hereby granted, provided that the software is used on Digi products only #
# and that the software contain this copyright notice,  and the following  #
# two paragraphs appear in all copies, modifications, and distributions as #
# well. Contact Product Management, Digi International, Inc., 11001 Bren   #
# Road East, Minnetonka, MN, +1 952-912-3444, for commercial licensing     #
# opportunities for non-Digi products.                                     #
#                                                                          #
# DIGI SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED   #
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A          #
# PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, #
# PROVIDED HEREUNDER IS PROVIDED "AS IS" AND WITHOUT WARRANTY OF ANY KIND. #
# DIGI HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,         #
# ENHANCEMENTS, OR MODIFICATIONS.                                          #
#                                                                          #
# IN NO EVENT SHALL DIGI BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,      #
# SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,   #
# ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF   #
# DIGI HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.                #
#                                                                          #
############################################################################
 
"""
    Simple WVA to Device Cloud Example
"""
 
import time
import json
import httplib
import traceback
from cgi import escape
 
import idigidata
 
class wva_simple(object):
    """
        this class connect to the local wva api
    """
    VERSION = "1.1"
 
    def __init__(self, host="127.0.0.1"):
        self.host = host
        self.connection = None
        self.json_headers = {'ACCEPT': 'application/json',
                             'Content-Type': 'application/json'}
 
    def collect(self, list_of_urls):
        """
            Description:
                collect data from the WVA
            Args:
                list_of_urls - a list of WVA data urls
            Returns:
                a json object
            Raises:
                (None)
        """
        data_obj = {}
        try:
            for url in list_of_urls:
                full_url = self.host + "/ws/" + url
                print "URL = %s" % full_url
                _data = self.read(url)[1]
                data_obj.update(json.loads(_data))
        except ValueError:
            print "Did not receive json data back: [[[%s]]]" % str(_data)
        except:
            print "Error while reading url: %s\n%s" % (full_url, traceback.format_exc())
        finally:
            self.connection.close()
            self.connection = None
        return data_obj
 
    def read(self, partial_url):
        """
            Description:
                perform a url request
            Args:
                partial_url: a url to be read - i.e: /vehicle/dtc
                output_format: response output, The WVA support JSON(default) and XML
            Returns:
                status: the response status from the server
                res: the response status (JSON or XML String)
            Raises:
                HTTPException: if an Error occurs when trying to read.
        """
        try:
            if not self.connection:
                self.connection = httplib.HTTPSConnection(self.host, timeout=15)
            self.connection.request("GET", "/ws/" + partial_url, headers=self.json_headers)
            response = self.connection.getresponse()
            return response.status, response.read()
        except httplib.HTTPException, err:
            raise httplib.HTTPException(str(err) + " " + partial_url)
 
def wva_collect_forever():
    """
        Description:
            This is the main entry point of this example
        Args:
            (None)
        Returns:
            (None)
        Raises:
            (None)
    """
    data_list = [
        "vehicle/data/VehicleSpeed",
        "vehicle/data/EngineSpeed",
        "vehicle/data/TotalEngineHours",
        "vehicle/data/TotalDistance",
        "vehicle/data/BatteryPotential",
        "vehicle/data/FuelEconomy",
        "vehicle/data/FuelLevel",
    ]
 
    # initialize wva interface
    wva = wva_simple()
 
    while True:
        #collect
        collected = wva.collect(data_list)
 
        #format
        datapoints = ""
        for data in collected:
            datapoints += ("<DataPoint>"
                           "<streamId>%(streamId)s</streamId>"
                           "<data>%(data)s</data>"
                           "<timestamp>%(timestamp)s</timestamp>"
                           "</DataPoint>"
                           % {
                               "streamId": escape(data),
                               "data": collected[data]["value"],
                               "timestamp": int(time.mktime(time.strptime(collected[data]["timestamp"],
                                                                          "%Y-%m-%dT%H:%M:%SZ")) * 1000)
                           })
 
        datapoint_list = "<list>%s</list>" % str(datapoints)
        print datapoint_list
 
        #upload
        print idigidata.send_to_idigi(datapoint_list, "DataPoint/stream.xml")
        time.sleep(60)
 
if __name__ == '__main__':
    wva_collect_forever()
Personal tools
Wiki Editing