starwisp.scm 73.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
;; Starwisp Copyright (C) 2013 Dave Griffiths
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Affero General Public License as
;; published by the Free Software Foundation, either version 3 of the
;; License, or (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU Affero General Public License for more details.
;;
;; You should have received a copy of the GNU Affero General Public License
;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

16 17 18 19 20
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; strings

(define obs-gc "Group Composition")
(define obs-pf "Pup Focal")
21 22
(define obs-gp "Group Events")

23 24 25 26 27 28 29 30 31 32 33 34
(define entity-types
  (list
   "pup-focal"
   "pup-focal-nearest"
   "pup-focal-pupfeed"
   "pup-focal-pupfind"
   "pup-focal-pupcare"
   "pup-focal-pupaggr"
   "group-interaction"
   "group-alarm"
   "group-move"))

35 36 37 38 39 40 41 42 43
(define pup-focal-export
  (list
   "pup-focal-nearest"
   "pup-focal-pupfeed"
   "pup-focal-pupfind"
   "pup-focal-pupcare"
   "pup-focal-pupaggr"))


44 45
;; colours

46 47 48 49 50 51 52 53 54 55 56 57
(define pf-col (list 255 204 51 255))
(define gp-col (list 255 102 0 255))
(define gc-col (list 164 82 9 255))

(define pf-bgcol (list 255 204 51 127))
(define gp-bgcol (list 255 102 0 127))
(define gc-bgcol (list 164 82 9 127))

;(define pf-col (list  22  19 178  127))
;(define gp-col (list 255  97   0  127))
;(define gc-col (list 255 236   0  127))

58 59 60


(define trans-col (list 0 0 0 0))
61 62 63 64 65 66 67 68 69 70 71 72 73 74

(define (get-fragment-index name frag)
  (define (_ i l)
    (cond
     ((null? l) 0)
     ((equal? name (cadr (car l))) i)
     (else (_ (+ i 1) (cdr l)))))
  (_ 0 frag))

(define gc-fragments
  (list
   (list "Start" "gc-start")
   (list "Weights" "gc-weights")
   (list "Pregnant" "gc-preg")
75
   (list "Pup assoc" "gc-pup-assoc")
76 77 78 79
   (list "Oestrus" "gc-oestrus")
   (list "Babysit" "gc-babysitting")
   (list "End" "gc-end")))

80
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Dave Griffiths's avatar
Dave Griffiths committed
81
;; persistent database
82

83
(define db "/sdcard/mongoose/local-mongoose.db")
84
(define main-db "/sdcard/mongoose/mongoose.db")
85

86 87 88 89 90 91 92 93 94 95 96 97 98
(define (setup-database!)
  (msg "setting up database")
  (db-close db) ;; close just in case (sorts out db file delete while running problem)
  (db-open db)
  (msg "setting up tables")
  (setup db "local")
  (setup db "sync")
  (setup db "stream")
  (msg (db-status db))
  (insert-entity-if-not-exists
   db "local" "app-settings" "null" 1
   (list
    (ktv "user-id" "varchar" "No name yet...")))
99
  (msg (db-all-sort-normal db "local" "app-settings")))
Dave Griffiths's avatar
Dave Griffiths committed
100

Dave Griffiths's avatar
Dave Griffiths committed
101 102
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; stuff in memory
Dave Griffiths's avatar
Dave Griffiths committed
103

Dave Griffiths's avatar
Dave Griffiths committed
104 105
(define (store-set store key value)
  (cond
106 107 108 109 110
   ((null? store) (list (list key value)))
   ((eq? key (car (car store)))
    (cons (list key value) (cdr store)))
   (else
    (cons (car store) (store-set (cdr store) key value)))))
Dave Griffiths's avatar
Dave Griffiths committed
111

Dave Griffiths's avatar
Dave Griffiths committed
112
(define (store-get store key default)
Dave Griffiths's avatar
Dave Griffiths committed
113
  (cond
114 115 116 117 118 119 120 121 122 123 124 125 126
   ((null? store) default)
   ((eq? key (car (car store)))
    (cadr (car store)))
   (else
    (store-get (cdr store) key default))))

(define (store-exists? store key)
  (cond
   ((null? store) #f)
   ((eq? key (car (car store)))
    #t)
   (else
    (store-exists? (cdr store) key))))
Dave Griffiths's avatar
Dave Griffiths committed
127

Dave Griffiths's avatar
Dave Griffiths committed
128
(define store '())
Dave Griffiths's avatar
Dave Griffiths committed
129

Dave Griffiths's avatar
Dave Griffiths committed
130 131
(define (set-current! key value)
  (set! store (store-set store key value)))
Dave Griffiths's avatar
Dave Griffiths committed
132

Dave Griffiths's avatar
Dave Griffiths committed
133 134
(define (get-current key default)
  (store-get store key default))
Dave Griffiths's avatar
Dave Griffiths committed
135

136 137 138
(define (current-exists? key)
  (store-exists? store key))

139 140 141 142
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; db abstraction

;; store a ktv, replaces existing with same key
143 144 145
(define (entity-add-value! key type value)
  (set-current!
   'entity-values
146
   (ktv-set
147 148
    (get-current 'entity-values '())
    (ktv key type value))))
149

Dave Griffiths's avatar
Dave Griffiths committed
150 151 152
(define (entity-set! ktv-list)
  (set-current! 'entity-values ktv-list))

153
(define (date-time->string dt)
154 155
  (string-append
   (number->string (list-ref dt 0)) "-"
156 157 158 159 160
   (substring (number->string (+ (list-ref dt 1) 100)) 1 3) "-"
   (substring (number->string (+ (list-ref dt 2) 100)) 1 3) " "
   (substring (number->string (+ (list-ref dt 3) 100)) 1 3) ":"
   (substring (number->string (+ (list-ref dt 4) 100)) 1 3) ":"
   (substring (number->string (+ (list-ref dt 5) 100)) 1 3)))
161

162 163
;; build entity from all ktvs, insert to db, return unique_id
(define (entity-record-values db table type)
164 165
  ;; standard bits
  (entity-add-value! "user" "varchar" (get-current 'user-id "none"))
166
  (entity-add-value! "time" "varchar" (date-time->string (date-time)))
167 168
  (entity-add-value! "lat" "real" (car (get-current 'location '(0 0))))
  (entity-add-value! "lon" "real" (cadr (get-current 'location '(0 0))))
169 170 171 172 173 174 175 176 177 178 179
  (let ((values (get-current 'entity-values '())))
    (cond
     ((not (null? values))
      (let ((r (insert-entity/get-unique
                db table type (get-current 'user-id "no id")
                values)))
        (msg "inserted a " type)
        (entity-reset!) r))
     (else
      (msg "no values to add as entity!") #f))))

Dave Griffiths's avatar
Dave Griffiths committed
180 181 182 183 184 185 186 187 188 189 190 191
(define (entity-update-values db table)
  ;; standard bits
  (let ((values (get-current 'entity-values '()))
        (unique-id (ktv-get (get-current 'entity-values '()) "unique_id")))
    (cond
     ((and unique-id (not (null? values)))
      (update-entity db table (entity-id-from-unique db table unique-id) values)
      (msg "updated " unique-id)
      (entity-reset!))
     (else
      (msg "no values or no id to update as entity:" unique-id "values:" values)))))

192 193 194 195 196 197 198 199 200 201
(define (entity-reset!)
  (set-current! 'entity-values '()))

(define (assemble-array entities)
  (foldl
   (lambda (i r)
     (if (equal? r "") (ktv-get i "unique_id")
         (string-append r "," (ktv-get i "unique_id"))))
   ""
   entities))
202

Dave Griffiths's avatar
Dave Griffiths committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; syncing code

(define url "http://192.168.2.1:8888/mongoose?")

(define (build-url-from-ktv ktv)
  (string-append "&" (ktv-key ktv) ":" (ktv-type ktv) "=" (stringify-value-url ktv)))

(define (build-url-from-ktvlist ktvlist)
  (foldl
   (lambda (ktv r)
     (string-append r (build-url-from-ktv ktv)))
   "" ktvlist))

(define (build-url-from-entity table e)
  (string-append
   url
   "fn=sync"
   "&table=" table
   "&entity-type=" (list-ref (car e) 0)
   "&unique-id=" (list-ref (car e) 1)
Dave Griffiths's avatar
Dave Griffiths committed
224 225
   "&dirty=" (number->string (list-ref (car e) 2))
   "&version=" (number->string (list-ref (car e) 3))
Dave Griffiths's avatar
Dave Griffiths committed
226 227 228
   (build-url-from-ktvlist (cadr e))))

;; spit all dirty entities to server
229 230 231
(define (spit db table entities)
  (foldl
   (lambda (e r)
232
     (debug! (string-append "Sending a " (car (car e)) " to Raspberry Pi"))
233 234 235 236 237 238 239 240 241
     (append
      (list
       (http-request
        (string-append "req-" (list-ref (car e) 1))
        (build-url-from-entity table e)
        (lambda (v)
          (cond
           ((or (equal? (car v) "inserted") (equal? (car v) "match"))
            (update-entity-clean db table (cadr v))
242
            (debug! (string-append "Uploaded " (car (car e)))))
243
           ((equal? (car v) "no change")
244
            (debug! (string-append "No change for " (car (car e)))))
245 246
           ((equal? (car v) "updated")
            (update-entity-clean db table (cadr v))
247
            (debug! (string-append "Updated changed " (car (car e)))))
248
           (else
249 250 251
            (debug! (string-append
                     "Problem uploading "
                     (car (car e)) " : " (car v)))))
Dave Griffiths's avatar
Dave Griffiths committed
252 253
          (list
           (update-widget 'text-view (get-id "sync-dirty") 'text (build-dirty))))))
254 255 256
      r))
   '()
   entities))
257

258
(define (suck-entity-from-server db table unique-id)
Dave Griffiths's avatar
Dave Griffiths committed
259 260 261 262 263 264
  ;; ask for the current version
  (http-request
   (string-append unique-id "-update-new")
   (string-append url "fn=entity&table=" table "&unique-id=" unique-id)
   (lambda (data)
     ;; check "sync-insert" in sync.ss raspberry pi-side for the contents of 'entity'
265
     (let ((entity (list-ref data 0))
266 267
           (ktvlist (list-ref data 1))
           (exists (entity-exists? db table unique-id)))
Dave Griffiths's avatar
Dave Griffiths committed
268
       (if (not exists)
269 270 271 272 273 274 275
           (insert-entity-wholesale
            db table
            (list-ref entity 0) ;; entity-type
            (list-ref entity 1) ;; unique-id
            0 ;; dirty
            (list-ref entity 2) ;; version
            ktvlist)
Dave Griffiths's avatar
Dave Griffiths committed
276 277
           (update-to-version
            db table (get-entity-id db table unique-id)
278
            (list-ref entity 2) ktvlist))
279
       (debug! (string-append (if exists "Got new: " "Updated: ") (ktv-get ktvlist "name")))
Dave Griffiths's avatar
Dave Griffiths committed
280
       (list
281
        (update-widget 'text-view (get-id "sync-dirty") 'text (build-dirty)))))))
Dave Griffiths's avatar
Dave Griffiths committed
282

Dave Griffiths's avatar
Dave Griffiths committed
283
;; repeatedly read version and request updates
Dave Griffiths's avatar
Dave Griffiths committed
284
(define (suck-new db table)
285
  (debug! "Requesting new entities")
Dave Griffiths's avatar
Dave Griffiths committed
286 287 288
  (list
   (http-request
    "new-entities-req"
289
    (string-append url "fn=entity-versions&table=" table)
Dave Griffiths's avatar
Dave Griffiths committed
290
    (lambda (data)
Dave Griffiths's avatar
Dave Griffiths committed
291 292 293 294 295 296 297 298 299 300 301 302 303
      (let ((r (foldl
                (lambda (i r)
                  (let* ((unique-id (car i))
                         (version (cadr i))
                         (exists (entity-exists? db table unique-id))
                         (old
                          (if exists
                              (> version (get-entity-version
                                          db table
                                          (get-entity-id db table unique-id)))
                              #f)))
                    ;; if we don't have this entity or the version on the server is newer
                    (if (or (not exists) old)
304
                        (cons (suck-entity-from-server db table unique-id) r)
Dave Griffiths's avatar
Dave Griffiths committed
305 306 307
                        r)))
                '()
                data)))
308 309
        (cond
         ((null? r)
Dave Griffiths's avatar
Dave Griffiths committed
310
          (debug! "No new data to download")
Dave Griffiths's avatar
Dave Griffiths committed
311
          (set-current! 'download 1)
312
          (append
Dave Griffiths's avatar
Dave Griffiths committed
313 314
           (if (eqv? (get-current 'upload 0) 1)
               (list (play-sound "ping")) '())
315
           (list
Dave Griffiths's avatar
Dave Griffiths committed
316
            (toast "No new data to download")) r))
317 318 319 320
         (else
          (debug! (string-append
                   "Requesting "
                   (number->string (length r)) " entities"))
Dave Griffiths's avatar
Dave Griffiths committed
321 322 323
          (cons
           (play-sound "active")
           r))))))))
Dave Griffiths's avatar
Dave Griffiths committed
324

325 326 327
(define (build-dirty)
  (let ((sync (get-dirty-stats db "sync"))
        (stream (get-dirty-stats db "stream")))
328 329 330 331 332
    (if (or (not sync) (not stream))
        "No data yet"
        (string-append
         "Pack data: " (number->string (car sync)) "/" (number->string (cadr sync)) " "
         "Focal data: " (number->string (car stream)) "/" (number->string (cadr stream))))))
333

334 335 336 337 338 339
(define (upload-dirty db)
  (let ((r (append
            (spit db "sync" (dirty-entities db "sync"))
            (spit db "stream" (dirty-entities db "stream")))))
    (append (cond
             ((> (length r) 0)
Dave Griffiths's avatar
Dave Griffiths committed
340
              (debug! (string-append "Uploading " (number->string (length r)) " items..."))
341
              (list
Dave Griffiths's avatar
Dave Griffiths committed
342 343
               (toast "Uploading data...")
               (play-sound "active")))
344 345
             (else
              (debug! "No data changed to upload")
Dave Griffiths's avatar
Dave Griffiths committed
346 347 348 349 350
              (set-current! 'upload 1)
              (append
               (if (eqv? (get-current 'download 0) 1)
                   (list (play-sound "ping")) '())
               (list
Dave Griffiths's avatar
Dave Griffiths committed
351
                (toast "No data changed to upload"))))) r)))
352 353 354 355 356 357 358 359 360 361 362 363 364

(define (connect-to-net fn)
  (list
   (network-connect
    "network"
    "mongoose-web"
    (lambda (state)
      (debug! (string-append "Raspberry Pi connection state now: " state))
      (append
       (if (equal? state "Connected") (fn) '())
       (list
        ;;(update-widget 'text-view (get-id "sync-connect") 'text state)
        ))))))
365

Dave Griffiths's avatar
Dave Griffiths committed
366
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
367
;; user interface abstraction
Dave Griffiths's avatar
Dave Griffiths committed
368

Dave Griffiths's avatar
Dave Griffiths committed
369
(define (mbutton id title fn)
370
  (button (make-id id) title 30 fillwrap fn))
Dave Griffiths's avatar
Dave Griffiths committed
371

372
(define (mbutton2 id title fn)
373
  (button (make-id id) title 30 (layout 150 100 1 'centre 0) fn))
374

375
(define (mtoggle-button id title fn)
376
  (toggle-button (make-id id) title 30 (layout 'fill-parent 'wrap-content 1 'centre 0) "fancy" fn))
377

378 379 380 381 382 383 384 385 386
(define (mtoggle-button-yes id title fn)
  (toggle-button (make-id id) title 30 (layout 49 43 1 'centre 0) "yes" fn))

(define (mtoggle-button-maybe id title fn)
  (toggle-button (make-id id) title 30 (layout  49 43 1 'centre 0) "maybe" fn))

(define (mtoggle-button-no id title fn)
  (toggle-button (make-id id) title 30 (layout  49 43 1 'centre 0) "no" fn))

387
(define (mtoggle-button2 id title fn)
388
  (toggle-button (make-id id) title 30 (layout 150 100 1 'centre 0) "plain" fn))
389

Dave Griffiths's avatar
Dave Griffiths committed
390
(define (mtext id text)
391
  (text-view (make-id id) text 30 fillwrap))
392

393
(define (mtitle id text)
394
  (text-view (make-id id) text 50 fillwrap))
395

396 397
(define (medit-text id text type fn)
  (vert
398
   (mtext (string-append id "-title") text)
399
   (edit-text (make-id id) "" 30 type fillwrap fn)))
400 401 402 403 404 405 406

(define (mclear-toggles id-list)
  (map
   (lambda (id)
     (update-widget 'toggle-button (get-id id) 'checked 0))
   id-list))

407 408 409 410 411 412 413
(define (mclear-toggles-not-me me id-list)
  (foldl
   (lambda (id r)
     (if (equal? me id)
         r (cons (update-widget 'toggle-button (get-id id) 'checked 0) r)))
   '() id-list))

414 415 416 417 418 419 420 421 422 423
(define (xwise n l)
  (define (_ c l)
    (cond
      ((null? l) (if (null? c) '() (list c)))
      ((eqv? (length c) (- n 1))
       (cons (append c (list (car l))) (_ '() (cdr l))))
      (else
       (_ (append c (list (car l))) (cdr l)))))
  (_ '() l))

424 425
;;;;

426
(define (build-grid-selector name type title)
427 428 429 430 431 432 433 434 435 436
  (linear-layout
   0 'vertical
   (layout 'fill-parent 'wrap-content 1 'left 0)
   (list 0 0 0 0)
   (list
    (mtext "title" title)
    (linear-layout
     0 'horizontal
     (layout 'fill-parent 'wrap-content 1 'left 2) trans-col
     (list
437
      (image-view (make-id "im") "arrow_left" (layout 200 'fill-parent 1 'left 0))
438 439 440 441 442 443 444 445
      (scroll-view
       (make-id "scroller")
       (layout 'wrap-content 'wrap-content 1 'left 20)
       (list
        (linear-layout
         (make-id name) 'horizontal
         (layout 'wrap-content 'wrap-content 1 'centre 20) trans-col
         (list
446
          (button-grid (make-id name) type 3 30 (layout 100 60 1 'left 40)
447
                       (list) (lambda (v) '()))))))
448
      (image-view (make-id "im") "arrow_right" (layout 200 'fill-parent 1 'right 0)))))))
449

450
;; assumes grid selectors on mongeese only
451 452 453
(define (fast-get-name item)
  (list-ref (list-ref item 1) 2))

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
(define (build-button-items name items unknown)
  (append
   (map
    (lambda (item)
      (let ((item-name (fast-get-name item)))
        (list (make-id (string-append name item-name))
              item
              item-name)))
    items)
   (if unknown
       (list
        (list (make-id (string-append name "-unknown"))
              (list (ktv "name" "varchar" "Unknown")
                    (ktv "unique_id" "varchar" "Unknown"))
              "???"))
       '())))

(define (populate-grid-selector name type items unknown fn)
472 473
  (prof-start "popgrid")
  (prof-start "popgrid setup")
474
  (let ((id->items (build-button-items name items unknown))
475
        (selected-set '()))
476 477
    (prof-end "popgrid setup")
    (let ((r (update-widget
478 479
     'button-grid (get-id name) 'grid-buttons
     (list
480
      type 3 30 (layout 100 60 1 'left 0)
481 482
      (map
       (lambda (ii)
483
         (list (car ii) (caddr ii)))
484
       id->items)
485 486
      (lambda (v state)
        (cond
487 488
         ((equal? type "toggle")
          ;; update list of selected items
489 490 491 492 493 494 495 496 497
          (if state
              (set! selected-set (set-add v selected-set))
              (set! selected-set (set-remove v selected-set)))
          ;; find all items currently selected
          (fn (map
               (lambda (v)
                 (cadr (findv v id->items)))
               selected-set)))
         (else
Dave Griffiths's avatar
Dave Griffiths committed
498
          ;;(msg (findv v id->items))
499
          (fn (cadr (findv v id->items))))))))))
500 501 502 503
      (prof-end "popgrid")
      r)))

(define (db-mongooses-by-pack)
504
  (db-all-where
505 506
   db "sync" "mongoose"
   (ktv "pack-id" "varchar" (ktv-get (get-current 'pack '()) "unique_id"))))
507

508 509 510 511 512 513
(define (db-mongooses-by-pack-ignore-delete)
  (db-all-where-ignore-delete
   db "sync" "mongoose"
   (ktv "pack-id" "varchar" (ktv-get (get-current 'pack '()) "unique_id"))))


514
(define (db-mongooses-by-pack-male)
515
  (db-all-where2or
516 517
   db "sync" "mongoose"
   (ktv "pack-id" "varchar" (ktv-get (get-current 'pack '()) "unique_id"))
518
   (ktv "gender" "varchar" "Male") "Unknown"))
519 520

(define (db-mongooses-by-pack-female)
521
  (db-all-where2or
522 523
   db "sync" "mongoose"
   (ktv "pack-id" "varchar" (ktv-get (get-current 'pack '()) "unique_id"))
524
   (ktv "gender" "varchar" "Female") "Unknown"))
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540


;; (y m d h m s)
(define (date-minus-months d ms)
  (let ((year (list-ref d 0))
        (month (- (list-ref d 1) 1)))
    (let ((new-month (- month ms)))
      (list
       (if (< new-month 0) (- year 1) year)
       (+ (if (< new-month 0) (+ new-month 12) new-month) 1)
       (list-ref d 2)
       (list-ref d 3)
       (list-ref d 4)
       (list-ref d 5)))))

(define (db-mongooses-by-pack-pups)
Dave Griffiths's avatar
Dave Griffiths committed
541
  (db-all-newer
542 543 544 545
   db "sync" "mongoose"
   (ktv "pack-id" "varchar" (ktv-get (get-current 'pack '()) "unique_id"))
   (ktv "dob" "varchar" (date->string (date-minus-months (date-time) 6)))))

546 547 548 549 550 551
(define (db-mongooses-by-pack-adults)
  (db-all-older
   db "sync" "mongoose"
   (ktv "pack-id" "varchar" (ktv-get (get-current 'pack '()) "unique_id"))
   (ktv "dob" "varchar" (date->string (date-minus-months (date-time) 6)))))

552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604


(define (tri-state id text key)
  (linear-layout
   (make-id "") 'vertical (layout 'fill-parent 'wrap-content '1 'centre 0) trans-col
   (list
    (linear-layout
     (make-id "") 'horizontal (layout 'wrap-content 'wrap-parent '1 'centre 0) trans-col
     (list
      (mtoggle-button-yes
       (string-append id "-y") ""
       (lambda (v)
         (cond
          (v
           (entity-add-value! key "varchar" "yes")
           (list
            (update-widget 'toggle-button (get-id (string-append id "-n")) 'checked 0)
            (update-widget 'toggle-button (get-id (string-append id "-m")) 'checked 0)))
               (else
                (list
                 (update-widget 'toggle-button (get-id (string-append id "-y")) 'checked 1))))
              ))
      (mtoggle-button-maybe
       (string-append id "-m")  ""
       (lambda (v)
         (cond
          (v
           (entity-add-value! key "varchar" "maybe")
           (list
            (update-widget 'toggle-button (get-id (string-append id "-y")) 'checked 0)
            (update-widget 'toggle-button (get-id (string-append id "-n")) 'checked 0)))
          (else
           (list
            (update-widget 'toggle-button (get-id (string-append id "-m")) 'checked 1))))
         ))

      (mtoggle-button-no
       (string-append id "-n") ""
       (lambda (v)
         (cond
          (v
           (entity-add-value! key "varchar" "no")
           (list
            (update-widget 'toggle-button (get-id (string-append id "-y")) 'checked 0)
            (update-widget 'toggle-button (get-id (string-append id "-m")) 'checked 0)))
          (else
           (list
            (update-widget 'toggle-button (get-id (string-append id "-n")) 'checked 1))))
         ))))

    (text-view 0 text 30 (layout 'wrap-content 'wrap-parent '1 'centre 0)))))


605 606
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
Dave Griffiths's avatar
Dave Griffiths committed
607

608 609 610 611
(define (debug! txt)
  (set-current! 'debug-text (string-append txt "\n" (get-current 'debug-text ""))))

(define (update-debug)
612 613 614
  (update-widget 'debug-text-view (get-id "sync-debug") 'text
                 (get-current 'debug-text "")))

615
(define (debug-timer-cb)
Dave Griffiths's avatar
Dave Griffiths committed
616 617 618 619 620 621 622 623 624 625 626 627 628
  (append
   (cond
    ((get-current 'sync-on #f)
     (set-current! 'upload 0)
     (set-current! 'download 0)
     (connect-to-net
      (lambda ()
        (append
         (list (toast "sync-cb"))
         (upload-dirty db)
         (suck-new db "sync")))))
    (else '()))
   (list
629
    (delayed "debug-timer" (+ 10000 (random 5000)) debug-timer-cb)
Dave Griffiths's avatar
Dave Griffiths committed
630
    (update-debug))))
631

632

633 634
(define pf-length 20) ;; minutes...

635 636 637 638 639 640 641
(define (timer-cb)
  (set-current!
   'timer-seconds
   (- (get-current 'timer-seconds 59) 1))
  (append
   (cond
    ((< (get-current 'timer-seconds 59) 0)
642
     (set-current! 'timer-minutes (- (get-current 'timer-minutes pf-length) 1))
643
     (set-current! 'timer-seconds 59)
644 645 646 647 648 649 650 651 652 653 654 655 656 657
     (cond ((< (get-current 'timer-minutes pf-length) 1)
            (list
             (alert-dialog
              "pup-focal-end"
              "Pup focal time is up, have you finished?"
              (lambda (v)
                (cond
                 ((eqv? v 1)
                  (list (finish-activity 1)))
                 (else
                  (set-current! 'timer-minutes 1)
                  (list)))))))
           (else
            (list (replace-fragment (get-id "pf-top") "pf-scan1")))))
658 659 660 661 662
    (else '()))
   (list
    (delayed "timer" 1000 timer-cb)
    (update-widget
     'text-view (get-id "pf-timer-time-minutes") 'text
663
     (string-append (number->string (get-current 'timer-minutes pf-length))))
664 665 666 667 668
    (update-widget
     'text-view (get-id "pf-timer-time") 'text
     (string-append (number->string (get-current 'timer-seconds 59))))
    )))

Dave Griffiths's avatar
Dave Griffiths committed
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
(define (next-button id dialog-msg next-frag fn)
     (mbutton (string-append id "-nextb") "Next"
              (lambda ()
                (list
                 (alert-dialog
                  (string-append id "-d")
                  dialog-msg
                  (lambda (v)
                    (cond
                     ((eqv? v 1)
                      (append
                       (fn) (list (replace-fragment
                                   (get-id "gc-top") next-frag))))
                     (else '()))))))))

684 685 686 687
(define (force-pause)
  (list
   (delayed "timer" 1000 (lambda () '()))
   (update-widget 'toggle-button (get-id "pf-pause") 'checked 1)))
Dave Griffiths's avatar
Dave Griffiths committed
688

689 690
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; fragments
Dave Griffiths's avatar
Dave Griffiths committed
691 692 693

(define-fragment-list

694 695 696
  (fragment
   "pf-timer"
   (linear-layout
697
    (make-id "") 'vertical fillwrap trans-col
698
    (list
699
     (mtitle "pf-details" "Pack: xxx Pup: xxx")))
700 701 702
   (lambda (fragment arg)
     (activity-layout fragment))
   (lambda (fragment arg)
703 704 705 706 707 708
     (list
      (update-widget 'text-view (get-id "pf-details") 'text
                     (string-append
                      "Pack: " (ktv-get (get-current 'pack '()) "name") " "
                      "Pup: " (ktv-get (get-current 'individual '()) "name"))
                     )))
709 710 711 712 713 714 715
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '()))


  (fragment
716
   "events"
717
   (linear-layout
718
    0 'vertical fillwrap trans-col
719
    (list
720
     (linear-layout
Dave Griffiths's avatar
Dave Griffiths committed
721
      (make-id "ev-pf") 'vertical fill pf-col
722
      (list
723 724
       (mtitle "ev-pf-text" "Pup Focal Events")
       (horiz
Dave Griffiths's avatar
Dave Griffiths committed
725 726 727 728
        (mbutton2 "evb-pupfeed" "Pup Feed" (lambda () (list (replace-fragment (get-id "event-holder") "ev-pupfeed"))))
        (mbutton2 "evb-pupfind" "Pup Find" (lambda () (list (replace-fragment (get-id "event-holder") "ev-pupfind"))))
        (mbutton2 "evb-pupcare" "Pup Care" (lambda () (list (replace-fragment (get-id "event-holder") "ev-pupcare"))))
        (mbutton2 "evb-pupagg" "Pup Aggression" (lambda () (list (replace-fragment (get-id "event-holder") "ev-pupaggr")))))))
729
     (linear-layout
730
      (make-id "ev-pf") 'vertical fill gp-col
731
      (list
732 733
       (mtitle "text" "Group Events")
       (horiz
Dave Griffiths's avatar
Dave Griffiths committed
734 735
        (mbutton2 "evb-grpint" "Interaction" (lambda () (list (replace-fragment (get-id "event-holder") "ev-grpint"))))
        (mbutton2 "evb-grpalarm" "Alarm" (lambda () (list (replace-fragment (get-id "event-holder") "ev-grpalarm"))))
736 737
        (mbutton2 "evb-grpmov" "Movement" (lambda () (list (replace-fragment (get-id "event-holder") "ev-grpmov"))))
        (mbutton2 "evb-grpnote" "Note" (lambda () (list (replace-fragment (get-id "event-holder") "note")))))))))
738 739 740
   (lambda (fragment arg)
     (activity-layout fragment))
   (lambda (fragment arg)
Dave Griffiths's avatar
Dave Griffiths committed
741
     (if (equal? (get-current 'observation "none") obs-pf)
742 743
         (list
          (update-widget 'text-view (get-id "ev-pf-text") 'show 0)
Dave Griffiths's avatar
Dave Griffiths committed
744 745 746 747
          (update-widget 'linear-layout (get-id "ev-pf") 'show 0))
         (list
          (update-widget 'text-view (get-id "ev-pf-text") 'hide 0)
          (update-widget 'linear-layout (get-id "ev-pf") 'hide 0))))
748 749 750 751
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '()))
752

753 754 755
  (fragment
   "pf-scan1"
   (linear-layout
756
    (make-id "") 'vertical fillwrap pf-col
757
    (list
Dave Griffiths's avatar
Dave Griffiths committed
758
     (build-grid-selector "pf-scan-nearest" "single" "<b>Nearest Neighbour Scan</b>: Closest Mongoose")
759
     (build-grid-selector "pf-scan-close" "toggle" "Mongooses within 2m")
760 761 762 763
     (mbutton "pf-scan-done" "Done"
              (lambda ()
                (entity-add-value! "parent" "varchar" (get-current 'pup-focal-id ""))
                (entity-record-values db "stream" "pup-focal-nearest")
764
                (list (replace-fragment (get-id "pf-top") "pf-timer"))))))
765 766 767 768

   (lambda (fragment arg)
     (activity-layout fragment))
   (lambda (fragment arg)
769 770
     (entity-reset!)
     (entity-add-value! "scan-time" "varchar" (date-time->string (date-time)))
771
     (list
772 773
      (play-sound "ping")
      (vibrate 300)
774
      (populate-grid-selector
775
       "pf-scan-nearest" "single"
776
       (db-mongooses-by-pack-adults) #t
777 778
       (lambda (individual)
         (entity-add-value! "id-nearest" "varchar" (ktv-get individual "unique_id"))
779 780
         (list)))
      (populate-grid-selector
781
       "pf-scan-close" "toggle"
782
       (db-mongooses-by-pack-adults) #t
783 784
       (lambda (individuals)
         (entity-add-value! "id-list-close" "varchar" (assemble-array individuals))
785 786
         (list)))
      ))
787 788 789 790 791 792
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '()))


793 794 795
  (fragment
   "ev-pupfeed"
   (linear-layout
796
    (make-id "") 'vertical fillwrap pf-col
797
    (list
798
     (mtitle "title" "Event: Pup is fed")
799
     (build-grid-selector "pf-pupfeed-who" "single" "Who fed the pup?")
Dave Griffiths's avatar
Dave Griffiths committed
800
     (spacer 20)
801
     (horiz
Dave Griffiths's avatar
Dave Griffiths committed
802
      (mtext "text" "Food size")
803 804
      (spinner (make-id "pf-pupfeed-size") (list "Small" "Medium" "Large") fillwrap
               (lambda (v)
Dave Griffiths's avatar
Dave Griffiths committed
805 806 807
                 (entity-add-value! "size" "varchar" v) '())))
     (spacer 20)
     (horiz
808 809 810 811
      (mbutton "pf-pupfeed-done" "Done"
               (lambda ()
                 (entity-add-value! "parent" "varchar" (get-current 'pup-focal-id ""))
                 (entity-record-values db "stream" "pup-focal-pupfeed")
812 813 814
                 (list (replace-fragment (get-id "event-holder") "events"))))
      (mbutton "pf-pupfeed-cancel" "Cancel"
               (lambda ()
Dave Griffiths's avatar
Dave Griffiths committed
815
                 (list (replace-fragment (get-id "event-holder") "events")))))))
816 817 818 819

   (lambda (fragment arg)
     (activity-layout fragment))
   (lambda (fragment arg)
820
     (entity-reset!)
821 822 823
     (list
      (populate-grid-selector
       "pf-pupfeed-who" "single"
824
       (db-mongooses-by-pack-adults) #t
825
       (lambda (individual)
826
         (entity-add-value! "id-who" "varchar" (ktv-get individual "unique_id"))
827 828 829 830 831 832 833
         (list)))
      ))
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '()))

Dave Griffiths's avatar
Dave Griffiths committed
834 835 836
  (fragment
   "ev-pupfind"
   (linear-layout
837
    (make-id "") 'vertical fillwrap pf-col
Dave Griffiths's avatar
Dave Griffiths committed
838
    (list
839
     (mtitle "title" "Event: Pup found food")
Dave Griffiths's avatar
Dave Griffiths committed
840 841 842 843 844
     (horiz
      (mtext "text" "Food size")
      (spinner (make-id "pf-pupfind-size") (list "Small" "Medium" "Large") fillwrap
               (lambda (v) (entity-add-value! "size" "varchar" v) '())))
     (spacer 20)
Dave Griffiths's avatar
Dave Griffiths committed
845
     (horiz
846 847 848 849
      (mbutton "pf-pupfind-done" "Done"
               (lambda ()
                 (entity-add-value! "parent" "varchar" (get-current 'pup-focal-id ""))
                 (entity-record-values db "stream" "pup-focal-pupfind")
850 851 852
                 (list (replace-fragment (get-id "event-holder") "events"))))
      (mbutton "pf-pupfind-cancel" "Cancel"
               (lambda ()
Dave Griffiths's avatar
Dave Griffiths committed
853
                 (list (replace-fragment (get-id "event-holder") "events")))))))
Dave Griffiths's avatar
Dave Griffiths committed
854 855 856 857

   (lambda (fragment arg)
     (activity-layout fragment))
   (lambda (fragment arg)
858
     (entity-reset!)
Dave Griffiths's avatar
Dave Griffiths committed
859 860 861 862 863 864 865 866 867 868 869
     (list
      ))
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '()))


  (fragment
   "ev-pupcare"
   (linear-layout
870
    (make-id "") 'vertical fillwrap pf-col
Dave Griffiths's avatar
Dave Griffiths committed
871
    (list
872
     (mtitle "title" "Event: Pup is cared for")
Dave Griffiths's avatar
Dave Griffiths committed
873
     (build-grid-selector "pf-pupcare-who" "single" "Who cared for the pup?")
Dave Griffiths's avatar
Dave Griffiths committed
874
     (spacer 20)
Dave Griffiths's avatar
Dave Griffiths committed
875
     (horiz
Dave Griffiths's avatar
Dave Griffiths committed
876
      (mtext "text" "Type of care")
877 878
      (spinner (make-id "pf-pupcare-type") (list "Carry" "Lead" "Sniff" "Play" "Ano-genital sniff") fillwrap
               (lambda (v)
Dave Griffiths's avatar
Dave Griffiths committed
879 880 881
                 (entity-add-value! "type" "varchar" v) '())))
     (spacer 20)
     (horiz
882 883 884 885
      (mbutton "pf-pupcare-done" "Done"
               (lambda ()
                 (entity-add-value! "parent" "varchar" (get-current 'pup-focal-id ""))
                 (entity-record-values db "stream" "pup-focal-pupcare")
886 887 888
                 (list (replace-fragment (get-id "event-holder") "events"))))
      (mbutton "pf-pupcare-cancel" "Cancel"
               (lambda ()
Dave Griffiths's avatar
Dave Griffiths committed
889
                 (list (replace-fragment (get-id "event-holder") "events")))))))
Dave Griffiths's avatar
Dave Griffiths committed
890 891 892 893

   (lambda (fragment arg)
     (activity-layout fragment))
   (lambda (fragment arg)
894
     (entity-reset!)
Dave Griffiths's avatar
Dave Griffiths committed
895 896 897
     (list
      (populate-grid-selector
       "pf-pupcare-who" "single"
898
       (db-mongooses-by-pack-adults) #t
Dave Griffiths's avatar
Dave Griffiths committed
899
       (lambda (individual)
900
         (entity-add-value! "id-who" "varchar" (ktv-get individual "unique_id"))
Dave Griffiths's avatar
Dave Griffiths committed
901 902 903 904 905 906 907 908 909 910
         (list)))
      ))
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '()))

  (fragment
   "ev-pupaggr"
   (linear-layout
911
    (make-id "") 'vertical fillwrap pf-col
Dave Griffiths's avatar
Dave Griffiths committed
912
    (list
913
     (mtitle "title" "Event: Pup aggression")
Dave Griffiths's avatar
Dave Griffiths committed
914 915 916
     (build-grid-selector "pf-pupaggr-partner" "single" "Aggressive mongoose")

     (linear-layout
917
      (make-id "") 'horizontal (layout 'fill-parent 100 '1 'left 0) trans-col
Dave Griffiths's avatar
Dave Griffiths committed
918 919 920
      (list
       (vert
        (mtext "" "Fighting over")
921 922 923
        (spinner (make-id "pf-pupaggr-over") (list "Food" "Escort" "Nothing" "Other") fillwrap
                 (lambda (v)
                   (entity-add-value! "over" "varchar" v) '())))
Dave Griffiths's avatar
Dave Griffiths committed
924 925
       (vert
        (mtext "" "Level")
926 927 928
        (spinner (make-id "pf-pupaggr-level") (list "Block" "Snap" "Chase" "Push" "Fight") fillwrap
                 (lambda (v)
                   (entity-add-value! "level" "varchar" v) '())))
929 930 931 932 933 934 935 936 937 938

       (tri-state "pf-pupaggr-in" "Initiate?" "initiate")

       ;(mtoggle-button "pf-pupaggr-in" "Initiate?"
       ;                (lambda (v)
       ;                  (entity-add-value! "initiate" "varchar" (if v "yes" "no")) '()))


       (tri-state "pf-pupaggr-win" "Win?" "win")))

Dave Griffiths's avatar
Dave Griffiths committed
939
     (spacer 20)
940 941 942 943 944 945 946 947 948 949
     (horiz
      (mbutton "pf-pupaggr-done" "Done"
               (lambda ()
                 (entity-add-value! "parent" "varchar" (get-current 'pup-focal-id ""))
                 (entity-record-values db "stream" "pup-focal-pupaggr")
                 (list (replace-fragment (get-id "event-holder") "events"))))
      (mbutton "pf-pupaggr-cancel" "Cancel"
               (lambda ()
                 (list (replace-fragment (get-id "event-holder") "events")))))))

Dave Griffiths's avatar
Dave Griffiths committed
950 951 952 953

   (lambda (fragment arg)
     (activity-layout fragment))
   (lambda (fragment arg)
954
     (entity-reset!)
Dave Griffiths's avatar
Dave Griffiths committed
955 956 957
     (list
      (populate-grid-selector
       "pf-pupaggr-partner" "single"
958
       (db-mongooses-by-pack) #t
Dave Griffiths's avatar
Dave Griffiths committed
959
       (lambda (individual)
960
         (entity-add-value! "id-with" "varchar" (ktv-get individual "unique_id"))
Dave Griffiths's avatar
Dave Griffiths committed
961 962 963 964 965 966 967
         (list)))
      ))
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '())
   (lambda (fragment) '()))

968 969 970 971 972 973 974
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

  (fragment
   "ev-grpint"
   (linear-layout
    (make-id "") 'vertical fillwrap gp-col
    (list
975 976 977 978 979
     (build-grid-selector "gp-int-leader" "single" "<b>Inter-group interaction</b> Leader mongoose")
     (horiz
      (linear-layout
       (make-id "") 'vertical (layout 400 'fill-parent '1 'left 0) trans-col
       (list
980
        (mtext "text" "Outcome")
981
        (spinner (make-id "gp-int-out") (list "Retreat" "Advance" "Fight retreat" "Fight win") fillwrap
982
                 (lambda (v)
983
                   (entity-add-value! "outcome" "varchar" v) '()))
984
        (mtext "text" "Duration")
985 986 987 988 989 990
        (edit-text (make-id "gp-int-dur") "" 30 "numeric" fillwrap
                   (lambda (v) (entity-add-value! "duration" "int" (string->number v)) '()))))
      (build-grid-selector "gp-int-pack" "single" "Other pack"))
     (linear-layout
      (make-id "") 'horizontal (layout 'fill-parent 80 '1 'left 0) trans-col
      (list