Skip to content

Commit

Permalink
Report failed initialisation over HTTP
Browse files Browse the repository at this point in the history
Change-type: minor
Signed-off-by: Alex Bucknall <[email protected]>
  • Loading branch information
Bucknalla committed Jun 19, 2024
1 parent 9699dd7 commit 480a9b0
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
3 changes: 2 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ services:
- "/dev/i2c-1:/dev/i2c-1"
expose:
- "3434"
privileged: true
privileged: true
restart: always
25 changes: 18 additions & 7 deletions notecard/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,22 @@ const (
)

type server struct {
card *notecard.Context
card *notecard.Context
initError error
}

var transport = os.Getenv("NOTECARD_TRANSPORT")

func handleError(w http.ResponseWriter, err error, msg string) {
err_str := fmt.Sprintf("%s: %v", msg, err)
http.Error(w, err_str, http.StatusInternalServerError)
log.Print(err_str)
}

func (s *server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if s.card == nil {
log.Fatal("notecard not initialized")
if s.card == nil || s.initError != nil {
handleError(w, s.initError, "while initialising notecard")
log.Fatal("Notecard not initialised, exiting...")
}

if req.Method != http.MethodPost {
Expand All @@ -48,6 +52,7 @@ func (s *server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
handleError(w, err, "while performing a card transaction")
return
}
log.Printf("notecard response: %s", note_rsp)

// Set the Content-Type header to application/json
w.Header().Set("Content-Type", "application/json")
Expand All @@ -73,26 +78,32 @@ func setupNotecard(protocol string) (*notecard.Context, error) {
return card, nil
}

card, err := notecard.OpenI2C("/dev/i2c-1", 0x17)
card, err := notecard.OpenI2C("", 0x17)
if err != nil {
return nil, fmt.Errorf("error opening Notecard: %v", err)
}

status := map[string]interface{}{
"req": "card.status",
}
if _, err = card.Transaction(status); err != nil {
return nil, fmt.Errorf("error querying Notecard status: %v", err)
}
return card, nil
}

func main() {
transport := os.Getenv("NOTECARD_TRANSPORT")
if transport == "" {
log.Printf("transport protocol not provided, defaulting to I2C...")
transport = I2C
}

card, err := setupNotecard(transport)
if err != nil {
log.Fatalf("while setting up notecard: %v", err)
log.Printf("while setting up notecard: %v", err)
}
defer card.Close()

http.Handle("/", &server{card: card})
http.Handle("/", &server{card: card, initError: err})
http.ListenAndServe(":3434", nil)
}

0 comments on commit 480a9b0

Please sign in to comment.