// Write on Serial Terminal, contoh data dari Display
// STX1,RB30,3305ETX
// STX0,R10,0000,R12,0600,W81,3107,R92,20000000,R93,0489,R94,0585,R95,A934,RA4,0274,RA5,0000,RA6,0000,RA7,0082,RA8,0084,RB0,0003,RB1,0581,RB7,0000,1FF3ETX
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#define topicpub "v1/devices/me/telemetry"
#define subtopic "v1/devices/me/rpc/request/+"
#define re 2 // Receive Enable --> Active LOW
#define de 3 // Transmitt Enable -- Active HIGH
#define RXPIN 4 //RX-RO Pin
#define TXPIN 5 //TX - DI Pin
#define button 19 // Push button for testing
const byte numChars = 200;
char receivedChars[numChars];
char tempChars[numChars];
byte stx [] = {0x02};
byte etx [] = {0x03};
boolean newData = false;
boolean newSend = false;
boolean recvFromDisplay = false;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// const char* ssid = "Bonjour"; // Enter your WiFi name
// const char* password = "bbbbbbbb"; // Enter WiFi password
const char* mqttServer = "www.teismksuryacipta.com";
const int mqttPort = 1883;
const char* mqttUser = "basic"; //TOKEN
const char* mqttPassword = "";
const char* clientId = "basic";
char msg[300];
float temperature, humidity;
unsigned long waktu_now;
unsigned long interval = 20000; //delay pengiriman
/* ------------------- Variables --------------------*/
float sp_temp, amb_temp, chamb_temp, chamb_temp_ctrl, comp_op, offset_val;
String err_status, diff_temp, ctrl_state;
int inv_freq, fan_pwm_i, fan_freq_i, fan_freq_c, def_count;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
Serial.println("<Ready>");
pinMode(button, INPUT_PULLUP);
pinMode(re, OUTPUT);
pinMode(de, OUTPUT);
setMode(false); //false = receive mode, true = transmitt mode
Serial1.begin(62500, SERIAL_8N1, RXPIN, TXPIN);
// Serial2.begin(115200, SERIAL_8N1, RXPIN, TXPIN);
// Serial2.begin(115200);
setup_wifi();
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
}
void setup_wifi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
}
void reconnect() {
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect(clientId, mqttUser, mqttPassword )) {
Serial.println("connected");
client.subscribe(subtopic);
}
else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(subtopic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
msg[i] = (char)payload[i];
}
do_action(msg);
}
void loop()
{
if (WiFi.status() != WL_CONNECTED) {
setup_wifi();
}
if (WiFi.status() == WL_CONNECTED && !client.connected()) {
reconnect();
}
client.loop();
if (millis() >= waktu_now + interval)
{
waktu_now = millis();
sendData();
}
recvWithStartEndMarkers();
if (newData == true)
{
strcpy(tempChars, receivedChars);
showNewData();
parseData(tempChars);
newData = false;
}
}
void sendData() {
const size_t CAPACITY = JSON_OBJECT_SIZE(13);
StaticJsonDocument<CAPACITY> doc;
doc["sp"] = sp_temp;
doc["at"] = amb_temp;
doc["ct"] = chamb_temp;
doc["ct_ctrl"] = chamb_temp_ctrl;
doc["com_op"] = comp_op;
doc["inv_f"] = inv_freq;
doc["if_p"] = fan_pwm_i;
doc["if_f"] = fan_freq_i;
doc["cf_f"] = fan_freq_c;
doc["def_c"] = def_count;
doc["err_s"] = err_status;
doc["dif_temp"] = diff_temp;
// doc["control_state"] = ctrl_state;
char JSONmessageBuffer[256];
serializeJson(doc, JSONmessageBuffer, sizeof(JSONmessageBuffer));
Serial.println(JSONmessageBuffer);
client.publish(topicpub, JSONmessageBuffer);
Serial.println("Data Sent!");
}
void do_action(const char* miseji) {
StaticJsonDocument<200> doc;
DeserializationError err = deserializeJson(doc, miseji);
if (err) {
Serial.print(F("deserializeJson() failed with code "));
Serial.println(err.f_str());
}
else
{
Serial.println("Belum di set action");
}
}
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = 'S';
char endMarker = 'E';
// byte startMarker = 0x02;
// byte endMarker = 0x03;
char rc;
if (Serial.available() > 0) { //change to ser. kalo mau pake RS485
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
Serial.print(rc);
if (recvInProgress == true) {
if (rc != endMarker) {
if (rc == 'T' or rc == 'X') continue;
else
{
receivedChars[ndx] = rc;
ndx++;
}
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
}
}
else if (rc == startMarker) {
recvInProgress = true;
}
}
}
}
void showNewData() {
if (newData == true) {
Serial.println("");
Serial.print("Parsed Data : ");
Serial.println(receivedChars);
// newData = false;
newSend = false;
Serial.println("");
}
}
void parseData(char* data) {
char* token;
char* delimiter = ",";
String command;
// Parsing the first token
token = strtok(data, delimiter);
command = String(token);
Serial.print("Command : ");
Serial.println(command);
if (command == "0")
{
recvFromDisplay = true;
Serial.println("Data from Display!");
}
else
{
recvFromDisplay = false;
Serial.println("data from Mainboard!");
}
// Iterate through the tokens
while (token != NULL && recvFromDisplay == true) {
// Print the parsed token
// Serial.println(token);
// Set Point Temperature
if (strcmp(token, "R12") == 0)
{
Serial.print("Set Point Temp : ");
token = strtok(NULL, delimiter);
// float value = atof(token) / 100;
sp_temp = atof(token) / 100;
Serial.println(sp_temp);
}
// Ambient Temp. on Display
if (strcmp(token, "W81") == 0)
{
Serial.print("Ambient Temp : ");
token = strtok(NULL, delimiter);
amb_temp = atof(token) / 100;
Serial.println(amb_temp);
}
// Error Status (Binary)
if (strcmp(token, "R92") == 0)
{
Serial.print("Error Status. : ");
token = strtok(NULL, delimiter);
err_status = String(token);
Serial.println(err_status);
}
// Chamber Temp.
if (strcmp(token, "R93") == 0)
{
Serial.print("Chamber Temp. : ");
token = strtok(NULL, delimiter);
chamb_temp = atof(token) / 100;
Serial.println(chamb_temp);
}
// Chamber Temp. On Control
if (strcmp(token, "R94") == 0)
{
Serial.print("Chamber Temp. on Control : ");
token = strtok(NULL, delimiter);
chamb_temp_ctrl = atof(token) / 100;
Serial.println(chamb_temp_ctrl);
}
// Differential Temperature, not yet calculated
if (strcmp(token, "R95") == 0)
{
Serial.print("Differential Temp. : ");
token = strtok(NULL, delimiter);
// float value = atof(token) / 100;
diff_temp = String (token);
Serial.println(diff_temp);
}
// Control State, binary, not yet calculated
if (strcmp(token, "RA4") == 0)
{
Serial.print("Control State : ");
token = strtok(NULL, delimiter);
// float value = atof(token) / 100;
ctrl_state = String (token);
Serial.println(ctrl_state);
}
// Inverter Control Frequency
if (strcmp(token, "RA5") == 0)
{
Serial.print("Inverter Frequency : ");
token = strtok(NULL, delimiter);
inv_freq = atoi(token);
// String value = String (token);
Serial.println(inv_freq);
}
// Internal Fan PWM (0 - 100)
if (strcmp(token, "RA6") == 0)
{
Serial.print("Fan PWM : ");
token = strtok(NULL, delimiter);
fan_pwm_i = atoi(token);
// String value = String (token);
Serial.println(fan_pwm_i);
}
// Internal Fan Frequency (0 - 120 Hz)
if (strcmp(token, "RA7") == 0)
{
Serial.print("Fan Internal Frequency : ");
token = strtok(NULL, delimiter);
fan_freq_i = atoi(token);
// String value = String (token);
Serial.println(fan_freq_i);
}
// Fan Condenser Frequency (0 - 120 Hz)
if (strcmp(token, "RA8") == 0)
{
Serial.print("Fan Condenser Frequency : ");
token = strtok(NULL, delimiter);
fan_freq_c = atoi(token);
// String value = String (token);
Serial.println(fan_freq_c);
}
// Defrost counter (0-999)
if (strcmp(token, "RB0") == 0)
{
Serial.print("Defrost Counter : ");
token = strtok(NULL, delimiter);
def_count = atoi(token);
// String value = String (token);
Serial.println(def_count);
}
// Compressor Operation (0 (0%) - 1000 (100%))
if (strcmp(token, "RB1") == 0)
{
Serial.print("Compressor Operation : ");
token = strtok(NULL, delimiter);
comp_op = atof(token) / 10;
// String value = String (token);
Serial.println(comp_op);
}
//Offset Correction Value (-999 (-9,99) - 999 (9,99))
if (strcmp(token, "RB7") == 0)
{
Serial.print("Offset Value : ");
token = strtok(NULL, delimiter);
offset_val = atof(token) / 10;
// String value = String (token);
Serial.println(offset_val);
}
// Get the next token
token = strtok(NULL, delimiter);
}
}
void sendSerialData(String data) {
char STX = 0x02; // Start of Text
char ETX = 0x03; // End of Text
Serial1.write(STX);
for (size_t i = 0; i < data.length(); i++) {
Serial1.write(data.charAt(i));
}
Serial1.write(ETX);
}
void setMode(bool mode) {
digitalWrite(re, mode); //Active LOW
digitalWrite(de, mode); // Active High
}