Exemple #1
0
def getDeviceLog(connection, entryStart=0, entryEnd=25):

    global eventCommandPath

    count = int(entryStart)

    logEntryListStr = []

    logEntryList = []

    Commands.loadCommandsFromFile()

    logCommandJSON = Commands.getCommandJSON(eventCommandPath)

    memAddr = getTotalEventsCount(connection) - int(entryStart)

    while (count <= entryEnd):
        cmd = logCommandJSON['command'] + Common.hex3_encoded(memAddr)[2:]
        # cmd = logCommandJSON['command'] + Common.hex3(count)[2:]
        Config.getLogger().debug("Sending log entry command " + cmd +
                                 " to get entry #" + str(count) +
                                 " out of limit of " + str(entryEnd))
        recvString = connection.sendCommand(str(cmd))

        if memAddr == 0:
            memAddr = 511
        else:
            memAddr = memAddr - 1

        if recvString == "evno":
            break

        logEntryListStr.append(recvString[2:len(recvString) - 3])

        count = count + 1

    index = entryStart

    Config.getLogger().debug("List of event strings:\n %s",
                             pformat(logEntryListStr))

    for logStr in logEntryListStr:
        logEntry = makeLogListEntry(number=index)

        logEntry['code'] = logStr[0] + logStr[1] + logStr[2] + logStr[3]
        logEntry['event'] = CodeTable.getEventNameByCode(logEntry['code'])
        logEntry['zone'] = logStr[4] + logStr[5] + "-" + logStr[8] + logStr[9]
        logEntry['event_type'] = CodeTable.getEventTypeByCode(logStr[7])
        logEntry['activated'] = logStr[10] + logStr[11]
        logEntry['timestamp'] = parseDateTime(logStr[12] + logStr[13] +
                                              logStr[14] + logStr[15] +
                                              logStr[16] + logStr[17] +
                                              logStr[18] + logStr[19])
        #logEntry['date'] = '{:%Y-%m-%d, %a}'.format(logEntry['timestamp'])
        #logEntry['time'] = '{:%H:%M:%S}'.format(logEntry['timestamp'])

        logEntryList.append(logEntry)
        index += 1

    return logEntryList
Exemple #2
0
    def __del__(self):
        '''
        Destructor
        
        Makes sure that connection was closed before object is deleted
        '''
        if self.connection.isOpen:
            self.connection.close()

        if not self.connection.isOpen():
            Config.getLogger().info("Connection closed successfully")
Exemple #3
0
    def resetConnection(self):

        connCheckIterations = 2048
        i = 0

        Config.getLogger().debug("Performing Serial-over-TCP connection reset")

        self.connection.close()

        if self.connection.isOpen:
            Config.getLogger().error("Unable to close connection to " +
                                     self.connString)

        self.connection.open()

        while (i < connCheckIterations):
            if self.connection.isOpen:
                Config.getLogger().debug("Connection became ready after " +
                                         str(i) + " iterations")
                break
            i += 1

        if not self.connection.isOpen:
            Config.getLogger().error("Unable to open connection to " +
                                     self.connString)
Exemple #4
0
    def sendRequest(self, requestString, chunkSize=1):
        '''
        Send raw text to serial port
        '''

        Config.getLogger().debug("Port opened. Sending request '" +
                                 requestString + "'")
        self.resetConnection()
        self.connection.write(requestString)

        resp = ""
        msg = ""
        index = 0
        eoc_index = 1

        Config.getLogger().debug("Reading port output")
        while (index < self.read_limit):
            msg = self.connection.read(chunkSize)
            # Config.getLogger().debug("Got chunk [" + str(index) + "]: " + msg)
            resp += msg
            if msg == "&":
                # Config.getLogger().debug("Got symbol & as a chunk for " + str(eoc_index) + " time!")
                if eoc_index >= self.cmd_EoC_count:
                    break
                eoc_index += 1
            index += 1

        Config.getLogger().debug("Got response: " + resp)
        if self.read_limit - 1 == index:
            Config.getLogger().warning("Read length was reached (" +
                                       self.read_limit + ")")

        return resp
Exemple #5
0
def getEventTypeByCode(eventTypeCode):

    eventTypesFile = open(Config.getCodeTableEventTypes())

    eventTypesJSON = json.load(eventTypesFile)

    return eventTypesJSON[str(eventTypeCode)]
Exemple #6
0
def getTotalEventsCount(connection):

    global eventCommandPath

    Commands.loadCommandsFromFile()

    logCommandJSON = Commands.getCommandJSON(eventCommandPath)

    recvString = connection.sendCommand(str(logCommandJSON['command'] + "000"))
    memAddrStr = recvString[len(recvString) - 3:]
    memAddr = int(memAddrStr, 16)

    Config.getLogger().debug("Got memAddrStr as [0x" + memAddrStr + "] or [" +
                             str(memAddr) + "]")

    return memAddr
Exemple #7
0
def getSensorTypeByCode(sensorCode):

    sensorTypeFile = open(Config.getCodeTableSensorCode())

    sensorTypesJSON = json.load(sensorTypeFile)

    return sensorTypesJSON[str(sensorCode)]
Exemple #8
0
    def extractResponse(self, lsSerialResponse):
        '''
        Extract the response message from raw LS30 serial response
        '''

        message = ""

        try:
            message = lsSerialResponse[
                lsSerialResponse.index(self.cmd_prefix) +
                1:lsSerialResponse.index(self.cmd_suffix)]
        except ValueError:
            Config.getLogger().error(
                "Unable to extract command from response [" +
                lsSerialResponse + "]")

        return message
Exemple #9
0
def getWEBTemlate(templateFile):

    templateFilePath = Config.getWEBTemplatesDir() + "/" + templateFile
    templateContent = ""

    if not os.path.isfile(templateFilePath):
        raise ValueError("Template %s not found in directory %s" %
                         (templateFile, Config.getWEBTemplatesDir()))

    try:
        templateFile = open(templateFilePath)
        templateContent = templateFile.read()

    except:
        print "Unable to read file contents from file " + templateFilePath

    return templateContent
Exemple #10
0
def getCommandJSON(commandPath):
    global commandsDataJSON
    global isJSONLoaded

    commandJSON = commandsDataJSON

    if not isJSONLoaded:
        Config.getLogger().warning("JSON command data were not loaded!")
        return commandJSON

    print "Looking for JSON object in commands file by search path [" + commandPath + "]"

    jsonIndex = ""

    while (True):

        try:
            # get the value until first found dot
            jsonIndex = commandPath[:commandPath.index(".")]
            if jsonIndex == "":
                break
            # remove everything until including first found dot
            commandPath = commandPath[commandPath.index(".") + 1:]
        except ValueError:
            jsonIndex = commandPath

        print "[DEBUG] First index is " + jsonIndex

        if isinstance(commandJSON, list):
            print "[DEBUG] So, we have a list here..."
            for command in commandJSON:
                if command['id'] == jsonIndex:
                    print "[DEBUG] Found list entry " + jsonIndex
                    commandJSON = command
                    break
        else:
            commandJSON = commandJSON[jsonIndex]

        print "[DEBUG] JSON Object under index " + jsonIndex + " is:"
        pprint(commandJSON)

        if jsonIndex == commandPath:
            break

    return commandJSON
Exemple #11
0
    def __init__(self, connectionString=""):
        '''
        Constructor.
        
        Opens connection to the remote serial-to-TCP port specified by connectionString
        '''
        if connectionString != "":
            self.connString = connectionString
        else:
            self.connString = Config.getLS30ConnectionString()

        Config.getLogger().info("Opening serial connection to " +
                                self.connString)
        self.connection = serial_for_url(self.connString)

        if not self.connection.isOpen():
            raise SerialException()

        Config.getLogger().info("Connection to " + self.connString +
                                " established")
Exemple #12
0
def loadCommandsFromFile(commandsJSONFile=""):

    global commandsDataJSON
    global isJSONLoaded

    if commandsJSONFile == "":
        commandsJSONFile = Config.getCommandsConfig()

    commandsData = open(commandsJSONFile)

    commandsDataJSON = json.load(commandsData)

    isJSONLoaded = True

    commandsData.close()
Exemple #13
0
def hex2_encoded(n):

    hex_str = hex2(n)

    hexCodesFile = open(Config.getCodeTableHex())
    hexCodesJSON = json.load(hexCodesFile)

    new_hex_str = ""

    for hex_chr in hex_str:
        if str(hex_chr) != 'x':
            new_hex_chr = hexCodesJSON[str(hex_chr)]
        else:
            new_hex_chr = hex_chr
        new_hex_str += str(new_hex_chr)

    return new_hex_str
Exemple #14
0
from bottle import Bottle, run, SimpleTemplate, static_file, redirect, error

from LS30Connector import ReqRsnp
from LS30Util import Commands, Config
from LS30Web import Util
from LS30Data import DeviceLog, DeviceStatus, CodeTable

import pprint
from pprint import pformat

webHost = "0.0.0.0"
webPort = 8080

# connString  = "socket://192.168.1.220:1681"
connString = Config.getLS30ConnectionString()

app = Bottle()
isInitialized = False

reqRsnp = None


def init(host="localhost", port=8080):
    global webHost, webPort, isInitialized
    webHost = host
    webPort = port
    isInitialized = True


def start():
Exemple #15
0
def getSensorGroupConfig():

    groupConfigFile = open(Config.getSensorGroupConfig())

    return json.load(groupConfigFile)
Exemple #16
0
#!/usr/bin/python
# encoding: utf-8
'''
Created on Feb 6, 2015

@author: rpavlyuk
'''
import sys
import os

dirBase = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.insert(0, dirBase)

from LS30Web import LSWebUI
from LS30Util import Config

Config.setBaseDir(dirBase)
Config.configure()

if __name__ == '__main__':
    LSWebUI.start()
Exemple #17
0
def getHelpString(label):
    fileName = Config.getStringsFileHelp()
    return getString(fileName, label)
Exemple #18
0
def getDeviceStatus(connection, deviceGroup = 0, countStart = 0):
    
    deviceLimit = 256
    
    listDevices = [ ]
    listDevicesStr = [ ]
    
    recvString = ""
    
    sGroup = None
    
    Config.getLogger().debug("Getting device group information")
    deviceGroup = int(deviceGroup)    
    deviceGroups = CodeTable.getSensorGroupConfig() 
    
    Config.getLogger().debug("Loaded device groups:\n %s", pformat(deviceGroups))
    
    if int(deviceGroup) < len(deviceGroups['sensorGroups']):    
        for sensorGroup in deviceGroups['sensorGroups']:
            if sensorGroup['id'] == deviceGroup:
                sGroup = sensorGroup
                break
        
        if not sGroup:
            raise ValueError("Incorrect deviceGroup variable provided")
    else:
        # it means that we are going to get all devices.
        # We will use recursion for this purpose
        
        Config.getLogger().info("Getting all devices by iterating over sensor groups")
        
        countStart = 1
        
        for sensorGroup in deviceGroups['sensorGroups']:
            
            Config.getLogger().debug("Got sensor group: " + pformat(sensorGroup))
            
            deviceGroupList = getDeviceStatus(connection, int(sensorGroup['id']), countStart-1)
            countStart += len(deviceGroupList)
            
            listDevices.extend(deviceGroupList)
            
        return listDevices
            
            
    
    count = 0
    
    Commands.loadCommandsFromFile()
    deviceCommandJSON = Commands.getCommandJSON(sGroup['command'])
    
    while (count < deviceLimit):
        cmd = deviceCommandJSON['command'] + "?" + Common.hex2_encoded(count)[2:]
        Config.getLogger().debug("Sending device status command " + str(cmd) + " for device #" + str(count))
        recvString = connection.sendCommand(str(cmd))
        
        if (recvString[2]+recvString[3] == "00"):
            break
        
        if (recvString == deviceCommandJSON['command'] + "no"):
            break
        
        listDevicesStr.append(recvString[2:])
        count += 1
    
    Config.getLogger().debug("List of event strings:\n %s", pformat(listDevicesStr))
    
    index = countStart
    
    for deviceString in listDevicesStr:
        
        device = makeDeviceEntry(index+1)
        
        device['zone'] = deviceString[14] + deviceString[15] + "-" + deviceString[16] + deviceString[17]
        device['sensorType'] = CodeTable.getSensorTypeByCode(deviceString[0] + deviceString[1])
        device['sensorId'] = deviceString[2] + deviceString[3] + deviceString[4] + deviceString[5] + deviceString[6]
        device['ma'] = deviceString[8] + deviceString[9]
        device['dc'] = deviceString[10] + deviceString[11]
        device['es'] = deviceString[18] + deviceString[19] + deviceString[20] + deviceString[21]
        device['x10'] = deviceString[22] + deviceString[23] + deviceString[24] + deviceString[25]
        device['cs'] = deviceString[26] + deviceString[27]
        device['dt'] = deviceString[28] + deviceString[29]
        
        if (len(deviceString) > 30):
            device['cd'] = str(0 - (255 - int(deviceString[30] + deviceString[31],16) + 1))
            if device['cd'] == "-128":
                device['cd'] = ""
            device['hl'] = str(0 - (255 - int(deviceString[32] + deviceString[33],16) + 1))
            if device['hl'] == "-128":
                device['hl'] = ""
            device['ll'] = str(0 - (255 - int(deviceString[34] + deviceString[35],16) + 1))
            if device['ll'] == "-128":
                device['ll'] = ""
            device['ss'] = deviceString[36] + deviceString[37]
            
        
        listDevices.append(device)
        index += 1
        
        
    
    
    
    return listDevices
Exemple #19
0
def static(path):
    return static_file(path, root=Config.getWEBStaticContentDir())