# SatLink 2 Protocol Reference - Complete Analysis
# Generated from reverse-engineering SatlinkLoggerCommunicator.exe

## Executive Summary

**Binary**: SatlinkLoggerCommunicator.exe (Delphi/VCL, Borland C++ Compiler, 2014)
**Device**: Sutron SatLink 2 Environmental Data Logger
**Connection**: RS-232 Serial via USB-to-Serial adapter
**Protocol**: Sutron SatLink 2 Command Protocol

### Key Findings
1. **Packet Format**: [SYNC1][0x00][LEN_H][LEN_L][OPCODE_H][OPCODE_L][SEQ][DATA...][CRC_H][CRC_L]
2. **Minimum Packet Size**: 10 bytes (8 header + 2 CRC)
3. **Maximum Data Length**: 1024 bytes (0x0400)
4. **Sequence Number**: Starts at 9 (0x09), increments per command, wraps at 0xFF
5. **Comm Object Size**: Minimum 0x90 bytes (144 bytes)
6. **279 Opcodes**: Complete opcode table reverse-engineered
7. **Sync Byte**: Likely 0x23 ('#') or 0x24 ('$') - needs validation
8. **CRC-16**: Reflected algorithm, table at 0x00685d74 (polynomial unknown)

---

## Serial Port Configuration

### From connect_port_full (0x0040a900):
```
CreateFileA(port_name, 0xc0000000, 0, NULL, 3, 0, NULL)
// Access: GENERIC_READ | GENERIC_WRITE
// Share: None
// Creation: OPEN_EXISTING

DCB:
  BaudRate = param_1[5]      // Configurable
  ByteSize = param_1+0x19    // Usually 8
  Parity = param_1+0x1a      // 0=None, 1=Odd, 2=Even
  StopBits = param_1+0x1b    // 0=1, 1=1.5, 2=2
  EofChar = 0x01
  
  // DTR/RTS control (based on param_1[6]):
  if param_1[6] == 0:
    // Standard mode
    fOutxCtsFlow = 0, fOutxDsrFlow = 0
    fRtsControl = 1 (RTS_HANDSHAKE)
    fDtrControl = 1 (DTR_HANDSHAKE)
  else:
    // Alternate mode
    fOutxCtsFlow = 1, fOutxDsrFlow = 1
    fRtsControl = 2 (RTS_ENABLE)
    fDtrControl = 2 (DTR_ENABLE)

COMMTIMEOUTS:
  ReadIntervalTimeout = 0xFFFFFFFF  // Immediate return
  ReadTotalTimeoutMultiplier = 0
  ReadTotalTimeoutConstant = 0
  WriteTotalTimeoutMultiplier = 10
  WriteTotalTimeoutConstant = 50    // 50ms
```

### Recommended Python Configuration:
```python
import serial
ser = serial.Serial(
    port='COM3',
    baudrate=9600,      # Or 19200, 38400, 115200
    bytesize=8,
    parity='N',
    stopbits=1,
    timeout=2.0,
    write_timeout=0.05
)
```

---

## Comm Object Structure

### Memory Layout (offsets from base):
| Offset | Size | Type | Initial Value | Description |
|--------|------|------|---------------|-------------|
| 0x00 | 4 | ptr | vtable | Virtual function table pointer |
| 0x04 | 4 | ptr | ? | Unknown |
| 0x08 | 4 | HANDLE | -1 | Serial port handle (INVALID_HANDLE_VALUE) |
| 0x0C | 4 | ptr | ? | Port name string pointer |
| 0x10 | 4 | ptr | ? | Unknown |
| 0x14 | 4 | int | 9600 | Baud rate |
| 0x18 | 1 | byte | ? | Unknown |
| 0x19 | 1 | byte | 8 | Byte size (data bits) |
| 0x1A | 1 | byte | 0 | Parity (0=None, 1=Odd, 2=Even) |
| 0x1B | 1 | byte | 0 | Stop bits (0=1, 1=1.5, 2=2) |
| 0x1C | 4 | ptr | ? | Unknown |
| 0x20 | 4 | ptr | ? | Unknown |
| ... | ... | ... | ... | ... |
| 0x68 | 1 | byte | ? | **HEADER_BYTE** (expected header for validation) |
| 0x69 | 1 | byte | 9 | **SEQ_NUM** (sequence number, initial value) |
| 0x6A | 1 | byte | 0x22 | **SECONDARY_SEQ** (secondary sequence/status) |
| 0x6B | 1 | byte | 0 | Unknown |
| 0x6C | 4 | int | 0 | **TIMESTAMP** (last activity, GetTickCount) |
| 0x70 | 4 | int | ? | **TIMEOUT** (inter-byte timeout value) |
| 0x74 | 4 | ptr | ? | Unknown |
| 0x78 | 1 | byte | 0 | **RETRY_FLAG** (retry control) |
| 0x79 | 1 | byte | ? | **MODE_FLAG** (header type: 0=standard, 1=alternate) |
| 0x7A | 1 | byte | 0 | **RESPONSE_FLAG** (1=complement match detected) |
| 0x7B | 1 | byte | 0 | Unknown |
| 0x7C | 4 | int | 0 | Last result code |
| 0x80 | 4 | HANDLE | ? | Thread handle |
| 0x84 | 1 | byte | 0 | **BUSY_FLAG** (1=processing command) |
| 0x85 | 3 | bytes | 0 | Padding |
| 0x88 | 4 | ptr | NULL | **TX_BUFFER_PTR** (pointer to TX buffer) |
| 0x8C | 4 | int | 0 | **TX_BUFFER_POS** (current position in TX buffer) |
| 0x90 | 4 | int | 0 | **TX_BUFFER_SIZE** (size of TX buffer) |

**Minimum size**: 0x90 bytes (144 bytes)

---

## Packet Format

### TX Packet (PC → SatLink):
```
Offset  Size    Field           Description
------  ----    -----           -----------
0       1       SYNC1           Sync byte (0x23 = '#' or 0x24 = '$')
1       1       0x00            Second sync byte (always 0x00)
2       1       LEN_H           Data length high byte
3       1       LEN_L           Data length low byte
4       1       OPCODE_H        Command opcode high byte
5       1       OPCODE_L        Command opcode low byte
6       1       SEQ             Sequence number (0x09-0xFF)
7..N    var     DATA            Command data payload
N+1     2       CRC_H, CRC_L    CRC-16 over [SYNC..DATA]
```

**Minimum packet size**: 10 bytes (8 header + 2 CRC, no data)
**Maximum data length**: 1024 bytes (0x0400)
**Sequence number**: Starts at 9 (0x09), increments per command, wraps at 0xFF

### RX Response (SatLink → PC):
```
Offset  Size    Field           Description
------  ----    -----           -----------
0       1       HDR1            Response header (should match SYNC1 or complement)
1       1       HDR2            Secondary header
2       1       STATUS          Response status code
3       1       SEQ_ECHO        Echoed sequence number
4       1       ???             Unknown (needs validation)
5       1       ???             Unknown (needs validation)
6       1       LEN_H           Response data length high
7       1       LEN_L           Response data length low
8..N    var     DATA            Response data payload
N+1     2       CHKSUM_H, CHKSUM_L  Data checksum
N+3     2       CRC_H, CRC_L    CRC-16 over complete frame
```

### Response Header Validation:
```c
// From handle_response (0x00447054):
if (*(byte *)(param_1 + 0x68) != received_byte) {
    if ((byte)~*(byte *)(param_1 + 0x68) != received_byte) {
        return 4;  // BAD_REPLY - header mismatch
    }
    *(undefined1 *)(param_1 + 0x7a) = 1;  // Complement match flag
}
```

### Return Codes:
| Code | Name | Description |
|------|------|-------------|
| 0 | SUCCESS | Communication completed successfully |
| 1 | NO_REPLY | Device did not respond within timeout |
| 2 | ABORTED | Communication was aborted |
| 3 | FAILED | Could not connect or write |
| 4 | BAD_REPLY | Response header mismatch |
| 6 | INCOMPLETE | Response data truncated |

---

## CRC-16 Algorithm

### Table Location: 0x00685d74 (256 entries x 2 bytes = 512 bytes)

**CONFIRMED**: The CRC table was successfully extracted from the binary and verified against the standard CRC-16-CCITT table. The SatLink 2 uses **CRC-16-CCITT (polynomial 0x1021)**.

### Algorithm:
```python
# CRC-16 Table extracted from SatlinkLoggerCommunicator.exe at VA 0x00685d74
# Polynomial: 0x1021 (CRC-16-CCITT)
CRC_TABLE = [...]  # 256 entries, extracted from binary

def calc_crc16(data: bytes) -> int:
    """Calculate CRC-16 using the confirmed Sutron lookup table."""
    crc = 0x0000  # Initial value
    for byte in data:
        crc = CRC_TABLE[(crc >> 8) ^ byte] ^ ((crc << 8) & 0xFFFF)
    return crc & 0xFFFF
```

### CRC Calculation Scope:
- Covers: SYNC1, 0x00, LEN_H, LEN_L, OPCODE_H, OPCODE_L, SEQ, DATA
- Does NOT include: CRC bytes themselves
- Initial value: 0x0000
- Polynomial: 0x1021 (CRC-16-CCITT) - CONFIRMED from binary extraction
- Reflected: No (standard non-reflected algorithm)

---

## Command Opcodes (Complete List)

### System Commands (0x0000-0x0045)
| Opcode | Name | Description |
|--------|------|-------------|
| 0x0002 | SYSTEM_STATE | Get system state |
| 0x0003 | LAST_SYSTEM_ERROR | Get last error code |
| 0x0004 | GET_ASCII_SYSTEM_STATUS | Get ASCII status string |
| 0x0005 | CLEAR_SYSTEM_STATUS | Clear status flags |
| 0x0006 | RESET_SYSTEM | Reset device |
| 0x0007 | RESET_FAILSAFE | Reset failsafe timer |
| 0x0008 | SET_BAUD_RATE | Set serial baud rate |
| 0x0009 | ENABLE_LOW_POWER_MODE | Enable/disable low power |
| 0x000A | SET_STATION_NAME | Set station ID name |
| 0x000B | GET_STATION_NAME | Get station ID name |
| 0x000C | GET_FAILSAFE_STATUS | Get failsafe status |
| 0x000D | SET_EEPROM_MAP | Write EEPROM |
| 0x000E | GET_EEPROM_MAP | Read EEPROM |
| 0x000F | QUICK_STATUS | Quick status check |
| 0x0010 | BLST_RESULTS | Get blast results |
| 0x0011 | GET_FWD_REF_POWER | Get forward reference power |
| 0x0012 | SET_DUMB_LOGGER | Set dumb logger mode |
| 0x0013 | GET_DUMB_LOGGER | Get dumb logger mode |
| 0x0014 | SET_NO_LED_POWER | Set no-LED power mode |
| 0x0015 | GET_NO_LED_POWER | Get no-LED power mode |
| 0x0016 | IS_PASSWORD_PROTECTED | Check password protection |
| 0x0017 | SET_PASSWORD_PROTECTION | Enable/disable password |
| 0x0018 | CHANGE_PASSWORD | Change password |
| 0x0019 | LOG_IN | Login to device |
| 0x001A | LOG_OUT | Logout from device |
| 0x001B | OVERRIDE_PASSWORD | Override password |
| 0x001E | SET_DATE_TIME | Set date/time |
| 0x001F | GET_DATE_TIME | Get date/time |
| 0x0020 | GET_DATE_TIME_AND_QUALITY | Get date/time + quality |
| 0x0021 | SET_UNIX_DATE_TIME | Set Unix timestamp |
| 0x0022 | GET_UNIX_DATE_TIME | Get Unix timestamp |
| 0x0023 | GET_UNIX_DATE_TIME_AND_QUALITY | Get Unix timestamp + quality |
| 0x0024 | GET_ASCII_TIME_STATUS | Get ASCII time status |
| 0x0025 | SET_LOCAL_TIME_OFFSET | Set local time offset |
| 0x0026 | GET_LOCAL_TIME_OFFSET | Get local time offset |
| 0x0028 | SET_GOES_ID | Set GOES satellite ID |
| 0x0029 | GET_GOES_ID | Get GOES satellite ID |
| 0x002A | SET_INSAT_2ND_ID | Set INSAT 2nd ID |
| 0x002B | GET_INSAT_2ND_ID | Get INSAT 2nd ID |
| 0x0032 | SET_GPS_ACQUIRE_TIME | Set GPS acquire timeout |
| 0x0033 | GET_GPS_ACQUIRE_TIME | Get GPS acquire timeout |
| 0x0034 | SYNC_TO_GPS_NOW_ENABLE | Enable GPS sync |
| 0x0035 | SET_ENABLE_USE_OF_GPS | Enable GPS usage |
| 0x0036 | GET_ENABLE_USE_OF_GPS | Get GPS enable state |
| 0x0037 | CAL_GPS_NOW_ENABLE | Enable GPS calibration |
| 0x0038 | GET_GPS_CAL_INFO | Get GPS calibration info |
| 0x0039 | SET_ENABLE_GPS_BASELINE | Set GPS baseline enable |
| 0x003A | GET_ENABLE_GPS_BASELINE | Get GPS baseline enable |
| 0x003B | SET_GPS_BASELINE_INTERVAL | Set GPS baseline interval |
| 0x003C | GET_GPS_BASELINE_INTERVAL | Get GPS baseline interval |
| 0x003D | SET_GPS_TIME_BECOMES_OLD | Set GPS time old threshold |
| 0x003E | GET_GPS_TIME_BECOMES_OLD | Get GPS time old threshold |
| 0x003F | SET_UTC_OFFSET | Set UTC offset |
| 0x0040 | GET_UTC_OFFSET | Get UTC offset |
| 0x0041 | SET_GPS_BYPASS_SYNC_IF_GPS_FAILS | Set GPS bypass sync |
| 0x0042 | GET_GPS_BYPASS_SYNC_IF_GPS_FAILS | Get GPS bypass sync |
| 0x0043 | GET_LAT_LONG | Get latitude/longitude |
| 0x0044 | GET_TIME_TO_FIX | Get GPS time to fix |
| 0x0045 | GPS_PASSTHRU | GPS passthrough mode |

### Scheduled Transmission (0x00C8-0x00E1)
| Opcode | Name |
|--------|------|
| 0x00C8 | SET_ENABLE_SCHED_TX |
| 0x00C9 | GET_SCHED_TX_ENABLED |
| 0x00CA | SET_SCHED_CHANNEL |
| 0x00CB | GET_SCHED_CHANNEL |
| 0x00CC | SET_SCHED_INTERVAL |
| 0x00CD | GET_SCHED_INTERVAL |
| 0x00CE | SET_SCHED_OFFSET |
| 0x00CF | GET_SCHED_OFFSET |
| 0x00D0 | SET_SCHED_BAUD_RATE |
| 0x00D1 | GET_SCHED_BAUD_RATE |
| 0x00D2 | GET_TIME_OF_NEXT_SCHED_TX |
| 0x00D3 | GET_HOW_MANY_BYTES_IN_SCHED_TX |
| 0x00D4 | SET_SCHED_WINDOW |
| 0x00D5 | GET_SCHED_WINDOW |
| 0x00D6 | SET_ENABLE_SCHED_WINDOW_CENTERING |
| 0x00D7 | GET_SCHED_WINDOW_CENTERING_ENABLE |
| 0x00D8 | INSERT_DATA_FOR_SCHED_TX |
| 0x00D9 | APPEND_DATA_FOR_SCHED_TX |
| 0x00DA | SCHED_TEST_TX |
| 0x00DB | GET_SCHED_TIME_TILL_DATA_ACCEPTED |
| 0x00DC | GET_SCHED_TX_TRIED_COUNT |
| 0x00DD | GET_SCHED_TX_SUCCEEDED_COUNT |
| 0x00DE | GET_SCHED_TX_LENGTH_OF_TX |
| 0x00DF | SET_SCHED_APPEND_QUALITY |
| 0x00E0 | GET_SCHED_APPEND_QUALITY |
| 0x00E1 | SET_SCHED_APPEND_LAT_LON |

### Measurement Commands (0x02BD-0x02FB) ⭐ KEY FOR SENSORS
| Opcode | Name | Description |
|--------|------|-------------|
| 0x02BD | GET_MEASUREMENT_LABEL | Get measurement label |
| 0x02BE | SET_MEASUREMENT_ACTIVE | Set measurement active |
| 0x02BF | GET_MEASUREMENT_ACTIVE | Get measurement active |
| 0x02C0 | SET_MEASUREMENT_RELATIVE_TO_TX | Set relative to TX |
| 0x02C1 | GET_MEASUREMENT_RELATIVE_TO_TX | Get relative to TX |
| 0x02C2 | SET_MEASUREMENT_TIME | Set measurement time |
| 0x02C3 | GET_MEASUREMENT_TIME | Get measurement time |
| 0x02C4 | SET_MEASUREMENT_INTERVAL | Set measurement interval |
| 0x02C5 | GET_MEASUREMENT_INTERVAL | Get measurement interval |
| 0x02C6 | SET_MEASUREMENT_RIGHT_DIGITS | Set decimal digits |
| 0x02C7 | GET_MEASUREMENT_RIGHT_DIGITS | Get decimal digits |
| 0x02C8 | SET_MEASUREMENT_SLOPE | Set calibration slope |
| 0x02C9 | GET_MEASUREMENT_SLOPE | Get calibration slope |
| 0x02CA | SET_MEASUREMENT_OFFSET | Set calibration offset |
| 0x02CB | GET_MEASUREMENT_OFFSET | Get calibration offset |
| 0x02CC | SET_MEASUREMENT_LOG | Set logging enable |
| 0x02CD | GET_MEASUREMENT_LOG | Get logging enable |
| 0x02CE | SET_MEASUREMENT_SCHED_TX | Set scheduled TX |
| 0x02CF | GET_MEASUREMENT_SCHED_TX | Get scheduled TX |
| 0x02D0 | SET_MEASUREMENT_NUM_VALS_SCHED | Set values for sched TX |
| 0x02D1 | GET_MEASUREMENT_NUM_VALS_SCHED | Get values for sched TX |
| 0x02D2 | SET_MEASUREMENT_RND_TX | Set random TX |
| 0x02D3 | GET_MEASUREMENT_RND_TX | Get random TX |
| 0x02D4 | SET_MEASUREMENT_NUM_VALS_RND | Set values for random TX |
| 0x02D5 | GET_MEASUREMENT_NUM_VALS_RND | Get values for random TX |
| 0x02D6 | SET_MEASUREMENT_TYPE | Set measurement type |
| 0x02D7 | GET_MEASUREMENT_TYPE | Get measurement type |
| 0x02D8 | SET_MEASUREMENT_HI_ALARM_MODE | Set high alarm mode |
| 0x02D9 | GET_MEASUREMENT_HI_ALARM_MODE | Get high alarm mode |
| 0x02DA | SET_MEASUREMENT_LOW_ALARM_MODE | Set low alarm mode |
| 0x02DB | GET_MEASUREMENT_LOW_ALARM_MODE | Get low alarm mode |
| 0x02DC | SET_MEASUREMENT_HI_ROC_ALARM_MODE | Set high ROC alarm |
| 0x02DD | GET_MEASUREMENT_HI_ROC_ALARM_MODE | Get high ROC alarm |
| 0x02DE | SET_MEASUREMENT_LOW_ROC_ALARM_MODE | Set low ROC alarm |
| 0x02DF | GET_MEASUREMENT_LOW_ROC_ALARM_MODE | Get low ROC alarm |
| 0x02E0 | SET_MEASUREMENT_HI_LEVEL | Set high level threshold |
| 0x02E1 | GET_MEASUREMENT_HI_LEVEL | Get high level threshold |
| 0x02E2 | SET_MEASUREMENT_LOW_LEVEL | Set low level threshold |
| 0x02E3 | GET_MEASUREMENT_LOW_LEVEL | Get low level threshold |
| 0x02E4 | SET_MEASUREMENT_HI_ROC_LEVEL | Set high ROC level |
| 0x02E5 | GET_MEASUREMENT_HI_ROC_LEVEL | Get high ROC level |
| 0x02E6 | SET_MEASUREMENT_LOW_ROC_LEVEL | Set low ROC level |
| 0x02E7 | GET_MEASUREMENT_LOW_ROC_LEVEL | Get low ROC level |
| 0x02E8 | SET_MEASUREMENT_DEADBAND | Set deadband |
| 0x02E9 | GET_MEASUREMENT_DEADBAND | Get deadband |
| 0x02EA | SET_MEASUREMENT_SDI12_COMMAND | Set SDI-12 command |
| 0x02EB | GET_MEASUREMENT_SDI12_COMMAND | Get SDI-12 command |
| 0x02EC | SET_MEASUREMENT_SDI12_PARAM | Set SDI-12 parameters |
| 0x02ED | GET_MEASUREMENT_SDI12_PARAM | Get SDI-12 parameters |
| 0x02EE | SET_MEASUREMENT_MANUAL_ENTRY | Set manual entry mode |
| 0x02EF | GET_MEASUREMENT_MANUAL_ENTRY | Get manual entry mode |
| 0x02F0 | SET_MEASUREMENT_SETTINGS_TO_DEFAULT | Reset to defaults |
| 0x02F1 | FORCE_MEASUREMENT | Force measurement cycle |
| 0x02F2 | SET_AUTO_START | Set auto-start |
| 0x02F3 | GET_AUTO_START | Get auto-start |
| 0x02F4 | SDI_PASS_THRU_COMMAND | SDI-12 passthrough ⭐ |
| 0x02F5 | SET_TIPPING_BUCKET_COUNT | Set tipping bucket count |
| 0x02F6 | ABORT_FORCED_MEASUREMENT | Abort forced measurement |
| 0x02F7 | CLEAR_LOG | Clear data log |
| 0x02F8 | READ_LOG | Read data log |
| 0x02F9 | GET_LAST_MEASUREMENT | Get last measurement ⭐ |
| 0x02FA | GET_ALL_LAST_MEASUREMENTS | Get all measurements ⭐ |
| 0x02FB | CLEAR_ALL_LAST_MEASUREMENTS | Clear all measurements |

---

## Key Functions (Addresses)

| Address | Name | Purpose |
|---------|------|---------|
| 0x004085c4 | opcode_name_lookup | Maps opcode → name string |
| 0x004463f8 | command_dispatcher | High-level command execution |
| 0x0044672c | send_receive_packet | Core: build, send, receive |
| 0x00447054 | handle_response | Parse incoming response |
| 0x0044741c | pkt_parse | Build packet (simpler version) |
| 0x00447608 | init_buffer | Wait inter-byte timeout |
| 0x004476d4 | write_header | Write header with timing |
| 0x004476b0 | write_byte | Write byte to buffer |
| 0x00447680 | store_byte | Store byte in buffer |
| 0x00447650 | read_byte | Read byte from response |
| 0x004049a0 | crc_update | Update CRC with one byte |
| 0x0040a2a8 | send_buffer | Send via WriteFile |
| 0x0040a900 | connect_port | Open and configure COM port |
| 0x00445d44 | copy_response | Copy response data |
| 0x00445e18 | copy_data | Copy data with delays |

---

## Communication Flow

### 1. Connection
```python
import serial
import time

# Open port
ser = serial.Serial(
    port='COM3',
    baudrate=9600,
    bytesize=serial.EIGHTBITS,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    timeout=2.0,
    write_timeout=0.05
)

# Wait 150ms after connect (from Sleep 0x96 in binary)
time.sleep(0.15)
```

### 2. Send Command
```python
# Build packet
SYNC1 = 0x23  # '#' - needs validation
SYNC2 = 0x00  # Always 0x00

# Header (6 bytes)
header = bytes([
    SYNC1,
    SYNC2,
    (len(data) >> 8) & 0xFF,  # LEN_H
    len(data) & 0xFF,         # LEN_L
    (opcode >> 8) & 0xFF,     # OPCODE_H
    opcode & 0xFF,            # OPCODE_L
])

# Sequence number (starts at 9, increments per command)
seq = 9  # Initial value, stored at comm object offset 0x69

# Build packet without CRC
packet_no_crc = header + bytes([seq]) + data

# Calculate CRC
crc = calc_crc16(packet_no_crc)

# Complete packet
packet = packet_no_crc + struct.pack(">H", crc)

# Send (in 128-byte chunks with 1ms delay between chunks)
for i in range(0, len(packet), 128):
    chunk = packet[i:i+128]
    ser.write(chunk)
    ser.flush()
    time.sleep(0.001)  # 1ms between chunks
```

### 3. Receive Response
```python
# Read response header (minimum 8 bytes)
response = b""
while len(response) < 8:
    byte = ser.read(1)
    if not byte:
        break
    response += byte

# Parse header
hdr1 = response[0]  # Should match SYNC1 or complement
hdr2 = response[1]
status = response[2]
seq_echo = response[3]
len_h = response[6]
len_l = response[7]
data_len = (len_h << 8) | len_l

# Read data + checksum + CRC
remaining = ser.read(data_len + 4)
response += remaining
```

### 4. Validate
```python
# Check header byte
expected_hdr = SYNC1
if hdr1 != expected_hdr:
    if (hdr1 ^ 0xFF) & 0xFF == expected_hdr:
        print("Complement match detected")
    else:
        print("BAD_REPLY - header mismatch")
        # Return code 4

# Check CRC
received_crc = struct.unpack(">H", response[-2:])[0]
calculated_crc = calc_crc16(response[:-2])
if received_crc != calculated_crc:
    print("CRC mismatch")
    # Handle error
```

---

## Return Codes (Confirmed from Binary)

| Code | Name | Description |
|------|------|-------------|
| 0 | SUCCESS | Communication completed successfully |
| 1 | NO_REPLY | Device did not respond within timeout |
| 2 | ABORTED | Communication was aborted |
| 3 | FAILED | Could not connect or write |
| 4 | BAD_REPLY | Response header mismatch |
| 6 | INCOMPLETE | Response data truncated |

**Note**: Code 5 is unused (gap in sequence)

---

## File Locations

All analysis files in `E:\Satlink_v7.41\`:

| File | Description |
|------|-------------|
| `PROTOCOL_REFERENCE.md` | This reference document |
| `satlink2_protocol.py` | Python protocol library (with CRC-16-CCITT) |
| `satlink2_sniff.py` | Protocol sniffer tool |
| `protocol_investigation.py` | Protocol investigation script |
| `deep_analysis.json` | Complete analysis data |
| `opcode_name_lookup.c` | Opcode → name mapping |
| `dispatcher_0x004463f8.c` | Command dispatcher |
| `send_receive_packet.c` | Core send/receive |
| `handle_response.c` | Response parser |
| `crc_table_generated.py` | Generated CRC-16-CCITT table |
| `crc_tables_all.py` | All generated CRC tables |

---

## Next Steps

### Immediate (Priority 1)
1. **Capture Real Traffic**: Use `satlink2_sniff.py` to validate:
   - Exact sync byte (0x23 or 0x24)
   - Exact response format
   - CRC polynomial
2. **Test Simple Commands**: Start with:
   - QUICK_STATUS (0x000F)
   - GET_STATION_NAME (0x000B)
   - GET_UNIX_DATE_TIME (0x0022)

### Validation (Priority 2)
3. **Validate CRC**: Confirm CRC-16 calculation matches real packets
   - Try CRC-16-CCITT (0x1021) first
   - If fails, try CRC-16-IBM (0x8005)
   - If fails, try CRC-16-MODBUS (0x8005 reflected)
4. **Document Response Format**: Complete response structure from captured traffic

### Implementation (Priority 3)
5. **Implement Sensor Reading**: Use GET_ALL_LAST_MEASUREMENTS (0x02FA)
6. **SDI-12 Integration**: Use SDI_PASS_THRU_COMMAND (0x02F4) for direct sensor access
7. **Measurement Parsing**: Decode measurement data from responses

---

*Document generated from reverse-engineering SatlinkLoggerCommunicator.exe*
*Protocol analysis complete as of August 2026*
*Last updated: Deep investigation - packet format, sync bytes, response format, comm object structure*