У меня проблема с моим кодом. Я хочу, чтобы мое значение из URL-адреса при вызове Ajax обновлялось не дважды, а только один раз. Но то, что делает код, продолжает обновлять это поле из URL-адреса и не соответствует значению от 0 до 1 в URL-адресе при вызове Ajax. Пожалуйста, посмотрите мою логику в этом коде и помогите мне улучшить мою логику. Я хочу, чтобы мое field8 = 1 обновлялось только один раз только для функции BtnOn (), поэтому, если я щелкаю дважды, не обновляя страницу, это не так, то же самое относится и к функции BtnOff (). Это сохраняет это исходное значение в его состоянии как field8 = 0. Таким образом, он не будет совпадать между field8 = 1, что делает то, что в данный момент плохо для пользователя, а также сообщение о состоянии.
<div class ="success"></div>
<div class = "warning"></div>
<div class="col-md-2 text-center">
<button id="singlebutton" name="singlebutton" class="btn btn-danger"
onclick="BtnOff();">Off</button> <br>
</div>
<!------
---->
<br/>
<div class = "col-md-2 text-center">
<button id = "singlebtn" name="singlebtn" class="btn btn-success"
onclick = "BtnOn();">On</button> <br>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var data;
function BtnOff() {
$.ajax({
url:'https://api.thingspeak.com/update api_key=D***&field8=0',
type:'GET',
data:{
type:'text'
},
success:function(response){
alert(response);
$('div.warning').html('status changed to zero').delay(1000).fadeOut();
$('#singlebutton').append(data);
return false;
}
});
//setTimeout("Subscribe()", 100);
}
// second button to unsubscribe.
function BtnOn() {
$.ajax({
url:'https://api.thingspeak.com/updateapi_key=D***&field8=1',
type:'GET',
data:{
type:'text'
},
success:function(response){
alert(response);
$('div.success').html('status changed to one').delay(1000).fadeOut();
$('#singlebtn').append(data);
return data;
}
});
var h = setTimeout("Subscribe()", 100);
clearTimeout(h);
}
</script>
<!-- Back End--->
/*
Azure IoT Hub WiFi
This sketch securely connects to an Azure IoT Hub using MQTT over WiFi.
It uses a private key stored in the ATECC508A and a self signed public
certificate for SSL/TLS authetication.
It publishes a message every 5 seconds to "devices/{deviceId}/messages/events/" topic
and subscribes to messages on the "devices/{deviceId}/messages/devicebound/#"
topic.
The circuit:
- Arduino MKR WiFi 1010 or MKR1000
This example code is in the public domain.
*/
#include <Wire.h>
#include <Arduino_MKRENV.h>
#include <SPI.h>
#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include <utility/ECCX08SelfSignedCert.h>
#include <ArduinoMqttClient.h>
#include <WiFiNINA.h> // change to #include <WiFi101.h> for MKR1000
#include "arduino_secrets.h"
/////// Enter your sensitive data in arduino_secrets.h
const char ssid[] = SECRET_SSID;
const char pass[] = SECRET_PASS;
const char broker[] = SECRET_BROKER;
String deviceId = SECRET_DEVICE_ID;
String mqttPassword = SECRET_MQTT_PASSWORD;
WiFiClient wifiClient; // Used for the TCP socket connection
BearSSLClient sslClient(wifiClient); // Used for SSL/TLS connection, integrates with ECC508
MqttClient mqttClient(sslClient);
unsigned long lastMillis = 0;
unsigned long postNumbers = 0;
float temperature, humidity, pressure, illuminance, uva, uvb, uvIndex;
String jsonString = "";
void setup()
{
Serial.begin(9600);
while (!Serial);
if (!ENV.begin())
{
Serial.println("Failed to initialize MKR ENV shield!");
while (1);
}
if (!ECCX08.begin())
{
Serial.println("No ECCX08 present!");
while (1);
}
// reconstruct the self signed cert
ECCX08SelfSignedCert.beginReconstruction(0, 8);
ECCX08SelfSignedCert.setCommonName(ECCX08.serialNumber());
ECCX08SelfSignedCert.endReconstruction();
// Set a callback to get the current time
// used to validate the servers certificate
ArduinoBearSSL.onGetTime(getTime);
// Set the ECCX08 slot to use for the private key
// and the accompanying public certificate for it
sslClient.setEccSlot(0, ECCX08SelfSignedCert.bytes(), ECCX08SelfSignedCert.length());
// Set the client id used for MQTT as the device id
mqttClient.setId(deviceId);
// Set the username to "<broker>/<device id>/api-version=2018-06-30" and empty password
String username;
username += broker;
username += "/";
username += deviceId;
username += "/api-version=2018-06-30";
mqttClient.setUsernamePassword("MKR1010", mqttPassword);
// Set the message callback, this function is
// called when the MQTTClient receives a message
mqttClient.onMessage(onMessageReceived);
}
void loop()
{
if (WiFi.status() != WL_CONNECTED)
{
connectWiFi();
}
if (!mqttClient.connected())
{
// MQTT client is disconnected, connect
connectMQTT();
}
// poll for new MQTT messages and send keep alives
mqttClient.poll();
// publish a message roughly every 60 seconds.
if (millis() - lastMillis > 60000)
{
lastMillis = millis();
publishMessage();
readEnvSensors();
}
}
void readEnvSensors()
{
// read all the sensor values
temperature = ENV.readTemperature();
humidity = ENV.readHumidity();
pressure = ENV.readPressure();
illuminance = ENV.readIlluminance();
uva = ENV.readUVA();
uvb = ENV.readUVB();
uvIndex = ENV.readUVIndex();
postNumbers++;
Serial.print("Post number: ");
Serial.println(postNumbers);
// print each of the sensor values
Serial.print("Temperature = ");
Serial.print(temperature);
Serial.println(" °C");
Serial.print("Humidity = ");
Serial.print(humidity);
Serial.println(" %");
Serial.print("Pressure = ");
Serial.print(pressure);
Serial.println(" kPa");
Serial.print("Illuminance = ");
Serial.print(illuminance);
Serial.println(" lx");
Serial.print("UVA = ");
Serial.println(uva);
Serial.print("UVB = ");
Serial.println(uvb);
Serial.print("UV Index = ");
Serial.println(uvIndex);
}
unsigned long getTime()
{
// get the current time from the WiFi module
return WiFi.getTime();
}
void connectWiFi()
{
Serial.print("Attempting to connect to SSID: ");
Serial.print(ssid);
Serial.print(" ");
while (WiFi.begin(ssid, pass) != WL_CONNECTED)
{
// failed, retry
Serial.print(".");
delay(5000);
}
Serial.println();
Serial.println("You're connected to the network");
Serial.println();
}
void connectMQTT()
{
Serial.print("Attempting to MQTT broker: ");
Serial.print(broker);
Serial.println(" ");
while (!mqttClient.connect(broker, 8883))
{
// failed, retry
Serial.print(".");
Serial.println(mqttClient.connectError());
delay(5000);
}
Serial.println();
Serial.println("You're connected to the MQTT broker");
Serial.println();
// subscribe to a topic
mqttClient.subscribe("channels/899906/subscribe/fields/field8/F35GLOFJ8L99D0OM");
}
void publishMessage()
{
Serial.println("Publishing message");
// send message, the Print interface can be used to set the message contents
mqttClient.beginMessage("channels/899906/publish/DLQ0F7W5FGVO1I9Q");
String dataString = String("field1=") + String(temperature) + String("&field2=") + String(illuminance);
mqttClient.print(dataString);
mqttClient.endMessage();
/*
// send message, the Print interface can be used to set the message contents
mqttClient.beginMessage("channels/899906/publish/fields/field1/DLQ0F7W5FGVO1I9Q");
mqttClient.print(temperature);
mqttClient.endMessage();
mqttClient.beginMessage("channels/899906/publish/fields/field2/DLQ0F7W5FGVO1I9Q");
mqttClient.print(illuminance);
mqttClient.endMessage();
*/
}
void onMessageReceived(int messageSize)
{
// we received a message, print out the topic and contents
Serial.print("Received a message with topic '");
Serial.print(mqttClient.messageTopic());
Serial.print("', length ");
Serial.print(messageSize);
Serial.println(" bytes:");
// use the Stream interface to print the contents
while (mqttClient.available())
{
Serial.print((char)mqttClient.read());
}
Serial.println();
Serial.println();
}