/* This is a sample template program for ESP32 connecting to AWS IoT over MQTT to make distributed machine device for group project of Machine design and mechanial design in FabAcademy 2020 (students at Fablab Kamakura and Kannai). As this code contains certification information, PLEASE DO NOT UPLOAD THIS SOURCE CODE to ANY SHARABLE PLACE DIRECTLY(including FabAcademy page). If you need to upload this to sharable place, PLEASE MAKE SURE YOU DELETE VALUES OF rootCA, certificate and privateKey CHARACTORS. For preparation, please find PubSubClient.h in youf local library and chhange #define MQTT_MAX_PACKET_SIZE 128 to 512. For using this, please update as follows. 1) Set your ssid and password 2) Configure your topic (or for your use to publish/receive message) 3) Specify your topic name to subscribe in connectAWSIoT() 4) Write your logic on receiving message in mqttCallback() 5) Write your logic for publishing message in mqttLoop() */ #include #include #include #include #include // pin assignment for LED blink const int ledPin = 13; //#define ledPin 13 #define DCMotor 25 //for barduino //#define button1 32 //for barduino //#define button2 33 //for barduino // 1) set your ssid and password ---------- char *ssid = "your_wifi_ssid"; char *password = "your_wifi_password"; // 1) end --------------------------------- // AWS_IOT endpoint setting (fixed) const char *endpoint = "a2toz7cb5zl4er-ats.iot.ap-northeast-1.amazonaws.com"; const int port = 8883; //char deviceId[4]; // random device ID in 4 digit hexadecimal (max: ffff) byte mac_addr[6]; char deviceId[20]; // 2) configure your topic (or for your use to connect to other people) ----- // Topic name needs to be format in "fa2020jp/topic[*]" // Topic for publishing (if you do not need to publish, you do not need pubTopic. //char *pubTopic0 = "fa2020jp/topic0"; //char *pubTopic1 = "fa2020jp/topic1"; // Topic for subscribing char *subTopic0 = "fa2020jp/topic0"; char *subTopic4 = "fa2020jp/topic4"; // 2) end ----------------------------------------------------------- const char* rootCA = "-----BEGIN CERTIFICATE-----\n" \ *** //need to put own rootCA downloaded from AWS (reference: https://recipe.kc-cloud.jp/archives/9612) "-----END CERTIFICATE-----\n"; const char* certificate = "-----BEGIN CERTIFICATE-----\n" \ *** //need to put own certificate generated by AWS "-----END CERTIFICATE-----\n"; const char* privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" \ *** //need to put own privateKey generated by AWS "-----END RSA PRIVATE KEY-----\n"; WiFiClientSecure httpsClient; PubSubClient mqttClient(httpsClient); long randomNumber; //for stepper motor #include const int stepsPerRevolution = 1000; Stepper myStepper(stepsPerRevolution, 12, 14, 27, 26); void setup() { //for stepper motor myStepper.setSpeed(30); //middle speed Serial.begin(115200); pinMode(ledPin, OUTPUT); pinMode(DCMotor,OUTPUT); // Start WiFi connection Serial.println("Connecting to "); Serial.print(ssid); WiFi.begin(ssid, password); // wait until WiFi connected while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("\nWifi Connected."); // Configure certification and MQTT Client httpsClient.setCACert(rootCA); httpsClient.setCertificate(certificate); httpsClient.setPrivateKey(privateKey); mqttClient.setServer(endpoint, port); mqttClient.setCallback(mqttCallback); // initialize the random number generator with a fairly random input // randomSeed(analogRead(0)); // Set device Id from Mac Address WiFi.macAddress(mac_addr); sprintf(deviceId, "%02X:%02X:%02X:%02X:%02X:%02X", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); connectAWSIoT(); } void connectAWSIoT() { while (!mqttClient.connected()) { // generate device ID in 4 digit hexadecimal (max: ffff) // generate random decimal max 65536 and convert it to hexadecimal format // if device ID is dupulicated with the other device, re-generate device ID. // randomNumber = random(65536); // ltoa(randomNumber, deviceId, 16); if (mqttClient.connect(deviceId)) { Serial.print("mqtt Connected - deviceId: "); Serial.println(deviceId); // QoS 0 is sending message only 1 time (the fastest) // QoS 1 is returning puback to publisher after send message successfully // QoS 2 is sending message only 1 time with validation (the slowest) // AWS IoT only allows QoS 0 or 1. int qos = 0; // 3) Specify your topic name to subscribe ----------- mqttClient.subscribe(subTopic0, qos); // 3) end -------------------------------------------- Serial.println("Subscribed."); } else { Serial.print("mqttClient.connect() Failed - deviceId:"); Serial.println(randomNumber); Serial.print("Error state="); Serial.println(mqttClient.state()); // Wait every 5 seconds until connect to MQTT broker delay(5000); } } } long messageSentAt = 0; int dummyValue = 0; int dummyValue1 = 0; char pubMessage0[256]; char pubMessage1[256]; void mqttCallback (char* topic, byte* payload, unsigned int length) { DynamicJsonDocument doc(256); // Write serial monitor Serial.print("Received. topic="); Serial.println(topic); // deserialize DeserializationError error = deserializeJson(doc, payload); if (error) { Serial.print("deserializeJson() failed with code "); Serial.println(error.c_str()); return; } // 4) Write your logic on received message ----------------- // blink LED if(doc["seq"].as()){ // digitalWrite(ledPin, HIGH); // //stepper motor // Serial.println("clockwise"); // myStepper.step(stepsPerRevolution); // } analogWrite(DCMotor,250); //70,72補助ありで回転開始、73自力スタート delay(950); analogWrite(DCMotor,0); delay(80); } // int i; // for(i=255;i>=0;i--/2){ // analogWrite(DCMotor,i); // delay(10); // } // for(i=0;i<=255;i++/2){ // Serial.println(i); // analogWrite(DCMotor,i); // delay(10); // } // dump Json in readable format serializeJsonPretty(doc, Serial); Serial.println(); // parse Json (retrieve int value from for each track) // Serial.print("track1: "); // Serial.println(doc["t1"].as()); // Serial.print("track2: "); // Serial.println(doc["t2"].as()); // Serial.print("track3: "); // Serial.println(doc["t3"].as()); // Serial.print("track4: "); // Serial.println(doc["t4"].as()); // Serial.print("track5: "); // Serial.println(doc["t5"].as()); // wait for blink LED delay(200); digitalWrite(ledPin, LOW); // 4) end ------------------------------------------------- } void mqttLoop() { if (!mqttClient.connected()) { connectAWSIoT(); } mqttClient.loop(); // // 5) ----- Write your logic for publishing message from here ----- // // (If you are not pubishing anything, you can delete following code) // // // In this case, send message every 5 seconds. // long now = millis(); // if (now - messageSentAt > 3000) { // messageSentAt = now; // // // increment dummyValue // dummyValue1 = dummyValue++; // // // It looks good to declare JsonDocument in local scope // DynamicJsonDocument doc0(256); // DynamicJsonDocument doc1(256); // // // edit data for topic1 // doc0["t1"]=dummyValue1; // track1 for topic0 // doc0["t2"]=dummyValue++; // track2 for topci0 // doc0["t3"]=0; // track2 for topci0 // doc0["t4"]=1; // track2 for topci0 // doc0["t5"]=2; // track5 for topci0 // // // edt data for topic2 // doc1["t1"]=dummyValue1; // track1 for topic1: same note (at the same time) with doc1(topic1) // doc1["t2"]=dummyValue++; // track2 for topic1 // doc1["t3"]=11; // off // track3 for topic1 // doc1["t4"]=12; // on // track4 for topic1 // doc1["t5"]=13; // track5 for topci1 // // // serialize Json object to message in byte charactors // serializeJson(doc0, pubMessage0); // serializeJson(doc1, pubMessage1); // // Serial.print("Publishing message to topic0 "); // Serial.println(pubTopic0); // Serial.println(pubMessage0); // Serial.print("Publishing message to topic1 "); // Serial.println(pubTopic1); // Serial.println(pubMessage1); // // // Publish message to topic // mqttClient.publish(pubTopic0, pubMessage0); // mqttClient.publish(pubTopic1, pubMessage1); // Serial.println("Published."); // } // // 5) end--------------------------------------------------- } void loop() { mqttLoop(); // if((digitalRead(button1) == LOW) && (digitalRead(button2) != LOW)){ // // step one revolution in one direction: // Serial.println("clockwise"); // myStepper.step(stepsPerRevolution); // } // // if((digitalRead(button1) != LOW) && (digitalRead(button2) == LOW)){ // Serial.println("counterclockwise"); // myStepper.step(-stepsPerRevolution); // } // // if((digitalRead(button1) == LOW) && (digitalRead(button2) == LOW)){ // Serial.println("around the world"); // myStepper.step(200); // } }