Esempio n. 1
0
def register(request):
    """
    用户注册
    """
    name = request.POST["username"]
    telephone = request.POST["telephone"]
    email = request.POST["email"]
    password = request.POST["password"]
    token = uuid.uuid4()
    if UserModel.objects.filter(telephone=telephone):
        return restful.params_error(message="this user is exist!")
    try:
        user = UserModel.objects.create_user(username=name,
                                             telephone=telephone,
                                             email=email,
                                             password=password,
                                             token=token,
                                             is_active=1)
        user.compID = user.id
        user.save()
        login(request, user)
        result = restful.ok()
    except Exception as e:
        result = restful.server_error(
            message="this telephone or email is exist!")
    return result
Esempio n. 2
0
def bulk_import_dnc_params(request):
    """
    批量导入DNC协议采集项目模板
    :return:
    """
    # DNC协议采集项模板文件放置路径
    basic_path = os.path.join(BASE_DIR, "apps", "Tm", "MatterAnalysis",
                              "ProtocolTemp")
    # 设置默认DNC协议采集项模板文件
    file_import_path = os.path.join(BASE_DIR, "apps", "Tm", "MatterAnalysis",
                                    "ProtocolTemp", "temp.xlsx")
    # 查找是否有DNC协议采集项模板文件(xlsx/xls)
    for root, dirs, files in os.walk(basic_path):
        for filename in files:
            name, suf = os.path.splitext(filename)
            if (suf == '.xlsx') or (suf == '.xls'):
                file_import_path = os.path.join(root, filename)
    # 确定路径下有模板文件
    if not os.path.exists(file_import_path):
        return restful.params_error("没有找到协议模板文件")
    # 读取excel信息
    workbook = xlrd.open_workbook(file_import_path)
    sheet_list = workbook.sheet_names()
    # 初始化数据
    data = []
    for sheet in sheet_list:
        booksheet = workbook.sheet_by_name(sheet)
        # 获取数据的长宽
        x = booksheet.ncols
        y = booksheet.nrows
        # 获取模板内采集项key
        key = [booksheet.cell_value(0, i) for i in range(x)]
        key.append("协议名称")
        if y:
            for j in range(1, y):
                # 获取采集项信息value
                value = [booksheet.cell_value(j, i) for i in range(x)]
                value.append(sheet)
                info = dict(zip(key, value))
                data.append(info)
    # 将采集项数据与数据库建立映射
    for dt in data:
        basic = {
            "ProType": dt.get("协议名称", ""),
            # operationValue 变量名
            "operationValue": dt.get("Description", ""),
            "Description": dt.get("Title", ""),
            "type": dt.get("变量类型", ""),
            #  采集项单位未配置时默认“-”
            "operationUnit": dt.get("单位", "") if dt.get("单位", "") else "-",
            "configValue": dt.get("configValue", ""),
        }
        # excel导入时数字为float,需转化成int
        if isinstance(basic["Description"], float):
            basic["Description"] = int(basic["Description"])
        try:
            ProtocolParamsDNC.objects.create(**basic)
        except Exception:
            continue
    return restful.ok()
Esempio n. 3
0
def Login(request):
    """
    用户登录
    """
    username = request.POST["username1"]
    password = request.POST["password1"]
    user = UserModel.objects.filter(
        Q(username=username) | Q(telephone=username)).all()
    if user:
        user = user[0]
        if user.check_password(password):
            if user.is_active:
                login(request, user)
                result = restful.ok(data={"token": user.token})
            else:
                result = restful.params_error(message="telephone")
        else:
            result = restful.params_error(message="password")
    else:
        result = restful.params_error(message="telephone")
    return result
Esempio n. 4
0
def del_template(request):
    """
    删除协议模板
    :param request:
    :return:
    """
    try:
        idList = [int(i) for i in request.POST["idList"].split(",")]
        # operationFlag更新为0
        DeviceTemplates.objects.filter(id__in=idList).update(operationFlag=0)
        result = restful.ok()
    except Exception as e:
        result = restful.params_error(message="模板删除失败!")
    return restful.ok()
Esempio n. 5
0
def get_identifying_code(request):
    """
    根据手机号从redis获取验证码,前端表单值与redis存储的验证码进行比对
    """
    telephone = request.POST["telephone"]
    cache_code = request.POST["cache_code"]
    user = UserModel.objects.filter(phoneNum=telephone)
    data = {
        "phoneNum": telephone,
        "verificationCode": cache_code,
        "rname": "i_plc.Page.register.register.verifyCode"
    }
    res = requests.post(message_url, data=data).json()
    if not user:
        if res["success"]:
            result = restful.params_error(message="telephone")
        else:
            result = restful.params_error(message="both")
    else:
        if res["success"]:
            result = restful.ok()
        else:
            result = restful.params_error(message="cache_code")
    return result
Esempio n. 6
0
def get_plc_params(request):
    """
    获取plc采集项
    :return:
    """
    data = {}
    protocols = request.POST["protocols"].split(",")
    if protocols:
        for i in protocols:
            if i in plc_protocol:
                data[i] = plc_protocol[i]
        result = restful.ok(data=data)
    else:
        result = restful.params_error(message="param is null!")
    return result
Esempio n. 7
0
def chage_gatename(request):
    """
    更改网关名称
    :param request:
    :return:
    """
    gateMac = request.POST["gateMac"]
    gateName = request.POST["gateName"]
    gateinfo = GateInfoModel.objects.filter(gateMac=gateMac).all()[0]
    gateinfo1 = GateInfoModel.objects.filter(gateName=gateName)
    if gateinfo1:
        result = restful.params_error(message="this gateName is exist!")
    else:
        gateinfo.gateName = gateName
        gateinfo.save()
        result = restful.ok()
    return result
Esempio n. 8
0
def send_identifying_code(request):
    """
    生成6位随机数并发送给用户
    """
    try:
        telephone = request.POST["telephone"]
        data = {
            "phoneNum": telephone,
            "rname": "i_plc.Page.register.register.getSMS_login"
        }
        res = requests.post(message_url, data=data).json()
        if res["success"]:
            result = restful.ok()
        else:
            result = restful.params_error(
                message="failure to send verification code")
    except Exception as e:
        result = restful.server_error(message=e)
    return result
Esempio n. 9
0
def delete_device(request):
    """
    删除物影子
    :return:
    """
    deviceCode = request.POST["deviceCode"]
    gateMac = request.POST["gateMac"]
    gateType = request.POST["gateType"]
    try:
        Variables.objects.filter(machCode=deviceCode).delete()
        if gateType == "GW_DNC":
            ProtocolDNC.objects.filter(machCode=deviceCode).delete()
        else:
            ProtocolPLC.objects.filter(machCode=deviceCode).delete()
        # 将deviceMoal表中的数据清除
        DeviceModal.objects.filter(machCode=deviceCode).delete()
        result = restful.ok()
    except Exception as e:
        result = restful.params_error(message="删除网关失败!")
    return result
Esempio n. 10
0
def gateinfo(request):
    """
    获取网关信息,展示在网关接入界面
    :param request:
    :return:
    """
    token = request.POST["token"]
    # 当前查看页
    page = int(request.POST["page"])
    # 每页显示的条数
    limit = int(request.POST["limit"])
    # 搜索关键字, ""表示查询所有
    searchKey = request.POST["searchKey"]
    # 升降序
    order = request.POST["order"]
    # 排序字段
    orderProp = request.POST["orderProp"]
    # 取每一页的第一行和最后一行数的下标
    start = (page - 1) * limit
    end = start + limit
    user = UserModel.objects.filter(token=token).all()
    if user:
        compID = user[0].compID
    else:
        compID = ""
    if compID:
        # 管理员
        if compID == -1:
            # 所有网关
            gateInfos = GateInfoModel.objects.filter()
        else:
            # 根据公司来查询
            compID = str(compID).zfill(4)
            # 该公司所有网关
            gateInfos = GateInfoModel.objects.filter(compID=compID)
        if not searchKey:
            gateInfo1 = gateInfos.filter()
        else:
            if searchKey in ["已启用", "未激活", "启用", "激活"]:
                if searchKey in ["已启用", "启用"]:
                    searchKey = 1
                else:
                    searchKey = 0
                gateInfo1 = gateInfos.filter(ifregister=searchKey)
            else:
                # id字段是对数据库中查询出来的主键ID进行的排序结果,故不支持ID搜索
                gateInfo1 = gateInfos.filter(
                    (Q(gateMac__icontains=searchKey)
                     | Q(compID__icontains=searchKey)
                     | Q(ServerIP__icontains=searchKey)
                     | Q(gateType__icontains=searchKey)
                     | Q(software_version__icontains=searchKey)
                     | Q(lastBuildTime__startswith=searchKey)))
        # 前端展示的字段是status, 后端数据字段是ifregister, 当排序status字段时需要转换成ifregister
        if orderProp == "status":
            orderProp = "ifregister"
        if orderProp == "compName":
            orderProp = "compID"
        # 升降序排序
        if order == "ascending":
            gateInfo1 = gateInfo1.order_by(orderProp)
        else:
            gateInfo1 = gateInfo1.order_by("-" + orderProp)
        gateInfo2 = gateInfo1[start:end]
        gate_list = []
        for index, i in enumerate(gateInfo2):
            try:
                compName = UserModel.objects.filter(
                    compID=int(i.compID))[0].compName
            except:
                compName = None
            data = {
                "id": i.id,
                "compID": i.compID,
                "compName": compName,
                "gateMac": i.gateMac,
                "ServerIP": i.ServerIP,
                "gateType": i.gateType,
                "software_version": i.software_version,
                "status": i.ifregister,
                "lastBuildTime": i.lastBuildTime.strftime("%Y-%m-%d %H:%M:%S"),
            }
            gate_list.append(data)
        # 总的网关数
        totalCount = len(gateInfo1)
        # 启用的网关数
        allowCount = len(gateInfo1.filter(ifregister=1))
        # 禁用的网关数
        forbidCount = len(gateInfo1.filter(ifregister=9))
        result = restful.ok(
            data={
                "items": gate_list,
                "totalCount": totalCount,
                "allowCount": allowCount,
                "forbidCount": forbidCount
            })
    else:
        result = restful.params_error(message="token is worng!")
    return result
Esempio n. 11
0
def new_template(request):
    """
    新建协议模板
    :return:
    """
    # 获取POST数据
    gateType = request.POST["gateType"]
    selectParams = eval(request.POST["selectedProtocol"])
    """
    下面的代码块是保存模板
    """
    params = {
        "TemplateName": request.POST['name'],
        "proType": gateType,
        "TypeList": ",".join(selectParams),
    }
    count = DeviceTemplates.objects.filter(
        TemplateName=params["TemplateName"]).count()
    if count:
        return restful.params_error(message="模板名重复")
    else:
        DeviceTemplates.objects.create(**params)
    """
    下面的代码块是为了将模板中的采集项保存到解析表中,通过data字典存入数据库
    """
    # 获取模板ID
    template_id = DeviceTemplates.objects.filter(
        TemplateName=params["TemplateName"])[0].id
    # 遍历前端传递过来的协议列表,DNC: ["ABB", "KUKA"]  PLC: ["FINS_UDP", "MODBUS_TCP"]
    configs = eval(request.POST["config"])
    # 遍历前端传递过来的协议数据
    for key, values in configs.items():
        # 将每个协议对应的所有需要保存的数据,以对象的形式存储到列表中,进行单协议批量存储,减少数据库的save操作
        data_object_list_plc = []
        data_object_list_dnc = []
        # data用来存储每一条数据,通过data去生成一个ORM对象
        data = {"template": template_id, "operationFlag": 9}
        # 前端传递过来的协议属于key,直接取value即可
        if gateType == "GW_PLC":
            for i in range(len(values)):
                data["name"] = values[i][0]["value"]
                data["type"] = values[i][1]["selectedItem"]
                data["functionCode"] = values[i][2]["selectedItem"]
                data["startAddress"] = values[i][3]["value"]
                data["len"] = values[i][4]["value"]
                data["delayMs"] = values[i][5]["value"]
                data["operationUnit"] = values[i][6]["value"]
                data["dataType"] = ProtocolType.objects.get(TypeList=key)
                data["deviceType"] = key
                if key in protocol_plc_list:
                    data["deviceIP"] = values[i][7]["value"]
                else:
                    data["serialNum"] = values[i][7]["value"]
                    data["deviceID"] = values[i][8]["value"]
                data_object_list_plc.append(ProtocolPLC(**data))
            try:
                ProtocolPLC.objects.bulk_create(data_object_list_plc)
            except Exception as e:
                continue
        else:
            for i in range(0, len(values["normal"])):
                if values["normal"]:
                    data["operationValue"] = values["normal"][i]["name"]
                    data["operationUnit"] = values["normal"][i]["unit"]
                    data["upload"] = values["normal"][i]["upload"]
                    data["Description"] = values["normal"][i]["description"]
                    data["deviceType"] = ProtocolType.objects.get(TypeList=key)
                    data["Description"] = values["normal"][i]["description"]
                    data["configValue"] = values["normal"][i]["param"]
                    data["type"] = \
                        ProtocolParamsDNC.objects.filter(operationValue=data["operationValue"], ProType=key)[0].type
                if values["advanced"]:
                    for k in values["advanced"]:
                        if k["name"] == "IP地址":
                            data["deviceIP"] = k["value"]
                            continue
                    data_object_list_dnc.append(ProtocolDNC(**data))
            try:
                ProtocolDNC.objects.bulk_create(data_object_list_dnc)
            except Exception as e:
                continue
    return restful.ok()
Esempio n. 12
0
def get_MatterAnalysis(request):
    """
    获取物解析列表
    :return:
    """
    token = request.POST["token"]
    # 当前查看页
    page = int(request.POST["page"])
    # 每页显示的条数
    limit = int(request.POST["limit"])
    # 搜索关键字, ""表示查询所有
    searchKey = request.POST["searchKey"]
    # 升降序
    order = request.POST["order"]
    # 排序字段
    orderProp = request.POST["orderProp"]
    # 取每一页的第一行和最后一行数的下标
    start = (page - 1) * limit
    end = start + limit
    # 存储查询出的网关数据
    gate_list = []
    user = UserModel.objects.filter(token=token).all()
    if user:
        compID = user[0].compID
    else:
        compID = ""
    if compID:
        # 管理员
        if compID == -1:
            # 所有网关
            gateInfos = GateInfoModel.objects.filter(ifregister=1)
        else:
            # 根据公司来查询
            compID = str(compID).zfill(4)
            # 该公司所有网关
            gateInfos = GateInfoModel.objects.filter(compID=compID,
                                                     ifregister=1)
        # 根据搜索关键字来查询
        if not searchKey:
            gateInfo1 = gateInfos.filter()
        else:
            # 查询出关联的设备编码和协议类型
            devices = DeviceModal.objects.filter(
                gateMac__in=[i.gateMac for i in gateInfos]).filter(
                    Q(protocol__icontains=searchKey)
                    | Q(machCode__icontains=searchKey))
            # 根据搜索字来查询,当搜索协议或者machCode时,根据gateMac__in可以查询出有这些协议或者machCode的网关
            gateInfo1 = gateInfos.filter(
                Q(gateName__icontains=searchKey)
                | Q(gateMac__icontains=searchKey)
                | Q(gateType__icontains=searchKey)
                | Q(machID__icontains=searchKey)
                | Q(gateMac__in=[i.gateMac for i in devices]))
        # 对数据进行排序
        if order == "ascending":
            gateInfo1 = gateInfo1.order_by(orderProp)
        else:
            gateInfo1 = gateInfo1.order_by("-" + orderProp)
        # 总的网关数
        totalCount = len(gateInfo1)
        # 拿出分页数据
        gateInfo2 = gateInfo1[start:end]
        # 遍历查询出的数据,存储到gate_list中,以便返回给前端进行展示
        for index, i in enumerate(gateInfo2):
            protocol = []
            data = {
                "id": i.id,
                "gateName": i.gateName,
                "compID": i.compID,
                "gateType": i.gateType,
                "gateMac": i.gateMac,
                "serverIP": i.ServerIP,
                "status": i.status,
                "software_version": i.software_version,
                # 网关的操作状态
                "operateStatus": ""
            }
            devices = DeviceModal.objects.filter(gateMac=i.gateMac)
            # 获取网关对应的machCode
            data["machCode"] = [x.machCode for x in devices]
            # 获取网关对应的协议,协议是与物影子进行绑定的,需要通过物影子获取
            for x in devices:
                device_protocol = DeviceModal.objects.filter(
                    machCode=x.machCode)[0].protocol
                if device_protocol:
                    protocol.extend([i for i in device_protocol.split(",")])
            protocol = list(set(protocol))
            data["protocols"] = protocol
            gate_list.append(data)
        gate_infos = {"items": gate_list, "totalCount": totalCount}
        result = restful.ok(data=gate_infos)
    else:
        result = restful.params_error(message="token is worng!")
    return result