From 0145ff15cb437ab4f000d44809bfdbf2199ce017 Mon Sep 17 00:00:00 2001 From: palo Date: Wed, 25 Oct 2023 19:54:45 +0200 Subject: [PATCH] Added get_pizza_list --- scontrini.rkt | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/scontrini.rkt b/scontrini.rkt index ac0bbcd..78a425b 100644 --- a/scontrini.rkt +++ b/scontrini.rkt @@ -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)