# uncompyle6 version 3.9.1
# Python bytecode version base 2.2 (60717)
# Decompiled from: Python 3.9.6 (default, Jun 27 2024, 17:58:20) 
# [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
# Embedded file name: wxdata.py
# Compiled at: 2007-01-13 00:33:26
import re, time, types, shutil, twc.dsmarshal, twc.DataStoreInterface, twc.InterestList, twc.MiscCorbaInterface, twccommon, twccommon.Log, domestic.BulletinInfo, os, glob
ds = twc.DataStoreInterface
dsm = twc.dsmarshal
BulletinInfo = domestic.BulletinInfo
CHANNEL_NAME = 'SystemEventChannel'
MAP_ACTIVE_KEY = 'mapcuts.active'
MAP_PENDING_KEY = 'mapcuts.pending'
MAP_FORCE_KEY = 'mapcuts.force'

def getBulletinInterestList(ugc):
    cl = getUGCInterestList(ugc, 'county')
    zl = getUGCInterestList(ugc, 'zone')
    return cl + zl


def getUGCInterestList(ugc, type):
    locs = []
    mo = _ugcRegex.search(ugc)
    while mo != None:
        (start, end) = mo.span()
        sl = ugc[start:end]
        ugc = ugc[end:]
        locs.extend(_parseUGCStateList(sl))
        mo = _ugcRegex.search(ugc)

    il = _getInterestList(type)
    locs = filter((lambda e: e in il), locs)
    return locs
    return


def setDailyRec(loc, data, obsTimeT):
    currTemp = getattr(data, 'temp', None)
    if currTemp:
        twccommon.Log.debug('currTemp = %d' % currTemp)
        dailyRec = twc.Data(currHighTemp=currTemp, currLowTemp=currTemp)
        save = 0
        try:
            dkey = 'daily.%s.recordTemps' % loc
            dailyRec = dsm.get(dkey)
            if currTemp > dailyRec.currHighTemp:
                save = 1
                dailyRec.currHighTemp = currTemp
            if currTemp < dailyRec.currLowTemp:
                save = 1
                dailyRec.currLowTemp = currTemp
        except:
            save = 1

        if save == 1:
            (y, m, d, H, M, S, wd, jd, dst) = time.localtime(obsTimeT)
            midnight = time.mktime((y, m, d + 1, 0, 0, 0, 0, 0, -1))
            dsm.set(dkey, dailyRec, int(midnight))
    return


def setData(loc, type, data, expiration, update=0):
    if type == 'obs':
        setDailyRec(loc, data, expiration - 75 * 60)
    key = '%s.%s' % (type, str(loc))
    _setData(key, data, expiration, update)
    twccommon.Log.debug('set %s' % (key,))
    if type == 'hdln':
        log_msg = 'set hdln for location %s' % loc
        twccommon.Log.info(log_msg)
        modifiedHeadlines = []
        matchCategories = ((4, 'INLAND HURRICANE WATCH', re.compile('INLAND HURRICANE WATCH'), 'HURRICANE WATCH'), (3, 'HURRICANE WATCH', re.compile('(?<!INLAND )HURRICANE WATCH'), 'HURRICANE WATCH'), (2, 'INLAND HURRICANE WARNING', re.compile('INLAND HURRICANE WARNING'), 'HURRICANE WARNING'), (1, 'HURRICANE WARNING', re.compile('(?<!INLAND )HURRICANE WARNING'), 'HURRICANE WARNING'))
        for i in range(len(data.headlines)):
            headline = data.headlines[i]
            compareHeadline = (' ').join(headline.upper().split())
            matchAppender = []
            for (v, match, headlineRe, abb) in matchCategories:
                if headlineRe.search(compareHeadline):
                    matchAppender = [(v, i, abb, headline)]

            modifiedHeadlines += matchAppender

        modifiedHeadlines.sort()
        if len(modifiedHeadlines) > 0:
            d = twc.Data(header=modifiedHeadlines[0][2], message=modifiedHeadlines[0][3])
            dsm.set('hurricaneStatement', d, expiration)
            ds.commit()
        else:
            try:
                dsm.remove('hurricaneStatement')
                ds.commit()
            except KeyError:
                pass


def setDaypartData(loc, type, data, validTime, numDayparts, expiration, update=0):
    (Y, M, D, h, m, s, wday, day, dst) = time.localtime(validTime)
    window = 24 / numDayparts
    h = h / window * window
    validTime = time.mktime((Y, M, D, h, 0, 0, wday, day, -1))
    key = '%s.%s.%d' % (type, str(loc), validTime)
    _setData(key, data, expiration, update)
    twccommon.Log.debug('set %s' % (key,))


def setBulletin(loc, data, expiration):
    setBulletins([(loc, data, expiration)])


def setBulletins(blist):
    setlist = []
    for (loc, data, expiration) in blist:
        info = BulletinInfo.getBulletinProperties(data.pil, data.pilExt)
        il = _getInterestList('county')
        if loc in il[1:]:
            if not info.multicountied:
                continue
        data.county = loc
        data.expiration = expiration
        setlist.append((loc, info.group))
        which = '%s.%d' % (loc, info.group)
        key = 'bulletin.' + which
        dsm.set(key, data, expiration, 0)
        key = 'bulletin.lastIssue.%s' % data.pil
        dsm.set(key, data.issueTime, 0, 0)
        key = 'bulletin.lastIssue.%s%s' % (data.pil, data.pilExt)
        dsm.set(key, data.issueTime, 0, 0)
        ds.commit()

    if len(setlist):
        _signalRPC('playman.playCmd.bulletin.setList', (setlist,))
        twccommon.Log.info('set bulletins %s' % setlist)


def cancelBulletin(loc, pil, pilExt):
    cancelBulletins([(loc, pil, pilExt)])


def cancelBulletins(l):
    setlist = []
    for (loc, pil, pilExt) in l:
        info = BulletinInfo.getBulletinProperties(pil, pilExt)
        which = '%s.%d' % (loc, info.group)
        key = 'bulletin.%s' % (which,)
        try:
            dsm.remove(key)
            ds.commit()
            setlist.append((loc, info.group))
        except KeyError:
            pass

    if len(setlist):
        _signalRPC('playman.playCmd.bulletin.cancelList', (setlist,))
        twccommon.Log.info('cancel bulletins %s' % setlist)


def setImageData(type, fname):
    twccommon.Log.info('setImageData(%s, %s)' % (type, fname))
    (imgType, imgLoc) = type.split('.')
    if imgType in ['map', 'radar', 'satellite', 'radarSatellite']:
        fnName = 'execd.imageProc.%s.process' % imgType
    else:
        fnName = 'execd.imageProc.image.process'
    _signalRPC(fnName, (imgType, imgLoc, fname))
    twccommon.Log.info('set %s image: %s' % (type, fname))


def setMapCut(type):
    _signalRPC('execd.map.process', (type,))
    twccommon.Log.info('set map cut: %s' % type)


def setMapData(key, data, expiration, update=0):
    mapForceKey = MAP_FORCE_KEY
    try:
        mapCutRequired = dsm.get(mapForceKey)
    except:
        mapCutRequired = 0

    mapDataKey = key + '.MapData'
    try:
        old = twc.DefaultedData(dsm.get(mapDataKey))
        for (k, v1) in data.__dict__.items():
            v2 = getattr(old, k, None)
            if v2 != v1:
                mapCutRequired = 1
                break

    except:
        mapCutRequired = 1

    if mapCutRequired:
        pendingKey = MAP_PENDING_KEY
        try:
            mapPendingList = dsm.get(pendingKey)
        except KeyError:
            mapPendingList = []
        else:
            if mapPendingList.count(key) < 1:
                mapPendingList.append(key)
                dsm.set(pendingKey, mapPendingList, 0)
                ds.commit()
            twccommon.Log.info('set %s' % (mapDataKey,))
            _setData(mapDataKey, data, expiration, update)
            setMapCut(key)
    return


def setInterestList(ilType, configVersion, val):
    if type(val) != types.ListType:
        raise RuntimeError, 'invalid interest list; should be a list of strings'
    key = 'Config.%s.interestlist.%s' % (configVersion, ilType)
    try:
        old = dsm.get(key)
    except KeyError:
        old = None

    if old != val:
        dsm.set(key, val, 0)
        ds.commit()
        twccommon.Log.info('setting %s to: %s' % (key, val))
        twc.InterestList.getInterestList(ilType, updateCache=1)
        if _ilistSignalMap.has_key(ilType):
            for fnName in _ilistSignalMap[ilType]:
                _signalRPC(fnName, (val,))

    return


def setTimeZone(timezone):
    twccommon.Log.info('setting timezone to: %s' % timezone)
    shutil.copyfile('/usr/share/zoneinfo/%s' % timezone, '/etc/localtime')


def installPackage(pkg, instPath):
    _signalRPC('execd.ipackage.install', (pkg, instPath))


def installMediaPack(pack, replace):
    _signalRPC('execd.mediapack.install', (pack, replace))


def getMediaPackVersion(pack):
    version = None
    versionFile = '/media/%s.version' % (pack,)
    if os.path.exists(versionFile):
        try:
            fd = open(versionFile, 'r')
            version = fd.readline()
            version = version[:-1]
            fd.close()
        except:
            twccommon.Log.warning('getMediaPackVersion: Error reading version file: %s.' % (versionFile,))

    else:
        twccommon.Log.info('getMediaPackVersion: Pack %s not installed.' % (pack,))
    return version
    return


def shutdown():
    reboot()


def reboot():
    twccommon.Log.info('Shut down requested! Rebooting...')
    os.system('shutdown -r now')


def restart():
    twccommon.Log.info('Restart requested! Killing processes...')
    os.system('killall receiverd')


def loadClock():
    pass


def loadData(prodType, argData):
    if prodType == 'tag':
        id = 'tag-%s' % argData.id
        duration = argData.duration * 30 + argData.durationFrames
        scheds = "[DynamicSchedule('Tag')]"
        params = twccommon.Data(mediaNum=argData.mediaNum)
        _pmLoad(id, duration, argData.expire, scheds, params)
    elif prodType == 'localAvail':
        id = 'localAvail-%s' % argData.id
        duration = 68
        durationFrames = 0
        duration = duration * 30 + durationFrames
        scheds = "[DynamicSchedule('LocalAvail')]"
        params = twccommon.Data()
        _pmLoad(id, duration, argData.expire, scheds, params)
    else:
        _runPlayCmd(prodType, 'load', argData)


def runData(prodType, argData):
    if prodType == 'tag':
        id = 'tag-%s' % argData.id
        _pmRun(id, argData.time, argData.frame)
    elif prodType == 'localAvail':
        id = 'localAvail-%s' % argData.id
        _pmRun(id, argData.time, argData.frame)
    else:
        _runPlayCmd(prodType, 'run', argData)


def processHeartbeat(**kw):
    v = _getDictVal(kw, 'time')
    if v != None:
        (sec, millisec) = v
        _setTime(sec, millisec)
    dispMode = _getDictVal(kw, 'displayMode')
    if dispMode != '*':
        _processStateVal(kw, 'displayMode')
    _processStateVal(kw, 'sensorState')
    return


def setTime(sec, millisec):
    pass


def setTrafficIncidents(path):
    twccommon.Log.info('Traffic: setTrafficIncidents: path %s.' % (path,))
    _signalRPC('execd.traffic.processIncidents', (path,))


def setTrafficMap(path, hasData):
    if hasData:
        twccommon.Log.info('Traffic: setTrafficMap: path %s.' % path)
    else:
        twccommon.Log.info('Traffic: set Temp Unavail Traffic Map: path %s.' % path)


def changeIrdChannel(channelNumber):
    _signalRPC('execd.altFeed.channelChange', (channelNumber,))


DELAYED_CHANNEL_CHANGE = 0
IMMEDIATE_CHANNEL_CHANGE = 1

def setIrdChannel(channelNumber, switchMethod=DELAYED_CHANNEL_CHANGE):
    if switchMethod == IMMEDIATE_CHANNEL_CHANGE:
        twccommon.Log.info('AltFeed: IMMEDIATE ird channel change requested to channel %s.' % (channelNumber,))
        changeIrdChannel(channelNumber)
    else:
        _signalRPC('execd.altFeed.channelChangeRequest', (channelNumber,))
        twccommon.Log.info('AltFeed: ird channel change requested: Channel %s.' % (channelNumber,))


def system(cmd):
    _signalRPC('execd.system', (cmd,))


def toggleNationalLDL(activate):
    id = 0
    _runPlayCmd('ldl', 'toggleNationalLDL', id, activate)


_ugcRegex = re.compile('[A-Z]{2}[ZC]([0-9]{3}[\\->])*[0-9]{3}')
_getInterestList = twc.InterestList.getInterestList
_ilistSignalMap = {'climId': ['playman.init.setClimIds'], 'county': ['playman.playCmd.bulletin.setCountyInterestList']}

def _setData(key, data, expiration, update):
    dsm.set(key, data, expiration, update)
    ds.commit()


def _signalEvent(type, value):
    twc.MiscCorbaInterface.signalEvent(CHANNEL_NAME, type, value)


def _signalRPC(rpcName, args):
    twc.MiscCorbaInterface.signalEvent(CHANNEL_NAME, rpcName, repr(args))


def _parseUGCStateList(ugc):
    state = ugc[:3]
    ugc = ugc[3:]
    sp = ugc.split('-')
    locs = []
    for loc in sp:
        pos = loc.find('>')
        if pos == -1:
            locs.append('%s%03d' % (state, int(loc)))
        start = int(loc[:pos])
        end = int(loc[pos + 1:])
        for i in range(start, end + 1):
            locs.append('%s%03d' % (state, i))

    return locs


def _getDictVal(dict, key):
    val = None
    try:
        val = dict[key]
    except KeyError:
        pass

    return val
    return


def _processStateVal(kw, valName):
    v = _getDictVal(kw, valName)
    if v == None:
        return
    dsv = dsm.defaultedGet(valName, None)
    if v == dsv:
        return
    _setData(valName, v, 0, 0)
    if valName == 'sensorState':
        toggleNationalLDL(v)
    return


def _pmLoad(id, duration, expire, scheds, params):
    args = (id, duration, expire, scheds, params)
    twccommon.Log.info('signalling load of %s (%s, %s, %s, %s)' % args)
    _signalRPC('playman.playCmd.pm.load', args)


def _pmRun(id, startTime, startFrame):
    args = (id, startTime, startFrame)
    twccommon.Log.info('signalling run of %s (%s, %s)' % args)
    _signalRPC('playman.playCmd.pm.run', args)


def _runPlayCmd(prodType, playCmd, *params):
    twccommon.Log.info('signalling %s of %s %s' % (playCmd, prodType, str(params)))
    fnName = 'playman.playCmd.%s.%s' % (prodType, playCmd)
    _signalRPC(fnName, params)

# okay decompiling /tmp/toolnb/2f57ca055d83b3439a658f5d0df21f01/main.pyc

# uncompyle6 version 3.9.1
# Python bytecode version base 2.2 (60717)
# Decompiled from: Python 3.9.6 (default, Jun 27 2024, 17:58:20) 
# [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
# Embedded file name: radar.py
# Compiled at: 2007-05-14 23:20:55
import os, twccommon.Log, string, glob, twc, twc.dsmarshal
dsm = twc.dsmarshal

def init(config):
    global _config
    _config = config


def uninit():
    pass


def genSmoothingCommandLine(inputFile, outputFile, miles):
    cmdString = ''
    if miles <= 120:
        radius = 12
        scale = 8
        round = 0.5
        dropShadow = 4
        gaussian = 1
    elif miles >= 121 and miles <= 180:
        radius = 8
        scale = 8
        round = 0.5
        dropShadow = 4
        gaussian = 0
    elif miles >= 181 and miles <= 250:
        radius = 4
        scale = 8
        round = 0.5
        dropShadow = 4
        gaussian = 0
    elif miles >= 251 and miles <= 370:
        radius = 2
        scale = 8
        round = 0.5
        dropShadow = 4
        gaussian = 0
    elif miles > 370:
        radius = 0
        scale = 14
        round = 0.5
        dropShadow = 2
        gaussian = 0
    else:
        radius = 0
        scale = 8
        round = 0.5
        dropShadow = 2
        gaussian = 0
    cmdString += ' -i %s -o %s -r %d -s %d -R %f -d %d -g %d' % (inputFile, outputFile, radius, scale, round, dropShadow, gaussian)
    return cmdString


def buildIndexFile(rootName, validTimeString):
    """Builds an index file that contains an AVERAGE of ALL rainDensity amounts
       and a MAXIMUM value of all the precip types. This index will have the
       same date/time naming convention as a stats file and will reprsent what
       the entire contents of the radar cuts directory looks like when the
       'snapshot' is taken.
       
    latestRadarImage will look like this (for example):
        '/{path}/Config.1.Core1.0.Local_LocalDoppler.0.1171278600.1171290300.data.stats'
    """
    global glob
    globName = rootName + '.*.data.stats'
    statsList = glob.glob(globName)
    loopRainDensity = 0
    maxPrecipType = 0
    totalRainDensity = 0
    rainDensityCount = len(statsList)
    for statsFile in statsList:
        nsStats = {}
        try:
            execfile(statsFile, nsStats, nsStats)
        except:
            pass

        if nsStats.has_key('rainDensity'):
            rainDensity = nsStats['rainDensity']
            totalRainDensity += rainDensity
        else:
            twccommon.Log.warning("Missing 'rainDensity' in %s. Assuming a value of 5." % (statsFile,))
            totalRainDensity += 5
        if nsStats.has_key('precipType'):
            precipType = nsStats['precipType']
            if precipType > maxPrecipType:
                maxPrecipType = precipType
        else:
            twccommon.Log.warning("Missing 'precipType' in %s. Assuming a value of 3." % (statsFile,))
            maxPrecipType = 3

    loopRainDensity = round(float(totalRainDensity) / float(rainDensityCount))
    indexFile = '%s.%s.data.index' % (rootName, validTimeString)
    twccommon.Log.info('generating radar stats INDEX file: %s' % (indexFile,))
    f = open(indexFile, 'w+')
    f.write('# Radar Index File\n')
    f.write('loopRainDensity = %d   # (values > 5 are significant)\n' % (loopRainDensity,))
    f.write('maxPrecipType = %d     # (0=none,1=rain,2=mixed,3=snow)\n' % (maxPrecipType,))
    f.close()


def process(ftype, loc, iname):
    splitName = os.path.splitext(os.path.basename(iname))
    if splitName[1] == '.gz':
        os.system('gzip -d -f %s' % (iname,))
        fname = os.path.join(os.path.split(iname)[0], splitName[0])
        bname = os.path.splitext(os.path.basename(splitName[0]))[0]
    else:
        fname = iname
        bname = splitName[0]
    rc = 0
    key = 'Config.%s.interestlist.%s.%s.cuts' % (dsm.getConfigVersion(), ftype, loc)
    il = dsm.get(key)
    for prod in il:
        print("this is a thing in il" + prod)
        mapDataKey = prod + '.MapData'
        attribs = dsm.get(mapDataKey)
        rootName = '%s/%s/%s.cuts/%s' % (_config.imageRoot, ftype, loc, prod)
        dataName = rootName + '.%s.data.tif' % (bname,)
        tempName = rootName + '.%s.TEMP.tif' % (bname,)
        smoothName = rootName + '.%s.SMOOTH.tif' % (bname,)
        finalName = rootName + '.%s.tif' % (bname,)
        x = attribs.datacutCoordinate[0]
        y = attribs.datacutCoordinate[1]
        w = attribs.datacutSize[0]
        h = attribs.datacutSize[1]
        fw = attribs.dataFinalSize[0]
        fh = attribs.dataFinalSize[1]
        offsetX = attribs.dataOffset[0]
        offsetY = attribs.dataOffset[1]
        basemapW = attribs.mapFinalSize[0]
        basemapH = attribs.mapFinalSize[1]
        limitSize = 0
        if basemapW > 512:
            fw = int(fw * 512 / basemapW)
            fh = int(fh * 512 / basemapH)
            offsetX = int(offsetX * 512 / basemapW)
            offsetY = int(offsetY * 512 / basemapH)
            limitSize = 1
        miles = int(attribs.mapMilesSize[0] * (720.0 / basemapW))
        TWCPERSDIR = os.environ['TWCPERSDIR']
        configFile = TWCPERSDIR + '/conf/imagecut.py'
        smoothingApplication = '/usr/twc/smooth/bin/imageSmooth'
        version = dsm.defaultedGet('version.twc_imagesmooth')
        if version == None:
            twccommon.Log.debug('Could not determine smoothing application version!')
        else:
            twccommon.Log.debug('Smoothing with imageSmooth v%s' % (version,))
        if _config.radarImageScalingMethod == 'fixedPalette':
            scalingMethod = _config.radarImageScalingMethod
        elif _config.radarImageScalingMethod == 'colorAverage':
            scalingMethod = _config.radarImageScalingMethod
        else:
            err = 'Radar Scaling Method Unrecognized! Failed to cut for %s.' % dataName
            twccommon.Log.error(err)
            raise RuntimeError, err
        cmd = NICE_VALUE
        cmd += _config.imageCutTool
        if limitSize:
            cmd += ' -i %s -o %s -l%d,%d -w%d -h%d -p%d,%d -S%d,%d                 -m%s -a0,0,0:20,20,20 -r -c %s -f%d,%d' % (fname, dataName, x, y, w, h, offsetX, offsetY, fw, fh, scalingMethod, configFile, 512, 512)
        else:
            cmd += ' -i %s -o %s -l%d,%d -w%d -h%d -p%d,%d -S%d,%d                 -m%s -a0,0,0:20,20,20 -r -c %s -f%d,%d' % (fname, dataName, x, y, w, h, offsetX, offsetY, fw, fh, scalingMethod, configFile, basemapW, basemapH)
        twccommon.Log.debug('Cutting %s' % cmd)
        rc = os.system(cmd)
        if rc != 0:
            err = 'Image failed to cut for %s.' % dataName
            twccommon.Log.error(err)
            raise RuntimeError, err
        if _config.enableSmoothing:
            if os.path.exists(smoothingApplication):
                cmd = NICE_VALUE
                cmd += smoothingApplication
                cmd += genSmoothingCommandLine(dataName, smoothName, miles)
                twccommon.Log.debug('Smoothing %s' % cmd)
                rc = os.system(cmd)
                if rc != 0:
                    err = 'Image failed to smooth for %s.' % dataName
                    twccommon.Log.error(err)
                    raise RuntimeError, err
                cmd = 'mv %s %s' % (smoothName, dataName)
                twccommon.Log.debug('Moving %s' % cmd)
                rc = os.system(cmd)
                if rc != 0:
                    err = 'Image failed to rename from %s to %s.' % (smoothName, dataName)
                    twccommon.Log.error(err)
                    raise RuntimeError, err
            else:
                err = 'Application [%s] not found.' % smoothingApplication
                twccommon.Log.error(err)
                raise RuntimeError, err
        else:
            twccommon.Log.warning('Image smoothing NOT enabled.')
        cmd = NICE_VALUE
        cmd += _config.imageCutTool
        cmd += ' -i %s -o %s -a0,0,0' % (dataName, tempName)
        twccommon.Log.debug('Adjusting %s' % cmd)
        rc = os.system(cmd)
        if rc != 0:
            err = 'Image failed to adjust for %s.' % finalName
            twccommon.Log.error(err)
            raise RuntimeError, err
        os.unlink(dataName)
        os.rename(tempName, finalName)
        buildIndexFile(rootName, bname)

    return


NICE_VALUE = 'nice -20 '
_config = None

# okay decompiling /tmp/toolnb/42bd9ecfbdcbc0a496b3448da836d548/main.pyc
setImageData("radar.us", '/twc/data/volatile/images/radar/us/1758982500.1758996831.tif')