Exemple #1
0
 def setUp(self):
     self.config = ConfigParser.ConfigParser()
     self.config.read(MID_CONFIG_LOC)
     self.hubCon = hubComm.HubComm(
         serialPath=self.config.get("MID", "hub_serial"))
     # start simulator
     self.startSimulator()
Exemple #2
0
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
import hubComm
import hubPackets
import sys

if __name__ == "__main__":
    hubCon = hubComm.HubComm(serialPath="/dev/ttyAMA0")
    port = int(raw_input("port #: "))
    channel = int(raw_input("channel #: "))
    address = int(raw_input("address: "))
    addressList = []
    # get addresses until we get the NULL address
    print "getting addresses..."
    tmpAddressList = []
    resetCmd = hubPackets.MultiTResetCmd(port, [address])
    hubCon.processCommand(resetCmd)
    while True:
        addrCmd = hubPackets.MultiTAddrCmd(0, channel, port, [address])
        hubCon.processCommand(addrCmd)
        if addrCmd.addrs[0] == 18446744073709551615L:
            break
        tmpAddressList += [addrCmd.addrs[0]]
Exemple #3
0
    # numReads = int(sys.argv[2])
    # ports=(1,2,3,4,5,6)

    #
    # get list of units, in chain order, from the supplied file path supplied
    #
    # open it and get the list of units
    infile_fh = open(infilePath)
    units = rt.parseInfile(infile_fh)
    infile_fh.close()
    print units
    #
    # create connection to hub
    #
    if ("hub_serial" in zip(*config.items('MID'))[0]):
        hubCon = hubComm.HubComm(serialPath=config.get("MID", "HUB_SERIAL"))
    else:
        hubCon = hubComm.HubComm(config.get("MID", "MID_IP"),
                                 config.getint("MID", "MID_PORT"),
                                 config.get("MID", "HUB_IP"),
                                 config.getint("MID", "HUB_PORT"))
    #
    # for each unit, create a T/RH command for each time we should read from it
    # then, shuffle the list
    # finally, reduce to the ports specified in cmd line
    # TODO: only does SHT for now. fix this.
    # TODO: only do one type of sensor for each unit?
    #
    hubCmds = []
    for unit in units[rt.SHT]:
        for nR in range(numReads):
Exemple #4
0
    def run(self):

        try:

            lastWWWcfgDateTime = None
            lastReadingDateTime = None
            lastUploadDateTime = None
            errorState = False
            log_level = logging.INFO

            # load configuration
            config = ConfigParser.ConfigParser()
            config.read(CONFIG_LOC)

            # setup logging
            if config.get("MID", "log_level") == "DEBUG":
                log_level = logging.DEBUG
            if config.get("MID", "log_level") == "INFO":
                log_level = logging.INFO
            elif config.get("MID", "log_level") == "WARNING":
                log_level = logging.WARNING
            elif config.get("MID", "log_level") == "ERROR":
                log_level = logging.ERROR
            logging.basicConfig(filename='./MID.log',
                                level=log_level,
                                format='%(asctime)s %(message)s')

            # read last WWW configuration saved to disk
            try:
                WWWcfg = readLatestWWWcfg()
            except:
                logging.warning("No WWW config found at " +
                                LAST_WWW_CONFIG_LOC + ".")

            # establish sensor hub connection
            try:
                if ("hub_serial" in zip(*config.items('MID'))[0]):
                    hubCon = hubComm.HubComm(
                        serialPath=config.get("MID", "HUB_SERIAL"))
                else:
                    hubCon = hubComm.HubComm(config.get("MID", "MID_IP"),
                                             config.getint("MID", "MID_PORT"),
                                             config.get("MID", "HUB_IP"),
                                             config.getint("MID", "HUB_PORT"))
            except Exception as e:
                logging.critical(
                    "Unable to establish communication with MID.  Sofware will probably stop now."
                )
                logging.critical(str(e))
                raise

            # establish WWW connection
            WWWcon = createWWWcon(config)

            #
            # THE MAIN LOOP
            #
            while (True):
                readingStartTime = datetime.datetime.now()
                #
                # reload local configuration
                #
                config.read(CONFIG_LOC)
                #
                # check shut-off flag
                #
                if not config.getboolean("MID", "turn_off"):
                    #
                    # update config from WWW
                    #
                    try:
                        newWWWcfg = WWWcon.getConfig()
                        if newWWWcfg:
                            # website config updates occured
                            WWWcfg = newWWWcfg
                            logging.debug(str(WWWcfg))
                            logging.info("WWW cfg file received.")
                            lastWWWcfgDateTime = time.time()
                            # write new cfg to file
                            try:
                                writeLatestWWWcfg(WWWcfg)
                                logging.info("Wrote WWW cfg to local file")
                            except:
                                logging.error(
                                    "Could not write latest WWW configuration to "
                                    + LAST_WWW_CONFIG_LOC + ".")
                    except:
                        logging.error(
                            "WWW configuration not received from web server.")
                    #
                    # generate and process all EA sensor unit commands
                    # that should be processed
                    #
                    # buid commands from JSON
                    allCmds = []
                    try:
                        logging.info(
                            "Creating commands from JSON received from WWW.")
                        allCmds = hubComm.allCmdsFromJSON(WWWcfg)
                    except Exception as e:
                        logging.error(
                            "Error occured while creating commands: " + str(e))
                    # process commands and record errors
                    allErrs = []  # storage place for all errors
                    for cmdi, cmd in enumerate(allCmds):
                        try:
                            logging.info("Processing command " +
                                         str(cmdi + 1) + " of " +
                                         str(len(allCmds)) + "...")
                            allErrs += [hubCon.processCommand(cmd)]
                        except hubComm.BadHubReplyError:
                            logging.warning(
                                "Bad hub reply, reporting error to WWW for all sensors in cmd."
                            )
                            # report error for all sensor IDs, will be the only one reported
                            allErrs += [hubPackets.HubErrorResponse()]
                            allErrs[-1].addParseErrors(cmd.getSensorIDs())
                            # clean up communications
                            hubCon.clearComm()
                        except hubPackets.HubTimeoutError:
                            logging.warning(
                                "Timed out waiting for hub reply, reporting error to WWW for all sensors in cmd."
                            )
                            # report error for all sensor IDs, it will be the only one reported
                            allErrs += [hubPackets.HubErrorResponse()]
                            allErrs[-1].addTimeoutError(cmd.getSensorIDs())
                            # clean up communications
                            hubCon.clearComm()
                        # log command
                        # logging.debug(str(cmd))

                    #
                    # create and process commands for Ethernet devices
                    #
                    successfulEthCmds = processEthCommands(
                        WWWcfg, config, WWWcon)
                    allCmds += successfulEthCmds
                    #
                    # create and process read commands for RS485 devices
                    #
                    # TODO: FIX THIS!!!
                    successfulRS485Cmds = processRS485Commands(
                        WWWcfg, config, WWWcon)
                    allCmds += successfulRS485Cmds
                    #
                    # handle the special case AB EtherNet/IP hack
                    #
                    try:
                        logging.info("Attempting the A-B VFD hack.")
                        AB_VFDs = VFDinterface.ABinterfaceFactory(WWWcfg)
                        for i in AB_VFDs:
                            i.update()
                        allCmds.extend(AB_VFDs)
                    except Exception as e:
                        logging.error(
                            "Error occured while reading the AB VFD parameters:"
                            + str(e))

                    try:
                        dmcmds = DMMCCmd.processDMMCCommands(
                            WWWcfg["commandInfo"])
                        allCmds += dmcmds
                        logging.info('Read from DryerMaster: ' +
                                     str(len(dmcmds)))
                    except Exception as e:
                        logging.error(
                            "Error occured while trying to read the Dryer Master's MC: "
                        )
                        logging.exception(e)

                    lastReadingDateTime = time.time()
                    #
                    # send data to WWW
                    #
                    try:
                        midPasswd = config.get("MID", "MIDpassword")
                        WWWcon.uploadReading(midPasswd,
                                             datetime.datetime.now(pytz.utc),
                                             allCmds, allErrs)
                        logging.info("SUCCESSFULLY UPLOADED DATA")
                        lastUploadDateTime = time.time()
                        if errorState:
                            try:
                                # send all readings stored in backup file
                                postStoredData(WWWcon)
                                logging.info(
                                    "SUCCESSFULLY UPLOADED STORED DATA")
                                # purge data backup file
                                purgeStoredData()
                                # indicate error state is over
                                errorState = False
                            except Exception as e:
                                logging.critical(
                                    "An error occured while trying to upload data from error state: "
                                    + str(e))
                    except Exception as e:
                        logging.error(
                            "Error occured while uploading results to server: "
                            + str(e))
                        # indicate MID is cut off from WWW server
                        errorState = True
                        # save latest reading to backup file
                        try:
                            storeReading(allCmds, DATA_BACKUP_LOC)
                        except:
                            logging.error(
                                "Cannot write to backup data location.")
                        # re-instantiate WWW
                        WWWcon = createWWWcon(config)
                    # TODO:send errors to WWW
                    lastRun = time.time()
                    # store raw data if instructed to do so
                    if config.getboolean("MID", "STORE_RAW_DATA_MODE"):
                        storeReading(allCmds,
                                     config.get("MID", "RAW_DATA_LOC"))
                else:
                    logging.info("Turn off flag set to TRUE")
                # END BLOCK FOR TURN-OFF FLAG CHECK
                # space readings out some minimum amount of time
                min_interval = config.getint("MID",
                                             "min_reading_interval_seconds")
                readingDuration = datetime.datetime.now() - readingStartTime
                if readingDuration.seconds < min_interval:
                    logging.info("taking a break for " +
                                 str(min_interval - readingDuration.seconds) +
                                 " seconds...")
                    time.sleep(min_interval - readingDuration.seconds)
                else:
                    logging.error(
                        "Unable to keep up with requested reading interval.  Last reading took "
                        + str(readingDuration.seconds) + " > " +
                        str(min_interval) + ".")
                    # TODO: log that we are unable to meet the desired reading interval
        except Exception as e:
            logging.critical("shit! " + str(e))
            logging.critical(traceback.format_exc())