Semua Tentang Belajar Teknologi Digital Dalam Kehidupan Sehari - Hari

Kamis, 09 November 2023

Cara Chat GPT Membantu Kodingan Kamu - Edisi Publish MQTT Web Socket

 



Perkenalan saya dengan fenomena Artificial Inteligent "Chat GPT" memasuki tahun ke dua dan terus menghasilkan rasa takjub di otak saya. Walau ada sedikit ke khawatiran yang selalu muncul sejak awal, yaitu mungkin akan mengakibatkan  'kemalasan' otak untuk berpikir. Namun atas saran seorang teman yang sangat membanggakan platform dari openAI apalagi si dia sudah mencoba versi 4 yang berbayar, saya makin gatel untuk mencobanya. Asalkan kamu bisa menggiring "prompt"  nya, maka semua pertanyaan yang kamu ajukan akan mendapatkan hasil yang memuaskan, begitu saran teman saya ini.

Seperti pada tulisan kali ini disaat suntuk kepanasan di siang bolong, saya membaca kembali tulisan saya sebelumnya tentang e-voting menggunakan MQTT dan python ( disini ), dan ketika melihat tampilan e-votingnya begitu 'rudimental' maka saya teringat dulu saya pernah juga membuat APK android  berbasis web saat bermain-main esp8266 dan kunci motor, bisa dibaca disini

Tapi permasalahannya saya gak paham apakah "plain" html dapat melakukan koding MQTT ? Seingat saya ada istilah di broker mqtt yang saya sering gunakan yaitu hivemq memiliki support terhadap protokol websocket di port 8000. Daripada pusing maka saya menggunakan fasilitas chat GPT untuk mencari jawaban bagaimana  cara coding htmlnya. Ayo saya share ke pembaca langkah2 saya menggunakan chat GPT.



Saya iseng aja membuka pembicaraan seperti gambar diatas dengan bertanya apakah chat gpt dapat mengirimkan pesan MQTT ? Ya tentu saja chat gpt namanya saja "chat" ya terbatas untuk mengirimkan jawaban dari pertanyaan. Selanjutnya saya menggiring chat gpt untuk menjawab pertanyaan seperti "kapan kira-kira bisanya kirim pesan mqtt?" , "apa kirim sms bisa lewat chat gpt?", "tolong dong kirimkan pesan mqtt", sangat iseng pokoknya.

Sampai saat saya waras kembali, saya mengajukan pertanyaan sederhana: " Can i send mqtt message via HTML ?" dan jawabannya mencerahkan saya.



Yes, you can send MQTT messages from a web page using HTML and JavaScript, but you would need to use a JavaScript library or framework that supports MQTT, such as the Eclipse Paho MQTT JavaScript library. Here are the general steps to send MQTT messages from a web page:

  1. Include the MQTT JavaScript library: You need to include the MQTT JavaScript library in your HTML page. You can do this by including the library's JavaScript file in your HTML, like this:
html
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js"></script>


Dan kemudian saya meminta untuk dituliskan contohnya, " show me complete html for mqtt publisher".

Creating a complete HTML page for an MQTT publisher requires more than just HTML; you'll need JavaScript and, optionally, CSS to create a user interface. Below is a basic example of an HTML page that includes JavaScript for an MQTT publisher. This example uses the Eclipse Paho MQTT JavaScript library to send messages to an MQTT broker. Remember to replace the MQTT broker and topic information with your own.

html
<!DOCTYPE html> 
<html> <head> <title>MQTT Publisher</title> </head> <body> <h1>MQTT Publisher</h1> <label for="message">Message:</label> <input type="text" id="message" placeholder="Enter your message"> <button id="publishButton">Publish Message</button> <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js"></script> <script> // Function to handle the button click function publishMessage() { var messageInput = document.getElementById("message"); var message = messageInput.value; // Create an MQTT client var client = new Paho.MQTT.Client("mqtt.eclipse.org", 80, "clientId"); // Set up the connection options var options = { onSuccess: onConnect, onFailure: onFailure, }; // Connect to the MQTT broker client.connect(options); // Called when the connection is successful function onConnect() { console.log("Connected to the MQTT broker"); // Send the MQTT message var message = new Paho.MQTT.Message(message); message.destinationName = "your/topic"; // Replace with your desired MQTT topic client.send(message); } // Called when the connection fails function onFailure(message) { console.log("Connection failed: " + message.errorMessage); } } // Attach the click event to the button var publishButton = document.getElementById("publishButton"); publishButton.addEventListener("click", publishMessage); </script> </body> </html>
*)Scriptnya agak kacau disini, namun di chat gpt dan editor notepad saya rapi kok !


Wihhh ayo kita coba langsung copy paste di notepad, sesuaikan parameter dan jalankan ! namun ada error yang muncul pada console html ( pencet click kanan lalu pilih  inspeksi  atau CTRL+SHIFT+I) dimana  library java nya error. Lalu saya bertanya begini :

mqttws31.min.js got error


dan dijawab :


I apologize for any confusion. The mqttws31.min.js script I mentioned earlier might not be the latest version, and it's possible that it may not work as expected. HiveMQ and the Paho MQTT library may have evolved since my last update.

To ensure that you are using an up-to-date version of the Paho MQTT JavaScript library that works with HiveMQ, it's best to include the latest version from a reliable source. You can get the latest version from the Eclipse Paho GitHub repository or their official website.

Here's how to include the latest version from the Eclipse Paho GitHub repository:

html
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.1.0/mqttws31.min.js"></script>

Alternatively, you can download the library directly from the Eclipse Paho GitHub repository and host it on your own server to ensure you are using the most recent version:

  1. Go to the Eclipse Paho GitHub repository for JavaScript: https://github.com/eclipse/paho.mqtt.javascript

  2. Download the latest release of the Paho JavaScript library.

  3. Host the downloaded JavaScript file on your server or include it directly in your HTML as needed.

Remember to replace "your-hivemq-broker-url" and other configuration settings with the correct values for your HiveMQ instance. Additionally, make sure that your HiveMQ instance is properly configured to support WebSocket connections.



Dan hasilnya untuk contoh (yang sudah saya sesuaikan) script pub yang benar ke broker seperti berikut 

<!DOCTYPE html>
<html>
<head>
    <title>MQTT WebSocket Publisher</title>
</head>
<body>
    <h1>MQTT WebSocket Publisher</h1>
    
    <label for="message">Message:</label>
    <input type="text" id="message" placeholder="Enter your message">
    
    <button id="publishButton">Publish Message</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js"></script>
	
    <script>
        // Function to handle the button click
        function publishMessage() {
            var messageInput = document.getElementById("message");
            var pesan = messageInput.value;

            // Create an MQTT client
            var client = new Paho.MQTT.Client("broker.hivemq.com", Number(8000), "clientId-yttggg");

            // Set up the connection options
            var options = {
                useSSL: false,  // Set to true if your broker supports secure WebSocket connections
                onSuccess: onConnect,
                onFailure: onFailure,
            };

            // Connect to the MQTT broker via WebSocket
            client.connect(options);

            // Called when the connection is successful
            function onConnect() {
                console.log("Connected to the MQTT broker");

                // Send the MQTT message
                var message = new Paho.MQTT.Message(pesan);
                message.destinationName = "/ahocool/chatgpt"; // Replace with your desired MQTT topic
                client.send(message);

                // Disconnect after sending the message (optional)
                client.disconnect();
            }

            // Called when the connection fails
            function onFailure(message) {
                console.log("Connection failed: " + message.errorMessage);
            }
        }

        // Attach the click event to the button
        var publishButton = document.getElementById("publishButton");
        publishButton.addEventListener("click", publishMessage);
    </script>
</body>
</html>



Hasilnya ketika saya membuka client mqtt dan klik publish pada topik "/ahocool/chatgpt " seperti gambar berikut :




Selanjutnya pada tulisan berikut akan kita bahas mengenai proses subscribe dan masih dengan bantuan chatgpt.
Share:

0 komentar:

Posting Komentar

Kontak Penulis



12179018.png (60×60)
+628155737755

Mail : ahocool@gmail.com

Site View

Categories

555 (8) 7 segmen (3) adc (4) amplifier (2) analog (19) android (12) antares (11) arduino (27) artikel (11) attiny (3) attiny2313 (19) audio (5) baterai (5) blog (1) bluetooth (1) chatgpt (2) cmos (2) crypto (2) dasar (46) digital (11) dimmer (5) display (3) esp8266 (26) euro2020 (13) gcc (1) gsm (1) iklan (1) infrared (2) Input Output (3) iot (74) jam (7) jualan (12) kereta api (1) keyboard (1) keypad (3) kios pulsa (2) kit (6) komponen (17) komputer (3) komunikasi (1) kontrol (8) lain-lain (8) lcd (2) led (14) led matrix (6) line tracer (1) lm35 (1) lora (11) lorawan (2) MATV (1) memory (1) metal detector (4) microcontroller (70) micropython (6) mikrokontroler (1) mikrokontroller (14) mikrotik (5) modbus (9) mqtt (3) ninmedia (5) ntp (1) paket belajar (19) palang pintu otomatis (1) parabola (88) pcb (2) power (1) praktek (2) project (33) proyek (1) python (8) radio (28) raspberry pi (9) remote (1) revisi (1) rfid (1) robot (1) rpm (2) rs232 (1) script break down (3) sdcard (3) sensor (2) sharing (3) signage (1) sinyal (1) sms (6) software (18) solar (1) solusi (1) tachometer (2) technology (1) teknologi (2) telegram (2) telepon (9) televisi (167) television (28) telkomiot (5) transistor (2) troubleshoot (3) tulisan (94) tutorial (108) tv digital (6) tvri (2) vu meter (2) vumeter (2) wav player (3) wayang (1) wifi (3) yolo (7)

Arsip Blog

Diskusi


kaskus
Forum Hobby Elektronika