Skip to main content
Intro to IoT Class Docs
Tech TLH Discord Code and Coffee TLH GitHub Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Gemini Code

Crafting a Prompt

Before getting lost in AI’s specific brand of madness, it’s good to write out what you want in a blank scratch document.

State your intent:

Generate a single webpage to view iot data.

State the specific technical details (change connection details to your own):

The page needs jquery to connect to HiveMQ.

The MQTT message is JSON and has the following properties:
* time (string in ISO8601 format)
* temperature (number in farenheit)
* humidity (number in percent)

The MQTT connection properties are:
* username: dashboard
* password: password123
* topic: /code/coffee
* server: 0123456789abcdef.s1.eu.hivemq.cloud:8884/mqtt

And state what you expect it to produce:

The page should have:
* large numbers showing the current values
* a switch to convert between farenheit and celsius
* a line graph showing history of both temperature and humidity

Gemini

If you put all of that together, you can cram it in that tiny textbox on Gemini.

Before you hit enter, though, be sure to click on Tools and select Canvas.

Selecting Canvas
Selecting Canvas

With canvas, the code will generate in the right pane and should switch to preview when done.

The Code/Preview Switch
The Code/Preview Switch

Does it look a little boring? Tell it.

I don't like the theme.  Make it look like Pokemon.

What It Generated

If you don’t have a Google account or don’t want to mess with AI, here is the code it generated in my attempt. You can save it locally as index.html and change the configuration in MQTT_CONFIG at line 70.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IoT Data Dashboard</title>
    <!-- Dependencies -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { background-color: #f8fafc; }
        .metric-card { transition: transform 0.2s; }
        .metric-card:hover { transform: translateY(-2px); }
    </style>
</head>
<body class="p-4 md:p-8">
    <div class="max-w-5xl mx-auto">
        <header class="flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
            <h1 class="text-3xl font-bold text-slate-800">HiveMQ IoT Monitor</h1>
            
            <div class="flex items-center gap-4 bg-white p-2 rounded-xl shadow-sm border border-slate-200">
                <span class="text-sm font-medium text-slate-600">Unit:</span>
                <div class="flex bg-slate-100 rounded-lg p-1">
                    <button id="btnCelsius" class="px-4 py-1 rounded-md text-sm font-bold transition-all">°C</button>
                    <button id="btnFahrenheit" class="px-4 py-1 rounded-md text-sm font-bold bg-white shadow-sm text-blue-600 transition-all">°F</button>
                </div>
            </div>
        </header>

        <!-- Connection Status Indicator -->
        <div id="statusBox" class="mb-6 p-3 rounded-lg text-center text-sm font-medium bg-amber-50 text-amber-700 border border-amber-200">
            Connecting to HiveMQ Cloud...
        </div>

        <!-- Big Numbers -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
            <div class="metric-card bg-white p-8 rounded-2xl shadow-sm border border-slate-100 flex flex-col items-center">
                <span class="text-slate-500 font-semibold uppercase tracking-wider text-xs mb-2">Temperature</span>
                <div class="flex items-baseline">
                    <span id="tempDisplay" class="text-6xl font-black text-slate-800">--</span>
                    <span id="tempUnitLabel" class="text-2xl font-bold text-slate-400 ml-1">°F</span>
                </div>
            </div>
            <div class="metric-card bg-white p-8 rounded-2xl shadow-sm border border-slate-100 flex flex-col items-center">
                <span class="text-slate-500 font-semibold uppercase tracking-wider text-xs mb-2">Humidity</span>
                <div class="flex items-baseline">
                    <span id="humDisplay" class="text-6xl font-black text-slate-800">--</span>
                    <span class="text-2xl font-bold text-slate-400 ml-1">%</span>
                </div>
            </div>
        </div>

        <!-- Chart -->
        <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100">
            <h2 class="text-lg font-bold text-slate-700 mb-4">Live History</h2>
            <div class="relative h-[350px]">
                <canvas id="iotChart"></canvas>
            </div>
        </div>

        <footer class="mt-8 text-center text-slate-400 text-sm">
            Last update: <span id="lastUpdate">Never</span>
        </footer>
    </div>

    <script>
        // Configuration
        const MQTT_CONFIG = {
            host: "0123456789abcdef.s1.eu.hivemq.cloud",
            port: 8884,
            path: "/mqtt",
            user: "dashboard",
            pass: "password123",
            topic: "/code/coffee"
        };

        let useFahrenheit = true;
        let lastTempRawF = null;
        const maxDataPoints = 30;
        const history = {
            labels: [],
            tempRawF: [], // Store raw data in F
            hum: []
        };

        // Initialize Chart
        const ctx = document.getElementById('iotChart').getContext('2d');
        const chart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: history.labels,
                datasets: [
                    {
                        label: 'Temperature',
                        borderColor: '#ef4444',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        data: [], // Will be populated by formatted data
                        tension: 0.4,
                        yAxisID: 'y'
                    },
                    {
                        label: 'Humidity (%)',
                        borderColor: '#3b82f6',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        data: history.hum,
                        tension: 0.4,
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: { grid: { display: false } },
                    y: { 
                        type: 'linear', 
                        display: true, 
                        position: 'left',
                        title: { display: true, text: 'Temp' }
                    },
                    y1: { 
                        type: 'linear', 
                        display: true, 
                        position: 'right',
                        grid: { drawOnChartArea: false },
                        title: { display: true, text: 'Humidity %' },
                        min: 0,
                        max: 100
                    }
                },
                plugins: {
                    legend: { position: 'top' }
                }
            }
        });

        // MQTT Client Setup
        const clientId = "client_" + Math.random().toString(16).substring(2, 8);
        const client = new Paho.MQTT.Client(MQTT_CONFIG.host, MQTT_CONFIG.port, MQTT_CONFIG.path, clientId);

        client.onConnectionLost = (responseObject) => {
            $("#statusBox").text("Connection Lost. Retrying...").removeClass("bg-green-50 text-green-700").addClass("bg-red-50 text-red-700");
            setTimeout(connect, 5000);
        };

        client.onMessageArrived = (message) => {
            try {
                const data = JSON.parse(message.payloadString);
                processData(data);
            } catch (e) {
                console.error("Failed to parse JSON:", e);
            }
        };

        function connect() {
            client.connect({
                useSSL: true,
                userName: MQTT_CONFIG.user,
                password: MQTT_CONFIG.pass,
                onSuccess: () => {
                    $("#statusBox").text("Connected to HiveMQ").removeClass("bg-amber-50 text-amber-700").addClass("bg-green-50 text-green-700 border-green-200");
                    client.subscribe(MQTT_CONFIG.topic);
                },
                onFailure: (err) => {
                    $("#statusBox").text("Connection Failed: " + err.errorMessage).addClass("bg-red-50 text-red-700 border-red-200");
                }
            });
        }

        // Conversion: F to C
        function convertFtoC(f) {
            return (f - 32) * 5/9;
        }

        function processData(data) {
            const timeLabel = new Date(data.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
            lastTempRawF = data.temperature; // Raw data is F
            
            updateUI(lastTempRawF, data.humidity, timeLabel);
            updateChart(lastTempRawF, data.humidity, timeLabel);
        }

        function updateUI(tempF, hum, time) {
            const displayValue = useFahrenheit ? tempF : convertFtoC(tempF);
            $("#tempDisplay").text(displayValue.toFixed(1));
            $("#humDisplay").text(hum.toFixed(1));
            $("#lastUpdate").text(time);
        }

        function updateChart(tempF, hum, time) {
            history.labels.push(time);
            history.tempRawF.push(tempF);
            history.hum.push(hum);

            if (history.labels.length > maxDataPoints) {
                history.labels.shift();
                history.tempRawF.shift();
                history.hum.shift();
            }

            refreshChartData();
        }

        function refreshChartData() {
            // Re-map temperature display values based on current unit
            chart.data.datasets[0].data = history.tempRawF.map(f => useFahrenheit ? f : convertFtoC(f));
            chart.options.scales.y.title.text = useFahrenheit ? 'Temp (°F)' : 'Temp (°C)';
            chart.update('none');
        }

        // Unit Toggles
        $("#btnCelsius").click(() => {
            useFahrenheit = false;
            $("#btnCelsius").addClass("bg-white shadow-sm text-blue-600");
            $("#btnFahrenheit").removeClass("bg-white shadow-sm text-blue-600");
            $("#tempUnitLabel").text("°C");
            if (lastTempRawF !== null) {
                $("#tempDisplay").text(convertFtoC(lastTempRawF).toFixed(1));
            }
            refreshChartData();
        });

        $("#btnFahrenheit").click(() => {
            useFahrenheit = true;
            $("#btnFahrenheit").addClass("bg-white shadow-sm text-blue-600");
            $("#btnCelsius").removeClass("bg-white shadow-sm text-blue-600");
            $("#tempUnitLabel").text("°F");
            if (lastTempRawF !== null) {
                $("#tempDisplay").text(lastTempRawF.toFixed(1));
            }
            refreshChartData();
        });

        // Start
        $(document).ready(connect);
    </script>
</body>
</html>

That’s A Wrap

You made it to the end! If you want to keep it going, be sure to join Tech TLH on Discord and keep up with future Code and Coffee TLH events!