Logo Pico-Framework A web-first embedded framework for C++
Loading...
Searching...
No Matches
DashboardController Class Reference

#include <DashboardController.h>

+ Inheritance diagram for DashboardController:
+ Collaboration diagram for DashboardController:

Public Member Functions

 DashboardController (Router &r, PicoModel &pico)
 
void initRoutes () override
 Initialize routes for this controller.
 
- Public Member Functions inherited from FrameworkController
 FrameworkController (const char *name, Router &sharedRouter, uint16_t stackSize=1024, UBaseType_t priority=tskIDLE_PRIORITY+1)
 Constructor.
 
void run () override final
 Main task loop.
 
const char * getName () const
 Get the name of this controller.
 
void enableEventQueue (size_t depth=8)
 Enable the event queue for this controller.
 
QueueHandle_t getEventQueue () const
 Get the event queue for this controller.
 
bool getNextEvent (Event &event, uint32_t timeoutMs)
 Check if there are any pending events in the queue.
 
- Public Member Functions inherited from FrameworkTask
 FrameworkTask (const char *name, uint16_t stackSize=1024, UBaseType_t priority=1)
 Constructor.
 
virtual ~FrameworkTask ()
 Destructor.
 
bool start ()
 Starts the task via FreeRTOS.
 
void suspend ()
 Suspends the task using vTaskSuspend().
 
void resume ()
 Resumes the task using vTaskResume().
 
TaskHandle_t getHandle () const
 Returns the FreeRTOS task handle.
 
const char * getName () const
 Returns the task name.
 
void notify (uint8_t index, uint32_t value=1)
 Sends a notification to this task using an index.
 
void notify (Notification n, uint32_t value=1)
 Sends a notification using a framework-defined enum.
 
void notifyFromISR (uint8_t index, uint32_t value=1, BaseType_t *pxHigherPriorityTaskWoken=nullptr)
 Sends a notification from an ISR (by index).
 
void notifyFromISR (Notification n, uint32_t value=1, BaseType_t *pxHigherPriorityTaskWoken=nullptr)
 Sends a notification from ISR using enum identifier.
 
bool waitFor (uint8_t index, TickType_t timeout=portMAX_DELAY)
 Waits for a notification (by index).
 
bool waitFor (Notification n, TickType_t timeout=portMAX_DELAY)
 Waits for a notification (by enum identifier).
 
Notification waitForAny (uint8_t index, uint32_t mask, TickType_t timeout=portMAX_DELAY)
 waits for any notification matching the given mask.
 

Private Member Functions

void getTemperature (HttpRequest &req, HttpResponse &res, const RouteMatch &match)
 
void getLedState (HttpRequest &req, HttpResponse &res, const RouteMatch &match)
 
void setLedState (HttpRequest &req, HttpResponse &res, const RouteMatch &match)
 
void uploadHandler (HttpRequest &req, HttpResponse &res, const RouteMatch &match)
 
void deleteFile (HttpRequest &req, HttpResponse &res, const RouteMatch &match)
 

Private Attributes

PicoModelpico
 

Additional Inherited Members

- Protected Member Functions inherited from FrameworkController
virtual void onStart ()
 Called once at task start before entering the main loop.
 
virtual void onEvent (const Event &event)
 Called when an event is dispatched to this controller.
 
virtual TickType_t getPollIntervalTicks ()
 Returns the polling interval in ticks used in run().
 
virtual void poll ()
 Called during every loop iteration for non-blocking background logic.
 
void runEvery (uint32_t intervalMs, const std::function< void()> &fn, const char *id)
 Run a function periodically with millisecond resolution.
 
- Protected Member Functions inherited from FrameworkTask
uint32_t waitFor (TickType_t timeout=portMAX_DELAY)
 Wait for any notification (default index).
 
bool createQueue (size_t itemSize, size_t length)
 Creates an internal FreeRTOS queue.
 
bool sendToQueue (const void *item, TickType_t timeout=0)
 Sends an item to the internal queue.
 
bool receiveFromQueue (void *item, TickType_t timeout=portMAX_DELAY)
 Receives an item from the internal queue.
 
- Protected Attributes inherited from FrameworkController
Routerrouter
 Handles path-to-handler mapping - reference to shared Router instance.
 
- Protected Attributes inherited from FrameworkTask
const char * _name
 
uint16_t _stackSize
 
UBaseType_t _priority
 
TaskHandle_t _handle = nullptr
 
QueueHandle_t _queue = nullptr
 

Detailed Description

Definition at line 26 of file DashboardController.h.

Constructor & Destructor Documentation

◆ DashboardController()

DashboardController::DashboardController ( Router r,
PicoModel pico 
)

Definition at line 12 of file DashboardController.cpp.

13 : FrameworkController("DashboardController", r, 1024, 1), pico(pico) {}
Base class for event-driven control logic in embedded applications.

Member Function Documentation

◆ deleteFile()

void DashboardController::deleteFile ( HttpRequest req,
HttpResponse res,
const RouteMatch match 
)
private

Definition at line 103 of file DashboardController.cpp.

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}
static constexpr std::uintptr_t getTypeKey()
Definition AppContext.h:91
HttpResponse & sendSuccess(const nlohmann::json &data={}, const std::string &message="")
HttpResponse & sendError(int statusCode, const std::string &code, const std::string &message)
std::optional< std::string > getParam(const std::string &name) const
Definition RouteTypes.h:22

References RouteMatch::getParam(), AppContext::getTypeKey(), HttpResponse::sendError(), and HttpResponse::sendSuccess().

Referenced by initRoutes().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getLedState()

void DashboardController::getLedState ( HttpRequest req,
HttpResponse res,
const RouteMatch match 
)
private

Definition at line 85 of file DashboardController.cpp.

86{
87 bool isOn = pico.getLedState(); // Get LED state from pico model
88 res.json({{"state", isOn ? 1 : 0}});
89}
HttpResponse & json(const std::string &jsonString)
Send a JSON string/object with correct content type.
bool getLedState()
Definition PicoModel.cpp:43

References PicoModel::getLedState(), HttpResponse::json(), and pico.

Referenced by initRoutes().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getTemperature()

void DashboardController::getTemperature ( HttpRequest req,
HttpResponse res,
const RouteMatch match 
)
private

Definition at line 79 of file DashboardController.cpp.

80{
81 float tempC = pico.getTemperature(); // Get temperature from pico model
82 res.json({{"temperature", tempC}});
83}
float getTemperature()
Definition PicoModel.cpp:24

References PicoModel::getTemperature(), HttpResponse::json(), and pico.

Referenced by initRoutes().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ initRoutes()

void DashboardController::initRoutes ( )
overridevirtual

@bcopydoc FrameworkController::initRoutes

Override to define HTTP routes or other event handlers. This is called once at task start.

Reimplemented from FrameworkController.

Definition at line 15 of file DashboardController.cpp.

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}
void getLedState(HttpRequest &req, HttpResponse &res, const RouteMatch &match)
void deleteFile(HttpRequest &req, HttpResponse &res, const RouteMatch &match)
void uploadHandler(HttpRequest &req, HttpResponse &res, const RouteMatch &match)
void setLedState(HttpRequest &req, HttpResponse &res, const RouteMatch &match)
void getTemperature(HttpRequest &req, HttpResponse &res, const RouteMatch &match)
Router & router
Handles path-to-handler mapping - reference to shared Router instance.
Forward declaration for potential routing needs.
Definition HttpRequest.h:32
Represents an HTTP response object.
HttpResponse & setContentType(const std::string &content_type)
Set the Content-Type header.
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.
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

References Router::addCatchAllGetRoute(), Router::addRoute(), deleteFile(), getLedState(), getTemperature(), Router::listDirectory(), FrameworkController::router, HttpResponse::send(), HttpResponse::sendFile(), Router::serveStatic(), HttpResponse::setContentType(), setLedState(), and uploadHandler().

+ Here is the call graph for this function:

◆ setLedState()

void DashboardController::setLedState ( HttpRequest req,
HttpResponse res,
const RouteMatch match 
)
private

Definition at line 91 of file DashboardController.cpp.

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}
void setLedState(bool state)
Definition PicoModel.cpp:34

References RouteMatch::getParam(), HttpResponse::json(), pico, and PicoModel::setLedState().

Referenced by initRoutes().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ uploadHandler()

void DashboardController::uploadHandler ( HttpRequest req,
HttpResponse res,
const RouteMatch match 
)
private

Definition at line 98 of file DashboardController.cpp.

99{
100 req.handle_multipart(res);
101}
int handle_multipart(HttpResponse &res)
Handle multipart/form-data uploads.

References HttpRequest::handle_multipart().

Referenced by initRoutes().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

Member Data Documentation

◆ pico

PicoModel& DashboardController::pico
private

Definition at line 38 of file DashboardController.h.

Referenced by getLedState(), getTemperature(), and setLedState().


The documentation for this class was generated from the following files: