# PDI-2025: Practice 4: TC/TM processing
Satellite instruments generate scientific data and other metadata onboard spacecraft. These data must be reliably and transparently transmitted to other computing systems in space or on Earth, which implies the need to encode and decode these data in a standardized and highly automated manner.
The Consultative Committee for Space Data Systems (CCSDS) is an international organization composed of various space agencies to recommend and develop international standards for spacecraft data and information systems. CCSDS has developed international standards for the transmission of space-acquired data from source to users, resulting in easier cooperation and service delivery. Packet telemetry provides a mechanism for implementing common data structures and protocols.

## CCSDS/PUS Packet brief


```c=
/**
* \brief Structure type to the Packet Header field of a TM/TC packet.
*/
struct ccds_pus_tmtc_packet_header {
uint16_t packet_id; // Version 3 bits, Type 1 bit, Flag 1 bit, APID 11 bits
uint16_t packet_seq_ctrl;
uint16_t packet_length;
};
/**
* \brief Structure type to store the Data Field Header field of a TC packet.
*/
struct ccds_pus_tc_df_header {
uint8_t flag_ver_ack; // flag_version four MSB => 0001, ACK four LSB bits
uint8_t type;
uint8_t subtype;
uint8_t sourceID;
};
/**
* \brief Structure type to store the Data Field Header field of a TM packet.
*/
struct ccds_pus_tm_df_header {
uint8_t version; // Always 0X10
uint8_t type;
uint8_t subtype;
uint8_t destinationID;
};
```
## TEST service sequence
The TEST service uses code 17, subtypes 1 and 2.
* TC[17,1]: request "are-you-alive connection test".
* TM[17,2]: response "are-you-alive connection test report".
The system receives a TC[17, 1] packet and generates a TM[17,2] packet as a response without associated data.

<!--
## Request Verification service sequence
After receiving a telecommand, the ACK acknowledgement four bits in the TC header must be checked.
* Bit 3: ack of successful acceptance. 1 => TM(1,1) required; 0 => TM(1,1) not required
* Bit 2: X, not used.
* Bit 1: X, not used.
* Bit 0: ack of successful execution. 1 => TM(1,7) is required; 0 => TM(1,7) not required.
In case it is requested in the TC, a report of correct acceptance TM(1,1) is generated. If after its execution everything has been performed correctly, a TM(1,7) successful execution telemetry is generated, which is shown in the figure on the left. In case an error occurs while executing, it is reported with TM (1,8), as shown in the following figures.
-->
### Failed acceptance
In the event that the format and integrity of the telecommand is checked and an error is found, a failed acceptance TM (1,2) telemetry is generated. For example if the TC type or subtype is unknown or the CRC does not match.

<!--
### Successful acceptance and failed execution

-->
## Response TM formats
The following figure describes the general structure of the TM packets. It is important to remain that in addition to the information shown, the CRC must be added at the end.

## P4 general design
The figure below shows the software architecture of the application. It is composed of two components communicated by means of a FIFO.
1. Main configures UART controller
2. UART isr reads a TC sequence and PUSH it into a FIFO when TC is complete
3. Main waits in a super-loop and POP TC from FIFO. The POP operation is a critical section since the access to the FIFO buffer is not atomic. Therefore, it must be carried in mutual exclusion.

### ISR state machine
The steps followed by the UART ISR is decribed in the following figure. Three states have been defined:
* IDLE: Begin of the sequence, all data before 0x1B is ignored. When 0x1B is received it is saved and state chages to ```READING_CCSDS_HEADER```.
* READING_CCSDS_HEADER: Reads the TC header. Saves each data received until ccsds packet header size is reached. Then state changes to ```READING_PACKET_DF```.
* READING_PACKET_DF: Reads the packet data field, this include the data field header, the application data (if exists) and the ```CRC```. When TC complete PUSH it into the FIFO and state returns to ```IDLE```.

## Development steps
Download P4_SKEL project from [P4_SKEL](https://drive.google.com/file/d/1PMAQgXmfGpXbwy2sRYSaZIhEf5HjrFWn/view?usp=sharing) and import it in eclipse. Study the code and understand the overall structure. You can also see the skeleton code of the practice at the link [P4 Skeleton](https://hackmd.io/@dasilvin/PDI-P4-SKEL)
First, pay attention to the fifo implementation in ```tc_fifo.c``` and ```tc_fifo.h```.
After that, identify the following elements to be completed:
* ```uart_rx_irq_handler``` ISR in ```tm_tc_handling.c```.
* Super-loop in ```main.c```.
* ```build_response_tm_1_1```, ```build_response_tm_1_2```, ```build_response_tm_1_7``` and ```build_response_tm_1_8``` in ```tm_tc_handling.c```. As an example, ```build_response_tm_17_2``` is already coded.
* ```processTC``` in ```main.c```.
### Phase 1: Receive TC and print the sequence in main
Implement the UART ISR according to the state machine described above. When the TC is complete **PUSH** it into de FIFO.
The main program will wait in a super loop until fifo is not empty. At that time **POPs** the TC and print its contents to verify that the TC has been completely received.
#### Code Snippets
The variable ```tc_fifo``` is declared in ```tc_fifo.c``` and defined as ```extern``` in ```tc_fifo.h```
```c=
// How to use tc_fifo variable
// tc_fifo is used in tc_fifo.c, main.c and tm_tc_handling.c
// Initilization of tc_fifo in main.c
tc_fifo_init( &tc_fifo );
// Pushing tc_bufer into tc_fifo, tc_fifo_push returns 0 if FIFO is full
uint8_t err = tc_fifo_push( &tc_fifo, tc_buffer, bytes_to_read );
// Poping tc_len bytes from tc_fifo and store them in tc_bytes, tc_fifo_pop returns 0 if FIFO is empty
uint8_t err = tc_fifo_pop( &tc_fifo, tc_bytes, &tc_len );
// Asking if tc_fifo is not empty, return 1 if tc_fifo is not empty
uint8_t not_empty = tc_fifo_not_empty( &tc_fifo );
// Print the tc_len bytes of tc_bytes
print_buffer( tc_bytes, tc_len);
```
Test it using using cutecom program. The hex sequence 1B 2C C0 01 00 05 10 11 01 19 D3 7D corresponds to the following valid TC(17,1).
:::spoiler Main code example
```c=
while(1)
{
/*
* if FIFO is not empty
* POP TC in mutual exclusion to avoid UART IRQ
* Just print received TC
*/
//----------
if ( tc_fifo_not_empty( &tc_fifo) )
{
plic_irq_mask( UART_IRQ ); // PLIC UART irq mask
tc_fifo_pop( &tc_fifo, tc_bytes, &tc_len );
plic_irq_unmask( UART_IRQ ); // PLIC UART irq unmask
print_buffer( tc_bytes, tc_len );
// processTC( tc_bytes, tc_len );
}
//----------
}
```
:::
---
### Phase 2: Nominal response to TC(17, 1)

The figure above shows the general flow of TC processing.
The function ```build_response_tm_17_2``` is already coded and provided as an example. Study and understand how it works.
Modify the ```processTC``` function to build and send the nominal response to TC(17,1)
```c=
/*
if TM(1,1) required {
printf("TM(1,1)\n");
build TM(1,1) and sendTM
}
*/
// build TM(17,2) and sendTM
printf("TC(17,1) ---> TM(17,2)\n");
tm_len = build_response_tm_17_2(tm_bytes, tm_seq_counter++, tc_packet_id, tc_packet_seq_ctrl );
sendTM( tm_bytes, tm_len );
/*
if (TM1,7) required {
printf("TM(1,7)\n");
build TM(1,7) and sendTM
}
*/
```
Test it using using ```cutecom``` program. The hex sequence ```1B 2C C0 01 00 05 10 11 01 19 D3 7D``` corresponds to the following valid TC(17,1).
```
-------- DATA PKT --------
PACKET PRIMARY HEADER ... 1B 2C C0 01 00 05
VERSION: 0
TYPE: 1 (TC)
PKT SEC HDR FLAG: 1 (YES)
APID: 812 (0x32C)
SEQUENCE FLAGS: 3
PACKET SEQUENCE: 1 (0x1)
PKT DATA LEN: 5 (6 bytes - 1)
PACKET DATA FIELD...
PKT SEC HDR (PUS) ..... 10 11 01 19
VERSION: 1
ACK: 0
SERVICE TYPE: 17
SERVICE SUBTYPE: 1
SOURCE ID: 25 (0x19)
<NO DATA>
CRC: 54141 (0xD37D)
-------------------------------------------
```
The response must be the following TM(17,2): ```0B 2C C0 01 00 05 10 11 02 78 6E 3F```
```
-------- DATA PKT --------
PACKET PRIMARY HEADER ... 0B 2C C0 01 00 05
VERSION: 0
TYPE: 0 (TM)
PKT SEC HDR FLAG: 1 (YES)
APID: 812 (0x32C)
SEQUENCE FLAGS: 3
PACKET SEQUENCE: 1 (0x1)
PKT DATA LEN: 5 (6 bytes - 1)
PACKET DATA FIELD...
PKT SEC HDR (PUS) ..... 10 11 02 78
VERSION: 1
SERVICE TYPE: 17
SERVICE SUBTYPE: 2
DESTINATION ID: 120 (0x78)
<NO DATA>
CRC: 28223 (0x6E3F)
-------------------------------------------
```
:::success
:raising_hand: Locate de service type and subtype inside both binary sequences.
* TC(17,1): ```1B 2C C0 01 00 05 10 11 01 19 D3 7D```
* TM(17,2): ```0B 2C C0 01 00 05 10 11 02 78 6E 3F```
:::
---
### Phase 3: TM(1,2) error response
#### CRC error
Code the ```build_response_tm_1_2``` function. Change a byte of the nominal TC(17, 1) sequence used above, this should provoque a CRC error. See the generated TM(1,2).
For example, for a CRC error (CRC_ERROR_CODE=1), the TM(1,2) should be ```0B 2C C0 01 00 0A 10 01 02 78 00 00 1B 2C 01 A5 4E```
```
-------- DATA PKT --------
PACKET PRIMARY HEADER ... 0B 2C C0 01 00 0A
VERSION: 0
TYPE: 0 (TM)
PKT SEC HDR FLAG: 1 (YES)
APID: 812 (0x32C)
SEQUENCE FLAGS: 3
PACKET SEQUENCE: 1 (0x1)
PKT DATA LEN: 10 (11 bytes - 1)
PACKET DATA FIELD...
PKT SEC HDR (PUS) ..... 10 01 02 78
VERSION: 1
SERVICE TYPE: 1
SERVICE SUBTYPE: 2
DESTINATION ID: 120 (0x78)
DATA: 00 00 1B 2C 01
CRC: 42318 (0xA54E)
-------------------------------------------
```
---
#### Service unknown error
Test the sequence ```1B 2C C0 01 00 05 10 12 01 19 8A 2D``` corresponding to the following valid TC(18,1).
```
-------- DATA PKT --------
PACKET PRIMARY HEADER ... 1B 2C C0 01 00 05
VERSION: 0
TYPE: 1 (TC)
PKT SEC HDR FLAG: 1 (YES)
APID: 812 (0x32C)
SEQUENCE FLAGS: 3
PACKET SEQUENCE: 1 (0x1)
PKT DATA LEN: 5 (6 bytes - 1)
PACKET DATA FIELD...
PKT SEC HDR (PUS) ..... 10 11 01 19
VERSION: 1
ACK: 0
SERVICE TYPE: 18
SERVICE SUBTYPE: 1
SOURCE ID: 25 (0x19)
<NO DATA>
CRC: 35373 (0x8A2D)
-------------------------------------------
```
In this case, since the program only accepts TC(17,1), the TM(1,2) for a service unknown error (SERVICE_UNKNOWN_ERROR_CODE=2) should be ```0B 2C C0 01 00 0A 10 01 02 78 00 00 1B 2C 02 95 2D```
```
-------- DATA PKT --------
PACKET PRIMARY HEADER ... 0B 2C C0 01 00 0A
VERSION: 0
TYPE: 0 (TM)
PKT SEC HDR FLAG: 1 (YES)
APID: 812 (0x32C)
SEQUENCE FLAGS: 3
PACKET SEQUENCE: 1 (0x1)
PKT DATA LEN: 10 (11 bytes - 1)
PACKET DATA FIELD...
PKT SEC HDR (PUS) ..... 10 01 02 78
VERSION: 1
SERVICE TYPE: 1
SERVICE SUBTYPE: 2
DESTINATION ID: 120 (0x78)
DATA: 00 00 1B 2C 02
CRC: 38189 (0x952D)
-------------------------------------------
```
:::success
:raising_hand: Locate de service type, subtype, application id and response error code inside both binary sequences.
* TM(1,2) (CRC error): ```0B 2C C0 01 00 0A 10 01 02 78 00 00 1B 2C 01 A5 4E```
* TM(1,2) (Service Unknown): ```0B 2C C0 01 00 0A 10 01 02 78 00 00 1B 2C 02 95 2D```
:::
### Phase 4: ACK field processing
After receiving a telecommand, the ACK acknowledgement four bits in the TC header must be checked.
* Bit 3: ack of successful acceptance. 1 => TM(1,1) required; 0 => TM(1,1) not required
* Bit 2: X, not used.
* Bit 1: X, not used.
* Bit 0: ack of successful execution. 1 => TM(1,7) is required; 0 => TM(1,7) not required.
In case it is requested in the TC, a report of correct acceptance TM(1,1) is generated. If after its execution everything has been performed correctly, a TM(1,7) successful execution telemetry is generated, which is shown in the figure on the left. In case an error occurs while executing, it is reported with TM (1,8), as shown in the following figures.
### Acceptance and successful execution

---
### Complete Execution Flow

Process ACK field and code the TM(1,1) and TM(1,7) and use the followings TC sequences to test all the combinations of TC ACK field:
| ACK | Valid TC(17,1)| Response |
| -------- | -------- | ---------
| 0000 | ```1B 2C C0 01 00 05 10 11 01 19 D3 7D``` | TM(17,2) |
| 0001 | ```1B 2C C0 01 00 05 11 11 01 19 A5 C9``` | TM(17,2) TM(1,7) |
| 1000 | ```1B 2C C0 01 00 05 18 11 01 19 56 BE``` | TM(1,1) TM(17,2) |
| 1001 | ```1B 2C C0 01 00 05 19 11 01 19 20 0A``` | TM(1,1) TM(17,2) TM(1,7) |
:::success
:raising_hand: Locate de ACK bits in the TC request described above.
:raising_hand: Locate the ```TM(1,1)``` ```TM(17,2)``` ```TM(1,7)``` response to ```TC(17,1)``` in the ```cutecom``` window. 
:::
It is not necessary to code the TM(1,8) corresponding to an erroneous execution of the TC since we are not going to test it.
---
### Phase 5: TC receiving timeout
Add a time reception control to the program so that each TC is received completely within a time span of one second.
If a TC is not received complete in that interval the ISR status must be reset and a new TC is expected to start.
In order to test it use```cutecom``` program to send an incomplete TC. For example the hex sequence ```1B 2C C0 01 00 05``` is just the header of a TC.
Testing steps:
* Send a valid TC(17,1) and verify that valid TM(17,2) response is received.
* Send just the header of a TC and wait until timer resets ISR state.
* Send again a valid TC(17,1) and verify that a valid TM(17,2) response is received.
---
#### Bonus: Error lights activation
Add the necessary logic to activate leds when an error condition occurs.
* Led0 when a TC with an invalid CRC is received.
* Led1 when a TC with unknown service code is received.
All leds indication will be cleared when P0 pushbutton is pressed.