Example #1
0
async def CheckNId(device):
    if models.ZbDevice.IsValidNId(device):
        sql_str = "select nid from rxg_zb_device where nid=?"
        row = await Get([sql_str, [device['nid']]])
        if row:
            raise rg_lib.RGError(rg_lib.ErrorType.SqliteIntegrityError())
        else:
            return True
    else:
        raise rg_lib.RGError(models.ErrorTypes.InvalidNetworkId())
Example #2
0
async def List(list_no, get_vals):
    """
    :param list_no: switch or sensor
    :param get_vals: boolean
    :return: devices
    """
    if list_no == 'switch':
        sql_str = "select id, nid, moduleid, name, device_no from rxg_zb_device where device_no=?"
        sql_args = [xy_lib.DeviceNo.XY_SWITCH]
    elif list_no == 'sensor':
        sql_str = """select r1.id id, 
                            r1.nid nid,
                            r1.moduleid moduleid,
                            r1.name name,  
                            r1.device_no device_no
                     from rxg_zb_device r1 where r1.device_no <> ?"""
        sql_args = [xy_lib.DeviceNo.XY_SWITCH]
    elif list_no == 'all':
        sql_str = """select r1.id id, 
                            r1.nid nid,
                            r1.moduleid moduleid,
                            r1.name name, 
                            r1.device_no device_no
                     from rxg_zb_device r1"""
        sql_args = []
    else:
        raise rg_lib.RGError(models.ErrorTypes.UnsupportedOp())
    devices = await api_core.BizDB.Query([sql_str, sql_args])
    if get_vals:
        for dev in devices:
            await SyncVal(dev)
    return devices
Example #3
0
async def ListSchedule(req_handler, para):
    """
    :param req_handler:
    :param sessionid:
    :param para: {"search_no": all, valid invalid}
    :return: [schedule obj,...]
    """
    try:
        await api_req_limit.CheckHTTP(req_handler)
        await api_auth.CheckRight(para['token'])
        search_no = para.get('search_no', 'all')
        if search_no == 'all':
            sql_str = """select r1.* from rgw_switch_schedule r1"""
            sql_args = []
        elif search_no == 'valid':
            sql_str = """select r1.* from rgw_switch_schedule r1 where r1.next_run_ts is not null"""
            sql_args = []
        elif search_no == 'invalid':
            sql_str = """select r1.* from rgw_switch_schedule r1 where r1.next_run_ts is null"""
            sql_args = []
        else:
            raise rg_lib.RGError(models.ErrorTypes.UnsupportedOp())
        return await api_switch_schedule.QueryMdl([sql_str, sql_args])
    except Exception:
        rg_lib.Cyclone.HandleErrInException()
Example #4
0
async def Req(rpc_no, method, params, timeout):
    tbl = {'id': 1, 'method': method, 'params': params}
    try:
        url = await api_core.SysCfg.GetGwApiUrl(rpc_no)
        if url:
            resp_defer = await treq.post(url,
                                         data=json.dumps(tbl).encode('utf-8'),
                                         timeout=timeout)
            res = await resp_defer.json()
            if res['error']:
                raise rg_lib.RGError(res['error'])
            else:
                return res['result']
        else:
            raise ValueError('Invalid Url')
    except error.TimeoutError:
        raise rg_lib.RGError(rg_lib.ErrorType.Timeout())
    except defer.CancelledError:
        raise rg_lib.RGError(rg_lib.ErrorType.Timeout())
Example #5
0
async def OpenSwitch(para):
    """
    :param para: {"switchids", "working_seconds": 0}
    :return:
    """
    if para['working_seconds'] < 15:
        raise rg_lib.RGError(
            rg_lib.ErrorType.ServerErr('working seconds >= 15 '))
    await api_switch_action.Open(para['switchids'], rg_lib.DateTime.utc(),
                                 para['working_seconds'])
    return "ok"
Example #6
0
 def Search(cls, para):
     """
     :param para: {"name", "val"}
     :return: [cfg,...]
     """
     if para['name'] == "name":
         sql_str = """select r1.* from rgw_sensor r1 where r1.name like ? limit ?"""
     else:
         raise rg_lib.RGError(models.ErrorTypes.UnsupportedOp())
     sql_args = ("{0}%".format(para['val']),
                 rgw_consts.DbConsts.SEARCH_LIMIT)
     return cls.Query([sql_str, sql_args])
Example #7
0
async def CheckMinuteRate(prefix, ip, rate=100):
    curr = rg_lib.DateTime.utc()
    key = rgw_consts.Keys.MINUTE_RATE_FMT.format(prefix, MinuteKey(curr), ip)
    count = await api_core.BizDB.redis_conn.get(key)
    if (count is not None) and (int(count) > rate):
        raise rg_lib.RGError(models.ErrorTypes.AccessOverLimit())
    else:
        pl_obj = await api_core.BizDB.redis_conn.pipeline()
        pl_obj.incr(key)
        pl_obj.expire(key, 60)
        await pl_obj.execute_pipeline()
        return True
Example #8
0
def Search(para):
    """
    :param para: {"name", "val"}
    :return: [cfg,...]
    """
    if para['name'] == "name":
        sql_str = """select r1.* from rxg_zb_device r1 where r1.name like ? limit ?"""
    elif para['name'] == "id":
        sql_str = """select r1.* from rxg_zb_device r1 where r1.id like ? limit ?"""
    else:
        raise rg_lib.RGError(models.ErrorTypes.UnsupportedOp())
    sql_args = ("{0}%".format(para['val']), rxg_consts.DbConsts.SEARCH_LIMIT)
    return api_core.BizDB.Query([sql_str, sql_args])
Example #9
0
 async def List(cls, arg):
     """
     :param arg: {list_no: "active", "backup"}
     :return:
     """
     if arg['list_no'] == 'active':
         return xy_lib.Api.GetModules()
     elif arg['list_no'] == 'backup':
         sql_str = "select id, serial_port_name, baud_rate from rxg_zb_module"
         mods = await cls.Query([sql_str, []])
         return mods
     else:
         raise rg_lib.RGError(models.ErrorTypes.UnsupportedOp())
Example #10
0
async def OpenSwitch(req_handler, para):
    """
    :param sessionid:
    :param para: {"deviceids", "working_seconds": 0, "token"}
    :return:
    """
    try:
        await api_req_limit.CheckHTTP(req_handler)
        await api_auth.CheckRight(para['token'])
        if para['working_seconds'] < 15:
            raise rg_lib.RGError(rg_lib.ErrorType.ServerErr('working seconds >= 15 '))
        await api_switch_action.Open(para['switchids'], rg_lib.DateTime.utc(),
                                     para['working_seconds'])
        return "ok"
    except Exception:
        rg_lib.Cyclone.HandleErrInException()
Example #11
0
async def GetUserSchedules(para):
    """
    :param para: {'search_no': }
    :return: [schedule obj,...]
    """
    search_no = para.get('search_no', 'all')
    if search_no == 'all':
        sql_str = """select r1.* from rgw_switch_schedule r1"""
        sql_args = []
    elif search_no == 'valid':
        sql_str = """select r1.* from rgw_switch_schedule r1 where r1.next_run_ts is not null"""
        sql_args = []
    elif search_no == 'invalid':
        sql_str = """select r1.* from rgw_switch_schedule r1 where r1.next_run_ts is null"""
        sql_args = []
    else:
        raise rg_lib.RGError(models.ErrorTypes.UnsupportedOp())
    return await api_switch_schedule.QueryMdl([sql_str, sql_args])
Example #12
0
async def FindSensorMinsAvgLog(para):
    """
    :param para: {"sensorids":[], "start_ts": timestamp, "stop_ts": timestamp,
                  "mins_interval": integer}
                  or {"sensorids":[], "hours": hours range, "mins_interval": integer}
    :return: {"sensorids":[], "log_tbl": {sensorid->[mins data,...]},
              "sensors_tbl": {sensorid->sensor tbl}, "ts_series": [series of timestamp]}
    """
    if 'start_ts' in para and 'stop_ts' in para:
        start_ts, stop_ts = para['start_ts'], para['stop_ts']
    elif 'hours' in para:
        stop_ts = rg_lib.DateTime.dt2ts(rg_lib.DateTime.utc())
        start_ts = stop_ts - para['hours'] * 3600
    else:
        raise rg_lib.RGError(models.ErrorTypes.UnsupportedOp())

    # for start_ts to align %HH:00:00
    start_ts = rg_lib.DateTime.dt2ts(
        rg_lib.DateTime.ts2dt(start_ts).replace(minute=0, second=0))
    tbls = await api_sensor_avg_data.QueryMinAvg(start_ts, stop_ts,
                                                 para['sensorids'],
                                                 para['mins_interval'], 2000)
    result = {
        "sensorids":
        para['sensorids'],
        "log_tbl":
        collections.defaultdict(list),
        'ts_series':
        rg_lib.DateTime.GetMinSeries(start_ts, stop_ts, para['mins_interval'],
                                     'ts')
    }
    sql_str = rg_lib.Sqlite.GenInSql(
        """select r1.id,
                                               r1.data_no,
                                               r1.name, 
                                               r1.val_unit,
                                               r1.val_precision
                                        from rgw_sensor r1 where r1.id in """,
        para['sensorids'])
    tbls2 = await api_core.Sensor.Query([sql_str, para['sensorids']])
    for tbl in tbls:
        result['log_tbl'][str(tbl['sensorid'])].append(tbl)
    result['sensors_tbl'] = {str(t['id']): t for t in tbls2}
    return result
Example #13
0
async def CheckUser2(pwd):
    flag = await api_core.SysCfg.CheckPwd(pwd)
    if flag:
        return pwd
    else:
        raise rg_lib.RGError(models.ErrorTypes.NoRight())
Example #14
0
async def CheckUser(pwd):
    flag = await api_core.SysCfg.CheckPwd(pwd)
    if flag:
        return pwd
    else:
        raise rg_lib.RGError(models.ErrorTypes.PwdErr("password error"))