コード例 #1
0
def get_api_schedule(request):
    valid, response, user = authorize_request(request)
    if not valid:
        return response

    user_buildings = user.userprofile.authorized_buildings()
    try:
        if 'agent_id' in request.query_params:
            agent_id = request.query_params['agent_id']
        else:
            agent_id = request.data['agent_id']
    except:
        return Response({"message": "agent_id missing in query params"}, status=status.HTTP_400_BAD_REQUEST)

    try:
        device = DeviceMetadata.objects.get(agent_id=agent_id)
    except DeviceMetadata.DoesNotExist:
        return Response({"message": "No such device exists"}, status=status.HTTP_400_BAD_REQUEST)

    if device.building not in user_buildings:
        return Response({"message": "User not authorized to control that"}, status=status.HTTP_400_BAD_REQUEST)

    device_mac = device.mac_address
    device_schedule_data, schedule_metadata = get_schedule_data(device_mac)
    schedule = device_schedule_data['schedulers']['everyday']
    return Response(schedule)
コード例 #2
0
def api_schedule_update(request):
    logger.debug("got api schedule update request")
    logger.debug(request.data)
    valid, response, user = authorize_request(request)
    if not valid:
        return response

    user_buildings = user.userprofile.authorized_buildings()
    try:
        if 'agent_id' in request.query_params:
            agent_id = request.query_params['agent_id']
        else:
            agent_id = request.data['agent_id']
    except:
        return Response({"message": "agent_id missing in query params"}, status=status.HTTP_400_BAD_REQUEST)

    try:
        device_info = DeviceMetadata.objects.get(agent_id=agent_id)
    except DeviceMetadata.DoesNotExist:
        return Response({"message": "No such device exists"}, status=status.HTTP_400_BAD_REQUEST)

    if device_info.building not in user_buildings:
        return Response({"message": "User not authorized to control that"}, status=status.HTTP_400_BAD_REQUEST)

    if 'schedule_data' in request.data:
        schedule_data = request.data['schedule_data']
    else:
        schedule_data=request.data['data']

    schedule = {'everyday':schedule_data}
    schedule_type = 'everyday'
    logger.debug("Schedule sent:" +str(schedule_data))
    result = update_schedule(request,agent_id,schedule,schedule_type,user,rest_response=True)
    return result
コード例 #3
0
def get_list(request):

    valid, response, user = authorize_request(request)
    if not valid:
        return response

    authorized_buildings = user.userprofile.authorized_buildings()
    return_data = {}
    try:
        for building in authorized_buildings:
            return_data[building.name] = dict()
            return_data[building.name]['zipcode'] = building.zip_code
            return_data[
                building.name]['location'] = building.building_settings.get(
                    'location', '')
            devices = Devicedata.objects.filter(agent__building=building,
                                                agent__approval_status="APR")
            for device in devices:
                if device.agent.device_type.device_type not in return_data[
                        building.name]:
                    return_data[building.name][
                        device.agent.device_type.device_type] = list()
                return_data[building.name][
                    device.agent.device_type.device_type].append(
                        device.as_json())

        return Response(return_data)
    except Exception as er:
        print er
        return Response({"message": "Internal failure"},
                        status=status.HTTP_400_BAD_REQUEST)
コード例 #4
0
def get_all_devices_list(request, approval_type):
    valid, response, user = authorize_request(request)
    if not valid:
        return response

    authorized_buildings = user.userprofile.authorized_buildings()
    return_data = {}
    try:
        for building in authorized_buildings:
            return_data[building.name] = dict()
            return_data[building.name]['zipcode'] = building.zip_code
            return_data[building.name]['settings'] = building.building_settings
            return_data[building.name]['description'] = building.description
            return_data[building.name]['devices'] = dict()
            devices = DeviceMetadata.objects.filter(
                approval_status=approval_type)
            for device in devices:
                if device.device_type.device_type not in return_data[
                        building.name]['devices']:
                    return_data[building.name]['devices'][
                        device.device_type.device_type] = list()
                return_data[building.name]['devices'][
                    device.device_type.device_type].append(device.as_json())

        return Response(return_data)
    except Exception as er:
        print er
        return Response({"message": "Internal failure"},
                        status=status.HTTP_400_BAD_REQUEST)
コード例 #5
0
def get_data(request):
    valid, response, user = authorize_request(request)
    if not valid:
        return response
    data = request.data
    mac = data['mac']
    return_data = export_time_series_data_spreadsheet(request, mac, body=data)
    return return_data
コード例 #6
0
def get_password_api(request):
    valid, response, user = authorize_request(request)
    if not valid:
        return response

    user_buildings = user.userprofile.authorized_buildings()
    return_data = {}
    try:
        result = [ob.as_json() for ob in PasswordsManager.objects.filter(building__in=user_buildings)]
        return Response(result)
    except Exception as er:
        print er
        return Response({"message":"Internal failure"}, status=status.HTTP_400_BAD_REQUEST)
コード例 #7
0
def change_zones_api(request):
    valid, response, user = authorize_request(request)
    if not valid:
        return response
    if request.method == 'POST':
        user_building = user.userprofile.authorized_buildings()[0]
        post_data = request.data['data']
        try:
            processChangeZone(post_data)
            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": "success"})
コード例 #8
0
def device_monitor(request):
    print "device_monitor"
    print request.data
    success, response, user = authorize_request(request)

    received_data = request.data
    if isinstance(received_data, dict):
        data = json.loads(received_data['dumps'])
    else:
        myDict = dict(received_data.iterlists())
        data = dict()
        for key, value in myDict.iteritems():
            data[key.encode('utf8')] = value[0].encode('utf8')
    device_nickname = data['nickname']
    var = data['variable']

    db_nickname = find_in_nicknames(device_nickname)
    if db_nickname:
        device_info = DeviceMetadata.objects.get(
            nickname__icontains=db_nickname)
    else:
        response = {'success': 0, 'cause': 'No such device found'}
        return Response(response)
    agent_id = device_info.agent_id
    device_data = Devicedata.objects.get(agent_id=agent_id).data
    if 'variable' in data.keys():
        try:
            var = data['variable']
            if var == '':
                response = {'success': 0, 'cause': 'Empty variable.'}
            else:
                try:
                    response = {'success': 1, 'value': device_data[var]}
                except KeyError:
                    ont = find_ontology(var)
                    if ont:  #ontology found
                        var = ont.NAME
                    response = {'success': 1, 'value': device_data[var]}
            return Response(response)
        except KeyError:
            response = {'success': 0, 'cause': 'variable does not exist'}
            return Response(response)
    else:
        response = {'success': 1}
        response.update({'value': device_data})
        return Response(response)
コード例 #9
0
def add_password_api(request):
    valid, response, user = authorize_request(request)
    if not valid:
        return response
    if request.method=='POST':
        user_building = user.userprofile.authorized_buildings()[0]
        return_data = {}
        try:
            passwords_dict=request.data['data']
            passwords_dict['last_modified'] = tzNow()
            mm = SupportedDevices.objects.get(device_model=passwords_dict['device_model'])
            passwords_dict['device_model'] = mm
            passwords_dict['password'] = encrypt_value(passwords_dict['password']).encode('utf8')
            new_password = PasswordsManager(**passwords_dict)
            new_password.building = user_building
            new_password = new_password.save()
            return Response({"message":"success"})
        except Exception as er:
            print er
            return Response({"message":"Internal failure"}, status=status.HTTP_400_BAD_REQUEST)
コード例 #10
0
def submit_devicedata_api(request):
    valid, response, user = authorize_request(request)
    if not valid:
        return response

    if request.method == 'POST':
        try:
            user_buildings = user.userprofile.authorized_buildings()
            try:
                if 'agent_id' in request.query_params:
                    agent_id = request.query_params['agent_id']
                else:
                    agent_id = request.data['agent_id']
            except:
                return Response(
                    {"message": "agent_id missing in query params"},
                    status=status.HTTP_400_BAD_REQUEST)

            try:
                device_info = DeviceMetadata.objects.get(agent_id=agent_id)
            except DeviceMetadata.DoesNotExist:
                return Response({"message": "No such device exists"},
                                status=status.HTTP_400_BAD_REQUEST)

            if device_info.building not in user_buildings:
                return Response(
                    {"message": "User not authorized to control that"},
                    status=status.HTTP_400_BAD_REQUEST)

            post_data = request.data['data']
            post_data.update({"agent_id": agent_id})
            vip_publish('ui', "basicagent", 'update', post_data)
            logger.info("API Submiting Data to agent: " + str(post_data))
            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": "Not a post request"})
コード例 #11
0
def charts_device_api(request):
    valid, response, user = authorize_request(request)
    if not valid:
        return response
    try:
        if 'agent_id' in request.query_params:
            agent_id = request.query_params['agent_id']
        else:
            agent_id = request.data['agent_id']
        post_data = {'agent_id': agent_id}
        data = Devicedata.objects.get(agent_id=agent_id)
        data_variables = dict()
        for item in data.data.keys():
            data_variables[item] = item
        json_result = returnsCharts(post_data,
                                    data_variables,
                                    get_weather=False)
        return Response(json_result)
    except Exception as er:
        print er
        return Response({"message": "Internal failure"},
                        status=status.HTTP_400_BAD_REQUEST)
コード例 #12
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)
コード例 #13
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)