summaryrefslogtreecommitdiff
path: root/ebus-racket/db.rkt
blob: 9ebdfa90a5eb5cd2787221ab898e8f44e3381c64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#lang racket/base
(require (prefix-in db: (planet ryanc/db:1:5)))

(define pgc
  (db:postgresql-connect #:user "ebus"
                         #:database "ebus"
                         #:password "ebus"
                         #:server "10.2.2.26"))

;; Query ID of sensor given by sensor-name
;; Returns null if sensor is undefined
(define (get-sensor-id sensor-name)
  (with-handlers ([exn:fail?  (lambda (exn) (void))])
    (db:query-value pgc "SELECT id FROM sensor WHERE name = $1" sensor-name)))

;; Create Sensor-ID with given name
;; returns id
(define (create-sensor-id sensor-name)
  (db:query-exec "INSERT INTO sensor(name) VALUES ($1)" sensor-name)
  (get-sensor-id sensor-name))

;; Get ID of sensor given by sensor-name
;; define sensor if needed
(define (sensor-id sensor-name)
  (define id (get-sensor-id sensor-name))
  (cond ((void? id) (create-sensor-id sensor-id))
	(else id)))

(define (insert sensor-name value-float value-int value-string)
  (define sensor-id (sensor-id sensor-name))
  (define type (cond ((not (void? value-string)) "string")
                    ((not (void? value-float)) "float")
                    ((not (void? value-int)) "int")))
  (db:query-exec (string-append "INSERT INTO value(timestamp, sensor_id, type, value_float, value_int, value_string) "
				"VALUES (now(), $1, $2, $3, $4, $5)")
		 sensor-id type value-float value-int value-string))

(provide
 (prefix-out db- insert))