# Protocol Commands and Responses

The **CloudBox Protocol** is a set of commands and responses designed to control, configure, and monitor the CloudBox timing system. These commands allow you to manage timing sessions, configure system settings, check system statuses, and perform various network functions. Below is a detailed explanation of all the commands, including their possible responses and error codes.

## Protocol Command Format

When sending commands to the CloudBox via TCP socket, the commands must always be sent as **plain text** in a specific format. The general structure of the command follows these rules:

1. **Command Name**: The first part of the command is the name of the action you want to perform (e.g., `CHANGESYSTEMIPADDRESS`).
2. **Arguments**: Any required or optional arguments must be passed **in order**, separated by **semicolons (`;`)**.
3. **Termination**: Each command must be terminated with the characters `\r` (carriage return and newline) to signal the end of the command.

**Command Format Example**

For example, when sending the `CHANGESYSTEMIPADDRESS` command with the required arguments for IP address, port, and subnet, the format would be:

```plaintext
CHANGESYSTEMIPADDRESS;192.168.1.100;8080;/24\r\n
```

In this example:

* `CHANGESYSTEMIPADDRESS`: The name of the command.
* `192.168.1.100`: The new IP address to assign to the system.
* `8080`: The new port to assign.
* `/24`: The subnet mask.
* `\r`: Marks the end of the command.

## Protocol Response Format

In the CloudBox protocol, the responses to commands are always structured in a **JSON format**, following a consistent pattern. Each response contains two main keys:

1. **command**: This key specifies the command that was sent to the CloudBox. It confirms what action or query was requested.
2. **result**: This key contains the actual result or data returned by the system based on the command executed.

Here is an example of a typical response for the `GETSYSTEMTIME` command:

```json
{
    "command": "GETSYSTEMTIME",
    "result": {
        "dateTimeSync": "NTP",
        "timezone": "Europe/Madrid (CEST, +0200)",
        "timestamp": "2024-09-17;18:44:11.649"
    }
}
```

## Key Commands and Responses

### **1. START**

Initiates the start of the timing session.

**Responses**:

* `START_MODE`: The system is already in timing mode.
* `READERNOTOK`: The RFID reader is not present or functioning correctly.
* `DEVICE_INTEGRITY_FAILED`: The integrity check of the device has failed.
* `INVALIDREADERMODEL`: The configured reader model is not valid.
* `ERRREADER`: General reader error.
* `OK`: The timing session has started successfully.

### **2. STOP**

Stops the current timing session.

**Responses**:

* `READERNOTOK`: The RFID reader is not present or functioning correctly.
* `INVALIDREADERMODEL`: The configured reader model is not valid.
* `ERRREADER`: General reader error.
* `OK`: The session has stopped successfully.

### **3. GETSYSTEMSTATUS**

Returns the current status of the system, including battery level, 4G network connection status, GPS status, and more.

**Response Example**:

```json
{
  "batteryVolts": "25.33",
  "batteryPercentage": "88.27",
  "cpuTemperature": "53.75",
  "hasPower": false,
  "hasInternet": true,
  "startMode": false,
  "sessionPassingCount": 0,
  "lastPassingTimestamp": null,
  "operator4G": null,
  "signal4G": null,
  "networkService4G": null,
  "status4G": {"status": "CME_ERROR", "message": "SIM not inserted"},
  "statusGps": {"status": "SEARCHING", "message": "No GPS data found. Searching..."},
  "statusIoT": {"status": true, "message": "Connected to IoT server"},
  "backupDownloadLink": "http://192.168.0.3:2999/download",
  "sessionToken": null,
  "cloudPassingCount": 0,
  "deviceIntegrity": "Device integrity check passed",
  "readerStatus": "RFID Reader not found",
  "updateInfo": null,
  "currentBackendVersion": "1.0.4",
  "currentFrontVersion": "1.0.4"
}
```

### **4. GETSYSTEMCONFIG**

Fetches the current system configuration, including network settings, reader configuration, and system parameters.

**Response Example**:

```json
{
  "bounceTime": 1,
  "buzzerPassings": false,
  "readerModel": "R420",
  "readerHost": "10.0.0.2",
  "readerPort": "5084",
  "tcpHost": "192.168.0.3",
  "tcpSubnet": "/8",
  "tcpPort": "8080",
  "apName": "CLBX_192_168_0_3",
  "wifiSsid": "MOVISTAR_91DA",
  "disableStartButton": false,
  "dateTimeSync": "NTP",
  "timezone": "America/Argentina/Buenos_Aires",
  "simPin": "4509",
  "modemImei": "862636053313696",
  "deviceSerialNumber": "CLBX10001"
}
```

### **5. SETSYSTEMTIME;timestamp**

Sets the system time. The format is `YYYY-MM-DD HH:mm:ss`.

**Responses**:

* `BAD_FORMAT`: The date or time format is incorrect.
* `START_MODE`: The system is in timing mode and the command cannot be executed.
* `NTPACTIVE`: NTP synchronization is active, and manual time changes are disabled.
* `CMDERROR`: General command error.
* `OK`: The system time has been set successfully.

### **6. GETSYSTEMTIME**

Returns the current system time, time zone, and synchronization settings.

**Response Example**:

```json
{
  "dateTimeSync": "NTP",
  "timezone": "Europe/Madrid (CEST, +0200)",
  "timestamp": "2024-09-17;18:44:11.649"   
}
```

### **7. SETDATETIMESYNC;syncMode**

Sets the date and time synchronization mode. Available options are: `"DISABLED"`, `"GPS"`, `"NTP"`.

**Responses**:

* `START_MODE`: The system is in timing mode and the command cannot be executed.
* `SYNCNOTAVAILABLE`: The selected synchronization mode is not available.
* `OK`: The synchronization mode has been successfully set.

### **8. CHANGESYSTEMIPADDRESS;ip;port;subnet**

Changes the system's IP address, port, and subnet mask.

**Responses**:

* `START_MODE`: The system is in timing mode and the command cannot be executed.
* `INVALIDNETWORKCONFIGURATION`: The provided network configuration is invalid.
* `INVALIDNETWORKSUBNET`: The subnet mask is invalid.
* `RESERVEDIPADDRESS`: The IP address is reserved.
* `STDERROR`: General application error.
* `OK`: Success. The system will restart to apply the new configuration.

### **9. SETBUZZERPASSINGS;value**

Enables or disables the buzzer for passing detections (true/false).

**Response**:

* `OK`: The buzzer setting has been successfully updated.

### **10. SETBOUNCETIME;seconds**

Sets the bounce time between RFID reads. If seconds is `null` or <= 0, the default value is 5 seconds.

**Response**:

* `OK`: The bounce time has been successfully set.

### **11. SHUTDOWN**

Shuts down the system after 10-15 seconds.

**Responses**:

* `START_MODE`: The system is in timing mode and the command cannot be executed.
* `OK`: The system will shut down.

### **12. LISTBACKUPFILES**

Returns a list of available backup files. Example: `["20240712-135902.txt"]`

**Responses**:

* `ERROR`: Failed to retrieve the backup files.
* `OK`: Successfully retrieved the list of files.

### **13. DELETEBACKUPFILES**

Deletes all backup files from the system.

**Responses**:

* `START_MODE`: The system is in timing mode and the command cannot be executed.
* `ERROR`: Failed to delete the files.
* `OK`: The backup files have been successfully deleted.

### **14. REWIND;startTimestamp;endTimestamp**

Rewinds the passing data between the specified start and end timestamps (`YYYY-MM-DD HH:mm:ss`) and streams it to connected TCP clients.

**Response**:

* `OK`: The passing data is being streamed.

### **15. GETGPSINFO**

Returns the GPS information, including latitude, longitude, altitude, and last synchronization time.

**Response Example**:

```json
{
  "latitudeDecimal": 41.28425,
  "longitudeDecimal": 1.98251,
  "googleMapsLink": "https://www.google.com/maps/place/41.28425,1.98251",
  "gpsTimezone": "Europe/Madrid",
  "altitude": 38.7,
  "speed": 0,
  "lastSync": "2024-07-24 20:27:02"
}
```
