LynxJS Workshop: Advanced Integration และ Best Practices

LynxJS Workshop: Advanced Integration และ Best Practices

Dev Team · IT ·

LynxJS Workshop: Advanced Integration และ Best Practices

ยินดีต้อนรับสู่บทความสุดท้ายของ LynxJS Workshop Series! 🎉

ในบทความนี้ เราจะเจาะลึกการ integrate LynxJS กับระบบภายนอก, Cloud Services, และ Best Practices ที่ควรทราบ

🎯 สิ่งที่จะได้เรียนรู้

  • ☁️ การเชื่อมต่อกับ Cloud Services (AWS, Azure, GCP)
  • 🔗 การ integrate กับ Home Automation Systems
  • 📱 การสร้าง Mobile App ควบคุม
  • 🛡️ Security Best Practices
  • 📈 Performance Optimization

☁️ Cloud Integration

1. AWS IoT Core

AWS IoT Core เป็น managed cloud platform ที่ให้ device connectivity และ messaging

```typescript import { AWSIoT } from ‘@lynxjs/cloud’;

const iot = new AWSIoT({ region: ‘ap-southeast-1’, endpoint: ‘xxxxx-ats.iot.ap-southeast-1.amazonaws.com’, certificates: { cert: ‘/path/to/certificate.pem’, key: ‘/path/to/private.key’, ca: ‘/path/to/root-CA.pem’ } });

// เชื่อมต่อ await iot.connect();

// Subscribe รับข้อมูล iot.subscribe(‘home/sensors/+’, (topic, message) => { console.log(`Received from ${topic}:`, message); });

// Publish ส่งข้อมูล await iot.publish(‘home/sensors/temperature’, JSON.stringify({ temperature: 25.5, timestamp: Date.now() })); ```

2. Azure IoT Hub

```typescript import { AzureIoT } from ‘@lynxjs/cloud’;

const azure = new AzureIoT({ connectionString: ‘HostName=iothub.azure-devices.net;DeviceId=myDevice;SharedAccessKey=xxx’ });

await azure.connect();

// Send telemetry await azure.sendTelemetry({ temperature: 25.5, humidity: 60 });

// Receive cloud-to-device messages azure.onMessage((message) => { console.log(‘Received:’, message); }); ```

3. Google Cloud IoT

```typescript import { GCPIoT } from ‘@lynxjs/cloud’;

const gcp = new GCPIoT({ projectId: ‘my-project’, cloudRegion: ‘asia-east1’, registryId: ‘my-registry’, deviceId: ‘my-device’, privateKeyFile: ‘/path/to/rsa_private.pem’ });

await gcp.connect();

// Publish to Pub/Sub await gcp.publish(‘sensor-data’, { temp: 25.5 });

// Subscribe to config changes gcp.onConfig((config) => { console.log(‘New config:’, config); // Apply config to device }); ```

🏠 Home Automation Integration

1. Home Assistant

Home Assistant เป็น open-source home automation platform ที่นิยมมาก

```typescript import { HomeAssistant } from ‘@lynxjs/integrations’;

const ha = new HomeAssistant({ url: ‘http://homeassistant.local:8123’, token: ‘eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…’ });

// ส่งข้อมูล sensor ไป Home Assistant await ha.setState(‘sensor.greenhouse_temperature’, { state: 25.5, attributes: { unit_of_measurement: ‘°C’, friendly_name: ‘Greenhouse Temperature’, device_class: ‘temperature’ } });

// รับ trigger จาก Home Assistant ha.onTrigger(‘automation.water_plants’, async () => { console.log(’💧 Water plants triggered’); // ทำการรดน้ำ }); ```

2. Node-RED

Node-RED เป็น flow-based programming tool สำหรับ IoT

```typescript import { NodeRED } from ‘@lynxjs/integrations’;

const nodered = new NodeRED({ url: ‘http://nodered.local:1880’ });

// ส่งข้อมูลไป Node-RED await nodered.inject(‘temperature-input’, { temperature: 25.5, humidity: 60 });

// รับข้อมูลจาก Node-RED nodered.on(‘water-pump-control’, (payload) => { if (payload.action === ‘on’) { waterPump.on(); } else { waterPump.off(); } }); ```

3. MQTT Broker

เชื่อมต่อกับ MQTT Broker ของคุณเอง

```typescript import { MQTTClient } from ‘@lynxjs/network’;

const mqtt = new MQTTClient(‘mqtt://broker.hivemq.com’);

await mqtt.connect();

// Subscribe mqtt.subscribe(‘home/commands/+’, (topic, message) => { const cmd = JSON.parse(message); if (cmd.action === ‘water’) { waterPump.on(); } });

// Publish await mqtt.publish(‘home/status’, JSON.stringify({ online: true, ip: getIPAddress(), uptime: process.uptime() })); ```

📱 Mobile App Integration

สร้าง Mobile App ควบคุม IoT devices ด้วย React Native

Backend API

```typescript // src/api/routes.ts import { HTTPServer } from ‘@lynxjs/network’;

const server = new HTTPServer(3000);

// GET /api/sensors - ดึงข้อมูล sensors server.get(‘/api/sensors’, async (req, res) => { const data = { temperature: await dht22.temperature(), humidity: await dht22.humidity(), moisture: await soilMoisture.read(), light: await lightSensor.read() };

res.json(data); });

// POST /api/pump - ควบคุมปั้มน้ำ server.post(‘/api/pump’, async (req, res) => { const { action } = req.body;

if (action === ‘on’) { waterPump.on(); res.json({ success: true, message: ‘Pump turned on’ }); } else { waterPump.off(); res.json({ success: true, message: ‘Pump turned off’ }); } });

server.start(); ```

React Native App

```typescript // Mobile App import React, { useState, useEffect } from ‘react’; import { View, Text, Button } from ‘react-native’;

const App = () => { const [sensors, setSensors] = useState({});

useEffect(() => { // ดึงข้อมูลทุก 5 วินาที const interval = setInterval(async () => { const response = await fetch(‘http://your-pi-ip:3000/api/sensors’); const data = await response.json(); setSensors(data); }, 5000);

return () => clearInterval(interval);

}, []);

const controlPump = async (action) => { await fetch(‘http://your-pi-ip:3000/api/pump’, { method: ‘POST’, body: JSON.stringify({ action }) }); };

return ( Temperature: {sensors.temperature}°C Humidity: {sensors.humidity}% <Button title=“Turn ON Pump” onPress={() => controlPump(‘on’)} /> <Button title=“Turn OFF Pump” onPress={() => controlPump(‘off’)} /> ); }; ```

🛡️ Security Best Practices

1. ใช้ Environment Variables

```bash

.env

WIFI_SSID=your-network WIFI_PASSWORD=your-password MQTT_BROKER=mqtt://broker.hivemq.com API_KEY=your-secret-api-key ```

```typescript import dotenv from ‘dotenv’; dotenv.config();

const config = { wifi: { ssid: process.env.WIFI_SSID, password: process.env.WIFI_PASSWORD }, mqtt: process.env.MQTT_BROKER }; ```

2. Certificate-based Authentication

```typescript import { TLSConfig } from ‘@lynxjs/security’;

const tls = new TLSConfig({ cert: ‘/path/to/cert.pem’, key: ‘/path/to/key.pem’, ca: ‘/path/to/ca.pem’, rejectUnauthorized: true });

// ใช้กับ MQTT const mqtt = new MQTTClient(‘mqtts://broker.example.com’, { tls }); ```

3. API Key Validation

```typescript import { APIKeyAuth } from ‘@lynxjs/security’;

const auth = new APIKeyAuth(process.env.API_KEY);

server.use((req, res, next) => { const apiKey = req.headers[‘x-api-key’];

if (!auth.validate(apiKey)) { return res.status(401).json({ error: ‘Invalid API key’ }); }

next(); }); ```

4. Rate Limiting

```typescript import { RateLimiter } from ‘@lynxjs/security’;

const limiter = new RateLimiter({ windowMs: 60000, // 1 minute max: 100 // 100 requests per minute });

server.use(limiter.middleware()); ```

📈 Performance Optimization

1. Data Batching

```typescript import { DataBatcher } from ‘@lynxjs/utils’;

const batcher = new DataBatcher({ maxSize: 100, flushInterval: 10000 // 10 seconds });

// เก็บข้อมูล batcher.add({ temp: 25.5, humidity: 60 });

// Flush ไป database เมื่อ batch เต็ม batcher.onFlush(async (batch) => { await influx.writeBatch(batch); }); ```

2. Caching

```typescript import { Cache } from ‘@lynxjs/utils’;

const cache = new Cache({ ttl: 60000 }); // 1 minute

async function getSensorData() { const cached = cache.get(‘sensor-data’); if (cached) return cached;

const data = await readAllSensors(); cache.set(‘sensor-data’, data); return data; } ```

3. Connection Pooling

```typescript import { ConnectionPool } from ‘@lynxjs/utils’;

const pool = new ConnectionPool({ max: 10, min: 2, acquireTimeoutMillis: 30000 });

// ใช้ connection จาก pool const conn = await pool.acquire(); await conn.query(‘SELECT * FROM sensors’); pool.release(conn); ```

🎓 สรุป

ในบทความนี้เราได้เรียนรู้:

✅ การ integrate กับ Cloud Services (AWS, Azure, GCP) ✅ การเชื่อมต่อกับ Home Automation Systems ✅ การสร้าง Mobile App ควบคุม IoT devices ✅ Security Best Practices ✅ Performance Optimization


🎉 สรุปทั้งซีรีส์

ใน 3 บทความนี้ เราได้เรียนรู้ LynxJS ตั้งแต่:

  1. Part 1: พื้นฐานและการติดตั้ง
  2. Part 2: การสร้าง IoT Application ที่ซับซ้อน
  3. Part 3: Advanced Integration และ Best Practices

ตอนนี้คุณพร้อมที่จะสร้าง IoT Applications ด้วย LynxJS แล้ว! 🚀


🔗 Links:


❓ มีคำถาม?

Happy IoT Building! 🌟