Skip to content

Commit 83a1959

Browse files
committed
Add Internet Computer (Motoko) integration guide with frontend proxy pattern solution
1 parent afda68d commit 83a1959

1 file changed

Lines changed: 348 additions & 14 deletions

File tree

‎CAFFEINE_AI_INTEGRATION_GUIDE.md‎

Lines changed: 348 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -757,24 +757,358 @@ Before deploying to production:
757757

758758
---
759759

760+
## Internet Computer (Motoko) Integration - CRITICAL
761+
762+
### ⚠️ Important: Internet Computer Limitations
763+
764+
**Internet Computer canisters CANNOT directly connect to HTTP endpoints!**
765+
766+
The error you're seeing:
767+
```
768+
Connecting to caffeine-ai-broker.run.goorm.site failed: DNS error
769+
```
770+
771+
This happens because:
772+
1. **IC canisters can only make HTTPS outbound calls** (not HTTP)
773+
2. **IC requires whitelisted domains** for HTTP outcalls
774+
3. **Direct HTTP connections from canisters are blocked** for security
775+
776+
### Solution: Use Frontend as Proxy (Recommended)
777+
778+
**Architecture:**
779+
```
780+
User Browser [HTTPS]
781+
↓
782+
Caffeine.ai Frontend [HTTPS]
783+
↓ (fetch from browser)
784+
Bridge API (localhost:8080) [HTTP]
785+
↓
786+
Industrial Scales
787+
```
788+
789+
**Implementation:**
790+
791+
#### 1. Frontend Proxy Function (TypeScript/JavaScript)
792+
793+
Create a proxy function in your frontend that calls Bridge API:
794+
795+
```typescript
796+
// frontend/src/services/bridge-proxy.ts
797+
const BRIDGE_URL = import.meta.env.VITE_BRIDGE_URL || 'http://127.0.0.1:8080';
798+
799+
export async function callBridgeAPI(
800+
endpoint: string,
801+
options?: RequestInit
802+
): Promise<Response> {
803+
// Frontend (browser) can call HTTP endpoints
804+
const url = `${BRIDGE_URL}${endpoint}`;
805+
806+
const response = await fetch(url, {
807+
...options,
808+
headers: {
809+
'Content-Type': 'application/json',
810+
...options?.headers,
811+
},
812+
});
813+
814+
if (!response.ok) {
815+
throw new Error(`Bridge API error: ${response.status} ${response.statusText}`);
816+
}
817+
818+
return response;
819+
}
820+
821+
// Wrapper functions
822+
export async function getBridgeHealth() {
823+
const response = await callBridgeAPI('/health');
824+
return await response.json();
825+
}
826+
827+
export async function getDevices() {
828+
const response = await callBridgeAPI('/devices');
829+
return await response.json();
830+
}
831+
832+
export async function executeScaleCommand(deviceId: string, command: string) {
833+
const response = await callBridgeAPI('/scalecmd', {
834+
method: 'POST',
835+
body: JSON.stringify({ device_id: deviceId, command }),
836+
});
837+
return await response.json();
838+
}
839+
```
840+
841+
#### 2. Motoko Canister - Expose Query/Update Methods
842+
843+
In your Motoko canister, expose methods that the frontend can call:
844+
845+
```motoko
846+
// Main.mo
847+
import Text "mo:base/Text";
848+
import Result "mo:base/Result";
849+
850+
actor ScaleService {
851+
852+
// Frontend will call this, then proxy to Bridge
853+
public query func getHealthStatus() : async Text {
854+
// Return status - frontend will check Bridge
855+
return "Frontend will check Bridge health";
856+
};
857+
858+
// Store weight reading from frontend
859+
private var lastWeightReading : ?WeightReading = null;
860+
861+
public type WeightReading = {
862+
gross_weight : Float;
863+
net_weight : Float;
864+
unit : Text;
865+
is_stable : Bool;
866+
timestamp : Text;
867+
};
868+
869+
// Frontend calls Bridge, then calls this to store result
870+
public func storeWeightReading(reading : WeightReading) : async () {
871+
lastWeightReading := ?reading;
872+
};
873+
874+
public query func getLastWeightReading() : async ?WeightReading {
875+
return lastWeightReading;
876+
};
877+
878+
// Frontend will handle Bridge communication
879+
public func requestWeightReading(deviceId : Text, command : Text) : async Text {
880+
// Return instruction for frontend to call Bridge
881+
return "Frontend should call Bridge API and then storeWeightReading()";
882+
};
883+
}
884+
```
885+
886+
#### 3. Frontend Integration (React/TypeScript)
887+
888+
```typescript
889+
// frontend/src/components/ScaleControl.tsx
890+
import { callBridgeAPI, executeScaleCommand } from '@/services/bridge-proxy';
891+
import { actor } from '@/services/ic-agent'; // Your IC agent setup
892+
893+
async function handleReadWeight(deviceId: string) {
894+
try {
895+
// 1. Call Bridge API from frontend (browser can access HTTP)
896+
const bridgeResponse = await executeScaleCommand(deviceId, 'readGross');
897+
898+
if (bridgeResponse.success && bridgeResponse.result) {
899+
// 2. Store result in IC canister
900+
const weightReading = {
901+
gross_weight: bridgeResponse.result.gross_weight,
902+
net_weight: bridgeResponse.result.net_weight,
903+
unit: bridgeResponse.result.unit,
904+
is_stable: bridgeResponse.result.is_stable,
905+
timestamp: bridgeResponse.result.timestamp,
906+
};
907+
908+
await actor.storeWeightReading(weightReading);
909+
910+
return weightReading;
911+
} else {
912+
throw new Error(bridgeResponse.error || 'Command failed');
913+
}
914+
} catch (error) {
915+
console.error('Error reading weight:', error);
916+
throw error;
917+
}
918+
}
919+
```
920+
921+
### Alternative Solution: HTTPS Tunnel for Bridge
922+
923+
If you need canister to directly call Bridge, you MUST use HTTPS:
924+
925+
#### Step 1: Set up HTTPS Tunnel
926+
927+
```bash
928+
# Using ngrok
929+
ngrok http 8080
930+
931+
# Or Cloudflare Tunnel
932+
cloudflared tunnel --url http://localhost:8080
933+
```
934+
935+
#### Step 2: Configure IC HTTP Outcalls
936+
937+
In your `dfx.json` or canister configuration, whitelist the HTTPS domain:
938+
939+
```json
940+
{
941+
"canisters": {
942+
"your_canister": {
943+
"http_outcalls": {
944+
"allowed_urls": [
945+
"https://your-bridge-tunnel.ngrok.io",
946+
"https://bridge.yourdomain.com"
947+
]
948+
}
949+
}
950+
}
951+
}
952+
```
953+
954+
#### Step 3: Use HTTPS Outcalls in Motoko
955+
956+
```motoko
957+
import HTTP "mo:base/Http";
958+
import Text "mo:base/Text";
959+
960+
actor ScaleService {
961+
let bridgeUrl = "https://your-bridge-tunnel.ngrok.io";
962+
963+
public func readWeight(deviceId : Text) : async Result.Result<WeightReading, Text> {
964+
let url = bridgeUrl # "/scalecmd";
965+
let body = Text.encodeUtf8(
966+
"{ \"device_id\": \"" # deviceId # "\", \"command\": \"readGross\" }"
967+
);
968+
969+
let request : HTTP.Request = {
970+
method = "POST";
971+
url = url;
972+
headers = [
973+
("Content-Type", "application/json")
974+
];
975+
body = body;
976+
};
977+
978+
// Use HTTPS outcall
979+
switch (await HTTP.http_request(request)) {
980+
case (#ok response) {
981+
// Parse JSON response
982+
// Return WeightReading
983+
};
984+
case (#err error) {
985+
return #err("HTTP error: " # debug_show(error));
986+
};
987+
};
988+
};
989+
}
990+
```
991+
992+
### Recommended Architecture for Caffeine.ai
993+
994+
**Best Practice: Frontend Proxy Pattern**
995+
996+
```
997+
┌─────────────────┐
998+
│ User Browser │
999+
└────────┬────────┘
1000+
│ HTTPS
1001+
↓
1002+
┌─────────────────────────┐
1003+
│ Caffeine.ai Frontend │ ← React/TypeScript
1004+
│ (Vercel/IC Frontend) │
1005+
└─────┬───────────┬───────┘
1006+
│ │
1007+
│ HTTPS │ HTTPS (update call)
1008+
↓ ↓
1009+
┌──────────┐ ┌──────────────────┐
1010+
│ Bridge │ │ IC Canister │
1011+
│ (HTTP) │ │ (Motoko) │
1012+
└──────────┘ └──────────────────┘
1013+
```
1014+
1015+
**Flow:**
1016+
1. User clicks "Read Weight" in frontend
1017+
2. Frontend calls Bridge API directly (browser → HTTP Bridge) ✅
1018+
3. Frontend receives weight reading
1019+
4. Frontend calls IC canister to store result (browser → HTTPS IC) ✅
1020+
5. IC canister stores data on-chain
1021+
1022+
**Why this works:**
1023+
- Browser can access HTTP endpoints (with Mixed Content handling)
1024+
- Browser can access HTTPS IC canisters
1025+
- No need for IC HTTP outcalls
1026+
- Simpler architecture
1027+
- Better error handling
1028+
1029+
### Error Handling for Caffeine.ai
1030+
1031+
```typescript
1032+
// frontend/src/services/bridge-proxy.ts
1033+
export async function callBridgeAPIWithRetry(
1034+
endpoint: string,
1035+
options?: RequestInit,
1036+
maxRetries: number = 3
1037+
): Promise<Response> {
1038+
for (let i = 0; i < maxRetries; i++) {
1039+
try {
1040+
return await callBridgeAPI(endpoint, options);
1041+
} catch (error) {
1042+
if (i === maxRetries - 1) throw error;
1043+
1044+
// Check for Mixed Content
1045+
if (error.message.includes('Failed to fetch') &&
1046+
window.location.protocol === 'https:') {
1047+
throw new Error('MIXED_CONTENT_BLOCKED: Please allow Mixed Content in browser settings');
1048+
}
1049+
1050+
// Wait before retry
1051+
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
1052+
}
1053+
}
1054+
throw new Error('Max retries exceeded');
1055+
}
1056+
```
1057+
1058+
### Configuration for Caffeine.ai
1059+
1060+
**Environment Variables (Frontend):**
1061+
```env
1062+
# For local development
1063+
VITE_BRIDGE_URL=http://127.0.0.1:8080
1064+
1065+
# For production (use your computer's IP)
1066+
VITE_BRIDGE_URL=http://192.168.1.100:8080
1067+
1068+
# Or use HTTPS tunnel
1069+
VITE_BRIDGE_URL=https://bridge-tunnel.ngrok.io
1070+
```
1071+
1072+
**Important Notes:**
1073+
1. **Never call Bridge API directly from Motoko canister** (unless using HTTPS tunnel)
1074+
2. **Always use frontend as proxy** for HTTP Bridge endpoints
1075+
3. **Store results in IC canister** after receiving from Bridge
1076+
4. **Handle Mixed Content** if frontend is HTTPS and Bridge is HTTP
1077+
5. **Use environment variables** for Bridge URL configuration
1078+
1079+
---
1080+
7601081
## Summary for Caffeine.ai Agent
7611082

7621083
**Key Points:**
763-
1. Bridge API runs on `http://localhost:8080` (local) or `http://IP:8080` (network)
764-
2. All endpoints support CORS automatically
765-
3. Mixed Content (HTTPS → HTTP) must be handled via:
1084+
1. **IC canisters CANNOT call HTTP endpoints directly** - use frontend proxy
1085+
2. Bridge API runs on `http://localhost:8080` (local) or `http://IP:8080` (network)
1086+
3. All endpoints support CORS automatically
1087+
4. Mixed Content (HTTPS → HTTP) must be handled via:
7661088
- Environment variable with IP address
7671089
- HTTPS tunnel
7681090
- User instructions
769-
4. Always implement timeout handling (30 seconds recommended)
770-
5. Use proper error handling for network errors
771-
6. Bridge supports TCP/IP and Serial connections
772-
7. Commands: `readGross`, `readNet`, `tare`, `zero`
773-
774-
**Recommended Approach:**
775-
1. Use environment variable `VITE_BRIDGE_URL` for Bridge URL
776-
2. Implement Mixed Content detection and user instructions
777-
3. Use IP address instead of `localhost` for network access
778-
4. Implement retry logic for transient errors
779-
5. Always set timeouts for API calls
1091+
5. Always implement timeout handling (30 seconds recommended)
1092+
6. Use proper error handling for network errors
1093+
7. Bridge supports TCP/IP and Serial connections
1094+
8. Commands: `readGross`, `readNet`, `tare`, `zero`
1095+
1096+
**Recommended Approach for Caffeine.ai:**
1097+
1. **Use Frontend Proxy Pattern:**
1098+
- Frontend (browser) calls Bridge API directly
1099+
- Frontend calls IC canister to store results
1100+
- No direct IC → Bridge communication needed
1101+
2. Use environment variable `VITE_BRIDGE_URL` for Bridge URL
1102+
3. Implement Mixed Content detection and user instructions
1103+
4. Use IP address instead of `localhost` for network access
1104+
5. Implement retry logic for transient errors
1105+
6. Always set timeouts for API calls
1106+
1107+
**Architecture Pattern:**
1108+
```
1109+
Browser → Frontend → Bridge (HTTP) ✅
1110+
Browser → Frontend → IC Canister (HTTPS) ✅
1111+
IC Canister → Bridge (HTTP) ❌ NOT POSSIBLE
1112+
IC Canister → Bridge (HTTPS Tunnel) ✅ POSSIBLE but complex
1113+
```
7801114

0 commit comments

Comments
 (0)