コード例 #1
0
ファイル: ota.py プロジェクト: kostaman/pycom-libraries
    def __init__(self, lora):
        self.lora = lora
        self.is_updating = False
        self.version_file = '/flash/OTA_INFO.py'
        self.update_version = '0.0.0'
        self.update_time = -1
        self.resp_received = False
        self.update_in_progress = False
        self.operation_timeout = 10
        self.max_send = 5
        self.listen_before_sec = uos.urandom(1)[0] % 180
        self.updates_check_period = 6 * 3600

        self.mcAddr = None
        self.mcNwkSKey = None
        self.mcAppSKey = None

        self.patch = ''
        self.file_to_patch = None
        self.patch_list = dict()
        self.checksum_failure = False
        self.device_mainfest = None

        self._exit = False
        _thread.start_new_thread(self._thread_proc, ())

        self.inactivity_timeout = 120
        self.wdt = Watchdog()

        self.lora.init(self.process_message)
コード例 #2
0
def main(args):
    """
    Read args passed to script, load tokens and run watchdog.

    Keyword arguments:
    :param args:    arguments parsed by argparse ArgumentParser

    :return:        returns status code 0 on successful completion

    """
    jenkins_server = args.jenkins_server.strip()
    jenkins_user = args.jenkins_user.strip()
    jenkins_token = open(args.jenkins_token).read().replace('\n', '').strip()
    msteams_url = open(args.msteams_url).read().replace('\n', '').strip()
    github_credentials = args.github_credentials
    github_org = args.github_org
    github_project = args.github_project
    ci_job = args.ci_job.strip()
    watchdog_job = args.watchdog_job.strip()
    quiet = args.quiet

    wd = Watchdog(jenkins_token=jenkins_token,
                  jenkins_server=jenkins_server,
                  jenkins_user=jenkins_user,
                  github_credentials=github_credentials,
                  git_org=github_org,
                  git_project=github_project,
                  msteams_url=msteams_url,
                  ci_job_name=ci_job,
                  watchdog_job_name=watchdog_job)
    wd.run(quiet=quiet)

    return 0
コード例 #3
0
ファイル: scrape_script.py プロジェクト: alexsieusahai/Jobbie
def scrape():
    scraper = LinkedinScraper()
    scraper.login(os.environ['LINKEDIN_USER'], os.environ['LINKEDIN_PW'])
    gatherer = Gatherer(scraper)
    watchdog = Watchdog(gatherer)

    job_list = [
        'data intern', 'machine learning intern', 'software intern',
        'python intern'
    ]

    location_list = [
        'Vancouver',
        'New York',
        'San Francisco Bay Area',
        'Toronto',
    ]

    for job in job_list:
        for location in location_list:
            print('gathering for', job, location)
            watchdog.monitor_gather(job, location)

    for job in job_list:
        print('gathering for', job, 'Worldwide')
        watchdog.monitor_gather(job, 'Worldwide')

    return 'Done'
コード例 #4
0
def start_watchdog(update, context):
    job_queue = context.job_queue
    query = context.user_data['query']
    chat = update.effective_chat

    w = Watchdog(query, chat)
    w.start_job(job_queue)
    context.user_data['watchdogs'].append(w)
    return
コード例 #5
0
 def build(self):
     # Build this app!
     try:
         os.remove('status.oracle')  # remove oracle status file...
     except:
         pass
     self.patients = db.all('patients')
     self.watchdog = Watchdog(['status.oracle'])
     self.watchdog.events.on_change += self.update_status
     signal.signal(signal.SIGINT, self.kill_threads)
コード例 #6
0
 def __init__(self):
     super(iAltar, self).__init__()
     self.name = "iAltarPlayer"
     print("starting: %s" % self.name)
     self.searchType = Specs().s['defaultSearchType']
     print("%s: default search type: %s" % (self.name, self.searchType))
     Watchdog().add(self)
     if Hosts().getLocalAttr("hasServer"):
         Server().register({'Search': self.setSearchType})
     self.queue = Queue.Queue()
コード例 #7
0
def main():

    import sys
    sys.modules.clear()

    from button_handler import Button
    from pins import Pins

    # Init device button IRQ:
    Pins.button_pin.irq(Button().irq_handler)

    from context import Context

    context = Context()

    import wifi
    wifi.init(context)
    del sys.modules['wifi']

    _RTC_KEY_RUN = 'run'
    _RUN_WEB_SERVER = 'web-server'
    _RUN_SOFT_OTA = 'soft-ota'

    from rtc import get_rtc_value
    if get_rtc_value(_RTC_KEY_RUN) == _RUN_WEB_SERVER:
        print('start webserver')

        from rtc import update_rtc_dict
        update_rtc_dict(data={_RTC_KEY_RUN:
                              _RUN_SOFT_OTA})  # run OTA client on next boot

        del update_rtc_dict
        del get_rtc_value
        del sys.modules['rtc']

        # init Watchdog timer
        from watchdog import Watchdog
        context.watchdog = Watchdog(context)

        from webswitch import WebServer

        WebServer(context=context, version=__version__).run()
    else:
        print('start "soft" OTA')
        Pins.power_led.off()
        from rtc import update_rtc_dict
        update_rtc_dict(data={_RTC_KEY_RUN:
                              _RUN_WEB_SERVER})  # run web server on next boot
        from ota_client import SoftOtaUpdate

        SoftOtaUpdate().run()

    from reset import ResetDevice
    ResetDevice(reason='unknown').reset()
コード例 #8
0
ファイル: imageHandler.py プロジェクト: sibosop/sibcommon
    def run(self):
        print("%s starting" % self.name)
        afiles = []
        (minTime, maxTime) = Specs().s["displayTimeRange"]
        lastImageDir = ""
        imageIndex = 0
        splash = Specs().s['splashImg']
        print("displaying f:%s" % splash)
        Display().image(splash)
        ts = None
        while True:
            Watchdog().feed(self)
            try:
                path = self.queue.get(timeout=ts)
            except Queue.Empty:
                path = lastImageDir

            if path == "__stop__":
                print("%s is stopping" % self.name)
                break

            print("%s: path %s lastImageDir %s" %
                  (self.name, path, lastImageDir))
            if path != lastImageDir:
                print("%s reseting imageIndex" % self.name)
                imageIndex = 0
                lastImageDir = path
                if len(afiles) == 0:
                    print("empty image file. waiting")
                    ts = 1
                    continue
            afiles = glob.glob(path + "/*.jpg")
            numFiles = len(afiles)
            if numFiles == 0:
                print("%s directory empty!!" % self.name)
                print("displaying f:%s" % splash)
                Display().image(splash)
                ts = 1
                continue
            print("imageIndex %d len afiles %d" % (imageIndex, numFiles))
            if imageIndex >= numFiles:
                print("resetting imageIndex")
                imageIndex = 0
            f = afiles[imageIndex]
            imageIndex += 1
            print("displaying f:%s" % f)
            if Display().image(f) == False:
                print "skipping bad images:%s" % f
                ts = .1
                continue
            ts = (random.random() * (maxTime - minTime)) + minTime
            print("next display %f" % ts)
コード例 #9
0
    async def listen(self, channels: list[str], callbacks: dict[str,
                                                                Callable]):
        self.__watchdog = Watchdog(HEARTBEAT_TIMEOUT)
        self.__invoke_lock = asyncio.Lock()
        await self.__connect()
        if self.api_key is not None:
            await self.__auth()

        assert 'heartbeat' not in channels
        channels.append('heartbeat')
        callbacks['heartbeat'] = self.__on_heartbeat
        await self.__subscribe(channels, callbacks)
        await self.__watchdog.loop()
        self.__connection.close()
コード例 #10
0
ファイル: imageHandler.py プロジェクト: sibosop/sibcommon
 def __init__(self):
     super(ImageHandler, self).__init__()
     self.name = "ImageHandler"
     print("starting: %s" % self.name)
     Watchdog().add(self)
     self.currentId = None
     self.queue = Queue.Queue()
     if Hosts().getLocalAttr('hasServer'):
         Server().register({
             'AddImage': self.addImage,
             'RmCacheDir': self.rmCacheDir,
             'SetImageDir': self.setImageDir,
             'ClearCache': self.clearCache
         })
コード例 #11
0
    def __init__(self, args):
        """
        1. Bootstrap dependencies
            a. test gps
            b. check for SDR
        2. Start srsue with config file
            a. watch srsue for crashes and restart
        3. Start watchdog daemon
        4. Start web daemon
        """
        self.threads = []
        self.subprocs = []
        self.debug = args.debug
        self.disable_gps = args.disable_gps
        self.disable_wigle = args.disable_wigle
        self.web_only = args.web_only
        self.config_fp = 'config.ini'
        self.config = args.config = configparser.ConfigParser()
        self.config.read(self.config_fp)
        self.earfcn_list = []
        signal.signal(signal.SIGINT, self.signal_handler)
        signal.signal(signal.SIGTERM, self.signal_handler)

        if args.project_name:
            self.project_name = args.project_name
        else:
            self.project_name = self.config['general']['default_project']
            args.project_name = self.config['general']['default_project']

        if self.project_name not in self.config:
            self.config[self.project_name] = {}

        # GPSD settings
        self.gpsd_args = {
            'host': self.config['gpsd']['host'],
            'port': int(self.config['gpsd']['port'])
        }

        # Set up logging
        self.logger = args.logger = verboselogs.VerboseLogger(
            "crocodile-hunter")
        fmt = f"\b * %(asctime)s {self.project_name} - %(levelname)s %(message)s"
        if (self.debug):
            log_level = "DEBUG"
        else:
            log_level = "VERBOSE"
        coloredlogs.install(level=log_level, fmt=fmt, datefmt='%H:%M:%S')

        self.watchdog = Watchdog(args)
コード例 #12
0
def main():

    log.info('starting ' + c.DRIVER_NAME)

    tty = parse_cmdline_args()
    sensor = ImtSiRs485Sensor(tty)

    hw_ver, fw_ver = sensor.identify()

    # add hw and fw version to the signals, they are mandatory
    signals = c.SIGNALS + [
        DbusSignal('/HardwareVersion', hw_ver),
        DbusSignal('/FirmwareVersion', fw_ver)
    ]

    service_name = c.SERVICE_NAME + '.' + tty
    watchdog_timeout = (c.UPDATE_INTERVAL + c.SERIAL_TIMEOUT) * 2

    # starting watchdog here, because with VeDbusServiceAsync we are going multi-threaded
    with Watchdog(watchdog_timeout) as watchdog, VeDbusServiceAsync(
            service_name, signals) as dbus:

        settings_for_tty = get_settings_for_tty(tty)
        settings = SettingsDevice(dbus.dbusconn, settings_for_tty, None)
        _is_subsensor_present = partial(is_subsensor_present, settings)

        # only the modbus signals are updated, the others are const
        modbus_signals = [s for s in signals if isinstance(s, ModbusSignal)]

        while True:

            watchdog.alive()  # signal the watchdog that we are still alive

            registers = sensor.read_modbus_registers()

            for s in modbus_signals:
                value = registers[s.reg_no]
                if s.signed and value & 0x8000:
                    value -= 0x10000
                value *= s.gain

                if _is_subsensor_present(s.dbus_path, value):
                    dbus[s.dbus_path] = value
                else:
                    dbus[s.dbus_path] = None

            log.debug('iteration completed, sleeping for ' +
                      str(c.UPDATE_INTERVAL) + ' seconds')
            sleep(c.UPDATE_INTERVAL)
コード例 #13
0
    def __init__(self):

        # Connect to the Gazepoint tracker.
        self.gp = GazePoint()

        # Establish an event bus.
        self.events = Events()

        # Set up the watchdog...
        try:
            os.remove('request.oracle')
        except:
            pass
        target_files = ['request.oracle']
        self.watchdog = Watchdog(target_files)
        self.watchdog.events.on_change += self.scan
コード例 #14
0
    def __init__(self):

        # Set up socket connections/event bus.
        self.events = Events()

        # Boot up datastore/etc.
        self.valid_keys = ['t', 't_sys', 'v', 'filtered']
        self.datastore = DataStore()
        self.session_id = None
        self.is_recording = False
        self.is_broadcasting = True
        self.counter = 0

        # Configure filtering.
        self.allowed_channels = [0, 1]
        self.freq_cutoff = 10
        self.filter_order = 6
        self.downsample_rate = 32
        self.zi = {}
        self.channel_data = {}
        self.buffers_to_watch = []
        for chn in self.allowed_channels:
            self.zi[chn] = np.zeros(self.filter_order)
            self.channel_data[chn] = []
            self.buffers_to_watch.append('buffer-{:02d}.dat'.format(chn))
        self.buffers_to_watch.append('oracle_status.dat')

        # Listen for buffer changes:
        self.watchdog = Watchdog(self.buffers_to_watch)

        # Set up threading to handle i/o in background.
        self.q = Queue()
        nb_workers = 1
        target = self.data_received
        for _ in range(nb_workers):
            worker = Thread(target=target, args=(self.q, ), daemon=True)
            worker.start()

        # Listen for data from the server.
        self.watchdog.events.on_change += self.push_to_queue
        self.last_time = time()
コード例 #15
0
    def __init__(self, start_bg_thread=True):
        self.dbc = pymongo.MongoClient()

        self.registration_col1 = self.dbc.db.registration_col1
        self.ranking = self.dbc.db.ranking
        self.config_col = self.dbc.db.config
        self.raw_data = self.dbc.db.raw_data
        self.snapshots_col_rooms = self.dbc.db.snapshots_col_rooms
        self.snapshots_col_appliances = self.dbc.db.snapshots_col_appliances
        self.DRL_recommendations = self.dbc.db.DRL_recommendations
        self.snapshots_col_users = self.dbc.db.snapshots_col_users
        self.web_registration = self.dbc.db.web_registration
        self.web_comfort_feedback = self.dbc.db.web_comfort_feedback
        self.web_rec_feedback = self.dbc.db.web_rec_feedback

        self.snapshots_parameters = self.dbc.db.snapshots_parameters
        self._latestSuccessShot = 0

        self._ReadConfigs()
        self.watchdog = Watchdog(self.WATCHDOG_TIMEOUT_USER,
                                 self.WATCHDOG_TIMEOUT_APPLIANCE)
        ## Data Structure Init: bipartite graph between rooms and appls
        ## TODO: Add a web interface to update config in db, and pull new config into memory.

        self._ConstructInMemoryGraph()
        ## Construct bipartite graph.
        # self._accumulator()
        #self._GracefulReloadGraph()
        ## Read appliance values from database; TODO: occupants location
        #self._HardcodeValues()

        # self.watchdogInit()

        self.recommender = recommenderSystem()
        if start_bg_thread:
            self.startDaemon()

        self.snapshots_col_rooms = self.dbc.db.snapshots_col_rooms
        self.snapshots_col_appliances = self.dbc.db.snapshots_col_appliances
        self.snapshots_col_users = self.dbc.db.snapshots_col_users
コード例 #16
0
    def run(self):
        self.logger.debug("run")
        telemetry = {}
        telemCoef = {
            'SatCount': 1,
            'outside_temp': 10,
            'inside_temp': 10,
            'barometer': 1,
            'battery': 100
        }
        exitFlag = False
        self.prev_gps_status = ""
        while not exitFlag:
            try:
                # blink
                self.ledState = 1 - self.ledState
                GPIO.output(self.config['pins']['LED1'], GPIO.HIGH)
                watchdog = Watchdog(60)

                # gps
                self.gps.loop()
                gpsdata = self.gps.get_data()
                self.calc_balloon_state(gpsdata)
                if gpsdata['status'] == "fix" and gpsdata['alt'] > 0:
                    self.sensors.calibrate_alt(gpsdata['alt'])
                if gpsdata['status'] != "fix":
                    gpsdata['alt'] = self.sensors.read_pressure()

                # sensors
                sensordata = self.sensors.get_data()
                sensordata.update(self.cam.status)
                status_bits = self.calc_status_bits(gpsdata, sensordata)
                telemetry[
                    'Satellites'] = gpsdata['SatCount'] * telemCoef['SatCount']
                telemetry['outside_temp'] = sensordata[
                    'outside_temp'] * telemCoef['outside_temp']
                telemetry['inside_temp'] = sensordata[
                    'inside_temp'] * telemCoef['inside_temp']
                telemetry['barometer'] = sensordata['barometer'] * telemCoef[
                    'barometer']
                telemetry[
                    'battery'] = sensordata['battery'] * telemCoef['battery']

                if gpsdata['status'] != self.prev_gps_status:
                    frame = self.aprs.create_telem_data_msg(
                        telemetry, status_bits, gpsdata['alt'])
                    self.modem.encode(frame)
                    self.modem.saveToFile(
                        os.path.join(self.tmp_dir, 'aprs.wav'))
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join(self.tmp_dir, 'aprs.wav'))
                    self.prev_gps_status = gpsdata['status']

                # UI
                self.webserver.update(gpsdata, sensordata, self.state)
                self.update_system_datetime(gpsdata)

                if self.timers.expired("APRS"):
                    if gpsdata['status'] == "fix":
                        self.logger.debug("sending location")
                        frame = self.aprs.create_location_msg(
                            gpsdata, telemetry, status_bits)
                    else:
                        self.logger.debug("sending only telemetry")
                        frame = self.aprs.create_telem_data_msg(
                            telemetry, status_bits, gpsdata['alt'])
                    self.modem.encode(frame)
                    self.modem.saveToFile(
                        os.path.join(self.tmp_dir, 'aprs.wav'))
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join(self.tmp_dir, 'aprs.wav'))
                    with open(os.path.join(self.tmp_dir, "flight.log"),
                              'a+') as f:
                        merged = dict()
                        merged.update(gpsdata)
                        merged.update(sensordata)
                        merged['datatime'] = datetime.datetime.now().isoformat(
                        )
                        f.write(json.dumps(merged, indent=2))
                        f.write(',\n')

                if self.timers.expired("APRS-META"):
                    frame = self.aprs.create_telem_name_msg(
                        telemetry, self.status_names)
                    self.modem.encode(frame)
                    self.modem.saveToFile(
                        os.path.join(self.tmp_dir, 'aprs.wav'))
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join(self.tmp_dir, 'aprs.wav'))

                    frame = self.aprs.create_telem_eqns_msg(telemCoef)
                    self.modem.encode(frame)
                    self.modem.saveToFile(
                        os.path.join(self.tmp_dir, 'coef.wav'))
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join(self.tmp_dir, 'coef.wav'))

                if self.timers.expired("Capture"):
                    self.capture_image()

                if self.timers.expired("Snapshot"):
                    self.imaging_counter += 1
                    cam_select = self.imaging_counter % CAMERAS
                    self.capture_image(archive=False)
                    self.prep_image(cam_select, gpsdata, sensordata)
                    self.webserver.snapshot()

                if self.timers.expired("Imaging"):
                    self.imaging_counter += 1
                    cam_select = self.imaging_counter % CAMERAS
                    cam_system = self.imaging_counter % (CAMERAS + 1)
                    self.logger.info("imageing trigger")
                    self.logger.debug("cam %s system %s" %
                                      (cam_select, cam_system))
                    self.capture_image(archive=False)
                    self.prep_image(cam_select, gpsdata, sensordata)
                    self.webserver.snapshot()
                    if cam_system == 0:
                        self.logger.info("->sstv")
                        _thread.start_new_thread(self.process_sstv, ())
                    else:
                        self.logger.info("->ssdv")
                        _thread.start_new_thread(self.process_ssdv, ())

                if self.timers.expired("PLAY-SSDV"):
                    self.logger.debug("sending ssdv")
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join("data", 'starting_ssdv.wav'))
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join("data", 'habhub.wav'))
                    self.radio_queue(self.config['frequencies']['APRS'],
                                     os.path.join(self.tmp_dir, 'ssdv.wav'))

                if self.timers.expired("PLAY-SSTV"):
                    self.logger.debug("sending sstv")
                    self.radio_queue(
                        self.config['frequencies']['APRS'],
                        os.path.join("data", 'switching_to_sstv.wav'))
                    self.radio_queue(self.config['frequencies']['SSTV'],
                                     os.path.join("data", 'starting_sstv.wav'))
                    self.radio_queue(self.config['frequencies']['SSTV'],
                                     os.path.join(self.tmp_dir, 'sstv.wav'))

                if self.timers.expired("Buzzer"):
                    for i in range(3):
                        GPIO.output(self.config['pins']['BUZZER'], GPIO.HIGH)
                        time.sleep(0.5)
                        GPIO.output(self.config['pins']['BUZZER'], GPIO.LOW)
                        time.sleep(0.5)

                GPIO.output(self.config['pins']['LED1'], GPIO.LOW)
                watchdog.stop()
                time.sleep(1)

            except Watchdog:
                self.logger.error("task timedout!")
            except KeyboardInterrupt:  # If CTRL+C is pressed, exit cleanly
                exitFlag = True
                self.gps.stop()
                break
            except Exception as x:
                self.logger.exception(x)
        self.logger.info("Done.")
コード例 #17
0
import json

from miners import MINER_TYPES
from api import API
from watchdog import Watchdog

from elasticsearch import Elasticsearch

if __name__ == '__main__':
    config = json.load(open('config.json'))
    Miner = MINER_TYPES[config['miner']]

    es = Elasticsearch([config['elastic_host']])

    miner = Miner(
        config['miner_host'],
        config['miner_port'],
        config.get('miner_name', 'mstack-miner'),
    )

    push_service = Pushover(config['push_user_token'],
                            config['push_app_token'])

    Watchdog(config.get('watchdog_interval', 60), miner, es,
             push_service).start()

    API(config.get('api_port',
                   3000), config['api_username'], config['api_password'],
        config['ssl_cert'], config['ssl_key'], miner).serve()
コード例 #18
0
    def run(self):
        print("%s in run loop" % self.name)
        hosts = Hosts().getHosts()
        imageHosts = []
        phraseHosts = []
        lastCacheId = 0
        for h in hosts:
            ip = h['ip']
            if Hosts().isLocalHost(ip):
                ImageHandler.clearCache(None)
            else:
                Hosts().sendToHost(ip, {
                    'cmd': 'ClearCache',
                    'args': None
                })
            iAltar = Hosts().getAttr(ip, 'iAltar')
            if iAltar['enabled']:
                if iAltar['image']:
                    Debug().p("%s: display type for %s: image" %
                              (self.name, ip))
                    imageHosts.append(ip)
                if iAltar['phrase']:
                    Debug().p("%s: wants phrase for %s: " % (self.name, ip))
                    phraseHosts.append(ip)
        sleepTime = .001
        while True:
            try:
                Debug().p("%s: sleeping %d" % (self.name, sleepTime))
                msg = self.queue.get(timeout=sleepTime)
                if msg == "__stop__":
                    print("%s: stopping" % self.name)
                break
            except Queue.Empty:
                pass

            Watchdog().feed(self)
            cacheId = random.randint(10000, 20000)
            images = []
            choices = []
            urls = []
            if self.searchType == 'Archive':
                [images, choices] = Archive().getArchive()
                for i in images:
                    Debug().p("%s: image %s" % (self.name, i))
                for c in choices:
                    Debug().p("%s: choice %s" % (self.name, c))
            elif self.searchType == 'Google':
                choices = []
                msg = doGetRecog('')
                if msg != "":
                    test = json.loads(msg)
                    Debug().p("%s got %s" % (self.name, test))
                    if test['recog'] != ["", ""]:
                        choices = test['recog']
                        Debug().p["%s choices from recog %s" %
                                  (self.name, choices)]
                if len(choices) == 0:
                    choices = Words().getWords()
                urls = Search().getUrls(choices)
                if urls == None:
                    Debug().p("%s Google Error switching to Archive" %
                              self.name)
                    self.searchType = "Archive"
                    continue
                if len(urls) == 0:
                    Debug().p("%s Nothing found try again" % self.name)
                    continue
                images = self.urlsToImages(Search().getUrls(choices))
            else:
                Debug().p("%s unimplemented type %s switching to archive" %
                          (self.name, searchType))
                self.searchType = 'Archive'
            if self.searchType != 'Archive':
                Archive().putArchive(choices)

            phraseArgs = {}
            if len(phraseHosts) != 0:
                phraseArgs['phrase'] = choices
                phraseArgs['phraseData'] = ""
                Debug().p("%s sending %s to %s" % (self.name, choices, ip))
                for ip in phraseHosts:
                    phr = Hosts().getAttr(ip, 'phrase')
                    if phr['voice']:
                        lang = random.choice(Specs().s['langList'])
                        phraseArgs['phraseData'] = makeSpeakData(
                            "%s %s" % (choices[0], choices[1]), lang)

                #os.unlink(file.replace("mp3","wav"));

            if len(imageHosts) != 0:
                numImages = len(images)
                imagesPerHost = numImages / len(imageHosts)
                extraImages = numImages % len(imageHosts)
                extra = 0
                count = 0
                Debug().p("%s numImages:%d imagesPerHost:%d extraImages:%d" %
                          (self.name, numImages, imagesPerHost, extraImages))
                for ip in imageHosts:
                    args = {}
                    args['id'] = cacheId
                    args['imgData'] = []
                    for i in range(0, imagesPerHost):
                        fname = images[i + count]
                        args['imgData'].append(self.setImgData(fname))
                    count += imagesPerHost
                    if extra < extraImages:
                        fname = images[count + extra]
                        args['imgData'].append(self.setImgData(fname))
                        extra += 1
                    cmd = {'cmd': "AddImage", 'args': args}
                    if Hosts().isLocalHost(ip):
                        ImageHandler().addImage(args)
                    else:
                        Hosts().sendToHost(ip, cmd)

                for ip in imageHosts:
                    args = [cacheId]
                    if Hosts().isLocalHost(ip):
                        ImageHandler().setImageDir(args)
                    else:
                        Hosts().sendToHost(ip, {
                            'cmd': 'SetImageDir',
                            'args': args
                        })

                if lastCacheId != 0:
                    for ip in imageHosts:
                        args = [lastCacheId]
                        if Hosts().isLocalHost(ip):
                            ImageHandler.rmCacheDir(args)
                        else:
                            Hosts().sendToHost(ip, {
                                'cmd': 'RmCacheDir',
                                'args': args
                            })
                lastCacheId = cacheId

            if len(phraseHosts) != 0:
                for ip in phraseHosts:
                    if Hosts().isLocalHost(ip):
                        PhraseHandler().setPhrase(phraseArgs)
                    else:
                        Hosts().sendToHost(ip, {
                            'cmd': 'Phrase',
                            'args': phraseArgs
                        })

            sleepTime = Specs().s['iAltarSleepInterval']
コード例 #19
0
import time
from watchdog import Watchdog

while True:
    dog = Watchdog('watchdog.ini')
    dog.ping()
    time.sleep(10)
コード例 #20
0
if __name__ == '__main__':
    import time
    import signal
    import sys

    from watchdog import Watchdog as Watchdog
    from digital_output import DigitalOutput as DigitalOutput

    def signal_handler(sig, frame):
        myOutput.cleanup()
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    print('Ctrl+C to exit')

    with Watchdog() as watchdog:
        watchdog.enable(wait=True)
        myOutput = DigitalOutput(0)
        myOutput.enable()
        increment = 0.1
        delay = 1.0
        while True:
            if delay > 3.0 or delay < 1.0:
                increment = -increment

            if myOutput.is_on():
                watchdog.update(0)
                myOutput.off()
                state = 'off'
            elif myOutput.is_off():
                watchdog.update(1)
コード例 #21
0
    elif data['type'] == 'order':
        task['type'] = 'add_order_or_watchdog'
    elif data['type'] == 'clear_order':
        task['type'] = 'clear_order'
    elif data['type'] == 'cost':
        task['type'] = 'receive_cost'
    elif data['type'] == 'acknowledge_order':
        task['type'] = 'acknowledge_order'
    add_task(task)


#elevator.run(MY_ID, add_task)
elevator = Elevator(MY_ID, add_task)
elevator.run()
#watchdog.run(add_task)
watchdog = Watchdog(add_task)
watchdog.run()
network.run(add_task_from_message)


def order_watcher():
    global ordersAndCosts
    while True:
        current_time = int(time.time())
        popList = []
        for element in ordersAndCosts:
            if element['timestamp'] + ORDER_WATCHER_LIMIT < current_time:
                #print(f'Costs: {element}')
                if len(element['costs']) > 0:
                    lowest_cost = 1000
                    for costElement in element['costs']:
コード例 #22
0
    def recv(self, message, ref):
        action = message.get('action', None)

        if action == 'config':
            if self.manager.isrunning:
                self.debug("Reconfiguration process: Shutting down Manager",
                           color='cyan')
                self.manager.shutdown()

            # Initialize manager
            self.debug("Starting up manager", color='blue')
            self.manager.attach(
                WebServer(uuid.uuid4(), 'Local Webserver', self.__commit))
            watchdog_uuid = uuid.uuid4()
            self.manager.attach(Watchdog(watchdog_uuid, 'Watchdog', self))
            self.manager.set_watchdog(watchdog_uuid)

            # Get commit ID
            commit = message.get('commit', None)
            if commit:
                if self.__force_version:
                    self.debug("Using static version: {}".format(
                        self.__force_version),
                               color="cyan")
                else:
                    # Set new commit
                    self.debug("Setting COMMIT to: {}".format(commit),
                               color="cyan")
                    with open("commit.dat", "w") as F:
                        F.write(commit)

                    # Pull changes
                    cmd = "git show --format='%H' --no-patch"  # Long HASH
                    status, output = getstatusoutput(cmd)
                    if status:
                        lastcommit = output
                    else:
                        lastcommit = None

                    if commit != lastcommit:
                        status, output = getstatusoutput("git fetch origin")
                        if status:
                            self.error(
                                "Couldn't fetch changes from REPOSITORY, I won't try any MERGE!"
                            )
                        else:
                            if commit == 'LATEST':
                                extraarg = ''
                            else:
                                extraarg = ' ' + commit
                            status, output = getstatusoutput(
                                "git merge{}".format(extraarg))
                            if status:
                                self.error("Couldn't merge changes!")

            else:
                # Delete commit.dat
                self.warning("This client is not linked to GITHUB")
                if os.path.exists("commit.dat"):
                    os.unlink("commit.dat")

            # Configure hardware
            self.debug("Setting configuration", color='blue')

            error = False
            for hw in message.get('hardware', []):
                # Get details
                uuidtxt = hw.get('uuid', None)
                kind = hw.get('kind', '')
                config = hw.get('config', {})

                if uuidtxt is not None:
                    uid = uuid.UUID(uuidtxt)
                    if not self.manager.exists_worker(uid):
                        self.debug("    > Configuring ",
                                   color='yellow',
                                   tail=False)
                        self.debug(str(uid),
                                   color='purple',
                                   head=False,
                                   tail=False)
                        self.debug(" as ",
                                   color='yellow',
                                   head=False,
                                   tail=False)
                        if kind in self.AVAILABLE_HARDWARE:
                            self.debug(kind, color='white', head=False)
                            try:
                                self.manager.attach(
                                    self.AVAILABLE_HARDWARE.get(kind)(uid,
                                                                      config))
                            except HardwareError as e:
                                self.send_error(
                                    "Device {} as {} is wrong configured: {}".
                                    format(uid, kind, e), ref, uid)
                                error = True
                        else:
                            self.debug(
                                "{}??? - Not setting it up!".format(kind),
                                color='red',
                                head=False)
                else:
                    self.error(
                        "    > I found a hardware configuration without UUID, I will not set it up!"
                    )

            # Make sure all tasks in manager are running
            self.manager.run(self)

            # If some error during startup
            if error:
                self.error(
                    "I have detected some error, I will try to reconfigure system when next message arrives!"
                )
            else:
                # No error happened, we are ready to go
                self.debug("Everything is set up and ready to work",
                           color='green')
                self.__fully_configured = True

        elif action == 'reset':
            self.warning("Got Reset request from Server")
            self.close(reason='Reset requested from Server')
        elif action == 'msg':
            msg = message.get('message', None)
            uid = message.get('uuid', None)
            if msg and uid:
                error = self.manager.recv(msg, ref, uid)
                if error:
                    self.send_error(error, ref)
            elif msg:
                self.send_error("No destination added to your message", ref)
            elif uuid:
                self.send_error("Got message for '{}' with no content", ref)
            else:
                self.send_error(
                    "Missing message and destination for your message", ref)
        elif action == 'error':
            self.error("Got an error from server: {}".format(
                message.get('error', 'No error')))
        elif action == 'ping':
            subref = message.get('ref', '-')
            self.debug("Sending PONG {} (ref:{})".format(subref, ref))
            self.send({'action': 'pong'}, ref)
        elif action != 'config':
            self.send_error("Unknown action '{}'".format(action), ref)

        if action != 'config' and not self.__fully_configured:
            self.debug("Reconfigure system", color='yellow')
            self.send({'action': 'get_config'}, ref)
コード例 #23
0
ファイル: webui.py プロジェクト: 5l1v3r1/crocodilehunter-1
    import coloredlogs, verboselogs
    import configparser

    logger = verboselogs.VerboseLogger("crocodile-hunter")
    fmt=f"\b * %(asctime)s crocodile-hunter - %(levelname)s %(message)s"
    coloredlogs.install(level="DEBUG", fmt=fmt, datefmt='%H:%M:%S')

    if not 'CH_PROJ' in os.environ:
        print("Please set the CH_PROJ environment variable")
        sys.exit()
    class Args:
        disable_gps = True
        disable_wigle = False
        debug = False
        project_name = os.environ['CH_PROJ']
        logger = logger
        config_fp = 'config.ini'
        config = configparser.ConfigParser(inline_comment_prefixes=('#', ';'))
        config.read(config_fp)

    w = Watchdog(Args)
    webui = Webui(w)
    SQL_PATH = f"mysql://*****:*****@localhost:3306"
    DB_PATH = f"{SQL_PATH}/{Args.project_name}"
    webui.app.config['SQLALCHEMY_DATABASE_URI'] = DB_PATH

    if 'db' in sys.argv:
        webui.manager.run()
    else:
        webui.start_daemon()
コード例 #24
0
ファイル: hub.py プロジェクト: ZSPina/wt_uhf_hub
''' Main screen that shows time and record symbol '''
def mainScreen():
    ''' Main Screen '''
    lcd.custom_char(0,customChar.RecordSym('offSym'))
    lcd.custom_char(1,customChar.RecordSym('onSym'))
    lcd.move_to(0,0)
    lcd.putchar(chr(0))
    lcd.move_to(5, 0)
    lcd.putstr(time.strftime('%m/%d %H:%M', time.localtime()))

GPIO.setup('P2_20', GPIO.OUT)
GPIO.output('P2_20', GPIO.LOW)
LCD_I2C_ADDR = 0x3f
lcd = I2cLcd(1, LCD_I2C_ADDR, 2, 16)
introScreen()
watchdog = Watchdog(180, myHandler)
rop = threading.Thread(target=ropHandler)
rop.start()

from google.cloud import datastore

#Initialize global variables to be used 
minFreq = 0
maxFreq = 0
samprate= 0
incremFreq = 0
timer1 = 0
timer2 = 0
numWDTHandle = 0
TIMER1_TIME = 15
TIMER2_TIME = 20
コード例 #25
0
async def on_message(message):
    if message.author == client.user:
        return

################################################
#           Modules start here!

    if message.content.startswith('$flip '):

        print("replied to a message, $flip")
        Product = message.content[6:].lower()

        Send = flip(Product)

        color = random.randint(0, 0xffffff)
        embed = discord.Embed(title="$flip " + Product, color=color)
        embed.set_author(
            name="BazaarViewer",
            icon_url=
            "https://cdn.discordapp.com/attachments/703719065977487390/708392264086585364/yeeeeeeeeee.png"
        )

        i = 0
        for x in Send:
            embed.add_field(name="#" + str(i + 1) + ":",
                            value=Send[i],
                            inline=False)
            i += 1
        strColor = str(color)
        embed.set_footer(text="Color: " + strColor)
        await message.channel.send(embed=embed)

    elif message.content.startswith('$commands'):
        color = random.randint(0, 0xffffff)
        embed = discord.Embed(title="Every command", color=color)
        embed.set_author(
            name="BazaarViewer",
            icon_url=
            "https://cdn.discordapp.com/attachments/703719065977487390/708392264086585364/yeeeeeeeeee.png"
        )
        embed.add_field(name="$commands",
                        value="Show every command.",
                        inline=False)
        embed.add_field(
            name="$flip (item)",
            value=
            "This will give you information about one item, like the NPC buy and sell price, and also the bazaar prices.",
            inline=False)
        embed.add_field(name="$merchantflip",
                        value="Shows the top products to flip.",
                        inline=False)
        embed.add_field(name="$everymerchantflip",
                        value="Sends you a DM with every products to flip.",
                        inline=False)
        embed.add_field(
            name="$pricedifference",
            value=
            "This will give you the items from the bazaar with the biggest buy-sell gap.",
            inline=False)
        embed.add_field(name="$request (item)",
                        value="If a item isnt supported yet, do this.",
                        inline=False)
        embed.add_field(
            name="$notify",
            value=
            "Using these two commands, you can toggle your notifications for events.",
            inline=False)
        embed.add_field(
            name="$eflip",
            value=
            "This will show you the top 5 items, you can buy from the bazaar, craft to the enchanted versions and resell them.",
            inline=False)
        embed.add_field(name="$bestlog",
                        value="Shows the woodtype, thats worth the most atm.",
                        inline=False)
        #embed.add_field(name="$minions", value="You type in the details, and I say you how much you would make with that minion setup **code by e56, ported to a discord-bot by me.**", inline=False)
        embed.add_field(
            name="$skyscore",
            value=
            "(BETA) That shows you the SkyScore of a product. The score gets calculated from the money you can make flipping it, and the buy/sell volume.",
            inline=False)
        embed.add_field(
            name="$reverseflip",
            value=
            "This shows you items, that you can buy at the Bazaar and sell to an NPC for profit. Not much, but easy.",
            inline=False)
        embed.add_field(
            name="$watchdog",
            value=
            "Everyone loves the watchdog message, right? Now you can get it on discord!",
            inline=False)
        strColor = str(color)
        embed.set_footer(text="Color: " + strColor)
        await message.channel.send(embed=embed)
        print("answered to $commands")

    elif message.content.startswith('$merchantflip'):
        print("replied to a message, $merchantflip!")

        sortedtoplist = MerchantFlip()
        color = random.randint(0, 0xffffff)
        embed = discord.Embed(title="How much can you make?", color=color)
        embed.set_author(
            name="BazaarViewer",
            icon_url=
            "https://cdn.discordapp.com/attachments/703719065977487390/708392264086585364/yeeeeeeeeee.png"
        )
        i = 0
        for x in sortedtoplist:
            embed.add_field(name="#" + str(i + 1) + ":",
                            value=sortedtoplist[i],
                            inline=False)
            i += 1
            if i == 4:
                break
        strColor = str(color)
        embed.set_footer(text="Color: " + strColor)
        await message.channel.send(embed=embed)

        sortedtoplist = []
        AllProfit = 0

    elif message.content.startswith('$request'):
        Product = message.content[9:].lower()
        Request(Product)
        await message.channel.send(
            "Ok, <@585935919224324117> has to add this. I wrote it to a text file."
        )

    elif message.content.startswith('$eflip'):

        sortedtoplist = eFlip()
        #I love try and except
        color = random.randint(0, 0xffffff)
        embed = discord.Embed(
            title="Nice!",
            description="Look up first, if you have the right collection!",
            color=color)
        embed.set_author(
            name="BazaarViewer",
            icon_url=
            "https://cdn.discordapp.com/attachments/703719065977487390/708392264086585364/yeeeeeeeeee.png"
        )

        try:
            embed.add_field(name="#1:", value=sortedtoplist[0], inline=False)
            try:
                embed.add_field(name="#2:",
                                value=sortedtoplist[1],
                                inline=False)
                try:
                    embed.add_field(name="#3:",
                                    value=sortedtoplist[2],
                                    inline=False)
                    try:
                        embed.add_field(name="#4:",
                                        value=sortedtoplist[3],
                                        inline=False)
                        try:
                            embed.add_field(name="#5:",
                                            value=sortedtoplist[4],
                                            inline=False)
                        except:
                            a = 0
                    except:
                        a = 0
                except:
                    a = 0
            except:
                a = 0
        except:
            embed.add_field(name="No items found",
                            value="Cant find any items :/",
                            inline=False)

        strColor = str(color)
        embed.set_footer(text="Color: " + strColor)
        await message.channel.send(embed=embed)
        print("replied to a message, e-flip!")
        toplist = []

    elif message.content.startswith('$reverseflip'):

        print("replied to a message!")
        sortedtoplist = ReverseFlip()
        color = random.randint(0, 0xffffff)
        embed = discord.Embed(title="Gettin that cash", color=color)
        embed.set_author(
            name="BazaarViewer",
            icon_url=
            "https://cdn.discordapp.com/attachments/703719065977487390/708392264086585364/yeeeeeeeeee.png"
        )
        i = 0
        for x in sortedtoplist:
            embed.add_field(name="#" + str(i + 1) + ":",
                            value=sortedtoplist[i],
                            inline=False)
            if i == 4:
                break
            i += 1

        await message.channel.send(embed=embed)

    elif message.content.startswith('$bestlog'):
        print("answered to BestLogs")

        #print(BestLogs())
        sortedtoplist = BestLogs()
        color = random.randint(0, 0xffffff)
        embed = discord.Embed(
            title="For how much can you sell each log?",
            description="You can sell every log for 2$ to the NPC.",
            color=color)
        embed.set_author(
            name="BazaarViewer",
            icon_url=
            "https://cdn.discordapp.com/attachments/703719065977487390/708392264086585364/yeeeeeeeeee.png"
        )
        i = 0
        for x in sortedtoplist:
            embed.add_field(name="#" + str(i + 1) + ":",
                            value=sortedtoplist[i],
                            inline=False)
            i += 1
        strColor = str(color)
        embed.set_footer(text="Color: " + strColor)
        await message.channel.send(embed=embed)
        sortedtoplist = []

    elif message.content.startswith("$pricedifference"):

        sortedtoplist = PriceDifference()
        color = random.randint(0, 0xffffff)
        embed = discord.Embed(title="Dont lose your money!", color=color)
        embed.set_author(
            name="BazaarViewer",
            icon_url=
            "https://cdn.discordapp.com/attachments/703719065977487390/708392264086585364/yeeeeeeeeee.png"
        )
        i = 0
        for x in sortedtoplist:
            embed.add_field(name="#" + str(i + 1) + ":",
                            value=sortedtoplist[i],
                            inline=False)
            if i == 4:
                break
            i += 1
        strColor = str(color)
        embed.set_footer(text="Color: " + strColor)
        await message.channel.send(embed=embed)

        toplist = []
        sortedtoplist = []

    elif message.content.startswith('$everymerchantflip'):
        sortedtoplist = MerchantFlip()
        a = 1
        b = 0
        color = random.randint(0, 0xffffff)
        embed = discord.Embed(title="Gettin that cash", color=color)
        embed.set_author(
            name="BazaarViewer",
            icon_url=
            "https://cdn.discordapp.com/attachments/703719065977487390/708392264086585364/yeeeeeeeeee.png"
        )
        i = 0
        for x in sortedtoplist:
            embed.add_field(name="#" + str(i + 1) + ":",
                            value=sortedtoplist[i],
                            inline=False)
            i += 1
        member = message.author
        channel = await member.create_dm()
        strColor = str(color)
        embed.set_footer(text="Color: " + strColor)
        await channel.send(embed=embed)
        await message.channel.send(
            "Ok, you should have gotten a DM with the prices.")

    elif message.content.startswith('$notifyme '):

        print("replied to a message, $notifyme")
        ############getting the product and the sender
        Person = message.author.id
        Product = message.content[10:].lower()
        #is this a existing product?
        if NormalName(Product) == "error":
            await message.channel.send(
                "Couldnt find the item " + Product +
                ". If you think it should be added, request it with $request "
                + Product + ".")
            #it is!
        else:
            time.sleep(1)
            #getting the buy/sell data:
            await message.channel.send(
                "Do you want to wait for the sell or buy price of the product to be a specific number? Enter buy or sell. You have 20 seconds."
            )
            buysell = await client.wait_for('message', timeout=20)
            if buysell.content == "sell" or buysell.content == "buy":
                buysell = buysell.content.lower()
                #nice!
                # when do you want to be notified?
                await message.channel.send(
                    "Ok, when do you want to be notified for the product " +
                    Product +
                    "? Please enter just a number. You have 20 seconds.")
                msg = await client.wait_for('message', timeout=20)
                try:
                    time.sleep(1)
                    Price = float(msg.content)
                    strPrice = str(Price)
                    await message.channel.send(
                        'Ok, you will be notified if the ' + buysell +
                        ' price of ' + Product + " is under " + strPrice +
                        "$.")
                    NewNotify(Product, Person, Price, buysell)
                except:
                    await message.channel.send(
                        "ERROR: Pleace just enter a number")
                    NewNotify(Product, Person, Price, buysell)

            else:
                await message.channel.send(
                    "ERROR: Please just say buy or sell.")

    elif message.content.startswith('$skyscore'):
        sortedtoplist = Score()
        color = random.randint(0, 0xffffff)
        embed = discord.Embed(title="Double check everything, still beta",
                              color=color)
        embed.set_author(
            name="BazaarViewer",
            icon_url=
            "https://cdn.discordapp.com/attachments/703719065977487390/708392264086585364/yeeeeeeeeee.png"
        )
        i = 0
        for x in sortedtoplist:
            embed.add_field(name="#" + str(i + 1) + ":",
                            value=sortedtoplist[i],
                            inline=False)
            if i == 4:
                break
            i += 1
        strColor = str(color)
        embed.set_footer(text="Color: " + strColor)
        await message.channel.send(embed=embed)

    elif message.content.startswith('$watchdog'):
        await message.channel.send(Watchdog())
コード例 #26
0
            if prediction is None:
                action = functools.partial(graphics_utils.draw_xcentered_text, text='No match', height=100)

            else:
                action = functools.partial(graphics_utils.draw_xcentered_text, text=prediction, height=100)

                email = face_identifier.get_email_for_name(prediction)
                match_action(email, timed_frame_modify)

            timed_frame_modify.add_modification(action, 3, 'nametext', exclusive=True)

        frame_counter += 1

        if Wakeup.are_we_awake():
            for frame_worker in awake_frame_workers:
                frame = frame_worker.process_frame(frame)

            # display the frame, potentially break the loop
            cv2.imshow('Video', frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
            cv2.imshow('Video', frame)

if __name__ == "__main__":
    watchdog = Watchdog(action=Wakeup.run_wakeup_command)
    watchdog.start_watchdog()
    try:
        main_loop(watchdog)
    finally:
        watchdog.stop_watchdog()
コード例 #27
0
                result = False
            else:
                # unknown error occurred or wrong
                result = False

        return make_summary(result, grader_msg, grader_checks, str(error))

    def tidy(self):
        pass


if __name__ == "__main__":
    loglevel = logging.INFO
    if len(sys.argv) > 1:
        if sys.argv[1] == "DEBUG":
            loglevel = logging.DEBUG

    # Initialize logging
    logging.basicConfig(
        filename="poller.log",
        filemode='a',
        format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
        datefmt='%m-%d %H:%M:%S',
        level=loglevel)

    def poll():
        Poller_Isa().run()

    poller = Watchdog(poll)
    poller.watch()
コード例 #28
0
ファイル: database_ops.py プロジェクト: f0lg0/gelata
def dbops_init(path):
    global DB_PATH
    global wd

    DB_PATH = path
    wd = Watchdog(DB_PATH)
コード例 #29
0
ファイル: task.py プロジェクト: michealtianlan/cloudtask
    def work(cls, jobs, session, taskconf):

        if taskconf.ssh_identity:
            sshkey = ssh.PrivateKey(taskconf.ssh_identity)
        else:
            sshkey = ssh.TempPrivateKey()

        def status(msg):
            timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
            session.logs.manager.write("%s :: session %d %s\n" %
                                       (timestamp, session.id, msg))

        status("(pid %d)" % os.getpid())
        print >> session.logs.manager

        class CaughtSignal(CloudWorker.Terminated):
            pass

        def terminate(sig, f):
            signal.signal(sig, signal.SIG_IGN)
            sigs = dict([(getattr(signal, attr), attr) for attr in dir(signal)
                         if attr.startswith("SIG")])

            raise CaughtSignal("caught %s termination signal" % sigs[sig], sig)

        exception = None
        while True:
            watchdog = Watchdog(session.logs.manager, session.paths.workers,
                                taskconf)

            signal.signal(signal.SIGINT, terminate)
            signal.signal(signal.SIGTERM, terminate)

            executor = None

            work_started = time.time()
            try:
                executor = CloudExecutor(session.logs, taskconf, sshkey)
                for job in jobs:
                    executor(job)

                executor.join()
                executor_results = list(executor.results)

            except Exception, exception:
                if isinstance(exception, CaughtSignal):
                    print >> session.logs.manager, "# " + str(exception[0])

                elif not isinstance(
                        exception,
                    (CloudWorker.Error, CloudWorker.Terminated)):
                    traceback.print_exc(file=session.logs.manager)

                if executor:
                    executor.stop()
                    executor_results = list(executor.results)
                else:
                    executor_results = []

            watchdog.terminate()
            watchdog.join()

            session.jobs.update(jobs, executor_results)

            if len(session.jobs.pending
                   ) != 0 and executor_results and exception is None:
                print >> session.logs.manager
                status("(auto-resuming) %d pending jobs remaining" %
                       len(session.jobs.pending))
                print >> session.logs.manager

                jobs = list(session.jobs.pending)
                if taskconf.split > len(jobs):
                    taskconf.split = len(jobs)
            else:
                break
コード例 #30
0
def watchdog(device_address):
    Watchdog(int(device_address)).start()