Machine ID:
%s
Copy and save the machine ID because you will need it to control the device.
", machineId); 315 | WiFiManagerParameter custom_text_machine_id(htmlMachineId); 316 | 317 | //WiFiManager 318 | //Local intialization. Once its business is done, there is no need to keep it around 319 | WiFiManager wifiManager; 320 | 321 | //set config save notify callback 322 | wifiManager.setSaveConfigCallback(saveConfigCallback); 323 | 324 | //add all your parameters here 325 | wifiManager.addParameter(&custom_mqtt_server); 326 | wifiManager.addParameter(&custom_mqtt_port); 327 | wifiManager.addParameter(&custom_workgroup); 328 | wifiManager.addParameter(&custom_mqtt_user); 329 | wifiManager.addParameter(&custom_mqtt_pass); 330 | wifiManager.addParameter(&custom_text_machine_id); 331 | #ifdef HOME_ASSISTANT_DISCOVERY 332 | wifiManager.addParameter(&custom_mqtt_ha_name); 333 | #endif 334 | 335 | //reset settings - for testing 336 | //wifiManager.resetSettings(); 337 | 338 | //set minimu quality of signal so it ignores AP's under that quality 339 | //defaults to 8% 340 | //wifiManager.setMinimumSignalQuality(); 341 | 342 | //sets timeout until configuration portal gets turned off 343 | //useful to make it all retry or go to sleep 344 | //in seconds 345 | wifiManager.setTimeout(300); 346 | digitalWrite(pinAlarm, HIGH); 347 | 348 | //fetches ssid and pass and tries to connect 349 | //if it does not connect it starts an access point 350 | //and goes into a blocking loop awaiting configuration 351 | wifiManager.setAPCallback(apWiFiCallback); 352 | // Append the last 5 character of the machine id to the access point name 353 | String apId(machineId); 354 | apId = apId.substring(apId.length() - 5); 355 | String accessPointName = "ANAVI Light Controller " + apId; 356 | if (!wifiManager.autoConnect(accessPointName.c_str(), "")) 357 | { 358 | digitalWrite(pinAlarm, LOW); 359 | Serial.println("failed to connect and hit timeout"); 360 | delay(3000); 361 | //reset and try again, or maybe put it to deep sleep 362 | ESP.reset(); 363 | delay(5000); 364 | } 365 | 366 | //if you get here you have connected to the WiFi 367 | Serial.println("connected...yeey :)"); 368 | //publish state to server as soon as possible on boot 369 | publishState(); 370 | digitalWrite(pinAlarm, LOW); 371 | 372 | //read updated parameters 373 | strcpy(mqtt_server, custom_mqtt_server.getValue()); 374 | strcpy(mqtt_port, custom_mqtt_port.getValue()); 375 | strcpy(workgroup, custom_workgroup.getValue()); 376 | strcpy(username, custom_mqtt_user.getValue()); 377 | strcpy(password, custom_mqtt_pass.getValue()); 378 | #ifdef HOME_ASSISTANT_DISCOVERY 379 | strcpy(ha_name, custom_mqtt_ha_name.getValue()); 380 | #endif 381 | 382 | //save the custom parameters to FS 383 | if (shouldSaveConfig) 384 | { 385 | Serial.println("saving config"); 386 | DynamicJsonDocument json(1024); 387 | json["mqtt_server"] = mqtt_server; 388 | json["mqtt_port"] = mqtt_port; 389 | json["workgroup"] = workgroup; 390 | json["username"] = username; 391 | json["password"] = password; 392 | #ifdef HOME_ASSISTANT_DISCOVERY 393 | json["ha_name"] = ha_name; 394 | #endif 395 | 396 | File configFile = SPIFFS.open("/config.json", "w"); 397 | if (!configFile) 398 | { 399 | Serial.println("failed to open config file for writing"); 400 | } 401 | 402 | serializeJson(json, Serial); 403 | serializeJson(json, configFile); 404 | configFile.close(); 405 | //end save 406 | } 407 | 408 | Serial.println("local ip"); 409 | Serial.println(WiFi.localIP()); 410 | 411 | ArduinoOTA.onStart(otaStarted); 412 | ArduinoOTA.onEnd(otaFinished); 413 | ArduinoOTA.onProgress(otaProgress); 414 | ArduinoOTA.onError(otaError); 415 | ArduinoOTA.begin(); 416 | 417 | // Sensors 418 | htu.begin(); 419 | 420 | // MQTT 421 | Serial.print("MQTT Server: "); 422 | Serial.println(mqtt_server); 423 | Serial.print("MQTT Port: "); 424 | Serial.println(mqtt_port); 425 | // Print MQTT Username 426 | Serial.print("MQTT Username: "); 427 | Serial.println(username); 428 | // Hide password from the log and show * instead 429 | char hiddenpass[20] = ""; 430 | for (size_t charP=0; charP < strlen(password); charP++) 431 | { 432 | hiddenpass[charP] = '*'; 433 | } 434 | hiddenpass[strlen(password)] = '\0'; 435 | Serial.print("MQTT Password: "); 436 | Serial.println(hiddenpass); 437 | 438 | #ifdef HOME_ASSISTANT_DISCOVERY 439 | Serial.print("Home Assistant sensor name: "); 440 | Serial.println(ha_name); 441 | #endif 442 | 443 | const int mqttPort = atoi(mqtt_port); 444 | mqttClient.setServer(mqtt_server, mqttPort); 445 | mqttClient.setCallback(mqttCallback); 446 | 447 | mqttReconnect(); 448 | 449 | Serial.println(""); 450 | Serial.println("-----"); 451 | Serial.print("Machine ID: "); 452 | Serial.println(machineId); 453 | Serial.println("-----"); 454 | Serial.println(""); 455 | 456 | setupADPS9960(); 457 | } 458 | 459 | void setCurrentColorWhite() 460 | { 461 | currentRed = 255; 462 | currentGreen = 255; 463 | currentBlue = 255; 464 | brightnessLevel = 255; 465 | } 466 | 467 | void setupADPS9960() 468 | { 469 | if(apds.begin()) 470 | { 471 | //gesture mode will be entered once proximity mode senses something close 472 | apds.enableProximity(true); 473 | apds.enableGesture(true); 474 | } 475 | } 476 | 477 | void waitForFactoryReset() 478 | { 479 | Serial.println("Press button within 2 seconds for factory reset..."); 480 | for (int iter = 0; iter < 20; iter++) 481 | { 482 | digitalWrite(pinAlarm, HIGH); 483 | delay(50); 484 | if (false == digitalRead(pinButton)) 485 | { 486 | factoryReset(); 487 | return; 488 | } 489 | digitalWrite(pinAlarm, LOW); 490 | delay(50); 491 | if (false == digitalRead(pinButton)) 492 | { 493 | factoryReset(); 494 | return; 495 | } 496 | } 497 | } 498 | 499 | void factoryReset() 500 | { 501 | if (false == digitalRead(pinButton)) 502 | { 503 | Serial.println("Hold the button to reset to factory defaults..."); 504 | bool cancel = false; 505 | for (int iter=0; iter<30; iter++) 506 | { 507 | digitalWrite(pinAlarm, HIGH); 508 | delay(100); 509 | if (true == digitalRead(pinButton)) 510 | { 511 | cancel = true; 512 | break; 513 | } 514 | digitalWrite(pinAlarm, LOW); 515 | delay(100); 516 | if (true == digitalRead(pinButton)) 517 | { 518 | cancel = true; 519 | break; 520 | } 521 | } 522 | if (false == digitalRead(pinButton) && !cancel) 523 | { 524 | digitalWrite(pinAlarm, HIGH); 525 | Serial.println("Disconnecting..."); 526 | WiFi.disconnect(); 527 | 528 | // NOTE: the boot mode:(1,7) problem is known and only happens at the first restart after serial flashing. 529 | 530 | Serial.println("Restarting..."); 531 | // Clean the file system with configurations 532 | SPIFFS.format(); 533 | // Restart the board 534 | ESP.restart(); 535 | } 536 | else 537 | { 538 | // Cancel reset to factory defaults 539 | Serial.println("Reset to factory defaults cancelled."); 540 | digitalWrite(pinAlarm, LOW); 541 | } 542 | } 543 | } 544 | 545 | void mqttCallback(char* topic, byte* payload, unsigned int length) 546 | { 547 | // Convert received bytes to a string 548 | char text[length + 1]; 549 | snprintf(text, length + 1, "%s", payload); 550 | 551 | Serial.print("Message arrived ["); 552 | Serial.print(topic); 553 | Serial.print("] "); 554 | Serial.println(text); 555 | 556 | // Reset effects 557 | strcpy(effect, "none"); 558 | 559 | if (strcmp(topic, cmnd_power_topic) == 0) 560 | { 561 | power = strcmp(text, "ON") == 0; 562 | } 563 | else if (strcmp(topic, cmnd_color_topic) == 0) 564 | { 565 | StaticJsonDocument<200> data; 566 | deserializeJson(data, text); 567 | 568 | if (data.containsKey("color")) 569 | { 570 | const int r = data["color"]["r"]; 571 | const int g = data["color"]["g"]; 572 | const int b = data["color"]["b"]; 573 | currentRed = ((0 <= r) && (255 >= r)) ? r : 0; 574 | currentGreen = ((0 <= g) && (255 >= g)) ? g : 0; 575 | currentBlue = ((0 <= b) && (255 >= b)) ? b : 0; 576 | } 577 | else if (data.containsKey("brightness")) 578 | { 579 | const int brightness = data["brightness"]; 580 | if ( (0 <= brightness) && (255 >= brightness) ) 581 | { 582 | brightnessLevel = brightness; 583 | } 584 | } 585 | else if (data.containsKey("effect")) 586 | { 587 | if (strcmp(effect, data["effect"]) != 0) 588 | { 589 | strcpy(effect, data["effect"]); 590 | effectPos = 0; 591 | effectPreviousMillis = millis(); 592 | } 593 | 594 | } 595 | saveColors(); 596 | calculateBrightness(); 597 | if (data.containsKey("state")) 598 | { 599 | // Set variable power to true or false depending on the state 600 | power = (data["state"] == "ON"); 601 | } 602 | else if (data.containsKey("effect")) 603 | { 604 | // Turn on the power if any effect has been specified 605 | power = true; 606 | } 607 | else if (data.containsKey("brightness") || data.containsKey("color")) 608 | { 609 | // Turn on if any of the colors is greater than 0 610 | // Only if *either* color or brightness have been set. 611 | power = ( (0 < lightRed) || (0 < lightGreen) || (0 < lightBlue) ); 612 | } 613 | } 614 | 615 | saveState(); 616 | 617 | publishState(); 618 | 619 | setColorPins(); 620 | } 621 | 622 | void setColorPins() 623 | { 624 | calculateBrightness(); 625 | 626 | Serial.print("Red: "); 627 | Serial.println(lightRed); 628 | Serial.print("Green: "); 629 | Serial.println(lightGreen); 630 | Serial.print("Blue: "); 631 | Serial.println(lightBlue); 632 | Serial.print("Power: "); 633 | Serial.println(power); 634 | 635 | // Set colors of RGB LED strip 636 | if (power) 637 | { 638 | if (strcmp(effect, "switch_transition") == 0) 639 | { 640 | effectPos = 0; 641 | return; 642 | } 643 | analogWrite(pinLedRed, lightRed); 644 | analogWrite(pinLedGreen, lightGreen); 645 | analogWrite(pinLedBlue, lightBlue); 646 | } 647 | else 648 | { 649 | analogWrite(pinLedRed, 0); 650 | analogWrite(pinLedGreen, 0); 651 | analogWrite(pinLedBlue, 0); 652 | } 653 | } 654 | 655 | void saveColors() 656 | { 657 | tempRed = lightRed; 658 | tempGreen = lightGreen; 659 | tempBlue = lightBlue; 660 | } 661 | 662 | void calculateBrightness() 663 | { 664 | unsigned int maximumBrightness = 255; 665 | lightRed = (currentRed * brightnessLevel) / maximumBrightness; 666 | lightBlue = (currentBlue * brightnessLevel) / maximumBrightness; 667 | lightGreen = (currentGreen * brightnessLevel) / maximumBrightness; 668 | } 669 | 670 | void processEffects() 671 | { 672 | if (!power) 673 | { 674 | return; 675 | } 676 | 677 | if (strcmp(effect, "none") == 0) 678 | { 679 | return; 680 | } 681 | else if (strcmp(effect, "switch_transition") == 0) 682 | { 683 | if (effectPos == 256) 684 | { 685 | return; 686 | } 687 | 688 | if (lightRed > tempRed) 689 | { 690 | tempRed++; 691 | } 692 | else if (lightRed < tempRed) { 693 | tempRed--; 694 | } 695 | 696 | if (lightGreen > tempGreen) 697 | { 698 | tempGreen++; 699 | } 700 | else if (lightGreen < tempGreen) { 701 | tempGreen--; 702 | } 703 | 704 | if (lightBlue > tempBlue) 705 | { 706 | tempBlue++; 707 | } 708 | else if (lightBlue < tempBlue) { 709 | tempBlue--; 710 | } 711 | 712 | effectPos += 1; 713 | 714 | analogWrite(pinLedRed, tempRed); 715 | analogWrite(pinLedGreen, tempGreen); 716 | analogWrite(pinLedBlue, tempBlue); 717 | 718 | return; 719 | } 720 | else if (strcmp(effect, "rainbow1") == 0) 721 | { 722 | int pos = effectPos; 723 | if (pos < 256) 724 | { 725 | currentRed = pos; 726 | currentGreen = 255 - pos; 727 | currentBlue = 0; 728 | } 729 | else if (pos < 512) 730 | { 731 | currentRed = 255 - (pos - 256); 732 | currentGreen = 0; 733 | currentBlue = pos - 256; 734 | } 735 | else 736 | { 737 | currentRed = 0; 738 | currentGreen = pos - 512; 739 | currentBlue = 255 - (pos - 512); 740 | } 741 | 742 | effectPos += 1; 743 | if (effectPos == 766) // 255 * 3 + 1 744 | { 745 | effectPos = 0; 746 | } 747 | } 748 | else if (strcmp(effect, "rainbow2") == 0) 749 | { 750 | int pos = effectPos; 751 | if (pos < 256) 752 | { 753 | currentRed = 0; 754 | currentGreen = 255 - pos; 755 | currentBlue = pos; 756 | } 757 | else if (pos < 512) 758 | { 759 | currentRed = pos - 256; 760 | currentGreen = 0; 761 | currentBlue = 255 - (pos - 256); 762 | } 763 | else 764 | { 765 | currentRed = 255 - (pos - 512); 766 | currentGreen = pos - 512; 767 | currentBlue = 0; 768 | } 769 | 770 | effectPos += 1; 771 | if (effectPos == 766) 772 | { 773 | effectPos = 0; 774 | } 775 | } 776 | else if (strcmp(effect, "rainbow3") == 0) 777 | { 778 | int pos = effectPos; 779 | if (pos < 256) 780 | { 781 | currentRed = pos; 782 | currentGreen = 255 - pos; 783 | currentBlue = 255; 784 | } 785 | else if (pos < 512) 786 | { 787 | currentRed = 255; 788 | currentGreen = pos - 256; 789 | currentBlue = 255 - (pos - 256); 790 | } 791 | else 792 | { 793 | currentRed = 255 - (pos - 512); 794 | currentGreen = 255; 795 | currentBlue = pos - 512; 796 | } 797 | 798 | effectPos += 1; 799 | if (effectPos == 766) // 255 * 3 + 1 800 | { 801 | effectPos = 0; 802 | } 803 | } 804 | else if (strcmp(effect, "rainbow4") == 0) 805 | { 806 | int pos = effectPos; 807 | if (pos < 256) 808 | { 809 | currentRed = 255 - pos; 810 | currentGreen = pos; 811 | currentBlue = 255; 812 | } 813 | else if (pos < 512) 814 | { 815 | currentRed = pos - 256; 816 | currentGreen = 255; 817 | currentBlue = 255 - (pos - 256); 818 | } 819 | else 820 | { 821 | currentRed = 255; 822 | currentGreen = 255 - (pos - 512); 823 | currentBlue = pos - 512; 824 | } 825 | 826 | effectPos += 1; 827 | if (effectPos == 766) 828 | { 829 | effectPos = 0; 830 | } 831 | } 832 | setColorPins(); 833 | } 834 | 835 | void calculateMachineId() 836 | { 837 | MD5Builder md5; 838 | md5.begin(); 839 | char chipId[25]; 840 | sprintf(chipId,"%d",ESP.getChipId()); 841 | md5.add(chipId); 842 | md5.calculate(); 843 | md5.toString().toCharArray(machineId, 32); 844 | } 845 | 846 | void mqttReconnect() 847 | { 848 | // Generate unique MQTT client ID based on the machine ID 849 | char clientId[23 + sizeof(machineId)]; 850 | snprintf(clientId, sizeof(clientId), "anavi-light-controller-%s", machineId); 851 | 852 | // Loop until we're reconnected 853 | for (int attempt = 0; attempt < 3; ++attempt) 854 | { 855 | Serial.print("Attempting MQTT connection..."); 856 | // Attempt to connect 857 | if (true == mqttClient.connect(clientId, username, password)) 858 | { 859 | Serial.println("connected"); 860 | 861 | // Subscribe to MQTT topics 862 | mqttClient.subscribe(cmnd_power_topic); 863 | mqttClient.subscribe(cmnd_color_topic); 864 | publishDiscoveryState(); 865 | break; 866 | 867 | } 868 | else 869 | { 870 | Serial.print("failed, rc="); 871 | Serial.print(mqttClient.state()); 872 | Serial.println(" try again in 5 seconds"); 873 | // Wait 5 seconds before retrying 874 | delay(5000); 875 | } 876 | } 877 | } 878 | 879 | #ifdef HOME_ASSISTANT_DISCOVERY 880 | bool publishSensorDiscovery(const char *config_key, 881 | const char *device_class, 882 | const char *name_suffix, 883 | const char *state_topic, 884 | const char *unit, 885 | const char *value_template, 886 | bool binary = false) 887 | { 888 | DynamicJsonDocument json(1024); 889 | 890 | String sensorType = "sensor"; 891 | if (true == binary) 892 | { 893 | sensorType = "binary_sensor"; 894 | } 895 | else 896 | { 897 | // Unit of measurement is supported only by non-binary sensors 898 | json["unit_of_measurement"] = unit; 899 | json["value_template"] = value_template; 900 | } 901 | static char topic[48 + sizeof(machineId)]; 902 | snprintf(topic, sizeof(topic), 903 | "homeassistant/%s/%s/%s/config", sensorType.c_str(), machineId, config_key); 904 | 905 | if (0 < strlen(device_class)) 906 | { 907 | json["device_class"] = device_class; 908 | } 909 | json["name"] = String(ha_name) + " " + name_suffix; 910 | json["unique_id"] = String("anavi-") + machineId + "-" + config_key; 911 | json["state_topic"] = String(workgroup) + "/" + machineId + "/" + state_topic; 912 | 913 | json["device"]["identifiers"] = machineId; 914 | json["device"]["manufacturer"] = "ANAVI Technology"; 915 | json["device"]["model"] = "ANAVI Light Controller"; 916 | json["device"]["name"] = ha_name; 917 | json["device"]["sw_version"] = ESP.getSketchMD5(); 918 | 919 | JsonArray connections = json["device"].createNestedArray("connections").createNestedArray(); 920 | connections.add("mac"); 921 | connections.add(WiFi.macAddress()); 922 | 923 | Serial.print("Home Assistant discovery topic: "); 924 | Serial.println(topic); 925 | 926 | int payload_len = measureJson(json); 927 | if (!mqttClient.beginPublish(topic, payload_len, true)) 928 | { 929 | Serial.println("beginPublish failed!\n"); 930 | return false; 931 | } 932 | 933 | if (serializeJson(json, mqttClient) != payload_len) 934 | { 935 | Serial.println("writing payload: wrong size!\n"); 936 | return false; 937 | } 938 | 939 | if (!mqttClient.endPublish()) 940 | { 941 | Serial.println("endPublish failed!\n"); 942 | return false; 943 | } 944 | 945 | return true; 946 | } 947 | 948 | 949 | bool publishLightDiscovery() 950 | { 951 | DynamicJsonDocument json(1024); 952 | 953 | static char topic[48 + sizeof(machineId)]; 954 | snprintf(topic, sizeof(topic), 955 | "homeassistant/light/%s/light/config", machineId); 956 | 957 | json["schema"] = "json"; 958 | json["brightness"] = true; 959 | json["rgb"] = true; 960 | json["effect"] = true; 961 | JsonArray effects = json.createNestedArray("effect_list"); 962 | effects.add("none"); 963 | effects.add("switch_transition"); 964 | effects.add("rainbow1"); 965 | effects.add("rainbow2"); 966 | effects.add("rainbow3"); 967 | effects.add("rainbow4"); 968 | 969 | json["name"] = String(ha_name) + String(" ANAVI Light Controller"); 970 | json["unique_id"] = String("anavi-") + machineId + String("-rgb"); 971 | json["command_topic"] = String("cmnd/") + machineId + String("/color"); 972 | json["state_topic"] = String("stat/") + machineId + String("/#"); 973 | 974 | json["device"]["identifiers"] = machineId; 975 | json["device"]["manufacturer"] = "ANAVI Technology"; 976 | json["device"]["model"] = "ANAVI Light Controller"; 977 | json["device"]["name"] = ha_name; 978 | json["device"]["sw_version"] = ESP.getSketchMD5(); 979 | 980 | JsonArray connections = json["device"].createNestedArray("connections").createNestedArray(); 981 | connections.add("mac"); 982 | connections.add(WiFi.macAddress()); 983 | 984 | Serial.print("Home Assistant discovery topic: "); 985 | Serial.println(topic); 986 | 987 | int payload_len = measureJson(json); 988 | if (!mqttClient.beginPublish(topic, payload_len, true)) 989 | { 990 | Serial.println("beginPublish failed!\n"); 991 | return false; 992 | } 993 | 994 | if (serializeJson(json, mqttClient) != payload_len) 995 | { 996 | Serial.println("writing payload: wrong size!\n"); 997 | return false; 998 | } 999 | 1000 | if (!mqttClient.endPublish()) 1001 | { 1002 | Serial.println("endPublish failed!\n"); 1003 | return false; 1004 | } 1005 | 1006 | return true; 1007 | } 1008 | 1009 | #endif 1010 | 1011 | void publishDiscoveryState() 1012 | { 1013 | #ifdef HOME_ASSISTANT_DISCOVERY 1014 | 1015 | // Publish discovery information about the core feature 1016 | publishLightDiscovery(); 1017 | 1018 | // Publish discovery information if any I2C sensors are attached 1019 | static char payload[300]; 1020 | static char topic[80]; 1021 | 1022 | String homeAssistantTempScale = "°C"; 1023 | 1024 | if (isSensorAvailable(sensorHTU21D)) 1025 | { 1026 | publishSensorDiscovery("temp", 1027 | "temperature", 1028 | "Temperature", 1029 | "temperature", 1030 | homeAssistantTempScale.c_str(), 1031 | "{{ value_json.temperature | round(1) }}"); 1032 | 1033 | publishSensorDiscovery("humidity", 1034 | "humidity", 1035 | "Humidity", 1036 | "humidity", 1037 | "%", 1038 | "{{ value_json.humidity | round(0) }}"); 1039 | } 1040 | 1041 | if (isSensorAvailable(sensorBH1750)) 1042 | { 1043 | publishSensorDiscovery("light", 1044 | "illuminance", 1045 | "Light", 1046 | "light", 1047 | "Lux", 1048 | "{{ value_json.light }}"); 1049 | } 1050 | 1051 | #endif 1052 | } 1053 | 1054 | void publishState() 1055 | { 1056 | DynamicJsonDocument json(1024); 1057 | const char* state = power ? "ON" : "OFF"; 1058 | json["state"] = state; 1059 | 1060 | char stat_power_payload[150]; 1061 | serializeJson(json, stat_power_payload); 1062 | 1063 | Serial.print("["); 1064 | Serial.print(stat_power_topic); 1065 | Serial.print("] "); 1066 | Serial.println(stat_power_payload); 1067 | 1068 | mqttClient.publish(stat_power_topic, stat_power_payload, true); 1069 | 1070 | // Continue with the rest of the data for the colors 1071 | json["brightness"] = brightnessLevel; 1072 | json["effect"] = effect; 1073 | 1074 | json["color"]["r"] = power ? currentRed : 0; 1075 | json["color"]["g"] = power ? currentGreen : 0; 1076 | json["color"]["b"] = power ? currentBlue : 0; 1077 | 1078 | int payloadLength = measureJson(json); 1079 | if (mqttClient.beginPublish(stat_color_topic, payloadLength, true)) 1080 | { 1081 | if (serializeJson(json, mqttClient) == payloadLength) 1082 | { 1083 | mqttClient.endPublish(); 1084 | } 1085 | } 1086 | 1087 | char stat_color_payload[150]; 1088 | serializeJson(json, stat_color_payload); 1089 | 1090 | Serial.print("["); 1091 | Serial.print(stat_color_topic); 1092 | Serial.print("] "); 1093 | Serial.println(stat_color_payload); 1094 | 1095 | } 1096 | 1097 | void saveState() 1098 | { 1099 | Serial.println("saving config"); 1100 | DynamicJsonDocument json(1024); 1101 | const char* powerState = power ? "ON" : "OFF"; 1102 | json["state"] = powerState; 1103 | json["brightness"] = brightnessLevel; 1104 | json["effect"] = effect; 1105 | 1106 | json["color"]["r"] = power ? currentRed : 0; 1107 | json["color"]["g"] = power ? currentGreen : 0; 1108 | json["color"]["b"] = power ? currentBlue : 0; 1109 | 1110 | json["shortCycleCount"] = consecutiveShortCycles; 1111 | 1112 | File stateFile = SPIFFS.open("/state.json", "w"); 1113 | if (!stateFile) 1114 | { 1115 | Serial.println("failed to open state file for writing"); 1116 | } 1117 | 1118 | serializeJson(json, Serial); 1119 | serializeJson(json, stateFile); 1120 | stateFile.close(); 1121 | } 1122 | 1123 | void publishSensorData(const char* subTopic, const char* key, const float value) 1124 | { 1125 | StaticJsonDocument<100> json; 1126 | json[key] = value; 1127 | char payload[100]; 1128 | serializeJson(json, payload); 1129 | char topic[200]; 1130 | sprintf(topic,"%s/%s/%s", workgroup, machineId, subTopic); 1131 | mqttClient.publish(topic, payload, true); 1132 | } 1133 | 1134 | void publishSensorData(const char* subTopic, const char* key, const String& value) 1135 | { 1136 | StaticJsonDocument<100> json; 1137 | json[key] = value; 1138 | char payload[100]; 1139 | serializeJson(json, payload); 1140 | char topic[200]; 1141 | sprintf(topic,"%s/%s/%s", workgroup, machineId, subTopic); 1142 | mqttClient.publish(topic, payload, true); 1143 | } 1144 | 1145 | bool isSensorAvailable(int sensorAddress) 1146 | { 1147 | // Check if I2C sensor is present 1148 | Wire.beginTransmission(sensorAddress); 1149 | return 0 == Wire.endTransmission(); 1150 | } 1151 | 1152 | void handleHTU21D() 1153 | { 1154 | // Check if temperature has changed 1155 | const float tempTemperature = htu.readTemperature(); 1156 | if (0.1 <= fabs(tempTemperature - sensorTemperature)) 1157 | { 1158 | // Print new temprature value 1159 | sensorTemperature = tempTemperature; 1160 | Serial.print("Temperature: "); 1161 | Serial.print(sensorTemperature); 1162 | Serial.println("C"); 1163 | 1164 | // Publish new temperature value through MQTT 1165 | publishSensorData("temperature", "temperature", sensorTemperature); 1166 | } 1167 | 1168 | // Check if humidity has changed 1169 | const float tempHumidity = htu.readHumidity(); 1170 | if (1 <= abs(tempHumidity - sensorHumidity)) 1171 | { 1172 | // Print new humidity value 1173 | sensorHumidity = tempHumidity; 1174 | Serial.print("Humidity: "); 1175 | Serial.print(sensorHumidity); 1176 | Serial.println("%"); 1177 | 1178 | // Publish new humidity value through MQTT 1179 | publishSensorData("humidity", "humidity", sensorHumidity); 1180 | } 1181 | } 1182 | 1183 | void sensorWriteData(int i2cAddress, uint8_t data) 1184 | { 1185 | Wire.beginTransmission(i2cAddress); 1186 | Wire.write(data); 1187 | Wire.endTransmission(); 1188 | } 1189 | 1190 | void handleBH1750() 1191 | { 1192 | Wire.begin(); 1193 | // Power on sensor 1194 | sensorWriteData(sensorBH1750, 0x01); 1195 | // Set mode continuously high resolution mode 1196 | sensorWriteData(sensorBH1750, 0x10); 1197 | 1198 | uint16_t tempAmbientLight; 1199 | 1200 | Wire.requestFrom(sensorBH1750, 2); 1201 | tempAmbientLight = Wire.read(); 1202 | tempAmbientLight <<= 8; 1203 | tempAmbientLight |= Wire.read(); 1204 | // s. page 7 of datasheet for calculation 1205 | tempAmbientLight = tempAmbientLight/1.2; 1206 | 1207 | if (1 <= abs(tempAmbientLight - sensorAmbientLight)) 1208 | { 1209 | // Print new humidity value 1210 | sensorAmbientLight = tempAmbientLight; 1211 | Serial.print("Light: "); 1212 | Serial.print(tempAmbientLight); 1213 | Serial.println("Lux"); 1214 | 1215 | // Publish new humidity value through MQTT 1216 | publishSensorData("light", "light", sensorAmbientLight); 1217 | } 1218 | } 1219 | 1220 | void detectGesture() 1221 | { 1222 | //read a gesture from the device 1223 | const uint8_t gestureCode = apds.readGesture(); 1224 | // Skip if gesture has not been detected 1225 | if (0 == gestureCode) 1226 | { 1227 | return; 1228 | } 1229 | String gesture = ""; 1230 | switch(gestureCode) 1231 | { 1232 | case APDS9960_DOWN: 1233 | gesture = "down"; 1234 | break; 1235 | case APDS9960_UP: 1236 | gesture = "up"; 1237 | break; 1238 | case APDS9960_LEFT: 1239 | gesture = "left"; 1240 | break; 1241 | case APDS9960_RIGHT: 1242 | gesture = "right"; 1243 | break; 1244 | } 1245 | Serial.print("Gesture: "); 1246 | Serial.println(gesture); 1247 | // Publish the detected gesture through MQTT 1248 | publishSensorData("gesture", "gesture", gesture); 1249 | } 1250 | 1251 | void handleSensors() 1252 | { 1253 | if (isSensorAvailable(sensorHTU21D)) 1254 | { 1255 | handleHTU21D(); 1256 | } 1257 | if (isSensorAvailable(sensorBH1750)) 1258 | { 1259 | handleBH1750(); 1260 | } 1261 | } 1262 | 1263 | void loop() 1264 | { 1265 | // put your main code here, to run repeatedly: 1266 | ArduinoOTA.handle(); 1267 | 1268 | mqttClient.loop(); 1269 | 1270 | const unsigned long effectMillis = millis(); 1271 | if (effectsInterval <= (effectMillis - effectPreviousMillis)) 1272 | { 1273 | effectPreviousMillis = effectMillis; 1274 | processEffects(); 1275 | } 1276 | 1277 | if (thisCycleIsShort && millis() > shortCycleMaxMillis) 1278 | { 1279 | thisCycleIsShort = false; 1280 | consecutiveShortCycles = 0; 1281 | saveState(); 1282 | publishState(); 1283 | } 1284 | 1285 | // Reconnect if there is an issue with the MQTT connection 1286 | const unsigned long mqttConnectionMillis = millis(); 1287 | if ( (false == mqttClient.connected()) && (mqttConnectionInterval <= (mqttConnectionMillis - mqttConnectionPreviousMillis)) ) 1288 | { 1289 | mqttConnectionPreviousMillis = mqttConnectionMillis; 1290 | mqttReconnect(); 1291 | } 1292 | 1293 | const unsigned long currentMillis = millis(); 1294 | if (sensorInterval <= (currentMillis - sensorPreviousMillis)) 1295 | { 1296 | sensorPreviousMillis = currentMillis; 1297 | handleSensors(); 1298 | } 1299 | 1300 | // Handle gestures at a shorter interval 1301 | if (isSensorAvailable(APDS9960_ADDRESS)) 1302 | { 1303 | detectGesture(); 1304 | } 1305 | 1306 | // Press and hold the button to reset to factory defaults 1307 | factoryReset(); 1308 | } 1309 | -------------------------------------------------------------------------------- /platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [platformio] 12 | src_dir = anavi-light-controller-sw 13 | 14 | [env:esp01_1m] 15 | platform = espressif8266 16 | board = esp01_1m 17 | monitor_speed = 115200 18 | framework = arduino 19 | lib_deps = 20 | WiFiManager 21 | DNSServer 22 | ESP8266WebServer 23 | ESP8266WiFi 24 | ArduinoJson 25 | PubSubClient 26 | Adafruit HTU21DF Library 27 | Adafruit APDS9960 Library 28 | --------------------------------------------------------------------------------