Home
JAQForum Ver 24.01
Log In or Join  
Active Topics
Local Time 19:23 09 May 2025 Privacy Policy
Jump to

Notice. New forum software under development. It's going to miss a few functions and look a bit ugly for a while, but I'm working on it full time now as the old forum was too unstable. Couple days, all good. If you notice any issues, please contact me.

Forum Index : Microcontroller and PC projects : CMM2 sending prompts to Grok/Copilot/ChatGPT

Author Message
ManiB
Senior Member

Joined: 12/10/2019
Location: Germany
Posts: 106
Posted: 11:13pm 09 Mar 2025
Copy link to clipboard 
Print this post

Hello, I had the idea of using my CMM2 to send prompt inputs via the ESP-01 to an ESP gateway, which forwards the prompt to an AI and sends the response back to the CMM2.

I have attached the MMBasic programme and the C# programme for the ESP gateway below. The communication does not necessarily have to run via an ESP-01 module, it could also work via the serial connection.

But unfortunately I couldn't test it because API queries to the AI have to be paid for.

Perhaps one of you has the ability to test this.


MMBasic-Testprogramm:
' CMM2Grok: A simple MMBasic program to send prompts to Grok via ESP-01 Telnet
' Open the serial port COM2 with 115200 baud
open "COM2:115200" as 4

' Main program loop
do
 ' Display prompt and read user input
 input "CMM2Grok - Enter your prompt (type QUIT to exit): ", prompt$
 
 ' Check if the user entered "QUIT"
 if ucase$(prompt$) <> "QUIT" then
   ' Send the prompt to the ESP-01
   print #4, prompt$
   
   ' Wait for a response up to 5 seconds
   startTime = timer  ' Get the current timer value in milliseconds
   endTime = 5000     ' Set 5 seconds
   response$ = ""     ' Initialize response string
   do while (timer - startTime) < endTime  ' Loop for 5 seconds
     if loc(4) > 0 then
       endTime = 200
       response$ = response$ + input$(loc(4), 4)  ' Append incoming data
     endif
     pause 10  ' Short pause to avoid high CPU usage
   loop
   
   ' Display the response if any was received
   if response$ <> "" then
     print "Response: "; response$
   else
     print "No response received within 5 seconds"
   endif
 else
   ' Exit the program when "QUIT" is entered
   print "CMM2Grok exiting..."
   exit do
 endif
loop

' Close the serial port
close #4



Visual Studio C# Console Programm:
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
//using System.Text.Json;

namespace ESPGateway
{
   /// <summary>
   /// ESP-Gateway: A simple Telnet bridge between an ESP-01 (ESP-Link) and the Grok API.
   /// Receives data from a CMM2 via Telnet, sends it to Grok, and forwards the response back.
   /// Released for the TheBackShed Forum, no external dependencies.
   /// Compatible with .NET Framework (e.g., 4.8).
   /// </summary>
   class Program
   {
       private static TcpClient client;
       private static NetworkStream stream;
       private static readonly string espIp = "192.168.178.100"; // IP of the ESP-01
       private static readonly int espPort = 23; // Default Telnet port
       private static readonly string grokApiUrl = "https://api.xai.com/grok"; // Hypothetical Grok API URL
       private static readonly string grokApiKey = "YOUR_API_KEY"; // Replace with your API key
       private static readonly string copilotApiUrl = "https://api.copilot.microsoft.com/v1/engines/davinci-codex/completions"; // Copilot API URL
       private static readonly string copilotApiKey = "YOUR_API_KEY"; // Replace with your API key
       private static readonly string chatGptApiUrl = "https://api.openai.com/v1/chat/completions";
       private static readonly string chatGptApiKey = "YOUR_API_KEY";
       private static readonly string ai = "ChatGPT"; // selects ai "ChatGPT", "Copilot" or "Grok"

       static void Main(string[] args)
       {
           Console.WriteLine("ESP-Gateway starting...");
           Console.WriteLine("Establishing connection to {0}:{1}", espIp, espPort);

           while (true) // Reconnection logic
           {
               try
               {
                   // Establish Telnet connection (synchronous)
                   client = new TcpClient();
                   client.Connect(espIp, espPort); // Synchronous instead of ConnectAsync
                   stream = client.GetStream();
                   Console.WriteLine("Connected to ESP-01 Telnet");

                   // Start receiving data in a separate thread
                   Task.Factory.StartNew(ReceiveData, TaskCreationOptions.LongRunning);

                   // Keep the main thread alive
                   Console.WriteLine("Press Enter to exit...");
                   Console.ReadLine();
                   break; // Exit program on user input
               }
               catch (Exception ex)
               {
                   Console.WriteLine($"Connection error: {ex.Message}");
                   Console.WriteLine("Reconnecting in 5 seconds...");
                   Thread.Sleep(5000); // Wait before retrying (synchronous)
               }
               finally
               {
                   stream?.Close();
                   client?.Close();
               }
           }
       }

       /// <summary>
       /// Receives data from the ESP-01 and processes it.
       /// </summary>
       static void ReceiveData()
       {
           byte[] buffer = new byte[1024];
           while (true)
           {
               try
               {
                   if (stream.DataAvailable)
                   {
                       int bytesRead = stream.Read(buffer, 0, buffer.Length); // Synchronous read
                       string data = Encoding.UTF8.GetString(buffer, 0, bytesRead).Trim();
                       Console.WriteLine($"Received from CMM2: {data}");

                       string response = "";

                       if (ai == "ChatGPT")
                       {
                           // Send data to ChatGPT (async call within sync method)
                           response = SendToChatGPT(data).GetAwaiter().GetResult();
                           Console.WriteLine($"Response from ChatGPT: {response}");
                       }
                       else if (ai == "Copilot")
                       {
                           // Send data to Copilot (async call within sync method)
                           response = SendToCopilot(data).GetAwaiter().GetResult();
                           Console.WriteLine($"Response from Copilot: {response}");
                       }
                       else if (ai == "Grok")
                       {
                           // Send data to Grok (async call within sync method)
                           response = SendToGrok(data).GetAwaiter().GetResult();
                           Console.WriteLine($"Response from Grok: {response}");
                       }
                       else
                       {
                           response = "AI_NOT_DEFINED!";
                       }

                       // Send response back to ESP-01
                       byte[] responseBytes = Encoding.UTF8.GetBytes(response + "\r\n");
                       stream.Write(responseBytes, 0, responseBytes.Length); // Synchronous write
                       stream.Flush();
                   }
                   Thread.Sleep(100); // Reduce CPU load
               }
               catch (Exception ex)
               {
                   Console.WriteLine($"Error receiving data: {ex.Message}");
                   break; // Exit loop on error (reconnection in Main)
               }
           }
       }

       /// <summary>
       /// Sends the prompt to the Grok API and returns the response.
       /// </summary>
       static async Task<string> SendToGrok(string prompt)
       {
           // Check if the API key is the placeholder, then return a dummy response
           if (string.Equals(grokApiKey, "YOUR_API_KEY"))
           {
               string dummyResponse = $"Grok says: Hello back to '{prompt}'!";
               await Task.Delay(500); // Simulate network delay
               return dummyResponse;
           }

           using (var httpClient = new HttpClient())
           {
               try
               {
                   httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {grokApiKey}");
                   var content = new StringContent(
                       $"{{\"prompt\": \"{prompt}\"}}",
                       Encoding.UTF8,
                       "application/json"
                   );

                   HttpResponseMessage response = await httpClient.PostAsync(grokApiUrl, content);
                   if (response.IsSuccessStatusCode)
                   {
                       string result = await response.Content.ReadAsStringAsync();
                       // API response parsing would go here (e.g., JSON)
                       return result; // Simplified, adjust to actual API
                   }
                   return $"API error: {response.StatusCode}";
               }
               catch (Exception ex)
               {
                   return $"API connection error: {ex.Message}";
               }
           }
       }

       /// <summary>
       /// Sends the prompt to the Copilot API and returns the response.
       /// </summary>
       static async Task<string> SendToCopilot(string prompt)
       {
           // Check if the API key is the placeholder, then return a dummy response
           if (string.Equals(copilotApiKey, "YOUR_API_KEY"))
           {
               string dummyResponse = $"Copilot says: Hello back to '{prompt}'!";
               await Task.Delay(500); // Simulate network delay
               return dummyResponse;
           }

           using (var httpClient = new HttpClient())
           {
               try
               {
                   httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {copilotApiKey}");
                   var content = new StringContent(
                       $"{{\"prompt\": \"{prompt}\", \"max_tokens\": 100}}",
                       Encoding.UTF8,
                       "application/json"
                   );

                   HttpResponseMessage response = await httpClient.PostAsync(copilotApiUrl, content);
                   if (response.IsSuccessStatusCode)
                   {
                       string result = await response.Content.ReadAsStringAsync();
                       // API response parsing would go here (e.g., JSON)
                       return result; // Simplified, adjust to actual API
                   }
                   return $"API error: {response.StatusCode}";
               }
               catch (Exception ex)
               {
                   return $"API connection error: {ex.Message}";
               }
           }
       }

       /// <summary>
       /// Sends the prompt to the ChatGPT API and returns the response.
       /// </summary>
       static async Task<string> SendToChatGPT(string prompt)
       {
           if (string.Equals(chatGptApiKey, "YOUR_API_KEY"))
           {
               await Task.Delay(500);
               return $"ChatGPT says: Hello back to '{prompt}'!";
           }

           using (var httpClient = new HttpClient())
           {
               try
               {
                   httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {chatGptApiKey}");

                   string requestBody = "{\"model\":\"gpt-4\",\"messages\":[{\"role\":\"user\",\"content\":\"" + prompt + "\"}],\"max_tokens\":200}";

                   var content = new StringContent(
                       requestBody,
                       Encoding.UTF8,
                       "application/json"
                   );

                   HttpResponseMessage response = await httpClient.PostAsync(chatGptApiUrl, content);

                   if (response.IsSuccessStatusCode)
                   {
                       string result = await response.Content.ReadAsStringAsync();
                       return result; // API-Response als String zurückgeben
                   }

                   return $"API error: {response.StatusCode}";
               }
               catch (Exception ex)
               {
                   return $"API connection error: {ex.Message}";
               }
           }
       }
   }
}

Edited 2025-03-10 09:17 by ManiB
 
Print this page


To reply to this topic, you need to log in.

The Back Shed's forum code is written, and hosted, in Australia.
© JAQ Software 2025