Esempio n. 1
0
def execute():
    try:
        global tuples
        if len(tuples) > 0:
            db.connect()
            cursor = db.connection.cursor()
            for t in tuples:
                sql = "INSERT INTO readings (epoch, id, type, read_value, ip) VALUES  ({0}, '{1}', '{2}', '{3}', '{4}');".format(\
                    t[0],\
                    t[1],\
                    t[2],\
                    t[3],\
                    t[4]\
                )
                if util.get_config("debug") == True:
                    util.log(sql, "attini/readings.py", level="debug")
                cursor.execute(sql)
            db.connection.commit()
            cursor.close()
            return True
        else:
            util.log("Error: SQL ERROR", "attini/readings.py")
            return False
    except Exception as e:
        if e.args[0] == 1062:
            util.log("Warning: duplicate primary key", "attini/readings.py")
            return True
        else:
            util.log(
                "Error: {0} - {1} ".format(str(e.args[0]), str(e.args[1])),
                "attini/readings.py")
            return False
Esempio n. 2
0
def select_all(\
    id,\
    last_photo_epoch = 0\
):
    try:
        sql = """
            SELECT
                epoch,
                photo_bin
            FROM photo
            WHERE 1
        """
        sql = sql + " AND id = '{0}' ".format(id)
        if int(last_photo_epoch) > 0:
            sql = sql + " AND epoch > {0} ".format(last_photo_epoch)
        sql = sql + " ORDER BY epoch ASC "
        db.connect()
        cursor = db.connection.cursor()
        if util.get_config("debug") == True:
            util.log(sql, "attini/photo.py", level="debug")
        cursor.execute(sql)
        recordsets = cursor.fetchall()
        cursor.close()
        return recordsets
    except IndexError as e:
        util.log("attini/photo.py IndexError: {0}".format(str(e.args)))
        return False
    except Exception as e:
        util.log("attini/photo.py error: {0} - {1} ".format(
            str(e.args[0]), str(e.args[1])))
        return False
Esempio n. 3
0
def execute(epoch, id, photo_bin, ip):
    try:
        db.connect()
        cursor = db.connection.cursor()
        sql = "INSERT INTO photo (epoch, id, photo_bin, ip) VALUES(%s, %s, %s, %s);"
        args = (epoch, id, photo_bin, ip)
        if util.get_config("debug") == True:
            util.log(sql, "attini/photo.py", level="debug")
            util.log(str(args), "attini/photo.py", level="debug")
        cursor.execute(sql, args)
        db.connection.commit()
        cursor.close()
        return True
    except Exception as e:
        if e.args[0] == 1062:
            util.log("Warning: duplicate primary key", "attini/photo.py")
            return True
        else:
            util.log(
                "Error: {0} - {1} ".format(str(e.args[0]), str(e.args[1])),
                "attini/photo.py")
            return False
Esempio n. 4
0
def connect():
    try:
        util.log("Connecting to MySQL...", "attini/db.py", level = "debug")
        global connection
        if connection == None:
            connection = MySQLdb.connect(\
                host = util.get_config("db_ip"),\
                user = util.get_config("db_user"),\
                passwd = util.get_config("db_password"),\
                db = util.get_config("db_name"),\
                cursorclass = MySQLdb.cursors.DictCursor,\
                charset = 'utf8'\
            )
        else:
            util.log("Connected!", "attini/db.py", level = "debug")
    except MySQLdb.Error as e:
        util.log("Error: {0} - {1} ".format(str(e.args[0]),str(e.args[1])), "attini/db.py", level = "debug")
Esempio n. 5
0
def select_all():
    try:
        sql = """
            SELECT
                id
            FROM readings
            GROUP BY id
            ORDER BY id ASC;
        """
        db.connect()
        cursor = db.connection.cursor()
        if util.get_config("debug") == True:
            util.log(sql, "attini/experience.py", level="debug")
        cursor.execute(sql)
        recordsets = cursor.fetchall()
        cursor.close()
        return recordsets
    except IndexError as e:
        util.log("attini/experience.py IndexError: {0}".format(str(e.args)))
        return False
    except Exception as e:
        util.log("attini/experience.py error: {0} - {1} ".format(
            str(e.args[0]), str(e.args[1])))
        return False
Esempio n. 6
0
    def do_POST(self):
        try:
            client_ip = self.client_address[0]
            util.log("POST from IP {0}".format(str(client_ip)), "attini.py")

            self._set_headers()

            util.log("- Host: {0}".format(str(self.headers['Host'])), "attini.py")
            util.log("- User-Agent: {0}".format(str(self.headers['User-Agent'])), "attini.py")
            util.log("- Connection: {0}".format(str(self.headers['Connection'])), "attini.py")
            util.log("- Content-Type: {0}".format(str(self.headers['Content-Type'])), "attini.py")
            util.log("- Content-Length: {0}".format(str(self.headers['Content-Length'])), "attini.py")
            
            self.data_string = self.rfile.read(int(self.headers['Content-Length']))
            util.log("- Data: {0}".format(str(self.data_string)), "attini.py")
            
            self.send_response(200)
            self.end_headers()
            
            data = simplejson.loads(self.data_string.decode('utf8'))
            util.log("- JSON Data: {0}".format(str(data)), "attini.py")
            
            util.log("Processing JSON...", "attini.py")
            if 'id' in data:
                json_return = "{\"code\": \"0\", \"message\":\"Sent data was stored on server.\"}\r\n";
                
                read_inserts = []
                
                id = data['id']            
                util.log("ID: {0}".format(id), "attini.py")
                
                epoch = util.get_epoch()
                util.log("Epoch time: {0}".format(epoch), "attini.py")
                
                if 'photo_bin' in data:
                    if str(data['photo_bin']) != '0':
                        photo.execute(epoch, id, base64.b64decode(data['photo_bin'].encode('utf8')), client_ip)
                    else:
                        json_return = "{\"code\": \"-12\", \"message\":\"Photo datum was not found on dataset sent.\" }\r\n";
                        self.wfile.write(bytes(str(json_return), "utf8"))
                else:
                    json_return = "{\"code\": \"-11\", \"message\":\"Photo datum was not found on dataset sent.\" }\r\n";
                    self.wfile.write(bytes(str(json_return), "utf8"))
                
                if 'air_humidity' in data:
                    read_inserts.append([epoch, id, "air_humidity", str(data['air_humidity']), client_ip])
                else:
                    json_return = "{\"code\": \"-10\", \"message\":\"Air humidity datum was not found on dataset sent.\" }\r\n";
                    self.wfile.write(bytes(str(json_return), "utf8"))
                    
                if 'air_temperature' in data:
                    read_inserts.append([epoch, id, "air_temperature", str(data['air_temperature']), client_ip])
                else:
                    json_return = "{\"code\": \"-9\", \"message\":\"Air temperature datum was not found on dataset sent.\" }\r\n";
                    self.wfile.write(bytes(str(json_return), "utf8"))
                    
                if 'soil_moisture' in data:
                    read_inserts.append([epoch, id, "soil_moisture", str(data['soil_moisture']), client_ip])
                else:
                    json_return = "{\"code\": \"-8\", \"message\":\"Soil moisture datum was not found on dataset sent.\" }\r\n";
                    self.wfile.write(bytes(str(json_return), "utf8"))
                    
                read.insert(read_inserts)
                read.execute()
                util.log("Saved.", "attini.py")
                util.log("Return JSON is {0}.".format(str(json_return)), "attini.py")
                self.wfile.write(bytes(str(json_return), "utf8"))
            else:
                util.log("ID not found. Error: -7", "attini.py")
                json_return = "{\"code\": \"-7\", \"message\":\"ID datum was not found on dataset sent.\" }\r\n";
                self.wfile.write(bytes(str(json_return), "utf8"))
        except Exception as e:
            util.log("Error: {0}".format(str(e)), "attini.py")
            util.log("Error processing POST. Error: -6", "attini.py")
            json_return = "{\"code\": \"-6\", \"message\":\"Something gone wrong when dataset was processing.\" }\r\n";
            self.wfile.write(bytes(str(json_return), "utf8"))
Esempio n. 7
0
                util.log("ID not found. Error: -7", "attini.py")
                json_return = "{\"code\": \"-7\", \"message\":\"ID datum was not found on dataset sent.\" }\r\n";
                self.wfile.write(bytes(str(json_return), "utf8"))
        except Exception as e:
            util.log("Error: {0}".format(str(e)), "attini.py")
            util.log("Error processing POST. Error: -6", "attini.py")
            json_return = "{\"code\": \"-6\", \"message\":\"Something gone wrong when dataset was processing.\" }\r\n";
            self.wfile.write(bytes(str(json_return), "utf8"))

if __name__ == '__main__':
    args = sys.argv
    action = args[1]
    if action == "start":
        while True:
            try:
                util.log("Starting Attini server at {0}:{1}".format(util.get_config("server_ip"), util.get_config("server_port")), "attini.py", "debug")
                httpd = http.server.HTTPServer((\
                    util.get_config("server_ip"),\
                    util.get_config("server_port")\
                ), httpHandler)
                util.log("Serving forever at {0}:{1}".format(util.get_config("server_ip"), util.get_config("server_port")), "attini.py", "debug")
                httpd.serve_forever()
            except KeyboardInterrupt:
                util.log("Closing service at {0}:{1}".format(util.get_config("server_ip"), util.get_config("server_port")), "attini.py", "debug")
                httpd.server_close()
                sys.exit()
            except Exception as e:
                util.log("Closing service at {0}:{1}".format(util.get_config("server_ip"), util.get_config("server_port")), "attini.py", "debug")
                httpd.server_close()
                util.log("Waiting ~10 seconds to restart.", "attini.py")
                util.sleep(5,15)
Esempio n. 8
0
if __name__ == '__main__':
    args = sys.argv
    action = args[1]
    if action == "create_image_buffer":
        img_path = util.get_config("timelapse_img_path")
        video_path = util.get_config("timelapse_video_path")
        exps = experience.select_all()

        if not os.path.exists(img_path):
            os.makedirs(img_path)
        if not os.path.exists(video_path):
            os.makedirs(video_path)

        for exp in exps:
            util.log("Processing the experience #{0}".format(exp["id"]),
                     "timelapse.py")

            exp_path = img_path + "/{0}".format(str(exp["id"]))
            if not os.path.exists(exp_path):
                os.makedirs(exp_path)

            photos = sorted(os.listdir(exp_path))
            last_photo_epoch = photos[-1][:-4] if len(photos) > 0 else 0

            photos = photo.select_all(\
                id = exp["id"],\
                last_photo_epoch = last_photo_epoch\
            )
            util.log("Photos: {0}".format(str(len(photos))), "timelapse.py")

            for photo_bin in photos:
Esempio n. 9
0
def disconnect():
    connection.close()
    util.log("Disconnected from MySQL.", "attini/db.py", level = "debug")