Esempio n. 1
0
def getDataSourcesXidsByType(ip, reqCookie, dataSourceType):
    '''  The function gets a dataSource type and returns the xids of all data sources of the same type.'''
    common.print_frame()
    if "bacnet_ip" in dataSourceType.lower():
        ds_type = "BACnetIP"
    elif "sql" in dataSourceType.lower():
        ds_type = "SQL"
    elif "http" in dataSourceType.lower():
        ds_type = "HTTP_RETRIEVER"
    elif "mango" in dataSourceType.lower():
        ds_type = "PERSISTENT"
    elif "modbus_ip" in dataSourceType.lower():
        ds_type = "MODBUS_IP"
    elif "modbus_serial" in dataSourceType.lower():
        ds_type = "MODBUS_SERIAL"
    elif "bacnet_mstp" in dataSourceType.lower():
        ds_type = "BACnetMSTP"
    else:
        print "Unknown data source type"
        return
    xidsList = []
    ds = dataSources(ip, reqCookie)
    jds = json.loads(ds)
    for source in jds:
        if source['modelType'] == ds_type:
            xidsList.append(source['xid'])
    return xidsList
Esempio n. 2
0
def login(ip_add, user_name, password):
    """
         The function login to Mango and returns a cookie which needed to all API functions
    :param ip_add:
    :param user_name: The user name
    :param password: The password to login
    :return:
    """
    common.print_frame()
    myHeader = {'Accept': 'application/json',
                'password': password}
    try:
        r = requests.get('http://' + ip_add + ':8080' + '/rest/v1/login/' + user_name, headers=myHeader)
        if r.status_code == 200 or r.status_code == 201:
            print "Successfully login"
            setCookie = r.headers['Set-Cookie']
            return parseMyCookie(setCookie)
        else:
            print "Login was failed!"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 3
0
def getDataPointByXid(ip, reqCookie, xid):
    """
    :param ip:
    :param reqCookie:
    :param Xid: data point xid
    :return: Get data point by XID
    """
    common.print_frame()
    print xid
    myHeader = {
        'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']
    }
    try:
        r = requests.get('http://' + ip + ':8080' + '/rest/v1/data-points/' +
                         str(xid),
                         headers=myHeader,
                         cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 4
0
def getLogFilesNames(ip, reqCookie, limit):
    """
    :param ip:
    :param reqCookie:
    :return: Returns a list of logfile names
    """
    common.print_frame()
    myHeader = {
        'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']
    }
    try:
        r = requests.get('http://' + ip + ':8080' +
                         '/rest/v1/logging/files?limit=' + str(limit),
                         headers=myHeader,
                         cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 5
0
def setPointLocator_Modbus(modelType="PL.MODBUS",
                           dataType="BINARY",
                           settable="true",
                           relinquishable="false",
                           bit=0,
                           slaveId=1,
                           additive=0,
                           modbusDataType="BINARY",
                           multiplier=1,
                           slaveMonitor="false",
                           registerCount=0,
                           charset="ASCII",
                           writeType="SETTABLE",
                           range="COIL_STATUS",
                           offset=0):
    common.print_frame()
    textRenderer = setTextRenderer(dataType)
    pointLocator = {
        'modelType': modelType,
        'dataType': dataType,
        'settable': settable,
        'relinquishable': relinquishable,
        'bit': bit,
        'slaveId': slaveId,
        'additive': additive,
        'modbusDataType': modbusDataType,
        'multiplier': multiplier,
        'slaveMonitor': slaveMonitor,
        'registerCount': registerCount,
        'charset': charset,
        'writeType': writeType,
        'range': range,
        'offset': offset
    }
    return {'textRenderer': textRenderer, 'pointLocator': pointLocator}
Esempio n. 6
0
def getRecentLogsFromFile(ip, reqCookie, fileName):
    """
    :param ip:
    :param reqCookie:
    :param fileName:
    :return: Returns a list of recent logs
    """
    common.print_frame()
    myHeader = {
        'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']
    }
    try:
        r = requests.get('http://' + ip + ':8080' +
                         '/rest/v1/logging/by-filename/' + fileName,
                         headers=myHeader,
                         cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:  # This is the correct syntax
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 7
0
def realTimeList(ip, reqCookie):
    """
    :param ip:
    :param reqCookie:
    :return:List realtime values
    """
    common.print_frame()
    myHeader = {
        'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']
    }
    try:
        r = requests.get('http://' + ip + ':8080' +
                         '/rest/v1/realtime/list?limit=100',
                         headers=myHeader,
                         cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 8
0
def getThreads(ip, reqCookie):
    """
    :param ip:
    :param reqCookie:
    :return: Get all thread
    """
    common.print_frame()
    myHeader = {
        'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']
    }
    try:
        r = requests.get(
            'http://' + ip + ':8080' +
            '/rest/v1/threads?stackDepth=10&asFile=false',
            headers=myHeader,
            cookies=reqCookie,
        )
        print r.status_code
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 9
0
def login(ip_add, user_name, password):
    """
         The function login to Mango and returns a cookie which needed to all API functions
    :param ip_add:
    :param user_name: The user name
    :param password: The password to login
    :return:
    """
    common.print_frame()
    myHeader = {'Accept': 'application/json', 'password': password}
    try:
        r = requests.get('http://' + ip_add + ':8080' + '/rest/v1/login/' +
                         user_name,
                         headers=myHeader)
        if r.status_code == 200 or r.status_code == 201:
            print "Successfully login"
            setCookie = r.headers['Set-Cookie']
            return parseMyCookie(setCookie)
        else:
            print "Login was failed!"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 10
0
def getLatestPointValues(ip, reqCookie, xid, limit):
    """
    :param ip:
    :param reqCookie:
    :param xid:
    :param limit:
    :return: Get Latest Point Values
    """
    common.print_frame()
    myHeader = {
        'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']
    }
    try:
        r = requests.get(
            'http://' + ip + ':8080' + '/rest/v1/point-values/' + xid +
            '/latest?useRendered=false&unitConversion=false&limit=' +
            str(limit) + '&useCache=true',
            headers=myHeader,
            cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 11
0
def getPointHierarchyFolderByName(ip, reqCookie, folderName):
    """
    :param ip:
    :param reqCookie:
    :param folderName:
    :return: Get point hierarchy folder by name
    """
    common.print_frame()
    numOfWOrdes = len(folderName.split())
    newName = ""
    i = 0
    while i < numOfWOrdes - 1:
        newName = newName + folderName.split()[i] + '%20'
        i += 1
    newName = newName + folderName.split()[i]
    print newName
    myHeader = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']}
    try:
        r = requests.get('http://' + ip + ':8080' + '/rest/v1/hierarchy/by-name/' + newName, headers=myHeader, cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 12
0
def getPathToPointByXid(ip, reqCookie, Xid):
    """
    :param ip:
    :param reqCookie:
    :param Xid: point data Xid
    :return: Get path to a point using point's XID
    """
    common.print_frame()
    numOfWOrdes = len(Xid.split())
    newXid = ""
    i = 0
    while i < numOfWOrdes - 1:
        newXid = newXid + Xid.split()[i] + '%20'
        i += 1
    newXid = newXid + Xid.split()[i]
    print newXid
    myHeader = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']}
    try:
        r = requests.get('http://' + ip + ':8080' + '/rest/v1/hierarchy/path/' + newXid, headers=myHeader, cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 13
0
def setUserHomePage(ip, reqCookie, myUser, newUrl):
    """
    :param ip:
    :param reqCookie:
    :param userName:
    :param newUrl:
    :return: Update a user's home url
    """
    common.print_frame()
    myHeader = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']}
    try:
        r = requests.put('http://' + ip + ':8080' + '/rest/v1/users/' + myUser.username + '/homepage?url=' + newUrl, headers=myHeader,
                         cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            print "The user home page was set!"
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 14
0
def getDataPointByXid(ip, reqCookie, xid):
    """
    :param ip:
    :param reqCookie:
    :param Xid: data point xid
    :return: Get data point by XID
    """
    common.print_frame()
    print xid
    myHeader = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']}
    try:
        r = requests.get('http://' + ip + ':8080' + '/rest/v1/data-points/' + str(xid), headers=myHeader,
                         cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 15
0
def getLatestPointValues(ip, reqCookie, xid, limit):
    """
    :param ip:
    :param reqCookie:
    :param xid:
    :param limit:
    :return: Get Latest Point Values
    """
    common.print_frame()
    myHeader = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']}
    try:
        r = requests.get(
            'http://' + ip + ':8080' + '/rest/v1/point-values/' + xid +
            '/latest?useRendered=false&unitConversion=false&limit=' + str(limit) + '&useCache=true', headers=myHeader,
            cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 16
0
def getPointValuesHistoryByTimeRange(ip, reqCookie, xid, fromDate, endDate, rollup, timePeriodType):
    """
    :param ip:
    :param reqCookie:
    :param xid:
    :param fromDate:
    :param endDate:
    :param rollup: NONE/AVERAGE/DELTA/MINIMUM/MAXIMUM/ACCUMULATOR/SUM/FIRST/LAST/COUNT/INTEGRAL/FFT
    :param timePeriodType: MILLISECONDES/SECONDES/MINUTES/HOURS/DAYS/WEEKS/MONTHS/YEARS
    :return:
    """
    common.print_frame()
    newFromDate = str(fromDate).replace(':', '%3A')
    newEndDate = str(endDate).replace(':', '%3A')
    print newFromDate
    print newEndDate
    myHeader = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']}
    try:
        r = requests.get(
            'http://' + ip + ':8080' + '/rest/v1/point-values/' + xid + '?useRendered=true&unitConversion=true&from='
             + newFromDate + '&to=' + newEndDate + '&rollup=' + rollup + '&timePeriodType=' + timePeriodType,
            headers=myHeader, cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 17
0
def getCommentsExplainQuery(ip, reqCookie):
    """
    :param ip:
    :param reqCookie:
    :return: Get Explaination For Query
    """
    common.print_frame()
    myHeader = {
        'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']
    }
    try:
        r = requests.get('http://' + ip + ':8080' +
                         '/rest/v1/comments/explain-query',
                         headers=myHeader,
                         cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occured"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 18
0
def getFirstAndLastPointValuesInTimeRange(ip, reqCookie, xid, fromDate, endDate):
    """
    :param ip:
    :param reqCookie:
    :param xid:
    :param fromDate:
    :param endDate:
    :return:
    """
    common.print_frame()
    newFromDate = str(fromDate).replace(':', '%3A')
    newEndDate = str(endDate).replace(':', '%3A')
    print newFromDate
    print newEndDate
    myHeader = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']}
    try:
        r = requests.get(
            'http://' + ip + ':8080' + '/rest/v1/point-values/' + xid +
            '/first-last?useRendered=false&unitConversion=false&from=' + newFromDate + '&to=' + newEndDate,
            headers=myHeader, cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 19
0
def setPointLocator_HttpRetriever(dataType="BINARY",
                                  settable="false",
                                  modelType="PL.HTTP_RETRIEVER",
                                  relinquishable="false",
                                  valueRegex="",
                                  ignoreIfMissing="false",
                                  valueFormat="",
                                  timeRegex="",
                                  timeFormat="",
                                  setPointName=""):
    common.print_frame()
    textRenderer = setTextRenderer(dataType)
    pointLocator = {
        'modelType': modelType,
        'dataType': dataType,
        'settable': settable,
        'relinquishable': relinquishable,
        'valueRegex': valueRegex,
        'ignoreIfMissing': ignoreIfMissing,
        'valueFormat': valueFormat,
        'timeRegex': timeRegex,
        'timeFormat': timeFormat,
        'setPointName': setPointName
    }
    return {'textRenderer': textRenderer, 'pointLocator': pointLocator}
Esempio n. 20
0
def setPointLocator_Sql(dataType="BINARY",
                        settable="false",
                        relinquishable="false",
                        modelType="PL.SQL",
                        fieldName="",
                        timeOverrideName="",
                        updateStatement="",
                        tableModifier="false",
                        parameters=[],
                        dateParameterFormat="yyyy-MM-dd'T'HH:mm:ss"):
    common.print_frame()
    textRenderer = setTextRenderer(dataType)
    pointLocator = {
        'dataType': dataType,
        'settable': settable,
        'relinquishable': relinquishable,
        'modelType': modelType,
        'fieldName': fieldName,
        'timeOverrideName': timeOverrideName,
        'updateStatement': updateStatement,
        'tableModifier': tableModifier,
        'parameters': parameters,
        'dateParameterFormat': dateParameterFormat
    }
    return {'textRenderer': textRenderer, 'pointLocator': pointLocator}
Esempio n. 21
0
def dataPoints(ip, reqCookie):
    """
    :param ip:
    :param reqCookie:
    :return: The function returns all information about all data points
    """
    common.print_frame()
    myHeader = {
        'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']
    }
    try:
        r = requests.get('http://' + ip + ':8080' + '/rest/v1/data-points',
                         headers=myHeader,
                         cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 22
0
def setPointLocator_BacnetIp(mac,
                             modelType="PL.BACNET_IP",
                             dataType="BINARY",
                             settable="false",
                             relinquishable="false",
                             networkNumber=0,
                             remoteDeviceInstanceNumber=0,
                             objectTypeId="ANALOG_INPUT",
                             objectInstanceNumber=0,
                             propertyIdentifierId="PRESENT_VALUE",
                             useCovSubscription="false",
                             writePriority=16):
    common.print_frame()
    return {
        'modelType': modelType,
        'dataType': dataType,
        'settable': settable,
        'relinquishable': relinquishable,
        'mac': mac,
        'networkNumber': networkNumber,
        'remoteDeviceInstanceNumber': remoteDeviceInstanceNumber,
        'objectTypeId': objectTypeId,
        'objectInstanceNumber': objectInstanceNumber,
        'propertyIdentifierId': propertyIdentifierId,
        'useCovSubscription': useCovSubscription,
        'writePriority': writePriority
    }
Esempio n. 23
0
def checkIfDataSourceExists(ip, reqCookie, source_name):
    common.print_frame()
    all_dataSources = dataSources(ip, reqCookie)
    jds = json.loads(all_dataSources)
    check_if_data_source_exists = "false"
    for source in jds:
        if source['name'] == source_name:
            check_if_data_source_exists = "true"
    return check_if_data_source_exists
Esempio n. 24
0
def craeteDataSourceFile():
    """
    The function gets the type of the file to create: publishers or dataSources
     and creates the file with it's special text.
    """
    common.print_frame()
    with open('dataSource.txt', 'w') as f:
        f.write("{\n")
        f.write('"dataSources":[\n')
Esempio n. 25
0
def getDataPointsXidFromJson(json_data):
    '''The function gets a json file and returns a list of data points xids.'''
    common.print_frame()
    jds = json.loads(json_data)
    xids_list = []
    print(jds['total'])
    for row in jds['items']:
        xids_list.append(row['xid'])
    return xids_list
Esempio n. 26
0
def getPointsXidBelongsToDataSource(ip, reqCookie, d_xid):
    ''' The function gets dataSource xid and returns a list of all it\'s dataPoints xids.'''
    common.print_frame()
    dp = dataPointsForDataSourceByXid(ip, reqCookie, d_xid)
    jds = json.loads(dp)
    xids_list = []
    for source in jds:
        xids_list.append(source['xid'])
    return xids_list
Esempio n. 27
0
def addPublisher(myPublisher):
    common.print_frame()
    if not os.path.exists("publishers.txt"):
     craetePublishersFile()
    add_publisher = {}
    publisher_type = myPublisher.type
    if publisher_type == "PERSISTENT":
        add_publisher = {"xid": myPublisher.xid,
                         "type": "PERSISTENT",
                         "points": myPublisher.points,
                         "snapshotSendPeriodType": myPublisher.snapshotSendPeriodType,
                         "historyCutoffPeriodType": myPublisher.historyCutoffPeriodType,
                         "logLevel": myPublisher.logLevel,
                         "authorizationKey": myPublisher.authorizationKey,
                         "connectionCheckPeriod": myPublisher.connectionCheckPeriod,
                         "historyCutoffPeriods": myPublisher.historyCutoffPeriods,
                         "host": myPublisher.host,
                         "maxPointValuesToSend": myPublisher.maxPointValuesToSend,
                         "parallelSyncTasks": myPublisher.parallelSyncTasks,
                         "port": myPublisher.port,
                         "reconnectSyncs": myPublisher.reconnectSyncs,
                         "socketTimeout": myPublisher.socketTimeout,
                         "syncPattern": myPublisher.syncPattern,
                         "syncPointHierarchy": myPublisher.syncPointHierarchy,
                         "syncRealTime": myPublisher.syncRealTime,
                         "syncRequestRetryAttempts": myPublisher.syncRequestRetryAttempts,
                         "syncResponseTimeout": myPublisher.syncResponseTimeout,
                         "useCompression": myPublisher.useCompression,
                         "useCrc": myPublisher.useCrc,
                         "xidPrefix": myPublisher.xidPrefix,
                         "cacheDiscardSize": myPublisher.cacheDiscardSize,
                         "cacheWarningSize": myPublisher.cacheWarningSize,
                         "changesOnly": myPublisher.changesOnly,
                         "enabled": myPublisher.enabled,
                         "name": myPublisher.name,
                         "sendSnapshot": myPublisher.sendSnapshot,
                         "snapshotSendPeriods": myPublisher.snapshotSendPeriods
                         }

    if publisher_type == "BACnet":
        add_publisher = {"xid": myPublisher.xid,
                         "type": "BACnet",
                         "points": myPublisher.points,
                         "enabled": myPublisher.enabled,
                         "name": myPublisher.name,
                         "snapshotSendPeriodType": myPublisher.snapshotSendPeriodType,
                         "localDeviceConfig": myPublisher.localDeviceConfig,
                         "cacheDiscardSize": myPublisher.cacheDiscardSize,
                         "cacheWarningSize": myPublisher.cacheWarningSize,
                         "changesOnly": myPublisher.changesOnly,
                         "sendSnapshot": myPublisher.sendSnapshot,
                         "snapshotSendPeriods": myPublisher.snapshotSendPeriods
                         }

    with open('publishers.txt', 'ab+') as f:
        json.dump(add_publisher, f)
    closePublishersFile()
Esempio n. 28
0
def getDataPointsXidFromJson(json_data):
    '''The function gets a json file and returns a list of data points xids.'''
    common.print_frame()
    jds = json.loads(json_data)
    xids_list = []
    print(jds['total'])
    for row in jds['items']:
        xids_list.append(row['xid'])
    return xids_list
Esempio n. 29
0
def getPointsXidBelongsToDataSource(ip, reqCookie, d_xid):
    ''' The function gets dataSource xid and returns a list of all it\'s dataPoints xids.'''
    common.print_frame()
    dp = dataPointsForDataSourceByXid(ip, reqCookie, d_xid)
    jds = json.loads(dp)
    xids_list = []
    for source in jds:
        xids_list.append(source['xid'])
    return xids_list
Esempio n. 30
0
def parseMyCookie(reqCookie):
    common.print_frame()
    tempCookie = reqCookie.split(',')
    myCookie = {
        (tempCookie[0].split(';')[0]).split('=')[0].strip():
        (tempCookie[0].split(';')[0]).split('=')[1],
        (tempCookie[1].split(';')[0]).split('=')[0].strip():
        (tempCookie[1].split(';')[0]).split('=')[1]
    }
    return myCookie
Esempio n. 31
0
def createNewComment(ip,
                     reqCookie,
                     comment,
                     commentType="POINT",
                     level="INFORMATION"):
    """
    :param ip:
    :param reqCookie:
    :param comment:
    :param level: WARNING/ERROR/INFORMATION
    :param commentType: POINT
    :return: Create New User Comment
    """
    common.print_frame()
    payload = {
        "xid": "null",
        "name": "null",
        "timestamp": 0,
        "commentType": commentType,
        "comment": comment,
        "username": "",
        "modelType": "null",
        "userId": 0,
        "referenceId": 0,
        "validationMessages": [{
            "message": "",
            "level": level,
            "property": ""
        }]
    }
    parameters_json = json.dumps(payload)
    myHeader = {
        'Accept': 'application/json',
        'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN'],
        'User-Agent':
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36',
        'Content-Type': 'application/json; charset=UTF-8',
        'Connection': 'keep-alive'
    }
    try:
        r = requests.post('http://' + ip + ':8080' + '/rest/v1/comments',
                          headers=myHeader,
                          data=parameters_json,
                          cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            print "The comment was saved!"
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 32
0
def getDataSourceXid(ip, reqCookie, dataSourceName):
    """
    The function gets a data source name and returns it's xid
    """
    common.print_frame()
    ds = dataSources(ip, reqCookie)
    jds = json.loads(ds)
    for source in jds:
        if source['name'] == dataSourceName:
            return source['xid']
    return 'Data source not found.'
Esempio n. 33
0
def publisherSetMangoPersistentTCPoint(points):
    """
    The function gets a lists of data points Xids and return a new list with a specific syntax.
    :param points:
    :return:
    """
    common.print_frame()
    newList = []
    for point in points:
        newList.append({"dataPointId": point})
    return newList
Esempio n. 34
0
def insertUpdateDataPoint_json(ip, reqCookie, json_data):
    common.print_frame()
    print json.dumps(json_data)
    myHeader = {'Accept': 'application/json',
                'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN'],
                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36',
                'Content-Type': 'application/json; charset=UTF-8',
                'Connection': 'keep-alive'}
    r = requests.put('http://' + ip + ':8080' + '/rest/v1/data-points', data=json.dumps([json_data]), headers=myHeader,
                     cookies=reqCookie)
    print r.status_code
Esempio n. 35
0
def changeCOVvalueToFalse(ip, reqCookie):
    common.print_frame()
    bacnetXIDS = ds_f.getDataSourcesXidsByType(ip, reqCookie, "BACNET_ip")
    datapointsXIDS = []
    for datasource in bacnetXIDS:
        datapints_belongesTodatasource = getPointsXidBelongsToDataSource(ip, reqCookie, datasource)
        datapointsXIDS.extend(datapints_belongesTodatasource)
    for dataPoint in datapointsXIDS:
        dp = getDataPointByXid(ip, reqCookie, dataPoint)
        jdp = json.loads(dp)
        dataPoint_type = jdp['pointLocator']['modelType']
        if dataPoint_type == "PL.BACNET_IP":
            jdp['pointLocator']['useCovSubscription'] = "false"
            insertUpdateDataPoint_json(ip, reqCookie, jdp)
Esempio n. 36
0
def changeCOVvalueToFalse(ip, reqCookie):
    common.print_frame()
    bacnetXIDS = ds_f.getDataSourcesXidsByType(ip, reqCookie, "BACNET_ip")
    datapointsXIDS = []
    for datasource in bacnetXIDS:
        datapints_belongesTodatasource = getPointsXidBelongsToDataSource(
            ip, reqCookie, datasource)
        datapointsXIDS.extend(datapints_belongesTodatasource)
    for dataPoint in datapointsXIDS:
        dp = getDataPointByXid(ip, reqCookie, dataPoint)
        jdp = json.loads(dp)
        dataPoint_type = jdp['pointLocator']['modelType']
        if dataPoint_type == "PL.BACNET_IP":
            jdp['pointLocator']['useCovSubscription'] = "false"
            insertUpdateDataPoint_json(ip, reqCookie, jdp)
Esempio n. 37
0
def setUser(ip, reqCookie, oldName, myUser):
    """
    :param ip:
    :param reqCookie:
    :param currentUserName:
    :param newUserName:
    :param newPass:
    :param newMail:
    :return: Updates a user
    """
    common.print_frame()
    payload = {'username': myUser.username,
               'email': myUser.email,
               'admin': 'false',
               'disabled': myUser.disabled,
               'homeUrl': myUser.homeUrl,
               'muted': 'false',
               'password': myUser.password,
               'permissions': myUser.permissions,
               'receiveAlarmEmails': myUser.receiveAlarmEmails,
               'receiveOwnAuditEvents': 'false',
               'systemTimezone': myUser.systemTimezone,
               'timezone': myUser.timezone,
               'validationMessages':[{'message': myUser.validationMessages['message'],
                                      'level': myUser.validationMessages['level'],
                                      'property': myUser.validationMessages['property']}]
               }
    print payload['validationMessages']
    parameters_json = json.dumps(payload)
    myHeader = {'Accept': 'application/json',
                'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN'],
                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36',
                'Content-Type': 'application/json; charset=UTF-8',
                'Connection': 'keep-alive'}
    try:
        r = requests.put('http://' + ip + ':8080' + '/rest/v1/users/' + oldName, headers=myHeader, data=parameters_json,
                         cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            print "The user was updated!"
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 38
0
def setPointLocator_Sql(dataType="BINARY", settable="false", relinquishable="false", modelType="PL.SQL",
                        fieldName="", timeOverrideName="", updateStatement="", tableModifier="false",
                        parameters=[], dateParameterFormat="yyyy-MM-dd'T'HH:mm:ss"):
    common.print_frame()
    textRenderer = setTextRenderer(dataType)
    pointLocator = {'dataType': dataType,
                    'settable': settable,
                    'relinquishable': relinquishable,
                    'modelType': modelType,
                    'fieldName': fieldName,
                    'timeOverrideName': timeOverrideName,
                    'updateStatement': updateStatement,
                    'tableModifier': tableModifier,
                    'parameters': parameters,
                    'dateParameterFormat': dateParameterFormat}
    return {'textRenderer': textRenderer, 'pointLocator': pointLocator}
Esempio n. 39
0
def insertUpdateDataPoint_json(ip, reqCookie, json_data):
    common.print_frame()
    print json.dumps(json_data)
    myHeader = {
        'Accept': 'application/json',
        'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN'],
        'User-Agent':
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36',
        'Content-Type': 'application/json; charset=UTF-8',
        'Connection': 'keep-alive'
    }
    r = requests.put('http://' + ip + ':8080' + '/rest/v1/data-points',
                     data=json.dumps([json_data]),
                     headers=myHeader,
                     cookies=reqCookie)
    print r.status_code
Esempio n. 40
0
def closeDataSourceFile():
    """
    The function close the file and add some needed text.
    """
    common.print_frame()
    with open('dataSource.txt', 'ab+') as f:
        f.write("]}")

        # this part is needed to parse boolean strings to boolean ex. "false" -> false
        f = open('dataSource.txt', 'r')
        file_data = f.read()
        f.close()
        newdata = file_data.replace('"false"', "false")
        newdata2 = newdata.replace('"true"', "true")
        f = open('dataSource.txt', 'w')
        f.write(newdata2)
        f.close()
Esempio n. 41
0
def setPointLocator_HttpRetriever(dataType="BINARY", settable="false", modelType="PL.HTTP_RETRIEVER",
                                  relinquishable="false", valueRegex="", ignoreIfMissing="false", valueFormat="",
                                  timeRegex="", timeFormat="", setPointName=""):
    common.print_frame()
    textRenderer = setTextRenderer(dataType)
    pointLocator = {'modelType': modelType,
                    'dataType': dataType,
                    'settable': settable,
                    'relinquishable': relinquishable,
                    'valueRegex': valueRegex,
                    'ignoreIfMissing': ignoreIfMissing,
                    'valueFormat': valueFormat,
                    'timeRegex': timeRegex,
                    'timeFormat': timeFormat,
                    'setPointName': setPointName
                    }
    return {'textRenderer': textRenderer, 'pointLocator': pointLocator}
Esempio n. 42
0
def point_locator(type, **kwrgs):
    """
    The function gets the data point type and call the right function
    :param type:
    :param args:
    :return:
    """
    common.print_frame()
    ans = {}
    if type == "SQL":
        ans = setPointLocator_Sql(**kwrgs)
    if type == "HttpRetriever":
        ans = setPointLocator_HttpRetriever(**kwrgs)
    if type == "Modbus":
        ans = setPointLocator_Modbus(**kwrgs)
    if type == "BacnetIp":
        ans = setPointLocator_BacnetIp(**kwrgs)
    return ans
Esempio n. 43
0
def setPointLocator_BacnetIp(mac, modelType="PL.BACNET_IP", dataType="BINARY", settable="false", relinquishable="false",
                             networkNumber=0, remoteDeviceInstanceNumber=0, objectTypeId="ANALOG_INPUT",
                             objectInstanceNumber=0, propertyIdentifierId="PRESENT_VALUE", useCovSubscription="false",
                             writePriority=16):
    common.print_frame()
    return {'modelType': modelType,
            'dataType': dataType,
            'settable': settable,
            'relinquishable': relinquishable,
            'mac': mac,
            'networkNumber': networkNumber,
            'remoteDeviceInstanceNumber': remoteDeviceInstanceNumber,
            'objectTypeId': objectTypeId,
            'objectInstanceNumber': objectInstanceNumber,
            'propertyIdentifierId': propertyIdentifierId,
            'useCovSubscription': useCovSubscription,
            'writePriority': writePriority
            }
Esempio n. 44
0
def dataSources(ip, reqCookie):
    """
    :param ip:
    :param reqCookie:
    :return: Get all data sources
    """
    common.print_frame()
    myHeader = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']}
    try:
        r = requests.get('http://' + ip + ':8080' + '/rest/v1/data-sources/list', headers=myHeader, cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
Esempio n. 45
0
def publisherSetBACnetPoint(ip, reqCookie, points):
    common.print_frame()
    newList = []
    i = 0
    for point in points:
        pointData = dataPoints_Functions.getDataPointByXid(ip, reqCookie, point)
        deviceNameLocation = pointData.find('"deviceName"')
        endDeviceNameLocation = pointData.find(',', deviceNameLocation)
        daviceName = pointData[deviceNameLocation + 16: endDeviceNameLocation - 1]

        nameLocation = pointData.find('"name"')
        endNameLocation = pointData.find(',', nameLocation)
        name = pointData[nameLocation + 10: endNameLocation - 1]

        newList.append({"dataPointId": point,
                        "instanceNumber": i,
                        "objectName": daviceName + " - " + name})
        i += 1
    return newList
Esempio n. 46
0
def createNewComment(ip, reqCookie, comment, commentType="POINT", level="INFORMATION"):
    """
    :param ip:
    :param reqCookie:
    :param comment:
    :param level: WARNING/ERROR/INFORMATION
    :param commentType: POINT
    :return: Create New User Comment
    """
    common.print_frame()
    payload = {"xid": "null",
               "name": "null",
               "timestamp": 0,
               "commentType": commentType,
               "comment": comment,
               "username": "",
               "modelType": "null",
               "userId": 0,
               "referenceId": 0,
               "validationMessages": [{"message": "",
                                       "level": level,
                                       "property": ""}]}
    parameters_json = json.dumps(payload)
    myHeader = {'Accept': 'application/json',
                'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN'],
                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36',
                'Content-Type': 'application/json; charset=UTF-8',
                'Connection': 'keep-alive'}
    try:
        r = requests.post('http://' + ip + ':8080' + '/rest/v1/comments', headers=myHeader, data=parameters_json, cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            print "The comment was saved!"
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 47
0
def userComments(ip, reqCookie):
    """
    :param ip:
    :param reqCookie:
    :return: Query User Comments
    """
    common.print_frame()
    myHeader = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']}
    try:
        r = requests.get('http://' + ip + ':8080' + '/rest/v1/comments', headers=myHeader, cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 48
0
def getLogFilesNames(ip, reqCookie, limit):
    """
    :param ip:
    :param reqCookie:
    :return: Returns a list of logfile names
    """
    common.print_frame()
    myHeader = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'X-XSRF-TOKEN': reqCookie['XSRF-TOKEN']}
    try:
        r = requests.get('http://' + ip + ':8080' + '/rest/v1/logging/files?limit=' + str(limit), headers=myHeader, cookies=reqCookie)
        if r.status_code == 200 or r.status_code == 201:
            return r.content
        else:
            print "error occurred"
            print "Reason: status code " + str(r.status_code)
            print "Exiting program!"
            sys.exit(1)
    except requests.exceptions.RequestException as e:
        print "Error: " + str(e)
        print "Exiting program!"
        sys.exit(1)
Esempio n. 49
0
def setPointLocator_Modbus(modelType="PL.MODBUS", dataType="BINARY", settable="true", relinquishable="false", bit=0,
                           slaveId=1, additive=0, modbusDataType="BINARY", multiplier=1, slaveMonitor="false",
                           registerCount=0, charset="ASCII", writeType="SETTABLE", range="COIL_STATUS", offset=0):
    common.print_frame()
    textRenderer = setTextRenderer(dataType)
    pointLocator = {'modelType': modelType,
                    'dataType': dataType,
                    'settable': settable,
                    'relinquishable': relinquishable,
                    'bit': bit,
                    'slaveId': slaveId,
                    'additive': additive,
                    'modbusDataType': modbusDataType,
                    'multiplier': multiplier,
                    'slaveMonitor': slaveMonitor,
                    'registerCount': registerCount,
                    'charset': charset,
                    'writeType': writeType,
                    'range': range,
                    'offset': offset
                    }
    return {'textRenderer': textRenderer, 'pointLocator': pointLocator}