Blog

  • esbuild-react-ts-boilerplate

    Step-by-Step Tutorial: Setting up React + Esbuild + Typescript Project

    Table of Contents

    1. Project Setup

      1. Prerequisites
      2. Install Node.js
      3. Initialize the Project
      4. Install Dependencies
      5. Configure Gitignore
      6. Configure TypeScript
      7. Create Public Directory
      8. Add Public Files
      9. Add Optional Files
      10. Create Esbuild Configuration
      11. Enable Live Reloading (Optional)
      12. Create Environment Variables File
      13. Update Package.json
      14. Run the Project
    2. Test Suite Setup

      1. Install Packages
      2. Add Jest Config
      3. Add Tests Setup File
      4. Add Scripts to Package.json
    3. Linter and Formatter Setup

      1. Install Packages
      2. Add ESLint Config
      3. Add Prettier Config
      4. Add Paths to tsconfig.json (Optional)
      5. Add Scripts to Package.json

    Project setup

    Prerequisites

    Before you begin, make sure you have the following prerequisites installed:

    • Node Version Manager (nvm)

    Step 1: Install Node.js

    1. Open your terminal.

    2. Install the latest LTS version of Node.js using nvm by running the following command:

      nvm install --lts
    3. Create an .nvmrc file in your project’s root directory and add the installed Node.js version to it by running the following command:

      node --version > .nvmrc

    Step 2: Initialize the Project

    1. Create a new directory for your project.

    2. Navigate to the project’s root directory in the terminal.

    3. Initialize a new private project using Npm by running the following command:

      npm init -yp
    4. Edit the generated package.json file as needed. For example, you can remove the "main" field if you won’t be publishing the package, change the "license", etc.

    Step 3: Install Dependencies

    1. Install the necessary packages for React, Esbuild, Typescript, and other required dependencies by running the following command:

      npm install esbuild react react-dom dotenv typescript
    2. Install type definitions for React and React DOM as dev dependencies by running the following command:

      npm install --save-dev @types/react @types/react-dom
    3. Run npm install

    Step 4: Configure Gitignore

    1. Add following lines to .gitignore

      *.log
      .env
      coverage
      node_modules
      public/build/
      !public/build/.keep

    Step 5: Configure TypeScript

    1. Initialize the tsconfig.json file by running the following command:

      npx tsc --init --rootDir src --jsx react --module es6 --moduleResolution node --noEmit true

    Step 6: Create Public Directory

    1. Create a public directory in the project’s root directory.

    Step 7: Add Public Files

    1. Create an index.html file inside the public directory.

    2. Add the following HTML code to the index.html file:

      <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="utf-8" />
          <title>Title</title>
          <meta name="description" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <link rel="manifest" href="/manifest.json" />
          <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
          <script type="module" src="./build/bundle.js"></script>
        </head>
        <body>
          <noscript>You need to enable JavaScript to run this app.</noscript>
          <div id="root"></div>
        </body>
      </html>

    Step 8: Add Optional Files

    1. Optionally, you can add a favicon.ico file and a manifest.json file to the public directory.

    Step 9: Create Esbuild Configuration

    1. Create an esbuild.config.js file in the project’s root directory.

    2. Add the following JavaScript code to the esbuild.config.js file:

      import dotenv from 'dotenv';
      import esbuild from 'esbuild';
      
      dotenv.config();
      const args = process.argv;
      
      const config = {
        logLevel: 'info',
        entryPoints: ['src/index.ts'],
        outfile: 'public/build/bundle.js',
        bundle: true,
        define: {
          NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'production'),
        },
      };
      
      if (args.includes('--build')) {
        esbuild
          .build({
            ...config,
            minify: true,
            sourcemap: false,
          })
          .catch((e) => {
            console.error(e);
            process.exit(1);
          });
      }
      
      if (args.includes('--start')) {
        esbuild
          .context({
            ...config,
            minify: false,
            sourcemap: true,
          })
          .then(async (ctx) => {
            await ctx.watch(); // this is needed only if live reloading will be used
            await ctx.serve({
              servedir: 'public',
              onRequest: ({ remoteAddress, method, path, status, timeInMS }) => {
                console.info(remoteAddress, status, `"${method} ${path}" [${timeInMS}ms]`);
              },
            });
          })
          .catch((e) => {
            console.error(e);
            process.exit(1);
          });
      }

    Step 10: Enable Live Reloading (Optional)

    1. Open the entry file (src/index.ts) in your code editor.

    2. Add the following line of code at the beginning of the file:

      declare const NODE_ENV: string;
      if (NODE_ENV === 'development')
        new EventSource('/esbuild').addEventListener('change', () => location.reload());

    Step 11: Create Environment Variables File

    1. Create a .env file in the project’s root directory.

    2. Add the following content to the .env file:

      NODE_ENV=development

    Step 12: Update Package.json

    1. Open the package.json file in your code editor.

    2. Change the "type" field to "module" to enable ECMAScript modules:

      "type": "module",
    3. Add the following scripts to the "scripts" section of the package.json file:

      "scripts": {
        "build": "node esbuild.config.js --build",
        "start": "node esbuild.config.js --start"
      },

    Step 13: Run the Project

    1. Open your terminal.

    2. Navigate to the project’s root directory.

    3. Start the project by running the following command:

      yarn start
    4. The project should now be running, and you can view it in your browser at the specified URL.

    Congratulations! You have successfully set up a React + Esbuild + Typescript project. You can now start developing your application using this setup.

    Test suite Setup

    Step 1: Install packages

    • jest: A JavaScript testing framework used for writing and executing tests.

    • @testing-library/jest-dom: Provides additional matchers and utilities for testing DOM-related behavior in Jest.

    • @testing-library/react: Offers utilities for testing React components using the Testing Library approach.

    • @testing-library/user-event: Allows simulating user events in React components during testing.

    • @types/jest: TypeScript type definitions for Jest, ensuring accurate type information.

    • esbuild-jest: A Jest transformer that compiles JSX and TypeScript in test files, leveraging the fast esbuild bundler.

    • jest-environment-jsdom: Provides a JSDOM environment for Jest, allowing tests to interact with the DOM.

      yarn add -D jest \
      @testing-library/jest-dom @testing-library/react @testing-library/user-event \
      @types/jest esbuild-jest \
      jest-environment-jsdom

    Step 2: Add jest config

    1. Create jest.config.js

      /*
       * For a detailed explanation regarding each configuration property, visit:
       * https://jestjs.io/docs/configuration
       */
      
      export default {
        // Stop running tests after `n` failures
        bail: 1,
        // Automatically clear mock calls, instances, contexts and results before every test
        clearMocks: true,
        // Indicates whether the coverage information should be collected while executing the test
        collectCoverage: true,
        // The directory where Jest should output its coverage files
        coverageDirectory: 'coverage',
        // Indicates which provider should be used to instrument code for coverage
        coverageProvider: 'v8',
        // The root directory that Jest should scan for tests and modules within
        // rootDir: undefined,
        // A list of paths to directories that Jest should use to search for files in
        roots: ['src'],
        // The paths to modules that run some code to configure or set up the testing environment before each test
        // setupFiles: [],
        // A list of paths to modules that run some code to configure or set up the testing framework before each test
        setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
        // The number of seconds after which a test is considered as slow and reported as such in the results.
        slowTestThreshold: 5,
        // A list of paths to snapshot serializer modules Jest should use for snapshot testing
        // snapshotSerializers: [],
        // The test environment that will be used for testing
        testEnvironment: 'jsdom',
        // A map from regular expressions to paths to transformers
        transform: {
          '^.+\\.tsx?$': 'esbuild-jest',
          '^.+\\.ts?$': 'esbuild-jest',
        },
      };

    Step 3: Add tests setup file

    1. Create src/setupTests.ts

      // to expand availiable matchers in tests
      import '@testing-library/jest-dom';

    Step 4: Add scripts to package.json

    1. Update your package.json file and add the following scripts:

      "scripts": {
        "test": "jest --watch"
      }

    Linter and Formatter Setup

    Step 1: Install packages

    1. Install the following packages using Npm:
    • eslint: Code quality tool to catch bugs.

    • eslint-plugin-compat: Plugin to lint the browser compatibility of your code.

    • eslint-plugin-react: ESLint support for React.

    • eslint-config-prettier: Config extension to remove conflicts between ESLint and Prettier.

    • @typescript-eslint/eslint-plugin and @typescript-eslint/parser: ESLint support for TypeScript.

    • prettier: Code formatter to make code style consistent.

    • (Optional) @trivago/prettier-plugin-sort-imports: Plugin for Prettier to automatically sort imports.

      npm install --save-dev eslint \
      eslint-plugin-compat eslint-plugin-react eslint-config-prettier \
      @typescript-eslint/eslint-plugin @typescript-eslint/parser \
      prettier @trivago/prettier-plugin-sort-imports

    Step 2: Add eslint config

    1. Create eslint.config.cjs and add the following configuration:

      module.exports = {
        env: {
          browser: true,
          es2021: true,
        },
        extends: [
          'eslint:recommended',
          'plugin:@typescript-eslint/recommended',
          'plugin:react/recommended',
          'plugin:compat/recommended',
          'prettier',
        ],
        overrides: [
          {
            env: {
              node: true,
            },
            files: ['.eslintrc.{js,cjs}'],
            parserOptions: {
              sourceType: 'script',
            },
          },
        ],
        parser: '@typescript-eslint/parser',
        parserOptions: {
          ecmaVersion: 'latest',
          sourceType: 'module',
        },
        plugins: ['@typescript-eslint', 'react', 'compat'],
        ignorePatterns: ['public/build/*'],
        settings: {
          react: {
            version: 'detect',
          },
        },
        rules: {},
      };

    Step 3: Add prettier config

    1. Create .prettierrc (Optional, if you don’t plan to use the import sort plugin, you can leave the defaults):

      {
        "printWidth": 100,
        "singleQuote": true,
        "jsxSingleQuote": true,
        "importOrder": ["^@/(.*)$", "^[./]"],
        "importOrderSeparation": true,
        "importOrderSortSpecifiers": true
      }
    2. Create .prettierignore and add the following line to exclude the public/build directory:

      public/build

    Step 4: (Optional) Add paths to tsconfig.json

    1. Update your tsconfig.json file and add the following paths configuration to support absolute imports:

      "baseUrl": "src",
      "paths": {
        "@/*": ["*"]
      }

    Step 5: Add scripts to package.json

    1. Update your package.json file and add the following scripts:

      "scripts": {
        "fmt": "prettier --write",
        "lint": "eslint --fix"
      }

    Usage:

    • Run ESLint and automatically fix linting issues:

      npm run lint .
      npm run lint <filepath>
    • Format your code using Prettier:

      npm run fmt .
      npm run fmt <filepath>

    Visit original content creator repository
    https://github.com/VovaK0-23/esbuild-react-ts-boilerplate

  • CountryLookupUsingIPAddressJAVA

    CountryLookupUsingIPAddressJAVA

    Know the country info to which an IP address is originating from.

    Getting Started

    Clone this repo to your local machine How To Guide

    Prerequisites

    • Basic Knowledge of JAVA. Great tutorial on Javatpoint.
    • Java JDK 8 at least installed on Local machine. Oracle Doc for Mac & Windows.
    • An IDE installed in local machine. Check out intelliJ IDEA.

    Installing

    CountryLookupUsingIPAddressJAVA requires Java JDK 8+ to run.
    Setup development environment with desired IDE. Google step by step for desired IDE.

    After cloning the repo to local machine, IntelliJ IDEA guide for cloning directly from IDE.

    In building CLI i used external API’s, click links to download JAR files.

    ADD JAR files to cloned project ClassPath. Guide Intellij & Eclipse. You can google if you use any other IDE.

    Running the tests

    After setting up development environment and adding JAR files to ClassPath/BuildPath.

    • Build & Run

    You should comprehensive outputs in the terminal….Hurray you can now lookup country orgin of an IP address.

    Built With

    Contributing

    If you have a new feature idea, do well to create a PR.

    Versioning

    Only one version of this software at this time.

    Authors

    • Divine Odazie

    License

    No license.

    Visit original content creator repository
    https://github.com/Kikiodazie/CountryLookupUsingIPAddressJAVA

  • CountryLookupUsingIPAddressJAVA

    CountryLookupUsingIPAddressJAVA

    Know the country info to which an IP address is originating from.

    Getting Started

    Clone this repo to your local machine How To Guide

    Prerequisites

    • Basic Knowledge of JAVA. Great tutorial on Javatpoint.
    • Java JDK 8 at least installed on Local machine. Oracle Doc for Mac & Windows.
    • An IDE installed in local machine. Check out intelliJ IDEA.

    Installing

    CountryLookupUsingIPAddressJAVA requires Java JDK 8+ to run.
    Setup development environment with desired IDE. Google step by step for desired IDE.

    After cloning the repo to local machine, IntelliJ IDEA guide for cloning directly from IDE.

    In building CLI i used external API’s, click links to download JAR files.

    ADD JAR files to cloned project ClassPath. Guide Intellij & Eclipse. You can google if you use any other IDE.

    Running the tests

    After setting up development environment and adding JAR files to ClassPath/BuildPath.

    • Build & Run

    You should comprehensive outputs in the terminal….Hurray you can now lookup country orgin of an IP address.

    Built With

    Contributing

    If you have a new feature idea, do well to create a PR.

    Versioning

    Only one version of this software at this time.

    Authors

    • Divine Odazie

    License

    No license.

    Visit original content creator repository
    https://github.com/Kikiodazie/CountryLookupUsingIPAddressJAVA

  • core

    Promplate

    </Promplate/> = <template> // prompt
    

    Promplate is a prompting framework focusing on developing experience. However, it can also be a super-convenient SDK for simple LLM calls. Promplate progressively enhance your prompting workflow. And it values flexibility as well as perfect conventions. Try online

    Installation

    pip install promplate

    Promplate supports both CPython and PyPy, from 3.8 to 3.13. It even supports running in browsers through wasm implementations of python.

    Documentation

    You can visit our official docs site at docs.py.promplate.dev.

    IDE Support 🌹

    Promplate is fully typed, which means static type checker will find bugs correctly (if you use pyright for type checking).

    We recommend using VS Code as your IDE when coding with promplate, because it natively uses pyright.

    The language design of promplate is similar to Jinja2. So you can use the .j2 file extension for template files for syntax highlight.

    Development

    • use poetry to manage dependencies.
    • use isort to sort import statements.
    • use black to format code.
    • use pyright to check type annotations.

    Development should be done on dev branch, using >=3.10 language features. The master branch is used for py3.8 compatible releases.

    Promplate is well tested with pytest. GitHub Actions are used to run tests and linting. And there are test results continually generated on Vercel and Netlify. There is a coverage report too.

    Future Features (or TODOs?)

    • more documentation
    • javascript implementation
    • improved error handling
      • display compiled code when error occurs through linecache or tempfile

    Visit original content creator repository
    https://github.com/promplate/core

  • android-screenshot-framer

    android-screenshot-framer

    A really dirty port of https://developer.android.com/distribute/tools/promote/device-art.html into a node.js script.

    Usage:

    node frame.js --path=/search/for/**/*.png
    
    • --path=/some/path/**/*.png" a path where to recursively search for .png files.
    • --dryrun to just show pathes.
    • --postfix=framed to create pic_framed.png from pic.png`, if you don’t specify a postfix the original will be overwritten
    • --device=nexus_5, only nexus_5 works atm, which is also the default, other layouts have the wrong offsets.

    Example:

    node frame.js --path=test/*.png --device=nexus_5 --postfix=_framed --dryrun
    test/2016-09-28 12.05.22.png --> test/2016-09-28 12.05.22_framed.png (nexus_5)
    test/2016-09-28 12.05.37.png --> test/2016-09-28 12.05.37_framed.png (nexus_5)
    test/2016-09-28 13.15.31.png --> test/2016-09-28 13.15.31_framed.png (nexus_5)
    test/2016-09-28 13.15.42.png --> test/2016-09-28 13.15.42_framed.png (nexus_5)
    test/2016-09-28 13.15.46.png --> test/2016-09-28 13.15.46_framed.png (nexus_5)
    test/2016-09-28 13.25.53.png --> test/2016-09-28 13.25.53_framed.png (nexus_5)
    All submitted (dryrun: true)
    ``
    

    Visit original content creator repository
    https://github.com/d4rken/android-screenshot-framer

  • educationDataApp

    Getting Started with Create React App

    This project was bootstrapped with Create React App.

    Available Scripts

    In the project directory, you can run:

    npm start

    Runs the app in the development mode.
    Open http://localhost:3000 to view it in your browser.

    The page will reload when you make changes.
    You may also see any lint errors in the console.

    npm test

    Launches the test runner in the interactive watch mode.
    See the section about running tests for more information.

    npm run build

    Builds the app for production to the build folder.
    It correctly bundles React in production mode and optimizes the build for the best performance.

    The build is minified and the filenames include the hashes.
    Your app is ready to be deployed!

    See the section about deployment for more information.

    npm run eject

    Note: this is a one-way operation. Once you eject, you can’t go back!

    If you aren’t satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single build dependency from your project.

    Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except eject will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

    You don’t have to ever use eject. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

    Learn More

    You can learn more in the Create React App documentation.

    To learn React, check out the React documentation.

    Code Splitting

    This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting

    Analyzing the Bundle Size

    This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size

    Making a Progressive Web App

    This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app

    Advanced Configuration

    This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration

    Deployment

    This section has moved here: https://facebook.github.io/create-react-app/docs/deployment

    npm run build fails to minify

    This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

    Visit original content creator repository
    https://github.com/Michael-Fares/educationDataApp

  • lg-c2-utility

    LG C2 PC Input Mode Type Script

    The LG C2 TV annoyingly defaults to HDMI Input Mode Type.

    This mode has hight latency and bad image quality.

    The PC Input Mode Type fixes that, but it’s deeply nested under the webOS Home Dashboard, and resets every time the cable is disconnected (e.g. to plug it into another device).

    This script makes it so that your macOS device listens to the TV being available via AirPlay, and changes all HDMI’s Input Mode Type to PC.

    Tested in macOS Sonoma 14.0

    How to use

    1. Install the bscpylgtv library
    2. Place lg-pc-mode.sh in ~/.bin or equivalent folder.
    3. Make it executable
      1. Run chmod +x ~/.bin/lg-pc-mode.sh
    4. (Optional): Run and test it now:
      1. Run ~/.bin/lg-pc-mode.sh
      2. You should see your TV listed under “Instance Name”
    5. Add cron to run it upon every reboot:
      1. Run crontab -e
      2. Add and save: @reboot ~/.bin/lg-pc-mode.sh
      3. Confirm it’s been added running: crontab -l

    Troubleshooting

    • You need to have the bscpylgtvcommand binary inside /opt/homebrew/bin
      • Change the path used in the debounce function calls if you have it elsewhere.
    • Find your monitor model
      • Run dns-sd -B _airplay._tcp
        • Get the model number and update line 22 of the script with it.
        • Example output (your model number would be: OLED42C24LA):

    Browsing for _airplay._tcp
    DATE: ---Sat 14 Oct 2023---
     8:48:47.228  ...STARTING...
    Timestamp     A/R    Flags  if Domain               Service Type         Instance Name
     8:48:47.229  Add        3  14 local.               _airplay._tcp.       MacBook Pro
     8:48:47.229  Add        3   1 local.               _airplay._tcp.       MacBook Pro
     8:48:47.229  Add        3  19 local.               _airplay._tcp.       MacBook Pro
     8:48:47.229  Add        3  21 local.               _airplay._tcp.       MacBook Pro
     8:48:47.229  Add        3  23 local.               _airplay._tcp.       MacBook Pro
     8:48:47.229  Add        3  15 local.               _airplay._tcp.       MacBook Pro
     8:48:47.229  Add        2  15 local.               _airplay._tcp.       [LG] webOS TV OLED42C24LA
    

    Special Mentions

    • alin23 – Helping and providing the simplest solution using dns-sd. Also check out his awesome app for controlling monitors, Lunar.
    • ToggleHDR Apple Shortcut, also from alin23 lets you quickly enable/disable HDR in any monitor, including the LG C2 TV. This enhances brightness and arguably improves image quality.
    • bscpylgtv library by chros73 lets us control the webOS based LG TVs like the C2.

    Other sources

    Visit original content creator repository
    https://github.com/madeinchema/lg-c2-utility

  • the-knighting-of-sr-isaac

    Visit original content creator repository
    https://github.com/js13kGames/the-knighting-of-sr-isaac

  • organized-teleporter

    Organized Teleporter

    This is a system built for ATM9 to organize all of your teleportation locations

    Setup

    1. Create a teleport scroll. To do this, take an archmage’s spellbook from Ars, and create a spell with form of touch and effect of blink. Then take a some spell parchment and apply that spell to it using a scribe’s table.
    2. Create your teleport pad. A valid teleport pad consists of teleport rune (use the scroll from step 1 on an ars nouveau rune), an adjacent inventory, and a wired modem adjacent to that inventory. You will also need a source jar as well as a source generation setup to regenerate source, as each teleport uses up 1% of a source jar.
    3. Create your source inventory. A valid source inventory consists of what Minecraft considers an inventory -> for example, occultism mass storage and sophisticated storage will work, but AE2 and RS will not, at least with this branch (RS is currently supported on the refinedstorage branch). This code is MIT licensed, so feel free to fork it. It also requires an adjacent wired modem.
    4. Setup your computer. It requires an advanced monitor (currently configured for a 4 wide by 3 tall monitor, though that can be adjusted somewhat) and nbtStorage from advance peripherals to be at least connected to the wired network if not adjacent. This computer will need to be accessible, as the shell for the program has functionality the UI doesn’t.
    5. Connect all of the elements of your network, and make sure to activate every wired modem. Note down the peripheral names of the source inventory, and the teleport pad inventory.
    6. Download the main lua file. If you have the HTTP API enabled in your server’s CC:Tweaked settings, you can use pastebin put startup.lua ctysPxVz. Otherwise, use the import program. This is done by dragging the main.lua file onto
      the terminal. After that, use the move main.lua startup.lua to leave it in the appropriate place.
    7. Edit the config section of the file so that the program knows which inventory is the source inventory and which is the teleporter inventory. It’s under the comment --Config.
    8. Restart the computer, or manually run the startup script.
    9. Get ars nouveau stabilized warp scrolls with destinations, and rename them in an anvil. Note that all strings are trimmed, so don’t add spaces before any actual characters or after all of the actual characters. Spaces in between are fine. Then put them all into the source inventory.
    10. Finally go to the shell, and use the command refresh_locations
    11. You should be good to go to start using the system

    Shell Primer

    The shell is a little bit unusual, owing to how it handles spaces and tab completion. It works by entering a command, and then prompting you for the fields necessary to complete that command. For example, tagging a location currently works like this

    (teleport)> tag_location
    ------------------------------------------
    (tag to add location to)> Ad Astra
    (location to tag)> Venus
    Location Venus added to tag Ad Astra
    -----------------------------------------
    

    The shell will automatically trim whitespace off of the ends of all inputs. Tab completion should be present for most commands, but will be case sensitive. The actual inputs should ignore case whenever possible.

    Pitfalls/Known Bugs

    1. Owing to the problem that finding a certain named item requires an O(n) operation and constantly querying an inventory, using a regular Minecraft inventory doesn’t scale well. Use the refinedstorage branch if you want to use a large number of locations

    Visit original content creator repository
    https://github.com/astracerus/organized-teleporter

  • esp8266-openhab-switch

    esp8266-openhab-switch

    ESP8266-based switch for openHAB.

    Intro

    The motivation is to build a small physical Wi-Fi enabled switch that controls lights via openHAB. It should require only a power cable and send the commands via Wi-Fi and MQTT to the openHAB server which then controls the lights.

    Hardware

    Besides the openHAB server and some lights (this guide uses Philips Hue lights but others work as well), the following components are used:

    The OLED display is used to show network information and confirmation of the commands. The switch setup would probably also work with other ESP8266 boards but Adafruit’s Feather board is nice and easy to use. The buttons on the OLED board are used as the switch buttons but it’s also possible to use externally connected buttons/switches.

    ESP8266 Setup

    Flash the Arduino sketch esp8266-openhab-switch.ino to the board. Don’t forget to adjust the Wi-Fi and MQTT settings at the beginning of the sketch. The sketch requires that the ESP8266 drivers are installed and the Adafruit libraries for the Feather board and the OLED board are loaded in the Arduino IDE.

    Detailed instructions on how to use Adafruit’s ESP8266 Feather board with the Arduino IDE can be found here: https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/using-arduino-ide

    openHAB Setup

    MQTT Server

    On the openHAB2 server, first install the MQTT server and the openHAB MQTT binding. When using openHAB2 on a Raspberry Pi with Raspbian, the MQTT server can be installed with the following commands:

    wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
    sudo apt-key add mosquitto-repo.gpg.key
    cd /etc/apt/sources.list.d/
    sudo wget http://repo.mosquitto.org/debian/mosquitto-wheezy.list
    sudo apt-get install mosquitto
    

    After that the MQTT binding can be installed via the Paper UI. There’s also a good beginner’s guide on MakeUsOf that explains how to setup and test the MQTT server and binding. After installation, the MQTT binding has to be configured as shown in services/mqtt.cfg.

    Items & Rules

    In addition to the Hue light kitchen_ceiling_light_dimmer, two items are defined in the item file items/all.items: A dimmer that represents the ESP8266 board and a string to send a message to the ESP8266 OLED display, both connected to MQTT.

    The rule file rules/esp8266_switch.rules defines the dimmer behavior. The ESP8266 board sends values 100, 50, and 0 with the buttons A, B, and C via MQTT. The rule Kitchen Switch sets the Hue light state to the value that the board sent. The rule Kitchen Switch Display sends a string with the Hue light state to the board so it can be displayed. What’s cool here is that this string gets sent whenever the light state is changed, even through another UI (e.g. the Android app).

    Visit original content creator repository
    https://github.com/stefanthoss/esp8266-openhab-switch