Posted on
Real-Time WebSocket Architecture: AWS IoT + Angular Integration
1. Introduction
1) Is it possible to interact with real-time data in our Angular project?
Yes, it is possible to interact with the Angular project in real time, it is very easy to do this with WebSocket.
2) Why do we need WebSocket?
We need WebSocket because you don't need to make a request in WebSocket, it works like mqtt, it can connect directly to your iot data and give access to it.
3) What is the difference between API and WebSocket?
The biggest difference between API and WebSocket is that you must make requests for the API at intervals. It is not possible to listen to the data between these requests instantly. However, it is enough to connect to the WebSocket once and all the necessary data will reach you instantly via iot.
4) How do I configure the Angular project in real time with WebSocket?
Let me explain in detail
2. Flow
Figure 1: High-level architecture of the IoT-WebSocket integration.
3. Architecture Overview
- IoT Rule (receives message and triggers Lambda)
- Lambda (processes data and sends it to WebSocket)
- API Gateway (WebSocket API) (connection with client)
- DynamoDB (connectionId record)
- Angular app (connects via wss and processes message)
4. Step-by-Step Implementation
4.1 AWS IoT Setup
4.1.1) Go to IoT Core in AWS console
4.1.2) Click on the rules field under message forwarding and create rule.
4.1.3) Give a topic name (you can write whatever you want)
4.1.4) Use this in the Configure SQL Statement field when creating rules.SELECT * FROM <topic/Name>
4.1.5)<topic/Name>
The name you give in this field must be the same as the name in your plc flow connection.
4.2 API Gateway(WebSocket)
4.2.1) Enter the API gateway via the AWS console and click the Create an API button.
4.2.2) Then select WebSocket API and proceed with the default values.
4.2.3) Then it will give you an API with 3 variables: connect, disconnet, customRoute.
4.2.4) Add the API we will use for connect and the lambda you will create for connect from its lambda integration section (4.3.4).
4.3 Lambda Functions
4.3.1) Create 2 lambdas.
4.3.2) One lambda will record the connectId to dynamodb and the other lambda will send the data to the WebSocket using the iot core.
4.3.3) You can connect lambda to iot directly via rules.
const{DynamoDBClient}=require("@aws-sdk/client-dynamodb");const{DynamoDBDocumentClient,ScanCommand,DeleteCommand}=require("@aws-sdk/lib-dynamodb");const{ApiGatewayManagementApiClient,PostToConnectionCommand}=require("@aws-sdk/client-apigatewaymanagementapi");constddbClient=newDynamoDBClient({});constddbDocClient=DynamoDBDocumentClient.from(ddbClient);constapiGatewayClient=newApiGatewayManagementApiClient({endpoint:'<your-websocket-endpoint>'});consthandler=async(event)=>{console.log('MQTT event:',event);constdata=awaitddbDocClient.send(newScanCommand({TableName:'<Your-TableName>'}));constmessage=JSON.stringify(event);constpostCalls=data.Items.map(async({connectionId})=>{try{console.log('Sending message to connection:',connectionId);awaitapiGatewayClient.send(newPostToConnectionCommand({ConnectionId:connectionId,Data:Buffer.from(message)}));}catch(e){if(e.statusCode===410){awaitddbDocClient.send(newDeleteCommand({TableName:'WebSocketConnections',Key:{connectionId}}));}else{throwe;}}});awaitPromise.all(postCalls);return{statusCode:200};};exports.handler=handler;
ℹ️Info: A lambda code example is given for sample NodeJS version 18 that processes iot code (use it for iot lambda).
4.3.4) In the lambda for the API gateway that you connect to from your Angular application, all you need to do is get the connectId from the event(event.requestContext.connectionId) and write it to the table you want.
4.4 Angular WebSocket Connection
4.4.1) Go to your angular project and create a service file.
import{Injectable,NgZone}from'@angular/core';import{Subject}from'rxjs';@Injectable({providedIn:'root'})exportclassWebSocketService{privatesocket:WebSocket|null=null;publicmessages:Subject<string>=newSubject();constructor(privatengZone:NgZone){}publicconnect(url:string):void{this.socket=newWebSocket(url);this.socket.onopen=(event)=>{console.log('WebSocket connected');};this.socket.onmessage=(event)=>{this.ngZone.run(()=>{this.messages.next(event.data);});};this.socket.onerror=(event)=>{console.error('WebSocket error:',event);};this.socket.onclose=(event)=>{console.log('WebSocket closed:',event);};}publicsendMessage(message:string):void{if(this.socket&&this.socket.readyState===WebSocket.OPEN){this.socket.send(message);}}publicdisconnect():void{if(this.socket){this.socket.close();}}}
ℹ️Info: The code given above is the content of the service file created in an Angular project.
4.4.2) Then go to a component to which you have connected your service and connect to your connect API.
this.websocketService.connect('wss://your-websocket-url');this.websocketService.messages.subscribe(msg=>{console.log('Received:',msg);});
ℹ️Info: The code given above is for a TypeScript Angular component file connected to the service.
5. Conclusion
In this article, we explored how to implement real-time data interaction in an Angular application using WebSocket and AWS services like IoT Core, Lambda, and API Gateway. We covered the architecture, setup, and key implementation details including code samples.
By leveraging WebSocket, applications can achieve efficient, low-latency communication without polling, making it ideal for IoT and real-time scenarios.
Feel free to explore the code examples and customize them for your specific use cases. Happy coding!
References
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse