refactor(autocraft): improve peripheral initialization with retry logic

This commit is contained in:
2025-11-21 14:56:56 +08:00
parent 94f0de4c90
commit 82a9fec46d

View File

@@ -15,7 +15,7 @@ import {
const logger = new Logger({ const logger = new Logger({
processors: [ processors: [
processor.filterByLevel(LogLevel.Info), processor.filterByLevel(LogLevel.Info),
processor.addFullTimestamp(), processor.addTimestamp(),
], ],
renderer: textRenderer, renderer: textRenderer,
streams: [new ConsoleStream()], streams: [new ConsoleStream()],
@@ -33,22 +33,12 @@ const peripheralsNames = {
packageExtractor: "create:packager_0", packageExtractor: "create:packager_0",
}; };
const packsInventory = peripheral.wrap( let packsInventory: InventoryPeripheral;
peripheralsNames.packsInventory, let itemsInventory: InventoryPeripheral;
) as InventoryPeripheral; let packageExtractor: InventoryPeripheral;
const itemsInventory = peripheral.wrap( let blockReader: BlockReaderPeripheral;
peripheralsNames.itemsInventory, let wiredModem: WiredModemPeripheral;
) as InventoryPeripheral; let turtleLocalName: string;
const packageExtractor = peripheral.wrap(
peripheralsNames.packageExtractor,
) as InventoryPeripheral;
const blockReader = peripheral.wrap(
peripheralsNames.blockReader,
) as BlockReaderPeripheral;
const wiredModem = peripheral.wrap(
peripheralsNames.wiredModem,
) as WiredModemPeripheral;
const turtleLocalName = wiredModem.getNameLocal();
enum State { enum State {
IDLE, IDLE,
@@ -57,9 +47,39 @@ enum State {
} }
function main() { function main() {
while (true) {
try {
packsInventory = peripheral.wrap(
peripheralsNames.packsInventory,
) as InventoryPeripheral;
itemsInventory = peripheral.wrap(
peripheralsNames.itemsInventory,
) as InventoryPeripheral;
packageExtractor = peripheral.wrap(
peripheralsNames.packageExtractor,
) as InventoryPeripheral;
blockReader = peripheral.wrap(
peripheralsNames.blockReader,
) as BlockReaderPeripheral;
wiredModem = peripheral.wrap(
peripheralsNames.wiredModem,
) as WiredModemPeripheral;
turtleLocalName = wiredModem.getNameLocal();
logger.info("Peripheral initialization complete...");
break;
} catch (error) {
logger.warn(
`Peripheral initialization failed for ${String(error)}, try again...`,
);
sleep(1);
}
}
const craftManager = new CraftManager(turtleLocalName, itemsInventory); const craftManager = new CraftManager(turtleLocalName, itemsInventory);
const recipesQueue = new Queue<CraftRecipe>(); const recipesQueue = new Queue<CraftRecipe>();
const recipesWaitingMap = new Map<number, CraftRecipe[] | CraftRecipe>(); const recipesWaitingMap = new Map<number, CraftRecipe[] | CraftRecipe>();
let currentState = State.IDLE; let currentState = State.IDLE;
let nextState = State.IDLE; let nextState = State.IDLE;
let hasPackage = redstone.getInput(peripheralsNames.redstone); let hasPackage = redstone.getInput(peripheralsNames.redstone);