10 #include <mysql/mysql.h>
14 static char *host = NULL;
15 static char *user = NULL;
16 static char *pass = NULL;
17 static char *dbnm = "watermeter";
19 int dbconfig(char *conffile)
21 FILE *fp = fopen(conffile, "r");
27 while (fgets(buf, sizeof(buf), fp)) {
31 e = buf + strlen(buf) - 1;
32 if (*e == '\n') *e = '\0';
34 g_warning("%s:%d line too long", conffile, lc);
38 if ((k = strchr(buf, '#'))) {
42 for (k = buf; k < e && isspace(*k); k++) /*nothing*/ ;
43 for (v = k; v < e && !isspace(*v)
44 && *v != ':' && *v != '='; v++) /*nothing*/ ;
46 if (*k == '\0') continue; /* empty or comment-only line */
47 for (; v < e && (isspace(*v) || *v == ':' || *v == '=')
50 g_warning("%s:%d no value for key \"%s\"",
56 printf("k=%s v=%s\n", k, v);
58 if (!strcmp(k, "host")) host = strdup(v);
59 else if (!strcmp(k, "user")) user = strdup(v);
60 else if (!strcmp(k, "password")) pass = strdup(v);
61 else if (!strcmp(k, "database")) dbnm = strdup(v);
63 g_warning("%s:%d unrecognized key \"%s\"",
72 int dbstore(uint8_t which, uint32_t val)
81 char *table = (which == 1) ? "cold" : "hot";
84 uint32_t prev_val = 0;
87 (void)gmtime_r(&t, &tm);
88 (void)strftime(tstr, sizeof(tstr), "%Y-%m-%d %H:%M:%S", &tm);
90 if(!mysql_real_connect(&mysql, host, user, pass, dbnm, 0, NULL, 0)) {
91 g_warning("mysql connect error: %s\n", mysql_error(&mysql));
94 mysql_autocommit(&mysql, FALSE);
96 snprintf(statement, sizeof(statement),
97 "select value from %scnt order by timestamp desc limit 1;\n",
99 if ((rc = mysql_query(&mysql, statement)))
100 g_warning("mysql \"%s\" error: %s\n",
101 statement, mysql_error(&mysql));
102 else if ((result = mysql_store_result(&mysql))){
103 MYSQL_ROW row = mysql_fetch_row(result);
104 if (row && *row) prev_val = atoi(*row);
105 mysql_free_result(result);
107 if (val <= prev_val) {
108 snprintf(statement, sizeof(statement),
109 "insert into %sadj values (\"%s\",%u);\n",
110 table, tstr, prev_val);
111 g_info("%s %u <= %u, %s", table, val, prev_val, statement);
112 if ((rc = mysql_query(&mysql, statement)))
113 g_warning("mysql \"%s\" error: %s\n",
114 statement, mysql_error(&mysql));
116 snprintf(statement, sizeof(statement),
117 "insert into %scnt values (\"%s\",%u);\n",
119 if ((rc = mysql_query(&mysql, statement)))
120 g_warning("mysql \"%s\" error: %s\n",
121 statement, mysql_error(&mysql));
124 if ((rc = mysql_commit(&mysql)))
125 g_warning("mysql commit error: %s\n",
126 mysql_error(&mysql));
133 int main(int const argc, char *argv[])
135 if (dbconfig(argv[1])) {
136 printf("could not parse config file\n");
139 printf("host: %s\nuser: %s\npass: %s\ndbnm: %s\n",
140 host, user, pass, dbnm);