Added get_pizza_list

This commit is contained in:
palo 2023-10-25 19:54:45 +02:00
parent 3f0b9396ab
commit 0145ff15cb

View File

@ -7,6 +7,11 @@
(define port 4444)
(define hostname "127.0.0.1")
; Return a list of pizzas from the local file
(define (get-pizzas-list)
(let ((file (open-input-file "pizza_list.json")))
(read-json file)))
; Print the to-print string on the printer
; TODO add synchronization to avoid race conditions
(define (printer-print to-print)
@ -23,20 +28,22 @@
str))
; Parse the commands given in the JSON
(define (parse-json message)
(define (parse-json message output)
(let ((parsed-json (with-input-from-string message (lambda () (read-json))))) ; parse the JSON
(case (hash-ref parsed-json 'command)
(("print") (printer-print (hash-ref parsed-json 'text)))
(("pizza") (printer-print (format-pizza (hash-ref parsed-json 'pizzas)))))))
(("pizza") (printer-print (format-pizza (hash-ref parsed-json 'pizzas))))
(("get-pizzas") (write-json (get-pizzas-list) output)))))
; Receive the JSON message and execute the specified command
(define (get-message input)
; Execute the command specified in the JSON
(define (execute-commands input output)
(let ((message ""))
(let loop-until-eof ((str (read-string 1 input)))
(if (eof-object? str)
(begin
(parse-json message output)
(close-input-port input)
(parse-json message))
(close-output-port output))
(begin
(set! message (string-append message str))
(loop-until-eof (read-string 1 input)))))))
@ -46,8 +53,7 @@
(let ((listener (tcp-listen port 4 #t hostname)))
(let infinite-loop ()
(let-values (((input output) (tcp-accept listener)))
(close-output-port output) ; we don't need it
(thread (lambda () (get-message input)))
(thread (lambda () (execute-commands input output)))
(infinite-loop)))))
(wait-for-connection)