Example #1
0
def addDevice():
    device_name = bottle.request.forms.get('name')
    device_type = bottle.request.forms.get('type')
    device_function = bottle.request.forms.get('function')
    device_id = bottle.request.forms.get('id')
    device_location = bottle.request.forms.get('location')

    if device_name is not None: # check that the device name is present
        if re.match(r"\w+$", device_type) is not None: # check that device type is alphanumeric
            #if re.match(r"[a-zA-Z0-9]{0,128}$", device_id) is not None: # check that id only has letters and numbers
            if HomerHelper.deviceIdCheck(device_id) is False: # check that id only has letters and numbers
                if HomerHelper.roomCheck(device_location):
                    try:
                        sql_insert = "INSERT INTO `Devices`(`name`, `type`, `function`, `id`, `location`) VALUES (%s, %s,%s,%s,%s)"
                        db.query(sql_insert, (device_name, device_type, device_function, device_id, device_location))

                        HomerHelper.insert_history(device_name, device_id, "device added")

                    except MySQLdb.IntegrityError:
                        bottle.abort(400, "Doh! Device exsists")

                    try:
                        cur = db.query("SELECT * FROM Devices WHERE id = %s", device_id)
                        rows = cur.fetchall()

                        objects_list = []
                        for row in rows:
                            d = collections.OrderedDict()
                            d['name'] = row["name"]
                            d['type'] = row["type"]
                            d['function'] = row["function"]
                            d['id'] = row["id"]
                            d['location'] = row["location"]
                            objects_list.append(d)

                        return json.dumps(objects_list)

                    except MySQLdb.IntegrityError:
                        bottle.abort(400, "Doh! Adding user failed")
                else:
                    bottle.abort(400, "Doh! That request was no bueno.  The room is invalid.")
            else:
                bottle.abort(400, "Doh! That request was no bueno.  The id is invalid." + device_id)
        else:
             bottle.abort(400,"Doh! That request was no bueno.  The type is invalid")
    else:
        bottle.abort(400, "Doh! That request was no bueno.  The name is invalid")