Skip to content

Commit df41175

Browse files
committed
docs(openwrt-config-dashboard): add documentation for api cals to JSON-RPC openwrt (thymio2+)
1 parent b62c37c commit df41175

10 files changed

+104
-133
lines changed

apps/openwrt-config-dashboard/src/hooks/useLuciRCPjsonClient/GettingStarded.stories.mdx

+1-26
Original file line numberDiff line numberDiff line change
@@ -16,34 +16,12 @@ import { Meta, Description } from '@storybook/addon-docs'
1616

1717
This document provides a detailed guide on using the React hook for managing the state of an XState machine. This hook allows interacting with a state machine defined using the XState library in React applications.
1818

19-
## Imports and Configuration
19+
## Modules and Configurations
2020

2121
The React hook for managing the state of the XState machine is used to connect React components with state machines defined in XState. First, we import the necessary functions and tools:
2222

23-
```javascript
24-
import React, { createContext, useContext, useEffect, useRef, useState } from 'react';
25-
import { useActor } from '@xstate/react';
26-
import { Actions, assign, createMachine, DoneInvokeEvent, interpret, send } from 'xstate';
27-
import { getLoginSid } from './fetchCalls/getLoginToken';
28-
import { getDevices } from './fetchCalls/getAllDevicesIP:Name';
29-
import { getWifiStatus } from './fetchCalls/getWifiStatus';
30-
import { getInternetStatus } from './fetchCalls/getInternetStatus';
31-
import { ContextData, Event, ServiceEvent, initialState } from '.';
32-
import { createClient, IGroup, INode, Variables } from '@mobsya-association/thymio-api';
33-
import { getWifiConfigFile } from './fetchCalls/getWifiConfigFile';
34-
import { getUptime } from './fetchCalls/getUptime';
35-
import { getIfStatus } from './fetchCalls/getIfstatus';
36-
import CryptoJS from 'crypto-js';
37-
```
38-
3923
| Module or Function | Description |
4024
|---------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
41-
| `React` | Provides access to core React functions and components, allowing the creation of components and state management in React applications. |
42-
| `createContext` | Creates a React context, enabling data sharing between components without manually passing props through each level of the component tree. |
43-
| `useContext` | Allows accessing the value of the React context in a functional component, enabling consuming the context and using its value anywhere within the component. |
44-
| `useEffect` | Enables executing side effects in React components, such as subscriptions to external data, DOM updates, and resource cleanup. |
45-
| `useRef` | Creates a mutable reference that persists throughout the component's lifecycle, primarily used for accessing DOM nodes or mutable values without causing additional re-renders. |
46-
| `useState` | Adds local state to functional components in React, allowing declaring state variables within a functional component and updating them using the `setState` method. |
4725
| `useActor` | Provides access to XState actors in React components, allowing subscribing to changes in actor state and sending events to state machines. |
4826
| `Actions` | Provides functions and utilities for defining actions within XState machines, representing operations performed in response to events. |
4927
| `assign` | Defines an action that assigns values to properties of the state machine's context. |
@@ -319,6 +297,3 @@ export const useEmitter = () => {
319297
320298
Overall, these custom hooks encapsulate the logic for accessing state data, obtaining the current state of the state machine, and sending events to the state machine. They provide convenient abstractions for interacting with the state machine within React components, promoting code reusability and maintainability.
321299
322-
## Conclusion
323-
324-
The React hook for managing the state of the XState machine provides an efficient and straightforward way to interact with state machines in React applications. By following this guide, developers can easily integrate state machine logic into their React components in an organized and efficient manner.

apps/openwrt-config-dashboard/src/hooks/useLuciRCPjsonClient/fetchCalls/getAllDevicesIP:Name.ts

-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { Sid } from '..';
22

33
function matchesThymioPattern(str: string): boolean {
4-
// Expresión regular para coincidir con el patrón 'Thymio-XXXXXX.lan'
54
const pattern = /Thymio-[a-zA-Z0-9]+\.lan/;
65
return !pattern.test(str);
76
}
@@ -55,7 +54,6 @@ export async function getDevices({ sid }: { sid: Sid }): Promise<Array<any>> {
5554
id: device[1],
5655
}));
5756

58-
// fusione macs and devices by id key
5957
devices.forEach((device: { ip: string; id: string; mac: string; active: boolean }) => {
6058
const deviceByMac = macs?.find((mac: { mac: string; id: string }) => mac.id === device.id);
6159
if (device && deviceByMac) {

apps/openwrt-config-dashboard/src/hooks/useLuciRCPjsonClient/fetchCalls/getAllDevicesIP:Names.stories.mdx

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import { Meta, Description } from '@storybook/addon-docs'
1212

1313
# Get All Devices
1414

15-
### Function: `getDevices`
15+
### API CALL: `getDevices`
1616

1717
This function retrieves the devices connected to the Thymio2+ router, particularly tablets.
1818

apps/openwrt-config-dashboard/src/hooks/useLuciRCPjsonClient/fetchCalls/getIfstatus.stories.mdx

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import { Meta, Description } from '@storybook/addon-docs'
1212

1313
# Get Network Status
1414

15-
### Function: `getIfStatus`
15+
### API CALL: : `getIfStatus`
1616

1717
This function retrieves the status of the network interface from the router.
1818

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import { Meta, Description } from '@storybook/addon-docs'
2+
3+
<Meta
4+
title="HTTP CAlls/get internet status"
5+
parameters={{
6+
viewMode: 'docs',
7+
previewTabs: {
8+
canvas: { hidden: true }
9+
},
10+
}}
11+
/>
12+
13+
# Get Internet Status
14+
15+
### API CALL: getInternetStatus
16+
17+
#### Overview
18+
The `getInternetStatus` function checks if the device has an active internet connection by attempting to reach Google's homepage. It returns a boolean value indicating whether the internet is accessible.
19+
20+
#### Imports
21+
```javascript
22+
import axios, { AxiosRequestConfig } from 'axios';
23+
import { Sid } from '..';
24+
```
25+
- **axios**: Used for making HTTP requests.
26+
- **AxiosRequestConfig**: Type used for configuring the axios request.
27+
- **Sid**: A type imported from the parent directory, presumably representing session ID or similar credentials.
28+
29+
#### Parameters
30+
- `sid`: A session identifier of type `Sid`, required to authenticate or manage the session context for the request.
31+
32+
#### Returns
33+
- **Promise of boolean**: ```Promise<boolean>``` A promise that resolves to `true` if the internet is reachable, otherwise `false`.
34+
35+
#### Function Logic
36+
1. **Prepare the Request:**
37+
- The function constructs a JSON string that includes the command to check internet connectivity by using `wget` to quietly fetch Google's homepage.
38+
- The command will print 'true' if the fetch is successful, and 'false' otherwise.
39+
40+
```javascript
41+
const data = JSON.stringify({
42+
method: 'exec',
43+
params: ["wget -q --spider http://www.google.com 2>/dev/null && echo 'true' || echo 'false'"],
44+
});
45+
```
46+
47+
2. **Configure the Request:**
48+
- An axios configuration object is set up, specifying the HTTP method, URL endpoint, headers, data, and timeout for the request.
49+
50+
```javascript
51+
const config: AxiosRequestConfig = {
52+
method: 'post',
53+
url: '/cgi-bin/luci/rpc/sys',
54+
headers: {
55+
'Content-Type': 'application/json',
56+
},
57+
data: data,
58+
timeout: 4000,
59+
};
60+
```
61+
62+
3. **Execute the Request and Handle Response:**
63+
- The axios library is used to send the configured request asynchronously.
64+
- If the HTTP response status is not 200, an error is thrown.
65+
- The function checks if the response contains 'true' within the result field to determine internet connectivity.
66+
67+
```javascript
68+
const response = await axios(config);
69+
if (response.status !== 200) {
70+
throw new Error('Error fetching getWifiConfigFile');
71+
}
72+
return response.data.result.includes('true');
73+
```
74+
75+
4. **Error Handling:**
76+
- The catch block handles various errors such as axios cancellation due to timeout, server responses indicating failure, no response received, or other axios errors.
77+
- In any error scenario, the function returns `false`, indicating no internet connectivity.
78+
79+
```javascript
80+
catch (error: any) {
81+
if (axios.isCancel(error)) {
82+
// Request was cancelled due to timeout
83+
return false;
84+
} else if (error.response) {
85+
// Server responded with an error
86+
return false;
87+
} else if (error.request) {
88+
// No response was received
89+
return false;
90+
} else {
91+
// Other errors
92+
console.log('Error:', error.message);
93+
}
94+
return false;
95+
}
96+
```
97+
98+
#### Usage Example
99+
```javascript
100+
const isConnected = await getInternetStatus({ sid: yourSessionId })
101+
```

apps/openwrt-config-dashboard/src/hooks/useLuciRCPjsonClient/fetchCalls/getInternetStatus.ts

-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import axios, { AxiosRequestConfig } from 'axios';
22
import { Sid } from '..';
33

44
export async function getInternetStatus({ sid }: { sid: Sid }): Promise<boolean> {
5-
// Preparar el cuerpo de la solicitud y las cabeceras
65
const data = JSON.stringify({
76
method: 'exec',
87
params: ["wget -q --spider http://www.google.com 2>/dev/null && echo 'true' || echo 'false'"],
@@ -21,21 +20,17 @@ export async function getInternetStatus({ sid }: { sid: Sid }): Promise<boolean>
2120
try {
2221
const response = await axios(config);
2322

24-
// Verificar el estado de la respuesta
2523
if (response.status !== 200) {
2624
throw new Error('Error fetching getWifiConfigFile');
2725
}
2826

2927
return response.data.result.includes('true');
3028
} catch (error: any) {
3129
if (axios.isCancel(error)) {
32-
// console.log('La solicitud ha sido cancelada debido a un timeout');
3330
return false;
3431
} else if (error.response) {
35-
// console.log('Error response:', error.response.data);
3632
return false;
3733
} else if (error.request) {
38-
// console.log('No response received:', error.request);
3934
return false;
4035
} else {
4136
console.log('Error:', error.message);

docker-compose.yml

-27
This file was deleted.

dockerBuild.sh

-5
This file was deleted.

dockerfile

-21
This file was deleted.

infozeroconf.py

-45
This file was deleted.

0 commit comments

Comments
 (0)