Logo Pico-Framework A web-first embedded framework for C++
Loading...
Searching...
No Matches
DashboardController.cpp
Go to the documentation of this file.
1// DashboardController.cpp
3
4#include <pico/cyw43_arch.h>
5#include <hardware/adc.h>
6#include <cstdio>
7
10#include "PicoModel.h"
11
13 : FrameworkController("DashboardController", r, 1024, 1), pico(pico) {}
14
16{
17
18 printf("[DashboardController] Initializing routes...\n");
19
20 // Serve embedded upload HTML - you can also use a static file
21 router.addRoute("GET", "/upload", [this](HttpRequest &req, HttpResponse &res, const RouteMatch &match)
22 {
23 static const char* uploadHtml = R"rawliteral(
24 <!DOCTYPE html>
25 <html lang="en">
26 <head>
27 <meta charset="UTF-8">
28 <title>Upload</title>
29 </head>
30 <body>
31 <h1>Upload a File</h1>
32 <form method="POST" action="/api/v1/upload" enctype="multipart/form-data">
33 <input type="file" name="file" />
34 <button type="submit">Upload</button>
35 </form>
36 <p>Try opening the file at <code>/uploads/filename.jpg</code> after uploading.</p>
37 </body>
38 </html>
39 )rawliteral";
40
41 res.setContentType("text/html");
42 res.send(uploadHtml); });
43 router.addRoute("GET", "/api/v1/temperature", [this](auto &req, auto &res, const auto &match)
44 { getTemperature(req, res, match); });
45
46 router.addRoute("GET", "/api/v1/led", [this](auto &req, auto &res, const auto &match)
47 { getLedState(req, res, match); });
48
49 router.addRoute("POST", "/api/v1/led/{value}", [this](auto &req, auto &res, const auto &match)
50 { setLedState(req, res, match); });
51
52 router.addRoute("POST", "/api/v1/upload", [this](auto &req, auto &res, const auto &)
53 { uploadHandler(req, res, {}); });
54
55 router.addRoute("DELETE", "/uploads/{file}", [this](auto &req, auto &res, const auto &match)
56 { deleteFile(req, res, match); });
57
58 router.addRoute("GET", "/", [](auto &req, auto &res, const auto &)
59 { res.sendFile("/uploads/pico_gpios.html"); });
60
61 router.addRoute("GET", "/api/v1/ls(.*)", [this](HttpRequest &req, HttpResponse &res, const RouteMatch &match)
62 { this->router.listDirectory(req, res, match); });
63
64// Catch-all route for static files
65// router.addRoute("GET", "/(.*)", [this](HttpRequest &req, HttpResponse &res, const RouteMatch &match)
66// { this->router.serveStatic(req, res, match); });
67
68 // Catch-all route for static files - this is equiavalent to the commented-out line above
69 // It will match any GET request that doesn't match a specific route
70 // This is useful for serving static files like HTML, CSS, JS, etc.
71 // It will also match the root path ("/") and serve the index.html file if it exists
72
73 // Note: this is provided so that you don't have to worry about a catchall regex "eating"
74 // your other routes if it is ahead of them. It will only be called if no other GET route matches.
75 router.addCatchAllGetRoute([this](HttpRequest &req, HttpResponse &res, const RouteMatch &match)
76 { this->router.serveStatic(req, res, match); });
77}
78
80{
81 float tempC = pico.getTemperature(); // Get temperature from pico model
82 res.json({{"temperature", tempC}});
83}
84
86{
87 bool isOn = pico.getLedState(); // Get LED state from pico model
88 res.json({{"state", isOn ? 1 : 0}});
89}
90
92{
93 int value = std::stoi(match.getParam("value").value_or("0"));
94 pico.setLedState(value != 0); // Convert to boolean
95 res.json({{"state", value}});
96}
97
99{
100 req.handle_multipart(res);
101}
102
104{
106 if (!fs->isMounted() && !fs->mount())
107 {
108 res.sendError(500, "mount_failed", "Failed to mount filesystem");
109 return;
110 }
111
112 std::string path = "/uploads/" + match.getParam("file").value_or("");
113 if (fs->exists(path))
114 {
115 fs->remove(path);
116 res.sendSuccess({{"file", match.getParam("file")}}, "File deleted");
117 }
118 else
119 {
120 res.sendError(404, "File not found");
121 }
122}
Abstract interface for file and directory storage backends.
static constexpr std::uintptr_t getTypeKey()
Definition AppContext.h:91
void getLedState(HttpRequest &req, HttpResponse &res, const RouteMatch &match)
void deleteFile(HttpRequest &req, HttpResponse &res, const RouteMatch &match)
DashboardController(Router &r, PicoModel &pico)
void uploadHandler(HttpRequest &req, HttpResponse &res, const RouteMatch &match)
void initRoutes() override
Initialize routes for this controller.
void setLedState(HttpRequest &req, HttpResponse &res, const RouteMatch &match)
void getTemperature(HttpRequest &req, HttpResponse &res, const RouteMatch &match)
Base class for event-driven control logic in embedded applications.
Router & router
Handles path-to-handler mapping - reference to shared Router instance.
Forward declaration for potential routing needs.
Definition HttpRequest.h:32
int handle_multipart(HttpResponse &res)
Handle multipart/form-data uploads.
Represents an HTTP response object.
HttpResponse & setContentType(const std::string &content_type)
Set the Content-Type header.
HttpResponse & json(const std::string &jsonString)
Send a JSON string/object with correct content type.
void send(const std::string &body)
Send a full response including headers and body.
bool sendFile(const std::string &path)
Sends the specified file from mounted storage to the client.
HttpResponse & sendSuccess(const nlohmann::json &data={}, const std::string &message="")
HttpResponse & sendError(int statusCode, const std::string &code, const std::string &message)
void setLedState(bool state)
Definition PicoModel.cpp:34
float getTemperature()
Definition PicoModel.cpp:24
bool getLedState()
Definition PicoModel.cpp:43
The central router for handling HTTP requests and middleware.
Definition Router.h:60
void addCatchAllGetRoute(RouteHandler handler, std::vector< Middleware > middleware={})
Register a catch-all route with optional middleware.
Definition Router.cpp:203
void serveStatic(HttpRequest &req, HttpResponse &res, const RouteMatch &match)
Serve static files from the internal HttpFileserver.
Definition Router.cpp:314
void listDirectory(HttpRequest &req, HttpResponse &res, const RouteMatch &match)
Convenience method to list directory from the internal HttpFileserver.
Definition Router.cpp:321
void addRoute(const std::string &method, const std::string &path, RouteHandler handler, std::vector< Middleware > middleware={})
Register a route with optional middleware.
Definition Router.cpp:144
Represents a match of a route against an incoming HTTP request.
Definition RouteTypes.h:18
std::optional< std::string > getParam(const std::string &name) const
Definition RouteTypes.h:22