Exemple #1
0
 def POST(self, table_name):
     try:
         pos = [
             a for a in AgentTma.select(AgentTma.q.AgentType == 2)
             if a.table_name == table_name
         ][0]
     except IndexError:
         return web.notfound()
     inp = web.input()
     sql = "SELECT id FROM tma WHERE agent_id=%s AND waktu='%s' AND jam='%s'" % (
         pos.id, to_date(inp.waktu), inp.jam)
     rs = conn.queryAll(sql)
     print 'pos.id: ', pos.id
     if pos.id >= 200 and pos.id not in [231, 233]:
         inp_manual = float(inp.tma) - pos.DPL
     else:
         inp_manual = float(inp.tma)
     print pos.sqlmeta.asDict()
     if not rs:
         tma = TinggiMukaAir(agent=pos,
                             waktu=to_date(inp.waktu),
                             jam=inp.jam,
                             manual=inp_manual)
         #pub_object(tma)
     return web.redirect('/adm/tma/' + table_name, absolute=True)
Exemple #2
0
 def GET(self):
     tanggal = web.input().get('d')
     if not tanggal:
         tanggal = datetime.date.today() - datetime.timedelta(days=1)
     else:
         try:
             tanggal = to_date(tanggal)
         except:
             tanggal = to_date(tanggal)
     HIDE_THIS = [a.strip() for a in open('HIDE_ARR.txt').read().split(',')]
     agents = Agent.select(
         AND(OR(Agent.q.AgentType == KLIMATOLOGI, Agent.q.AgentType == 0.0),
             Agent.q.expose == True)).orderBy((
                 'wilayah',
                 'urutan',
             ))
     agents = [a for a in agents if a.table_name not in HIDE_THIS]
     data = []
     for a in agents:
         rain = a.get_segmented_rain(tanggal)
         row = {
             'pos': a.cname or a.AgentName,
             'id': a.AgentId,
             'telemetri': rain.get('total'),
             'manual': rain.get('manual')
         }
         data.append(row)
     return json.dumps({
         'tanggal': tanggal,
         'curahhujan': data
     },
                       default=json_serialize)
Exemple #3
0
    def GET(self, pid):
        try:
            pos = Agent.get(pid)
        except SQLObjectNotFound:
            return web.notfound()
        try:
            dari = to_date(web.input().dari)
            dari = datetime.datetime.combine(dari, datetime.time(7, 0, 0))
            hingga = to_date(web.input().hingga)
            hingga = datetime.datetime.combine(hingga,
                                               datetime.datetime.now().time())
        except:
            hingga = datetime.datetime.now()
            dari = hingga - datetime.timedelta(days=2)
            dari = dari.replace(hour=7, minute=0, second=0)
        #print dari, hingga
        tma_trend = pos.get_log_tma(dari, hingga)

        series = [
            '{x: %s, y: %s}' %
            (int(a[0].strftime('%s')) + a[1].seconds, float(a[2] or 0) * 0.01)
            for a in tma_trend
        ]
        data_series = [{
            'nama': pos.cname,
            'series': ', '.join(series),
            'satuan': 'M'
        }]

        return render.bendungan.show_tma({
            'pos': pos,
            'data': data_series,
            'dari': dari,
            'hingga': hingga
        })
Exemple #4
0
 def curah_hujan_home(self, tanggal=None, paper=False):
     if not tanggal:
         tanggal = datetime.date.today() - datetime.timedelta(days=1)
     else:
         try:
             tanggal = to_date(tanggal)
         except:
             tanggal = to_date(tanggal)
     HIDE_THIS = [a.strip() for a in open('HIDE_ARR.txt').read().split(',')]
     agents = AgentCh.select(
         AND(
             OR(AgentCh.q.AgentType == KLIMATOLOGI,
                AgentCh.q.AgentType == 0.0),
             AgentCh.q.expose == True)).orderBy((
                 'wilayah',
                 'urutan',
             ))
     agents = [a for a in agents if a.table_name not in HIDE_THIS]
     data = [{
         'pos': a,
         'ch': a.get_segmented_rain(tanggal)
     } for a in agents]
     sebelum = tanggal - datetime.timedelta(days=1)
     sesudah = tanggal + datetime.timedelta(days=1)
     template_render = render.curahhujan.harian_all
     if paper:
         template_render = render_plain.curahhujan.harian_paper
     return template_render(curah_hujan=data,
                            meta={
                                'now': tanggal,
                                'before': sebelum,
                                'after': sesudah
                            },
                            wilayah=WILAYAH)
Exemple #5
0
 def GET(self):
     sampling = web.input().get('sampling')
     if sampling:
         sampling = to_date(sampling)
     else:
         sampling = datetime.date.today()
     dari = int(sampling.strftime('%s'))
     hingga = int((sampling + datetime.timedelta(days=1)).strftime('%s'))
     print 'dari:', dari
     print 'hingga:', hingga
     device = web.input().get("d")
     result = [
         r for r in db.sensors.find(
             {
                 '$and': [{
                     'sampling': {
                         '$gte': dari
                     }
                 }, {
                     'sampling': {
                         '$lte': hingga
                     }
                 }]
             }, {
                 '_id': 0
             }).sort('sampling', 1)
     ]
     return json.dumps(result)
Exemple #6
0
 def GET(self):
     ''''''
     web.header('Content-Type', 'application/json')
     web.header('Access-Control-Allow-Origin', '*')
     inp = web.input()
     sampling = inp.get('sampling')
     fields = 'curahhujan,tma6,vol6,tma12,vol12,tma18,vol18,inflow_q,inflow_v,intake_q,intake_v,spillway_q,spillway_v,vnotch_tin1,vnotch_q1,vnotch_tin2,vnotch_q2,vnotch_tin3,vnotch_q3,a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4,c4,a5,b5,c5'.split(',')
     n = datetime.datetime.now()
     waktu = datetime.datetime(n.year, n.month, n.day)
     if sampling:
         d = to_date(sampling)
         waktu = datetime.datetime(d.year, d.month, d.day)
     wds = [d for d in WadukDaily.select(WadukDaily.q.waktu==waktu)]
     out = []
     for d in wds:
         row = dict([(a, d.sqlmeta.asDict().get(a)) for a in fields])
         row.update({'sampling': str(d.waktu), 'name': d.pos.table_name})
         if d.pos and d.pos.prima_id:
             sql = "SELECT CONCAT(SamplingDate, ' ', SamplingTime) \
             AS sampling, WLevel * 0.01 \
             FROM %s \
             WHERE CONCAT(SamplingDate, ' ', SamplingTime) <= NOW() \
             ORDER BY SamplingDate DESC, SamplingTime DESC \
             LIMIT 0, 1" % d.pos.table_name
             rst = conn.queryAll(sql)
             if rst:
                 row.update({'sampling_wlevel': rst[0][0], 'wlevel':
                             float(rst[0][1] or 0)})
         out.append(row)
     return json.dumps(out)
Exemple #7
0
    def GET(self, oid):
        try:
            bendung = Agent.get(int(oid))
        except SQLObjectNotFound:
            return web.notfound()
        inp = web.input()
        if inp.get('periode'):
            periode = to_date(inp.periode)
        else:
            periode = datetime.date.today()
        if periode.month < 11:
            periode = datetime.date(periode.year - 1, 11,
                                    1)  # 1 Nop tahun lalu
        else:
            periode = datetime.date(periode.year, 11, 1)

        tanggal = periode
        if periode.month > 10:
            tanggal = datetime.date(tanggal.year + 1, 11, 1)

        if tanggal.year <= 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=1))
                rr.append(periode.replace(day=16))
                periode += datetime.timedelta(days=jhar[i])
        if tanggal.year > 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=15))
                rr.append(periode.replace(day=jhar[i]))
                periode += datetime.timedelta(days=jhar[i])
        sql = "SELECT waktu, po_tma, po_inflow_q, po_inflow_v, \
                po_outflow_q, po_outflow_v, \
                tma6, vol6, inflow_q, inflow_v, intake_q, intake_v, po_bona, po_bonb, vol_bona, vol_bonb \
                FROM waduk_daily \
                WHERE waktu IN (%s) AND pos_id=%s \
                ORDER BY waktu" % (','.join(["'" + str(i) + "'"
                                             for i in rr]), oid)
        rst = Agent._connection.queryAll(sql)
        sql_realisasi = "SELECT \
                tma6, vol6, inflow_q, inflow_v, intake_q, intake_v \
                FROM waduk_daily \
                WHERE pos_id=%s AND waktu BETWEEN %s AND %s \
                ORDER BY waktu"

        meta = {
            'rst': rst,
            'daily': [],
            'dari': periode,
            'hingga': periode,
            'tanggal': tanggal
        }
        return render.bendungan.operasi(bendung, meta)
Exemple #8
0
    def GET(self):
        try:
            tanggal = to_date(web.input().get('d'))
        except:
            tanggal = datetime.date.today() - datetime.timedelta(days=1)
        poses = dict([l.split('\t') for l in open(
            'agent_table.txt').readlines()])
        klimat_manual = KlimatManual.select(func.DATE(KlimatManual.q.sampling) == tanggal)

        return render.klimatologi.index({'pos': klimat_manual, 'tanggal': tanggal, 'sebelum': tanggal - datetime.timedelta(days=1), 'sesudah': tanggal + datetime.timedelta(days=1)})
Exemple #9
0
 def GET(self):
     try:
         tanggal = to_date(web.input().get('d'))
     except:
         tanggal = datetime.date.today()
     poses = dict([l.split('\t') for l in open(
         'agent_table.txt').readlines()])
     agent_klimatologi = [Agent.get(poses.get(a)) for a in KLIMATOLOGI_POS]
     agent_klimatologi = [(a, a.get_segmented_klimatologi(tanggal)) for a in agent_klimatologi]
     return render.klimatologi.index({'pos': agent_klimatologi, 'tanggal': tanggal, 'sebelum': tanggal - datetime.timedelta(days=1), 'sesudah': tanggal + datetime.timedelta(days=1)})
Exemple #10
0
 def POST(self, table_name):
     try:
         pos = [
             a for a in AgentCh.select(AgentCh.q.AgentType == 1)
             if a.table_name == table_name
         ][0]
     except IndexError:
         return web.notfound()
     inp = web.input()
     sql = "SELECT id FROM curahhujan WHERE agent_id=%s AND waktu='%s'" % (
         pos.id, to_date(inp.waktu))
     rs = conn.queryAll(sql)
     if not rs:
         ch = CurahHujan(agent=pos,
                         waktu=to_date(inp.waktu),
                         manual=float(inp.hujan))
         # publish to MQTT Broker
         pub_object(ch)
     return web.redirect('/adm/ch/' + table_name, absolute=True)
Exemple #11
0
 def GET(self):
     sampling = web.input().get('sampling')
     if not sampling:
         sampling = datetime.date.today()
     else:
         sampling = to_date(sampling)
     #sampling = datetime.date(2019, 11, 16)
     kegiatan = Kegiatan.select().filter(
         Kegiatan.q.sampling==sampling).orderBy('table_name, petugas')
     return render.kegiatan.index({'kegiatan': kegiatan, 'sampling':
                                   sampling})
Exemple #12
0
 def GET(self, pid):
     try:
         oid = Agent.select(Agent.q.prima_id == pid)[0].AgentId
         bd = Agent.get(oid)
         if bd.AgentType != 3:
             raise web.notfound(404)
     except:
         raise web.notfound(404)
     tanggal = web.input().get('d')
     if not tanggal:
         tanggal = datetime.date.today()
     else:
         tanggal = to_date(tanggal)
     try:
         bendungan = Agent.get(int(oid))
         if bendungan.AgentType != 3:
             raise SQLObjectNotFound
     except SQLObjectNotFound:
         return web.notfound(404)
     sql = "SELECT SamplingDate, SamplingTime, WLevel, Temperature, Humidity, Rain4 FROM %(table_name)s \
             ORDER BY SamplingDate DESC, SamplingTime DESC \
             LIMIT 0, 25" % ({
         'table_name': bendungan.table_name
     })
     rst = [(int(r[0].strftime('%s')) + r[1].seconds, r[2], r[3], r[4],
             r[5]) for r in bendungan._connection.queryAll(sql)]
     latest = {}
     if not rst:
         sql = "SELECT SamplingDate, SamplingTime, WLevel, Temperature, Humidity, Rain4 FROM %(table_name)s \
             ORDER BY SamplingDate, SamplingTime LIMIT 0, 25" % ({
             'table_name':
             bendungan.table_name
         })
         rst = [(int(r[0].strftime('%s')) + r[1].seconds, r[2], r[3], r[4],
                 r[5]) for r in bendungan._connection.queryAll(sql)]
     d = rst[0]
     samp = datetime.datetime.fromtimestamp(d[0])
     if samp.date() == datetime.date.today():
         sampling = samp.strftime('%H:%M')
     else:
         sampling = samp.strftime('%d %b %H:%M')
     latest = dict(sampling=sampling,
                   wlevel=d[1] / 100.0,
                   temperature=d[2],
                   humidity=d[3],
                   sq=d[4])
     return render.bendungan.liveprima(bendungan,
                                       meta={
                                           'now':
                                           tanggal.strftime('%d %b %y'),
                                           'tma': rst,
                                           'latest_sampling': latest
                                       })
Exemple #13
0
    def GET(self, did=None):
        '''@params:
            did: (str)device id
            sampling: (datetime'''
        conn = pg.connect(dbname="bsolo3", user="******", password="******")
        cursor = conn.cursor()

        web.header('Content-Type', 'text/json')
        web.header('Access-Control-Allow-Origin', '*')
        if did:
            sql = "SELECT content FROM raw WHERE content->>'device' LIKE %s ORDER BY id DESC LIMIT 35"
            cursor.execute(sql, ('%/' + did + '/%', ))
            '''
            regx = re.compile('.*'+did+'/', re.IGNORECASE)
            rst = [r for r in db.sensors.find({"device": regx},
                                                {"_id": 0}).sort(
                                                    "_id", -1).limit(25)]
            '''
            rst = [r[0] for r in cursor.fetchall()]
            if not rst:
                return web.notfound()
            if web.input().get('sampling', None):
                #try:
                sampling = to_date(web.input().get('sampling'))
                _dari = time.mktime(sampling.timetuple())
                _hingga = _dari + 86400
                # satu hari = 86400 ms
                '''
                    rst = [r for r in db.sensors.find(
                        {"$and": [{"device": regx},
                                  {"sampling": {"$gte": _dari}},
                                  {"sampling": {"$lt": _hingga}}]}, {_id: 0})]
                '''
                sql = "SELECT content FROM raw WHERE content->>'device' LIKE %s AND (content->>'sampling')::int >= %s AND (content->>'sampling')::int <= %s"
                cursor.execute(sql, ('%/' + did + '/%', _dari, _hingga))
                rst = [r[0] for r in cursor.fetchall()]
                #except Exception as e:
                #    print e
            out = {}
            if web.input().get('raw'):
                out['periodic'] = rst
            else:
                out['periodic'] = [map_periodic(r) for r in rst]
            out["bsolo_logger"] = BSOLO_LOGGER.get(did)
        else:
            out = []
            sql = "SELECT DISTINCT(content->>'device') FROM raw"
            cursor.execute(sql)
            out = [r[0] for r in cursor.fetchall()]
        cursor.close()
        conn.close()

        return json.dumps(out)
Exemple #14
0
def import_rtow(file_input):
    '''Mengimport data RTOW (setahun) dari file excel
            nop1 | nop2 | des1 | des2 | ...
    tma
    outflow_q
    inflow_q
    bon_a
    bon_b


    '''
    # deteksi pemisah data TAB, ;,','
    seps = '\t_;_,_|'.split('_')
    lines = open(file_input).readlines()
    header = lines[1].strip()
    sep = None
    for s in seps:
        if len(header.split(s)) > 5:
            sep = s
            cols = header.split(s)
            numcol = len(cols)
            break
    if not sep:
        msg = 'Tidak ditemukan pemisah kolom yang valid. (' + '_'.join(seps)
        ret = dict(ok=False, msg=msg)
        return ret

    try:
        nama_bendungan = lines[0].strip().split(sep)[0]
    except IndexError:
        nama_bendungan = lines[0].strip()
    bd_names = dict([(a.table_name, a.AgentId)
                     for a in AgentBd.select(AgentBd.q.AgentType == 3)])
    if nama_bendungan not in bd_names.keys():
        ret = dict(ok=False, msg=','.join(bd_names))
        return ret
    data = []
    for i in range(len(lines) - 2):
        i += 2
        line = lines[i].strip().split(sep)
        waktu = to_date(line[0])
        val = dict(waktu=waktu, posID=bd_names.get(nama_bendungan))
        for j in (1, 2, 3, 4, 5, 6, 7, 8):
            try:
                val[cols[j]] = float(line[j].replace(',', '.'))
            except ValueError:
                val[cols[j]] = None
        data.append(val)
    ret = dict(ok=True,
               pos_id=bd_names.get(nama_bendungan),
               table_name=nama_bendungan,
               object=data)
    return ret
Exemple #15
0
    def GET(self, pid):
        try:
            pos = AgentCh.get(pid)
        except SQLObjectNotFound:
            return web.notfound()

        HIDE_THIS = [a.strip() for a in open('HIDE_ARR.txt').read().split(',')]
        agents = AgentCh.select(
            AND(
                OR(AgentCh.q.AgentType == KLIMATOLOGI,
                   AgentCh.q.AgentType == 0.0),
                AgentCh.q.expose == True)).orderBy((
                    'wilayah',
                    'urutan',
                ))
        agents = [a for a in agents if a.table_name not in HIDE_THIS]

        now = datetime.datetime.now()
        try:
            tanggal = to_date(web.input().get('d'))
        except:
            tanggal = datetime.date.today()
            if now.hour < 9:
                tanggal = tanggal - datetime.timedelta(days=1)
        ch_per_jam = pos.get_aday_ch(tanggal)
        sebelum = tanggal - datetime.timedelta(days=1)
        if tanggal == datetime.date.today():
            sesudah = None
        else:
            sesudah = tanggal + datetime.timedelta(days=1)
        start = datetime.datetime.combine(tanggal,
                                          now.time().replace(hour=7, minute=0))

        labels = [(start + datetime.timedelta(hours=h)).hour
                  for h in range(24)]
        ch_set = []
        ch_ = dict([(c[0].hour, c[1]) for c in ch_per_jam])
        for l in labels:
            ch_set.append((l, float(ch_.get(l, 0) or '0')))
        return render.curahhujan.jamjaman({
            'pos': pos,
            'tanggal': tanggal,
            'poses': agents,
            'wilayah': WILAYAH,
            'sebelum': sebelum,
            'sesudah': sesudah,
            'data': {
                'categories': labels,
                'series': ch_set
            }
        })
Exemple #16
0
 def GET(self):
     web.header('Content-Type', 'application/json')
     web.header('Access-Control-Allow-Origin', '*')
     inp = web.input()
     sampling = inp.get('sampling')
     n = datetime.datetime.now()
     waktu = n.replace(hour=0, minute=0, second=0, microsecond=0).date()
     if sampling:
         d = to_date(sampling)
         waktu = datetime.datetime(d.year, d.month, d.day).date()
     rst = [
         c.sqlmeta.asDict()
         for c in CurahHujan.select(CurahHujan.q.waktu == waktu)
     ]
     return json.dumps(rst, default=json_serialize)
 def GET(self):
     inp = web.input()
     if inp.get('sampling'):
         sampling = to_date(inp.sampling)
     else:
         sampling = datetime.date.today()
     tanggal = sampling
     bdgs = AgentBd.select(AgentBd.q.AgentType == 3).orderBy('wilayah')
     poses = dict([(a.table_name, a) for a in bdgs])
     daily_bd = dict([
         (w.pos.table_name, w)
         for w in WadukDaily.select(WadukDaily.q.waktu == tanggal)
     ])
     poses = [(poses.get(p), daily_bd.get(p))
              for p in [p.table_name for p in bdgs]]
     return render.adm.bendungan.index({'poses': poses, 'tanggal': tanggal})
    def GET(self, table_name, id=None):
        inp = web.input()
        tgl = to_date(
            inp.get('sampling',
                    datetime.date.today().strftime('%Y-%m-%d')))
        bd_id = BENDUNGAN_DICT.get(table_name)
        pos = AgentBd.get(int(bd_id))
        if id:
            kegiatan = Kegiatan.get(int(id))
            return render.adm.bendungan.kegiatan_show(kegiatan=kegiatan)
        if inp.get('sampling') and inp.get('paper'):
            sql = "SELECT k.id, k.petugas, k.uraian, f.id, f.filepath FROM \
                    kegiatan k, foto f \
                    WHERE f.obj_type='kegiatan' AND k.id=f.obj_id AND DATE(k.sampling)='%s' \
                    AND k.table_name='%s'" % (tgl.strftime('%Y-%m-%d'),
                                              table_name)
            rst = [{
                'kid': r[0],
                'p': r[1],
                'u': r[2],
                'fid': r[3],
                'f': r[4]
            } for r in conn.queryAll(sql)]
            print rst
            return render_plain.adm.bendungan.kegiatan_paper(pos, tgl, rst)

        sql = "SELECT k.petugas, DATE(k.sampling), k.uraian, k.id \
                FROM kegiatan k, foto f \
                WHERE f.obj_type='kegiatan' AND k.id=f.obj_id \
                AND k.table_name='%s' AND YEAR(k.sampling)=%s \
                AND MONTH(k.sampling)=%s \
                ORDER BY DATE(k.sampling) DESC" % (table_name, tgl.year,
                                                   tgl.month)
        rows = [r for r in conn.queryAll(sql)]
        tgls = list(set(r[1] for r in rows))
        result = dict([(t, {}) for t in tgls])
        for r in rows:
            if r[0] in result[r[1]]:
                result[r[1]][r[0]].append({'uraian': r[2], 'kid': r[3]})
            else:
                result[r[1]][r[0]] = [{'uraian': r[2], 'kid': r[3]}]
        return render.adm.bendungan.kegiatan(
            dict(pos=pos,
                 urutan_kegiatan=sorted(result, reverse=True),
                 petugas=PETUGAS_CHOICES,
                 kegiatan=result,
                 tgl=tgl))
Exemple #19
0
    def GET(self):
        try:
            tanggal = to_date(web.input().get('d'))
        except:
            tanggal = datetime.date.today()
        AGENT_TABLE = dict([
            a.strip().split('\t') for a in open('agent_table.txt').readlines()
        ])
        poses = []
        db = Agent._connection
        for a in DEBIT_POS.keys():
            pos = Agent.get(int(AGENT_TABLE.get(a)))
            if pos.lengkung_kapasitas:
                pos.lengkung_series = [
                    map(float,
                        s.strip().split('\t'))
                    for s in pos.lengkung_kapasitas.split('\n')
                ]
            formula = DEBIT_POS.get(a)
            if formula:
                pos.debit_formula = formula
            sql = "SELECT CONCAT(SamplingDate, ' ', SamplingTime), WLevel*0.01 AS WLevel FROM %s ORDER BY SamplingDate DESC, SamplingTime DESC LIMIT 0, 1" % (
                a, )
            rst = db.queryAll(sql)
            try:
                tma = float(rst[0][1])
                pos.tma = {
                    'tanggal':
                    datetime.datetime.strptime(rst[0][0], '%Y-%m-%d %H:%M:%S'),
                    'tma':
                    tma
                }
                debit = formula.get('a') * (tma -
                                            formula.get('b'))**formula.get('c')
                pos.debit = debit
            except:
                pos.tma = {'tanggal': None, 'tma': None}
                pos.debit = None

            poses.append(pos)

        return render.tma.lengkung_debit({'poses': poses, 'tanggal': tanggal})
Exemple #20
0
    def GET(self, bd):
        '''Tampilkan data Piezometer untuk lokasi "bd"
        Default tampilkan data terakhir, kecuali ada sampling yang diinginkan
        Menampilkan data selama _bulan_terpilih_
        '''
        inp = web.input()
        sampling = inp.get('sampling', None)
        bendungans = dict(
            [a.strip().split() for a in open('agent_table.txt').readlines()])
        id_bdg = bendungans.get(bd)
        if not id_bdg:
            return web.notfound()
        sql = "SELECT MAX(waktu) FROM waduk_daily WHERE pos_id=%s" % id_bdg
        rst = Agent._connection.queryAll(sql)
        if not sampling:
            sampling = rst[0]

        sampling = sampling and to_date(sampling) or None

        pos = Agent.get(id_bdg)

        if sampling.month == datetime.date.today().month:
            wds = [
                wd for wd in WadukDaily.select(
                    WadukDaily.q.pos == pos).orderBy('-waktu')
                if wd.waktu.year == sampling.year
                and wd.waktu.month == sampling.month
            ]
        else:
            wds = [
                wd for wd in WadukDaily.select(WadukDaily.q.pos == pos)
                if wd.waktu.year == sampling.year and wd.waktu.month ==
                sampling.month and wd.waktu.day <= datetime.date.today().day
            ]

        return render.bendungan.piezometer({
            'pos': pos,
            'bulan': sampling,
            'wds': wds
        })
    def POST(self, table_name):
        inp = web.input()
        if inp.get('state') == 'hapus':
            kegiatan_id = inp.get('kegiatan_id')
            foto_id = inp.get('foto_id')
            filename = inp.get('filename')

            deletekeg = Delete('kegiatan', where='id=' + kegiatan_id)
            query1 = conn.sqlrepr(deletekeg)
            conn.query(query1)

            deleteft = Delete('foto', where='id=' + foto_id)
            query2 = conn.sqlrepr(deleteft)
            conn.query(query2)

            if os.path.exists(filename):
                os.remove(filename)

            return "ok"
        else:
            keg = Kegiatan(table_name=table_name,
                           petugas=inp.get('petugas'),
                           uraian=inp.get('uraian'),
                           sampling=to_date(inp.get('waktu')),
                           cuser=session.username)
            filename = FOTO_PATH + table_name + '_kegiatan_' + str(
                keg.id) + '_' + inp.get('filename').lower()
            if not os.path.isdir(FOTO_PATH):
                os.mkdir(FOTO_PATH)
            with open(filename, 'wb') as f:
                f.write(base64.b64decode(inp.get('data').split(',')[1]))
            foto = Foto(filepath=filename,
                        keterangan=inp.get('uraian'),
                        obj_type='kegiatan',
                        obj_id=keg.id,
                        cuser=session.get('username'))
            keg.foto = foto
            web.header('Content-Type', 'application/json')
            return json.dumps({"Ok": "true"})
Exemple #22
0
    def GET(self, pid):
        try:
            pos = AgentCh.get(pid)
        except SQLObjectNotFound:
            return web.notfound()
        now = datetime.datetime.now()
        try:
            tanggal = to_date(web.input().get('d'))
        except:
            tanggal = datetime.date.today()
            if now.hour < 9:
                tanggal = tanggal - datetime.timedelta(days=1)
        ch_per_jam = pos.get_aday_ch(tanggal)
        sebelum = tanggal - datetime.timedelta(days=1)
        if tanggal == datetime.date.today():
            sesudah = None
        else:
            sesudah = tanggal + datetime.timedelta(days=1)
        start = datetime.datetime.combine(tanggal,
                                          now.time().replace(hour=7, minute=0))

        labels = [(start + datetime.timedelta(hours=h)).hour
                  for h in range(24)]
        ch_set = []
        ch_ = dict([(c[0].hour, c[1]) for c in ch_per_jam])
        for l in labels:
            ch_set.append((l, float(ch_.get(l, 0) or '0')))
        return render.curahhujan.jamjaman({
            'pos': pos,
            'tanggal': tanggal,
            'sebelum': sebelum,
            'sesudah': sesudah,
            'data': {
                'categories': labels,
                'series': ch_set
            }
        })
Exemple #23
0
    def GET(self, bd):

        if bd[3:] in NO_VNOTCH:
            return render.bendungan.vnotch_fail({'bd': bd, 'no_vnotch': True})
        if bd[3:] in FAIL_VNOTCH:
            return render.bendungan.vnotch_fail({
                'bd': bd,
                'fail_vnotch': True
            })
        inp = web.input()
        sampling = inp.get('sampling')
        sampling = sampling and to_date(sampling) or datetime.date.today()

        pos = [
            a for a in Agent.select(Agent.q.AgentType == 3)
            if a.table_name == bd
        ][0]
        if sampling.month == datetime.date.today().month:
            wds = [
                wd for wd in WadukDaily.select(
                    WadukDaily.q.pos == pos).orderBy('waktu')
                if wd.waktu.year == sampling.year
                and wd.waktu.month == sampling.month
            ]
        else:
            wds = [
                wd for wd in WadukDaily.select(WadukDaily.q.pos == pos)
                if wd.waktu.year == sampling.year and wd.waktu.month ==
                sampling.month and wd.waktu.day <= datetime.date.today().day
            ]

        return render.bendungan.vnotch({
            'pos': pos,
            'bulan': sampling,
            'wds': wds
        })
Exemple #24
0
    def POST(self, table_name):
        agent_id = dict([a.split('\t') for a in open('agent_table.txt').readlines()]).get(table_name)
        pos = Agent.get(agent_id)
        try:
            pos = [a for a in AgentCh.select(AgentCh.q.AgentType==1) if a.table_name == table_name][0]
        except IndexError:
            return web.notfound()
        inp = web.input()
        float_list = 'ch_m,temp_min_m,temp_max_m,humi_m,kec_angin_m,penguapan_m'.split(',')
        for kol in float_list:
            if inp.get(kol):
                inp.update({kol: float(inp.get(kol))})
            else:
                inp.update({kol: None})

        inp.update({'penyinaran_m': inp.get('penyinaran_m') and int(inp.get('penyinaran_m')) or None})
        inp.update({'agentID': pos.id, 'cuser': session.username, 'cdate': datetime.datetime.now()})
        inp.update({'sampling': to_date(inp.get('sampling'))})
        if 'csrf_token' in inp:
            del inp['csrf_token']
        rst = KlimatManual.select(AND(KlimatManual.q.agent==pos, 
                func.DATE(KlimatManual.q.sampling)==inp.get('sampling')))
        if rst.count():
            rst[0].set(**inp)
        else:
            km = KlimatManual(**inp)

        # table curahhujan perlu ditambah/update
        ch = CurahHujan.select(AND(CurahHujan.q.agent==pos,
            func.DATE(CurahHujan.q.waktu) == inp.get('sampling')))
        if ch.count():
            ch[0].set(**{'manual': float(inp.get('ch_m', 0))})
        else:
            ch = CurahHujan(**{'waktu': inp.get('sampling'), 
                'manual': float(inp.get('ch_m', 0)), 'agent': pos})
        return web.redirect('/adm/klimatologi/' + table_name, absolute=True)
Exemple #25
0
    def GET(self, oid):
        try:
            bendung = Agent.get(int(oid))
        except SQLObjectNotFound:
            return web.notfound()

        inp = web.input()
        if inp.get('periode'):
            periode = to_date(inp.periode)
        else:
            periode = datetime.date.today()
        year = datetime.date.today().year
        if periode.month < 11 and periode.year == year:
            periode = datetime.date(periode.year - 1, 11,
                                    1)  # 1 Nop tahun lalu
            year = datetime.date.today().year
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month > 10 and periode.year == year:
            periode = datetime.date(periode.year, 11, 1)  # 1 Nop tahun lalu
            year = datetime.date.today().year + 1
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month < 11 and periode.year > year:
            periode = datetime.date(periode.year - 1, 11, 1)
            year = datetime.date.today().year + 1
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month > 10 and periode.year > year:
            periode = datetime.date(periode.year, 11, 1)
            year = datetime.date.today().year
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month < 11 and periode.year < year:
            periode = datetime.date(periode.year - 1, 11, 1)
            year = datetime.date.today().year + 1
            start = datetime.date(year=year - 1, month=11, day=1)
        if periode.month > 10 and periode.year < year:
            periode = datetime.date(periode.year, 11, 1)
            year = datetime.date.today().year
            start = datetime.date(year=year - 1, month=11, day=1)

        #print start
        oneday = datetime.timedelta(days=1)
        oneweek = datetime.timedelta(days=7)

        while start.weekday() != 0:
            start += oneday

        days = []
        while start.year <= year:
            days.append(start.strftime("%Y-%m-%d"))
            start += oneweek
            if start.month == 11 and start.year == year:
                break
        #print days

        sql = "SELECT waktu, a1, b1, c1, a2, b2, c2, a3, b3, c3, a4, b4, c4, a5, b5, c5, vnotch_q1, vnotch_q2, vnotch_q3, vnotch_tin1, vnotch_tin2, vnotch_tin3 \
                FROM waduk_daily \
                WHERE waktu IN (%s) AND pos_id=%s \
                ORDER BY waktu" % (','.join(["'" + str(i) + "'"
                                             for i in days]), oid)

        rst2 = Agent._connection.queryAll(sql)

        #-----menambahkan nilai curah hujan keesokan hari nya(manipulasi database hujan)------
        j = []
        for f in rst2:
            j.append(f[0])

        day_ch = []
        for dch in j:
            d_ch = dch + datetime.timedelta(days=1)
            day_ch.append(d_ch)

        c_h = []
        for a in day_ch:
            wd = WadukDaily.select(
                AND(WadukDaily.q.waktu == a, WadukDaily.q.pos == oid))
            try:
                wdch = wd[0].curahhujan
            except IndexError:
                wdch = None
            c_h.append(wdch)

        z = []
        for b, d in zip(rst2, c_h):
            z.append((b, d))

        #print rst2

        #periode = datetime.date.today()
        #periode = datetime.date(periode.year - 1, 11, 1) # 1 Nop tahun lalu

        tanggal = periode
        if periode.month > 10:
            tanggal = datetime.date(tanggal.year + 1, 11, 1)

        if tanggal.year <= 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=1))
                rr.append(periode.replace(day=16))
                periode += datetime.timedelta(days=jhar[i])
        if tanggal.year > 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=15))
                rr.append(periode.replace(day=jhar[i]))
                periode += datetime.timedelta(days=jhar[i])

        sql = "SELECT waktu, po_tma, po_inflow_q, po_inflow_v, \
                po_outflow_q, po_outflow_v, \
                tma6, vol6, inflow_q, inflow_v, intake_q, intake_v, po_bona, po_bonb, vol_bona, vol_bonb \
                FROM waduk_daily \
                WHERE waktu IN (%s) AND pos_id=%s \
                ORDER BY waktu" % (','.join(["'" + str(i) + "'"
                                             for i in rr]), oid)

        rst1 = Agent._connection.queryAll(sql)

        meta = {
            'rst1': rst1,
            'rst2': z,
            'dari': periode,
            'hingga': periode,
            'tanggal': tanggal
        }
        return render.bendungan.keamanan.vnotchh(bendung, meta)
Exemple #26
0
 def GET(self, oid):
     try:
         bd = Agent.get(oid)
         if bd.AgentType != 3:
             raise web.notfound(404)
     except:
         raise web.notfound(404)
     tanggal = web.input().get('d')
     if not tanggal:
         tanggal = datetime.date.today()
     else:
         tanggal = to_date(tanggal)
     sebelum = tanggal - datetime.timedelta(days=1)
     sesudah = tanggal + datetime.timedelta(days=1)
     try:
         bendungan = Agent.get(int(oid))
         if bendungan.AgentType != 3:
             raise SQLObjectNotFound
     except SQLObjectNotFound:
         return web.notfound(404)
     s_mamin = 5.8
     s_mabanjir = 10.8
     plotlines = ""
     tma = bendungan.get_segmented_tma_bendungan(tanggal)
     series = [[float(v), float(k)] for k, v in tma.get('kapasitas_series')]
     elev_series = []
     if tma.get('elevasi'):
         s_elevasi = (s_mabanjir -
                      s_mamin) / (bendungan.siaga3 - bendungan.siaga4) * (
                          tma.get('elevasi') - bendungan.siaga4) + s_mamin
         plotlines = "{ value: \
             "                  + str(s_elevasi) + "\
             , color: '#000099', width: 2, label: {text: '+"\
             + str(tma.get('elevasi') or 0) + "', style: {fontSize: 24, backgroundColor: 'white'}}}, "
         elev_series = [[e[0], tma.get('elevasi') or 0] for e in series]
     return render.bendungan.elevasi(
         bendungan,
         meta={
             'now':
             tanggal.strftime('%d %b %y'),
             'before':
             sebelum.strftime('%d %b %y'),
             'after':
             sesudah.strftime('%d %b %y'),
             'categories1':
             [float(d[1]) for d in tma.get('kapasitas_series')],
             's_ma_min':
             s_mamin,
             's_ma_normal': (s_mabanjir - s_mamin) /
             (bendungan.siaga3 - bendungan.siaga4) *
             (bendungan.siaga1 - bendungan.siaga4) + s_mamin,
             's_ma_banjir':
             s_mabanjir,
             'series':
             series,
             'elev_series':
             elev_series,
             'plotlines':
             plotlines,
             'tma':
             tma
         })
Exemple #27
0
    def GET(self, did=None):
        '''@params:
            did: (str)device id
            sampling: (datetime'''
        conn = pg.connect(dbname="bsolo3", user="******", password="******")
        cursor = conn.cursor()

        if did:
            sql = "SELECT content FROM raw WHERE content->>'device' LIKE %s ORDER BY id DESC LIMIT 35"
            cursor.execute(sql, ('%/' + did + '/%', ))
            '''
            regx = re.compile('.*'+did+'/', re.IGNORECASE)
            rst = [r for r in db.sensors.find({"device": regx},
                                                {"_id": 0}).sort(
                                                    "_id", -1).limit(25)]
            '''
            rst = [r[0] for r in cursor.fetchall()]
            if not rst:
                return web.notfound()
            if web.input().get('sampling', None):
                #try:
                sampling = to_date(web.input().get('sampling'))
                _dari = time.mktime(sampling.timetuple())
                _hingga = _dari + 86400
                # satu hari = 86400 ms
                '''
                    rst = [r for r in db.sensors.find(
                        {"$and": [{"device": regx},
                                  {"sampling": {"$gte": _dari}},
                                  {"sampling": {"$lt": _hingga}}]}, {_id: 0})]
                '''
                sql = "SELECT content FROM raw WHERE content->>'device' LIKE %s AND (content->>'sampling')::int >= %s AND (content->>'sampling')::int <= %s"
                cursor.execute(sql, ('%/' + did + '/%', _dari, _hingga))
                rst = [r[0] for r in cursor.fetchall()]
                if not rst:
                    return "Tidak Ada Data Pada Tanggal " + web.input().get(
                        'sampling')
                rst.reverse()
                #except Exception as e:
                #    print e
            out = {}
            if web.input().get('raw'):
                out['periodic'] = rst
            else:
                out['periodic'] = [map_periodic(r) for r in rst]
            out["bsolo_logger"] = BSOLO_LOGGER.get(did)
        else:
            out = []
            sql = "SELECT DISTINCT(content->>'device') FROM raw"
            cursor.execute(sql)
            out = [r[0] for r in cursor.fetchall()]
        cursor.close()
        conn.close()

        #testing from asnan (data untuk kategori grafik) tinggal return untuk melihat
        data = []
        kategori = []
        battery = []
        signal_quality = []
        tick = []
        are_tick = False
        distance = []
        are_distance = False
        wl_scale = []
        are_wl_scale = False

        sun_radiation_scale = []
        wind_dir_scale = []
        temperature_ambien_scale = []
        humidity_ambien_scale = []
        wind_speed_scale = []
        are_klimatologi = False

        r = out["periodic"]
        r.reverse()

        for j in r:
            if "distance" in j:
                are_distance = True
                distance.append(j.get("distance"))
            if "wl_scale" in j:
                are_wl_scale = True
                wl_scale.append(j.get("wl_scale"))
            if "tick" in j:
                if "sun_radiation_scale" and "wind_dir_scale" and "temperature_ambien_scale" and "humidity_ambien_scale" and "wind_speed_scale" in j:
                    are_klimatologi = True
                    sun_radiation_scale.append(j.get("sun_radiation_scale"))
                    wind_dir_scale.append(j.get("wind_dir_scale"))
                    temperature_ambien_scale.append(
                        j.get("temperature_ambien_scale"))
                    humidity_ambien_scale.append(
                        j.get("humidity_ambien_scale"))
                    wind_speed_scale.append(j.get("wind_speed_scale"))
                    tick.append(j.get("tick"))
                else:
                    are_tick = True
                    tick.append(j.get("tick"))

            kategori.append(j.get("sampling"))
            battery.append(j.get("battery"))
            signal_quality.append(j.get("signal_quality"))
        #end
        data.append({'name': 'signal_quality', 'data': signal_quality})
        data.append({'name': 'battery', 'data': battery})
        if are_distance == True:
            data.append({'name': 'distance', 'data': distance})
            jenis_prima = "SONAR"
        if are_wl_scale == True:
            data.append({'name': 'wl_scale', 'data': wl_scale})
            jenis_prima = "PRESSURE"
        if are_tick == True:
            data.append({'name': 'tick', 'data': tick})
            jenis_prima = "ARR"
        if are_klimatologi == True:
            data.append({'name': 'tick', 'data': tick})
            data.append({
                'name': 'sun_radiation_scale',
                'data': sun_radiation_scale
            })
            data.append({'name': 'wind_dir_scale', 'data': wind_dir_scale})
            data.append({
                'name': 'temperature_ambien_scale',
                'data': temperature_ambien_scale
            })
            data.append({
                'name': 'humidity_ambien_scale',
                'data': humidity_ambien_scale
            })
            data.append({'name': 'wind_speed_scale', 'data': wind_speed_scale})
            jenis_prima = "KLIMATOLOGI"

        conn = Agent._connection
        sql = "SELECT cname from agent where prima_id = %s" % ('"' + did + '"')
        result = conn.queryAll(sql)
        if result:
            pname = result[0][0]
        else:
            pname = "--"
        #print result

        return render.sensor.sensor_graph({
            'data': str(data),
            'kategori': str(kategori),
            'did': did,
            'jenis_prima': jenis_prima,
            'pname': pname
        })
Exemple #28
0
    def GET(self, pid):
        try:
            pos = Agent.get(pid)
        except SQLObjectNotFound:
            return web.notfound()
        pics = []
        if pos.table_name in CCTV_POS:
            # mendapatkan 3 nama file terakhir dari CCTV FTP Server
            try:
                ftp = FTP(FTP_HOST)
                ftp.login()
                ftp.cwd(CCTV_IMG_DIR + '/' + pos.table_name)
                nlst = ftp.nlst()
                pics = nlst[-3:]
            except:
                pics = [
                    'Fail to Connect CCTV Server',
                    'Fail to Connect CCTV Server',
                    'Fail to Connect CCTV Server'
                ]
        try:
            dari = to_date(web.input().dari)
            dari = datetime.datetime.combine(dari, datetime.time(7, 0, 0))
            hingga = to_date(web.input().hingga)
            hingga = datetime.datetime.combine(hingga,
                                               datetime.datetime.now().time())
        except:
            hingga = datetime.datetime.now()
            dari = hingga - datetime.timedelta(days=3)
            dari = dari.replace(hour=7, minute=0, second=0)

        tma_trend = pos.get_log_tma(dari, hingga)

        # membuat pola waktu per jam
        ch_patt = []
        t = int(dari.strftime('%s'))
        thingga = int(hingga.strftime('%s'))
        while t <= thingga:
            ch_patt.append([t, 0])
            t += 60 * 60  # 60 * 60 = 60 menit/1 jam
        ch_patt = dict(ch_patt)
        series = [[a[0], a[1], float(a[2] or 0) * 0.01] for a in tma_trend]
        print len(ch_patt), len(series)
        data_series = [{'nama': pos.cname, 'series': series, 'satuan': 'M'}]
        # menghitung Debit
        if pos.table_name in DEBIT_POS.keys():
            formula = DEBIT_POS.get(pos.table_name)
            if formula:
                series = []  # series of debit
                for tgl, jam, tma in data_series[0].get('series'):
                    tma_lokal = tma - pos.DPL
                    if tma_lokal - formula.get('b') > 0:
                        deb = formula.get('a') * (
                            tma_lokal - formula.get('b'))**formula.get('c')
                    else:
                        deb = 0
                    #dt = datetime.datetime.combine(tgl, datetime.time(0)) + jam - datetime.timedelta(hours=7)

                    _d = {
                        'sampling': int(tgl.strftime('%s')) + jam.seconds,
                        'tma': tma,
                        'debit': deb
                    }
                    series.append(
                        '{x: %(sampling)s, y: %(tma)s, debit: %(debit)s}' % _d)
                data_series[0]['series'] = '[' + ','.join(series) + ']'
        else:
            series = []
            for tgl, jam, tma in data_series[0].get('series'):
                #dt = datetime.datetime.combine(tgl, datetime.time(0)) + jam - datetime.timedelta(hours=7)
                #epoch = datetime.datetime.utcfromtimestamp(0)

                #_d = {'sampling': timedelta_total_seconds((dt - epoch)),
                #        'tma': tma}
                _d = {
                    'sampling': int(tgl.strftime('%s')) + jam.seconds,
                    'tma': tma
                }
                series.append('{x: %(sampling)s, y: %(tma)s}' % _d)
            data_series[0]['series'] = '[' + ','.join(series) + ']'

        # mencari data CH
        data_ch = {'nama': '', 'series': [], 'satuan': 'mm'}
        if pos.table_name in CAUSE_TABLE.keys():
            ch_list = CAUSE_TABLE.get(pos.table_name)
            AGENT_TABLE = dict([
                (a.table_name, a.AgentId) for a in Agent.select(
                    OR(Agent.q.AgentType == 0, Agent.q.AgentType == 1,
                       Agent.q.AgentType == 2))
            ])
            for ch in ch_list:
                print 'CH', ch
                pos_ch = Agent.get(AGENT_TABLE.get(ch))
                ch_trend = pos_ch.get_log(dari, hingga, False)
                series = [(int(a[0].strftime('%s')) + a[1].seconds,
                           float(a[2] or 0)) for a in ch_trend]
                for s in series:
                    nilai = ch_patt.get(s[0])
                    if not nilai:
                        ch_patt[s[0]] = s[1]
                    else:
                        ch_patt[s[0]] = nilai > s[1] and nilai or s[1]
                _t = {'nama': pos_ch.cname, 'series': series}
                #print ch, _t['series']
                if not _t.get('series'):
                    _t['series'] = []
                data_ch['nama'] += ', ' + pos_ch.cname
            data_ch['series'] = '[' + ','.join(
                ['{x: %s, y: %s}' % (k, v) for k, v in ch_patt.items()]) + ']'
        data_series.append(data_ch)
        #        print len(data_series[0]['series'])

        return render.tma.show_tma_ch({
            'pos': pos,
            'data': data_series,
            'dari': dari,
            'hingga': hingga,
            'pics': pics
        })
    def GET(self):
        inp = web.input()
        try:
            pola_operasi = open('pola_operasi.txt').read()
        except:
            pola_operasi = "Basah"
        if inp.get('periode'):
            periode = to_date(inp.periode)
        else:
            periode = datetime.date.today()
        if periode.month < 11:
            periode = datetime.date(periode.year - 1, 11,
                                    1)  # 1 Nop tahun lalu
        else:
            periode = datetime.date(periode.year, 11, 1)

        tanggal = periode
        if periode.month > 10:
            tanggal = datetime.date(tanggal.year + 1, 11, 1)

        if tanggal.year <= 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=1))
                rr.append(periode.replace(day=16))
                periode += datetime.timedelta(days=jhar[i])
        if tanggal.year > 2018:
            jhar = [30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31]
            rr = []
            for i in range(12):
                rr.append(periode.replace(day=15))
                rr.append(periode.replace(day=jhar[i]))
                periode += datetime.timedelta(days=jhar[i])
        sql = "SELECT pos_id, waktu, po_outflow_q, po_tma, po_outflow_v, id, po_bona, po_bonb, vol_bona, vol_bonb \
                FROM waduk_daily \
                WHERE waktu IN (%s) \
                ORDER BY pos_id, waktu" % ','.join(
            ["'" + str(i) + "'" for i in rr])
        rst = conn.queryAll(sql)
        bdgs = dict([(a.AgentId, a)
                     for a in AgentBd.select(AgentBd.q.AgentType == 3)])
        bids = list(set([r[0] for r in rst]))
        data = []
        bid = 0
        row = []
        for r in rst:
            if bid != r[0]:
                bid = r[0]
                row = [{
                    'id': r[5],
                    'tma': r[3],
                    'q': r[2],
                    'v': r[4],
                    'bona': r[6],
                    'bonb': r[7],
                    'volbona': r[8],
                    'volbonb': r[9]
                }]
                data.append((r[0], row))
                continue
            row.append({
                'id': r[5],
                'tma': r[3],
                'q': r[2],
                'v': r[4],
                'bona': r[6],
                'bonb': r[7],
                'volbona': r[8],
                'volbonb': r[9]
            })
        return render.adm.bendungan.rotw({
            'data': data,
            'bendungan': bdgs,
            'periode': rr,
            'pola_operasi': pola_operasi,
            'tanggal': tanggal
        })
    def POST(self, table_name):
        try:
            try:
                pos = [
                    a for a in AgentBd.select(AgentBd.q.AgentType == 3)
                    if a.table_name == table_name
                ][0]
            except IndexError:
                return web.notfound()
            inp = web.input()
            fields = 'curahhujan,tma,vol,inflow_q,inflow_v,intake_q,intake_v,spillway_q,spillway_v'.split(
                ',')
            koloms = 'tanggal,jam,tma'.split(',')
            form2_fields = 'tma,vol'.split(',')
            form3_fields = 'vnotch_tin1,vnotch_q1,vnotch_tin2,vnotch_q2,vnotch_tin3,vnotch_q3'.split(
                ',')
            form4_fields = 'a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4,c4,a5,b5,c5'.split(
                ',')
            # memeriksa apakah record pada Pos dan waktu(tgl) sudah ada pada tabel 'waduk_daily'
            try:
                wd = WadukDaily.select(
                    AND(WadukDaily.q.waktu == to_date(inp.waktu),
                        WadukDaily.q.pos == pos))[0]
                is_wd_exist = True
            except IndexError:
                wd = None
                is_wd_exist = False

            # memeriksa apakah table 'tma' telah terisi dari pos dan waktu
            tmas = [
                t for t in TinggiMukaAir.select(
                    AND(TinggiMukaAir.q.agent == pos, TinggiMukaAir.q.waktu ==
                        to_date(inp.waktu)))
            ]

            if inp.tahap == 'pagi':
                obj = {}
                for f in fields:
                    if inp.get(f):
                        nilai = float(inp.get(f))
                    else:
                        nilai = None
                    if f in 'tma,vol'.split(','):
                        obj.update({f + '6': nilai})
                    else:
                        obj.update({f: nilai})
                obj.update({'pos': pos, 'waktu': to_date(inp.waktu)})
                if not is_wd_exist:
                    wd = WadukDaily(**obj)
                else:
                    wd.set(**obj)
                # Mengupdate / Insert data TinggiMukaAir
                try:
                    tma = [t for t in tmas if t.jam == '6'][0]
                    tma.set(**{'jam': '6', 'manual': obj.get('tma6')})
                    tma.syncUpdate()
                except:
                    tma = TinggiMukaAir(
                        **{
                            'agent': pos,
                            'waktu': obj.get('waktu'),
                            'jam': '6',
                            'manual': obj.get('tma6'),
                            'origin': 'web'
                        })
                    tma.syncUpdate()
            elif inp.tahap in ('siang', 'sore'):
                # jika data pagi belum ada, untuk WadukDaily perlu error
                if not is_wd_exist:
                    session[
                        'err'] = "<strong style='margin-right: 10px'>P e r h a t i a n</strong>Data TMA Pagi tidak ditemukan."
                    return web.redirect('/adm/bendungan/' + table_name +
                                        '?sampling=' +
                                        inp.waktu.replace('/', '-'),
                                        absolute=True)
                per = inp.tahap == 'siang' and '12' or '18'
                if per == '12':
                    wd.tma12 = float(inp.get('tma'))
                    wd.vol12 = float(inp.get('vol'))
                elif per == '18':
                    wd.tma18 = float(inp.get('tma'))
                    wd.vol18 = float(inp.get('vol'))

                # Mengupdate / Insert data TinggiMukaAir
                try:
                    tma = [t for t in tmas if t.jam == per][0]
                    tma.set(**{'jam': per, 'manual': float(inp.get('tma'))})
                    tma.syncUpdate()
                except:
                    tma = TinggiMukaAir(
                        **{
                            'agent': pos,
                            'waktu': to_date(inp.waktu),
                            'jam': per,
                            'manual': float(inp.get('tma')),
                            'origin': 'web'
                        })
                    tma.syncUpdate()
            elif inp.tahap == 'vnotch':  # inputan vnotch
                # jika data pagi belum ada, untuk WadukDaily perlu error
                if not is_wd_exist:
                    session[
                        'err'] = "<strong style='margin-right: 10px'>P e r h a t i a n</strong>Data TMA Pagi tidak ditemukan."
                    return web.redirect('/adm/bendungan/' + table_name +
                                        '?sampling=' +
                                        inp.waktu.replace('/', '-'),
                                        absolute=True)
                obj = {}
                for f in form3_fields:
                    if inp.get(f):
                        obj.update({f: float(inp.get(f))})
                wd.set(**obj)
            elif inp.tahap == 'piezometer':
                # jika data pagi belum ada, untuk WadukDaily perlu error
                if not is_wd_exist:
                    session[
                        'err'] = "<strong style='margin-right: 10px'>P e r h a t i a n</strong>Data TMA Pagi tidak ditemukan."
                    return web.redirect('/adm/bendungan/' + table_name +
                                        '?sampling=' +
                                        inp.waktu.replace('/', '-'),
                                        absolute=True)
                obj = {}
                for f in form4_fields:
                    if inp.get(f):
                        obj.update({f: float(inp.get(f))})
                wd.set(**obj)

            return web.redirect('/adm/bendungan/' + table_name, absolute=True)

        except AttributeError:
            try:
                bendungan = [
                    a for a in AgentBd.select(AgentBd.q.AgentType == 3)
                    if a.table_name == table_name
                ][0]
                bendungan_id = bendungan.id
                print bendungan_id
            except IndexError:
                return web.notfound()
            inp = web.input()
            # memeriksa apakah record pada bendungan_id, tanggal dan jam sudah ada pada tabel 'bendung_alert'
            if inp.tahap == 'banjir':
                try:
                    ba = BendungAlert.select(
                        AND(BendungAlert.q.tanggall == to_date(inp.tanggall),
                            BendungAlert.q.bendungan == bendungan_id,
                            BendungAlert.q.jam == inp.jam))[0]
                    print ba
                    is_ba_exist = True
                except IndexError:
                    ba = None
                    is_ba_exist = False

                if inp.tahap == 'banjir':
                    obj = {
                        'bendunganID': bendungan_id,
                        'tanggall': to_date(inp.tanggall),
                        'jam': inp.jam,
                        'tmab': float(inp.tmab),
                        'spillwayb_q': float(inp.spillwayb_q)
                    }
                    if not is_ba_exist:
                        ba = BendungAlert(**obj)
                    else:
                        ba.set(**obj)
                return web.redirect('/adm/bendungan/' + table_name,
                                    absolute=True)

            if inp.tahap == 'chterkini':
                # memeriksa apakah record pada bendungan__id, tanggal dan jam sudah ada pada tabel 'curahhujan_terkini'

                try:
                    chkini = CurahHujanTerkini.select(
                        AND(
                            CurahHujanTerkini.q.tanggall == to_date(
                                inp.tanggall),
                            CurahHujanTerkini.q.bendungan == bendungan_id,
                            CurahHujanTerkini.q.jam == inp.jam))[0]
                    print chkini
                    is_chkini_exist = True
                except IndexError:
                    chkini = None
                    is_chkini_exist = False

                if inp.tahap == 'chterkini':
                    objj = {
                        'bendunganID': bendungan_id,
                        'tanggall': to_date(inp.tanggall),
                        'jam': inp.jam,
                        'ch_terkini': float(inp.ch_terkini)
                    }
                    if not is_chkini_exist:
                        chkini = CurahHujanTerkini(**objj)
                    else:
                        chkini.set(**objj)
                return web.redirect('/adm/bendungan/' + table_name,
                                    absolute=True)