#!/usr/bin/env python3

# lirc_to_flipper.py
# 2026-04-06
# by Gernot Walzl

# Converts LIRC config files to Flipper IR files.
# Currently, only simple RC-6 signals are supported.

import argparse


def print_flipper_ir_head():
    print('Filetype: IR signals file')
    print('Version: 1')


def print_flipper_ir_key(name, command):
    print('# ')
    print('name: ' + name)
    print('type: parsed')
    print('protocol: RC6')
    print('address: 00 00 00 00')
    print('command: ' + command)


def convert_key_name(lirc_key):
    return lirc_key.replace('KEY_', '').title()


def convert_code_rc6(lirc_code):
    # LIRC does not distinguish between RC-5 and RC-6 signals.
    # Therefore, the logical meaning of RC-6 signals is inverted in LIRC.
    # https://sourceforge.net/p/lirc/tickets/389/
    code = 0xff - int(lirc_code[-2:], 16)
    return '{:02x} 00 00 00'.format(code).upper()


def lirc_to_flipper(filename):
    with open(filename, 'r') as file:
        in_codes = False
        for line in file:
            line = line.strip()
            if line.startswith('#'):
                continue
            elif line.startswith('flags'):
                if not line.endswith('RC6|CONST_LENGTH'):
                    print('ERROR: Only RC6 is supported.')
                    break
            elif line == 'begin codes':
                print_flipper_ir_head()
                in_codes = True
            elif line == 'end codes':
                in_codes = False
            elif in_codes:
                (lirc_key, lirc_code) = line.split()
                name = convert_key_name(lirc_key)
                command = convert_code_rc6(lirc_code)
                print_flipper_ir_key(name, command)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('filename', help='LIRC config file')
    args = parser.parse_args()
    lirc_to_flipper(args.filename)
