#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
unsigned char mirror_byte(unsigned char b) {
b = ((b & 0xF0) >> 4) | ((b & 0x0F) << 4);
b = ((b & 0xCC) >> 2) | ((b & 0x33) << 2);
b = ((b & 0xAA) >> 1) | ((b & 0x55) << 1);
return b;
}
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("Usage: %s <i2c-dev-path> <bitstream.bit>\n", argv[0]);
return 1;
}
int fd = open(argv[1], O_RDWR);
if (fd < 0) { perror("Failed to open I2C bus"); return 1; }
if (ioctl(fd, I2 gateway, I2C_SLAVE_FORCE, 0x40) < 0) { perror("Failed to set slave address"); return 1; }
FILE *f_bit = fopen(argv[2], "rb");
if (!f_bit) { perror("Failed to open bit file"); return 1; }
printf("[SMART_FLASH] Starting execution (Mirroring ONLY payload after 359 bytes)...\n");
/* 1. Ключ активации (как есть) */
unsigned char act_key[] = { 0xA4, 0xC6, 0xF4, 0x8A };
write(fd, act_key, 4); usleep(5000);
/* 2. ISC_ENABLE (как есть) */
unsigned char isc_enable[] = { 0xC6, 0x00, 0x00, 0x00 };
write(fd, isc_enable, 4); usleep(10000);
/* 3. ISC_ERASE (как есть) */
unsigned char isc_erase[] = { 0x0E, 0x01, 0x00, 0x00 };
write(fd, isc_erase, 4); usleep(100000);
/* 4. LSC_BITSTREAM_BURST (как есть) */
unsigned char burst_cmd[] = { 0x7A, 0x00, 0x00, 0x00 };
write(fd, burst_cmd, 4); usleep(2000);
/* 5. Потоковое чтение и умное разделение */
unsigned char block[1024];
size_t read_bytes, total_sent = 0;
while ((read_bytes = fread(block, 1, sizeof(block), f_bit)) > 0) {
for (size_t i = 0; i < read_bytes; i++) {
/* Первые 359 байт текста шлем как есть, всё остальное - зеркалим */
if (total_sent + i >= 359) {
block[i] = mirror_byte(block[i]);
}
}
if (write(fd, block, read_bytes) != read_bytes) { perror("Write error"); return 1; }
total_sent += read_bytes;
}
printf("[SMART_FLASH] Sent %zu bytes.\n", total_sent); usleep(5000);
/* 6. Добивка FIFO */
unsigned char padding[1024];
for(int i=0; i<1024; i++) padding[i] = 0xFF;
write(fd, padding, 1024); usleep(5000);
/* 7. ISC_DISABLE (как есть) */
unsigned char isc_disable[] = { 0x26, 0x00, 0x00, 0x00 };
write(fd, isc_disable, 4); usleep(5000);
/* 8. LSC_REFRESH (как есть) */
unsigned char refresh[] = { 0x79, 0x00, 0x00, 0x00 };
write(fd, refresh, 4);
printf("[SMART_FLASH] Complete! Run i2ctransfer status now.\n");
fclose(f_bit); close(fd); return 0;
}