Я пытаюсь подключить веб -клиента к AWS IoT Core, используя JavaScript Over Websocket, аутентифицированный через пул идентификации Amazon Cognito. Неавтотимированная роль, используемая Cognito, а также прикрепляла политику к сертификату, использованному устройством. /> "IoT: Connect",
"IOT: подписка",
"iot: chective",
"iot: publish"
],
"ресурс": "*"
}
} < /p>
javascript code: < /p>
} < /p>
javascript: < /p>
} < /p>
javascript: < /p> PrettyPrint-Override ">// --- Configuration ---
const AWS_REGION = '';
const COGNITO_IDENTITY_POOL_ID = '';
const IOT_CORE_ENDPOINT = '';
const MQTT_TOPIC = '';
// --- DOM Elements ---
const connectionStatusElement = document.getElementById('connection-status');
const iotDataElement = document.getElementById('iot-data');
const reconnectButton = document.getElementById('reconnect-button');
let connection; // Declare connection globally to manage its state
// --- Function to get AWS Credentials from Cognito ---
async function getAWSCredentials() {
AWS.config.region = AWS_REGION;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: COGNITO_IDENTITY_POOL_ID
});
try {
await AWS.config.credentials.getPromise();
console.log('Successfully got AWS credentials from Cognito.');
return {
accessKeyId: AWS.config.credentials.accessKeyId,
secretAccessKey: AWS.config.credentials.secretAccessKey,
sessionToken: AWS.config.credentials.sessionToken
};
} catch (error) {
console.error('Error getting AWS credentials:', error);
throw error; // Propagate the error
}
}
// --- Function to Connect to AWS IoT Core and Subscribe ---
async function connectAndSubscribe() {
connectionStatusElement.textContent = 'Connecting...';
reconnectButton.style.display = 'none';
try {
const credentials = await getAWSCredentials();
const clientID = `web_client_${Math.random().toString(16).substr(2, 8)}`; // Unique client ID
// Initialize the AWS IoT MQTT Connection
connection = new iot.AwsIotMqttConnection({
endpoint: IOT_CORE_ENDPOINT,
protocol: iot.AwsIotMqttConnectionConfig.ConnectThroughWebSocket,
credentialsProvider: {
get: {
credentials: () => ({
aws_access_key_id: credentials.accessKeyId,
aws_secret_access_key: credentials.secretAccessKey,
aws_session_token: credentials.sessionToken,
}),
}
},
cleanSession: true,
clientId: clientID,
keepAlive: 30
});
// --- Event Listeners ---
connection.on('connect', () => {
console.log('Connected to AWS IoT Core!');
connectionStatusElement.textContent = 'Connected';
connectionStatusElement.style.color = 'green';
// Subscribe to the topic
connection.subscribe(MQTT_TOPIC, iot.QoS.AtLeastOnce)
.then(() => {
console.log(`Subscribed to topic: ${MQTT_TOPIC}`);
})
.catch(error => {
console.error('Subscription error:', error);
connectionStatusElement.textContent = `Connected (Subscription Failed)`;
connectionStatusElement.style.color = 'orange';
});
});
connection.on('message', (topic, payload) => {
console.log(`Message received on topic ${topic}: ${payload.toString()}`);
try {
const data = JSON.parse(payload.toString());
iotDataElement.textContent = JSON.stringify(data, null, 2);
} catch (e) {
iotDataElement.textContent = `Raw: ${payload.toString()}`;
console.warn('Received non-JSON message:', payload.toString());
}
});
connection.on('error', (error) => {
console.error('MQTT Connection Error:', error);
connectionStatusElement.textContent = `Error: ${error.message}`;
connectionStatusElement.style.color = 'red';
reconnectButton.style.display = 'block';
});
connection.on('close', () => {
console.log('MQTT Connection Closed');
connectionStatusElement.textContent = 'Disconnected';
connectionStatusElement.style.color = 'gray';
reconnectButton.style.display = 'block';
});
// --- Connect to IoT Core ---
await connection.connect();
} catch (error) {
console.error('Failed to connect to AWS IoT Core:', error);
connectionStatusElement.textContent = `Failed to Connect: ${error.message || error}`;
connectionStatusElement.style.color = 'red';
reconnectButton.style.display = 'block';
}
}
// --- Reconnect Button Handler ---
reconnectButton.addEventListener('click', () => {
if (connection && connection.isConnected) {
console.log('Already connected, no need to reconnect.');
return;
}
connectAndSubscribe();
});
// --- Initial Connection on Page Load ---
document.addEventListener('DOMContentLoaded', connectAndSubscribe);
Подробнее здесь: https://stackoverflow.com/questions/796 ... -via-react
AWS IoT Core WebSocket MQTT через React ⇐ Javascript
Форум по Javascript
1749621460
Anonymous
Я пытаюсь подключить веб -клиента к AWS IoT Core, используя JavaScript Over Websocket, аутентифицированный через пул идентификации Amazon Cognito. Неавтотимированная роль, используемая Cognito, а также прикрепляла политику к сертификату, использованному устройством. /> "IoT: Connect",
"IOT: подписка",
"iot: chective",
"iot: publish"
],
"ресурс": "*"
}
} < /p>
javascript code: < /p>
} < /p>
javascript: < /p>
} < /p>
javascript: < /p> PrettyPrint-Override ">// --- Configuration ---
const AWS_REGION = '';
const COGNITO_IDENTITY_POOL_ID = '';
const IOT_CORE_ENDPOINT = '';
const MQTT_TOPIC = '';
// --- DOM Elements ---
const connectionStatusElement = document.getElementById('connection-status');
const iotDataElement = document.getElementById('iot-data');
const reconnectButton = document.getElementById('reconnect-button');
let connection; // Declare connection globally to manage its state
// --- Function to get AWS Credentials from Cognito ---
async function getAWSCredentials() {
AWS.config.region = AWS_REGION;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: COGNITO_IDENTITY_POOL_ID
});
try {
await AWS.config.credentials.getPromise();
console.log('Successfully got AWS credentials from Cognito.');
return {
accessKeyId: AWS.config.credentials.accessKeyId,
secretAccessKey: AWS.config.credentials.secretAccessKey,
sessionToken: AWS.config.credentials.sessionToken
};
} catch (error) {
console.error('Error getting AWS credentials:', error);
throw error; // Propagate the error
}
}
// --- Function to Connect to AWS IoT Core and Subscribe ---
async function connectAndSubscribe() {
connectionStatusElement.textContent = 'Connecting...';
reconnectButton.style.display = 'none';
try {
const credentials = await getAWSCredentials();
const clientID = `web_client_${Math.random().toString(16).substr(2, 8)}`; // Unique client ID
// Initialize the AWS IoT MQTT Connection
connection = new iot.AwsIotMqttConnection({
endpoint: IOT_CORE_ENDPOINT,
protocol: iot.AwsIotMqttConnectionConfig.ConnectThroughWebSocket,
credentialsProvider: {
get: {
credentials: () => ({
aws_access_key_id: credentials.accessKeyId,
aws_secret_access_key: credentials.secretAccessKey,
aws_session_token: credentials.sessionToken,
}),
}
},
cleanSession: true,
clientId: clientID,
keepAlive: 30
});
// --- Event Listeners ---
connection.on('connect', () => {
console.log('Connected to AWS IoT Core!');
connectionStatusElement.textContent = 'Connected';
connectionStatusElement.style.color = 'green';
// Subscribe to the topic
connection.subscribe(MQTT_TOPIC, iot.QoS.AtLeastOnce)
.then(() => {
console.log(`Subscribed to topic: ${MQTT_TOPIC}`);
})
.catch(error => {
console.error('Subscription error:', error);
connectionStatusElement.textContent = `Connected (Subscription Failed)`;
connectionStatusElement.style.color = 'orange';
});
});
connection.on('message', (topic, payload) => {
console.log(`Message received on topic ${topic}: ${payload.toString()}`);
try {
const data = JSON.parse(payload.toString());
iotDataElement.textContent = JSON.stringify(data, null, 2);
} catch (e) {
iotDataElement.textContent = `Raw: ${payload.toString()}`;
console.warn('Received non-JSON message:', payload.toString());
}
});
connection.on('error', (error) => {
console.error('MQTT Connection Error:', error);
connectionStatusElement.textContent = `Error: ${error.message}`;
connectionStatusElement.style.color = 'red';
reconnectButton.style.display = 'block';
});
connection.on('close', () => {
console.log('MQTT Connection Closed');
connectionStatusElement.textContent = 'Disconnected';
connectionStatusElement.style.color = 'gray';
reconnectButton.style.display = 'block';
});
// --- Connect to IoT Core ---
await connection.connect();
} catch (error) {
console.error('Failed to connect to AWS IoT Core:', error);
connectionStatusElement.textContent = `Failed to Connect: ${error.message || error}`;
connectionStatusElement.style.color = 'red';
reconnectButton.style.display = 'block';
}
}
// --- Reconnect Button Handler ---
reconnectButton.addEventListener('click', () => {
if (connection && connection.isConnected) {
console.log('Already connected, no need to reconnect.');
return;
}
connectAndSubscribe();
});
// --- Initial Connection on Page Load ---
document.addEventListener('DOMContentLoaded', connectAndSubscribe);
Подробнее здесь: [url]https://stackoverflow.com/questions/79661456/aws-iot-core-websocket-mqtt-via-react[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия