Exemple #1
0
def processChangeZone(data):
    command_group = list()
    status_change = dict()
    gateway_devices = dict()
    for row in data:
        # row = 'agent_id, Node_name, 'Nickname', 'Approved/pending'
        agent_id = row[0]
        building = BuildingInfo.objects.get(name__iexact=row[1])
        device_instance = DeviceMetadata.objects.get(agent_id=row[0])
        gateway = device_instance.gateway
        updated_approval_status = row[3]
        device_instance.building = building  # change field
        device_instance.nickname = row[2]
        device_instance.approval_status = updated_approval_status
        device_instance.save()
        if gateway:  # gateway exists,meaning it is a gateway controlled device
            if gateway.gateway not in gateway_devices:
                gateway_devices[gateway.gateway] = []
            gateway_devices[gateway.gateway].append(
                (agent_id, updated_approval_status))

        if updated_approval_status == APPROVAL_STATUS.APR:
            command_group.append(('ui', 'basicagent', 'onDemandMonitor', {
                'agent_id': agent_id
            }))
        else:
            # command_group.append(('ui', 'baicagent', 'stop', agent_id))
            pass  # nothing to be done/ the device will not be polled from now on

    if gateway_devices:
        for gateway, status_change_list in gateway_devices.items():
            vip_publish("ui", "gatewayagent",
                        "gateway_device_status_update" + "_" + str(gateway),
                        status_change_list)
    vip_publish_bulk(command_group)
Exemple #2
0
def discover_new_devices(request):
    if request.POST:
        _data = request.body
        _data = json.loads(_data)
        _data = [x.encode('utf-8') for x in _data]
        print _data
        authorized_buildings = request.user.userprofile.authorized_buildings()
        publish_messages = list()
        for building in authorized_buildings:
            message = {'devices': _data, 'building_id':building.building_id, 'account_id':request.user.userprofile.account.account_id}
            publish_messages.append(('ui','devicediscoveryagent','discovery_request', message))

        print publish_messages
        vip_publish_bulk(publish_messages)
        if request.is_ajax():
            return HttpResponse(json.dumps("success"))
Exemple #3
0
def discover_new_devices_api(request):
    valid, response, user = authorize_request(request)
    if not valid:
        return response
    if request.method == 'POST':
        if 'data' not in request.data:
            return Response({"message": "POST data dict missing 'data'"}, status=status.HTTP_400_BAD_REQUEST)
        _data = request.data['data']
        authorized_buildings = user.userprofile.authorized_buildings()
        try:
            publish_messages = list()
            for building in authorized_buildings:
                message = {'devices': _data, 'building_id': building.building_id,
                           'account_id': user.userprofile.account.account_id}
                publish_messages.append(('ui', 'devicediscoveryagent', 'discovery_request', message))

            vip_publish_bulk(publish_messages)
            return Response({"message": "success"})
        except Exception as er:
            print er
            return Response({"message": "Internal failure"}, status=status.HTTP_400_BAD_REQUEST)
    else:
        return Response({"message": "GET not supported"}, status=status.HTTP_400_BAD_REQUEST)
Exemple #4
0
def device_control(request):
    print "device_control"
    print request.data
    success, response, user = authorize_request(request)

    data = dict()
    failed_variables = list()
    senddata = dict()
    received_data = request.data
    # myDict=dict(received_data.iterlists())
    # for key,value in myDict.iteritems():
    #     data[key.encode('utf8')]=value[0].encode('utf8')
    if 'dumps' in received_data:
        data = received_data['dumps']
        if type(data) in [unicode, str]:
            data = json.loads(data)
    else:
        data = received_data

    nickname = str(data['nickname'])
    variables = data['variable']
    #The format is {'nickname':'device1','variable':{'cool setpoint':34}}
    if nickname.startswith("all_"):
        device_type = nickname[4:]
        if device_type[-1] == 's':  #if it is plural, make it singular
            device_type = device_type[:-1]
        devices = []
        for device in DeviceMetadata.objects.all():
            if ' ' + device_type.lower() in device.nickname.replace(
                    '_', ' '
            ).lower(
            ):  #make lights match with bedroom_light and bedroom light but not flight thermostat
                devices.append(device)
    else:
        db_nickname = find_in_nicknames(nickname)
        if db_nickname:
            devices = [DeviceMetadata.objects.get(nickname=db_nickname)]
        else:
            response = {'success': 0, 'cause': 'No such device found'}
            return Response(response)

    if not devices:
        response = {'success': 0, 'cause': 'No such device found'}
        return Response(response)

    vip_message_list = list()
    validdata = False
    for device in devices:
        agent_id = device.agent_id
        device_data = Devicedata.objects.get(agent_id=agent_id).data
        for variable, val in variables.items():
            ont = find_ontology(variable)
            if ont and hasattr(
                    ont, 'POSSIBLE_VALUES'
            ):  #convert the provided value into BEMOSS_ONTOLOGY value
                if type(val) in [str, unicode]:
                    val = val.lower()
                if hasattr(ont, 'POSSIBLE_SPOKEN_VALUES'
                           ):  #if POSSIBLE_SPOKEN_VALUES is defined, use that
                    for possible_ont_value, spoken_list in ont.POSSIBLE_SPOKEN_VALUES.items(
                    ):
                        if nom(val) in spoken_list:
                            val = possible_ont_value
                            break
                    else:
                        #failed_variables.append(variable) #can't match, use as it is
                        pass
                else:
                    possible_vals_dict = get_member_variables(
                        ont.POSSIBLE_VALUES
                    )  #if not, just try to match with POSSIBLE_VALUES
                    for key, possible_value in possible_vals_dict.items():
                        if nom(val) == nom(possible_value):
                            val = possible_value
                            break
                    else:
                        #failed_variables.append(variable)  # can't match, then use as it is
                        pass
            if ont:
                if ont.TYPE in ['double', 'float']:
                    val = float(val)
                elif ont.TYPE in ['int']:
                    val = int(val)
                elif ont.TYPE in ['text']:
                    val = str(val)

            if variable not in device_data.keys() and variable not in [
                    'color'
            ]:  #color is an exception. Devicedata has hexcolor, but control is done through color
                if ont and ont.NAME in device_data.keys():
                    validdata = True
                    senddata[ont.NAME] = val
                else:
                    message = "invalid attribute selected to change"
                    failed_variables.append(variable)
                    continue
            else:
                validdata = True
                senddata[variable] = val

        senddata['agent_id'] = agent_id
        vip_message_list.append(
            ('controlapi', "basicagent", 'update', dict(senddata)))

    if vip_message_list:
        vip_publish_bulk(vip_message_list)
        print "Sending this to agents"
        print vip_message_list

    if failed_variables:
        if validdata:
            response = {'success': 2, 'cause': 'One or more variable invalid'}
        else:
            response = {'success': 0, 'cause': 'invalid variables'}
        return Response(response)
    response = {'success': 1}
    return Response(response)