def maxNumberOfAllowedSimultaneousChannels(self):
     #Default
     dv = 5
     try:
         dv = int(self._settingsJson[dbc.KEY_SYMPHONY][dbc.KEY_MAXIMUM])
     except:
         logger(
             "_ERROR_",
             "appSettings[0][dbc.KEY_SETTINGS][dbc.KEY_SYMPHONY][dbc.KEY_MAXIMUM] doesn't exist"
         )
     return dv
Exemple #2
0
    def __init__(self, **kwargs):
        #threading.Thread.__init__(self)
        super().__init__()
        logger("_INFO_", "CpUiThread")
        self._rerun = False

        try:
            self.setFutureTerminationTime(kwargs['terminateAt'])
            logger("_INFO_", "CpUiThread terminate at:", kwargs['terminateAt'])
            self._rerun = True
        except KeyError:
            self.terminateAt = None
def main():
    global lRing

    logger("_INFO_", "GPIO version: ", GPIO.VERSION)

    #Set pin numbering reference mode
    GPIO.setmode(GPIO.BCM)

    #Setup GPIO as input
    #Motion sensor input needs pull down since it is ACTIVE HIGH and detection is required on RISING edge
    GPIO.setup(17, GPIO.IN,
               pull_up_down=GPIO.PUD_DOWN)  #GEN2 - Input - motion sensor
    #Button press input needs pull down since it is ACTIVE LOW and detection is required on RISING edge when button is released
    GPIO.setup(27, GPIO.IN,
               pull_up_down=GPIO.PUD_UP)  #GEN2 - button press / on demand

    #PWM
    lRing = LightRing(18)
    lRing.run()

    #GPIO.add_event_detect(18, GPIO.RISING, callback=gpio18_callback, bouncetime=1000)
    GPIO.add_event_detect(17,
                          GPIO.RISING,
                          callback=motionHandler,
                          bouncetime=1000)
    GPIO.add_event_detect(27,
                          GPIO.RISING,
                          callback=buttonPressHandler,
                          bouncetime=100)

    try:
        logger("_INFO_", "Setup complete. Waiting for interrupts")
        while True:
            time.sleep(100)
            #continue

    except KeyboardInterrupt:
        logger("_INFO_", "...Terminating")
        pass

    except:
        logger("_INFO_", "Unknown error")

    finally:
        #logger("_INFO_", "Cleaninug up GPIO")
        #GPIO.cleanup()
        lRing.terminate()
        logger(
            "_INFO_",
            "Not using GPIO.cleanup() with intent to prevent resetting of GPIOs"
        )

    return
 def isBirdChoiceLimitedToSameSpecies(self):
     #Default
     dv = False
     try:
         dv = self._settingsJson[dbc.KEY_SYMPHONY][
             dbc.KEY_LIMIT_TO_SAME_SPECIES]
     except:
         logger(
             "_ERROR_",
             "appSettings[0][dbc.KEY_SETTINGS][dbc.KEY_SYMPHONY][dbc.KEY_LIMIT_TO_SAME_SPECIES] doesn't exist"
         )
     return dv
Exemple #5
0
 def terminate(self):
     logger("_INFO_", "\na.terminate")
     self._rerun = False
     self._repeat = False
     if (self._pCurrent != None):
         self._pCurrent.kill()
         self._pCurrent = None
     if (self._pNext != None):
         self._pNext.kill()
         self._pNext = None
     if (self._futureTerminationCallback != None):
         self._futureTerminationCallback.cancel()
     return
def motionHandler(channel):
    global lRing
    ts = datetime.datetime.now()
    logger("_INFO_", "\nEvent captured on channel:", channel,
           ". Current value:", GPIO.input(channel), ". TS:", ts)
    #interface.processTrigger(interface.TriggerType.MOTION)
    t = Thread(target=interface.processTrigger,
               args=[(interface.TriggerType.MOTION)])
    t.name = "thread_motion_" + str(ts)
    t.start()
    logger("_INFO_", "Thread: ", t.name, "started")
    if (interface.isLightRingActivated()):
        lRing.activate()
    return
Exemple #7
0
def combinatoricData():
    ts = str(int(time.time()))

    response = {
        "state":"unsuccessful",
        "ts": ts
    }
    
    location = request.args.get("landscape")
    r = int(request.args.get("channels"))
    logger("_INFO_", "location=", location)

    d = Models(mysql.connection).fetch(ModelType.LOCATION_INFO, location)

    logger("_INFO_", "d=", d)
    logger("_INFO_", "d[totalBirdSounds]=", d[0]['totalBirdSounds'])
    #combinations = nCr
    n = d[0]['totalBirdSounds']
    if(n>0 and r>0):
        combInt = math.factorial(n)/(math.factorial(n-r) * math.factorial(r))
        comb = '{:.0}'.format(math.factorial(n)/(math.factorial(n-r) * math.factorial(r)))
        logger("_INFO_", "Combinations: ", comb, " Probability=", str(100/combInt))

        landscapeSubData = "This landscape has " + str(d[0]["distinctBirds"]) + " unique birds, " + str(d[0]["totalBirdSounds"]) + " songs, calls and other birdsounds, and " + str(d[0]["landscapeSounds"]) + " ambient soundscapes."
        channelsSubData = "With this setting, the number of birdsounds combinations possible are " + '{:,}'.format(combInt)[:-2] + ". Or in other words, the probability of listening to the same combination is " + f"{Decimal(100/combInt):.4E}" +"%"
        
        response["state"] = "successful"
        response["landscapeSubData"] = landscapeSubData
        response["channelsSubData"] = channelsSubData

    return json.dumps(response)
Exemple #8
0
def continousPbBirdsThreadEmulation(**kwargs):

    s = AppSettings()
    repeat = True
    while (repeat == True):

        if (s.isContinousPbBirdsEnabled() == False):
            #kill all audioThreads
            for a in AudioDbInterface.candidateAudioThreads:
                a.terminate()

            logger("_INFO_", "Audio threads stopped. Exiting")
            repeat = False
            continue

        logger("_INFO_", "AudioThreads: Live: ",
               str(len(AudioDbInterface.candidateAudioThreads)),
               "  Max Allowed:",
               str(s.maxNumberOfAllowedSimultaneousChannels()))
        if (len(AudioDbInterface.candidateAudioThreads) <
                s.maxNumberOfAllowedSimultaneousChannels()):
            c = getCandidateAudioFiles(s, triggerType="solo")
            for item in c:
                logger("_INFO_", "candidate item: ", item)
                adi = AudioDbInterface(item[dbc.KEY_ID],
                                       item[dbc.KEY_AUDIO_FILE])
                adi.start()

        time.sleep(5)
        logger("_INFO_", "Checking if cb/birds is still active")
        s.refresh()

    return
Exemple #9
0
    def terminate(self):
        logger("_INFO_", "Terminating continuous playback")

        #Cancel existing callback
        if (self._futureTerminationCallback != None):
            self._futureTerminationCallback.cancel()

        #Update the database
        queryFrag = "'$.continuousPlayback.enabled', False"
        Models(Db(dbc.MYSQL_DB).connection()).push(
            ModelType.UPDATE_APP_SETTINGS_IN_PLACE, str(queryFrag))

        self._rerun = False
        return
Exemple #10
0
 def __atSameFrameSwitchTrack(self):
     logger("_INFO_", "Running with cmd: ", self.__command())
     #Compute new frame
     self.startingFrame = round(
         (round(time.monotonic() * 1000) - self._pbStartTime) *
         self.framePerMs)
     self._pNext = subprocess.Popen("exec " + self.__command(),
                                    stdout=subprocess.PIPE,
                                    shell=True)
     #Set timer to kill old process
     timer = threading.Timer(self.switchingOffset,
                             self.__killProcess,
                             args=[self._pCurrent])
     timer.start()
     return
    def isContinousPbBirdsEnabled(self):
        if (self.isContinuousPlaybackEnabled() == False):
            return False

        #Default
        dv = False
        try:
            dv = self._settingsJson[dbc.KEY_CONTINUOUS_PLAYBACK][
                dbc.KEY_BIRDS_ENABLED]
        except:
            logger(
                "_ERROR_",
                "appSettings[0][dbc.KEY_CONTINUOUS_PLAYBACK][dbc.KEY_BIRDS_ENABLED] doesn't exist"
            )
        return dv
Exemple #12
0
def disableAmbientChannelAndUpdateSettings(ch):

    if (ch == 'ambientAudioChannel1'):
        queryFrag = "'$.continuousPlayback.ambience1', 'None'"
    elif (ch == 'ambientAudioChannel2'):
        queryFrag = "'$.continuousPlayback.ambience2', 'None'"
    else:
        logger("_INFO_", "Unsupported channel: ", ch)
        return

    #Update app settings in-place
    a = Models(Db(dbc.MYSQL_DB).connection()).push(
        ModelType.UPDATE_APP_SETTINGS_IN_PLACE, str(queryFrag))
    logger("_INFO_", "Settings updated inplace in database. Return: ", str(a))
    return
def buttonPressHandler(channel):
    global lRing
    ts = datetime.datetime.now()
    logger("_INFO_", "\nEvent captured on channel:", channel,
           ". Current value:", GPIO.input(channel), ". TS:", ts)
    #interface.processTrigger(interface.TriggerType.MOTION)

    #Make interface call only on rising-edge
    if (GPIO.input(channel) == 0):
        return

    t = Thread(target=interface.processTrigger,
               args=[(interface.TriggerType.BUTTON_PRESS)])
    t.name = "thread_motion_" + str(ts)
    t.start()
    logger("_INFO_", "Thread: ", t.name, "started")
    lRing.activate()
    return
Exemple #14
0
    def run(self):
        logger("_INFO_", "\na.run")
        self._pbStartTimeStatic = time.monotonic()

        self.__startSelf()
        while self._rerun == True:
            self._pCurrent.wait()
            if (self._pNext == None):
                if (self._repeat == True):
                    self.__startSelf()
                else:
                    self._rerun = False
            else:
                self._pCurrent = self._pNext
                self._pNext = None

        #self.terminate()
        logger("_INFO_", "------END OF RUN-------")
        return
 def print(self):
     logger("_INFO_", "appSettings: id=",
            str(self._appSettings[0][dbc.KEY_ID]))
     logger("_INFO_", "appSettings: last updated=",
            str(self._appSettings[0][dbc.KEY_LAST_UPDATED]))
     logger("_INFO_", "appSettings: settings=", str(self._settingsJson))
     return
Exemple #16
0
    def setFutureTerminationTime(self, terminationTime):
        if (self.terminateAt == terminationTime):
            return

        try:
            futureTime = parser.parse(terminationTime)
        except:
            logger("_INFO_", "Error: Unknown terminationTime: ",
                   str(terminationTime))
            return

        self.terminateAt = terminationTime
        logger("_INFO_", "Changing termination time to:", self.terminateAt)

        if (self._futureTerminationCallback != None):
            self._futureTerminationCallback.cancel()
            self._futureTerminationCallback = None

        #compute time
        currentTime = datetime.now()
        if (currentTime > futureTime):
            futureTime += timedelta(hours=24)

        secondsToTerminate = (futureTime - currentTime).total_seconds()
        logger("_INFO_", "Setting up termination for ", terminationTime,
               " in ", secondsToTerminate, " seconds")
        self._futureTerminationCallback = threading.Timer(secondsToTerminate,
                                                          self.terminate,
                                                          args=[])
        self._futureTerminationCallback.start()
        return
Exemple #17
0
def processTrigger(triggerType):
    #logger("_INFO_", "\n--> ",inspect.stack()[0][3], " CALLED BY ",inspect.stack()[1][3])
    #print("@processTrigger: ",triggerType)

    c = []
    latestSettings = AppSettings()
    maxNumberOfAllowedChannels = latestSettings.maxNumberOfAllowedSimultaneousChannels(
    )

    logger("_INFO_", "Trigger type:", triggerType)
    if (triggerType == TriggerType.MOTION):
        #1. Verify that triggers are enabled
        if (latestSettings.isMotionTriggerActive() == False):
            logger("_INFO_",
                   "Motion triggers are disabled in appSettings. Exiting")
            return
        #2. Verify that not in silent period
        if (latestSettings.isSilentPeriodActive()):
            logger("_INFO_", "Silent period active. Exiting")
            return

        c = getCandidateAudioFiles(
            latestSettings, requestedChannels=maxNumberOfAllowedChannels)

    elif (triggerType == TriggerType.ON_DEMAND_SOLO):
        numberOfChannelsRequested = 1
        c = getCandidateAudioFiles(latestSettings,
                                   requestedChannels=numberOfChannelsRequested)
    elif (triggerType == TriggerType.ON_DEMAND_SYMPHONY):
        c = getCandidateAudioFiles(
            latestSettings, requestedChannels=maxNumberOfAllowedChannels)
    elif (triggerType == TriggerType.ALARM):
        print("process alarm")
    elif (triggerType == TriggerType.BUTTON_PRESS):
        numberOfChannelsRequested = 1
        c = getCandidateAudioFiles(latestSettings,
                                   requestedChannels=numberOfChannelsRequested)
    else:
        print("unknown trigger type: ", triggerType)
        return

    #Once we have candidates, start audio threads here
    for item in c:
        logger("_INFO_", "candidate item: ", item)
        adi = AudioDbInterface(item[dbc.KEY_ID], item[dbc.KEY_AUDIO_FILE])
        adi.start()

    return
Exemple #18
0
def onStage():
    ts = str(int(time.time()))
    
    t = request.args.get("t")

    #print("local ts=",ts," t=",t," diff=",int(ts)-int(t))

    jsonObj = {
        "state":"unknown",
        "ts":ts
    }

    if(int(ts) - int(t) > 2):
        #Request too old
        jsonObj["state"] = "request too old"
        print("Rejecting request because it is too old", jsonObj)
        return jsonify(jsonObj)

    refetch = True
    while refetch==True:
        entries = None
        entries = Models(mysql.connection).fetch(ModelType.ACTIVE_ENTRIES)
        entries = [e['id'] for e in entries]
        logger("_INFO_", "\nfetchActiveEntries: ", json.dumps(entries))
        if(len(entries)==0):
            jsonObj["state"] = "empty"
            refetch = False
        else:
            purged = interface.purgeDeadEntries(60)
            print("Entries purged: ", purged)
            if(purged == 0):
                refetch = False
                jsonObj["state"] = "successful"
                jsonObj["data"] = json.dumps(entries)
            else:
                refetch = True

    return json.dumps(jsonObj)
    def isSilentPeriodActive(self):
        dv = False
        try:
            silentPeriodEnabled = self._settingsJson[dbc.KEY_SILENT_PERIOD][
                dbc.KEY_ENABLED]
            silentStartTime = parser.parse(
                self._settingsJson[dbc.KEY_SILENT_PERIOD][dbc.KEY_START_TIME])
            silentEndTime = parser.parse(
                self._settingsJson[dbc.KEY_SILENT_PERIOD][dbc.KEY_END_TIME])
        except:
            logger("_ERROR_", "appSettings doesn't exist")
            return dv

        if (silentPeriodEnabled == False):
            return False

        #Local time
        currentTime = datetime.datetime.now()
        logger("_INFO_", "    ** silentStartTime = ", silentStartTime)
        logger("_INFO_", "    ** currentTime = ", currentTime)
        logger("_INFO_", "    ** silentEndTime = ", silentEndTime)

        if (silentStartTime < silentEndTime):
            if (silentStartTime <= currentTime < silentEndTime):
                dv = True
            else:
                dv = False
        elif (silentStartTime > silentEndTime):
            if (silentStartTime <= currentTime or currentTime < silentEndTime):
                dv = True
            else:
                dv = False
        else:
            if (silentStartTime == currentTime == silentEndTime):
                dv = True
            else:
                dv = False

        return dv
 def activate(self):
     self.pwmTargetValue = 100
     logger("_INFO_", "Moving time marker from", self.timeMarker, "to",
            time.time())
     self.timeMarker = time.time()
Exemple #21
0
    def __init__(self, **kwargs):
        #threading.Thread.__init__(self)
        super().__init__()

        logger("_INFO_", "\n>>>> Initializing a new AudioThread Object")

        #private
        self._pCurrent = None
        self._pNext = None
        self._rerun = True
        self._repeat = True
        self._pbStartTime = 0
        self._pbStartTimeStatic = 0

        try:
            self.fp = kwargs['fp']
        except KeyError:
            logger("_INFO_", 'Error: fp (file path) is a required argument')
            exit()

        try:
            self._repeat = kwargs['repeat']
        except KeyError:
            self._repeat = True

        try:
            self.name = kwargs['tName']
        except KeyError:
            self.name = "AudioThread" + str(round(time.monotonic() * 1000))

        try:
            self.vol = kwargs['volume']
        except KeyError:
            self.vol = 100

        try:
            self.setFutureTerminationTime(kwargs['terminateAt'])
        except KeyError:
            self.terminateAt = None

        try:
            self.framePerMs = kwargs['fpms']
        except KeyError:
            self.framePerMs = 0.0382848

        try:
            self.startingFrame = kwargs['startingFrame']
        except KeyError:
            self.startingFrame = 0

        try:
            self.switchingOffset = kwargs['swOffset']
        except KeyError:
            self.switchingOffset = 0.6

        logger("_INFO_", "File: ", self.fp)
        logger("_INFO_", "Thread name: ", self.name)
        logger("_INFO_", "Volume: ", self.vol)
        logger("_INFO_", "Frames per millisecond: ", self.framePerMs)
        logger("_INFO_", "Starting frame: ", self.startingFrame)
        logger("_INFO_", "Switching offset: ", self.switchingOffset)
        logger("_INFO_", "Repeat: ", self._repeat)

        AudioThread.instanceCount += 1
        logger("_INFO_", "AudioThread instance count: ",
               AudioThread.instanceCount)
        return
Exemple #22
0
def getCandidateAudioFiles(appSettings, **kwargs):
    #print("\n--> ",inspect.stack()[0][3], " CALLED BY ",inspect.stack()[1][3])

    #2. TODO: Verify that required time has passed since last playback

    try:
        requestedChannels = kwargs['requestedChannels']
    except:
        requestedChannels = 1

    #Purge dead entries
    #Fetch
    activeEntries = Models(Db(dbc.MYSQL_DB).connection()).fetch(
        ModelType.ACTIVE_ENTRIES)
    activeEntries = [d[dbc.KEY_ID] for d in activeEntries]

    #3. Verify that number of active entries don't exceed maximum allowed
    if (len(activeEntries) > 0):
        purged = purgeDeadEntries(60)
        if (purged > 0):
            logger("_INFO_", purged, "Entries purged")
            activeEntries = Models(Db(dbc.MYSQL_DB).connection()).fetch(
                ModelType.ACTIVE_ENTRIES)

    logger("_INFO_", "Active entries:", activeEntries)
    logger("_INFO_", "Active/maxAllowed=", len(activeEntries), "/",
           appSettings.maxNumberOfAllowedSimultaneousChannels())
    if (len(activeEntries) >=
            appSettings.maxNumberOfAllowedSimultaneousChannels()):
        logger("_INFO_", "Channels saturated. Ignoring trigger. Exiting\n")
        return []

    #4. Compute number of channels to implement
    if (requestedChannels == 1):
        numberOfChannels = 1
    elif (requestedChannels > 1):
        emptyChannels = appSettings.maxNumberOfAllowedSimultaneousChannels(
        ) - len(activeEntries)
        if (requestedChannels > emptyChannels):
            numberOfChannels = emptyChannels
        else:
            numberOfChannels = requestedChannels

        if (randomizeNumberOfChannels):
            numberOfChannels = random.randint(1, requestedChannels)
    else:
        logger("_ERROR_", "Unsupported requested number of channels:",
               str(requestedChannels))
        return []

    #Scope:
    # (1) Fetch all sorted by last_updated asc
    data = Models(Db(dbc.MYSQL_DB).connection()).fetch(
        ModelType.IDS_NAMES_AUDIOFILE_SORTED_BY_LAST_UPDATED_OLDEST_FIRST)
    # (2) Select one t random from top 75% of that list
    #for d in data:
    #    print("New line")
    #    print(d[0])
    #    print(d[1])

    logger("_INFO_", "Total data rows: ", len(data))
    #print(type(data))
    #for d in data:
    #    print(type(d))
    #print(data)
    #print("\nJSON dumps:",json.dumps(data))

    allIds = [d[dbc.KEY_ID] for d in data]
    logger("_INFO_", allIds)
    eligibleLength = int(0.75 * len(data))
    candidates = []

    #Choose first at random
    candidates.append(data[random.randint(0, eligibleLength - 1)])
    logger("_INFO_", "CHOOSING 1st candidate:")
    logger(
        "_INFO_",
        "{:>4.4} {:32.32} {}".format(str(candidates[0][dbc.KEY_ID]),
                                     candidates[0][dbc.KEY_NAME],
                                     candidates[0][dbc.KEY_AUDIO_FILE]))
    data.remove(candidates[0])

    #Remove last 25%
    indicesToRemove = len(data) - eligibleLength
    for i in range(0, indicesToRemove):
        data.remove(data[len(data) - 1])

    logger("_INFO_", "Total number of channels to implement: ",
           numberOfChannels)

    if (numberOfChannels > 1):
        speciesConstrainedSet = []
        logger("INFO_", "Limit to same species: ",
               appSettings.isBirdChoiceLimitedToSameSpecies())
        if (appSettings.isBirdChoiceLimitedToSameSpecies()):
            for d in data:
                if (d == candidates[0]):
                    print(d, " :Already exists. Skipping")
                    #data.remove(candidates[0])
                    continue
                elif (d[dbc.KEY_NAME] == candidates[0][dbc.KEY_NAME]):
                    speciesConstrainedSet.append(d)
            data = speciesConstrainedSet

        logger("_INFO_", "Curated candidate data set: size=", len(data))
        for element in data:
            logger(
                "_INFO_",
                "{:>4.4} {:32.32} {}".format(str(element[dbc.KEY_ID]),
                                             element[dbc.KEY_NAME],
                                             element[dbc.KEY_AUDIO_FILE]))

        if (numberOfChannels >= len(data)):
            logger(
                "_INFO_", "Number of channels to implement " +
                numberOfChannels + " is more or equal to data set at hand ",
                len(data))
            for d in data:
                candidates.append(d)
        else:
            for i in range(0, numberOfChannels - 1):
                logger("_INFO_", "\nSelecting For channel ", i + 2)
                randomlyChosenRowIdx = random.randint(0, len(data) - 1)
                logger(
                    "_INFO_", "Size of data:", len(data), "  Chosen idx:",
                    randomlyChosenRowIdx, "id={} {} {}".format(
                        str(data[randomlyChosenRowIdx][dbc.KEY_ID]),
                        data[randomlyChosenRowIdx][dbc.KEY_NAME],
                        data[randomlyChosenRowIdx][dbc.KEY_AUDIO_FILE]))
                candidates.append(data[randomlyChosenRowIdx])
                #remove that row to avoid duplication
                data.remove(data[randomlyChosenRowIdx])

    #logger("_INFO_", "Final candidate list: ")
    #candidateAudioFiles = []
    #for c in candidates:
    #    print (c)
    #    candidateAudioFiles.append(c[1])
    return candidates
Exemple #23
0
def processUpstageSoundscape(ch, **kwargs):
    try:
        if (kwargs['terminate']):
            if (kwargs.get("terminate") == True):
                terminateSoundscapeAudioThread(ch)
        return
    except KeyError:
        logger("_INFO_", ch, " won't be terminated")

    atSettings = {}
    for key, value in kwargs.items():
        if (key == 'name'):
            if (value == 'None'):
                terminateSoundscapeAudioThread(ch)
                return
            else:
                d = Models(Db(dbc.MYSQL_DB).connection()).fetch(
                    ModelType.ID_FILE_FOR_NAME, value)[0]
                atSettings['fp'] = getAudioBasePath() + d[dbc.KEY_AUDIO_FILE]
        elif (key == 'endTime'):
            atSettings['terminateAt'] = value
        elif (key == 'vol'):
            atSettings['vol'] = value
        else:
            print("Unsupported key/value pair: ", str(key), ":", str(value))

    if (globals()[ch] == None or globals()[ch].isAlive() == False):
        #start new
        globals()[ch] = at(**atSettings)
        globals()[ch].start()

        #Update database if required
        logger("_INFO_", "audiothread started and waiting for completion")

        #Wait for completion
        globals()[ch].join()

        #Update database: appSettings
        logger("_INFO_",
               "Update appSettings here to reflect thread termination")
        disableAmbientChannelAndUpdateSettings(ch)
    else:
        #update existing
        for k, v in atSettings.items():
            if (k == 'fp'):
                try:
                    globals()[ch].changeFile(v)
                except:
                    logger("_ERROR_", "Fatal error: Could not change ", k,
                           "on", ch)
            elif (k == 'vol'):
                try:
                    globals()[ch].changeVolume(v)
                except:
                    logger("_ERROR_", "Fatal error: Could not change ", k,
                           "on", ch)
            elif (k == 'terminateAt'):
                try:
                    globals()[ch].setFutureTerminationTime(v)
                except:
                    logger("_ERROR_", "Fatal error: Could not change ", k,
                           "on", ch)
            else:
                print("Unsupported AT key/value pair: ", str(k), ":", str(v))

    return
Exemple #24
0
 def changeVolume(self, volume):
     if (self.vol != volume):
         logger("_INFO_", "Changing vol to:", volume)
         self.vol = volume
         self.__atSameFrameSwitchTrack()
     return
Exemple #25
0
def settingsChangeHandler():
    global ambientAudioChannel1, ambientAudioChannel2, continuousPlaybackThread

    latestSettings = AppSettings()
    logger("_INFO_", "\nLatest settings: id=", str(latestSettings.getId()))

    previousSettings = AppSettings(id=latestSettings.getId() - 1)
    logger("_INFO_", "Previous settings: id=", previousSettings.getId())

    sNew = latestSettings.getSettings()
    sOld = previousSettings.getSettings()
    logger("_INFO_", "\n    ### Current Settings: ", sNew)
    logger("_INFO_", "\n    ### Previous Settings: ", sOld)

    ########################################################
    #Ambient Sounscape handler
    for ambience in ['ambience1', 'ambience2']:
        ambientAudioChannel = ""
        if (ambience == 'ambience1'):
            ambientAudioChannel = 'ambientAudioChannel1'
            ambientVolume = 'amb1Vol'
        elif (ambience == 'ambience2'):
            ambientAudioChannel = 'ambientAudioChannel2'
            ambientVolume = 'amb2Vol'
        else:
            continue

        #Case 1: Continuous playback/upstage was turned OFF
        if ((sNew['continuousPlayback']['enabled'] == False
             or sNew['continuousPlayback']['upStageEnabled'] == False) and
            (sOld['continuousPlayback']['enabled'] == True
             and sOld['continuousPlayback']['upStageEnabled'] == True)):
            #processUpstageSoundscape(ambientAudioChannel, terminate=True)
            t = Thread(target=processUpstageSoundscape,
                       args=(ambientAudioChannel, ),
                       kwargs={'terminate': True})
            t.start()
            continue

        #Case 2: Continuous playback/upstage was turned ON or MODIFIED or UNMODIFIED
        elif (sNew['continuousPlayback']['enabled'] == True
              and sNew['continuousPlayback']['upStageEnabled'] == True):
            #Collect new settings into a dictionary:

            newAtSettings = {
                'name': sNew['continuousPlayback'][ambience],
                'endTime': sNew['continuousPlayback']['endTime'],
                'vol': sNew['continuousPlayback'][ambientVolume]
            }
            #processUpstageSoundscape(ambientAudioChannel, **newAtSettings)
            t = Thread(target=processUpstageSoundscape,
                       args=(ambientAudioChannel, ),
                       kwargs={**newAtSettings})
            t.start()

    ########################################################
    #Master Volume Handler
    if (sNew['volume'] != sOld['volume']):
        av.setVolume(int(sNew['volume']))

    ########################################################
    #Continuous playback handler - birds
    #Case 1: Cp/birds was turned off
    if ((sNew['continuousPlayback']['enabled'] == False
         or sNew['continuousPlayback']['birdsEnabled'] == False)
            and (sOld['continuousPlayback']['enabled'] == True
                 and sOld['continuousPlayback']['birdsEnabled'] == True)):
        logger("_INFO_",
               "Cp/birds was turned OFF - will be handled automatically")

    #Case 2: Cp/birds was turned ON
    elif ((sNew['continuousPlayback']['enabled'] == True
           and sNew['continuousPlayback']['birdsEnabled'] == True)
          and (sOld['continuousPlayback']['enabled'] == False
               or sOld['continuousPlayback']['birdsEnabled'] == False)):
        logger("_INFO_", "Cp/birds was turned ON")
        t = Thread(target=continousPbBirdsThreadEmulation)
        t.start()

    #Case 3: Cp/birds unchanged
    else:
        logger("_INFO_", "Cp/birds setting unchanged")

    ########################################################
    #Continuous playback
    if (sNew['continuousPlayback']['enabled'] == True):
        if (continuousPlaybackThread == None
                or continuousPlaybackThread.isAlive() == False):
            config = {'terminateAt': sNew['continuousPlayback']['endTime']}
            continuousPlaybackThread = ContinuousPlaybackUiThread(**config)
            continuousPlaybackThread.start()
        else:
            if (sNew['continuousPlayback']['endTime'] !=
                    sOld['continuousPlayback']['endTime']):
                continuousPlaybackThread.setFutureTerminationTime(
                    sNew['continuousPlayback']['endTime'])
    else:
        if (continuousPlaybackThread != None
                and continuousPlaybackThread.isAlive() == True):
            continuousPlaybackThread.terminate()
            continuousPlaybackThread = None

    return
Exemple #26
0
def saveSettings():

    logger("_INFO_", "Entering@:", str(int(time.time())))

    ts = str(int(time.time()))
    response = {
        "state":"unsuccessful",
        "ts": ts,
        "last_updated": ""
    }

    #Get current copy of settings
    a = AppSettings()
    #logger("_INFO_", "Current settings id=", a.getId())
    d = a.getSettings()

    if(request.method == 'POST'):
        #logger("_INFO_", "\n*********** form data ******************")
        #logger("_INFO_", "request.form: ", request.form)

        #if(request.form.get('cbSwitch')): print('cbSwitch checked')
        #if(request.form.get('upstageSwitch')): print('upstageSwitch checked')
        #if(request.form.get('mtEnabled')): print('mtEnabled checked')
        #if(request.form.get('symphonySwitch')): print('symphonySwitch checked')
        #if(request.form.get('symLimitToSame')): print('symLimitToSame checked')
        #if(request.form.get('silentPeriod')): print('silentPeriod checked')

        for field in list(request.form):
            #print(field, "=", request.form.get(field)) #.name, " ==== ", field.description, " ==== ", field.label.text, " ==== ", field.data)
            #logger("_INFO_", " >>> ", field, "=", request.form.get(field))

            #Values
            if(field == "landscape"): d['landscape'] = request.form.get(field)
            
            elif(field == "continuousPlayback.ambience1"): d['continuousPlayback']['ambience1'] = request.form.get(field)
            elif(field == "continuousPlayback.amb1Vol"): d['continuousPlayback']['amb1Vol'] = request.form.get(field)
            elif(field == "continuousPlayback.ambience2"): d['continuousPlayback']['ambience2'] = request.form.get(field)
            elif(field == "continuousPlayback.amb2Vol"): d['continuousPlayback']['amb2Vol'] = request.form.get(field)
            elif(field == "continuousPlayback.endTime"): d['continuousPlayback']['endTime'] = request.form.get(field)

            elif(field == "motionTriggers.frequency"): d['motionTriggers']['frequency'] = request.form.get(field)
            
            elif(field == "symphony.maximum"): d['symphony']['maximum'] = request.form.get(field)

            elif(field == "silentPeriod.startTime"): d['silentPeriod']['startTime'] = request.form.get(field)
            elif(field == "silentPeriod.endTime"): d['silentPeriod']['endTime'] = request.form.get(field)
            
            elif(field == "volume"): d['volume'] = request.form.get(field)
            
            elif(field == "continuousPlayback.enabled" or 
                 field == "continuousPlayback.birds" or
                 field == "continuousPlayback.upStageEnabled" or
                 field == "motionTriggers.enabled" or
                 field == "symphony.enabled" or
                 field == "symphony.limitToSameType" or
                 field == "silentPeriod.enabled"): 
                    #logger("_INFO_", "Checkbox", field, "handled outside loop")
                    continue

            else: logger("_INFO_", "ERROR! Form field/value: ", field,"/",request.form.get(field)," NOT BEING HANDLED")
        
        #Checkboxes
        d['continuousPlayback']['enabled'] = True if(request.form.get("continuousPlayback.enabled")) else False
        d['continuousPlayback']['birdsEnabled'] = True if(request.form.get("continuousPlayback.birds")) else False
        d['continuousPlayback']['upStageEnabled'] = True if(request.form.get("continuousPlayback.upStageEnabled")) else False

        d['motionTriggers']['enabled'] = True if(request.form.get("motionTriggers.enabled")) else False

        d['symphony']['enabled'] = True if(request.form.get("symphony.enabled")) else False
        d['symphony']['limitToSameType'] = True if(request.form.get("symphony.limitToSameType")) else False

        d['silentPeriod']['enabled'] = True if(request.form.get("silentPeriod.enabled")) else False

        #Convert to json
        jsonStr = json.dumps(d)
        #logger("_INFO_", "Json settings string to be saved: ", jsonStr)

        #Push to database
        a.save(jsonStr)
        #logger("_INFO_", "\nSettings saved. New id=",a.getId())
        #logger("_INFO_", "************* END *************")

        #Invoke settingsChange handler
        ambientSoundscapeThread = Thread(target=interface.settingsChangeHandler(), args=[1, 4])
        ambientSoundscapeThread.name = "ambientSoundScapeThread"
        ambientSoundscapeThread.start()

        #Set state of response
        response['state'] = 'successful'

    #logger("_INFO_", "Last updated: ", a.getLastUpdated(), " time-zone:", datetime.datetime.now(tzlocal()).tzname())
    response['last_updated'] = str(a.getLastUpdated()) + " " + datetime.datetime.now(tzlocal()).tzname()
    logger("_INFO_", "Exiting@:", str(int(time.time())))
    return(jsonify(response))
Exemple #27
0
    logging.info('Saving: {}'.format(checkpoint_location))
    pkl.dump((h_epoch, h_train, h_valid), open(checkpoint_location, 'wb'))

    model_ckpt = 'checkpoints/{}/{}_torch_model_{}_{}.pkl'.format(
            expt, model, time_stamp, config_summary)
    logging.info('Saving: {}'.format(model_ckpt))
    torch.save(auto_encoder, model_ckpt)


if __name__ == "__main__":
    expt = 'titanic'
    model = 'autoencoder_basic'
    marker = 'A'
    pr_time, fl_time = time_stp()

    logger(expt, model, fl_time, 'A')

    log_time('Start', pr_time)
    args = autoencoder_argparse()
    main(
        model=model,
        time_stamp=fl_time,
        device=args['device'],
        ally_classes=int(args['n_ally']),
        advr_1_classes=int(args['n_advr_1']),
        advr_2_classes=int(args['n_advr_2']),
        encoding_dim=int(args['dim']),
        test_size=float(args['test_size']),
        batch_size=int(args['batch_size']),
        n_epochs=int(args['n_epochs']),
        shuffle=int(args['shuffle']) == 1,
Exemple #28
0
    checkpoint_location = \
        'checkpoints/{}/{}_training_history_{}.pkl'.format(
            expt, model, time_stamp)
    sep()
    logging.info('Saving: {}'.format(checkpoint_location))
    pkl.dump(h, open(checkpoint_location, 'wb'))


if __name__ == "__main__":
    expt = 'mimic'
    model = 'ind_gan'
    marker = 'H'
    pr_time, fl_time = time_stp()

    logger(expt, model, fl_time, marker)

    log_time('Start', pr_time)
    args = comparison_argparse()
    main(model=model,
         time_stamp=fl_time,
         device=args['device'],
         ally_classes=args['n_ally'],
         advr_1_classes=args['n_advr_1'],
         advr_2_classes=args['n_advr_2'],
         encoding_dim=args['dim'],
         hidden_dim=args['hidden_dim'],
         leaky=args['leaky'],
         test_size=args['test_size'],
         batch_size=args['batch_size'],
         n_epochs=args['n_epochs'],
Exemple #29
0
            (round(time.monotonic() * 1000) - self._pbStartTime) *
            self.framePerMs)
        self._pNext = subprocess.Popen("exec " + self.__command(),
                                       stdout=subprocess.PIPE,
                                       shell=True)
        #Set timer to kill old process
        timer = threading.Timer(self.switchingOffset,
                                self.__killProcess,
                                args=[self._pCurrent])
        timer.start()
        return

    def __killProcess(self, p):
        p.kill()
        return


if __name__ == '__main__':
    a = AudioThread(fp="GregoryAlanIsakov3am.mp3", swOffset=0.75)
    a.start()
    time.sleep(10)
    a.changeVolume(70)
    logger("_INFO_", "State of thread: a.isAlive: ", a.isAlive())
    time.sleep(15)
    logger("_INFO_", "State of thread: a.isAlive: ", a.isAlive())
    a.changeVolume(30)
    time.sleep(4)
    a.changeVolume(10)
    time.sleep(4)
    a.terminate()