Node‐Red Advanced AI flows - BitMakerMan/Share_NodeRed_Flow GitHub Wiki

🧠 Node-RED Avanzato: Intelligenza Artificiale e Integrazione Hardware

🚀 Obiettivo: Esempi pratici e avanzati per integrare AI, hardware specializzato (Google Coral), modelli LLM locali (Ollama) e flussi complessi in Node-RED. Tutti i nodi utilizzati sono attualmente supportati e non deprecati.


Indice

  1. 🧠 Riconoscimento immagini con TensorFlow.js
  2. 🤖 Object Detection con Google Coral (Edge TPU)
  3. 💬 Chat con Ollama (LLM locale)
  4. 📊 Anomaly Detection con dati MQTT e AI
  5. 🛠️ Nodi avanzati e installazione
  6. 🔍 Pro Tips avanzati

🧠 Riconoscimento immagini con TensorFlow.js

Obiettivo

Usare un modello TensorFlow.js (es. MobileNet) per riconoscere oggetti in un’immagine inviata tramite HTTP.

Nodi necessari

  • http in (per ricevere l’immagine)
  • function (per formattare i dati)
  • tfjs (per eseguire il modello)
  • debug (per visualizzare il risultato)

Flusso JSON

[
    {
        "id": "http-in",
        "type": "http in",
        "name": "Immagine HTTP",
        "url": "/image",
        "method": "post",
        "wires": ["format-image"](/BitMakerMan/Share_NodeRed_Flow/wiki/"format-image")
    },
    {
        "id": "format-image",
        "type": "function",
        "name": "Formatta immagine",
        "func": "msg.payload = {\n    image: msg.payload,\n    model: \"mobilenet\"\n};\nreturn msg;",
        "wires": ["run-model"](/BitMakerMan/Share_NodeRed_Flow/wiki/"run-model")
    },
    {
        "id": "run-model",
        "type": "tfjs",
        "name": "Esegui modello",
        "wires": ["show-result"](/BitMakerMan/Share_NodeRed_Flow/wiki/"show-result")
    },
    {
        "id": "show-result",
        "type": "debug",
        "name": "Mostra risultato",
        "active": true,
        "complete": "payload",
        "console": "false",
        "wires": []
    }
]

Come usarlo

  1. Installa il nodo TensorFlow.js:
    npm install node-red-contrib-tfjs
    
  2. Carica un’immagine in base64 tramite POST su /image.
  3. Il modello restituirà le 3 classi più probabili (es. dog, cat, car).

🤖 Object Detection con Google Coral (Edge TPU)

Obiettivo

Usare un sensore Google Coral (Edge TPU) per rilevare oggetti in tempo reale da un video stream.

Nodi necessari

  • opencv (per catturare il video)
  • coral (per inferenza con Edge TPU)
  • debug (per visualizzare i risultati)

Flusso JSON

[
    {
        "id": "camera",
        "type": "opencv",
        "name": "Stream video",
        "device": 0,
        "wires": ["detect-objects"](/BitMakerMan/Share_NodeRed_Flow/wiki/"detect-objects")
    },
    {
        "id": "detect-objects",
        "type": "coral",
        "name": "Rileva oggetti",
        "model": "ssd_mobilenet_v2_coco_quant_postprocess_edgetpu.tflite",
        "labels": "coco_labels.txt",
        "wires": ["show-objects"](/BitMakerMan/Share_NodeRed_Flow/wiki/"show-objects")
    },
    {
        "id": "show-objects",
        "type": "debug",
        "name": "Mostra oggetti",
        "active": true,
        "complete": "payload",
        "console": "false",
        "wires": []
    }
]

Come usarlo

  1. Collega la Coral USB a Raspberry Pi o PC.
  2. Scarica il modello TFLite e i label da Edge TPU Models.
  3. Configura il nodo Coral con i file corretti.
  4. Il flusso restituirà oggetti rilevati (es. person, bottle, chair).

💬 Chat con Ollama (LLM locale)

Obiettivo

Integrare un modello LLM locale (es. Llama3, Mistral) tramite Ollama per rispondere a domande tramite Node-RED.

Nodi necessari

  • http request (per chiamare l’API di Ollama)
  • function (per formattare la richiesta)
  • debug (per visualizzare la risposta)

Flusso JSON

[
    {
        "id": "b0cfb97eb513bc00",
        "type": "tab",
        "label": "Flow 2",
        "disabled": false,
        "info": "Flusso di esempio per monitoraggio temperatura con Telegram",
        "env": []
    },
    {
        "id": "4c41415061383636",
        "type": "function",
        "z": "b0cfb97eb513bc00",
        "name": "Controlla temperatura",
        "func": "if (msg.payload > 30) {\n    msg.payload = {\n        chatId: context.global.chatId,\n        type: 'message',\n        text: \"⚠️ Temperatura alta! Valore: \" + msg.payload + \"°C\"\n    };\n} else {\n    msg.payload = null;\n}\nreturn [msg];",
        "outputs": 1,
        "timeout": "",
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 660,
        "y": 500,
        "wires": [
            [
                "e406399d9f533795"
            ]
        ]
    },
    {
        "id": "e406399d9f533795",
        "type": "telegram sender",
        "z": "b0cfb97eb513bc00",
        "name": "",
        "bot": "d031d697a567012e",
        "haserroroutput": true,
        "outputs": 2,
        "x": 890,
        "y": 500,
        "wires": [
            [],
            []
        ]
    },
    {
        "id": "8b393b9cbd4e274b",
        "type": "inject",
        "z": "b0cfb97eb513bc00",
        "name": "",
        "props": [
            {
                "p": "payload"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "31",
        "payloadType": "num",
        "x": 430,
        "y": 520,
        "wires": [
            [
                "4c41415061383636"
            ]
        ]
    },
    {
        "id": "3d26ec3dd10c919a",
        "type": "inject",
        "z": "b0cfb97eb513bc00",
        "name": "",
        "props": [
            {
                "p": "payload"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "20",
        "payloadType": "num",
        "x": 430,
        "y": 480,
        "wires": [
            [
                "4c41415061383636"
            ]
        ]
    },
    {
        "id": "8c1ffcd898785bb1",
        "type": "telegram receiver",
        "z": "b0cfb97eb513bc00",
        "name": "",
        "bot": "d031d697a567012e",
        "saveDataDir": "",
        "filterCommands": false,
        "x": 450,
        "y": 400,
        "wires": [
            [
                "e363d702064d91c1"
            ],
            []
        ]
    },
    {
        "id": "e363d702064d91c1",
        "type": "function",
        "z": "b0cfb97eb513bc00",
        "name": "Registra Chat ID",
        "func": "// Memorizza il chatId globalmente\nif (msg.payload.chatId) {\n    context.global.chatId = msg.payload.chatId;\n    node.warn(\"Chat ID registrato: \" + context.global.chatId);\n} else {\n    node.warn(\"Errore: chat ID non trovato nel messaggio.\");\n}\nreturn msg;",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 680,
        "y": 400,
        "wires": [
            []
        ]
    },
    {
        "id": "d031d697a567012e",
        "type": "telegram bot",
        "botname": "TEST",
        "usernames": "",
        "chatids": "",
        "baseapiurl": "",
        "testenvironment": false,
        "updatemode": "polling",
        "pollinterval": 300,
        "usesocks": false,
        "sockshost": "",
        "socksprotocol": "socks5",
        "socksport": 6667,
        "socksusername": "anonymous",
        "sockspassword": "",
        "bothost": "",
        "botpath": "",
        "localbothost": "0.0.0.0",
        "localbotport": 8443,
        "publicbotport": 8443,
        "privatekey": "",
        "certificate": "",
        "useselfsignedcertificate": false,
        "sslterminated": false,
        "verboselogging": false
    }
]

Come usarlo

  1. Avvia Ollama localmente:
    ollama run llama3
    
  2. Installa il nodo node-red-node-http se non è presente.
  3. Importa il flusso e premi Deploy.
  4. La risposta del modello apparirà nel debug.

📊 Anomaly Detection con dati MQTT e AI

Obiettivo

Rilevare anomalie (es. picchi di temperatura) usando dati MQTT e un modello AI semplice (es. media + deviazione standard).

Nodi necessari

  • mqtt in (per ricevere dati)
  • function (per logica di rilevamento)
  • debug (per segnalare anomalie)

Flusso JSON

[
    {
        "id": "temp-sensor",
        "type": "mqtt in",
        "name": "Sensore Temperatura",
        "topic": "home/temperature",
        "broker": "your-broker-id",
        "wires": ["check-anomaly"](/BitMakerMan/Share_NodeRed_Flow/wiki/"check-anomaly")
    },
    {
        "id": "check-anomaly",
        "type": "function",
        "name": "Rileva anomalie",
        "func": "context.values = context.values || [];\ncontext.values.push(msg.payload);\nif (context.values.length > 10) context.values.shift();\n\nlet avg = context.values.reduce((a, b) => a + b, 0) / context.values.length;\nlet std = Math.sqrt(context.values.map(x => Math.pow(x - avg, 2)).reduce((a, b) => a + b, 0) / context.values.length);\n\nif (Math.abs(msg.payload - avg) > 2 * std) {\n    msg.payload = \"⚠️ Anomalia rilevata: \" + msg.payload + \"°C\";\n    return [null, msg];\n} else {\n    return [msg, null];\n}",
        "wires": ["debug", "alert"](/BitMakerMan/Share_NodeRed_Flow/wiki/"debug",-"alert")
    },
    {
        "id": "alert",
        "type": "debug",
        "name": "Segnala anomalia",
        "active": true,
        "complete": "payload",
        "console": "false",
        "wires": []
    }
]

Come usarlo

  1. Collega un sensore MQTT per la temperatura.
  2. Il flusso calcola la media e la deviazione standard degli ultimi 10 valori.
  3. Se un nuovo valore supera 2 deviazioni standard, viene segnalato come anomalo.

🛠️ Nodi avanzati e installazione

Apri il terminale nella cartella .node-red e installa i nodi mancanti:

cd ~/.node-red
npm install node-red-contrib-tfjs
npm install node-red-contrib-coral
npm install node-red-contrib-opencv2
npm install node-red-node-http

Poi riavvia Node-RED:

node-red

🔍 Pro Tips avanzati

Trucco Descrizione
🐳 Usa Docker Isola i nodi pesanti (es. TensorFlow) in container separati
📁 Versiona i flussi Usa Git per tracciare modifiche ai file flows.json
📊 Grafana + InfluxDB Archivia e visualizza dati AI/ML per analisi avanzata
🔐 Sicurezza API Usa chiavi API o JWT per proteggere endpoint HTTP
📦 Modelli quantizzati Usa modelli TensorFlow quantizzati per Coral o Edge TPU