# obniz Docs - Full Content > This file contains the full text content of all obniz documentation pages. > Each page is separated by a horizontal rule and prefixed with its title and URL. --- ## Guides for Products URL: https://obniz.com/guides Layers in Detail Each layer, with the docs you need Where you start depends on the project. Use the SaaS, build with the SDK, or integrate the hardware directly — whichever path you take, the documentation is right here. 01 · Solutions obniz Now Use-case packages built on obniz Ready-to-deploy SaaS for temperature monitoring, water-leak detection, PLC remoting, and more — installed and managed without writing code. Referenceobniz Now product reference Terms of Service Privacy Policy 02 · Cloud Platform obniz Cloud The management plane that connects devices to apps A unified API for managing tens of thousands of devices. Authentication, OTA delivery, device monitoring — all included. Hit it from REST, GraphQL, or WebSocket, or build on top with the SDKs. ReferenceOverview and core concepts Hardware API (WebSocket)Direct realtime device control GraphQL APIManage devices, users, and events obniz MCP ServerControl obniz devices from AI clients SDK obniz.js App SDK Lua Plugin obniz.js — GitHub App SDK — GitHub Terms of Service 03 · Operating System obnizOS The cloud-connected OS embedded on each device Reconnect logic, key management, OTA updates, sleep/wake, and network connectivity — all handled by obnizOS. App developers never have to think about this layer. ReferenceobnizOS for ESP32 — full documentation SettingsConfigure devices via web tool ChangelogobnizOS version history Lua on obnizOSRun Lua scripts directly on device OTAOver-the-air firmware updates Self-hostingConnect devices to your own cloud Network Wi-Fi Ethernet LTE / LTE-M / NB-IoT 04 · Hardware Devices Certified hardware running obnizOS Pick the form factor and connectivity that fits your site. The OS, Cloud, and SDKs above are identical across all devices. Intelligent Edge KiloRS232 / RS485 / CAN gateway Intelligent Edge MicroCompact LTE-M / Wi-Fi edge device BLE/Wi-Fi Gateway Gen2Bridge BLE devices to the cloud BLE/LTE Gateway (Cat.4)SIM-attached, deploy anywhere obniz Board / 1YFor prototyping and small builds obniz Starter KitAll-in-one kit for first-timers Supported devicesAll hardware obnizOS runs on Not sure where to start? Begin with the Starter Guide to connect your first device to the cloud, or jump straight into the obniz.js reference. Starter guide obniz.js reference --- ## M5StickC URL: https://obniz.com/guides/m5stickc M5StickC Guide Preparement Connect To obniz Cloud For Beginners Use electrical parts from HTML (5) Block Program (9) Node.js (5) obniz.js Device Control Connection Wait and Repeat Parts Library IO IO Animation AD PWM UART SPI I2C LogicAnalyzer Measurement Display Switch Sleep BLE obniz Cloud Hardware API Online Editor Repository WebApp Account and Invoice Serverless Event Device Management HTML/JavaScript/Node.js JavaScript Basics of HTML/JavaScript Loop UI Button Image Form Type Typing Form Radio Button Form Slider Form Select Box Form Color Picker 3D Show and control cube  MachineLearning Voice Recognition Text Recognition Human Recognition Posture Recognition Web ServiceIntegration Smart Speaker MessageApp Google Spread Sheet IFTTT SNS Guides for Products obniz Board / 1Y M5StickC obniz BLE obnizOS for ESP32 KIT Guides obniz Starter Kit AI Robot Kit IoT Home Kit --- ## obniz Starter Guide URL: https://obniz.com/guides/obniz-starter-guide A guide to getting started with IoT with obniz. This guide covers all products, including obniz Board and obnizOS writing. ****Click here for preparation and lessons for KIT.**** - [obniz Starter Kit](/guides/obniz-starter-kit/about/) - [AI Robot Kit](/guides/ai-robot-kit/) - [IoT Home Kit](/guides/iot-home-kit/) --- ## Get an Official Device URL: https://obniz.com/guides/obniz-starter-guide/buy-licensed-product Obniz sells official devices that come with obnizOS installed and are ready to be used as soon as you turn them on and set them up, including Wi-Fi. [Product List](https://obniz.com/products) ## How to choose a device If you want to run a motor, obniz Board The obniz board is capable of carrying up to 1 ampere of current at all IOs and connects motors directly. If you want to run on batteries, obniz Board 1Y In addition to the obniz Board, it includes a sleep function for battery operation, allowing for long-term operation far from the power source. If you want to create something with HTML, you can use M5StickC In addition to the color display, there are pre-installed sensors and buttons inside, so you can quickly create little creations that integrate with HTML. DevKitC for product development prototypes The ESP32-WROOM32 is equipped with the ESP32-WROOM32, which allows you to build a prototype environment in no time. If you use the BLE, obniz BLE/Wi-Fi Gateway It is a BLE gateway that can be plugged in, and can be installed in a development environment as well as in an actual store. ## How to buy You will find a [list of products](https://obniz.com/products) with their respective purchase options in the Product List. There are two main ways to purchase - EC: You can buy from the official store, Amazon or any wholesaler - stores: Available at stores that carry multiple companies' electronic components. --- ## Connect to the Cloud URL: https://obniz.com/guides/obniz-starter-guide/connect-to-the-obniz-cloud There is a Quick start for each official device. [obniz Board (1Y)](/reference/board-1y/quick-start/) [M5StickC](/reference/m5stickc/quick-start/) [obniz BLE/Wi-Fi Gateway](/reference/obniz-ble-wi-fi-gateway/quick-start/) The common network settings for obnizOS are [setup](/reference/obnizos-for-esp32/settings/) for more information. --- ## Account Creation and Linking URL: https://obniz.com/guides/obniz-starter-guide/account-link The official device you purchased can be registered to your account to access the following features. - Device Management Adding device descriptions for multiple devices, checking connection history, OTA, etc. - Repository Area for storing programs, etc. - Serverless Events Run the program on the server There are multiple plans available, but you can create an account for free. ## Create an account You can create an account by [sign up](https://console.obniz.com/users/signup). reference page: [account](/reference/cloud/account/) ## Register your device You can register the device you purchased to your account. Turn on the device and go to "Devices" in the cloud console to register it. reference page: [Registration](/reference/cloud/device-management/registration/) --- ## How to use the program editor URL: https://obniz.com/guides/obniz-starter-guide/editor There is an online editor available for free that allows you to edit and execute HTML in your browser. [Open the program editor](https://obniz.com/console/program) ![](images/htmleditor.png?w=835&ssl=1) ## How to use When you open the editor, you will be asked for your obnizID. So, by entering the ID of the device you purchased, you will get a It opens the HTML. You can also run the sample code without editing anything by just running it. ## Execution of the program You can execute the edited HTML in your browser by pressing the "Run" button at the top right of the screen. Otherwise - You can open it in a new tab and run it. - You can download the HTML to your PC and open it in your browser to execute it. --- ## Use internal components URL: https://obniz.com/guides/obniz-starter-guide/use-internal-component There are several electronic components available on the device without the need for LEDs or sensors. Let's use the program first. ## Use the display The obniz Board series and the M5Stick have a screen, which allows you to draw the screen. reference page: [obniz.js display](/reference/common/display/) You can use the following command to draw on the display. ``` obniz.display.print("🧡😁"); ``` --- ## Use parts from the parts library URL: https://obniz.com/guides/obniz-starter-guide/parts-library The SDK, obniz.js, includes programs to manipulate some of the components by default It's easy and convenient to handle. It's easy and convenient to work with, and you can see below what parts are included in the library It is. [parts library](/sdk/parts) ## Buy electronic components The parts library also includes a list of where the part is sold, which you can purchase online or in the store. ## Connecting Electronic Components Each library page also tells you how to connect to the device. For example, if it's an LED [LED](/sdk/parts/LED/README.md) In the section about the function called wired(), you can find instructions on how to connect to the obniz board. In many cases, how to connect to the obniz board is introduced in this book. ![](images/img01.png) reference page: [Use the obniz.js parts](/reference/common/parts/) --- ## Turning on a LED URL: https://obniz.com/guides/obniz-starter-guide/parts-library/turning-on-a-led Connect LED to obniz and turn the LED ON and OFF from your smartphone. ## Connect Did you already configure Wi-Fi? If not, that is what you should do first. Please do so here [QuickStart](/quickstart) ![](images/led_pin.jpg) LED of course lights up by supplying electricity. It has two pins, anode and cathode. Connect anode to the plus plug and cathode to the minus, then the LED should light up. Anode is a bit longer than cathode. Connect anode to obniz io0 and cathode to io1. If you are using LED that is without resistor, you should add a resistor. ## Turn ON LED Open your obniz [ProgramPage](https://console.obniz.com/program). Let's first try to just turn on the LED. Below is the code, which you can copy/paste it onto your program page. ``` LED ``` Change "OBNIZ\_ID\_HERE" ``` var obniz = new Obniz("OBNIZ_ID_HERE"); ``` to your obniz id. For example, if your obniz id is `1234-5678`, it should look like below ``` var obniz = new Obniz("1234-5678"); ``` And run this program by pressing "Run". LED then should get turned ON! ## Control LED using Buttons on HTML Next, let's make ON and OFF buttons on HTML, and control LED using these buttons. Things to do are: 1. Add two buttons 2. Turn the LED ON/OFF from Events First, add two buttons on HTML ``` ON OFF ``` Just like this. Simply add this code to your HTML. You will see two buttons when you open your program. The next step is to ON/OFF the LED from these button through press event. We are going to use jQuery which is available on the program page. The ON button has the attribute`id="on"`. With jQuery, you can set functions to be called when a button is pressed, just like this. ``` $("#on").on("click",function(){ // this function will run when pressed id=on button }); ``` Using this, you can write to make the state of LED change depending on which button is pressed, as shown below. ``` $("#on").on("click",function(){ led.on(); }); $("#off").on("click",function(){ led.off(); }); ``` And that's it! The complete program is shown below. Copy and paste below and change `OBNIZ_ID_HERE` to you obniz id. After running it, you will see two buttons and be able to control LED by pressing the ON/OFF buttons. ``` LED Switch ON OFF ``` Easy? You have now learned how to coordinate the "Web" and "Physical Matters". Let's proceed to the next lesson. ## More You can see the details of LED shown on this page on the link below [https://obniz.com/sdk/parts/LED](/sdk/parts/LED) You will see that more functions are avaiable, not just on() off(). You want to know more about jQuery? Click below. [http://learn.jquery.com/about-jquery/how-jquery-works/](http://learn.jquery.com/about-jquery/how-jquery-works/) --- ## Servo Motor URL: https://obniz.com/guides/obniz-starter-guide/parts-library/servo-motor In this lesson, we will use RC servo motor. ![](images/servomotor.gif) ## Connect Servo motor is listed on the SDK Parts library, the details of which can be seen here: [ServoMotor](/sdk/parts/ServoMotor). First, connect a servomotor to obniz. RC servo motor usually has 3 wires - vcc(+), gnd(-), and Signal(angle control) ![](images/servocable.jpg) Let's connect as below 1. io0 servomotor gnd 2. io1 servomotor vcc 3. io2 servomotor signal It should look ike this ![](images/servomotor.jpg) ## Slider Wouldn't it be super cool if a servo can be controlled from HTML slider!? The slider looks like this. You can slide it with your mouse or finger. Let's add SliderUI to HTML. The slider is indicated by ``. First, add below line to your HTML on top. ``` ``` As noted, the slider is defined by `input type="range"`. Here, the id is "slider". (but you can choose whatever you want to be the id. "slider" is just an example.) min and max define the value range. We want to control the range of the servomotor within 0 and 180 degrees, so `min=0` and `max=180`. Next, we will see how to control changing positions of the slider. ``` $("#slider").on('input', function() { // this function will be called when someone move a slider. var val = $("#slider").val(); }); ``` The program below allows you to know exactly how much the slider has been moved. `$("#slider").val()` gets you the current value of the slider position, which is between 0 and 180. ## Control Servomotor See the details here: [ServoMotor](/sdk/parts/ServoMotor) To change the angle of a servomotor, the necessary program is shown below. ``` var servo = obniz.wired("ServoMotor", {gnd:0, vcc:1, signal:2}); servo.angle(90.0); // half position ``` `servo.angle(90)` means it will change the motor's angle to 90 degrees. The value must be between 0 and 180. This is why it was set so that min is 0 and max is 180! The full code is shown below. ``` ServoMotor ``` Copy&paste this and put in your obniz id. If you run this program, you will see the slider on HTML. Try moving the slider, and you should see your servo motor change its angle. --- ## Get a sensor value URL: https://obniz.com/guides/obniz-starter-guide/parts-library/get-a-sensor-value In this lesson we will learn how to get the Potention Meter's angle from the web. ![](images/c_pm.jpg) ## Connect Potention Meter is a part that changes its resistor value according to its angle or position. obniz can read the resistor value by using AD. As obniz has [Potentiometer](/sdk/parts/Potentiometer), let's use this for programming. Connect the three cables of the potentiometer to obniz io 0, 1, 2. See the image below. ![](images/c_pm.jpg) Let's show the angle on HTML when the angle changes. The steps are: 1. Get the changed angle of the potentiometer 2. Show the angle as text on HTML First, create a meter object. ``` var meter = obniz.wired("Potentiometer", {pin0:0, pin1:1, pin2:2}); ``` And add a function that will be called when the meter's angle changes. ``` meter.onchange =function(position) { }; ``` The variable "position" has a position value. Its value is set between 0 and 1. So, 0.5 means it is half way turned. ## Add DOM Let's add div in the body to print the position. Add the code below to the top of your code. ``` ``` Now we can print a string onto this when the meter gets turned. By using jQuery, texts can be set as below. ``` $("#print").text("Hello") ``` Now the code has been prepared. This way, you can set the content of the id "print" to "Hello". Below is the full code. ``` PotensionMeter ``` Copy&paste this code to the program page, change the obniz id and run the program. How did it go? I believe the letters on the page changed as the meter's angle changed. --- ## Dial controls Servo Motor URL: https://obniz.com/guides/obniz-starter-guide/parts-library/dial-controls-servo-motor Control servo motor in accordance with potention meter. ## Connect Let's use two parts this time. Connect the potentiometer and the servo motor to an obniz. The potention meter should be connected to 0,1,2 and servo motor to 3,4,5. ![](images/potention_servo.jpg) ## Program The program is simple as it is a combination of what we have seen already. This is the full code. ``` Dial To Servo ``` After opening the HTML, the servo motor will move following the potentiometer. Perhaps the servo motor will rotate towards the opposite direction from the potentiometer. How would you change the direction of rotation? Please give it a thought. --- ## Two obniz integration URL: https://obniz.com/guides/obniz-starter-guide/parts-library/two-obniz-integration Let's control servo motor from potentiometer that is connected to another obniz. ![](images/two_obniz.gif) ## Connect This lesson uses two obniz. One is connected to a potention meter, while another is connected to servo motor. Let's control the servo from the potention meter. First, connect a potention meter to obniz io 0,1,2. (let's call it obnizA) Then connect a servo motor to another obniz(obnizB) 1. io0 servomotor gnd 2. io1 servomotor vcc 3. io2 servomotor signal It will turn out like this. ![](images/two_obniz.jpg) ## Program Until this lesson, we used only one obniz per program. This time, we are connecting two obniz to one program. THe simplest way is to connect another obniz after successfully connecting the first obniz. For example, assuming you have obnizA(0000-0000) and obnizB(1234-5678), then it would look like this. ``` var obnizA = new Obniz("0000-0000"); obnizA.onconnect = async function () { var obnizB = new Obniz("1234-5678"); obnizB.onconnect = async function() { // integration here } } ``` This program is attempting to connect obnizB after the connection of obnizA succeeds. And an integration code will be written after connection of obnizB succeeds. This is the simplest way. However, we will face a problem when obnizA gets disconnected. As it reconnects, another obnizB will be created. In this lesson, we will ignore this problem for the time being. Let's keep it simple. Now, where it says "integration here", let's try writing a program in which the potention meter of obnizA moves the servo of obnizB. This is the exact same program as we did last time. The only difference is that the servo's "wired" has become obnizB. ``` Dial to Servo(two obniz) ``` The program would look like above. Copy&paste this to your program page and run it. You now see that there is no need to move the two obniz closer. Everything can be controlled via the Internet even when they are far apart. As long as Wi-Fi is available, you can control servo motor even from other countries. --- ## Use parts by manipulating IO and BLE URL: https://obniz.com/guides/obniz-starter-guide/io-control If you want to connect to a part that is not in your parts library or to some other product via UART or BLE, you can use You will use obniz.js to manipulate IO etc. directly. ## Peripheral operations such as IO-BLE The documentation for each peripheral can be found in the [obniz.js documentation](/reference/common/). For example, for IO You can check from [IO](/reference/common/io/) ## class reference All functions or peripherals in obniz.js, such as IO, have a class reference It's available on GitHub. You can check the arguments and return values of each function that aren't documented in the documentation, and you can use It is. [class reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html) --- ## What is a serverless event? URL: https://obniz.com/guides/obniz-starter-guide/serverless/what-is-serverless With obniz serverless events you can run programs on obniz cloud based on triggers. At a certain time, if a certain webhook gets hit, if obniz comes online. The program can be automatically executed in the cloud based on [multiple triggers](/reference/cloud/serverless-event/triggers/) such as This makes it possible to start the pump in the morning and water it without having the program always open in the browser. You can record changes in temperature around 1 hour. reference: [serverless event](/reference/cloud/serverless-event/) --- ## Run the program at a fixed time. URL: https://obniz.com/guides/obniz-starter-guide/serverless/time-event Production example - [An easy to create serverless program for regular watering](https://blog.obniz.com/en/make/watering-regularly/) ## Make a time report reference: [serverless event](/reference/cloud/serverless-event/) Make a time signal that buzzes regularly. You will need to create an account and register the device to your account. Once you've added it, let's create a program in your repository. Register this program to an event to be called every hour. Press create from the [repository](https://console.obniz.com/repository) and create the HTML with a name (in this case, test) to create the HTML. ![](images/Screen-Shot-2020-05-25-at-215013.png) ## Wiring and Programming First, connect the speakers to the obniz. In this case, I connected the io3 and io9 speakers to the obniz. ![](images/event_alerm.jpg) The program should make a sound every time it is opened without having to press any buttons. ``` ``` Paste this HTML into the HTML you just created (the one you created as a test) and save it. You should hear 1khz sound for 1 second. Event requires that the done() function be called when the process is complete. If it is not called, it will stop automatically after 30 seconds as an error. Since the done function is only present when called by the event, you should check to see if there is a done function, and if there is one, call done. ``` ``` ## Register for the event Creating an event is also done from the "Create New" section of the developer's console. ![](images/Screen-Shot-2020-05-25-at-215233.png) 1. Project Name: The name of the event. Anything. 2. trigger: Select which trigger you want to use. Choose Repetition and set it to 1, then choose your hour. Now every hour. 3. Applications to run: This is where we select which HTML to open and execute when the event occurs. Select "HTML in Repository" and choose the test you just created. When you're done typing, press "Create" to create it. That's it. ### Test run Let's run it for a test run. Press the "Test Run" button on the event screen to run it for a test run. Did you hear a sound? This completes the event setup. From now on, you should hear a sound automatically coming out of the speakers every hour. If things don't work, you can check the execution log on the event screen. You can see the log output from errors and console.log(), etc., and you can use it to check the Check it out. --- ## Integrate with IFTTT via Webhook URL: https://obniz.com/guides/obniz-starter-guide/serverless/webhook The event also has a webhook trigger, which allows you to run the program when a specific URL is called. Various services such as Slack and Facebook support webhooks and will hit the webhooks every time something goes wrong. In this case, [IFTTT](https://ifttt.com/), a service called IFTTT is useful because it can be set up to hit a webhook based on a variety of triggers, so let's use it. ## Manage reminders. What we're going to create is a smartphone reminder (a task management feature on an iPhone, for example) that raises a flag when a task is available and lowers the flag when it's done. We'll create two webhooks 1. Configure IFTTT to hit the Webhook when creating reminders. obniz Event When the webhook comes in, turn the servo motor. 2. Configure IFTTT to hit the webhook on completion of reminders. obniz Event When the webhook comes in, turn the servo motor in the opposite direction. ## Connect the motor. Attach the flag to the servo motor and connect it to the obniz. First, push the button to check if the flag rises and falls properly. ![](images/ifttt_servo.jpg) ``` Up Down ``` If you open it up and run it, I think the motor will spin every time you press UP Down. ### Event Settings Secondly, we need to handle the events. First, we need to make the request body available to the webhook to be registered in IFTTT, and then the so that you can see if the task was created or finished. You can learn how to get the body of a webhook (read more about it [here](/reference/cloud/serverless-event/setup/)) by using the Create a task if body is created, or create a task if body is done as follows We'll assume that the We will register this value later in IFTTT. ``` ``` servo.angle(), and then a wait to wait a little while for the motor to turn properly. It's in there. Once created, create the event. 1. Project Name: Whatever. 2. trigger: Select Webhook. 3. Applications to run: Choose "In Repository" and set the flag to the one you just created. You should see the URL in the Webhooks field. It starts with `https://obniz.com/events`. When this URL is called, the registered flag will be executed. Now, let's register it to IFTTT. ## Register with IFTTT Put the IFTTT app on your iPhone, and choose Create New in My Applets Select the reminder as a trigger. Select Any new reminder. ![](images/ifttt_1.png) Under What to do next, select the webhook. ![](images/ifttt_2.png) Enter the URL from the obniz event into the webhook URL. Set the Method to POST and ContentType to application/json. Create a json named {"created":true} for the Body. (Be careful not to use the double quotation mark "" instead of "". not "".) ![](images/ifttt_3.png) Then, when the reminder task is complete, you can add a {"done":true} Create a webhook to send the json. ![](images/ifttt_5.png) Now you're done. ## Operate So, let's start creating tasks with iPhone reminders. I think the flag will be raised by the motor if you wait a little bit and the IFTTT takes longer to detect the event. So if it's taking too long, launching the IFTTT app will make it easier to detect. If the flag is successfully raised, you can also try completion. Reminders can also be created from Siri and others, which is very useful. You can raise and lower flags with your voice, and Webhooks can do a lot of things with IFTTT alone. It is possible. Please try to create some things. --- ## Run the program on device events URL: https://obniz.com/guides/obniz-starter-guide/serverless/device-event Serverless events can also be triggered by "the device is online" or "a button on the device is pressed".( reference: [trigger](/reference/cloud/serverless-event/triggers/) ) ### Production example - [Power-saving open/close detection device using the obniz board 1Y with sleep function(linked to slack)](https://blog.obniz.io/en/make/obniz-board-1y-open-close-detection/) --- ## HTML/JavaScript URL: https://obniz.com/guides/basics-of-html-and-javascript In lessons, we control obniz by using HTML and javasript. This lesson shows you how to do this. ## HTML is just a text HTML is a document format for browser. It is written with attributions like size of text, location of text, and where to jump when something is clicked. For example, by opening the HTML below, you can see "Hello" on browser. You can do this on the program page on our website, or create a text file, put HTML into it and open it on browser. ```html Hello ``` As you can see, it is enclosed with ``and``, which means "anything between these are HTML". In HTML, an area enclosed by `<>` is considered one block. Browser recognizes this and decides, "Ah, so this is HTML. OK, I will display it". The HTML above shows a minimal composition to display letters. What is actually shown on browser is anything enclosed by `body`. The area enclosed by body gets displayed on screen as it is. ## Attribution HTML has various attributions. For instance, surrounding texts by `` will turn them into bold texts.obniz idTest Open ```html Hello ``` You can specify more attributions by writing more commands. For example, you can change the text color by supplying "style". ```html Hello ``` Besides texts, you can also display images by using ``. Let's try to show [https://obniz.com/images/obnizfront.jpg](./images/obnizfront.jpg)obniz idTest Open ```html Hello ``` This suffices to display an image. Can you see the image? Although `` is not enclosed by ``, some attributions do not require enclosure. All websites are written in HTML like this. You can design websites freely, including the size, color and location of texts, as well as the size and location of images. ## JavaScript Additionally, HTML can contain a program called "JavaScript". A program is an area enclosed by ` ``` You can still see "Hello", but cannot see `console.log("This is JavaScript");` on browser. That is because the area between `script` is recognized as a program by browser. It is thus not just texts but a program to be executed. It is executed line by line from the top. You might wonder what JavaScript can do. First, JavaScript can control HTML. Let's rewrite the HTML above, "Hello", from JavaScript.obniz idTest Open ```html Hello ``` You can see "What's up" on browser. But it still says "Hello" in between the body! Take a closer look at the program. There is a program written in JavaScript `$("strong").text("What's up")`. It means "rewrite texts enclosed by strong to "What's up"". It is thus overwritten by JavaScript to show "What's up", even though it is originally written to display "Hello". This process is not visible anyway and thus redundant. Just providing "What's up" in HTML would have been enough. However, this is just an example to show what JavaScript can do. JavaScript can be connected to the internet to read/write information. It can therefore retrieve news from news websites to display the information within HTML. In this case, it would not be redundant. That was just an introduction. The previous example was on overwriting a HTML text. Let's now try the reverse - controlling JavaScript using HTML.obniz idTest Open ```html Please touch this text ``` You can see "Please touch this text" on browser. By clicking or tapping on this text, it changes into "Touched!". JavaScript would change the text only when someone taps/clicks the text. Just like this, JavaScript can be controlled through HTML as well. You may notice ``. In HTML, you can specify name of an area. JavaScript also uses a name like`$("#here")`, which means an "area which has id=here". So the program works in such a way that if you click id=here, id=here gets changed. `strong` means bold, which you might use more than twice in a single HTML. So it sometimes becomes difficult to identify which lines you want to apply bold to. That is when id becomes useful. ## Incorporating external JavaScript The HTML above has the below line added. ```html ``` It is a JavaScript program called "jQuery", which is hosted on another website. You can see its code by opening [https://code.jquery.com/jquery-3.3.1.js](https://code.jquery.com/jquery-3.3.1.js). It is a very long code. By writing ` Not online ``` `id=here` can be updated to "Online" once connected to the specified obniz. You already know how to handle a program that changes certain texts by clicking/tapping them. So it should be easy to make LED turn on from HTML when certain texts are clicked/tapped.obniz idTest Open ```html Touch to turn on LED ``` By touching "Touch to turn on LED", wired LED will be turned on. You have already done this in LED lesson. If you connect a temperature sensor instead of LED, you could display the current temperature or draw a temperature graph by incorporating JavaScript chart library. --- ## What is a usable UI in a browser? URL: https://obniz.com/guides/run-on-browser/what-is-ui Integrates various browser functions with hardware by running obniz.js in the browser. You can create the following collaborations in one Program. You can create the following federations in one program. - Temperature sensor values are expressed in numbers and drawn in graphs. - Pressing a button on the screen or moving the motor to the position of the mouse - Sending data in the form via UART - Display the image taken by the camera on the screen and other rich, interactive screens and electronic circuits can be combined with JavaScript alone. ## What kind of UI does it have? #### form Forms are a standard part of HTML. reference: [form](https://developer.mozilla.org/ja/docs/Web/HTML/Element/form) Forms allow you to put things on the screen that allow you to manipulate electronic circuits. These include check buttons, sliders, and text entry in input forms. #### graph With [Chart.js](https://www.chartjs.org/), you can easily draw various graphs such as bar charts, pie charts, etc. . It can be used to graph temperature changes and to represent A/D changes and the timing of errors. ![](images/Screen-Shot-2020-05-25-at-205512.png) #### 3D Graphics 3D drawing can be easily performed by using tools such as [Three.js](https://threejs.org/). The situation in reality collected using sensors, such as a graphical representation of the tilt using an accelerometer can be represented on the screen. ![](images/Screen-Shot-2020-05-25-at-210602.png) #### Speech Synthesis/Speech Recognition Some browsers, such as Chrome, can synthesize speech from JavaScript and recognize speech. You can do this. This allows you to create remote controls and talking robots that can be directed by voice. --- ## Form Operated Electronics URL: https://obniz.com/guides/run-on-browser/form ### Production Examples - [The button controls the LEDs.](https://blog.obniz.com/en/make/turn-on-an-led-when-pressing-a-button-block-program/) - [form and character entry](https://blog.obniz.com/en/make/send-text-messages-on-uart/) - [form radio button](https://blog.obniz.com/en/make/radio-button-color-change/) - [form slider](https://blog.obniz.com/en/make/led-slider/) - [form select box](https://blog.obniz.com/en/make/display-the-list-of-ble-devices/) - [form color picker](https://blog.obniz.com/en/make/color-picker-led-change/) --- ## Plotting the temperature on a graph URL: https://obniz.com/guides/run-on-browser/temp-to-graph ### Production Examples - [Real-time temperature graphs](https://blog.obniz.com/en/make/temperature-logger-webapp/) --- ## 3D Graphics URL: https://obniz.com/guides/run-on-browser/3d ### Production Examples - [Press the button to rotate the 3D object.](https://blog.obniz.com/en/make/rotate-a-3d-object-when-pressing-a-button/) --- ## Adjust the style URL: https://obniz.com/guides/run-on-browser/styles Each HTML element can be adjusted in color, shape, etc. by using style sheets. In HTML, each element is made up of an element called the DOM. ``` Hello LED ON ``` When you have this kind of HTML, h1 is a DOM, and so is a button. Also, the body is a single DOM. Style sheets allow you to set up the appearance of each without changing the content. Especially for the HTML, CSS is used. ## CSS Now, let's actually change the previous page. If you use the previous HTML in the obniz program and open it in Safari on a Mac, you see this ![](images/design0.png) This is good enough, but the buttons are also small and a bit hard to press. Let's try to improve this with CSS. ``` Hello LED ON ``` Copy This This is what it looks like when you do this ![](images/design1.png) Hello on h1 is now red and the button is larger. CSS can be written inside a In the case above. 1. The tag "h1" with the text color red 2. Add 50 pixels of padding to the button1 id There are two designs named The design set here is applied to everything in this Html. To find out what kind of settings you can do, check out sites that are familiar with CSS. There are many things you can do with CSS, such as centering, rounded corners, shadows, etc. Reference Site. [https://www.w3schools.com/css/](https://www.w3schools.com/css/) English ## Loading External CSS There are people who create and publish "cool designs" without having to prepare CSS from scratch. You can create a "cool design" simply by importing the CSS into your Html. The famous one is a CSS called bootstrapping, published by Twitter. [http://getbootstrap.com](http://getbootstrap.com) It's free to use. Let's import the published CSS here. ``` Hello LED ON ``` As you can see, is used to load an external CSS file that is open to the public, and the You can apply it with The version 4.1.1 of Twitter's Bootstrap is being loaded here. And we've set the class for the button. For now, if we run it, we'll look like this ![](images/design2.png) It's now stylish. For the button, I added a new class. This makes it look like this blue button. You can see that the CSS for btn and btn-primary classes has a This is what I got from simply writing the class because it's written in the bootstrap. You can see what's available in the CSS and It's on the Component page. Take a look at it. [http://getbootstrap.com/docs/4.0/getting-started/introduction/](http://getbootstrap.com/docs/4.0/getting-started/introduction/) --- ## Importing External Libraries URL: https://obniz.com/guides/run-on-browser/library Various JavaScript can be imported from HTML. Even obniz.js is loaded and running. To import JavaScript from HTML, use the ` ``` You can take in the following. This is on https://unpkg.com/obniz/obniz.js It means to take the JavaScript and run it and make it available. In addition to obniz.js, there are many other libraries available from around the world for various browsers. ## Illustration: moment.js [moment.js](https://momentjs.com/) is a library that simplifies date manipulation. Let's take a look at this library. moment.js is available at the following URL It seems. ``` https://cdn.jsdelivr.net/npm/moment@2.26.0/moment.min.js ``` To get this in, you can include the following Script tag ``` ``` By including this, moment.js can be used from HTML. This makes it easy to display the date in a simple format. ``` ``` --- ## Object Recognition with TensorFlow URL: https://obniz.com/guides/run-on-browser/tensorflow [Tensorflow](https://www.tensorflow.org/js) is a matrix calculation library distributed by Google, which can be run in the browser as well, and can easily perform various image recognition tasks such as face and gesture recognition. ### Production example - [Turn the motor to match the tilt of your head.](https://blog.obniz.com/en/make/move-the-servomotor-tilt-the-head/) - [A doll that matches the movement of the head](https://blog.obniz.com/en/make/puppet-with-tensorflow-js-and-posenet/) - [If I see a cat, I'll ring the buzzer.](https://blog.obniz.com/en/make/buzzer-alerts-when-a-cat-is-caught-on-camera/) --- ## Motor control by voice recognition URL: https://obniz.com/guides/run-on-browser/voicecontol ### Production example - [Voice recognition drives the motor.](https://blog.obniz.com/en/make/speech-for-dcmotor/) - [Use voice recognition to wave a flag when you hear "I'm home](https://blog.obniz.com/en/make/move-servo-motor-by-voice-recognition/) --- ## About Browser App URL: https://obniz.com/guides/browser-app/about By registering programs made of HTML and block programs on the obniz cloud as apps. - No need to enter your obniz ID Create applications that are easy to distribute - Run your programs in the cloud - Ability to record the status of the cloud at runtime - You can have the settings done at the time of app installation You will be able to do things like One of the major advantages of using the app is that you can easily distribute your app to other people and devices through "Find My App", especially since you don't have to write your obnizID in the program. ![](./images/exploreapp.png) Cloud execution can also be saved as an app setting, so if you create and distribute an app that records the temperature at 10am every morning, users can simply install it and use it on the device they installed it on. The cloud-run results of the app's cloud execution can also be displayed to users. ![](./images/app_status.png) --- ## Create an App URL: https://obniz.com/guides/browser-app/create-app (You need to create an account and register your device before you can create an app.) From [app development](https://console.obniz.com/myapps), select [create app](https://console.obniz.com/myapps/create). ![](./images/create-app.png) You can create an app from a template. Choose the programming language you want to use and an app similar to the one you want to create from your device, choose a name and create it. ![](./images/create-app-templates.png) Once created, you will go to the app settings screen. Here you can set up your app, such as the name of the app, the trigger for running the cloud, and more. ![](./images/create-app-config.png) ## Program. You can open the program in the online editor by clicking "Edit Program". For example, if you choose the simplest program in HTML, this is what you get from the beginning. ```html ``` Usually, obniz programs use `OBNIZ_ID_HERE` to insert the obniz ID or set an access token. Therefore, you can't use `option' as the second argument in the app. ```javascript // App Program var obniz = new Obniz("OBNIZ_ID_HERE"); // It will be replaced when run var obniz = new Obniz("0000-0000", {access_token: "XXXXX"}); ``` ### Do it now. The app usually runs on that device after it is installed, but we provide the ability for developers to run the program immediately on the device they specify. When you open the app program, you'll see a list of devices you own in the online editor. It's next to the Run button. From there you can select the obniz ID you want to use and press the Run button to run the program without installing it. ![](./images/create-app-runnow.png) ## Installation. You can install the app on your device. Go to [App Development](https://console.obniz.com/myapps) and choose "Install" for the app and select the device you want to install it on. You can run the installed app in your browser by pressing "Open App". ## Limited link release. Also, if you want to share your app with others, you can get your app's link in Find My App which only people who know the URL can open from "Find My App (URL limited link)" in the app settings. By sharing this URL, you can share your app with other obniz users. ## Update your app. The app program is not copied with each installation. Therefore, you can change the program of the app to use the latest program on all installed devices. There is no need to prompt you to reinstall the program when it changes. --- ## Install setting URL: https://obniz.com/guides/browser-app/install-setting You can prepare settings for the app when you install it. If you prepare these settings in "Installation Settings" in the app settings, you can show them to the user as a required setting during installation. You can set different settings for different users and devices. - The keys of the APIs the user wants to use - Temperature thresholds for sending an email warning The types of settings that can be made are The types you can set are |Type|Description| |---|---| |string| any string| |switch|take true or false| |Radio box|radiobox| | selectbox|pull-down select box| There are four types of Each one is displayed to the user as follows. ![](./images/selections.png) ## Using from a program. Settings can be read with the settings reading function in [obniz.js app](/reference/common/app). All settings are assigned to one object per key. ```javascript var install_configration = Obniz.App.configs(); var water_interval = install_configration['water_interval']; ``` It will be an empty object if it is run from the online editor without being installed. It is a good idea to provide a default value for this, or in case the user never set it. ```javascript var install_configration = Obniz.App.configs(); var water_interval = install_configration['water_interval'] || 30; // default 30 ``` --- ## Cloud Execution by time URL: https://obniz.com/guides/browser-app/evt-cron The browser app can be run in the obniz[cloud](/reference/cloud/app/browserapp-cloudexec) as well as the user's browser. Periodic execution is a setting that allows your app to run in the cloud at regular intervals. ## Configuring Periodic Execution. From the app's settings, under "Cloud Execution", list the time in "Run in Time". The format is as found in [document](/reference/cloud/app/browserapp-cloudexec) - Regular interval: every/10minutes, every/10hours - Every day at a specific time: daily/11:11 You can specify the time in the following way. Installing a configured app will start it automatically for that device. Periodic execution can be used to monitor things that don't change much or to manipulate things that only need to be moved occasionally, as it runs at regular intervals. (Example.) - Watering the plants by moving the pump at regular intervals - Monitor the river level every 30 minutes and email me if there is anything unusual. The following is an example of a pump connected to io0 and io1 that runs at regular intervals. ```javascript var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { var motor = obniz.wired("DCMotor", {forward:0, back:1}); motor.forward(); await obniz.wait(1000); if (Obniz.App.isCloudRunning()) { Obniz.App.done({ status: 'success', text: `Worked` }) } else { alert("Done.") } } ``` Or if you want to throw an API that monitors the temperature and sends an email ```javascript var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { let device = obniz.wired("DHT12",{scl:26,sda:0}); let temperature = await device.getTempWait(); if (Obniz.App.isCloudRunning()) { if(temperature > 30) { try { fetch(`https://xxxxx/xxxxx`) } catch(e) { console.error(e); } Obniz.App.done({ status: 'error', text: `Too hot ${temperature} degree` }) } else { Obniz.App.done({ status: 'success', text: `It's fine ${temperature} degree` }) } } else { alert("Done.") } } ``` --- ## Cloud Execution App Status URL: https://obniz.com/guides/browser-app/appstatus The app status is a mechanism to check the status of your app when you run it in the cloud. Unlike the browser, you can't see the result of cloud execution, so you can check it with the app status. If you don't do anything in the cloud, the program will end at a specified time (depending on the plan) and the timeout will be recorded as the app status. ![](./images/timeout.png) You can update this status from the app program. As you can see in [documentation](/reference/common/app), there is a special function for this purpose. First, it determines whether it is executed in the cloud or not with `Obniz.App.isCloudRunning()`, and updates the app status with `Obniz.App.done()` if it is executed in the cloud. If the app is running in the cloud, it updates the status by `Obniz.App.done()`. Calling `done()' updates the app status and the cloud execution. ```javascript if (Obniz.App.isCloudRunning()) { Obniz.App.done({ status: 'success', text: `It's OK` }) } ``` You can store any string of characters, so you can record the value of the temperature sensor, for example. ```javascript if (Obniz.App.isCloudRunning()) { var temp = '27' Obniz.App.done({ status: 'success', text: `${tmp} degree` }) } ``` You can choose `error` as the status. If it is `error`, it shows an error. ```javascript if(temperature > 30) { Obniz.App.done({ status: 'error', text: `Too hot ${temperature} degree` }) } else { Obniz.App.done({ status: 'success', text: `It's fine ${temperature} degree` }) } ``` --- ## Cloud Execution by webhook URL: https://obniz.com/guides/browser-app/evt-webhook Cloud execution can also be triggered by webhooks, so if something happens on a service like IFTTT or Slack, you can skip the webhook to the obniz app and launch the app. ## Settings. To enable webhooks, go to the app settings, "Cloud Execution" and check "Run with Webhooks". ![](./images/webhook.png) Once you install the enabled app, the webhook URL will appear on the device's admin screen. ![](./images/webhook_url.png) webhooks support GET and POST. ## query and body You can retrieve the query and body (in the case of POST) when the webhook is hit from the program. [documentation](/reference/common/app) ```javascript if (Obniz.App.isCloudRunning()) { const req = Obniz.App.req(); console.log(req.query); console.log(req.body); Obniz.App.done({ status: 'success', text: `Webhook called` }) } ``` --- ## Cloud Execution by device trigger URL: https://obniz.com/guides/browser-app/evt-hardware Cloud execution can be triggered by triggers related to the installed device. - The device is now online. - The device has been switched on (obniz Board / 1Y and M5tickC only) You can choose a trigger such as. You can create an IoT device using a switch as a trigger for other hardware or APIs. Also, you can use device online as a trigger for the sleep function of obniz board 1Y. Sleep=>Wake=>Run=>Run program in cloud=>Sleep again. [see documentation](/reference/cloud/app/browserapp-cloudexec) ## Configuration and Execution. Go to "Cloud Execution" in the app settings and check the one you want to use. By installing that app, you can run the app in the cloud based on the device's triggers. For example, you can make a motion to hit a URL just by pressing a switch. ```javascript if (Obniz.App.isCloudRunning()) { // move a motor for 1 second. try { fetch(`https://xxxxx/xxxx`) } catch(e) { console.error(e); } Obniz.App.done({ status: 'success', text: `Pressed` }) } ``` Or it can be run intermittently in this way in combination with the sleep of obniz Board 1Y. ```javascript if (Obniz.App.isCloudRunning()) { // move a motor for 1 second. var motor = obniz.wired("DCMotor", {forward:0, back:1}); motor.forward(); await obniz.wait(1000); // sleep 1 hour obniz.sleepMinute(60); Obniz.App.done({ status: 'success', text: `Worked and Sleeped` }) } ``` --- ## Publish an App URL: https://obniz.com/guides/browser-app/publish ## Limited link release. If you want to share your app with others, you can get your app's link from "Find Apps (URL-only link)" in the app settings and only people who know the URL can open it. By sharing this URL, you can share your app with other obniz users. ## Open to the public at Find My App In order to open your app to the public and allow anyone to search for it, you will need to have your app reviewed and a plan for doing so. For more information, please contact us. --- ## To run Node.js URL: https://obniz.com/guides/nodejs/how-to-run ## What is Node.js? Node.js is a JavaScript application for running on the PC, not the browser. Software. You can't use obniz unless you have that page open when you run it in a browser, whereas Node .js allows you to run it on your computer or server all the time, so you can use it every hour. You can easily do things like save the temperature to Dropbox. Furthermore, there are plenty of libraries built for Node.js, so it's easy to create a variety of software. It is. **Features.** - Because it runs on a PC or server, the program can run constantly. - You can do a lot of things with the Node.js library. ## Install Nodejs If you're new to Nodejs, the first step is to install Nodejs! [https://nodejs.org/](https://nodejs.org/) You can download it from this site. ## Create Nodejs Project Let's create a Node.js project. The only thing you need to do is create a folder and put one or two files inside it. First, you need to create a folder, which can be any name. The name can be anything, and if you're on Windows, you can use the command line. Then you create the folder from the command line on Windows, or from the shell on Mac or Linux. into ``` npm init ``` and command. You will be asked for various questions, but press Enter and proceed for now. Then there is a package.json in this empty folder. This is the file of the project. Next, we need to prepare app.js to write the app. Prepare an empty text file, name it app.js and save it in this folder . Your project is now complete! ## Install obniz.js Next, install obniz from npm. The browser used to use "" tags to load external programs, but Node.js uses a software called npm to install the software in name only. ``` npm install obniz ``` to run the program. This will download the latest version of obniz.js and allow you to use it from within the program, and you can use I did. ## Coding Let's open app.js in your editor and write the program. First of all, let's import the "obniz.js" program that we just installed. Load the software you installed in Similar to the way it was loaded in the browser with . ``` const Obniz = require("obniz"); ``` That's OK. After this, it's exactly the same as when I was programming in HTML. jQuery is no longer used. So be careful. First connect to obniz. The way they are described is the same. ``` var Obniz = require("obniz"); var obniz = new Obniz("1234-5678"); obniz.onconnect = async function () { } ``` And you can write various programs in onconnect for the same purpose. It's the same as HTML to run a servo motor. ``` var Obniz = require("obniz"); var obniz = new Obniz("1234-5678"); obniz.onconnect = async function () { var servo = obniz.wired("ServoMotor", {gnd:0, vcc:1, signal:2}); servo.angle(90); } ``` You can do it this way. ### Implementation You can run this JavaScript from the command line or from a shell using ``` node app.js ``` and command to run it. And this app will continue to run until you make it stop. To stop, press "Ctrl + C". ## Cooperation with other services There are various packages available on npm. The ability to integrate with other web services is the main difference between npm and HTML. For example, if you're on Twitter. [https://github.com/desmondmorris/node-twitter](https://github.com/desmondmorris/node-twitter) Dropbox. [https://github.com/dropbox/dropbox-sdk-js](https://github.com/dropbox/dropbox-sdk-js) There are libraries such as Let's create various things by integrating these libraries with obniz. --- ## Using AWS Lambda and the API Gateway URL: https://obniz.com/guides/nodejs/aws-lambda ## What is AWS Lamda? This is a serverless system provided by AWS. Serverless means that you don't have to be aware of the machine running the program, such as CPU and memory. It's a philosophy that allows you to run programs. By using this, you can run Nodejs programs without worrying about the server. It is. It's especially good for event-driven execution, which makes it easier to support webhooks, etc., and allows you to create a variety of things with minimal cost. Here is an example of using obniz with AWS Lambda. ![](images/lambda_overview.jpg) ## Creating a Node file First, create a node package to run on lambda and install obniz ``` mkdir obniz_lambda cd obniz_lambda npm install obniz ``` We need "index.js" for lambda, so we'll create that too ``` touch index.js ``` Then, the folder structure looks like this. ![](images/lambda_1.png) In index.js, you need to write the obniz code that you want to run. For example, the following code displays "Hello World" on the display, and drives a servo motor connected to PIN0~2. ``` var Obniz = require("obniz"); exports.handler = function(event, context, callback) { var obniz = new Obniz("YOUR OBNIZ_ID_HERE"); obniz.onconnect = async function () { var servo = obniz.wired("ServoMotor", {gnd:0, vcc:1, signal:2}); servo.angle(90.0); obniz.display.clear(); obniz.display.print("Hello World"); await obniz.wait(500) servo.angle(0.0); obniz.close(); callback(null, "success"); }; }; ``` Replace `YOUR OBNIZ_ID_HERE` with your own obnizID There are several points in the code. It is loaded in `require("obniz").` `exports.handler = function …` you can use lambda to write Creates a function to be used. This function is called when some event occurs (e.g. a web hook or a file is created in S3). We will decide later on when the event is called. `callback(null, "success")`; is a callback function of Node. js is an asynchronous language, so it is necessary to call the callback after the process is finished. You should pay attention to WebSocket. If you don't break the connection, the lambda function will not terminate and will time out, so the You need to call `obniz.close()`; properly ## Configuring AWS Lambda The code is uploaded to Lambda as a zip file, so we create a zip file. This zip file contains the necessary node\_modules and index.js is at the top It is necessary. Be careful not to compress the whole folder by mistake. (index.js comes to a lower level, such as obniz\_lambda/index.js, and is used in (I'll be done.) ``` zip -r obniz_lambda_codes.zip index.js node_modules/ package-lock.json ``` This is the structure of the file. ![](images/lambda_2.png) Access AWS Lambda and log in. [https://aws.amazon.com/console/?nc1=h\_ls](https://aws.amazon.com/console/?nc1=h_ls) ![](images/lambda_3.png) Select the Lambda service and change the region to your preferred location. (In this case, I've chosen Tokyo.) ![](images/lambda_4.png) Press "Create Function". ![](images/lambda_5.png) This time, we are going to build the program from scratch, so we choose "Author from scratch" and fill in the fields. Name : Whatever … I've changed it to "obniz\_lambda". Runtime : Node.js 8.10 Role : Choose an existing role Existing role : lambda\_basic\_execution When you are done, press the "Create Function" button. ![](images/lambda_6.png) In the Function code section, upload the zipped code. Set the code entry type to "Upload a .ZIP file" and add "obniz\_" to the Upload the "lambda\_codes.zip" file. ![](images/lambda_7.png) Don't forget to press the Save button in the upper right corner. If your code is likely to run for more than 3 seconds, you can extend the timeout period by selecting "Basic setting". ![](images/lambda_8.png) So, let's run some tests. Select "Configure test events" from the "select a test event" section When you name the event, create it. You can leave the other fields as they are. ![](images/lambda_9.png) To test it, connect the obniz to the power supply, motor and Wi-Fi. ![](images/lambda_obniz_servo.jpg) Press the "test" button to start the test, and "Hello World" is displayed for a moment in obniz. appears and the servo motor has moved. The screen will show "Execution result : successed. ![](images/lambda_10.png) If this fails, please review your code and settings. In particular, you should pay attention to whether "YOUR OBNIZ CODE" is changed or not, and whether the timeout is appropriate. ## Configuring the AWS API Gateway Although there are many different lambda events, in this article, we will configure the API Gateway to be accessible from the external web. Select "API Gateway" in the Designer, and ![](images/lambda_11.png) "Configure triggers" will appear, and you can fill in the form. - API name: Whatever … The default of "LambdaMicroservice" will be fine. - Deployment stage : Whatever … "prod" defaults are fine. - Security :"Open". You can connect from anywhere without security. ![](images/lambda_12.png) This is what it looks like when you save it ![](images/lambda_13.png) Click on the API Gateway name (in the image, "vbm34885sg") to go to the API Gateway configuration page. However, all the settings are done automatically. ![](images/lambda_14.png) In this state, it is a private API, so we deploy it and make it public. Press Actions → Deploy API. When the modal view appears, set the Deployment stage to "prod" and deploy. ![](images/lambda_15.png) ## Try it from your browser. When you deploy, you will be automatically moved to the "prod Stage Editor". The base address of the entire API is written next to the Invoke URL (in Japanese, the URL call). You can find the URL for lambda in prod → / → /obniz\_lambda → GET page ![](images/lambda_16.png) The URL next to the Invoke URL is the address of the API. If you click on the GET button, the lambda is called, so you can click on it and obniz will start working ## Demo and Code github : [https://github.com/9wick/obniz\_lambda](https://github.com/9wick/obniz_lambda) --- ## Creating a temperature acquisition API URL: https://obniz.com/guides/nodejs/create-an-api ## Expose sensor values as an API Now that we have an endpoint, let's go one step further and api the room's room temperature Connect the LM35 analog temperature sensor like this ![](images/wired.png) We'll create an API that returns this kind of data ``` { "status" : "success", "temperature" : 25.3 } ``` If obniz was not connected, it returns ``` { "status" : "failed", "error" : "Cannot connect to obniz." } ``` So let's write the code. ``` // Runkit Endpoint Example const Obniz = require("obniz"); const express = require("@runkit/runkit/express-endpoint/1.0.0"); const app = express(exports); const yourObnizId = "OBNIZ\_ID\_HERE"; // write your obniz id app.get("/", async (req, res) => { let obniz = new Obniz(yourObnizId); let connected = await obniz.connectWait({timeout:10}); if(connected){ let tempSensor = obniz.wired('LM35', { gnd: 0, output: 1, vcc: 2 }); await obniz.wait(100); //wait for stabilizing let temp = await tempSensor.getWait(); obniz.close(); res.json({ status: "success", temprature : temp}); }else{ res.json({ status: "failed", error : "Caonnot connect to obniz."}); } }); ``` Let's run it and access the URL. The temperature should be measured and a response should be returned. --- ## Cooperation with arduino URL: https://obniz.com/guides/arduino You can power up your programs with arduino by integrating arduino with obniz. What you can do with arduino - Remotely update arduino programs (OTA) - Checking arduino serial logs remotely - Send commands to arduino remotely via serial communication --- ## How to view arduino log with obniz URL: https://obniz.com/guides/arduino/logging ### Hardware Configuration. ![](images/obniz_arduino_(1).png) To connect them, you need to connect the obniz device to the arduino serial The arduino's serial Note that arduino serials have different pin assignments for different devices. ![SerialBaudRate](images/serial_baud_rate.png) [https://www.arduino.cc/reference/en/language/functions/communication/serial/]( https://www.arduino.cc/reference/en/language/functions/communication/serial/) Use these SERIAL PINS (pins to connect to the PC for writing). Connects arduino's serial to obniz's serial. VCC, GND, RX, and TX connections are required. ## Software. ### Checking arduino serial logs remotely All you have to do to see the log is connect uart. Let's write a program. Let's write a program that uses ```javascript var obniz = new Obniz("OBNIZ ID HERE"); obniz.onconnect = async function(){ var baud = 115200; // configration for UNO obniz.uart0.start({tx: 0, rx: 1, baud:baud }); obniz.uart0.onreceive = async function(data, text) { console.log(text); } } ``` ```c void setup() { Serial.begin(115200); } void loop() { Serial.print("Hello"); delay(2000); } ``` The caveat here is that you need to match the communication speed. ![](images/obniz_arduino_(3).png) Serial.begin(115200);` written on the Arduino side is a yellow balloon BaudRate, the `var baud = 115200` written on the obniz side is a blue BaudRate. --- ## How to arduino OTA with obniz URL: https://obniz.com/guides/arduino/ota When you write, you will need two obniz devices. The configuration is that two obniz devices relay the writing of arduino. ### Hardware Configuration. ![](images/obniz_arduino_(2).png) Let's take a look at how to connect specifically. ![SerialBaudRate](images/serial_baud_rate.png) [https://www.arduino.cc/reference/en/language/functions/communication/serial/]( https://www.arduino.cc/reference/en/language/functions/communication/serial/) Use these SERIAL PINS (pins to connect to the PC for writing). Connect the arduino serial to the obniz. VCC, GND, RX and TX are required. ### Write Program. Arudino uses UART for both program writing and serial log. If you use arudino's UART, you will be able to complete writing. Connect the arduino's obniz device and the PC's obniz device. For writing, we need to reset the device at the start of communication, so we'll add that too. ```javascript var obnizA = new Obniz("OBNIZ ID HERE"); //PC-side obniz obnizA.onconnect = async function () { var obnizB = new Obniz("OBNIZ ID HERE"); //Arduino -side obniz obnizB.onconnect = async function(){ var baud = 115200; // configration for UNO obnizA.uart0.start({tx: 0, rx: 1, baud:baud }); obnizB.uart0.start({tx: 0, rx: 1, baud:baud }); obnizB.uart0.start({tx: 0, rx: 1, baud:baud }); obnizB.uart0.start({tx: 0, rx: 1, baud:baud }); // obnizB.uart0.start({tx: 0, rx: 1, baud:baud }); // obnizA.io3.output(false); obnizA.io3.output(false); //USB-UART GND obnizB.io4.output(true); //Arduino Power obnizB.io3.output(false); //Arduino GND obnizB.io2.output(true); //DTR(Arduino Reset) //Arduino GND $("#on").click(function(){ obnizB.io3.output(false); }) $("#off").click(function(){ obnizB.io3.output(true); }) var lastTime = new Date().getTime(); obnizA.uart0.onreceive = async function(data, text) { // PC to arduino obnizB.uart0.send(data); // automatic reset to turn arduino to upload-mode var now = new Date().getTime(); if (now - lastTime > 1000){ obnizB.io2.output(false); obnizB.wait(10); obnizB.io2.output(true); } lastTime = new Date().getTime(); } obnizB.uart0.onreceive = async function(data, text) { // arduino to pc obnizA.uart0.send(data); } } } ``` As a point of caution, you need to match the communication speed. This time, you will find some communication speeds. ![](images/obniz_arduino_(4).png) The `var baud = 115200;` written on the obniz side is the two blue balloons BaudRate. Each device has its own baud rate that can be used for writing, so you must use the Yes. The yellow balloon on the Arduino side and the orange balloon on the PC side are fixed to each device. For example For example, the speed is as follows - arduino UNO : 115200 - arduino Pro : 57600 To find out how fast other boards write, here's a good place to start. [https://github.com/Optiboot/optiboot/blob/master/optiboot/boards.txt](https://github.com/Optiboot/optiboot/blob/master/optiboot/boards.txt) --- ## Full operation URL: https://obniz.com/guides/production In order to use obniz as a commercial service, you need to design the system properly In particular, when controlling multiple obniz devices, it is necessary to manage the connection to each device. Here we will take a specific case study on them. --- ## How to write a secure and trouble-free program URL: https://obniz.com/guides/production/security To run obniz securely and with little trouble, you need to pay attention to some things about how to write the program. ### Publish an access token. Increase the level of security to prevent others from moving obniz without permission. Issuing an access token makes it impossible for anyone who doesn't know this token to access It is. [/reference/cloud/device-management/security-setting/](/reference/cloud/device-management/security-setting/) ### Clarify the behavior when disconnecting and reconnecting If the connection with obniz is lost, no subsequent communication with obniz can take place. If you are using infinite loops for sensing, this part of the process may not be taken into account. You can use `obniz.onloop` to safely manage loops. [/guides/basics-of-html-and-javascript/how-to-loop/](/guides/basics-of-html-and-javascript/how-to-loop/) ### To use obniz in a callback function, check the status of obniz For example, a function that is executed at any point in time, such as when an HTTP request is received, can be called The status of the obniz may be offline. You can't send commands to obniz or parts that are offline, so please check the connection state of `obniz. connectionState === "connected"` before sending commands to obniz and parts. to. ### If the process ends, restart it. It's not limited to obniz, but unexpected errors are common in programs. In order to keep the service running even if an unexpected error occurs, you should use persistent Take advantage of our automation services. Here's a sample program based on the above. ```javascript const Obniz = require("obniz"); initDb(); // Set the access_token. const obniz = new Obniz("obniz_id_here", { access_token:"xxxxxxxxxxx" }) obniz.onconnect = async ()=>{ // Processing at connection (initial settings, etc.) await saveObnizStatusToDb("connected"); const tempSensor = obniz.wired("LM35DZ", { gnd:0 , output:1, vcc:2}); obniz.onloop = async ()=>{ //repetitive processing:Use obniz.onloop to get out of the loop when you're offline const temp = await tempSensor.getWait(); console.log(temp); await saveTempToDb(temp); }; } obniz.onclose = async ()=>{ // Disconnection processing (e.g., resetting callbacks) await saveObnizStatusToDb("disconnected"); } // To use obniz in a callback function, check the state function onSomeCallback(){ if(obniz.connectionState === "connected"){ obniz.display.clear(); obniz.display.print(text); }else{ // What to do when obniz is offline } } function initDb(){ } async function saveTempToDb(temp){ } async function saveObnizStatusToDb(status){ } ``` --- ## AWS EC2: Managing one device on one machine URL: https://obniz.com/guides/production/single-obniz When building a robust system that uses obniz, there are a few things to keep in mind. For example, consider an app that records sensor values in a database on AWS. ![](images/obniz_aws_4.png) In this case, since the connection between obniz↔EC2 is accessed from EC2 to obniz, there is no need to open the port or otherwise allow access to EC2 from the outside. You can integrate with obniz from a closed EC2 while keeping it secure. There are some things to keep in mind in the way you write and execute the program. - Publish an access token. - Clarify the behavior when disconnecting and reconnecting - If the process dies, make sure to restart it. For more information, see our page on [how to write secure and trouble-free programs](/guides/obniz-starter-guide/production/security/). Here's a sample program based on the above. ```javascript const Obniz = require("obniz"); initDb(); // Set the access_token. const obniz = new Obniz("obniz_id_here", { access_token:"xxxxxxxxxxx" }) obniz.onconnect = async ()=>{ // Processing at connection (initial settings, etc.) await saveObnizStatusToDb("connected"); const tempSensor = obniz.wired("LM35DZ", { gnd:0 , output:1, vcc:2}); obniz.onloop = async ()=>{ //repetitive processing const temp = await tempSensor.getWait(); console.log(temp); await saveTempToDb(temp); }; } obniz.onclose = async ()=>{ // Disconnection processing (e.g., resetting callbacks) await saveObnizStatusToDb("disconnected"); } function initDb(temp){ } async function saveTempToDb(temp){ } async function saveObnizStatusToDb(status){ } ``` At run time, use pm2 and run as follows ``` npm install pm2 -g pm2 start ./app.js ``` Since it is persistent, the stop also stops through pm2. ``` pm2 stop app ``` --- ## AWS EC2: Managing multiple devices (2 to 100) on a single machine URL: https://obniz.com/guides/production/multi-obniz Obniz can manage about 100 obniz with a single program by creating a good system. For example, consider an app that records sensor values in a database on AWS. All devices are equivalent, and the sensors are connected to any device for the same purpose, and any device can be used to Suppose you want the same behavior. The system configuration in this case is the same as when dealing with a single obniz. ![](images/obniz_aws_5.png) In this case, since the connection between obniz↔EC2 is accessed from EC2 to obniz, there is no need to open the port or otherwise allow access to EC2 from the outside. You can integrate with obniz from a closed EC2 while keeping it secure. There are some things to keep in mind in the way you write and execute the program. - Publish an access token. - Clarify the behavior when disconnecting and reconnecting - If the process dies, make sure to restart it. For more information, see our page on [how to write secure and trouble-free programs](/guides/obniz-starter-guide/production/security/). In this program, each sensor value is moved independently, so it's simple to use a single unit with When you use it, you should have multiple programs running. There is another way to launch the process, but that would take up excessive resources, so you can use Manage all obniz in one process, up to 100 units in one process It is simple and easy to manage. Here's a sample program based on the above. ```javascript const Obniz = require("obniz"); initDb(); const obnizIdList = [ {obnizId:"obniz_id_1", accessToken: "access_token_1" }, {obnizId:"obniz_id_2", accessToken: "access_token_2" }, {obnizId:"obniz_id_3", accessToken: "access_token_3" }, ... {obnizId:"obniz_id_99", accessToken: "access_token_99" }, ]; for(const targetObniz of obnizIdList){ const obnizId = targetObniz.obnizId; const accessToken = targetObniz.accessToken; // Set the access_token. const obniz = new Obniz(obnizId, { access_token: accessToken }) obniz.onconnect = async ()=>{ // Processing at connection (initial settings, etc.) await saveObnizStatusToDb(obnizId, "connected"); const tempSensor = obniz.wired("LM35DZ", { gnd:0 , output:1, vcc:2}); obniz.onloop = async ()=>{ //repetitive processing const temp = await tempSensor.getWait(); console.log(obnizId, temp); await saveTempToDb(obnizId, temp); }; } obniz.onclose = async ()=>{ // Disconnection processing (e.g., resetting callbacks) await saveObnizStatusToDb(obnizId, "disconnected"); } } function initDb(){ } async function saveTempToDb(obnizId, temp){ } async function saveObnizStatusToDb(obnizId, status){ } ``` At run time, use pm2 and run as follows ``` npm install pm2 -g pm2 start ./app.js --name app ``` Since it is persistent, the stop also stops through pm2. ``` pm2 stop app ``` --- ## AWS Lambda: Manage one obniz with one function URL: https://obniz.com/guides/production/aws-lambda-single It can be useful to use serverless for periodic runs, such as once an hour. There are a few things to keep in mind when combining obniz and serverless. ### Make sure there is no confusion in the startup. One of the features of serverless systems is the ease of multiplexing. It is possible to control one obniz from a program, but there is a limit to the number (1 (up to 5 programs per obniz at the same time), and you need to consider how to write the program. So, we recommend not to use lambda in that way until you have a deeper understanding of it. In other words, you need to control the lambda processes so that they don't start at the same time. In the lambda settings, there is a number of simultaneous executions, so set this to 1. If you do so, an error will occur if you try to start the second one, and it will not start. ![](images/2020-06-22_154300.png) ### Consider the time limit. After the lambda function is launched, the connection and authentication to obniz is performed, so the time required to connect and authenticate to obniz will be reduced by It may take about 1 second to connect to obniz, so you may have to wait for a few more seconds to get the data. I recommend that you allow about 5 seconds for the time of ![](images/2020-06-22_154243.png) ### Consider if you can't connect. obniz is not always online, and depending on the signal conditions, it may be offline It is also possible that you have You need to program for the possibility of being offline. ### Specific implementation For example, let's say you are using AWS lambda to retrieve data from a temperature sensor. ![](images/obniz_aws_11.png) The devices are automatically connected from lambda, so there is no need to put in place an API gateway or anything like that There is no such case. Please put it on the case that you want to access it by URL separately. ``` const Obniz = require("obniz"); exports.handler = async (event) => { // Disable auto_connect to connect manually const obniz = new Obniz("obniz_id_hiere", {auto_connect: false, access_token: targetObniz.accessToken}); // Connect to obniz. If it doesn't connect within 3 seconds, it will time out. const connected = await obniz.connectWait({ timeout: 3 }); if (!connected) { // How to handle obniz when it is off-line const response = { statusCode: 404, body: JSON.stringify({error: "obniz is not online"}), }; return response; } //initialization const tempSensor = obniz.wired("LM35DZ", { gnd:0 , output:1, vcc:2}); const temp = await tempSensor.getWait(); //Disconnect from obniz on exit (if you don't do this, you'll still have a connected session) obniz.close(); const response = { statusCode: 200, body: JSON.stringify({temp}), }; return response; }; ``` --- ## AWS Lambda: Manage multiple obniz with one function URL: https://obniz.com/guides/production/aws-lambda-multi Serverless is convenient for regular runs, but there is some network response wait time, such as connecting to obniz, which is a waste of money. To solve that, let's manage multiple obniz with a single lambda function. The prerequisites are the same as for one car. - Make sure there is no confusion in the startup. - Consider the time limit. - Consider if you can't connect. For more information, see [AWS Lambda: Managing one obniz with 1 function](/guides/obniz-starter-guide/production/aws-lambda-single/) ![](images/obniz_aws_10.png) The way the program is written changes a bit. Create an instruction function for one obniz as oneTask and complete the process in that function to do. Run it for a few minutes of obniz and wait until it's all done in `Promise.all` I will. ``` const Obniz = require("obniz"); const obnizIdList = [ {obnizId: "obniz_id_1", accessToken: "access_token_1"}, {obnizId: "obniz_id_2", accessToken: "access_token_2"}, {obnizId: "obniz_id_3", accessToken: "access_token_3"}, ... {obnizId: "obniz_id_99", accessToken: "access_token_99"}, ]; // For one obniz async function oneTask(targetObniz) { const obniz = new Obniz(targetObniz.obnizId, {auto_connect: false, access_token: targetObniz.accessToken}); try { const connected = await obniz.connectWait({timeout: 3}); if (!connected) { return new Error("obniz " + targetObniz.obnizId + " is not online"); } const tempSensor = obniz.wired("LM35DZ", {gnd: 0, output: 1, vcc: 2}); const temp = await tempSensor.getWait(); obniz.close(); } catch (e) { return e; } return null; } exports.handler = async (event) => { let tasks = []; for (const targetObniz of obnizIdList) { tasks.push(oneTask(targetObniz)); } let results = await Promise.all(tasks); for (const result of results) { if (result) { const response = { statusCode: 500, body: JSON.stringify({status: "error", error: result}), }; } } const response = { statusCode: 200, body: JSON.stringify({status: "success"}), }; return response; }; ``` --- ## Extend OS with Plugin URL: https://obniz.com/guides/plugin ## What is a Plug-in? Plug-in is to create an obnizOS that contains a user-created program and operate it on a device (plug-in OS), instead of operating it via the cloud. This enables the development of the following software that cannot be handled by the existing obnizOS alone. - Fast and accurate IO operations that are not affected by network delays - Program offline behavior - Arduino libraries can be used for development with ArduinoIDE ## How to develop Create the program you want to run in the Arduino IDE. You can use the plug-in by putting it into the device you want to run. The created plugin OS supports OTA from obnizCloud as well as USB writing from Arduino IDE, and OTA processing is done by cloud and obnizOS, so you don't need to develop software for it. [obnizOS plugin](/reference/obnizos-for-esp32/plugin/) ![](./images/system.png) ## The relationship between obnizOS and plugins The program will "use obnizOS" from the software you create. You can start and stop obnizOS from the software you create. However, if obnizOS is not running, you cannot use OTA, device management, IO control, and other functions available in obniz. When you start obnizOS, it will create a new task. By doing this, obnizOS will run while the plug-in continues to run. In obnizOS, when you connect to the network or go offline, an event is generated, which can be retrieved by the plug-in. See the reference for details. ```c++ // Example #include . void setup() { Serial.begin(115200); obniz.start(); } void loop() { } ``` ## Sample projects Example plug-ins for M5ATOM and M5ATOM Lite are available. - Wi-Fi connection status display with LED - button to enter device setting mode This is an example. [https://github.com/obniz/obniz-plugin-atom](https://github.com/obniz/obniz-plugin-atom) --- ## Getting Start URL: https://obniz.com/guides/plugin/io ## Build the environment Please see the reference for environment construction. [obnizOS plugin](/reference/obnizos-for-esp32/plugin/) ## Using obnizOS obnizOS will not start automatically. It is started by calling `obniz.start()`. The following is the least complicated program. Once started, obniz will automatically retrieve the device key and connect to the cloud using Wi-Fi or other means. ```c++ // Example #include void setup() { Serial.begin(115200); obniz.start(); } void loop() { } ``` After writing and starting operation from the ArduinoIDE, you need to set the device key from the serial monitor if it is the first device to be written. [Devicekey install](/reference/obnizos-for-esp32/quick-start/#configuration-from-a-terminal) After setting up the device key, you will also need to configure the network. [obnizOS Setting](/reference/obnizos-for-esp32/settings/) ## Using IO The following will be a program that repeatedly turns IO on and off. Since all IOs are managed by obniz, you need to remove IOs from the management of obnizOS by `obniz.pinReserve()` and occupy them with plugins before using them. After that, the operation is no different from the ESP32 program for Arduino. In the following example, IO 12 turns on and off every 0.5 seconds, so if you connect an LED, it will blink regardless of obnizOS. ```c++ #include void setup() { Serial.begin(115200); obniz.start(); obniz.pinReserve(12); pinMode(12, OUTPUT); } void loop() { digitalWrite(12, HIGH); delay(500); digitalWrite(12, LOW); delay(500); } ``` Let's write this code to the ESP32 board using the ArduinoIDE in [build environment](/reference/obnizos-for-esp32/plugin/arduino-ide). Although it is not used this time, pin 12 cannot be controlled from the obniz.js side. This is to prevent obnizOS from resetting the board at an unintended time and losing control. --- ## Receive an Event URL: https://obniz.com/guides/plugin/event Next, we will create a program that will receive an event from obnizOS when we go online and light up the LED when we are online. ## event By using `obniz.onEvent()`, you can make it call a function when it is triggered to connect to the Internet or to the cloud. If you have an ESP32-DevKitC and an LED, connect the anode of the LED (the longer leg) to pin 12 and the cathode of the LED (the shorter leg) to GND. ```c++ #include #define LED_IO 12 bool onlineFlg = false; void onEvent(os_event_t event, uint8_t* data, uint16_t length) { switch (event) { case PLUGIN_EVENT_NETWORK_CLOUD_CONNECTED: Serial.println("cloud Connected"); onlineFlg = true; break; case PLUGIN_EVENT_NETWORK_CLOUD_DISCONNECTED: Serial.println("cloud Disconnected"); onlineFlg = false; break; } } void setup() { Serial.begin(115200); Serial.println("online led start!"); obniz.onEvent(onEvent); obniz.start(); obniz.pinReserve(LED_IO); pinMode(LED_IO, OUTPUT); } void loop() { digitalWrite(LED_IO, onlineFlg); delay(500); } ``` Let's write this code to the ESP32 board using the ArduinoIDE in [environment](/reference/obnizos-for-esp32/plugin/arduino-ide). Make sure you are connected to the network in advance. After a while, you should see "cloud Connected" on the serial monitor and the LED should light up. This time, we are only using the event when we are able to connect to the obniz cloud, but there are several other events as well. Please refer to the documentation for details. --- ## Transmit/Receive Datas URL: https://obniz.com/guides/plugin/extention Let's create an extension using a specific plugin. We will use Uart to create a program that sends data to obnizCloud only when there is an error. By using the plugin, we can reduce the communication capacity, which has been difficult with obniz so far, and eliminate data loss at high communication speeds. ## Sending and receiving data The plugin includes - Send data to obnizCloud - Receiving data from obnizCloud There are two functions. On the plugin side, you can send and receive data as follows. ```c++ #include // on data received from obnizCloud. void onCommand(uint8_t* data, uint16_t length){ Serial.println("\nonCommand"); Serial.write(data,length); } void setup() { Serial.begin(115200); obniz.start(); // receive data from obnizCloud obniz.commandReceive(onCommand); } void loop() { if (obniz.isOnline()) { uint8_t *text = "Hello"; obniz.commandSend(text, strlen(text)); // send data to obnizCloud delay(1 * 1000); } } ``` You can also use obniz.js to send and receive data to and from plugins as follows. ```javascript // receive from target device obniz.plugin.onreceive = data => { console.log(data); }; // send to target device obniz.plugin.send("obniz.js send data get device?") ``` ## Example of using UART In this example, we use the obniz board as the communication partner for the Uart, but in actual use, it will be the respective device. First, let's look at the plug-in code. When the obniz board is online, it reads the Uart and sends a message as `a` for correct data and `b` for abnormal data. The connection method is as follows. ESP32-DevKitC | obniz Board :---: | :---: 16(Rx) | 0(TX) GND | 3(GND) ```c++ #include void setup() { Serial.begin(115200); obniz.start(); //RX:16 TX:17 obniz.pinReserve(16); obniz.pinReserve(17); Serial2.begin(115200); } void loop() { if (obniz.isOnline()) { if (Serial2.available()) { uint8_t inByte = Serial2.read(); Serial.write(inByte); if(inByte != 'a'){ Serial.print(" Error"); obniz.commandSend((uint8_t*)&inByte,1); } Serial.println(""); } } } ``` Next comes the obniz.js code. There are two buttons, one sends the Uart correctly, and the other generates an error. When an error occurs, the console is notified that an error has occurred. You can also check the serial monitor in the Arduino IDE to see the data received. ```html Uart Serial OK Uart A send Error Uart B send ``` This is a test using a button, but I hope you get the idea. If we program the plugin, we can easily change the processing depending on the data and send a message to obniz.js. In this way, communication capacity can be reduced and data can be exchanged at high speed. Please try using plugins. --- ## Plugin Key and OTA URL: https://obniz.com/guides/plugin/ota For more details, please see the following. [Plugin OTA](/reference/obnizos-for-esp32/plugin/ota) The created plug-ins can be registered in the cloud as "obnizOS (plug-in OS) with plug-ins" and can be written from the cloud to the device via the Internet. 1. register to the cloud and generate a key 2. set the key in the plug-in program and build it ```c obniz.setKey("1EfR9nLYGVOkWKP1nf9V8fKEPM194je4"); obniz.onEvent(onEvent); obniz.start(); ``` 3. Register the built plug-in OS to the cloud again. 4. write to the device via OTA from device management --- ## Long Term Operation on Battery URL: https://obniz.com/guides/battery-long-life The obnizBoard 1Y can operate continuously on AA batteries for up to one year by using the Sleep function to reduce battery consumption at unnecessary times. This feature is only available on obnizBoard 1Y. obniz Board and M5StickC It's not available on the obnizOS version. ### Get sensor values only once a day. For example, let's say you only measure the temperature once a day and store it in the cloud. obniz device is up and running once a day is enough, and there is nothing to do during the lumpy hours. By Sleeping in this do-nothing time, you can reduce battery consumption. And after a period of time, it will automatically start up to measure the temperature again. ![](images/a9c9087317e9a084036b9c80bf8b9085.png) ``` obniz.onconnect = async function(){ var tempsens = obniz.wired("LM61", { gnd:0 , output:1, vcc:2}); var temp = await tempsens.getWait(); console.log(temp); //output tempeature obniz.sleepMinute(60*24); // one day sleep } ``` Using sleepMinute allows you to sleep for a specified amount of time, and when sleep is started, it automatically starts to The connection to obniz will be severed and it will enter the sleep state. The obnizBoard 1Y looks the same as it does when it is not connected to the power supply, and there is nothing on the screen It will no longer be possible. ![](images/IMG_9810.jpg) Sleep中のobnizBoard 1Y After the specified time has passed (24 hours in this case), it will automatically release the sleep state, make a wifi connection and call the program onconnect. ### Activated by an external stimulus. In addition to sleep until the time is up, external factors such as "a button was pressed" or "a person came" are also considered to be You can also use triggers to cancel Sleep. ![](images/3e5d6ae8d7d9e4186cedf4edd855e77f.png) On the obnizBoard 1Y, io0 is a special pin that can be used to break the sleep state by changing the voltage on this pin. ``` obniz.onconnect = async function(){ var tempsens = obniz.wired("LM61", { gnd:0 , output:1, vcc:2}); var temp = await tempsens.getWait(); console.log(temp); //output tempeature obniz.sleepIoTrigger(true); // wake up when rising edge on io0 } ``` sleepIoTrigger wakes up from sleep when io0 changes from 0V to 5V. When the button is not pressed, the voltage is 0V when the button is pressed, and when the button is pressed, the voltage is 5V. When the button is pressed, the sleep state is released and the device starts up.  By devising a sensor, you can also create a program that will send a notification to slack when a door is opened to release sleep. https://blog.obniz.com/en/make/obniz-board-1y-open-close-detection/ --- ## What is Sleep Action? URL: https://obniz.com/guides/battery-long-life/what-is-sleep The sleep function is one of the ways to reduce battery consumption. When you go to sleep, instead of not being able to do all of io's output, communication, etc., it reduces battery consumption. You can #### What you can do while you're asleep - Waking up after a specific time - Awake when there is a specific voltage input #### What you can't do while in sleep. - Pin to output - Obtaining sensor data - Move the actuator. - Communicate with obniz cloud - Check the status in obniz cloud - Display The obnizBoard 1Y can operate continuously on AA batteries for about a year by using a good sleep function. This feature is only available on obnizBoard 1Y. obniz Board and M5StickC It's not available on the obnizOS version. --- ## Regular execution URL: https://obniz.com/guides/battery-long-life/intervally For example, let's say you only measure the temperature once a day and store it in the cloud. obniz device is up and running once a day is enough, and there is nothing to do during the lumpy hours. By Sleeping in this do-nothing time, you can reduce battery consumption. And after a period of time, it will automatically start up to measure the temperature again. ![](images/a9c9087317e9a084036b9c80bf8b9085.png) ``` obniz.onconnect = async function(){ var tempsens = obniz.wired("LM61", { gnd:0 , output:1, vcc:2}); var temp = await tempsens.getWait(); console.log(temp); //output tempeature obniz.sleepMinute(60*24); // one day sleep } ``` sleepMinute allows you to sleep for a specified amount of time. the connection to obniz will be automatically severed and the system will enter the sleep state. The state of the obnizBoard 1Y will look the same as it did when it was not connected to the power supply, and there will be nothing on the screen It will not be displayed. ![](images/IMG_9810.jpg) ObnizBoard 1Y in Sleep After the specified time has passed (24 hours in this case), it will automatically release the sleep state, make a wifi connection and call the program onconnect. --- ## Wakeup on sensor changes URL: https://obniz.com/guides/battery-long-life/sensor-wakeup "An external factor, such as a button being pressed or a person coming to the house, can trigger the release of Sleep. You can. ![](images/3e5d6ae8d7d9e4186cedf4edd855e77f.png) On the obnizBoard 1Y, io0 is a special pin that can be used to break the sleep state by changing the voltage on this pin. ``` obniz.onconnect = async function(){ var tempsens = obniz.wired("LM61", { gnd:0 , output:1, vcc:2}); var temp = await tempsens.getWait(); console.log(temp); //output tempeature obniz.sleepIoTrigger(true); // wake up when rising edge on io0 } ``` sleepIoTrigger wakes up from sleep when io0 changes from 0V to 5V. When the button is not pressed, the voltage is 0V when the button is pressed, and when the button is pressed, the voltage is 5V. When the button is pressed, the sleep state is released and the device starts up.  By devising a sensor, you can also create a program that will send a notification to slack when a door is opened to release sleep. https://blog.obniz.com/en/make/obniz-board-1y-open-close-detection/ --- ## Flashing obnizOS URL: https://obniz.com/guides/device-create You can convert your device to an obniz by writing an obnizOS and a device key (obnizID) to your ESP32 or a device that is using ESP32. There is a monthly fee for issuing an ID, depending on the number of devices.( [price list](https://iot.obniz.com/pricing) )。 ![](images/product_ESP32.jpg) ## Writing of OS and device key (obnizID) If you don't have a device on hand, you must first select a device and purchase it. The choice is made by [selecting the device processor](/guides/obniz-starter-guide/device-create/processor-selection/). Next, you need to issue an obnizID and write it to the device with the OS. Connect the device to your PC by serial communication and write to the device by [using a software called "obniz-cli"](/guides/obniz-starter-guide/device-create/obniz-cli/). --- ## Processor ・ device URL: https://obniz.com/guides/device-create/processor-selection obnizOS for ESP32 runs on the following processors from Espressif - ESP32 - ESP32-PICO It can work on devices with them, but the following devices in particular require the dedicated obnizOS It is available. So it supports the on-board screen, so you can see the obniz logo on the start-up and You can use features such as a button to bring up the settings screen. - M5StickC --- ## Create and configure devices with obniz-cli URL: https://obniz.com/guides/device-create/obniz-cli [obniz-cli](https://github.com/obniz/obniz-cli) is a CLI tool for writing and configuring obnizOS. It can be used from the shell to do the following - Writing in obnizOS - Sign in to the cloud and create a device - Writing a DeviceKey by specifying an obnizID - Network settings such as Wi-Fi With obniz-cli, you can create devices and set up WiFi with just one command, which makes it easy to create a large number of devices. For example, the following command will create the device (with description) => Write OS=>WiFi configuration. ``` obniz-cli os:flash-create -p /dev/tty.USBSERIAL --description "Installed in Plant A" --config ./wifi-config.json ``` reference: [Install obnizOS](/reference/obnizos-for-esp32/quick-start/) --- ## BLE Location Service URL: https://obniz.com/guides/ble-location-service With obniz, you can place the program on a server such as AWS EC2 and access nearby BLE devices through multiple obniz BLE/Wi-fi gateways. By distributing obniz BLE/Wi-fi gateways, you can see which gateway the BLE device was close to. ![](./images/system.png) In the past, the BLE device information had to be installed on each gateway, but with obniz, only the server in the cloud needs to keep the information. Therefore, the - Additional BLE devices are available. - Ready to expand the area by adding a gateway Features such as. --- ## Send the beacon scan results to the server URL: https://obniz.com/guides/ble-location-service/scan-and-send-data-from-1-obniz If you are using only one obnizBLEGateway, the system will be simple. The system configuration would look like this ![](./images/system-single.png) A single obniz device can be used to detect multiple BLE Beacon devices. The basic flow of the program is as follows 1. Establish a connection to multiple obniz devices. 2. Initialize the BLE system 3. Start scan for peripheral BLE devices 4. Save the scan results to a database or other location 5. Repeat 3 to 4. Here's what it looks like in concrete terms. ```javascript const Obniz = require('obniz'); var obniz = new Obniz("OBNIZ_ID_HERE"); // Establish a connection to multiple obniz devices. obniz.onconnect = async function () { //Initialize the BLE system await obniz.ble.initWait(); obniz.ble.scan.onfind = async function(peripheral){ console.log(peripheral.localName); // Save the scan results to a database or other location sendToDatabase(peripheral); }; obniz.ble.scan.onfinish = async function(peripherals, error){ console.log("scan timeout!") // Start scan for peripheral BLE devices await obniz.ble.scan.startWait(); }; // Start scan for peripheral BLE devices await obniz.ble.scan.startWait(); } function sendToDatabase() { } ``` By customizing the above program, you can have more detailed control. Please refer to [How to use BLE](/reference/common/ble/) in obnizjs to customize the program. For example, here are some articles that can help you - If you want to narrow down your scan results Set ScanTarget in [conditional search](/reference/common/ble/central-scan#conditional-search) - I want to reduce the amount of communication. [Filter by device to reduce traffic](/reference/common/ble/central-scan-filter#filtering-on-devices-to-reduce-traffic) E3%82%A3%E3%83%AB%E3%82%BF%E3%83%AA%E3%83%B3%E3%82%B0%E3%82%92%E3%81%97%E3%81%A6%E9%80%9A%E4%BF%A1%E9%87%8F%E3%82%92%E5%89%8A%E6%B 8%9B%E3%81%99%E3%82%8B) - I want to scan all the time, not just every 30 seconds. Set up ScanSetting in [conditional search](/reference/common/ble/central-scan#conditional-search) - I want to receive multiple advertisements from the same device Set up ScanSetting in [conditional search](/reference/common/ble/central-scan#conditional-search) The basic flow of the program is as follows Establish a connection with an obniz device 2. initialize the BLE system 3. perform a scan for peripheral BLE devices 4. save the scan results to a database or other location 5. repeat 3 to 4. --- ## Extend the area with multiple obniz devices URL: https://obniz.com/guides/ble-location-service/scan-and-send-data-from-multi-obniz When using multiple obnizBLEGateway, the system will still be able to use It is almost the same as the case of a single unit. The system configuration looks like this ![](./images/system.png) The basic program flow is as follows: 1. Establish a connection to multiple obniz devices. 2. initialize the BLE system 3. start scan for peripheral BLE devices 4. save the scan results to a database or other location 5. repeat 3 to 4. Here's what it looks like in concrete terms. ```javascript const Obniz = require('obniz'); var obnizIdList = [ "OBNIZ_ID_A_HERE", "OBNIZ_ID_B_HERE", "OBNIZ_ID_C_HERE", "OBNIZ_ID_D_HERE" ] for(let obnizId of obnizIdList){ var obniz = new Obniz(obnizId); // Establish a connection to multiple obniz devices. obniz.onconnect = async function () { //initialize the BLE system await obniz.ble.initWait(); obniz.ble.scan.onfind = async function(peripheral){ console.log(peripheral.localName); // save the scan results to a database or other location sendToDatabase(peripheral); }; obniz.ble.scan.onfinish = async function(peripherals, error){ console.log("scan timeout!") // start scan for peripheral BLE devices   await obniz.ble.scan.startWait(); }; // start scan for peripheral BLE devices await obniz.ble.scan.startWait(); } } function sendToDatabase() { } ``` Can you see that the program is almost the same as the one used for one unit? By customizing the above program, you can have more detailed control. Please refer to [How to use BLE](/reference/common/ble/) in obnizjs to customize the program. For example, here are some articles that can help you - If you want to narrow down your scan results Set ScanTarget in [conditional search](/reference/common/ble/central-scan#conditional-search) - I want to reduce the amount of communication. [Filter by device to reduce traffic](/reference/common/ble/central-scan-filter#filtering-on-devices-to-reduce-traffic) E3%82%A3%E3%83%AB%E3%82%BF%E3%83%AA%E3%83%B3%E3%82%B0%E3%82%92%E3%81%97%E3%81%A6%E9%80%9A%E4%BF%A1%E9%87%8F%E3%82%92%E5%89%8A%E6%B 8%9B%E3%81%99%E3%82%8B) - I want to scan all the time, not just every 30 seconds. Set up ScanSetting in [conditional search](/reference/common/ble/central-scan#conditional-search) - I want to receive multiple advertisements from the same device Set up ScanSetting in [conditional search](/reference/common/ble/central-scan#conditional-search) The basic flow of the program is as follows Establish a connection with an obniz device 2. initialize the BLE system 3. perform a scan for peripheral BLE devices 4. save the scan results to a database or other location 5. repeat 3 to 4. --- ## HTML/JavaScript URL: https://obniz.com/guides/basics-of-html-and-javascript In lessons, we control obniz by using HTML and javasript. This lesson shows you how to do this. ## HTML is just a text HTML is a document format for browser. It is written with attributions like size of text, location of text, and where to jump when something is clicked. For example, by opening the HTML below, you can see "Hello" on browser. You can do this on the program page on our website, or create a text file, put HTML into it and open it on browser. ```html Hello ``` As you can see, it is enclosed with ``and``, which means "anything between these are HTML". In HTML, an area enclosed by `<>` is considered one block. Browser recognizes this and decides, "Ah, so this is HTML. OK, I will display it". The HTML above shows a minimal composition to display letters. What is actually shown on browser is anything enclosed by `body`. The area enclosed by body gets displayed on screen as it is. ## Attribution HTML has various attributions. For instance, surrounding texts by `` will turn them into bold texts.obniz idTest Open ```html Hello ``` You can specify more attributions by writing more commands. For example, you can change the text color by supplying "style". ```html Hello ``` Besides texts, you can also display images by using ``. Let's try to show [https://obniz.com/images/obnizfront.jpg](./images/obnizfront.jpg)obniz idTest Open ```html Hello ``` This suffices to display an image. Can you see the image? Although `` is not enclosed by ``, some attributions do not require enclosure. All websites are written in HTML like this. You can design websites freely, including the size, color and location of texts, as well as the size and location of images. ## JavaScript Additionally, HTML can contain a program called "JavaScript". A program is an area enclosed by ` ``` You can still see "Hello", but cannot see `console.log("This is JavaScript");` on browser. That is because the area between `script` is recognized as a program by browser. It is thus not just texts but a program to be executed. It is executed line by line from the top. You might wonder what JavaScript can do. First, JavaScript can control HTML. Let's rewrite the HTML above, "Hello", from JavaScript.obniz idTest Open ```html Hello ``` You can see "What's up" on browser. But it still says "Hello" in between the body! Take a closer look at the program. There is a program written in JavaScript `$("strong").text("What's up")`. It means "rewrite texts enclosed by strong to "What's up"". It is thus overwritten by JavaScript to show "What's up", even though it is originally written to display "Hello". This process is not visible anyway and thus redundant. Just providing "What's up" in HTML would have been enough. However, this is just an example to show what JavaScript can do. JavaScript can be connected to the internet to read/write information. It can therefore retrieve news from news websites to display the information within HTML. In this case, it would not be redundant. That was just an introduction. The previous example was on overwriting a HTML text. Let's now try the reverse - controlling JavaScript using HTML.obniz idTest Open ```html Please touch this text ``` You can see "Please touch this text" on browser. By clicking or tapping on this text, it changes into "Touched!". JavaScript would change the text only when someone taps/clicks the text. Just like this, JavaScript can be controlled through HTML as well. You may notice ``. In HTML, you can specify name of an area. JavaScript also uses a name like`$("#here")`, which means an "area which has id=here". So the program works in such a way that if you click id=here, id=here gets changed. `strong` means bold, which you might use more than twice in a single HTML. So it sometimes becomes difficult to identify which lines you want to apply bold to. That is when id becomes useful. ## Incorporating external JavaScript The HTML above has the below line added. ```html ``` It is a JavaScript program called "jQuery", which is hosted on another website. You can see its code by opening [https://code.jquery.com/jquery-3.3.1.js](https://code.jquery.com/jquery-3.3.1.js). It is a very long code. By writing ` Not online ``` `id=here` can be updated to "Online" once connected to the specified obniz. You already know how to handle a program that changes certain texts by clicking/tapping them. So it should be easy to make LED turn on from HTML when certain texts are clicked/tapped.obniz idTest Open ```html Touch to turn on LED ``` By touching "Touch to turn on LED", wired LED will be turned on. You have already done this in LED lesson. If you connect a temperature sensor instead of LED, you could display the current temperature or draw a temperature graph by incorporating JavaScript chart library. --- ## obniz First Program URL: https://obniz.com/guides/basics-of-html-and-javascript/first-program Use obniz from your program. ## Online HTML editor Let's write a simple program to use obniz. With obniz.js it becomes easy to use obniz from JavaScript. Each obniz has one free HTML. Let's try using it to write a JavaScript program! To open that HTML, enter developer's console on the navigation above this page. ![](images/console_location.png) Then, open the program page by pressing the "program". ![](images/program_location.png) The page will ask for your obniz id, so please put it in. Then the HTML will appear. This same page can also be accessed by scanning the QR code. Now you are able to edit and save the HTML. Write a JavaScript on it and run it by opening the HTML on your browser. The HTML is saved on this site. Any changes are saved automatically. You can open the same page even on your smartphone. Let's try writing a program! As this would be your first time, let's just use the display on obniz. Shown below is a sample program. Copy this sample program( HTML ) and paste to your program page. Also, replace `` to your obniz id such as "1234-5678". ``` ``` Is everything OK? If so, let's save the program and open it again to run it. Press "Run" button, which will save the HTML on the web and open it in iFrame. A browser will open the HTML and run the JavaScript embedded in the HTML. This is how obniz coordinates with browser. The URL on the left of the "Run" button is the URL for the HTML you are editing. This can be opened on different tabs and even on smartphones. ![](images/firstprogram_1.png) Within the program page, HTML you wrote on iFrame can be opened. In your HTML, a green bar should appear on top of the page once its connection with obniz is established, and "Hellow World" should appear on obniz. iFrame can be closed by pressing the "End" button on the top left corner. ![](images/firstprogram_2.png) "Show console" button is at the bottom of the iFrame page. ``` obniz.onconnect = async function () { obniz.display.clear(); obniz.display.print("Hello World!") console.log("hello: " + new Date()) }; ``` In the example above, console.log() will print "hello: " and the current time. This is same as the browser's debugging console. ![](images/firstprogram_3.png) If something is wrong on your program, an error will also be shown here. ``` obniz.onconnect = async function () { obniz.display.clear(); obniz.display.print("Hello World!") SomethingWrong()(); }; ``` When you run a program with error like above, you will see an error message like below. ![](images/firstprogram_4.png) Find and fix the error once you know it is there. ## Account What can you do when you want to write and save more programs? Once you create an account on the Cloud and registrate your device, you can save on the web as many HTML and js as the set capacity allocated. Create an account on [Register page](https://console.obniz.com/users/signin). By creating an account, you will also be able to use functions such as [obniz Event](/obniz_cloud/about_event), which will automatically run your program based on a configured trigger. It also becomes possible to restrict access to your obniz by setting a key. See more details on [Cloud Document](/reference/cloud). ## Connecting the parts You have finished writing your first program! Let's now try to connect electronic parts and use them through programs. We have a number of lessons to guide you through. Let's first try [Turning on LED](/guides/obniz-starter-guide/parts-library/turning-on-a-led). Enjoy! --- ## How to loop URL: https://obniz.com/guides/basics-of-html-and-javascript/how-to-loop How to loop in JavaScript ## Overview We sometimes want to make something move sequentially, like moving a motor towards left and right infinitely. This can be done by creating a loop. Let's see how to do this. With obniz, the ways to program loop are as follows. 1. [setTimeout and setInterval](#settimeout-and-setinterval) 2. [obniz.onloop](#obnizrepeat) 3. [while(true) and obniz.wait()](#whiletrue-and-obnizwait) ## 1\. Use setTimeout and setInterval JavaScript has a loop function embedded already. 1. setTimeout・・・call function after a set time 2. setInterval・・・call function periodically setInterval is useful when you want to call a function periodically. ``` setInterval(function(){ // every second }, 1000) ``` // every second will be called every 1 sec(=1000msec). By using this, let's make the servo motor move sequentially and make it look like it's waving. ``` obniz instant HTML ``` Every second, this code will be called ``` servo.angle(angle); if (angle == 0) { angle=90; } else { angle=0; } ``` It sets the servo motor's angle with the "angle" variable. After that, set it so that if angle = 0, the angle changes to 90. and if angle = 90 then it changes to 0. This way, the servo motor will move from 0 degree to 90 degrees, and back to 0 degree and again to 90 degrees, and so on. ## 2\. Use obniz.onloop setInterval works fine but there is a problem that it does not stop even when it gets disconnected from obniz. To resolve this issue, we provide the repeat function which automatically stops calling when obniz gets disconnected. ``` obniz.onloop = async function(){ // called repeatedly } ``` It looks similar to setInterval. The only difference is that this function is never called once obniz gets disconnected. Below is an example of writing the program using this function. ```html obniz instant HTML ``` ## 3\. Use while(true) and obniz.wait obniz has a function that pauses a program. ``` led.on(); await obniz.wait(1000); led.off(); ``` By writing this way, you can lit a LED only for 1sec. You can use the while(true) infinite loop and obniz's wait function. ``` obniz instant HTML ``` It looks very neat and clean. You can see that it works fine. However, this function also has the same problem as setInterval, as the loop continues even when it is disconnected from obniz. It thus becomes necessary to break this infinite loop. --- ## Location Kit URL: https://obniz.com/guides/obniz-location-kit ## Overview With this kit, you can experience and develop indoor location information using obniz's BLE. You can purchase this kit at [obniz Official Store](http://store.obniz.com/products/location-kit). ![](./images/pict-locationkit.jpg) What you can do with this kit: - You can check the BLE beacon detection capability of obniz. - You can experience indoor location scanning with multiple units. - You can experience indoor location technology such as triangulation. - You can use obniz to align your tools for developing indoor location information The kit includes the following: - obniz BLE/Wi-Fi Gateway (include obniz Cloud usage License) ×3 - Beacon tag (iBS04i [iBeacon]) ×3 - Start Guide By using [the App](https://obniz.com/webapp/2329) prepared for this kit, you can experience it right away without any programming. Also, the application program is available to the public, so you can start developing based on it. ![](./images/gui-locationkit.jpg) --- ## Getting Start URL: https://obniz.com/guides/obniz-location-kit/start First, let's experience indoor location information using [the App](https://obniz.com/webapp/2329) provided. The configuration is as follows. The visualization software operates the obniz BLE/Wi-Fi Gateway via obnizCloud to scan for BLE. As a result, it picks up the signal emitted by the beacon tag and the visualization software displays it on the browser. ![](./images/cnst-locationkit.jpg) ## Setup 1. Connect all three obniz BLE/Wi-Fi Gateway units to Wi-Fi. 2. Register an account in obniz Cloud and connect all three gateways to the account. 3. Open the app with obnizID and enter the information of the other two units. Check the location of the beacon tag. ### 1. Connecting the obniz BLE/Wi-Fi Gateway to Wi-Fi First, turn on the gateway and connect it to Wi-Fi. For detailed instructions, please click here[Internet Connection Setting](/reference/obniz-ble-wi-fi-gateway/quick-start). ### 2. Connect the gateway to your account. #### Sign in to the Developer's Console (obniz Cloud) From [Developer's Console](https://obniz.com/console), connect the gateway to your account. If you do not have an account, please [sign up](https://obniz.com/users/signup) for one. #### How to connect gateway While signed in to the developer console, simply scan the QR code on the side of the obniz BLE/Wi-Fi Gateway unit to connect it to your account (only once). For detailed instructions, please click [Registration](/reference/cloud/device-management/registration#authenticate-with-the-registry-token-qr-code). By registering the gateway to your account, you can check the online status, upgrade the OS, and install applications. ### 3. Use the App to check the location of the beacon tag. A browser application (HTML program) for the Location Kit is available. Please refer to the following for actual use and instructions. [App for Location Kit](https://obniz.com/webapp/2329) ## Software Developments The program for the app is publicly available. You can view and copy it from the "View Code" page, so you can develop based on it. A [Guide](/guides/ble-location-service/) on how to create an indoor location-based service is available. Also, for BLE development using obniz, see [BLE](/reference/common/ble/) Reference. --- ## Sensing Kit URL: https://obniz.com/guides/obniz-sensing-kit >This kit has been discontinued. ## Overview With this kit, you can start developing sensing IoT using obniz BLE. ![](./images/contents-sensingkit.jpg) ![](./images/sensingkit-sensors.jpg) What you can do with this kit: - You can check the BLE beacon detection capability of obniz. - You can do an evaluation of the BLE sensor. - You can use it for PoC development to remotely view temperature and door sensors. - You can use obniz to get a complete set to develop IoT services. The kit includes the following: - obniz BLE/Wi-Fi Gateway (include obniz Cloud usage License) ×1 - Temperature / Humidity sensor (iBS01T) ×1 - Magnetic sensor (iBS01H) ×1 - Human detection Sensor (iBS02PIR2) ×1 - Proximity detection Sensor (iBS02IR2) ×1 - Start Guide By using [the App](https://obniz.com/webapp/2330) prepared for this kit, you can experience it right away without any programming. Also, the application program is available to the public, so you can start developing based on it. ![](./images/gui-sensingkit.jpg) --- ## Getting Start URL: https://obniz.com/guides/obniz-sensing-kit/start First, let's check the values from the sensor using [the App](https://obniz.com/webapp/2330) provided. The configuration is as follows. The visualization software operates the obniz BLE/Wi-Fi Gateway via obnizCloud to scan for BLE. As a result, it picks up the signal emitted by the BLE sensors and the visualization software displays it on the browser. ![](./images/cnst-sensingkit.jpg) ## Setup 1. Connecting the obniz BLE/Wi-Fi Gateway to Wi-Fi 2. Register an account in obniz Cloud and connect gateway to the account. 3. Enter your obnizID in the application screen and run it. ### 1. Connecting the obniz BLE/Wi-Fi Gateway to Wi-Fi First, turn on the gateway and connect it to Wi-Fi. For detailed instructions, please click here[Internet Connection Setting](/reference/obniz-ble-wi-fi-gateway/quick-start). ### 2. Connect the gateway to your account. #### Sign in to the Developer's Console (obniz Cloud) From [Developer's Console](https://obniz.com/console), connect the gateway to your account. If you do not have an account, please [sign up](https://obniz.com/users/signup) for one. #### How to connect gateway While signed in to the developer console, simply scan the QR code on the side of the obniz BLE/Wi-Fi Gateway unit to connect it to your account (only once). For detailed instructions, please click [Registration](/reference/cloud/device-management/registration#authenticate-with-the-registry-token-qr-code). By registering the gateway to your account, you can check the online status, upgrade the OS, and install applications. ### 3. Use the App to check sensor values. A browser application (HTML program) for the Sensing Kit is available. Please refer to the following for actual use and instructions. [App for Sensing Kit](https://obniz.com/webapp/2330) ## Software Developments The program for the app is publicly available. You can view and copy it from the "View Code" page, so you can develop based on it. Also, for BLE development using obniz, see [BLE](/reference/common/ble/) Reference. --- ## Preparation and assembly URL: https://obniz.com/guides/ai-robot-kit/start Welcome to the world of AI robot kits! The kit contains parts for assembling the robot. Kit contents Cardboard x 3Motor x 2casterTire x 2Tire x 2Distance sensorDistance sensor cableMicro USB cable (*)obniz Board(※) * USB cable and obniz Board are not included in the Boardless Kit.   Other things that need to be prepared In addition to the kit, a smartphone, mobile battery, and Wi-Fi environment are required. Step0. Connect obniz Board to Wi-Fi First, connect the obniz Board to Wi-Fi.How to start obniz Board and how to set up connection to Wi-Fi is Please confirm.quick start Step1.Remove unnecessary parts Step2. Assembling the inner part of the robot We will assemble the second largest cardboard parts. Step3. Assembling the outer part of the robot Assemble the remaining two cardboard parts and combine them. Next, attach the motor and tires. Insert so that the flat part of the shaft fits.Insert until the white shaft of the motor disappears. Step4. Combine the inner and outer parts of the robot Combine the parts assembled in Step 2 and Step 3. Step5. Attach castors and distance sensor First, attach the casters. After sticking the velcro with a sticker, glue the casters. Next, attach the distance sensor with double-sided tape. Step6. Attachment of obniz Board After plugging the cord into the obniz Board, place it in your cardboard pocket. --- ## About block programs URL: https://obniz.com/guides/ai-robot-kit/aboutblock In this AI robot kit lesson, we will program using a block program. ![](images/blockprogram.gif) Before getting into the kit program, try the obniz block program from the lesson below. You don't have to be able to do all the lessons, you can start the kit lesson if you can do "AI: Let's talk". [obniz block program lesson](/guides/block-programing/start) ## For those who want to program with JavaScript The obniz block program is actually converted to JavaScript and executed. If you look at [Step up to JavaScript](/guides/block-programing/js) in the block program lesson, you can see how to get the converted version. You can arrange them in blocks as shown in this lesson, get JavaScript from them, and proceed with the lesson in JavaScript format. ![](images/blockprogram_exportjs.png) --- ## Let's move the robot URL: https://obniz.com/guides/ai-robot-kit/firstmove ![](images/blockprogram_forward.gif) Let's move the robot first by turning the motor from obniz. First, supply power to the robot obniz with a mobile battery etc. and check that the QR is displayed. Since the smartphone is not placed on the robot this time, you can put the mobile battery in the place where you put the smartphone, or you can fix it with double-sided tape on the top surface. ![](images/blockprogram_move_front.jpg) ![](images/blockprogram_move_back.jpg) ## Program This time, let's move forward by 2 seconds and stop. You can also check if the wiring is done with this and if the motor rotates. The final program looks like this. Let's look at each one. ![](images/firstmove1-1.png) The program first connects to obniz. For kits, blocks are provided in the category called "kits". "Move the robot forward" and "Rotate" are also prepared as blocks, and you can move the robot just by arranging them. First, set up that obniz is connected to the AI robot kit. Bring the "Connect airobotki to obniz" block from the "Kit" and connect it after connecting obniz. Now you can move the robot. There is also a block in the kit called "Move the airoo bot kit forward" When this block is executed, the robot will move forward. Let's connect this under the block and move forward. After that, we want to stop the robot after a while. There is no function to do how many meters you should go, so let's make a program that stops after how many seconds. There is a block called "Wait 500" in the "loop", bring this and connect it. Then connect the "Stop airobot kit" block in the "Kit" at the end. ### "What is waiting?" "Wait for 500" means to wait for 500 milliseconds.1000 milliseconds is 1 second, 500 means 0.5 seconds. ![](images/blockprogram_500msec.png) 0.5 seconds is pretty short, isn't it? Increase it to 2000 and let the robot move for 2 seconds. "Wait for 2000" does not mean that the robot will stop for 2 seconds. It is the program, not the robot, that waits.In other words, it means "stop the program once until 2000 milliseconds wait until the next block is executed". The robot is executing a block called "move forward" just before this, and the motor is running. "Wait 2000" stops the program once, but the motor keeps running.This allows the robot to move forward by 2 seconds. After 2 seconds, "Stop airobotkit" will be executed. The motor is stopped for the first time here, and the robot stops. ## Try to move Let's actually move it. Run the block program. But sometimes it doesn't move forward. It turns like this. We want to move the side where the smartphone is placed forward. ![](images/blockprogram_rotate.gif) This is because the motor wiring is reversed. We wired it at the time of assembly, but We did not care much about the orientation.If you connect the motor in the opposite direction, it will rotate in the opposite direction. Therefore, depending on the wiring, it may rotate or move in the opposite direction. Let's change the wiring so that it moves in the correct direction. Let's reverse the wiring of the motor that is rotating in the opposite direction. ![](images/blockprogram_replacecable.jpg) If you do, the robot will move forward like this. ![](images/blockprogram_forward.gif) You have created your first robot program! --- ## Move the robot from the button URL: https://obniz.com/guides/ai-robot-kit/addbutton https://youtu.be/BC8X32NFMPU Let's use the button that was also used in [UI Button Linkage](/guides/block-programing/uibutton) in the block program lesson. It is a program that advances the robot while pressing the button. ## Button display and "If" To proceed only when the button is pressed, you first need to add a UI button to see if it is pressed in a loop. And if it is pressed, it will move forward, and if it is not pressed, it will stop. ## program The end result is a program like this. ![](images/addbutton.png) First, add a button.Add "Make button with text" from "UI". Change the text part to "Proceed". Then, "Connect airobotkit to obniz" enables you to use airobotkit. From here, prepare "If" by saying "Run all the time" so that it loops. Put "button is pressed" in "UI" in the condition of if。 And if it is pressed, what you do is "move the airobot kit forward", If it is not pressed, I want to stop it, so let's stop it with "Stop airobot kit". When you run it and connect to obniz, a button will appear like this. The button design is slightly different depending on the model. ![](images/blockprogram_airobot_button.png) Let's press the button.The robot will move by pressing。 https://youtu.be/BC8X32NFMPU Your program runs a robot over the internet! Even if you take your smartphone far away,Even if you go to a different country, you can operate it remotely as long as you have the internet.。 --- ## Add a button to make it a radio control URL: https://obniz.com/guides/ai-robot-kit/radiocontrol https://youtu.be/fFeUXrMyOl4 Just moving forward is boring. Let's make it a remote radio control by increasing the number of buttons so that it can be rotated. ## Add button You can add two or more UI buttons. Let's make a back button that backs up when pressed. But how do you distinguish between two or more buttons? Button 1 or Button 2? In the block program, each button is given a name and distinguished by the name. Make a button with a name and check "Is button XX pressed?" To check if it is pressed. It's easy to add more buttons. Press "Add UI Button" from the UI. ![](images/airobot_adduibutton.png) Then you will be asked for name. Before you make a button, you will set a name for the button. (Since the button is managed as a variable, you will decide the name of the variable.) Give an appropriate name in half-width alphanumeric characters. We want to go back in the opposite direction of going forward, so we'll name it "backbutton". Then press OK. ![](images/airobot_uibuttonvarname.png) Pressing OK does not change anything on the screen. we just increased the names that can be used. However, if you put 「Create button with "text"」 in another block program and select the place called "button", the "backbutton" you created earlier will appear, so by selecting this, this The button is created with the name "backbutton". ![](images/airobot_uibuttonselect.png) Now let's go back if this is pressed. You can increase the "what if" condition in the loop. There is a plus button at the bottom left of if. You can add another condition by pressing this. Bring another "button is pressed" from the UI and add it here. Then select "button" and change it to "back button". Bring "Move airobot kit" from "Kit" and switch the direction of movement to "Back" instead of "Forward". With this, you can prepare three blocks, one you want to execute when "button" is pressed, the block you want to execute when "back button" is pressed, and the other block you want to execute when neither is pressed. It was. Will look like this ![](images/airobot_multiplebuttonif.png) If you execute it, two buttons will appear like this. And if you press "Proceed", the robot will advance, and if you press "Return", it will back. ![](images/airobot_twobutton.png) ## 4 buttons Let's also rotate. Add two more buttons in the same way. And make it rotate when each is pressed. The "kit" has a block for rotation that says "airobot kit turns to the right". Let's use this to rotate when the button is pressed. This is the completed radio control program that can rotate front, back, left and right. ![](images/radiocontrol.png) We also have a programmed video, so if you want to see where the blocks are and how to do it, take a look. https://youtu.be/eKrL3jE11-I When you run this program, four buttons will appear on the screen. ![](images/airobot_buttons.png) Let's remotely control the robot by pressing it! https://youtu.be/fFeUXrMyOl4 --- ## Proceed if the kit find a person URL: https://obniz.com/guides/ai-robot-kit/detecthuman https://youtu.be/vNIKZr4pXKg From this time, let's do a program like an AI robot instead of a button. Place your smartphone on the robot and try to move forward when you find someone on the camera. ## Program It's not too difficult because you can proceed if there is a person in the camera, just like pressing a button to proceed. How to use the camera was in the block program lesson [Find your face with the camera](/guides/block-programing/cam) Please refer to. Prepare the camera and use "If" in the loop. Set "The face is in the camera" as the condition on if. This allows it to make different movements when the face is visible and when it is not visible. When it is in the picture, insert a block to move the robot forward so that it can move forward. Place a block to stop when it is not shown. Then it looks like this. ![](images/detecthuman.png) ## Set Set the smartphone on the robot. ![](images/airobot_setaphone.jpg) Then open the program on your smartphone and run it. When you connect to obniz, the "Are you sure you want to use the camera?" Dialog is displayed. Click "Allow". Then the image of the camera is displayed, and if there is a person in it, move forward as shown in the video below. https://youtu.be/vNIKZr4pXKg --- ## following people URL: https://obniz.com/guides/ai-robot-kit/followhuman https://youtu.be/zjGXJbm8xuE The obniz block program also understands if a person is on the left or on the right. It makes even a robot to chase the man. let's do it. ## How to chase If there are people, all it have to do is go straight. But what if the person was a little to the right? You want it to move to the right. It can chase people by "moving in the direction of people". To do this, it need to know the position of the person (the position of the face in the camera). And it has to change the movement of the motor based on that position ## The position of the person Use the "Face Position" block to find out where the face is in the picture. ![](images/airobot_facepositionblock.png) This block gives a numerical answer as to which side the face is on. It gets bigger as something goes to the right, The leftmost is -100, the center is 0, and the rightmost is 100. So, if it is a little to the right of the center, it will be 10 or 20. ![](images/airobot_faceposition.png) Let's use this to chase people. ## How to move. Let's divide the movement into three parts. 1. If something is on the left, go to the left 2. If something is in the middle, go straight ahead 3. If something is on the right, go to the right It can now see the location in the "Face Position" block. \ It is -100 to 100, we will divide it into three. \ For -100 to -50, the face is on the far left, so set it to "go left". \ For -50 to 50, there is a face in the middle, so go straight. 50 to 100 will be "go right". ![](images/airobot_humandirection.png) ## Block program First, check with a loop to see if the face is visible. If obniz can't see it, we want it to stop, so we'll put a block to stop it. Then it will be like this. ![](images/airobot_followhuman0.png) The problem is from here. We want to change the movement depending on the position of the face in this "If the face is in the picture". First, let's make a case where the face is on the right side. Bring a "If" block.And if you bring a block to compare the numbers in "logic" to the condition.It's like this. ![](images/airobot_compare.png) This compares two numbers. 10 = 10 is correct, so the block inside what happens is executed. Put "Position on face" here. Then, what was an equal sign (=) is changed to an inequality sign (>). Let's also use the number 50 instead of 10. ![](images/airobot_facebpositioncomparison.png) What does this mean? The position of the face in the camera is in the "Face position" block. And if it is greater than 50, it is correct. In other words, if you make a "if" block, it can see that the face is on the right side! This is OK. ![](images/airobot_faceisright.png) Let's add it not only on the right but also on the left. You press the plus at the bottom left of if block,But this time the condition that Tara less than -50.And prepare "other" which is neither.The other is that the face is roughly in the middle of -50 to 50. ![](images/airobot_humandirectionthreeif.png) ## Motor output change Assuming that the camera shows that there are people on the right or left How can motor slowly turn to the right or left instead of straight or rotating? There is a block called "motor rotation". In this block you can change the power of the motor using numbers. And we can set different values for left and right. ![](images/airobot_motorpower.png) If we use this, you can make only the right motor a little weaker. Then it will slowly move to the right. Let's use this to weaken the right motor a little and move it to the right when your face is to the right, and weaken the left when it is to the left. And if neither is the case, try turning the motor with the same power. ![](images/airobot_followhuman1.png) It looks like this. Come on! done! That is completed we put this if block in the "If the face is in the camera"! ![](images/followhuman.png) Let's move it. It will follow your face properly like the video below. https://youtu.be/zjGXJbm8xuE --- ## Let's find a banana URL: https://obniz.com/guides/ai-robot-kit/findbanana https://youtu.be/CtqIv6fMpsM Let's recognize things other than humans.You can make a robot that reacts to bananas and lemons. ## Tensorflow.js The obniz block program can recognize objects using Google's machine learning library Tensorflow.js.It is the recognition of "banana" and "ballpoint pen". JavaScript can recognize 1000 types, but block programs allow you to select several types around you. ## Get closer to the banana and away from the pumpkin ghost Let's actually program it. Check what is in the camera in the loop. If the camera shows a banana, move it forward and If it's a Jack O Lantern (pumpkin ghost), move it backwards. If neither is the case, try to stop. ![](images/findbanana.png) If you move this and show the banana to the robot, it will come closer, and if you show the pumpkin ghost, it will move away. https://youtu.be/CtqIv6fMpsM ## JavaScript The model of Tensorflow.js used this time is mobile net. [https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet\_v1.md](https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet_v1.md) If you use it with JavaScript, you can identify more (1000 types). The list of things that can be identified [http://image-net.org/challenges/LSVRC/2012/browse-synsets](http://image-net.org/challenges/LSVRC/2012/browse-synsets) [https://github.com/starpentagon/python\_scripts/blob/master/dataset/ILSVRC2012\_class\_name/ILSVRC2012\_class\_name.csv](https://github.com/starpentagon/python_scripts/blob/master/dataset/ILSVRC2012_class_name/ILSVRC2012_class_name.csv) Etc. will be helpful. --- ## Give curiosity URL: https://obniz.com/guides/ai-robot-kit/givecuriosity https://youtu.be/Tj8d7RSUgEQ It's good to find a banana and proceed, but if a robot stop when there is nothing, it can't find it yourself. Let's give curiosity. Move the robot even when nothing is happening to make the program look like it is curious. ## Operant behavior Try moving forward or turning to the right when nothing is happening. Such spontaneous behavior is called "operant behavior" in psychological terms. It's the behavior that people do when they're bored, or the whimsical behavior that makes them crazy. If you move the robot somehow and if it finds a banana and move forward firmly, you can make a robot as if it is curious! ## Program Let's rewrite the part of the previous program that finds bananas and goes on without finding anything. Now let's use the function. A function is a function that can combine several blocks into one. If you can do that, you can make only one movement into one, so the program will be refreshed. There is a "destination" do something "" in the "function", so we bring it. This is a function, and we can put blocks in it. And "Do something" is the name of the function.Let's change this. This time, we want to put a program about operant behavior here, so we will call it "operant". Then, a small block called "operant" is created in the "function". When this block is executed, the block put in the operator function is executed! Let's put a program of operant behavior in the operant function, and put this little operator block when it can't find a banana or a pumpkin ghost. ![](images/airobot_function.gif) This will execute the inside of the operator function when nothing is found. Let's put some whimsical movements here. ## Whimsical movement Computer is not good at random. It is designed to work as instructed, so it am not good at not having instructions. We want to move forward somehow or turn to the right somehow, what should we do? There is a block called "Random Number" in "Calculation". ![](images/airobot_rand.png) This round block is a block that changes to a different number each time, sometimes it becomes 1 and sometimes it becomes 50. This is useful for making random movements! For example, if it goes straight only when it is 1 and turn right otherwise, it can go straight very sometimes. If it is 50 or less, it is straight, and if it is larger than 50, it is rotated clockwise. There is a 50% chance that it will go straight or turn to the right. ![](images/airobot_operantnowait.png) There is like this. If this number is less than "accidentally" 50, the robot will rotate forward, otherwise it will rotate clockwise. But the loop moves very fast. This alone will make the movement really strange, so let's put in a block to wait and decide the movement once and let it move a little as it is. ![](images/airobot_operant.png) The whole program looks like this. ![](images/givecuriosity.png) By doing this, even when there is nothing, it will make random movements such as spinning and going straight.It's like it's looking for something! ## Find a banana If a robot find a banana, it will go straight, so let's put a little banana and experiment. A robot should move a little more slowly so that it can find it. Let's make the movement during operant action a block that can change the strength of the motor. Set it to a slightly smaller value such as 40 or 50 and rotate it straight. ![](images/airobot_operant_param.png) When we try to move it, it works just as well, but unlike before, finding bananas has become a little easier. A robot is a whim,it can find only way when there is a banana. https://youtu.be/Tj8d7RSUgEQ ## How to make it easier to find This is fine if it's random, but it can be smarter if it's a move for the "find bananas" mission. It will develop from here, so please try various things. For example, if a robot knows that a banana is definitely nearby, it may find it better not to go too far. Or, it would be nice to move away while drawing a circle. There are many ideas.It should be easier to find just by changing the speed of the motor. Please try various things --- ## Obstacle avoidance URL: https://obniz.com/guides/ai-robot-kit/avoiding ![](images/airobot_avoiding.gif) The kit also comes with a distance sensor. By attaching it to a robot, it can detect nearby obstacles and move to avoid them. ## Attachment Let's attach the distance sensor. First, connect the cable to the two black eye-like distance sensors. There are three red, black and yellow wires on the cable. Connect to obniz respectively. Connect red to obniz number 7, black to number 8, and yellow to number 9 as shown in the picture below. ![](images/airobot_wiredistance.jpg) Next, attach the distance sensor on the body. There are no attaching holes on the body.Since it is a light sensor, it can be attached anywhere with double-sided tape. Attach double-sided tape to the distance sensor and install it on the body.For example like this. ![](images/airobot_bonddistance.jpg) It can measure the distance from this eye-like object to the object ahead. ## Distance The distance measured from the robot using this distance sensor can be known from this "measured distance (mm)" block. ![](images/airobot_distanceblock.png) This round block is the measured distance. If there is something 10 cm ahead of the sensor, this block will be 100. ## Obstacle avoidance Let's use the distance sensor to run without hitting. If there is nothing nearby (if the distance value is large), go ahead and If not, try to rotate to the right. This way, we can go straight, turn right when something approaches, and move forward when nothing is left. we can move. If we use a block. As a condition, let's say "if the distance is greater than 200". By doing this, you can see that there is nothing up to 200 mm in front of the sensor. Advance the robot here. In the photo above, the sensor was attached on the side where obniz is located. It's the opposite of when you put your smartphone down. Therefore, turning the motor with a negative value advances to the side where the sensor is located. And if there is something near the sensor, rotate it. Both of them will collide if they are too early, so let's move a little slowly. The end result is a program like this. ![](images/avoiding.png) When you run the program, it will move by itself using the sensor. Try blocking it with your hands or walls. ![](images/airobot_avoiding.gif) --- ## Run along the white line URL: https://obniz.com/guides/ai-robot-kit/followaline https://youtu.be/6L1fjv2MqTA There is a block where you can find the "white line" in the camera and find its position. You can recognize the white line just like in the previous lesson [Getting Face Position](./followhuman). Let's run along the white line this time. ## Position of white line The position of the white line can be obtained from "Position of the white line in the camera" in AI. ![](images/airobot_lineposblock.png) It is the same as the position of the face, and you can get the position from -100 to 100. ## Block program It's basically the same as the [Follow people](./followhuman) program. The difference is that it is not the position of the person, but the position of the white line. And the one with the weaker motor output is set to 30. You need to make adjustments so that it do not lose sight of the white line. The more it squeaks, the more it loses sight of it unless it turns around in a hurry. ![](images/followaline.png) Let's move it. If you put a white line on a place that is not very bright with vinyl tape etc., it will run along it. https://youtu.be/6L1fjv2MqTA --- ## Works with IFTTT / Google Home URL: https://obniz.com/guides/ai-robot-kit/ifttt-googlehome https://youtu.be/qzkTGF6dLaQ IFTTT is a convenient app that allows you to set various "triggers" and set "what to do" when the trigger occurs.As a trigger, you can set "If you speak this word" on Google Home of your own home. And you can set a webhook for "what to do".Then you can hit the webhook with "Forward" to run the program in the obniz cloud. ## Repository First is the program.However, this time, instead of the block program prepared for each obniz, save the new block program in your own repository in the cloud.If you save it here, it will be able to be executed automatically from the webhook. For the process of creating an account on the cloud and registering obniz, see [About Account](/obniz_cloud/about_cloud_account).Based on that, we will create an account and link the obniz you have to the account. When that is done, select New from the repository in the [Developer Console](https://console.obniz.com), select "Block Program" as the type, give an appropriate file name (this time "test"), and select the program file. make. ![](images/airobot_htmlsavetorepo.png) ## Program Let's program with this new block program. This program is [Let's move the robot](/guides/ai-robot-kit/firstmove/) Use the same program as.It's just a program that moves forward when you run it. ![](images/firstmove.png) Once created, let's run it.It's OK if the robot moves forward properly. ## Register for the event Well, we was able to save it in the repository. Next, set the event.By setting an event, we can automatically run the program on the cloud from the webhook. Similarly, press "New" from the event in the developer console. We named it move.Then, select the WebApp you created earlier to run. This time we chose "test", so I chose it. The trigger was a webhook. ![](images/airobot_event.png) Now create it. ## Confirm Let's try it out! The created event page has a "Run Test" button. You can execute the event by pressing this. ![](images/airobot_testwebhookrun.png) When you press the button, the program will be executed on the cloud. Did the robot move? ## IFTTT settings Put the IFTTT app on your smartphone and create a new applet. Select Google Assistant for IF and select a simple phrase. Set the keyword "go forward" and "let's go" as a reply. ![](images/airobot_ifttt_if.png) Then select Webhook for THEN. For the webhook URL, enter the webhook URL of the event created in the obniz cloud. ![](images/airobot_ifttt_then.jpg) At this point, you're done! It may take some time for the IFTTT settings to work properly. Let's wait a few minutes. ## Try to speak Let's say "OK Google Go ahead".The robot will move forward with a reply saying "Let's go ahead". https://youtu.be/qzkTGF6dLaQ --- ## Let's convert to JavaScript URL: https://obniz.com/guides/ai-robot-kit/convertjs If you want to do something more advanced than the block program does, you can program it in JavaScript. The obniz block program can be written in the form of JavaScript and HTML to run it. With this function, you can easily convert a program created in blocks to JavaScript from the middle and make it more sophisticated. This time, I will introduce how to convert the code. This lesson is the same as [Step Up to JavaScript](/guides/block-programing/js) in the block program. ## Code writing For example, if you create this block program and look at its code, ![](images/convertjs.png) Click the file name in the upper left of the block program editor and click You can see the HTML and javascript by pressing "View Code". ![](images/blockprogram_exportjs.png) If you do so HTML like this comes out. The program is slightly different depending on the version of the block editor. ``` Block Program running... ``` --- ## Let's recognize characters and move URL: https://obniz.com/guides/ai-robot-kit/readtext Operate the robot kit with handwritten characters https://youtu.be/FGJbGRYfI0M This section uses Html / JavaScript instead of the traditional block program. We also use Cloud Vision, an image recognition service provided by Google. # Get the Google Cloud Api key This app requires a Google Cloud Api API key. 1.[Get a Google account](https://accounts.google.com/). 2\.[Go to the Google Cloud Platform Dashboard](https://console.cloud.google.com/). Select a library from APIs and services. ![](https://storage.obniz.com/images/22b5e7b13176c20d1540276945542) 3\. The API library search screen will appear, so search by vision. ![](https://storage.obniz.com/images/ad1bde6b487d1fec1540276950947) 4\. Cloud VisionAPIを選択します。 ![](https://storage.obniz.com/images/6ed665975dcbf7ac1540276959845) 5\. Press the button to enable. ![](https://storage.obniz.com/images/532fe67556fa863a1540276965399) 6\. Once activated, return to the API and Services dashboard and select your credentials. ![](https://storage.obniz.com/images/55951f4840d0b2121540276970463) 7\. From Create Credentials, select the API key. ![](https://storage.obniz.com/images/a24e43106ad51dde1548236940334) 8\. Make a note of the displayed API key as we will use it later. # Try to move The program is here. Enter your obnizID and press TestOpen. There is a field to enter the google api key, so enter the API key and press the Start button to start the camera. If you show characters such as "Recommend" and "Stop" so that they can be seen well on the camera, the robot kit will also move. ![](https://storage.obniz.com/images/52f2d2a787a880f01540276980476) ``` Video Capture Example Start ``` --- ## Quick Start URL: https://obniz.com/guides/block-programing/start You will learn how to program obniz from an online block program editor. obniz's blocking program not only turns LEDs on and off, but also makes use of smart phone connectivity and artificial intelligence. ## What is a block program? A block program is a program that arranges already prepared blocks in a row, unlike a program that uses a keyboard to type letters. ![](images/blockprogram.gif) You only have to choose from what's provided, and you don't have to be familiar with the keyboard to program it. There is a block program editor on the obniz site that you can use in your browser, and you can create a program using your own obniz just by opening the page. ## First, get the obniz ready. Buy obniz from our [product list](https://obniz.com/products). Turn on your obniz and connect it to Wi-Fi. Please refer to this [Quick Start](/quickstart/) for details, and go to Step 2. ## Open the block program editor To start the blocking program, go to the "Developer Console" at the top right of the site. ![](images/blockprogram_location.png) You can move to the block program writing screen by selecting "Block Program". ![](images/blockprogram_location2.png) Then, you will see a dialog to enter the id of obniz. Enter the 8-digit number displayed in obniz in half-width alphanumeric characters. You can use a hyphen (-) or not. Press "Open" when you have entered the data. ![](images/blockprogram_obniziddialog.png) Then, the editor page will be opened. This will be a block program page prepared for your obniz. You are free to program it here and store it in the cloud. If you save it in the cloud, when you close the page and open it, you will be able to start again. I think three blocks have been placed there since I first opened it. The program is ready for you to run and try it right away. ![](images/blockprogram_scaffold.png) Let's just move it without thinking about the meaning of the block. Is obniz connected to Wi-Fi and QR is displayed? If so, let's press "Run" at the top right of the screen. By pressing this, the program will be saved in the cloud and run in your browser. > (Block programs are stored in the cloud in XML format. And at runtime it will be converted to JavaScript and run on your browser's iFrame.) ![](images/blockprogram_execute.png) The screen at the bottom of this page is the one that is in operation. ![](images/blockprogram_run.png) Your program will continue to run until you press "Exit" or you close this page. Your program is running in your browser. Yes, your browser and your obniz already work together via the internet! Do you see the words "Hello World!" in the obniz? ![](images/blockprogram_helloworld.jpg) This time, it's simple. 1. Connect from your browser to your obniz 2. obniz's display goes black. 3. Hello World on the display I programmed the blocks to do only the three things above. From the next lesson, let's actually move the blocks and program them ourselves! --- ## Let's program it! URL: https://obniz.com/guides/block-programing/pickandplace This time, let's actually line up the blocks and program them by yourself. Let's do it while seeing how to line up the blocks. ## Where are the blocks? There are blocks that can be used in the screen. First, let's open the block program editor like we were doing in [Quick Start](/guides/block-programing/start/). Then you can see the icons on the left side of the screen. As you can see in the image below, on a large horizontal display, such as a computer, you can see the letters that make sense of the icons. There are all the blocks in this. You can click on each one to see the blocks associated with it. For example, if you open a "loop", you'll see a block to repeat something. ![](images/blockprogram_nav.png) In the case of a mobile phone, there is no text to explain, just an icon. The loop becomes an icon that looks like it is spinning. If you tap with your finger, the related blocks will appear. ![](images/blockprogram_nav_s.png) As you can see, the blocks on the left side are divided by type. The top one is obniz, then there are other blocks that are electronic parts, parts on the screen, and other blocks that determine the flow of the program that are not parts, such as "loops". By dragging the blocks you want to use from here, you can actually program them. ## Place blocks and lay them out. Now, let's actually lay them out. In the "UI" section, I'll try to connect "Show text in console" to the last of the three blocks that are already on the screen. If you press the "UI (finger icon)" on the left, you'll see "Show text in console". If you click and hold it, or if you're on a smartphone, hold it down with your finger and move it, it will follow you. Let's connect to the bottom of the three blocks. Then, the "text" part of the block is changed to "connected". If obniz is online, let's just run it. Then you will see "Hello World" on obniz and "Connected" on the screen where you are programming. ![](images/blockprogram_placing.gif) ## Block program flow In a block program, the programs are executed in the order in which they are connected. Here are the four that are lined up in the editor right now. ![](images/pickandplace.png) In a block program, the programs are executed in the order in which they are connected. Here are the four that are lined up in the editor right now. First, your PC/smartphone is connected to the obniz ID. (Of course, obniz IDs vary from person to person.) It won't go to the block below it until the connection is complete. In other words, "turn off the display" is underneath it, but it won't disappear until it connects to obniz. The next thing to do after connecting with obniz is to "turn off the display". This display refers to the screen that is on obniz. It will be erased, so everything that is displayed will disappear and become black. Next is "Show Hello, World!". This will cause this character to appear in the display. Finally, "Connected" will be displayed on the screen where the program is currently running by clicking "Display "Connected" on the console. It's a boring program on its own, but it's still my first block program! ## How to remove and erase blocks It's a way to remove, replace, and erase lined blocks. Let's remove the two in the center, the part that moves the obniz display. There are many ways to do it, but let's try to do it the most carefully. In this block program editor, when a block you grab is removed, the block underneath it is also attached to it. First, take "Turn off the display of obniz" and remove it. Next, grab "Show "Connected" in console" and connect under "Connect to obniz id "". Now I can do what I want to do! However, I don't need "Turn off display" and "Show Hello World" anymore, so I want to turn them off. There are two ways to turn it off. The block will disappear if you press the "Delete" button while the PC is selected. If you are using a smartphone, you can remove the block by taking it to the trash can icon at the bottom right of the screen and releasing it. ![](images/blockprogram_delete.gif) ## Make the block smaller or larger If the block is too small or too big for your convenience, you can use You can change the overall size by using the + and - buttons on the trash can in the lower right corner of the screen. --- ## Move the block all the way around. URL: https://obniz.com/guides/block-programing/block-repeat The block program is executed one by one from the top to the bottom. That means that when you get to the bottom, it's over. This time I'm going to show you how to keep the program running without ending it. ## What's good about moving all the time? We use loops when we "wait" for something, for example, waiting for a button to be pressed, or for a human being to appear on the camera. In other words, "I'm going to use a loop and check it over and over until it happens. ## Repetition In addition to blocks that do something like "put the letters on the screen", there are blocks that determine the movement of the block. The "loop" is one of them. ![](images/blockprogram_loop.png) A block in the "loop" can be a block within a block. When you put it in, the block you put in will be executed from the top in the same way, but when you get to the bottom, it will go back to the top of the loop and be executed again. Let's put a loop in the block where the text appears in the console after connecting to the previous obniz. If you look inside the loop, there are several loops. This time, I'll use the one labeled "repeat do". This is a block that repeats the block you put in it all the time. I'm going to put this in after connecting it to obniz, and then I'm going to put something that displays text on the console in it. This way, the text will stay on the screen the whole time. ![](images/block-repeat.png) And when you run it, you will see a lot of "Connected" characters on the program screen after it is connected to obniz as shown in the image below. ![](images/blockprogram_loopconsole.gif) Now I've managed to keep it running all the way through the program without finishing it! ## Types of loops There are other blocks in the "loop" besides "repeat do. For example, this is a block that will loop a specified number of times; 10 will only be executed 10 times ![](images/blockprogram_loopcount.png) This loop is a block that loops only when certain conditions are met. ![](images/blockprogram_loopif.png) And this is not a loop, but a block that only waits for a certain amount of time. Looping is a very heavy burden on your smartphone or PC because you have to repeat it all the time. Giving them time to do nothing and rest will prevent them from draining the battery. If you're willing to wait, it's good for your battery if you put this block in a repetition. ![](images/blockprogram_loopwait.png) --- ## Let's work with the UI buttons. URL: https://obniz.com/guides/block-programing/uibutton This time, let's display a button in the program's screen and link the button and obniz together! It looks like it's going to be fun to "press the button and the text will appear on the obniz screen. ## UI button A UI button is a button that can be displayed on the browser where the block program is running. The one that says "button" in this bottom photo is that. ![](images/blockprogram_button.png) You can do this with a block program, or you can program what to do when the button is pressed. This time, when the button is pressed, I will try to show the text on the screen of obniz. ## Make a button. First, you need to display the button. The button is in the "UI" on the left It's called "make a button with "text"". I'm going to put this in the place just after obniz connects. You can put your own characters in the text part. This time, I'll use "buttons". ![](images/uibutton.png) Just do this and you will see a button on the screen after connecting with obniz. ## If block Next, I know the button has been pressed, and when it is pressed, I put the letters on the obniz display. How to do this is to use the "loop" we did in the previous lesson and the new "if". The "if" is a block in the "logic". ![](images/blockprogram_logics.png) You can put a block within a block, just like you can put a loop within a block. However, the block you put in will only be executed if the condition "if" is OK. To the right of "if" is the part that says "true". You can put a condition here. Incidentally, the conditions are always rhombus-shaped. Let's put this in after obniz is connected and put the part to add the button inside. ![](images/image-3.png) I think that the button will go out properly even if it is executed in this state. The word "true" in "what if" means "correct", which is a condition for it to be executed. In other words, because it was true, the block that created the button you put in it was executed and the button was displayed. Let's change it a bit: select true and switch it to false. ![](images/image-4.png) If it is set to false, the button will not be displayed. False means "not correct". In this case, the block in "What if" will not be executed, so the button will not be displayed. It went into the next "Run all the way" without being displayed, and the button didn't come up because it was never run again. ## Use Loops. How do I write the letters on the obniz screen when the button is pressed? Repeatedly, you have to check "if" to see if the button has been pressed. And let's try to draw the letters on the screen of obniz if it is pressed. [Youtube: obniz BlockProgram](https://youtu.be/p\_NFldFJTO4) First of all, remove the "if" and make sure to make a button. And then it's gone all the way to the console in execution because it doesn't want to see it anymore. I keep putting the "if" in the execution. Then, put the "Turn off display" and "Show Hello World" blocks in "obniz" into the "What if" block newly. All that's left to do is to say "if" when the button is pressed and it's perfect. In the "UI" where the button is located, there is a rhombus-shaped block that says "button clicked". You can fit this into the true or false rhombus of "if". To make a rhombus or circle block work well, it's important that the finger or mouse that holds the block is in the desired position. ![](images/blockprogram_placingdiamond.gif) If done well, it will be a block like this. And you're done! ![](images/image-5.png) If you run it and connect to obniz, you will see a button on the screen. And I'm sure you can see some numbers and such on the obniz display. Let's press the button on the screen. Press the button and you should see "Hello World" on the obniz display. The IoT-ish program is now complete. Your obniz is controlled remotely from your smart phone/PC via the internet! --- ## Let's remember the event. URL: https://obniz.com/guides/block-programing/memory 'Do something when the button is pressed' is like a reflex. Without thinking about anything in particular, "Now! and the program runs. Let's give it a little more of a try. Use "memory" in your program to do things like "the button was pressed, this is the third time. If you can do this, you will be able to react to things like, "Oh, the robot only hits to the right, let's make it move more to the left," or "I saw this person's face on the camera a while ago. ## Variable The things that can be remembered in a program are called "variables". The block program of obniz is based on a language called JavaScript, so you can use the variables of JavaScript. You can store anything in that variable. Numbers, letters, pictures, and even programs can be memorized, but block programs use numbers and letters primarily. You can let them memorize it whenever they want and ask, "What was that?" whenever they want. Let's put it to use right away. ## Variable block Let's take a quick look at the variables. I'll try to remember the number of times the UI button is pressed and show the number of times it is displayed on the screen. Variables can be found in the "Variables" section on the left, under "Create variable… button to create one. ![](images/blockprogram_var.png) Press the button and you will be asked to enter your name. ![](images/blockprogram_varcreate.png) Pressing OK brings up a block to manipulate the variable you created inside the variable block. ![](images/blockprogram_varblock.png) ## Learning Let them actually learn. The "set~to" at the top is the block to remember the variable and the round block with only the name of the variable at the bottom is the one to retrieve the value of the variable. ![](images/blockprogram_varset.png) ![](images/blockprogram_varget.png) ### The idea of variables Variables are like boxes that you "put" numbers, letters, etc. into and make them memorize. So, when you make him remember, you can say, "Assign to a variable". ### Let's program it. Now, let's actually make them learn. The block to assign to the variable count is placed before it enters the loop. And let's set the value to the number 0. There is a number block at the top of the "Calculate" block, so move it to the right side of the block we just placed, to the right of the assignment. The number 0 is now in the variable called count. If you take out the item in count after this, it will always be 0. Let's use count in the actual display of obniz. Let's grab the round count block in the variable block and put it at the place where "Show Hello World in obniz" is shown. Now you can see what's in the count variable in the obniz display. If it is now, it is 0. ![](images/blockprogram_varset0.gif) This is how the program will be completed. ![](images/memory.png) If you do this and push the button called "button" that comes up, you will see the number 0 on the display of obniz. ![](images/blockprogram_varzero.jpg) ## Rewrite a value If you only put a value in a variable once, then there is no point in the variable. Now let's count the number of button presses using a variable. There are two ways to rewrite the values, one is to use the dedicated blocks that allow you to increase or decrease the number in them, and the other is to use them. This is a number in a variable and can only be used if you want to increase or decrease it. ![](images/blockprogram_varup.png) The other way is to put in a new value. If you want to increase the value by 1, you can add 1 to the previously entered value and put it back into the variable as a new value. This time, we'll just count the number of button presses, so we'll use blocks to increase the number. In the block that is executed when the button is pressed, there is a block called "Increase or decrease the variable count 1", so I put this. Then, it looks like this. ![](images/memory2.png) Let's try to do this. Pressing the button in the same way will show 1 in the OBNIZ display. Since the number in the variable count is increased by 1 before it is displayed in the obniz display, the The count is 0+1 with a 1 in it. Then the obniz display will show the value in the count, which is 1 If you press the button again, you will see 1+1 this time with 2 in the count and 2 in the obniz. You have a good memory! With this, you can create an advanced program to easily count something or find out if something has or hasn't happened. ## Development If you can afford it, why don't you try something like this? 1. When the button is pressed three times, the letters appear on the obniz display. 2. Use the assignment and addition blocks to increase the numbers in the variable, rather than the increase or decrease blocks in the count. --- ## AI: Let's look for the face with the camera URL: https://obniz.com/guides/block-programing/cam In obniz's block program, you can also use a block called image analysis such as "A person is in the picture!" Using a camera. Let's use it this time. ## Use the camera There is a type of block called AI. You can use blocks such as whether or not a person is shown in this. Of course, I will use the camera, but I will use the camera attached to the smartphone or computer running this block program. If you don't have a camera, you can't use it. First, erase all the block programs and start from the state of nothing. Place "Prepare Camera" inside the AI ​​block. If you use a camera, you need to prepare by doing this once. Then, if you see your face on the camera, try to display "Who?" On the console. For that, we use a loop. Make sure to repeat the loop and check in the "if" block. What you check is "Your face is in the camera" in AI. Put this in the condition of if. Then put the console in the UI inside something and say "Who?". It will be a block like this. Since it does not use the obniz block, it can be used immediately without obniz. ![](images/cam.png) Now let's try to run this. After waiting for a while, you will see a permission screen like this one: "The site is trying to use your camera, are you sure? The design of the screen is different for each machine you are using, whether it is a PC or a smartphone. By pressing "Allow", the camera will move and you will see your face on the screen. ![](images/blockprogram_aicampermission.png) As long as your face is on the screen, you will continue to see "Who? will continue to appear on the console.How about this? if you cover the camera with your hand so that your face is not visible, it will stop coming out. To make it work, you need to take a clear picture of the face. For example, let's try this in the following situation. ・Not bright enough -> Brighten the room ・Backlighting (the sun, fluorescent lights) -> Change the direction and angle of the camera. etc. ![](images/blockprogram_airena.png) --- ## AI: Let's talk URL: https://obniz.com/guides/block-programing/talk You can make it speak any characters you want on your phone or computer running the block program. With this, you can make your obniz robot say things like "looks delicious" when it finds an apple. ## Talking Blocks The talking blocks are very easy to use. It's in the AI category, and you can make the written text speak just by running this block. **However, Safari on iPhone is not supported, so it is only available on Android or PC.** ![](images/blockprogram_say.png) [Let's try to find a face with the camera.](/guides/block-programing/cam/)We have already displayed text on the screen when we found a face, but this time let's make it talk instead. Bring the "Say Hello" block from the AI blocks and put it in the "If the camera shows your face" block. However, this block will not wait until you finish speaking. This block is that "say it!". So, you need to put in a waiting period "It'll probably be done talking in a few minutes" after that, Then it looks like this. ![](images/talk.png) Let's try to do this. It will be your phone or computer that does the talking.So if you are using a smartphone, deactivate silent mode and turn up the volume on your speakers. Of course, the same goes for your computer. Get the program working,[Let's try to find a face with the camera.](/guides/block-programing/cam/)In the same way, if you put your face on the camera, you will hear a voice saying "Hello" from the screen where the program is running. The feel of the voice, the ability to use Japanese, etc. depends on the PC/phone you are using. --- ## Use parts: Let's move the motor URL: https://obniz.com/guides/block-programing/motor Let's connect the components to obniz and run it as a block program. This time, we will connect a small DC motor. This is a motor that rotates when electricity is applied, and is often used in toys. ## Connection In the case of obniz, you can connect it anywhere on the io, but this time we will connect it to pins 0 and 1. ![](images/blockprogram_motor.jpg) Now, if you apply current to 0 and 1 of obniz, the motor will turn. ## Motor block Since the DC motor is prepared as a block, the block program will use it. In the "Moving" category, there is a "DCMotor".This will be the block for the motor. ![](images/blockprogram_motorblocks.png) Let's use it right away. ## Program Here is the program that was completed earlier. This time the challenge is to make the motor turn only while the button is pressed on the screen where the program is running. ![](images/motor.png) First, we need to set up where the motors are connected so that we can use them. This is done after connecting to obniz and displaying the button on the screen. There are forward:0, back:1.This means that you have connected the two wires of the motor to 0 and 1. Then, in a loop, check to see if the button on the screen is pressed repeatedly. If the button is pressed, the "rotate dcmotor to forward" block will be executed, so the command to turn the motor will reach obniz and the motor will turn. On the other hand, if it is not being pushed, it will try to stop the motor. This is what it will look like when you run it. ![](images/blockprogram_movingmotor.gif) --- ## Step up to JavaScript URL: https://obniz.com/guides/block-programing/js The block program is useful, but if you want to do something more advanced, You should use JavaScript to program it. For example, you can use deeper programming for example external Dropbox, Twitter, etc. This is a case where you are creating a game that draws 3D on the screen. They can also be created using a combination of HTML and JavaScript. The obniz block program is actually converted to HTML/javascript and executed. So,If you modify the HTML/javascript created from the block program you created, you can continue to program more detailed movements in JavaScript. ## Code-writing For example, if you create this block program and look at its code ![](images/js.png) You can check the HTML and javascript by clicking on the file name in the upper left corner of the block program editor and pressing "View Code". Click on the file name in the upper left corner of the block program editor and click on "View Code" to see the HTML and javascript. ![](images/blockprogram_exportjs.png) If you do so, You will see HTML like this. The program is slightly different depending on the version of the block editor. ``` Block Program running... ``` --- ## Preparation and assembly URL: https://obniz.com/guides/iot-home-kit/start Welcome to the world of IoT!The kit contains parts for assembling the IoT home kit. Kit contents Cardboard x 3ServomotorServo motor connectorInfrared moduleVarious screwsDistance sensorDistance sensor cableMicro USB cable (*)obniz Board(※) ※The Kit with no Board does not include a USB cable and obniz Board.   Other things that need to be prepared In addition to the kit, you will need a smartphone and mobile battery, double-sided tape, a Phillips screwdriver, and a Wi-Fi environment. Step0. Connect obniz Board to Wi-Fi First, connect the obniz Board to Wi-Fi.How to start obniz Board and how to set up connection to Wi-Fi is Please confirmquick start Step1. Remove unnecessary parts Step2. Mount the servo motor and distance sensor Mounting image First, mount the servo motor.Use screws, two washers, and hexagon bolts to fix them in two places on the left and right. Next, mount the distance sensor.Use a screw, a washer, and a hex bolt to fix it in two places on the left and right. Step3. Assembly of the main body Fold all the fold lines into valley folds and assemble.Make sure all cables finally come out of the top. Step4. Attachment of cardboard parts and flag Attach the cardboard parts to the top surface.It will be the location of obniz Board. Attach the parts and flag to the servo motor. Step5. Attachment of obniz Board Connect the servo motor, distance sensor, and infrared module to the obniz Board.Pay attention to the position (order) of inserting the pins. --- ## About block programs URL: https://obniz.com/guides/iot-home-kit/aboutblock The lessons in this kit use block programs to program. ![](images/blockprogram.gif) Before getting into the kit program, try the obniz block program from the lesson below. You don't have to be able to do all the lessons.If you can do "AI: Let's talk", you can start the lesson of the kit enough. [obniz block program lesson](/guides/block-programing/start) ## For those who want to program with JavaScript The obniz block program is actually converted to JavaScript and executed. If you look at [Step up to JavaScript](/guides/block-programing/js) in the block program lesson, you can see how to get the converted version. You can arrange them in blocks as shown in this lesson, get JavaScript from them, and proceed with the lesson in JavaScript format. ![](images/blockprogram_exportjs.png) --- ## Let's move the flag URL: https://obniz.com/guides/iot-home-kit/shakeflag ![](images/iothome_shakngflag.gif) Let's move the machine first by turning the servo motor from obniz. First, supply power to obniz from a computer or mobile battery, and check that the QR is displayed.If you can confirm it, let's program it. ## Program We have also prepared a video from nothing to the completion of this program. https://youtu.be/fQqXtxfvmG4 This time, We will try the movement of "raising the flag and lowering it after 2 seconds". The final program looks like this.Let's look at each one. ![](images/shakeflag.png) The program first connects to obniz. For kits, blocks are provided in the category called "kits". Raising and lowering the flag is also prepared in blocks. ![](images/iothome_flagblock.png) First, set up that obniz is connected to the AI robot kit. Bring the "Connect iothome kit to obniz" block from "Kit" and connect it after connecting obniz. Now you can use the servo motor, distance sensor, etc. included in the kit from obniz. There is also a block in the kit called "Raise the flag of the iot home kit". When this block is executed, the servo motor will rotate and the flag will rise. We want to raise the flag and lower it a little later.s There is a block called "Wait 500" in the "loop", bring this and connect it.Then bring "Raise the flag of iothome kit" in "Kit" again, connect it at the end, and change "Raise" to "Lower". ### "What is waiting?" "Wait for 500" means to wait for 500 milliseconds. 1000 milliseconds is 1 second, 500 means 0.5 seconds. ![](images/blockprogram_500msec.png) 0.5 seconds is pretty short.Let's increase it to 2000. Even if we say "wait for 2000", it doesn't mean that you will stop for 2 seconds. It is the program that waits, not the obniz side.In other words, it means "stop the program once until 2000 milliseconds wait until the next block is executed". Even if it wait, it don't lower the flag without permission. The program will stop once at "Wait 2000", but the flag will remain raised because it says "Raise the flag". After 2 seconds, "Lower the flag of iothomekit" will be executed. The flag goes down here. ## Try to move Let's actually move it. Run the block program. Will the flag move? The flag was attached at the time of assembly. So the m flag seems be out of position. Now remove the entire disk (black circle) and adjust the position. ![](images/iothome_replaceflag.jpg) Let's move it again. If you move like this, you are successful! ![](images/iothome_shakngflag.gif) You have your first program! --- ## Move the flag from the button URL: https://obniz.com/guides/iot-home-kit/buttonflag ![](images/iothome_buttontoflag.gif) Let's use the button that was also used in [UI Button Linkage](/guides/block-programing/uibutton) in the block program lesson. Try to raise the flag once the button is pressed. ## Button display with the "if" As a program, first add a UI button.The button will now appear on the screen. You have to find out if it was pressed next.You need to find out if it is pressed in a loop. And if it is pressed, raise the flag. ## Program The end result is a program like this. ![](images/buttonflag.png) First, add a button.Add "Make button with text" from "UI". Change the text part to "give". Then, enable iothomekit by "Connecting iothomekit to obniz". Lower the flag before entering the loop.Lower the flag with "Lower the flag of iot home kit". From here, prepare "Run all the time" so that it loops, and check repeatedly by putting "If" inside. Put "button was clicked" in "UI" in the condition of if. And if it is clicked even once, raise the flag with "Raise the flag of iot home kit". When you run it and connect to obniz, a button will appear like this.The button design is slightly different depending on the model. ![](images/iothome_buttondesign.png) Let's press the button.The flag that is going down will go up by pressing it. ![](images/iothome_buttontoflag.gif) Your program runs a robot over the internet! Even if you take your smartphone far away,Even if you go to a different country,You can run it remotely as long as you have the internet. --- ## Prepare two buttons URL: https://obniz.com/guides/iot-home-kit/twobutton ![](images/iothome_twobutton.gif) If you can raise the flag with a button, we want to lower it with a button. Let's add two buttons to make it an up button and a down button. ## Add button You can add two or more UI buttons. But how do you distinguish between two or more buttons? Button 1 or Button 2? In the block program, each button is given a name and distinguished by the name.ボタンをMake it with a name and check "Is button XX pressed?" To check if it is pressed. It's easy to add more buttons. Press "Add UI Button" from the UI. ![](images/iothome_addbutton.png) Then you will be asked for name. Before you make a button, you will set a name for the button. (Since the button is managed as a variable, you will decide the name of the variable.) In alphanumeric, and give it a suitable name.We will make a button to lower the flag, so set it to "flag down". ![](images/iothome_uibuttonvarname.png) Pressing OK does not change anything on the screen.We just increased the names that can be used. However, if you put "Create button with" text "" in another block program and select the place called "button", the "flagdown" you created earlier will appear, so by selecting this This button is created with the name "flagdown". ![](images/iothome_flagdown.png) Now let's lower the flag if this is pressed. ## Check in loop The final program looks like this. ![](images/twobutton.png) Make two buttons and check the "what if" block to see if the button was clicked all the time in the loop. Makes the flag fly when the button is clicked And when the flagdown button is clicked, the flag is lowered. By doing this and pressing a button, you will be able to raise and lower the flag like this! ![](images/iothome_twobutton.gif) --- ## Use a distance sensor URL: https://obniz.com/guides/iot-home-kit/distance ![](images/iothome_proximitydemo.gif) This kit comes with a distance sensor. At the millimeter level, it can detect if there are obstacles. By using this, it can be used for detecting whether or not there is a person. This time, let's do a simple program that raises the flag if it is nearby. ## Distance sensor The distance sensor is like the black eyes in front of your home kit. It always measure the distance to the object in front of me. This is a block that divides the distance into three stages and allows it to check whether there is something up close, near, or far away. ![](images/iothome_proximityblock.png) If you use a block, you can do this when it's nearby, and do it otherwise. ## Program The program is very simple. Connect to obniz, put a connection block in iothomekit, and loop. Check if there is something "close" in the loop using the block that checks the distance between the block and the previous one. Set the flag to be raised if it is near, otherwise lowered. ![](images/distance.png) If you run this program, the flag will rise when you bring your hand close to it, and the flag will drop when you release it. ![](images/iothome_proximitydemo.gif) ## Development Some blocks allow you to get the distance as a number in millimeters. ![](images/iothome_distancemm.png) This block contains the value of the distance measured by the current distance sensor as a number. You can also use this and a block that compares numbers to program it to react at any distance you like. Please try it. --- ## Let's change the characters on the screen URL: https://obniz.com/guides/iot-home-kit/changeuitext ![](images/iothome_proximitylabel.gif) It is useful to know if there are people on your smartphone from a distance. If you put it in the bathroom, you can check from your smartphone that "Is anyone using it now?" ## UILabel In the last program, you knew if there were any people near the distance sensor. After that, it would be nice if you could say "yes" or "not" on the screen when there are people and when there are no people. In addition to buttons, there are labels in the "UI" block. You can use this to display your favorite characters on the screen. First is the block that makes the label.Doing this will create a label on the screen. A label is a place to display characters. This block only prepares a label on the screen, and you cannot set what characters are displayed there. ![](images/iothome_labelblock.png) Characters are displayed on the label created using the block below. ![](images/iothome_labelprintblock.png) We will use these two. ## Program The program connects to obniz, sets up iothomekit, and then creates a label. Then, in the loop, if there is something near the sensor, change the labeled text to "Something!".On the contrary, if nothing is near, "No" will be displayed. Then it becomes such a program. ![](images/changeuitext.png) We will try it. Then, "Not" will be displayed on the screen. Stand in front of the sensor or cover it with your hand.Then, "Something is there!" Will be displayed on your smartphone or PC. ![](images/iothome_proximitylabel.gif) This is IoT, over the internet. You can use it even if you are not nearby. When you want to know if there is anyone, such as in the bathroom or in your room, you can check it remotely by running the program. --- ## Use as a learning remote control URL: https://obniz.com/guides/iot-home-kit/ir https://youtu.be/JwLIP6ykycU This kit comes with a module that can receive and send infrared signals. Many home appliances powered by remote controls use infrared rays to send signals, so obniz can receive and store these signals. If you send the saved signal from obniz again, you can output the signal of the saved remote control, so you can operate the air conditioner at home from your smartphone on the go. ## Receive A lot of infrared rays are flying around us. There are even remote controls. However, even if they use the same infrared rays, the contents sent using them are different so that the air conditioner does not turn on without permission even if the remote control of the TV is used. obniz's infrared module can capture many infrared signals as they are. There is a block for receiving infrared signals. This block will stop the program and wait until one of the infrared rays arrives. ![](images/iothome_irreceiveblock.png) This is useful. It will wait for you, so you can receive it by bringing the remote control when you are waiting and pressing the button to memorize the infrared rays you want to remember. But how do you save the received signal? The received signal will be a large number. We can't write on paper. But,the block program will be terminated when the screen is closed, so the acquired data will also be lost. There is a block to store in the cloud. Let's use it and save it to the obniz cloud.Then you can retrieve it again by closing the program. **You must be logged in to the cloud to save to the cloud. Create an account from [Sign up] (https://console.obniz.com/users/signin) and "register" for obniz.** There is a block in the "Kit" that can store this infrared signal in the cloud. By inserting the previous block as the saved data of this block, The moment you receive it, it will be automatically saved in the cloud. ![](images/iothome_cloudstorage.png) This way, you can reopen the program and retrieve what you saved from the cloud. You can give it a name when you save it.This time, It will remember the infrared signal of the electric fan by the name of "power supply". It will look like the image below ![](images/iothome_cloudsaveblock.png) ## Receive and save when button is pressed Let's receive it first. Prepare a button, and when the button is pressed, set it to infrared reception, and when it receives it, save it with the name "power". Then, when it is received, the label "Received" is displayed so that it is easy to tell whether or not it has been received. ![](images/ir.png) Let's run this program and press the button to receive it. Point the remote control you want to remember around the green base on the kit and press the button you want to remember. When "Received" is displayed on the screen, the save is successful! https://youtu.be/nlfdM7jjFiA ## Send Sending is very easy. All you have to do is take out the memorized signal and send it from infrared rays. First is the part that retrieves data from the cloud. The block is "Load signal" from iothome kit "in" Kit ". I decided to save it under the name "Power", so when I take it out, I also take it out with "Power". ![](images/iothome_retrive.png) By attaching this block to the block for transmitting infrared rays, you will be able to transmit. ![](images/iothome_irsend.png) Also prepare a send button so that you can send it when you press it. The completed program looks like this. ![](images/ir2.png) When you do this, you will see two buttons. ![](images/iothome_irscreen.png) If you receive it earlier, it is saved in the cloud, so you don't have to receive it anymore. Let's press send to emit infrared rays. If that doesn't work, try changing the location or orientation of your IoT Home Kit, or try receiving it again. https://youtu.be/JwLIP6ykycU --- ## Let's move the remote control from Google Home URL: https://obniz.com/guides/iot-home-kit/googlehome https://youtu.be/EVlpAMGy5QE IFTTT is a convenient app that allows you to set various "triggers" and set "what to do" when the trigger occurs.As a trigger, you can set "If you speak this word" on Google Home of your own home. And you can set a webhook for "what to do".Then you can hit the webhook with "Turn on the fan" and run the program in the obniz cloud. ## Repository First is the program.However, this time, instead of the block program prepared for each obniz, save the new block program in your own repository in the cloud.If you save it here, you will be able to execute it automatically from the webhook. For the process of creating an account on the cloud and registering obniz, see [About Account] (/obniz_cloud/about_cloud_account).Based on that, we will create an account and link the obniz you have to the account.When that is completed, select "block program" as the type from the new repository creation from [Developer Console] (https://console.obniz.com), give an appropriate file name (this time, "turn on"), and create a program file. .. ![](images/iothome_repo.png) ## Program Let's program with this new block program. In the last infrared lesson, infrared rays are stored even though it is called "power supply". This time, it's very simple because it just uses the stored data to output the infrared signal of that "power supply". All you have to do is bring the signal stored under the name "Power" from the cloud and emit it in infrared. ![](images/googlehome.png) Try it out, it will emit infrared light as soon as you move it.It's OK if the fan works properly. ## Register for the event Well, We was able to save it in the repository.Next, set the event.By setting an event, you can automatically run the program on the cloud from the webhook. Similarly, press "New" from the event in the developer console. We named it Google Home. Anything is fine.Then, select the WebApp you created earlier to run. This time you chose "turn on", so you chose it. The trigger was a webhook. ![](images/iothome_event.png) Now create it. ## Confirm Let's try it out! The created event page has a "Run Test" button. You can execute the event by pressing this. When you press the button, the program will be executed on the cloud. Did the fan work? ## IFTTT settings Put the IFTTT app on your smartphone and create a new applet. Select Google Assistant for IF and select a simple phrase. The keyword is "turn on the fan" and the reply is "hot monne". ![](images/iothome_ifttt.jpg) Then select Webhook for THEN. For the webhook URL, enter the webhook URL of the event created in the obniz cloud. ![](images/iothome_ifttt_then.jpg) At this point, you're done!It may take some time for the IFTTT settings to work properly. If that doesn't work, wait a few minutes. ## Try to speak Let's say "OK Google fan on". I get a reply saying "It's hot" and I think the fan will turn on in a few seconds. https://youtu.be/EVlpAMGy5QE --- ## Get the weather forecast URL: https://obniz.com/guides/iot-home-kit/weather Get the weather forecast via the internet and change the movement according to the weather. For example, it would be convenient to be able to raise a flag if it rains. ## Weather block Use the weather block to get the weather. ![](images/iothome_weatherblock.png) This block has a place to put the area name and a place to specify the weather. If you put it in a block and use it. In the case of the block above, if the weather in Tokyo is cloudy, it is a block. Use this to raise the flag if it rains and lower the flag otherwise. ## Program **(This program will run in the cloud in the next lesson, so we recommend creating a new one in the repository.)** The program looks like this. ![](images/weather.png) If you can connect and the kit can be connected, use the block to separate the programs depending on whether it is raining or not. If it rains, raise the flag, otherwise lower it. When you run the program, it will get the weather and raise or lower the flag. It also appears as text on the on-screen console. --- ## Let's run it regularly URL: https://obniz.com/guides/iot-home-kit/timer If you run a program that moves the flag depending on the previous weather at 6 o'clock every morning, It seems convenient when you go out in the morning. Let's run it at the same time every day by using cloud events. ## Program First of all, regarding the previous program, please save it in the repository on the cloud. (OK if already saved) ![](images/timer.png) Make sure this program runs in the cloud every morning at 6am. ## Timer Create a new event with Create Event from the Developer Console. The name is appropriate, and the program to be executed is the program saved earlier (saved as weather.xml in this lesson). Select "Every day at this time" to trigger the event. The time specified here is Coordinated Universal Time (UTC), not Japan time. 9 hours before Japan. If you want to go to 6 o'clock in the morning, you have to subtract 9 hours from there, so you will have 21 on the previous day. So set it to 21:00. ![](images/iothome_eventtimer.png) Let's create it now. By pressing Execute Test, you can start the test immediately without crossing 6 o'clock.The flag moves and nothing happens depending on the weather.Even so, the obniz display will change from QR to a different screen, and it will return to QR soon. All you have to do is wait for tomorrow! --- ## About the kit URL: https://obniz.com/guides/obniz-starter-kit/about ## Overview This kit is a starter kit that brings together the most commonly used components of obniz so that you can start implementing your ideas right away. Why don't you try running your hardware in JavaScript? The links in this guide will take you to the detail pages of the components, which will summarize the program and features of how it can be used in obniz, so if you have an idea or something you want to build, please visit its detail page. If you can't think of anything specific, or if you want to learn, try the sensors in order from the top to the bottom to get a better understanding of what obniz can do, and to get a better idea of what you can create. ## Starter Kit things included in a package - obniz Board - USB micro B cable - Sensors - LED signal - Button - Buzzer - Servomotor - Temperature sensor - Human detection sensor - Distance sensor - Matrix LED ## Procedure ![](images/amzn-sk-steps.png) #### 1\. Wi-FiSetting First, connect the obniz Board to Wi-Fi.TO setup procedure, please refer to [Start obniz Board and set up Wi-Fi.](/reference/board-1y/quick-start"). #### 2\. Select Parts #### 3\. Run the program The program and functions of each part can be found in detail in [Connect Parts](/guides/obniz-starter-kit/use-parts/). --- ## Let's run the sample program URL: https://obniz.com/guides/obniz-starter-kit/start-guide/lesson-run-sample-program First, connect the obniz Board to Wi-Fi. Quick start for obniz For instructions on how to start up the obniz board and set up a connection to Wi-Fi, please see Quick Start for obniz Board/obniz Board 1Y. After setting up the wifi, let's try to run obniz with a simple program. ### 1\. Program Go to the online HTML editor at [http://obniz.com/ja/console/program](http://obniz.com/ja/console/program) and enter the obniz id. Copy the following program in its entirety and paste it into your program screen. ```html Connect From Your Browser LED ON OFF ON OFF TEXT Print on obniz ``` ### 2\. Enter your obnizID In the program ``` var obniz = new Obniz("OBNIZ_ID_HERE"); ``` and set OBNIZ\_ID\_HERE to your own obniz id. For example, for 1234-5678, enter the following ``` var obniz = new Obniz("1234-5678"); ``` ### 3\. Run the program Click the\ [Run\] button in the upper right corner to connect your browser to the obniz Board. If you see the following screen in your browser, you have succeeded. ![https://s3-us-west-2.amazonaws.com/secure.notion-static.com/be045608-cbdc-4725-9e24-218564c260dc/handson1.png](images/handson1.png) #### **Move - LED ON / OFF-** You can turn the LED on and off by pressing the buttons displayed on the browser. The green button controls the green LED and the yellow button controls the yellow LED. Connect the LED signal to the obniz as shown in the picture, and press the button to switch the green and yellow LEDs on and off. GND, G, Y, and R are connected to 0, 1, 2, and 3 respectively. ![https://s3-us-west-2.amazonaws.com/secure.notion-static.com/7be7d579-cb48-4579-886a-382c53763033/handson6.png](images/handson6.png) #### **Display text on the display** Display your favorite letters and messages on the Board's display. Change the "Hello World" part to your favorite text or message and press the \[Print on obniz\] button. The characters you enter on the obniz Board will appear on the Board display. ## Let's try to run it on a smartphone. Since obniz runs its program through the cloud, it can be easily operated from a smartphone. Go back to the editor screen, display the QR code from the file at the top, and scan it with your smartphone to make it work. ![https://s3-us-west-2.amazonaws.com/secure.notion-static.com/6c6bf416-f222-4ebe-bd45-a5a93e43d9ca/handson2.png](images/handson2.png) --- ## Let's change the program URL: https://obniz.com/guides/obniz-starter-kit/start-guide/add-program [Sample Program](/guides/obniz-starter-kit/start-guide/lesson-run-sample-program/), we cannot control the red LED, so let's add a program to control the red LED. ## Adding operation buttons (HTML) First, we will add a red button in HTML. HTML for the yellow button ```html ON OFF ``` Copy and add the following code above it ```html ON OFF ``` The CSS is loaded and used from something called [Bootstrap](http://getbootstrap.com/). For example, the class name btn-danger is used to make the button red. If you are interested, you can refer to the reference and change the design as you like. ## Add movement (JavaScript) Next, we will make it possible to control the ON/OFF of the red LED when this button is pressed. In jQuery, when you want to do something when the id "on" is pressed, you can write something like this. ```html $("#on").on("click",function(){ // on pressed }) ``` The red buttons that we just added are given the ids red\_on and red\_off, respectively, so we can write this to turn the LED on when the ON button is pressed and turn it off when the OFF button is pressed. ```html $('#red_on').click(function () { light.red.on(); }); $('#red_off').click(function () { light.red.off(); }); ``` Add the above program under the green and yellow programs (under the following part of the sample program) and try to run it. ```html $('#yellow_off').click(function () { light.yellow.off(); }); ``` The screen will look like the following, and if you can control the red LED with the red button, you have succeeded. ![https://s3-us-west-2.amazonaws.com/secure.notion-static.com/da5989c1-93b1-4055-8d54-f240743b6bbf/handson3.png](images/handson3.png) --- ## HTML/JavaScript URL: https://obniz.com/guides/basics-of-html-and-javascript In lessons, we control obniz by using HTML and javasript. This lesson shows you how to do this. ## HTML is just a text HTML is a document format for browser. It is written with attributions like size of text, location of text, and where to jump when something is clicked. For example, by opening the HTML below, you can see "Hello" on browser. You can do this on the program page on our website, or create a text file, put HTML into it and open it on browser. ```html Hello ``` As you can see, it is enclosed with ``and``, which means "anything between these are HTML". In HTML, an area enclosed by `<>` is considered one block. Browser recognizes this and decides, "Ah, so this is HTML. OK, I will display it". The HTML above shows a minimal composition to display letters. What is actually shown on browser is anything enclosed by `body`. The area enclosed by body gets displayed on screen as it is. ## Attribution HTML has various attributions. For instance, surrounding texts by `` will turn them into bold texts.obniz idTest Open ```html Hello ``` You can specify more attributions by writing more commands. For example, you can change the text color by supplying "style". ```html Hello ``` Besides texts, you can also display images by using ``. Let's try to show [https://obniz.com/images/obnizfront.jpg](./images/obnizfront.jpg)obniz idTest Open ```html Hello ``` This suffices to display an image. Can you see the image? Although `` is not enclosed by ``, some attributions do not require enclosure. All websites are written in HTML like this. You can design websites freely, including the size, color and location of texts, as well as the size and location of images. ## JavaScript Additionally, HTML can contain a program called "JavaScript". A program is an area enclosed by ` ``` You can still see "Hello", but cannot see `console.log("This is JavaScript");` on browser. That is because the area between `script` is recognized as a program by browser. It is thus not just texts but a program to be executed. It is executed line by line from the top. You might wonder what JavaScript can do. First, JavaScript can control HTML. Let's rewrite the HTML above, "Hello", from JavaScript.obniz idTest Open ```html Hello ``` You can see "What's up" on browser. But it still says "Hello" in between the body! Take a closer look at the program. There is a program written in JavaScript `$("strong").text("What's up")`. It means "rewrite texts enclosed by strong to "What's up"". It is thus overwritten by JavaScript to show "What's up", even though it is originally written to display "Hello". This process is not visible anyway and thus redundant. Just providing "What's up" in HTML would have been enough. However, this is just an example to show what JavaScript can do. JavaScript can be connected to the internet to read/write information. It can therefore retrieve news from news websites to display the information within HTML. In this case, it would not be redundant. That was just an introduction. The previous example was on overwriting a HTML text. Let's now try the reverse - controlling JavaScript using HTML.obniz idTest Open ```html Please touch this text ``` You can see "Please touch this text" on browser. By clicking or tapping on this text, it changes into "Touched!". JavaScript would change the text only when someone taps/clicks the text. Just like this, JavaScript can be controlled through HTML as well. You may notice ``. In HTML, you can specify name of an area. JavaScript also uses a name like`$("#here")`, which means an "area which has id=here". So the program works in such a way that if you click id=here, id=here gets changed. `strong` means bold, which you might use more than twice in a single HTML. So it sometimes becomes difficult to identify which lines you want to apply bold to. That is when id becomes useful. ## Incorporating external JavaScript The HTML above has the below line added. ```html ``` It is a JavaScript program called "jQuery", which is hosted on another website. You can see its code by opening [https://code.jquery.com/jquery-3.3.1.js](https://code.jquery.com/jquery-3.3.1.js). It is a very long code. By writing ` Not online ``` `id=here` can be updated to "Online" once connected to the specified obniz. You already know how to handle a program that changes certain texts by clicking/tapping them. So it should be easy to make LED turn on from HTML when certain texts are clicked/tapped.obniz idTest Open ```html Touch to turn on LED ``` By touching "Touch to turn on LED", wired LED will be turned on. You have already done this in LED lesson. If you connect a temperature sensor instead of LED, you could display the current temperature or draw a temperature graph by incorporating JavaScript chart library. --- ## Turn the motor URL: https://obniz.com/guides/obniz-starter-kit/iot-by-html-and-javascript/rotate-servo-motor Welcome to the HTML / JavaScript lesson page of the obniz Starter Kit!\ First of all, let's turn the "servo motor", which is the most visible part of the obniz Starter kit! ## What is a servo motor? For example, when the user says "Rotate to the position of 60 degrees!", It is a convenient motor that turns to the specified angle.\ When you turn on the power, it keeps spinning like "Vienna", which is different from the ordinary motor you often see. ![](./images/servoHW.gif) ## Connection First, let's take out the servo motor from the bag. ![](./images/servoPackage.jpg) It contains parts called a servo motor and a servo horn (also called a horn). ![](./images/servoContents.jpg) The horn is a part for attaching something first and moving the object, but if you attach it, it is easy to understand the rotation and the direction of rotation, so let's attach it. ![](./images/servoConnection.jpg) Then, let's connect with obniz.\ The servo motor has three wires, which are divided into gnd (ground), vcc (power supply voltage), and signal (signal), respectively. ![](./images/servoPin.jpg) This time, connect as follows. | obniz pin number | Servo motor wire | | :-------------: | :--------------: | | 0 | gnd(Brown) | | 1 | vcc(Red) | | 2 | signal(yellow)| ![](./images/servoPinPosition.jpg) ## Program Now that the connection is complete, let's write the program!\ But you don't have to think hard.\ Each part of the obniz Starter Kit has a "[library](https://obniz.com/ja/guides/obniz-starter-kit/use-parts/)".\ This is a tool in which all the difficult processes originally required to move the servo motor are described in another place, and the user side can operate the parts by giving simple instructions using the library.\ With this library, we can turn the servo motor just by specifying the angle of the servo motor!\ The [Servomotor Library](https://obniz.com/ja/sdk/parts/ServoMotor/README.md), which can actually be accessed from the previous library, describes various ways to handle servomotors.\ Now let's write a program that uses that library.\ [Explanation for using online editor with HTML/JavaScript](https://obniz.com/ja/guides/basics-of-html-and-javascript/first-program), so obniz online editor If you are not confident in how to use, or if you read the program below and find it "difficult", take a look.\ Other than the following two lines, it is the form when programming the basic obniz, so please concentrate on it here.\ These two lines use the "library" mentioned earlier, so let's continue to practice using various parts and learn how to use them while looking at the previous page. ```js var servo = obniz.wired("ServoMotor", { gnd: 0, vcc: 1, signal: 2 }); //Set the library of servo motors servo.angle(90.0); //Set the angle to 90 degrees ``` ```html ``` Try launching this program and the servo motor should work!\ If you don't get an error and say "I can't move ?!", maybe the motor was originally in the 90 degree position, so specify an angle other than 90 degrees and start it again. Let's. ## Evolution: Servo motors alternate between 90 ° ↔ 0 ° Now let's modify the program a little more so that the servomotor alternates between 0 and 90 degrees.\ To keep your program running, you need to [use a loop](https://obniz.com/ja/guides/basics-of-html-and-javascript/how-to-loop). From this document, let's use a loop of the type obniz.repeat () so that when the program is stopped, the servo motor will also stop this time. ```html ``` As you saw at the beginning of this page, did the servo motor wave and return "Hello World!"?\ This is the world of obniz that moves things from the browser.\ In the next lesson, let's do various things unique to HTML / JavaScript using the working servo motor and browser! --- ## Turn the motor from the screen URL: https://obniz.com/guides/obniz-starter-kit/iot-by-html-and-javascript/browser-button-and-servo-motor Hey everyone,Welcome to the HTML/JavaScript lesson page of the obniz Starter Kit!\ In this lesson, you will learn how to use HTML/JavaScript in a browser, in [last lesson](./rotate-servo-motor.md)working,Let's try to move the servo motor!\ The goal is to create a UI that looks like the following and try to move the servo motors! ![](./images/browserOnSmartphone.gif) ## What is a browser? Applications such as Microsoft Edge, Google Chrome, Mozilla Firefox, Safari, etc., which you usually use to watch Youtube or surf the web..\ In fact, HTML/JavaScript is used by these browsers when they run, so you can use HTML/JavaScript to make pages that look like the ones you see on Youtube.(You have to study a lot to get to that level....)\ In this article, we will use an existing program and modify it slightly to make it work easily. ## Placing buttons in HTML Did you look at [Let's run the sample program](https://obniz.com/ja/guides/obniz-starter-kit/start-guide/lesson-run-sample-program)?\ Here, on the last page,I have a button on my browser that lights up an LED..\ Let's make a button in the browser, just like this one.\ For now, copy the program that runs the LED in the link above to an online editor. When you run it, do you see an interface like the following? ![](./images/browserLEDinterface.png) (It's hard to write from the beginning,)we'd like to somehow incorporate this interface into the program we'll be using. This is where the "Starter Kit Guide" [HTML/JavaScript Basics](https://obniz.com/ja/guides/obniz-starter-kit/start-guide/basic-of-html-and-javascript /) in the Starter Kit Guide will be helpful here. If you read this site, you'll see that you can change the text in the HTML section, so let's change the relevant section while referring to this site.\ You should see the text changes if you run the online editor yourself and try it a little at a time. ### Practice 1 - Let's change the word "LED" to "Servo Motor" and the words on the button from "ON" and "OFF" to "0 deg" and "90 deg".\ Hint: Where are the words "ON" and "OFF" located in the program?\ Run the program after making the changes, and if it looks like the following, it is successful. ![](./images/browserServoInterface.png) ### Development 1 (You can proceed without doing this) - In [HTML/JavaScript Basics](https://obniz.com/guides/basics-of-html-and-javascript/), there is a story about how to place ids. \ In this HTML, IDs such as `id="green_on"` are placed, so you should change them to values that are easy for you to understand.\ If you have changed it, please remember to rewrite the corresponding part in JavaScript later. \ Did you get it? If you can't, please check the program at the end of the page. ## Writing programs in JavaScript By writing HTML, the "outside" of the interface is done.\ But this was just a program to light up the LED, so I need to make a program to run the servo motor, right?\ Since JavaScript is in charge of the movement, let's rewrite the part in ``.\ [Let's run the sample program.](https://obniz.com/ja/guides/obniz-starter-kit/start-guide/basic-of-html-and-javascript/), the LED would turn on and off when you pressed a button on the browser. You can change that by using [last lesson](. /rotate-servo-motor.md) to make the servo motor move. The flow of the change is as follows 1. Change the LED library to a servo motor library. 2. Set angle to change the rotation angle of the motor. 3. Change the event that occurs when the button is pressed from lighting the LED to turning the servo motor. Try to figure it out yourself first, and then look at the changes between `` below.\ Also, if you have just rewritten the ID of the text in development 1, don't forget to change the corresponding ID from `'#green_on'` etc. to the ID you have set. ```html ``` Then you can run it in an online editor. ![](./images/browserOnSmartphone.gif) If the servo motor turns to the specified angle when you press the green button, you've succeeded!\ (The movement of the yellow button is not implemented, so you can modify it by yourself to increase the angle.) ## Development: Changing the display Now, let's modify the display to show the current angle of the servo motor.\ In the previous interface, there is a button to show "Hello World" on the obniz display, so let's change it. ### HTML First, let's delete the Hello World part and make the button look like the following. ![](./images/anotherButton.png) Rewrite the corresponding part of the button. ```html --> Print on obniz --> Print degree on obniz ``` ### JavaScript Rewrite the program part of the obniz display.\ If you want to know how to use the display, please look at the [Display](https://obniz.com/ja/reference/common/display) page. ```js $("#showtime").on("click", function () { obniz.display.clear(); // obniz.display.print($("#text").val()); obniz.display.print(angle + " deg"); }); ``` Press the button, and the current angle you set should appear on the obniz display as shown below. ![](./images/printDegOnDisplay.gif) That's it for this development!\ In the next lesson, we'll combine a physical button, a servo motor, and a browser! ## Completed version of the program If this doesn't work for you, take a look at the following program and compare. ```html Connect From Your Browser LED --> Servo Motor ON OFF --> 0 deg 90 deg ON OFF --> +5 deg -5 deg TEXT --> Print on obniz --> Print degree on obniz ``` --- ## Detect button URL: https://obniz.com/guides/obniz-starter-kit/iot-by-html-and-javascript/detect-button-on-browser Welcome to the HTML/JavaScript lesson page of the obniz Starter Kit!\ In the last lesson, we tried to turn the servo motor from the button we put on the browser.\ In this lesson, let's use a "physically pressable button" from the parts and check if the button is pressed in the browser. ## Learn about buttons. The buttons in the Starter Kit have a [documentation page](https://obniz.com/ja/sdk/parts/Keyestudio_Button/README.md).\ (There is a page one level above this one called [Connecting Parts](https://obniz.com/ja/guides/obniz-starter-kit/use-parts/) that explains about each part of the Starter Kit. If you are interested, please have a look.) Now, if you look at this page > onchange = function(pressed){}\ Calls the callback function when the button is pressed or released. There is a function above\ Let's write a program using it. ## Connect the parts The connection should be as follows. ![](./images/buttonConnection.jpg) | Pin number of obniz | Servo motor wire | | :-----------------: | :----------------: | | 0 | signal | | 1 | vcc | | 2 | gnd | Actually, this pin connection corresponds to `{signal:0, vcc:1, gnd:2}` in `obniz.wired` shown below. ```js var button = obniz.wired("Keyestudio_Button", {signal:0, vcc:1, gnd:2}); ``` This means that if you want to connect a button part to another part, you just have to change the corresponding pin number! ## Write the program Once the connection is made, it's programmed..\ As you did in [1. Running a Servo: Simply Rotate a Servo Motor](. /rotate-servo-motor.md), you just need to add a library for buttons to the basic obniz program part.\ If you can afford it, write as much as you can, run it, and then compare it with the program below to see what doesn't work. ```html ``` Now open the console logs (the part that says "Show console logs"), and you will see the following text when you press the button. ![](./images/buttonResultInConsole.png) That's ultimately all this lesson is about!\ Are you a little short?\ That's good, because it means you're getting used to obniz HTML/JavaScript programming! (Maybe it's also because the last lesson was a tough one).\ Now, in the next section, we'll try to add some more movement when the button is pressed! ## Let's make the action when the button is pressed more flashy. ### First, let's get some text on the run screen. Now, you can see in your browser that you have pressed the button in the previous program.\ But even if it's only displayed on the console screen, it's very plain....\ So, let's add an action when the button is pressed.\ First of all, it would be easier to understand if the execution screen shows that you pressed the button.s\ So, let's add some text to the execution screen so that the text changes when the button is pressed. There are comments in the newly added areas, so please read them carefully. ```html Was the button pressed? ``` ### Try to change the background color randomly when a button is pressed. The behavior when the button is pressed is written in the if statement, so let's write the JavaScript to change the background color there. ```js button.onchange = function(pressed){ console.log("pressed " + pressed) if(pressed == false){ $("#press").text("press!"); colors=new Array(10); colors[0]="yellow"; colors[1]="red"; colors[2]="blue"; colors[3]="green"; colors[4]="lime"; colors[5]="brown"; colors[6]="gray"; colors[7]="orange"; colors[8]="purple"; colors[9]="fuchsia"; index=Math.floor(10*Math.random()); document.bgColor=colors[index]; }else{ $("#press").text("not press..."); document.bgColor="white"; } }; ``` Is it done? ![](./images/buttonResultOnBackground.gif) Unlike the keyboard, it would be quite interesting to be able to change the background in the browser via the Internet from a button that is not connected to the PC, wouldn't it? That's it for this lesson!s\ In the next lesson, we'll use the distance sensor to see the distance to an obstacle in numbers! --- ## Measure distance URL: https://obniz.com/guides/obniz-starter-kit/iot-by-html-and-javascript/detect-distance Welcome to the HTML/JavaScript lesson page of the obniz Starter Kit!\ In the last lesson, we checked if a button was pressed by dynamically changing the browser.\ In this lesson, let's use the "distance sensor" from the parts to check if the distance is measured in the browser or on the obniz side. ## How does the distance sensor work in the first place? The distance sensor has an ultrasonic generator, which [generates ultrasonic waves](https://www.google.com/search?q=距離センサ_超音波_原理&tbm=isch) When it hits an object, the sensor receives the reflected ultrasonic wave, and the time T(sec) that it took for the sound wave to travel can be determined. Thus, from here the distance D can be, D = T × 340(m/sec) ÷ 2 calculated by using the formula\ If you know the principle, you know that you can prepare something that easily reflects ultrasonic waves (a flat object such as a plate) and measure the distance. Now, as we have seen, there is a page[Connect the parts](https://obniz.com/ja/guides/obniz-starter-kit/use-parts/) that explains each part of the Starter Kit, so Let's take a look at the [HC-SR04 explanation page](https://obniz.com/ja/sdk/parts/HC-SR04/README.md) from the "Distance Sensor" link. Now, if you look at this page > [await] measureWait()\ It is the same as measure(), but this function returns promise There is a function above.\ Let's make a quick program using this as before.\ (I have explained the principles and formulas, but in the end the library does all the calculations for you. It's very easy.)\ If you are wondering, "What are await and promise?please look up "await promise javascript" in your browser.\ In addition, the terms "synchronous processing and asynchronous processing" will probably come up, so if you look into that as well, you'll get a better understanding of how to program in JavaScript.\ If you have difficulty understanding it, you may want to add or remove await in your obniz program to learn empirically how obniz works differently. ## Write the program As we have done in the previous articles, we just need to add a library for the distance sensor to the basic obniz program.\ However, if we keep the sample as it is, we can only get the distance once, so we can use a loop statement to get the distance continuously.\ Do you remember that the loop statement was previously used in the program [Use Loop](https://obniz.com/ja/guides/basics-of-html-and-javascript/how-to-loop) to move the servo motors alternately?\ This time, I will use obniz.onloop.\ Let's try to write as much as we can and then compare it with the program below.\ (When I say "write," you can copy sentences from the library, or you can try to write them all yourself, at your own discretion!)\ Are you all getting used to thinking and writing on your own by now? ```html ``` If you now open the console logs (the part that says "Show console logs"), you should see the following distances. ![](./images/distanceInConsole.gif) Well, that's it for this lesson... Hmmm... that's a little too much for us, so let's try combining it with other parts again!\ In the next section, we'll use distance sensors and LED signals! ## Let's try to make the distance visually obvious. In the sample program we were running, the `avg` part averaged the distances measured several times (to reduce the variation of the distance sensor values). ```js console.log(avg); ``` I was able to see the distance with a program that displays a statement on the console screen called\ So it would be good if we can change the behavior of the LED signal according to this distance.\ So let's get to work on the items that will make that work!\ It's important to note that...\ ・Declare the two parts properly so that they can be used.\ →When you do this, change the pin numbers where the parts are connected.\ ・Create a variable called "distance" so that it can be used for both ultrasonic sensors and LED signals.\ ・Write conditional branching program statements such as if~else syntax to change the behavior of the LED signal depending on the distance.\ We haven't mentioned the LED signals in the article yet, but you can use them yourself from the [Connect the parts](https://obniz.com/ja/guides/obniz-starter-kit/use-parts/) page!\ If you can do this, you are now an intermediate user and can go to the parts page to see and use the program yourself!\ Now that you have a grasp of the LED signals, let's write the program. Of course, if you have any questions, you can refer to the program below.\ In the program below, the LED signals light up in order depending on the distance. It is up to you to decide which library function to use and how to make it behave.\ It would also be interesting to have it glow randomly. ```html ``` Now, when you run this (in my program), the LED signals will light up depending on the distance: near -> red, medium -> yellow, and far -> green. ![](./images/LEDalongDistance.gif) The parts are connected as shown in the picture below, distance sensor: 0~3 pins, LED signal: 4~7 pins. ![](./images/pinPositionOfLEDandDistance.jpg) If you look at the declaration part of obniz.wired(), you will see that it does indeed.\ How did you make it behave? If it works the way you want it to, you've succeeded!\ Please keep on modifying the samples in the article and writing programs from the beginning, and try various combinations of your own parts to make it work! ## Development: Let's make a distance guessing game. In this development, we will try to create a game using a distance sensor that can be played by any number of people.\ For example, how about a game where you randomly choose a target distance value and guess it? 1. In the program, [randomly determine the distance](https://lab.syncer.jp/Web/JavaScript/Snippet/15/). 2. Insert the board in front of the distance sensor at the place where you think it should be.\ The LED signal is lit according to the distance from the target value. (close -> red, medium -> yellow, far -> green, etc.) 3. After a few times of taking turns, if you win, congratulations!Turn on all the LEDs! We will try to write this program based on the previous program.\ As I said before, if you have an idea to make it more interesting,let's modify it! ```html ``` --- ## Graph display of temperature URL: https://obniz.com/guides/obniz-starter-kit/iot-by-html-and-javascript/temp-sensor-on-graph Welcome to the HTML/JavaScript lesson page of the obniz Starter Kit!\ In the last lesson, we learned that we can get a specific distance in succession with a distance sensor. (By the way, I think we can now use LED signals as well).\ In this lesson, we will use the "temperature sensor" from the parts, and display the value of the temperature sensor on a graph in real time. ## About the JavaScript plugin JavaScript has a variety of plugins (libraries in the program) that can draw animations, draw graphs, and make writing programs much easier.\ In this article, we'll use a JS plugin called Chart.js to generate a graph of the temperature values obtained from the temperature sensor!\ [Chart.js](https://misc.0o0o.org/chartjs-doc-ja/) ![](./images/tempSensorGraph.gif) ## Write the program From the link given above, you go to [Install] -> [Use Chart.js CDN] (https://cdnjs.com/libraries/Chart.js) you will find various links.\ Depending on the situation, you can use it as a JavaScript library by writing ".min.js" or ".js" in the header of your HTML.\ So let's copy and paste it into the obniz program... But it says "obniz.js" in the same place.. ![](./images/JSlibrary.png) Well, actually, obniz is just another JavaScript library used in this HTML file! So, you can jump to the link given there to see the list of libraries running obniz.\ Of course, since you are a user of obniz, you don't need to read this section as you do with other libraries.\ Let's use it conveniently.. Now that Chart.js has been added to the HTML, let's take a look at how to use it.\ The various ways to use Chart are described in [Chart.js](https://misc.0o0o.org/chartjs-doc-ja/), so please look at it or search for it to understand how Chart is set up in the sample program.\ The sample program has a simple structure, so of course you can add as many features as you want!\ After that, we will use obniz's temperature sensor library, so let's see how to use it in [Temperature Library](https://obniz.com/ja/sdk/parts/Keyestudio_TemperatureSensor/README.md).\ No need to explain the parts in detail anymore, as the onchange function will send the temperature as needed. Now we just need to combine the Chart.js library with the temperature sensor library! ```html ``` Do you have a graph that can be updated one after another? ![](./images/tempSensorGraph.png) If you feel that the update is too fast! If you feel that the update is too fast, you can use obniz.repeat() to specify the number of seconds to run the loop. ## Development:Let's use WebApp obniz has an "app" feature.\ This is a HTML/JavaScript or block program written by someone and published in the form of an application.\ If you find something you want to use there, you can quickly install it and use it, which is very convenient.\ See [What is a browser application](https://obniz.com/ja/guides/browser-app/about) for a brief explanation.\ Parts libraries take care of the details of parts for you, and WebApps are like a superordinate entity that takes care of "every function" for you.\ Very luckily (...?) There is a graphing application that uses the same temperature sensor, so let's use it. ・[Temperature Graph & WebApp Page](https://blog.obniz.com/make/real-time-temperature-recording/) On the WebApp page, you will find several options, including the following.\ If you want to try out the various options, click "Install" and run it, then click\ If you are curious about what is actually written in the program, you can run it from [View Program], and then click\ If you just want to try it out, click [Run Now] to run it.\ (Account and device registration are required for installation..\ If you haven't completed it yet, please be patient, as more details will be presented in [next lesson](./making-webapp.md), so please be patient!!) ![temperatureWebApp](./images/temperatureWebApp.png) Can you display the temperature graph as shown in the following image from the [WebApp page for temperature graph](https://obniz.com/ja/webapp/1)?\ ![TemperatureLogger](images/TemperatureLogger.png) It's great to be able to use the IoT to achieve the functions you want right away without writing any programs like this.\ Of course, if the feature you want is not on the app page, you can create your own app using the HTML/JavaScript knowledge!\ Isn't it exciting to be able to create and publish an app with features that have never existed before, and have other people use your app?\ In the next article, I'll talk about the creation and publishing of this application in more detail. So long! --- ## Let's make an app URL: https://obniz.com/guides/obniz-starter-kit/iot-by-html-and-javascript/making-webapp Welcome to the HTML/JavaScript lesson page of the obniz Starter Kit!\ In the previous lesson, you registered your account and device, installed the WebApp on your device, and ran the temperature sensor.\ In this lesson, we'll finally try to create a WebApp by ourselves! ## Make an WebApp. There is an official article [Create an app](https://obniz.com/ja/guides/browser-app/create-app), so let's follow it to create an app. - From the user page, select [App Development] > [Create New]. ![appCreate](./images/appCreate.png) - Select [Empty Project] from your device (e.g. obniz1Y) and give it an appropriate name. It's a time signal, so you can call it "jihou"... ![emptyProject](./images/emptyProject.png) - In the settings screen, you can set what kind of behavior you want to include in the app.\ Since we will be creating a time signal, enter "every/10minutes" in the [Run by time] field so that we can check the operation every 10 minutes.(The limit of automatic execution by obniz is 144 times/day = 10 minutes/time.)\ Therefore, if you also check the [Run when device is online] checkbox at this time, the program will run as soon as obniz is turned on, so it will be easier to check the operation of the application.\ If you want to make the program available to all users, you can check the [Public] checkbox, and if you want to make the program available only to a limited number of users, you can share it by clicking the [Limited URL Link]. ![](./images/appSetting.png) - When you are done, click the [Update Settings] button at the bottom of the page to update the settings, and then click [Edit Program] at the top of the page to write the program to run.\ The template is available in advance, and you can add the library programs for the parts you want to use.\ This time we use a time signal,and we use the buzzer from the kit..\ Go to [Parts Page](https://obniz.com/ja/sdk/parts/Keyestudio_Buzzer/README.md) and look up the function that sounds the buzzer to make a time signal.An example of the program is shown below.\ Leave "OBNIZ_ID_HERE" as it is, because the app will get the ID automatically! ```html ``` Once you've done this, click [Ctrl]+[S] or [Save] from the [File] button to save the file, then go back to the app settings page and select [Install on my device]. ![appInstallToDevice](./images/appInstallToDevice.png) Check the ID of the obniz device you want to install and install it. ![selectObnizID](./images/selectObnizID.png) That'll be all! After that, let's make sure that the program runs automatically every 10 minutes and the time signal signals.\ If all goes well, you should see a green circle in the [App Status] column to indicate that the app is working properly.\ If there is no change in the display, try refreshing the page.\ If this doesn't work, you can check the status of the apps you have set up on your device from [Device], and check the errors that appear here.\ In particular, for errors such as "30000ms Timeout", please use Obniz.App.done() to check if the application is terminated and if there are any misspellings in the variables. ![deviceStatus](./images/deviceStatus.png) If it worked, now go to the app's settings and change "every/10minutes" to "every/1hour" and you've got a time signal! Other explanations about web apps and what they can do can be found at [Making browser apps](https://obniz.com/ja/guides/browser-app/), so if you're interested in learning more about them, please study them a bit more. No developments this time!\ If you're not satisfied, you can create your own beat and note functions and play a song with the buzzer sound played by the time signal.\ It is recommended that you use the buzzer to play 8-bit songs from games of the past.\ If you set it for a certain time every day, you can wake up to your own music... Oh my god... Next time, as a development of what we did this time, we would like to "record the temperature value by running the app regularly and check it with the app status". Please look forward to the next time! --- ## Make an hourly time signal URL: https://obniz.com/guides/obniz-starter-kit/iot-by-html-and-javascript/making-timesignalwebapp Welcome to the HTML/JavaScript lesson page of the obniz Starter Kit!\ In the previous lesson, you registered your account and device, installed the WebApp on your device, and ran the temperature sensor.\ In this lesson, we'll finally try to create a WebApp by ourselves! ## Make an WebApp. There is an official article [Create an app](https://obniz.com/ja/guides/browser-app/create-app), so let's follow it to create an app. - From the user page, select [App Development] > [Create New]. ![appCreate](./images/appCreate.png) - Select [Empty Project] from your device (e.g. obniz1Y) and give it an appropriate name. It's a time signal, so you can call it "jihou"... ![emptyProject](./images/emptyProject.png) - In the settings screen, you can set what kind of behavior you want to include in the app.\ Since we will be creating a time signal, enter "every/10minutes" in the [Run by time] field so that we can check the operation every 10 minutes.(The limit of automatic execution by obniz is 144 times/day = 10 minutes/time.)\ Therefore, if you also check the [Run when device is online] checkbox at this time, the program will run as soon as obniz is turned on, so it will be easier to check the operation of the application.\ If you want to make the program available to all users, you can check the [Public] checkbox, and if you want to make the program available only to a limited number of users, you can share it by clicking the [Limited URL Link]. ![](./images/appSetting.png) - When you are done, click the [Update Settings] button at the bottom of the page to update the settings, and then click [Edit Program] at the top of the page to write the program to run.\ The template is available in advance, and you can add the library programs for the parts you want to use.\ This time we use a time signal,and we use the buzzer from the kit..\ Go to [Parts Page](https://obniz.com/ja/sdk/parts/Keyestudio_Buzzer/README.md) and look up the function that sounds the buzzer to make a time signal.An example of the program is shown below.\ Leave "OBNIZ_ID_HERE" as it is, because the app will get the ID automatically! ```html ``` Once you've done this, click [Ctrl]+[S] or [Save] from the [File] button to save the file, then go back to the app settings page and select [Install on my device]. ![appInstallToDevice](./images/appInstallToDevice.png) Check the ID of the obniz device you want to install and install it. ![selectObnizID](./images/selectObnizID.png) That'll be all! After that, let's make sure that the program runs automatically every 10 minutes and the time signal signals.\ If all goes well, you should see a green circle in the [App Status] column to indicate that the app is working properly.\ If there is no change in the display, try refreshing the page.\ If this doesn't work, you can check the status of the apps you have set up on your device from [Device], and check the errors that appear here.\ In particular, for errors such as "30000ms Timeout", please use Obniz.App.done() to check if the application is terminated and if there are any misspellings in the variables. ![deviceStatus](./images/deviceStatus.png) If it worked, now go to the app's settings and change "every/10minutes" to "every/1hour" and you've got a time signal! Other explanations about web apps and what they can do can be found at [Making browser apps](https://obniz.com/ja/guides/browser-app/), so if you're interested in learning more about them, please study them a bit more. No developments this time!\ If you're not satisfied, you can create your own beat and note functions and play a song with the buzzer sound played by the time signal.\ It is recommended that you use the buzzer to play 8-bit songs from games of the past.\ If you set it for a certain time every day, you can wake up to your own music... Oh my god... Next time, as a development of what I did this time, I would like to "record the temperature value by running the app regularly and check it with the app status". Please look forward to the next time! --- ## Periodic temperature record URL: https://obniz.com/guides/obniz-starter-kit/iot-by-html-and-javascript/showtempinappstatus Welcome to the HTML/JavaScript lesson page of the obniz Starter Kit!\ In the last lesson, you created your own web application and made a time signal that runs periodically and sounds a buzzer.\ In this lesson, we'll take advantage of that periodic run to display the room temperature in the app status! ## Create an app [7. Making a time signal: Buzzer every hour with an app](./making-timeSignalWebApp.md), and create a new app that runs periodically every 10 minutes with an empty program. \ When setting up, check the [Run when device is online] checkbox to make sure it works this time. Once you have created the program, open [Edit Program] and create a program like the one below.\ In order to "add the values from the temperature sensor to the graph," ,which was also used in [5. Graphing: Real-time graphing of temperature sensor values](./temp-sensor-on-graph.md), let's use the sample from the [temperature library](https://obniz.com/ja/sdk/parts/Keyestudio_TemperatureSensor/README.md).\ In this case, we will use the `getWait()` function since we only need to get the value once by running the application. Now, we would like to check this temperature in the application status.\ The app status not only allows you to easily check if the app is running in the browser, but also allows you to view arbitrary values set by the user.\ Well, where is the app status ... As I mentioned a little in the previous article, that is the ribbon of [Device]. ![](./images/deviceStatus.png) Then, how to display numerical values ​​such as temperature here?\ There is a page called [App Status of Cloud Execution](https://obniz.com/ja/guides/browser-app/appstatus) that explains the app status, so let's take a look.\ Here is a sample program that is best fitting. ```js if (Obniz.App.isCloudRunning()) { var temp = '27' Obniz.App.done({ status: 'success', text: `${tmp} degree` }) } ``` So it seems good to put the value obtained from the temperature sensor in this temp. ```html ``` Now install this app on obniz and turn on obniz! Check that the status is updated from [Device] and the temperature is displayed. ![showTempInStatus](./images/showTempInStatus.png) After that, check if it is updated every 10 minutes.\ Let's wait patiently while drinking tea.\ When you look at the status again for a while, you can see that the temperature in the status column has changed or that it has been updated from the "... minutes ago" display in the status column. If you can, this lesson is over! Next time, let's display the weather information obtained regularly from the Internet instead of the temperature sensor on the LED traffic light and obniz screen. Please look forward to the next time! ## Development: Show error There is a sample that throws an error depending on the threshold on the page [App status of cloud execution](https://obniz.com/ja/guides/browser-app/appstatus) that you browsed earlier.\ This sample seems to return an error if it is above 30 ° C, so try setting it low to intentionally give an error. ```js if(temp > 5) { Obniz.App.done({ status: 'error', text: `Too hot ${temp.toFixed(1)} degree` }) } else { Obniz.App.done({ status: 'success', text: `It's fine ${temp.toFixed(1)} degree` }) } ``` If you try to execute it and get the following error, it is successful. ![](./images/appStatusError.png) In this way, you can easily check any numerical value and notify an error if there is an abnormality.\ Wouldn't it be very convenient to be able to check the temperature and other numerical values ​​of the place and detect errors from the browser in a place where obniz is not normally accessed?\ This development is over! --- ## Works with Google Home URL: https://obniz.com/guides/obniz-starter-kit/iot-by-html-and-javascript/ifttt Welcome to the HTML/JavaScript lesson page of the obniz Starter Kit!\ In the last lesson, we used the regular execution of the web application to display the room temperature in the application status.\ In this lesson, let's use Google Assistant to call the obniz web application from your smartphone! ## IFTTT : Cooperation between obniz and Google assistant You probably already know that you can run obniz from your smartphone via a browser.\ However, this time, we would like to put Google Assistant on my smartphone and "operate obniz by voice".\ Therefore, let's use [IFTTT](https://ifttt.com/), which allows you to easily connect various Web services and devices! ## Preparation: Insert Google assistant Let's put Google assistant on your smartphone.\ Search for "Google assistant" in the App Store for iPhone and Play store for Android, and install it.\ As will be described later, if the application can be triggered by IFTTT, it is actually OK even if you are not a Google assistant. ## Write a program for obniz This time, let's program with the story that when you say "attach a rice cooker" with Google Assistant, the servo motor attached to obniz operates and you press the switch of the rice cooker.(You don't have to actually prepare a rice cooker.)\ Let's let people know that the rice cooker is switched on by attaching an LED matrix when the servo motor moves. In other words, this time, "[Servomotor](https://obniz.com/ja/sdk/parts/ServoMotor/README.md)" and "[LED Matrix](https://obniz.com/ja/sdk/parts)" /Keyestudio_HT16K33/README.md) ”will be used. See how to use each parts library from the link, and create a program such as "When the program works, rotate the servo 90 ° to turn on the rice cooker and display" O "in the LED matrix" (if possible, yourself Let's write it.\ As an example, the program example is shown below.\ The LED matrix is ​​set to pins 0 to 3 and the servo motor is set to pins 9 to 11.\ The LED matrix seems to have the opposite VCC and GND, so be careful and proceed by looking at the library page. ```html ``` ## Create a WebApp After confirming the operation of the program, let's make the program a WebApp and set a Webhook.\ Webhook is a function to access a certain URL.\ Especially in obniz, you can start the obniz program via URL. [6.Create a WebApp](./making-WebApp.md)Create a new WebApp like the previous articles.\ At this time, check "Run with Webhook" on the setting screen to enable Webhook. ![ON_Something_AppSetting](./images/ON_Something_AppSetting.png) After creating the program, edit the program. Edit the program of the application from [App Development]-[Edit Program].\ However, all you have to do is port the script part of the program, that is, the Java Script part, into obniz.onconnect and add Obniz.App.done to tell the WebApp that the program is complete. ```html ``` If you finish it, check the URL of the Webhook from [Device]-[Check Webhook URL]. ![webhookURL](./images/webhookURL.png) ![webhookURL2](./images/webhookURL2.png) ## Cooperate with IFTTT Then, the next step is to implement the IFTTT function. Create an account from [Get started]. ![](./images/IFTTTguide0.png) If you finish it, create IFTTT from [create]. ![](./images/IFTTTguide1.png) First, select the application to be used as a trigger from [If This]. ![](./images/IFTTTguide2.png) Select Google assistant and select the same Google account that you are using with Google assistant from [connect].\ As mentioned earlier, you can choose an application that is not a Google assistant at this point. ![](./images/IFTTTguide3.png) Register the phrase that will trigger something.\ It's important to note that the word combination should be recognizable by the Google assistant.\ As an example, the following phrase uses "obnize", but this is not a general word and it is highly likely that it will not be recognized, so it is necessary to use another phrase. (Turn on a rice cooker, etc.) ![](./images/IFTTTguide4.png) Then, this time, search for the webhook from [Then That] and select it. ![](./images/IFTTTguide5.png) On the webhook setting screen, paste the URL of the webhook confirmed on the obniz device earlier. ![](./images/IFTTTguide7.png) Press [finish] from [continue] to complete the creation. ![](./images/IFTTTguide8.png) with this\ Say a specific phrase with Google assistant → obniz is executed from Webhook \ you were able to create the flow. ## Run Start Google assistant on your smartphone and speak your own words such as "Turn on the rice cooker".\ If IFTTT reacts and the servo motor connected to obniz moves, it is successful! ![](./images/googleAssistant.jpg) ![](./images/IFTTToutput.gif) If you apply this technology, you can make electrical appliances with switches all over the house.\ Internet → obniz → servo motor → home appliance switch\ You will be able to operate it!\ This is exactly IoT, a technology that you were able to learn through the lessons of the obniz starter kit! ## At the end This is the end of the HTML / JavaScript lesson, but you already know how to use obniz to use your IoT.\ From here, please try various things with obniz! See you in an obniz article somewhere. goodbye! --- ## About BlockProgram URL: https://obniz.com/guides/obniz-starter-kit/iot-by-block-programing/about-block-programing # What is a block program? Welcome to the block program lesson page of obniz Starter Kit! In this lesson, you will learn what you can do with the obniz Starter Kit while creating a block program. You can try them all in order, or start with what you are interested in. Please try while moving your hands together. ## About block programs As the name implies, a block program is programming in which blocks are arranged side by side. You can create a program more intuitively than programming by writing letters by yourself. In "[Introduction to Block Programs](https://obniz.com/ja/guides/block-programing/)", block programs are explained carefully from the basics. In this lesson, we will explain with reference to this introductory lesson of the block program as appropriate. You don't have to do all the lessons in advance, but if you find it difficult along the way, take a look at the relevant block program introductory page. ## Preparing obniz Now, let's move obniz by referring to "[Quick Start](https://obniz.com/ja/guides/block-programing/start)" in the introduction to block programs. Connect obniz to Wi-Fi and open the block program editor. Did you proceed to the screen where the following program is displayed? ![iotblock_01_01](images/iotblock_about_01.png) Where OBNIZ_ID_HERE is written, the obniz ID of your obniz will be entered. All programs that will appear in lessons in the future will also have this notation, so make sure that you have your own obniz ID before proceeding. Let's run it. Did you see the words "Hello, World!" On the display? If it looks good, you're ready to use the obniz Starter Kit. From the next lesson, let's move the parts of the obniz Starter Kit! --- ## Rotate the motor URL: https://obniz.com/guides/obniz-starter-kit/iot-by-block-programing/rotate-servo-motor # Move Servo: Simply Turn the Servo Motor From this lesson, we will use the parts of the obniz Starter Kit. First, let's move the "servo motor" that is easy to understand. ## What is a servo motor? When you think of a motor, it may be a motor that keeps spinning when you turn it on. Servo motors are different from such motors in that they can be rotated to a specified angle. ![](./images/servoHW.gif) Since it can be moved to a specified angle, it is often used for joints of robots. This time, we will try to move such a servo motor by specifying an angle. ## Connection Now, let's connect the servo motor to obniz. First, remove the servo motor from the bag. ![](./images/servoPackage.jpg) It contains parts called a servo motor and a servo horn (also called a horn). ![](./images/servoContents.jpg) The horn is a part for attaching something first and moving the object, but if you attach it, it is easy to understand the rotation and the direction of rotation, so let's attach it. ![](./images/servoConnection.jpg) Then, let's connect with obniz. The servo motor has three wires, each of which is divided into gnd (ground), vcc (power supply voltage), and signal (signal). ![](./images/servoPin.jpg) This time, connect as follows. | obniz pin number | Servo motor wire | | :-------------: | :----------------: | | 0 | gnd(Brown) | | 1 | vcc(Red) | | 2 | signal(Yellow) | ![](./images/servoPinPosition.jpg) ## Program Next, let's create a program to rotate the servo motor. The "[Let's program all together](https://obniz.com/ja/guides/block-programing/pickandplace)" introductory to block programming explains how to use the block editor. If you don't know how to operate, please refer to here. If you select the "Kit" category on the left, three categories will appear: "AIRobot Kit", "IoT Home Kit", and "Starer Kit". Try opening the third "Starter Kit". ![iotblock_02_01](images/iotblock_rotateservo_01.png) It contains blocks for using the Starter Kit parts. In future lessons, you will be able to select and use blocks from here. This time scroll to the bottom and use the "ServoMotor" block. ![iotblock_02_02](images/iotblock_rotateservo_02.png) Arrange these blocks and create a program like the one below. ![iotblock_02_03](images/iotblock_rotateservo_03.png) When you run the program, the servo motor should work. If it doesn't move, the servomotor angle may have been 90 degrees originally, so specify a different angle and try again. ## Development: Alternately move servo motors Let's modify the program a little more so that the servomotor alternates between 0 and 90 degrees. Use loop blocks to keep your program running all the time. Reference: [To move the block all the time](https://obniz.com/ja/guides/block-programing/block-repeat) This time, we will use the "Run all the time" block and the "Wait" block to create a program in which the servo motor goes back and forth between 0 and 90 degrees every second. Note that the unit of the "wait" block is ms (milliseconds), so enter 1000 (ms) to wait 1 second. ![iotblock_02_04](images/iotblock_rotateservo_04.png) Did it work? In a block program, you can easily move various things just by combining blocks in this way. Now that you can move the servo motor, let's try to operate this servo motor on the browser! --- ## Rotate the motor from the screen URL: https://obniz.com/guides/obniz-starter-kit/iot-by-block-programing/browser-slider-and-servo-motor # Move the servo with the slider: Let's turn the servo motor to the right and left with the slider displayed in the browser. Now that you can move the servo motor in [Last lesson](rotate-servo-motor-ja.md), let's move the servo motor using the browser. By moving the slider on the browser, you can freely change the angle of the servo motor. ## What is a browser? A browser is an application that you use to browse websites. You are watching this lesson article or doing a block program on your browser screen. In the block program editor, when you press the execute button, the following screen will be displayed. ![iotblock_03_01](images/iotblock_slider_01.png) Displaying the slider on the browser means displaying the slider on this screen. This time, let's make the following screen so that you can operate the servo motor! ![iotblock_03_02](images/iotblock_slider_02.png) ## UI block Block programs include UI blocks that can display various things on the browser. First, let's open the "UI" category and take a look. ![iotblock_03_03](images/iotblock_slider_03.png) There are five types: UI Button, UI Label, UI Slider, UI Image, and Debug. The following is displayed in each browser (light blue letters are comments for explanation). ![iotblock_03_04](images/iotblock_slider_04.png) We will create an operation screen using the UI slider and UI label in this (I will also use debugging in the middle of the lesson). If you want to use UI buttons, please read "[Let's work with UI buttons](https://obniz.com/ja/guides/block-programing/uibutton)" in the introduction to block programming. ## UI slider First, let's use the UI slider. Bring blocks from UISlider and Debug and try to create a program like the one below. In the "text" of "Display" text "on the console", we put the "slider value" block of UISlider. (It is easier to put it in if you bring it so that the finger or mouse holding the block can put it in the place you want to put it in) ![iotblock_03_05](images/iotblock_slider_05.png) Let's run it. ![iotblock_03_06](images/iotblock_slider_06.png) A slider appears on the screen and a number appears on the console. If you move the slider left or right, the numbers in the console log will change. (If you don't see the console, you can see it by pressing "Show console logs") The console is a place where you can communicate with your computer, and if something goes wrong or an error occurs in your program, a message will be displayed on the console. The debug block allows you to display any text you like on this console. If you move the slider from the leftmost to the rightmost, you can see that the number changes from 0 to 100. If you program the value of this slider to be the angle of the servo motor, it seems that you will be able to operate the servo motor freely between 0 degrees and 100 degrees. let's do it! > 注意 > サーボモーターに指定できる角度は範囲が決まっており、Starter Kitのサーボモーターは0度から180度までです(ブロックで直接入力できる数字も0〜180になっています)。 > 範囲外の角度に指定してしまうと、サーボモーターが壊れてしまう可能性があります。 > 今回はスライダーの値が0〜100なことを確認しましたが、今後自分でプログラムを書く場合や、別のサーボモーターを使う場合などは、範囲外にならないように気をつけてください。 ## Program The slider value displayed on the console is used to specify the angle of the servo motor. Recall the program that made the servo motor angle 90 degrees in the previous lesson. ![iotblock_03_07](images/iotblock_slider_07.png) Once you have a program, let's run it. It is successful if the servo motor rotates in response to the slider. However, in this state, we do not know what the angle of the servo motor is. Since it's a big deal, let's try to display the angle on the screen using the UI label. UI labels allow you to display your favorite text on the screen. Prepare a space for writing text in the "Create label" block, and display the text entered in the "Display ~ with label" block. The final program looks like this: ![iotblock_03_08](images/iotblock_slider_08.png) Let's run it.If you can operate the servo motor with the slider and the angle is also displayed, it is a great success! If the label display is above the slider, try reversing the order of the "make slider" block and the "make label" block. Since the block program is executed in order from the top, the block above is also on the browser screen. This concludes the servo motor lesson. Next time, let's use the button parts! --- ## Detect button URL: https://obniz.com/guides/obniz-starter-kit/iot-by-block-programing/detect-button-on-browser # Use Buttons: Check in your browser if the button was pressed Now that you can use the servo motor in the previous lessons, let's use the button parts. Last time we used the browser to move the servo motor, but this time we will change the display of the browser using the button. ## Connection First, connect the button to obniz.The parts shown in the picture are the buttons.You can detect that it has been pressed. ![iotblock_04_01](images/iotblock_button_01.jpg) [The Starter Kit Guide Parts Page](https://obniz.com/en/guides/obniz-starter-kit/use-parts/) introduces each part of the kit.You can also go to the details page from the part name on the left. Please refer to it when you do not know which part is what or when you want to know more about each part. Like the servo motor, the button has three pins, which are S (signal), V (vcc), and G (gnd), respectively. This time, connect as follows. | obniz pin number | Button pin | | :-------------: | :----------------: | | 0 | signal(S) | | 1 | vcc(V) | | 2 | gnd(G) | ![iotblock_04_02](images/iotblock_button_02.jpg) ## Program Now let's make it possible to confirm in the browser that the button has been pressed. There are two types of button blocks in the Starter Kit category. Make a program using these. ![iotblock_04_03](images/iotblock_button_03.png) First, arrange the blocks that connect the buttons to obniz, as in the case of the servo motor. ![iotblock_04_04](images/iotblock_button_04.png) From here, we would like to create a program that displays characters on the console when a button is pressed. To create a program such as "If a button is pressed, a character is displayed" or "If ...", use a block. Select the "If Run" block in the "Logical" category. Reference: [IF Block] (https://obniz.com/guides/block-programing/uibutton#%E3%82%82%E3%81%97%E3%82%82%E3%83%96%E3%83%AD%E3%83%83%E3%82%AF) If the block condition part (the diamond that is true), put the block where the Starter Kit button is pressed. (It is easier to put it in if you bring it so that the finger or mouse holding the block can put it in the place you want to put it in) To display the characters on the console, use the debug block you used in [the previous lesson](browser-slider-and-servo-motor-ja.md). The debug block is in the UI category. Enter the characters you want to display in text when the button is pressed. ![iotblock_04_05](images/iotblock_button_05.png) If this is left as it is, it will be judged only once immediately after the program is started, and it will not be judged after that, so nothing will happen even if the button is pressed.Put it inside a loop block so that it can be judged many times. ![iotblock_04_06](images/iotblock_button_06.png) The rest is completed by arranging these. ![iotblock_04_07](images/iotblock_button_07.png) Let's run it. If you see the letters on the console when you press the button, you're good to go! ![iotblock_04_08](images/iotblock_button_08.png) ## Evolution: Press a button to move the illustration on the browser Let's make what happens when a button is pressed more dynamic than just displaying characters. Try using a UI image that you haven't used yet in the UI category. The program to make is that the illustration displayed on the browser moves to the right when the button is pressed. If you can make it, please try to make your own program before seeing the answer. The basic usage of the UI image is the same as other UI blocks, and you can display the illustration on the screen with the "Create image" block. You can choose an illustration where it defaults to "banana". You can use any illustration you like, but we chose "dog" as an example to move. After that, when the button is pressed, execute "Move image 10px to the right". ![iotblock_04_09](images/iotblock_button_09.png) Did the illustration move to the right by the amount you pressed the button? It's fun to be able to operate the browser via the Internet using buttons that are not connected to the PC. In the next lesson, we'll use the distance sensor! --- ## Measure distance URL: https://obniz.com/guides/obniz-starter-kit/iot-by-block-programing/detect-distance # Check the distance: Check the distance to the obstacle numerically In [the previous lesson](detect-button-on-browser-ja.md), we confirmed in the browser that the button was pressed. This time, let's check the distance with a browser using the distance sensor. ## What is a distance sensor? In the first place, what is a sensor is a device that detects external information and converts it into signals and data.Like the five human senses, it has the role of "perception" in machines. Among such sensors, the distance sensor is, as the name implies, a sensor that measures distance. An object is measured by generating a signal and detecting the time it takes for it to hit the object and bounce off, and the strength of the signal when it returns. The output signal varies depending on the sensor such as laser, infrared ray, ultrasonic wave, etc., and the distance that can be measured and the usage situation vary depending on the signal. Included in the Starter Kit is the ultrasonic sensor shown in the photo below. Since ultrasonic waves are sound waves, they are not affected by the color of the object and have the advantage of being able to be used even in dark places. ![iotblock_05_01](images/iotblock_distance_01.jpg) ## Connection There are four pins on the distance sensor, which are gnd, echo, triger, and vcc, respectively. This time, let's connect as follows. | obniz pin number | Distance sensor pin | | :-------------: | :----------------: | | 0 | gnd | | 1 | echo | | 2 | triger | | 3 | vcc | ![iotblock_05_02](images/iotblock_distance_02.png) As you may have noticed in previous lessons, this pin number corresponds to the number entered in the "Connect to obniz" block during programming. ![iotblock_05_03](images/iotblock_distance_03.png) So, if you enter the numbers in this block correctly, it doesn't matter where you insert the part. In future lessons, we will omit the connection table and images, so check the program to see which pin to insert. ## Program Now, let's make it possible to check the value measured by the distance sensor on the browser. Again, we'll display the distance sensor value on the console. ![iotblock_05_04](images/iotblock_distance_04.png) It's the same as what we've done so far, so it might be easy. The point is to put it in a loop so that you can check it all the time. Let's run it. If you move your hand or object closer to or further away from the distance sensor, the numbers will change. ![iotblock_05_05](images/iotblock_distance_05.png) ## Development: Make music play when you bring your hands closer Since it is a special sensor, let's detect that your hand is approaching and play music. In the block program, there are blocks that can play music. It is a block of "play song" in the "AI" category. ![iotblock_05_06](images/iotblock_distance_06.png) You can choose from two types of songs, "Happy Birthday" and "Jingle Bell". In the sample program, try to play the "jingle bell" when you get close to it. The program that "plays music when you get close to your hand" is in the form of "if you do." It seems that the "IF block" used in [Last lesson](detect-button-on-browser-ja.md) can be used. ![iotblock_05_07](images/iotblock_distance_07.png) If I want to put the condition "when my hand approaches" in the block condition (true part), but unlike the button, there is no block that can be used as it is. Let's think about whether it is possible to create a condition "when the hand approaches" using the distance sensor. As I saw on the console earlier, the value of the distance sensor becomes smaller as the object gets closer (naturally because the distance is measured). Therefore, if we can create a condition that "when the value of the distance sensor becomes smaller than a certain value", it seems that we can judge that "the hand is approaching". The "Logic" category, which contains blocks, contains four types of diamond-shaped blocks that can be used to create conditions. ![iotblock_05_08](images/iotblock_distance_08.png) This time, we will use the block at the top of which you can compare numbers. ![iotblock_05_09](images/iotblock_distance_09.png) In this block, you can select equal signs and inequality signs and compare the magnitude of the left and right numbers. Select the inequality sign and enter the values in the left and right ellipses so that the conditional expression "when the value of the distance sensor becomes smaller than a certain value" is obtained. ![iotblock_05_10](images/iotblock_distance_10.png) If the number on the right is large, it will respond even if your hand is far away, and if it is small, it will not respond unless you get as close as possible. Make your own adjustments while looking at the values displayed on the console to see what value is right for you. Now that the conditions are complete, insert it into the diamond-shaped part of the block. Bring your finger or mouse holding the block where you want it. ![iotblock_05_11](images/iotblock_distance_11.png) The rest is complete if you combine this block with the program you created first. Don't forget to put it in a loop so that it will be judged many times. ![iotblock_05_12](images/iotblock_distance_12.png) Make sure the volume on your PC is not muted and try running it. Did the music play when you brought your hands closer? By adjusting the installation location and numerical values, it seems possible to detect the arrival of a person and create a door open / close sensor. If you measure the distance to the lid of the box, you can play Happy Birthday music when you open the box and use it for birthday surprises.(Reference: [Birthday song that plays when you open the box](https://blog.obniz.com/make/open-the-box-and-play-song/)). You can do various things depending on your ideas, so please come up with some ideas and think of fun ways to use them! --- ## Let's make an app URL: https://obniz.com/guides/obniz-starter-kit/iot-by-block-programing/make-app # Create an app: Introducing what you can do with the app, creating an account and registering a device With obniz, you can publish your program as an app. In this chapter, we will prepare what an app is and how to make it from the next time onwards. ## What is an app? An app is registered in the cloud so that the program can be used on various devices. You can see the apps that are open to the public on the "[Find apps](https://obniz.com/ja/webapp)" page. From these apps, you can install and use your favorite apps on your device. ![iotblock_06_01](images/iotblock_app_01.png) I think that everyone usually puts the apps selected in the store on their smartphones and uses them. The obniz app has the same image, and if you install an app created by someone on your device, you can easily use useful functions. ![iotblock_06_02](images/iotblock_app_02.png) You can also make your own app.It needs to be reviewed before it can be opened to the public so that anyone can search it, but since it can be published with a limited link, you can share the app with obniz users other than yourself by sharing the link(You can keep it private so that only you can use it). Creating a program as an app has the following advantages in addition to the advantage that it can be easily shared with other people. - It can be created from a template. - You can run a program on the cloud with something as a trigger. From the next lesson, we will use the parts of the Starter Kit, create various apps, and check what you can do with the apps. It's okay if you don't understand the benefits of the app yet. As with the previous lessons, let's move our hands to create a program and check it together. By the way, there are two main types of apps: "browser apps" and "hosted apps". This lesson deals with browser apps. Even if it is simply described as "app", please read it as if it refers to a browser app. A detailed description of the entire app can be found in [the App Documentation](https://obniz.com/ja/reference/cloud/app/).It may be a little difficult because the explanation is mainly HTML / JavaScript, but if you are worried about the difference between the browser application and the hosted application, please read it. ## Preparing for app development: account creation and device registration The next time you develop an app, you will need to create an account and register your device, so let's do it here. **1. Account creation** You can create an account from [Sign up](https://obniz.com/en/users/signup).Accounts can be created from email addresses and various SNS accounts. If you already have an account, please log in and proceed to the next device registration. **2. Device registration** If you have an account, you can register your device with that account.By registering the device, you will be able to manage the device and use the application functions. Refer to [the Device Registration page](https://obniz.com/en/reference/cloud/device-management/registration) and follow the steps to register your device. Since the Starter Kit contains the obniz Board, [Authenticate with the key shown on the display](https://obniz.com/reference/cloud/device-management/registration#%E3%83%87%E3%82%A3%E3%82%B9%E3%83%97%E3%83%AC%E3%82%A4%E3%81%AB%E8%A1%A8%E7%A4%BA%E3%81%95%E3%82%8C%E3%82%8B%E3%82%AD%E3%83%BC%E3%81%A7%E8%AA%8D%E8%A8%BC%E3%81%99%E3%82%8B). If it is displayed as a registered device in the [Device List](https://obniz.com/en/console/devices) of the developer console, registration is complete. ![iotblock_06_03](images/iotblock_app_03.png) This is the end of this lesson. We will continue to develop apps from now on! --- ## Make an hourly time signal URL: https://obniz.com/guides/obniz-starter-kit/iot-by-block-programing/app-time-signal # Make a time signal: Sound the buzzer every hour in the app In [Last lesson] (make-app-ja.md), we checked the app function of obniz and prepared to make an app.From here, we will continue to develop apps! In this lesson, we will use the buzzer parts to make a sound every hour and make a time signal. ## Buzzer A buzzer is a part that can make a sound. There are two types of buzzers, active buzzers and passive buzzers. The buzzer included in the Starter Kit is a passive buzzer. ![iotblock_07_01](images/iotblock_time_01.jpg) The active buzzer has a built-in vibration source, so you can make a sound just by connecting it to the power supply. On the other hand, the passive buzzer does not have such an oscillation circuit, and the sound is produced by an external audio signal. The passive buzzer can change the pitch of the sound by changing the frequency of the external signal. The buzzer of the Starter Kit can also specify the pitch, and in the block program, it can be specified by the scale of Doremi Fasolaside. ## Make an app Now that you understand the parts to use this time, let's start the work of creating an application. First, as usual, go to [Developer Console](https://obniz.com/en/console/). Then select "App Development" from the tab on the left and press the "New" button. ![iotblock_07_02](images/iotblock_time_02.png) Select "Browser app (block program)" as the app type, and select "Empty" in "Template using obniz Board / 1Y". A window for entering the app name will appear. Enter the app name you like and press "Create App". (Here, we named it "Time Signal" because it is a time signal application.) ![iotblock_07_03](images/iotblock_time_03.png) Then, the screen of the application settings will be displayed.This setting can be changed later, so let's leave it as it is for now and go to the screen to create the program first.Click the "Edit Program" button. ![iotblock_07_04](images/iotblock_time_04.png) The familiar program screen has appeared.On this screen, you will create a program by arranging blocks as before. ![iotblock_07_05](images/iotblock_time_05.png) The difference from the program screen of the normal block program is that the obnizID is specified as "OBNIZ_ID_HERE" and the obnizID of the registered device is entered in the upper right. The app is described in the form of "OBNIZ_ID_HERE" without specifying the obnizID so that it can be used on various devices. However, so that you can check the operation, you can immediately execute it on the browser by pressing the button on the upper right on the registered device without installing it. ## Sound the buzzer You can run it in your browser without installing the app, so let's use that function to sound the buzzer first. There is a buzzer block in the "Starter Kit" category. ![iotblock_07_06](images/iotblock_time_06.png) The "sound" block will continue to sound until the "stop" block is used. The "Beat the sound" block will play the sound for the specified number of beats. This time, I want you to stop naturally when it sounds a little, so I will use the "play tone" block. Create the following program and execute it with the execute button on the upper right. ![iotblock_07_07](images/iotblock_time_07.png) Does only middele C sound ? If it doesn't work, check that the pin with the buzzer corresponds to the number on the block. You can change the pitch by changing the "middle C" part to a different scale, and you can change the length of the sound by changing the "1" beat part. Now you can use the buzzer parts to make sounds! ## Run the program in time If you just press the run button and sound the buzzer, you can do the same with a normal block program. However, it is necessary to run the program regularly in time because it is not a time signal just to make a sound manually. Therefore, let's use the function called "cloud execution" of the application. Cloud execution is a mechanism to run a program on the cloud instead of launching a browser and executing it. You can set a trigger and run the program each time the trigger occurs. What can be set as a trigger - Webhook - Fixed time - Fixed time interval - When the device comes online - When the device switch is pressed There are avobe 5 types.。It is also possible to set multiple triggers. (Reference: [Browser app: Cloud execution](https://obniz.com/reference/cloud/app/browserapp-cloudexec)) This time, we want to make a time signal that sounds the buzzer every hour, so we set it to execute the program at the "fixed time interval" of "every hour". Now, let's set the cloud execution on the application setting screen that we skipped earlier. Save the program by selecting "File"-> "Save", and then return to the developer console by clicking " "New"-> "Browser App (Block Program)" and select "Empty" in "Template using obniz Board / 1Y". Enter your favorite app name (here, "Temperature Record") and press "Create App". ![iotblock_08_04](images/iotblock_temp_04.png) Last time, we skipped the application setting screen, but this time let's set the cloud execution first. We want to measure the temperature on a regular basis, so enter `every / 10 minutes` in Run in Time under Cloud Run. (It is recommended to check the operation in a short time of 10 minutes at first, but once you can check the operation, you can move it at your favorite time interval.) After setting the cloud execution, press "Edit Program" to move on to creating the program. ![iotblock_08_05](images/iotblock_temp_05.png) First, let's check the value of the temperature sensor by displaying it on the console. Connect the temperature sensor to the correct pin, make a program like the one below, and press the execute button on the upper right. You're getting used to the display on the console. Did you forget to loop it? ![iotblock_08_06](images/iotblock_temp_06.png) When runed, the values acquired by the temperature sensor will be displayed one after another on the console.There are some errors, but you can see the current temperature. Now let's remake this program into a program that displays the temperature in the app status. To display information in App Status, use the "Exit App. Status XX Text XX" block in the "Cloud" category. ![iotblock_08_07](images/iotblock_temp_07.png) Let's set the status to "success", put the measured temperature of the temperature sensor in the text part, and make a program like the following. ![iotblock_08_08](images/iotblock_temp_08.png) Now you can see the temperature in the app status every 10 minutes. Wasn't it easier than you expected? It's okay to complete it, but we'll improve the program a little more. If you run this program in your browser by pressing the run button in the upper right corner, you will see an error message similar to the following on the console: ![iotblock_08_09](images/iotblock_temp_09.png) It's not running in the cloud, so you can't quit the app or display anything in the app status. The "Exit app. Status 〇〇 Text XX" block is a block that can be used only when executing in the cloud, so when you execute it in the browser, such an error will occur. It works fine in cloud execution, so you can leave it as it is, but let's prevent this error message from appearing in browser execution. It's easy to do, put the condition block "Running in the cloud" in the "Cloud" category into the block and "Exit the app." Just insert the "Status XX Text XX" block. ![iotblock_08_10](images/iotblock_temp_10.png) ![iotblock_08_11](images/iotblock_temp_11.png) Now when you run the browser, the error message is no longer displayed. This is because the block made it a program that "if you're running in the cloud, quit the app and record the temperature in the app status". When running the browser, the condition "If you are running in the cloud" does not apply, so the "Exit app. Status XX Text XX" block will not be executed and no error will occur. Since there was no program to run in the browser this time, there was no problem with the first program, but if you want to use different programs for browser execution and cloud execution, you need to use the condition "if you are running in the cloud" Will come out. It's a good idea to keep in mind that the part you want to run in the cloud should be inside the block, and the part you want to run in the browser should be outside the block. ## Install the app and check the app status Now that the app is complete, let's install it on your device and run it in the cloud. Save the program and return to the developer console. Maybe your device has the time signal app you created in the last lesson installed. Only one app can be installed on one device, so you need to uninstall the time signal app to install this temperature recording app. Select "Device" from the tab on the left to go to the device list screen. If you press the lower triangle button next to "Open App", there is "Uninstall" at the bottom, so press it. ![iotblock_08_12](images/iotblock_temp_12.png) Now that the time signal app has been uninstalled, install the temperature recording app that we made this time. You can install it from the app settings or app list screen as in the previous lesson, or you can install it from the current device list screen with "Install my app". ![iotblock_08_13](images/iotblock_temp_13.png) After the app is installed, wait 10 minutes. If the app works well in the cloud, you should see the value obtained by the temperature sensor in the app status. ![iotblock_08_14](images/iotblock_temp_14.png) ## Development: Devise a character string to be displayed In the current program, the value acquired by the temperature sensor is displayed as a simple number in the app status. At first glance, it's hard to tell what this number represents, so let's devise a display to make it a little easier to understand. Now it is displayed as "12.7", but we would like to change it to "Temperature: 12.7 °". Please move to the program edit screen of the temperature recording application. To create your favorite string, use the blocks in the "String" category. ![iotblock_08_15](images/iotblock_temp_15.png) Prepare the character string blocks "Temperature:" and "°", combine them with the measured temperature block, and put them in the blanks of the "Create text" block in order. You can increase the number of blanks in the "Create Text" block by pressing the plus button on the far right. ![iotblock_08_16](images/iotblock_temp_16.png) Put this in the text part to be displayed in the app status and you're done. ![iotblock_08_17](images/iotblock_temp_17.png) Save the program and return to the device list screen. Wait 10 minutes for the string to appear in the app status. If the display is as you intended, it is a success! ![iotblock_08_18](images/iotblock_temp_18.png) By using the character string block in this way, you can freely create a character string. Let's make good use of the character string block so that the information displayed in the app status will be easy to understand in the future. --- ## Works with Google Home URL: https://obniz.com/guides/obniz-starter-kit/iot-by-block-programing/ifttt # IFTTTと連携:Webhookをきっかけに動くアプリを実装 前回までのレッスンでは、「決められた時間の間隔」で実行されるアプリを作ってきました。 今回は「Webhook」をきっかけとして、スマートフォンに話しかけることで動せるアプリを作ってみましょう。 ## 作りたいもの 今回のレッスンで目指すのは、スマートフォンに「電気をつけて」と言うと部屋の電気がつくという、IoTシステムを作ることです。 電気をつける部分は、サーボモーターを動かして、物理的にスイッチを押すことにします。 (そのため部屋の電気でなくても、炊飯器のスイッチを押すでも、扇風機のスイッチを押すでも、なんでも構いません) 皆さんはすでにスマートフォンからでも、ブラウザを介してobnizを操作することができるようになっていると思います。 なので今回新しく学ぶことは、「音声でアプリを実行させるにはどうすればよいか」ということになります。 ## 音声でアプリを実行する アプリのきっかけとして設定できるものを、改めて確認してみましょう。 - Webhook - 決められた時刻 - 決められた時間の間隔 - デバイスがオンラインになったら - デバイスのスイッチが押されたら (参考:[ブラウザアプリ:クラウド実行](https://obniz.com/ja/reference/cloud/app/browserapp-cloudexec)) 音声で実行させるために活用できるのは「Webhook」です。別のアプリケーションで「Webhookを叩く」ことができるので、それをきっかけにアプリを実行させることができます。 つまり、音声入力→Webhookを叩く→obnizでアプリ実行 というシステムが作れるということになります。 では、どうすれば「音声入力→Webhookを叩く」ということができるのでしょうか。そのためには、「IFTTT」というサービスを使います。 ![iotblock_10_01](images/iotblock_ifttt_01.png) https://ifttt.com/ IFTTは異なるソーシャルメディアやプラットフォームを連携させることのできるWebサービスです。 IFTTTという名称は「If This Then That」の頭文字で、「もしこれをしたら、あれをする」という仕組みを作ることができます。 そのため今回であれば、「もし話しかけたら、Webhookを叩く」という仕組みを作ればいいということになります。 音声を認識する部分にはGoogleアシスタントというアプリを使ってみましょう。 したがって、作るべき仕組みは Googleアシスタントに話しかける→IFTTTでWebhookを叩く→obnizでアプリ実行 ということになります。 ようやく全体像が掴めましたね。では実装に移っていきましょう! ## Googleアシスタントのインストール まずは自分のスマートフォンでGoogleアシスタントを用意しましょう。 iPhoneならApp Store、AndroidならPlay storeで「Google assistant」と検索して、インストールしてください。 ## アプリの作成 続いて、obnizで動かすアプリを作成します。 いつものように、開発者コンソールから「アプリ開発」へと進み、「obniz Board/1Yを使うテンプレート」の「Empty」を選択して、お好きなアプリ名でアプリを作成してください。 ![iotblock_10_02](images/iotblock_ifttt_02.png) 今回はWebhookで実行させたいので、アプリ設定で「Webhookで実行」にチェックを入れておきます。 ![iotblock_10_03](images/iotblock_ifttt_03.png) アプリ設定が終わったら「プログラムを編集」を押して、プログラムを作っていきましょう。 作成するプログラムは、スイッチを押せるようにサーボモーターを動かすプログラムです。 サーボモーターを接続するブロックの通りに、obniz Boardにもサーボモーターを接続しましょう。ケーブルの色とその意味は以下の表の通りです。 ![iotblock_10_04](images/iotblock_ifttt_04.png) | obnizのピン番号 | サーボモーターの線 | | :-------------: | :----------------: | | 0 | signal(黄) | | 1 | vcc(赤) | | 2 | gnd(茶) | サーボモーターを接続できたら、ブラウザ実行で一度角度を0度に回しておきましょう。そして、その角度が基準となるようにサーボホーンを取り付けます。 ![iotblock_10_05](images/iotblock_ifttt_05.png) あとは、サーボモーターがスイッチを押せるように、適度な角度で動くようなプログラムにすれば完成です。 このレッスンでは、40度の角度でスイッチを押し込むプログラムにしてみました。 ![iotblock_10_06](images/iotblock_ifttt_06.png) プログラムを保存したら開発者コンソールの画面に戻り、アプリをデバイスにインストールします。 アプリをインストールしたら、デバイス一覧の「アプリを開く」の横のボタンを押して、「Webhook URLの確認」に進んでください。 ![iotblock_10_07](images/iotblock_ifttt_07.png) ここで表示されているWebhook URLをIFTTTでの連携で使うので、控えておいてください。 ![iotblock_10_08](images/iotblock_ifttt_08.png) ## Googleアシスタントと連携 アプリが完成したので、今度はIFTTTを使ってGoogleアシスタントとアプリを連携させます。 [IFTTTのサイト](https://ifttt.com/)にいって、IFTTTのアカウントを作成してログインします。 右上の「Create」というボタンを押すと、新しい連携の仕組みを作ることができます。「If This」を押して、「Googleアシスタントに話しかけたら」の部分を作っていきましょう。 ![iotblock_10_09](images/iotblock_ifttt_09.png) 「Serch services」で「google assistant」と検索し、Googleアシスタントを選びます。 ![iotblock_10_10](images/iotblock_ifttt_10.png) 「Connect」から、スマートフォンにGoogleアシスタントを入れたときと同じアカウントを選びます。 その後、「Say a simple phrase」を選択して、Googleアシスタントとのやりとりを設定します。 ここでは何をきっかけの言葉とするか、Googleアシスタントの返事を何にするか、を決めることができます。 今回は「電気つけて」でスイッチを押してもらえるように、「電気つけて」をきっかけの言葉として設定しました。また、電気がついているときには「電気消して」でも反応するようにしました。 ![iotblock_10_11](images/iotblock_ifttt_11.png) 設定ができたら「Create trigger」を押します。これで「If This」の設定ができました。 今度は「Then That」で「obnizのアプリのWebhookを叩く」を設定します。 ![iotblock_10_12](images/iotblock_ifttt_12.png) 「Webhooks」を検索して選択し、「Make a web request」に進みます。 ![iotblock_10_13](images/iotblock_ifttt_13.png) URLのところに先ほど控えておいたWebhook URLを入力し、Content Typeは「application/json」を選びます。 ![iotblock_10_14](images/iotblock_ifttt_14.png) 設定できたら、「Create action」を押してください。これで「Then That」の設定も完了しました。 「Continue」を押し、好きなタイトルを設定したら、「Finish」を押して完了です。 ## 実行 スマートフォンでGoogleアシスタントを立ち上げて、「電気つけて」と話しかけてみましょう。アプリが起動してサーボモーターが動けば大成功です! もしGoogleアシスタントがうまく動作しないときは、きっかけとなる言葉を他の指示と混ざらないような言葉にしてみてください。 ## 最後に この回でStarter Kitのブロックプログラムのレッスンは終了です。 ここまで手を動かしてプログラムを作ってきた皆さんは、もう自分でさまざまなIoTを実現できるようになっていると思います。生活を便利にするようなIoTの仕組みを、obnizを使ってどんどん作っていってください。 また、もう少し発展的なプログラムが作りたくなった方は、ぜひJavascriptでのプログラミングにも挑戦してみてください。 obnizで皆さんの暮らしがより便利に、より楽しくなることを祈っています。 --- ## About attached parts URL: https://obniz.com/guides/obniz-starter-kit/use-parts Shines, moves, sounds LED matrix It is a part with LEDs arranged in 8 dots x 8 dots. You can use dots to display marks and characters. button You can get whether the button was pressed. buzzer Make a sound. If you set the frequency, you can express a scale like Doremifa. LED signal Parts with blue, yellow, and red LEDs. Each LED can be controlled individually. Servomotor Rotates to the specified angle. Sensor (detect) Temperature sensor You can get the temperature around the sensor. Human detect Sensor It reacts to changes when a person approaches or moves away. Distance sensor Measure the distance to things. You can detect that something has been placed or is approaching. --- ## LED signal URL: https://obniz.com/guides/obniz-starter-kit/use-parts/led-traffic-ligth Parts with blue, yellow, and red LEDs. Each LED can be handled individually and controlled like a signal. ![](images/ks_TrafficLightModule.jpg) ## Parts library [https://obniz.com/ja/sdk/parts/Keyestudio\_TrafficLight/README.md](/ja/sdk/parts/Keyestudio_TrafficLight/README.md) ## Example [Change the color of the LED signal depending on the weather](https://blog.obniz.com/make/led-integration-weather-api/) --- ## Button URL: https://obniz.com/guides/obniz-starter-kit/use-parts/button It can get whether the button was pressed. ![](images/ks_DigitalPush-Button.jpg) ## Parts library [https://obniz.com/ja/sdk/parts/Keyestudio\_Button/README.md](/ja/sdk/parts/Keyestudio_Button/README.md) ## Example --- ## Buzzer URL: https://obniz.com/guides/obniz-starter-kit/use-parts/buzzer Make a sound. It can also play Doremifa by setting the frequency. ![](images/ks_PassiveBuzzer-module.jpg) ## Parts library [https://obniz.com/ja/sdk/parts/Keyestudio\_Buzzer/README.md](/ja/sdk/parts/Keyestudio_Buzzer/README.md) ## Example --- ## servo URL: https://obniz.com/guides/obniz-starter-kit/use-parts/servo Rotates to the specified angle. It can wave flags and move things. ![](images/ks_MicroServo.jpg) ## Parts library [https://obniz.com/ja/sdk/parts/ServoMotor/README.md](/ja/sdk/parts/ServoMotor/README.md) ## Example [Use voice recognition to wave the flag when you hear "I'm home"](https://blog.obniz.com/make/move-servomoter-by-voice-recognition/) --- ## Temperature sensor URL: https://obniz.com/guides/obniz-starter-kit/use-parts/temp It can get the temperature. ![](images/ks_LM35LinearTemperatureSensor.jpg) ## Parts library [https://obniz.com/ja/sdk/parts/Keyestudio\_TemperatureSensor/README.md](/ja/sdk/parts/Keyestudio_TemperatureSensor/README.md) ## Example [Real-time temperature graph [WebApp]](https://blog.obniz.com/make/real-time-temperature-recording/) --- ## Human Sensor URL: https://obniz.com/guides/obniz-starter-kit/use-parts/pir It reacts when a person or something that emits infrared rays moves. ![](images/ks_PIRMotionSensor.jpg) ## Parts library [https://obniz.com/ja/sdk/parts/Keyestudio\_PIR/README.md](/ja/sdk/parts/Keyestudio_PIR/README.md) ## Example [Use StarterKit to send a message to SNS when people come!](https://blog.obniz.com/make/linking-motion-sensor-and-sns/) --- ## Distance sensor URL: https://obniz.com/guides/obniz-starter-kit/use-parts/distance It can measure the distance to an object. It can detect that something has been placed or that you are approaching. ![](images/image.jpg) OLYMPUS DIGITAL CAMERA ## Parts library [https://obniz.com/ja/sdk/parts/HC-SR04/README.md](/ja/sdk/parts/HC-SR04/README.md) ## Example --- ## Matrix LED URL: https://obniz.com/guides/obniz-starter-kit/use-parts/matrix-led It is a matrix LED. It can display marks and characters. ![](images/2d6f7842c67a7fdcac13fee8d8e29c23.jpg) ## Parts library [https://obniz.com/ja/sdk/parts/Keyestudio_HT16K33/README.md](/ja/sdk/parts/Keyestudio_HT16K33/README.md) ## Example --- ## Production example using the kit URL: https://obniz.com/guides/obniz-starter-kit/make [![](images/sk-sensor-sns.png)](https://blog.obniz.com/ja/make/linking-motion-sensor-and-sns/) #### Use StarterKit to send a message to SNS when people come! Create a program that sends a message to Twitter when a motion sensor detects a change. [See production examples](https://blog.obniz.com/ja/make/linking-motion-sensor-and-sns/) [![](images/sk-motor-voice.png)](https://blog.obniz.com/ja/make/move-servomoter-by-voice-recognition/) #### Use voice recognition to wave the flag when you hear "I'm home" Using the voice recognition of the browser, when you say "I'm home", wave the flag that says "Welcome back". [See production examples](https://blog.obniz.com/ja/make/move-servomoter-by-voice-recognition/) [![](images/sk-sensor-graph.png)](https://blog.obniz.com/ja/make/real-time-temperature-recording/) #### Real-time temperature graph \[WebApp\] Create a real-time temperature graph using WebApp. [See production examples](https://blog.obniz.com/ja/make/real-time-temperature-recording/) [![](images/sk-led-weather.png)](https://blog.obniz.com/ja/make/linking-led-and-weatherapi/) #### Change the color of the signal LED depending on the weather Use OpenWeatherMap's Weather API to change the color of the signal LED that lights up according to the weather. [See production examples](https://blog.obniz.com/ja/make/linking-led-and-weatherapi/) --- ## Advantages of using obniz for business URL: https://obniz.com/guides/obniz-for-full-scale-use/beginner-level/obniz-business ### What is obniz? obniz is the technology for building IoT services easily. obniz provides all the necessary functions for IoT: firmware on the device, communication and encryption with the cloud, and device authentication and management in the cloud. ![about-obniz.png](../images/about-obniz.png) ### Advantages of using obniz for business The advantages of using obniz over other IoT devices are as follows. - Can focus only on the necessary software development As mentioned above, obniz provides the management functions and security required for IoT. Therefore, the service provider can focus on the development of the software part. For example, in recent years, there are issues with the security of the IoT. If you use obniz devices, you can develop them without spending more man-hours on security than a typical conventional product. - Easy to expand and maintain You can link and control devices on the network with a single program in the cloud. There is no need to develop and manage firmware for each device, and only a program modification in the cloud can be applied to all devices immediately. - Can simplify distribution **Service delivery model that only obniz can provide** ![obniz-model.png](../images/obniz-model.png) If using obniz products (devices), service providers can use obniz devices already owned by users without the need to produce, manage, and stock them themselves. Even if the user does not own the device, obniz will ship it to the user. You can reduce reducing the burden on the service provider. --- ## Example of business use URL: https://obniz.com/guides/obniz-for-full-scale-use/beginner-level/business-example Here is an example of using obniz to build an IoT system (service system). ## Example of service building using obniz The following diagram shows an example of a CO2 concentration monitoring system using a BLE CO2 sensor. The system displays the CO2 concentration acquired by the sensor in real-time on the end-user's smartphone or tablet. ![system-configuration-simple.png](../images/system-configuration-simple.png) ### Actor - CO2 measurement service providers(referred to below as service provider) - obniz Inc.(referred to below as obniz) - End-users using the service(referred to below as end-users) ### Service requirements - End-users view the value of CO2 concentration detected by the sensor on the device. - End-users can view the changes and the histories of the values. - The system gives alerts when the value exceeds the threshold. - As long as end-users have a CO2 sensor, obniz device, and portable device, they can use the service. - The service will be widespread and the number of end-users will grow in the future. ### How end-users use the service 1. [service provider] Develop a CO2 measurement system (service system) 2. [service provider] Develop a system to get CO2 concentration data acquired by obniz devices from obniz Cloud (Hosted App) 3. [service provider] Procure CO2 concentration sensors and obniz devices 4. [end-users] Apply for the service 5. [end-users] Receive the sensor and obniz device, register an account in the app, and start using the service ### Finished system **System** ![system-configuration.png](../images/system-configuration.png) **① Linking the devices to an account** The service provider will create an account in obniz Cloud. All obniz devices used in the service will be tied to this account. ![system-connection.png](../images/system-connection.png) Register the devices to obniz Cloud through the service provider's system. By "register," we mean to link the devices to an account. **Registration flow through the system** 1. End-user scans the QR code of the obniz device with the system's app. 2. The system app sends the URL to the service system. 3. Service system sends a device registration request to obniz Cloud using Graphql API. 4. obniz device and obniz Cloud are connected, and the Hosted App (see below) is ready to acquire data. - obniz Cloud Connect the obniz devices to the service provider's account, and link it to the Hosted App (see below). - Graphql API By calling this API, you can make "requests for registering device" and "requests for linking devices to the Hosted App (see below)" to obniz Cloud. To use this service, please issue an API key on obniz Cloud and include it in your request in the specified format. The API published by obniz uses Graphql. For details, please refer to [obniz Cloud API](/reference/cloud/cloudapi). **②Data acquisition by Hosted App** 1. Send the CO2 concentration acquired by the sensor to the obniz Cloud through the network 2. POST data from obniz Cloud to the specified DB by Hosted App The service provider develop a system called "Hosted App (Node.js App)" to use the data sent to obniz Cloud. Hosted App is like a clay pipe into which pours the data you want to use in the service system from the obniz Cloud. For more details, please refer to [What is a Hosted App (Node.js App)](/guides/obniz-for-full-scale-use/beginner-level/business-example). **③ Processing using the acquired data** Process the CO2 concentration data acquired from obniz Cloud into a data format that can be used in portable devices, such as a graph display. **④⑤ End-user use** Receive the data from the server and draw it on the portable devices. --- ## What is a Hosted App (Node.js App) URL: https://obniz.com/guides/obniz-for-full-scale-use/intermediate-level/hosted-app The obniz device sends the data to obniz Cloud. The Node.js program that gets the data from obniz Cloud and passes it to the service system is the "Hosted App." The service provider needs to develop a system (Hosted App) to acquire the data from obniz and link it to the service. ### Overview of the process 1. Get device information from the API published by obniz Cloud 2. Format the acquired data 3. POST to the specified location Sample code: ```jsx const data = SomeSensorClass.getScanData(someSensorInstance); // a const formattedData = format(data); // b await sendToMyServiceSystem(formattedData); // c ``` ## Features of Auto-scale and redundancy are implemented as standard. It is theoretically possible to make a similar mechanism without Hosted App if you directly call the API published by obniz Cloud from the service system to get the data of obniz devices. For this reason, the Hosted App mechanism may seem redundant, but it is so helpful when scale or redundancy is required. For example, let's assume that a large number of restaurants will introduce the aforementioned CO2 concentration measurement system. Then, as the number of obniz devices increases, the amount of data handled by the server of the system increases, and program operation such as scaling and redundancy becomes a problem. With Hosted App, [obniz-app-sdk](https://github.com/obniz/obniz-app-sdk) (see below) includes the features of auto scale and various load balancing. That allows service providers to focus on developing business logic. --- ## Hosted App development using obniz-app-sdk URL: https://obniz.com/guides/obniz-for-full-scale-use/intermediate-level/app-sdk It is convenient to use obniz-app-sdk when creating a Hosted App for obniz. ### Features of Hosted App using obniz-app-sdk - Program operation in link with obniz Cloud - Load balancing/scaling support - Load balancing mode with multiple instances - Multi-core load balancing support by pm2 ![system-obniz-app-sdk.png](../images/system-obniz-app-sdk.png) By using obniz-app-sdk to create a Hosted App, you can easily specify the behavior of each obniz device according to its connection status and handle load balancing and scaling. For more information about obniz-app-sdk, please refer to [obniz-app-sdk documentation](https://github.com/obniz/obniz-app-sdk). Also, please see [Specific usage of obniz-app-sdk](/guides/obniz-for-full-scale-use/intermediate-level/app-implementation) for concrete implementation. --- ## Overall view of the system URL: https://obniz.com/guides/obniz-for-full-scale-use/intermediate-level/whole-system ## Overall diagram from the system to the end user When using the obniz-app-sdk, the configuration can be as shown in the figure. ![system-obniz-app-sdk%201.png](../images/system-obniz-app-sdk%201.png) ⚠If you use only obniz.js or WebSocket API directly, you need to implement your processing around scaling. "worker" is the program for one obniz device. The App instance works with obnizCloud, and when an app is installed/uninstalled on the device on obnizCloud, it creates/deletes the worker with it. Since information can be exchanged with the worker instance through the App instance, for example, it is possible to "check the latest device status through the App instance when the API is called and return that information. ## Connect to obniz ### Setting up obniz To operate an obniz device, it must be connected to obniz Cloud. ### Connection path from the app to the obniz Cloud ![system-outbound.png](../images/system-outbound.png) The connection from the app server (obniz-app-sdk slave) to the obniz Cloud, enclosed in the green line, is made outbound (from inside to outside). There is no direct connection from obniz to the app server and vice versa. obniz Cloud (*1) eliminates the need to go beyond NAT. Therefore, there is no need to open ports. *1 The obniz Cloud is running as a TURN server as well as an API server. ### To set up an outbound firewall Please allow access to [https://api.obniz.com:443](https://api.obniz.com:443) and [https://obniz.com:443](https://obniz.com:443). --- ## App implementation URL: https://obniz.com/guides/obniz-for-full-scale-use/intermediate-level/app-implementation ## Specific usage of obniz-app-sdk - Get the Hosted App token - Install the library - Write a program for a worker, which is a program for one obniz device - Create an App instance while specifying the worker ### Get the token Create a Hosted App in obnizCoud and acquire a token. For more details about token acquisition, please refer to [Creating a Hosted App](/guides/hosted-app/). ### Installing SDK Create a nodejs project and install the sdk. `$ npm i obniz-app-sdk`. ### The worker program A worker is an instance that is created for each obniz device. Write the program to operate the device in this worker. You inherit the worker to make your worker program. ```jsx class MyWorker extends Worker { } ``` That's it for the minimal worker. To use it in practice, override `onObnizConnect`, `onObnizLoop`, and so on. ```jsx class MyWorker extends Worker { // Called only once when a connection to an obniz is made. // The obniz argument is the same as each obniz instance in obniz.js. async onObnizConnect(obniz){ //BLE initialization and parts wired are done here await obniz.ble.initWait(); } // run repeatedly as long as it is connected to the device // pingWait() with the device all the time and loop as in obniz.onloop. // The argument obniz is the same as each obniz instance in obniz.js. async onObnizLoop(obniz){ //do the actual processing here that we want to repeat const peripherals = await obniz.ble.scan.startAllWait(null, { duration : 10 }); console.log(`founded beacons by obniz ${obniz.id} length=${peripherals.length}`) } } ``` ### Start app There are several parameters to create the app, but only four are required. ```jsx const app = new App({ appToken: ">>", workerClass: MyWorker, instanceType: AppInstanceType.Master, obnizClass: Obniz }) App.start(); ``` | Parameter | Description | | --- | --- | | appToken | Pass the Hosted App token. | | workerClass | Pass the worker class you created. | | instanceType | Specify Master/Slave to support scale. In this case, specify Master since there is only one instance. If you want to distribute the load across multiple servers, please refer to the load distribution section below. | | obnizClass | Pass the obniz instance of obniz.js you use. | Now let's run the program. It's up and running. In the log, we can see that the app-sdk has started. ```jsx [2021-11-14T16:13:36.942] [DEBUG] obniz-app-sdk - ready id:master ``` However, no workers exist because there is no device with the app installed in this state. You can add the device by installing the app from obniz Cloud. ```jsx [2021-11-14T16:13:37.535] [DEBUG] obniz-app-sdk - all | added | updated | deleted [2021-11-14T16:13:37.535] [DEBUG] obniz-app-sdk - 1 | 1 | 0 | 0 [2021-11-14T16:13:37.535] [DEBUG] obniz-app-sdk - synchronize sent to master idsCount=1 [2021-11-14T16:13:37.535] [INFO] obniz-app-sdk - New Worker Start id=8952-6555 ``` The `all:1 and add:1` part of this log shows that the app is newly installed on one device so that the total number of devices becomes one. The next `New Worker Start id=8952-6555` is the start log for the specific worker. Let's try uninstalling the app from the device. You will see that the number of workers has changed in the same way. As you can see, if you install the obniz Cloud app, it will automatically increase or decrease the number of workers and keep as many workers running as obniz devices with the app installed. For more information about obniz-app-sdk, please refer to [obniz-app-sdk documentation](https://github.com/obniz/obniz-app-sdk). ### Note: About "Install" In obniz, linking a Hosted App to a device is called "installing" the app on the device. By installing a Hosted App on a device, the logic defined in the Hosted App is applied to the data sent from the target device. Be careful with the word "install." iOS apps write data directly to the iPhone device, but app data is not written to the obniz device. It is just a mapping between the device and the Hosted App on the obniz Cloud. For more information about installation, please refer to [Hosted App: Installation](/reference/cloud/app/hosted-install). --- ## About scaling URL: https://obniz.com/guides/obniz-for-full-scale-use/advance-level/scaling This section will explain what kind of server configuration you should use, based on the actual operation image. ![system-overall-view.png](../images/system-overall-view.png) The Master/Slave feature of obniz-app-sdk makes it easy to scale the system. The Master allocates obniz to each Slave, and the Slaves make a connection with the allocated obniz device. ![system-scalling.png](../images/system-scalling.png) The Master and Slave communicate via Redis (PubSub), which allows for easy redundancy. ⚠Master does not support redundancy. Only Slave and Redis can be redundant. ### Example of scaling using obniz-app-sdk As mentioned above, Redis is required for scaling. Redis is generally used as an in-memory database, but obniz-app-sdk uses it as PubSub. On Ubuntu, you can install it with the following command. ```bash $ sudo apt install redis-server ```` Once the Redis setup is complete, add the obniz-app-sdk option to use Redis. If you installed it locally, write as follows. ```jsx const app = new App({ appToken: ">>", workerClass: MyWorker, instanceType: AppInstanceType.Master, // AppInstanceType.Slave for Slave ObnizClass: Obniz, Database: "redis", // added databaseConfig: "redis://address:6379", // added }) app.start(); ``` Now, load balancing is enabled. If you start one Master and multiple Slaves in this state and install applications on obniz, the load will be balanced automatically. Also, when you close a Slave, the portion allocated to that Slave will be taken over by the other Slaves. ⚠When you add more Slaves, the load will not be automatically taken over to the new Slaves. If you install the app to the new device, it will be allocated to the new Slaves. ### How to link with other services You can store data from Slave via database or Redis, and refer to it from other services. There are also other ways to send the data directly to other services or to integrate it directly into Master. ![system-linking-services.png](../images/system-linking-services.png) Since [obniz-app-sdk](https://github.com/obniz/obniz-app-sdk) is a library, you can directly integrate it into existing services. --- ## App server load URL: https://obniz.com/guides/obniz-for-full-scale-use/advance-level/server-load In the [Practicing with AWS](./aws-practice) section below, we will run the [Logtta CO2 demo](https://github.com/obniz/obniz-app-sdk_logtta-co2_demo). This app gets the advertisement that Logtta CO2 emits and logs the values of CO@ concentration. We measured the load when running on the AWS EC2 T4g.micro environment. The results are as follows. [comment]: <> (**Actual measurements**.) [comment]: <> (t4g.micro) [comment]: <> (CPU: Roughly 1.8) [comment]: <> (Mem: 210MB) [comment]: <> (In: 3MB/m) [comment]: <> (Out: 1.5MB/m) **CPU credit usage[%]** ![cpu-credit-usage](../images/cpu-credit-usage.png) **network usage[MB/m]** ![network-usage](../images/network-usage.png) (blue: IN, orange: OUT) ## Load/communication volume If obniz and the app server are connected and no processing is done, it will use **54 bytes** per minute. When the BLE scans specific advertisement packets, it will use about **300 bytes** per minute. ⚠When using a Cellular line, it will use **768 bytes** per minute even without any processing due to the limitation of the Cellular network. --- ## Practice with AWS URL: https://obniz.com/guides/obniz-for-full-scale-use/advance-level/aws-practice *Please install the app on at least two obniz and place [Logtta CO2](https://obniz.com/sdk/parts/LogttaCO2/README.md) near the obniz. Also, please make sure to create an instance on Amazon EC2. ### When using only master Connect to Amazon EC2 using SSH. ```bash $ ssh ec2-user@{EC2 address} -i ~/.ssh/{key} ``` Follow the instructions on the next page. [Tutorial: Setting Up Node.js on an Amazon EC2 Instance](https://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v2/developer-guide/setting-up-node-on-ec2-instance.html) ```bash $ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash $ . ~/.nvm/nvm.sh $ nvm install 16.13.0 $ node -e "console.log('Running Node.js ' + process.version)" ``` Clone [https://github.com/obniz/obniz-app-sdk_logtta-co2_demo](https://github.com/obniz/obniz-app-sdk_logtta-co2_demo) and run it while setting environment variables. The Typescript file is run directly as Node.js using ts-node. ```bash $ sudo yum install git $ git clone https://github.com/obniz/obniz-app-sdk_logtta-co2_demo.git $ cd obniz-app-sdk_logtta-co2_demo $ npm ci $ APP_TOKEN={app token} LOGTTA_CO2_ADDRESS={MAC address of Logtta CO2} npx ts-node src/index.ts ``` The "app token" is the token you get when you create a Hosted App in obniz Cloud in [App implementation](/guides/obniz-for-full-scale-use/intermediate-level/app-implementation). ### Load balancing using master/slave **IP address configuration (LAN)**. master: 172.31.40.186 slave: 172.31.35.144 Create another master-only configuration and install Redis on the master. You can also use Amazon ElastiCache, but we'll install it on the master to simplify the explanation. ```bash # master server $ sudo amazon-linux-extras install redis6 $ redis-server --protected-mode no # Start with a lower security level for simplicity (disconnecting ssh during startup will also terminate Redis). ```` Edit the master security group so that it is accessible from the slave. ![security-rule](../images/security-rule.png) **slave startup**. ```bash # slave server $ git checkout scaling $ INSTANCE_TYPE=slave REDIS_URL=redis://172.31.40.186:6379 APP_TOKEN={app token} LOGTTA_CO2_ADDRESS={MAC address of Logtta CO2} npx ts-node src/index.ts ``` **master startup**. ```bash # master server $ git checkout scaling $ INSTANCE_TYPE=master APP_TOKEN={app token} LOGTTA_CO2_ADDRESS={MAC address of Logtta CO2} npx ts-node src/index.ts # Now you can see that obniz is assigned to both slave and master and load balanced. ``` ⚠Note that start the slave first, or the master will be taken by the slave which the master contains. If a slave stops while a worker is running, it will be automatically allocated to another slave. In this example, the slave which the master contains will be allocated. --- ## Developer URL: https://obniz.com/developer ## Javascript x IoT with Open Source SDK Browser Begin BlockProgram Browser Browser Integration Browser Integration Develop Browser App obniz Board IoT Development IoT x DIY With obniz Board DIY Cases ## Service Development with Open Source Run on servers Node.js IoT Development obnizOS+Cloud Service Development Development on AWS --- ## obniz MCP Server URL: https://obniz.com/developer/mcp-server obniz MCP Server Control obniz devices from AI clients Use an obniz Cloud App Token to connect an MCP server and start operating devices from conversation. Show me the connected obniz devices. I will check the devices installed to your Hosted App. GET devices via MCP Available devices were found. Notice obniz MCP Server is currently in alpha. Specifications and behavior may change, and server availability or continued operation is not guaranteed. 01 Introduction See how the AI client, MCP server, and obniz devices fit together. 02 Quick Start Connect to the cloud MCP endpoint and verify device access. 03 Configuration Review authentication, endpoints, and self-host settings. --- ## Introduction URL: https://obniz.com/developer/mcp-server/introduction obniz MCP Server lets MCP-compatible AI clients operate obniz devices through obniz Cloud. MCP, or Model Context Protocol, is a standard way for an AI client to connect to external systems. With the obniz MCP Server, the AI client can request device operations without embedding obniz-specific code in the chat client itself. ## How it works 1 AI Client An MCP-compatible client such as Claude Desktop, Claude Code, or Codex. 2 MCP Server Receives requests and connects to the Hosted App tied to the App Token. 3 obniz Device Operates real hardware through obniz Cloud. 1. An AI client such as Claude Desktop or Claude Code connects to the obniz MCP Server. 2. The client sends an App Token in the `Authorization` header. 3. The MCP server uses the App Token to access the devices installed to the corresponding Hosted App in obniz Cloud. 4. The target obniz device is controlled through obniz Cloud. ## When to use it Use the MCP server when you want to: - operate an obniz device from an AI assistant - check device status from a chat-based workflow - try hardware behavior without writing a dedicated control program first - let an MCP-compatible client connect to an existing obniz Cloud setup ## Requirements - An [obniz Cloud](https://obniz.com/) account - A Hosted App on obniz Cloud - An App Token for that Hosted App - At least one obniz device installed to the Hosted App - An MCP-compatible AI client For the fastest setup, use the cloud MCP endpoint in [Quick Start](/developer/mcp-server/quick-start). --- ## Quick Start URL: https://obniz.com/developer/mcp-server/quick-start Notice obniz MCP Server is currently in alpha. Specifications and behavior may change, and server availability or continued operation is not guaranteed. The quickest way to start is to connect your MCP client to the cloud endpoint provided by obniz. Cloud endpoint Use https://mcp.obniz.com/mcp as the MCP client URL and Authorization: Bearer apptoken_xxx for authentication. ## 1. Prepare obniz Cloud Prepare the following in obniz Cloud: 1. Create or select a Hosted App. 2. Install the Hosted App to the obniz device you want to control. 3. Generate an App Token for the Hosted App. The App Token usually starts with `apptoken_`. Keep it private, because it grants access to the devices installed to that app. ## 2. Configure your MCP client Use `https://mcp.obniz.com/mcp` for the cloud server. Pass your App Token as `Authorization: Bearer apptoken_xxx`. ### Claude Desktop Add the server to `claude_desktop_config.json`: ```json { "mcpServers": { "obniz": { "url": "https://mcp.obniz.com/mcp", "headers": { "Authorization": "Bearer apptoken_xxx" } } } } ``` Common config file locations: | OS | Path | |---|---| | macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` | | Windows | `%APPDATA%\Claude\claude_desktop_config.json` | Restart Claude Desktop after editing the file. ### Claude Code Add the server to your project `.mcp.json` or another private MCP config: ```json { "mcpServers": { "obniz": { "type": "http", "url": "https://mcp.obniz.com/mcp", "headers": { "Authorization": "Bearer apptoken_xxx" } } } } ``` If you use a project file, do not commit a real App Token to Git. You can also add it from the CLI: ```bash claude mcp add obniz --transport http https://mcp.obniz.com/mcp \ -H "Authorization: Bearer apptoken_xxx" ``` ### Codex CLI With Codex CLI, store the App Token in an environment variable and register the HTTP MCP server: ```powershell setx OBNIZ_APP_TOKEN "apptoken_xxx" codex mcp add obniz --url https://mcp.obniz.com/mcp --bearer-token-env-var OBNIZ_APP_TOKEN ``` Environment variables set by `setx` are available to newly started Codex processes. Restart Codex after adding the token. Check the registered server with: ```powershell codex mcp list codex mcp get obniz ``` ### Other MCP clients Use these connection settings: | Item | Value | |---|---| | URL | `https://mcp.obniz.com/mcp` | | Transport | HTTP | | Authentication | `Authorization: Bearer ` | If your client supports only the legacy SSE transport, see [Configuration](/developer/mcp-server/configuration). ## 3. Verify the connection First, check whether the client can list devices. If the MCP connection and App Token are valid, the client should show the devices available to the Hosted App. I want to control an obniz device. Are any devices online? obniz-mcp - list_devices (MCP) └ [] There are no online devices. Check the device power, network connection, and Hosted App linked to your App Token. I turned it on. obniz-mcp - list_devices (MCP) └ [ { "obniz_id": "XXXX-XXXX", ... +6 lines } ] Show Hello World on the display. obniz-mcp - display_print (MCP) └ Displayed: "Hello World" ## Self-hosting You can run the MCP server in your own environment instead of using the cloud endpoint. For the latest self-hosting steps, Dockerfile, and source code, see [obniz/obniz-mcp](https://github.com/obniz/obniz-mcp). This page shows only the minimal setup. ```bash git clone https://github.com/obniz/obniz-mcp.git cd obniz-mcp docker build -t obniz-mcp:latest . docker run --rm -p 3000:3000 obniz-mcp:latest ``` After startup, use `http://localhost:3000/health` for a health check. When self-hosting, the App Token is still passed by the MCP client in the `Authorization` header, not as a server-side environment variable. Set your MCP client URL to `http://localhost:3000/mcp`. If you are developing the server itself, build and run it with Node.js 18 or later: ```bash npm install npm run build npm start ``` --- ## Configuration URL: https://obniz.com/developer/mcp-server/configuration This page summarizes the connection settings used by the obniz MCP Server. Token handling The App Token is passed by the MCP client. Self-hosted servers do not need a fixed server-side token. The cloud MCP server is in alpha, and behavior or availability is not guaranteed. ## Authentication The MCP server authenticates requests with an obniz Cloud App Token. Send the token in the HTTP `Authorization` header as `Bearer apptoken_xxx`. The App Token determines which Hosted App and installed devices the MCP client can access. ## Endpoints | Environment | MCP endpoint | Health check | |---|---|---| | Cloud | `https://mcp.obniz.com/mcp` | - | | Self-hosted | `http://localhost:3000/mcp` | `http://localhost:3000/health` | Connect new MCP clients to the MCP endpoint. For self-hosted startup steps and Docker settings, see [obniz/obniz-mcp](https://github.com/obniz/obniz-mcp). ## Self-hosted environment variables When you run the server yourself, these environment variables are available: | Variable | Required | Default | Description | |---|---|---|---| | `PORT` | No | `3000` | HTTP server port | When self-hosting, the App Token is still passed by the MCP client in the `Authorization` header, not as a server-side environment variable. Do not put real App Tokens in shared config files or Git. ## Multiple clients Multiple MCP clients can connect to the server. - Clients using the same App Token share the same device pool. - Clients using different App Tokens are isolated from each other. - When all clients disconnect, server-side session state is cleaned up automatically. ## Token handling Treat App Tokens like credentials. - Do not commit real tokens to Git. - Use local or user-specific MCP config files when possible. - Rotate the token in obniz Cloud if it may have been exposed. --- ## Reference URL: https://obniz.com/reference obniz MCP Server obniz.js, Remote Device Control obniz.js Class Reference Parts Library obniz Now obnizCloud obnizOS Official Devices Intelligent Edge Kilo Intelligent Edge Micro obniz Board / 1Y obniz BLE/Wi-Fi Gateway Gen2.0 obniz BLE/Wi-Fi Gateway obniz BLE/LTE(encored) AK-030 obniz PLC M5Stack Basic obniz.js To remotely control obnizOS-powered hardware from JavaScript SDK. How to connect to devices via the cloud to operate peripherals such as IO and SPI is listed.You can check out the included parts library here.Also, the obniz.js class reference is available on GitHub. obniz Cloud Device management, serverless events, editors and APIs provided in the cloud It is described about #### [obnizOS](/reference/obnizos-for-esp32/) The dedicated software running on the device, how to launch it, how to set up Wi-Fi, and It includes information on how to create the device. It also includes hardware information for each device and documentation for SDKs in other languages. #### Official Devices Pinouts and more for each piece of hardware that obnizOS runs on are listed. --- ## obniz Now URL: https://obniz.com/reference/obniz-now obniz Now is a platform that brings together everything you need to build IoT applications. A shared device and cloud infrastructure for use at any location creates a flexible environment. You can easily add more equipment to monitor or expand to more locations later on. By making your equipment smart, obniz Now optimizes operations and supports the sustainable growth of your business. ## Features - Connect to a wide range of sensors and equipment through obniz devices and APIs, and display the collected data on screen. - Notify the people in charge by email or phone, and record reports in any format you choose. - Beyond collecting data, you can also control equipment through obniz devices. - AI-powered data analysis enables advanced use of your data. --- ## Account URL: https://obniz.com/reference/obniz-now/account An account refers to the unit of an application that uses obniz Now. You need to create one account for each project. You register devices, terminals, and users to the account you have opened in obniz Now. :::info Depending on the plan, multiple people can access an account. > (Example) You prepare a single account for a smart security robot system, and while your employees manage it, you invite customers as guests. ::: --- ## Prepare an Account URL: https://obniz.com/reference/obniz-now/account/prepare-account ## How to Prepare an Account You cannot create an account on the web. :::info Please contact our sales representative through the inquiry form below. [https://iot.obniz.com/contact](https://iot.obniz.com/contact) ::: --- ## Switching Accounts URL: https://obniz.com/reference/obniz-now/account/switch-account All accounts are opened at now.obniz.com. If you are developing multiple projects or receiving multiple services, you switch between accounts. ## Switching Accounts You can switch accounts from the screen below while logged in. [https://now.obniz.com/account](https://now.obniz.com/account) A list of the accounts you belong to is displayed as shown below. ![](../images/49966452288409.png) :::info If you belong to only one account, the list above may not be displayed. ::: While you remain logged in, the account you switched to is retained. :::warning About URLs with Unique IDs, Such as Device Detail Screens If you have bookmarked a unique URL, such as a device detail screen, you will not be able to view the page after switching to a different account. The account does not switch automatically based on the URL, so switch to an account that can view the page, and then open it. ::: --- ## Audit Log URL: https://obniz.com/reference/obniz-now/account/audit-log Under `Admin` > `Audit Log` in the sidebar, you can view records of operations performed on obniz Now by people rather than by machines. :::info This feature is available when you have contracted a plan in which the audit log is enabled. Only the administrator (Owner) can view the audit log. ::: In the audit log, you can search records of all operations in chronological order. When an unexpected operation occurs, you can check who performed it and investigate the cause. ![](../images/50048132841625.png) --- ## Users & Permissions URL: https://obniz.com/reference/obniz-now/user-account An obniz Now account lets you register multiple users, grant them permissions, and invite them. --- ## Creating an User and Logging In URL: https://obniz.com/reference/obniz-now/user-account/create-account-login Users can register for free from the URL below, either with an external service account such as Google, or with an obniz Cloud account if they already have one. [https://now.obniz.com/login](https://now.obniz.com/login) :::info You must agree to the Terms of Use and Privacy Policy stated there. ::: ![](../images/49966621781657.png) ## About Email Addresses Email addresses may be duplicated. In other words, you can create multiple users with the same email address, or create a user with no email address at all. ## Changing Your Name You can change a user's name by opening the personal settings ( [https://now.obniz.com/mypage](https://now.obniz.com/mypage) ) from the menu at the top right of the screen. ![](../images/49966621782169.png) ## Changing Your Icon You can also change a user's icon by opening the personal settings ( [https://now.obniz.com/mypage](https://now.obniz.com/mypage) ) from the menu at the top right of the screen. ![](../images/change-user-icon.png) :::success Changing your name and icon makes it easier to find a user in the account list screen, and easier to recognize one another when exchanging messages with other users within the same account. ::: --- ## Switching Language URL: https://obniz.com/reference/obniz-now/user-account/language You can change the language used in the system from the personal settings ( [https://now.obniz.com/mypage](https://now.obniz.com/mypage) ). The currently supported languages are: - Japanese - English ![](../images/49966690352665.png) :::info Customized screens within the system, notification emails, and the like are not necessarily prepared for all languages, so they may be displayed in a language different from your setting. ::: --- ## User Permissions URL: https://obniz.com/reference/obniz-now/user-account/user-permissions You must always set permissions for a user you add to an account. :::success Imagining roles such as support staff or on-site users, you specify the range that a user added to the account can operate or view, for example "can view all data but cannot operate" or "can view only the devices the user themselves purchased." ::: ## Permissions Permissions can be determined when you invite a user. You can also change permissions later. Every user can belong to one group, and you can grant permissions according to that group. The following types of permissions are available. - **Owner** Can view and operate all information - **Member** Can view and operate the group they belong to - **Guest** Can only view the group they belong to, nothing else ![](../images/49987578331801.png) ## List of Permissions and What They Can Do |Permission|View own group|Operate own group|View and operate everything|Account settings and billing information| |:-|:-:|:-:|:-:|:-:| |Owner|◯|◯|◯|◯| |Member|◯|◯|✕|✕| |Guest|◯|✕|✕|✕| ## Navigation Structure Only Owners can use account-related settings and advanced settings. The navigation items displayed differ between Owners and non-Owner users. **For Owners** All items are displayed. ![](../images/50081331542425.png) **For Non-Owners** Features for account administration and settings are not displayed in the sidebar. ![](../images/50081331545753.png) --- ## Inviting and Approving Users URL: https://obniz.com/reference/obniz-now/user-account/invite-approve-users Once you have determined the permissions for the user you want to invite to the account, you send the invitation. :::info The number of users you can invite to an account and the permissions you can grant vary depending on the plan. ::: ## How to Invite You can invite a user in one of two ways. - Send an invitation URL and have the recipient log in - Have the recipient share their obniz Now user ID, then add them ### Inviting by Invitation URL From the sidebar, select `Admin` > [Team Members](https://now.obniz.com/admin/auth), then choose `Invite New User`. ![](../images/49987976502809.png) By entering an email address, you can also have obniz Now automatically send an invitation email. You can also set an expiration date for the invitation URL. :::success When inviting someone with Guest or Member permission, select: - **Group** A specific group - **Permission** Guest or Member ::: :::info About the Approval Process Normally, simply opening the URL and logging in does not grant access to the account. However, by enabling `Auto-approve`, the user can gain access just by opening the URL and logging in. If auto-approval is not enabled, the user who logs in is added to the waiting list. A user with Owner permission can formally register a new user by "approving" them from the waiting list. ::: :::info When You Receive an Invitation If you have received an invitation, you can register as a user by opening the invitation URL and logging in to obniz Now. If auto-approval is enabled, you can view the account immediately. If auto-approval is not enabled, you cannot view the account until the Owner who issued the invitation URL approves you. ::: :::info About Re-invitation If you want to send an invitation again, for example when the recipient did not receive the email, enter the same details. A URL different from the one issued the first time will be generated. ::: ### Inviting by Specifying a User ID If the recipient is already using obniz Now, you can add them directly by specifying their ID. From Invite New User for the same team members, select `Specify User ID`, then specify the recipient's user ID along with the group and permission. With this method, no notification is sent to the recipient even after the addition is complete. ![](../images/49987976504473.png) --- ## Devices URL: https://obniz.com/reference/obniz-now/devices In obniz Now, you register the equipment and facilities you manage in units called "devices", and manage data for each device. You can associate an obniz device with a device. Devices can be organized into groups; for example, you can create a group for each store or location. --- ## Registering an obniz Device URL: https://obniz.com/reference/obniz-now/devices/register-device The obniz device you purchased can be registered to your account using a QR code. :::info When we sell an obniz device to a corporate customer and have already completed its registration to obniz Now, no registration work is needed. ::: ## Registering with the Camera The product itself, or the QR code that comes with it, contains a single-use registration token. You can register the device to obniz Now by capturing this token with a camera. From `Devices` > [Register Device](https://now.obniz.com/machines/add) in the sidebar, start the camera, capture the QR code on the product or its accessory, and register the device. Pressing the `Scan QR` button makes the browser start the camera. Use the camera on your computer or smartphone. If you are asked to grant access, please allow it. If you cannot capture it properly, follow the on-screen help `If Scanning Fails`. Detected obniz devices are shown in the list. ![](../images/49967392442649.png) ## Registering with a Token To enter a token manually, specify `SerialCode` and `Token`, then `Add`. ![](../images/reg-token.png) ## Naming and Registering Detected obniz Devices Once your obniz device is detected, enter a name and press `Bulk Register Machines` to register it to your account. :::danger **A registered device cannot be removed from your account.** If you wish to remove one, please contact support. ::: :::info obniz Device Registration Limit Each account has a device registration limit determined by its plan, and an error occurs when the limit is reached. If you wish to change your plan, please contact your sales representative or support. ::: --- ## Device List URL: https://obniz.com/reference/obniz-now/devices/device-list From `Devices` > [List](https://now.obniz.com/machines) in the sidebar, you can view the devices registered to your account. :::warning This screen can be customized. If our company has performed setup work for you, or if a prepared template has been applied, the screen may differ from the one shown on this page. ::: The "machine name" is an arbitrary name that you can assign to a device. ![](../images/49988415734169.png) :::info A "machine" refers to a "device". ::: ## Searching for Devices From the search box in the upper right of the screen, you can search device names by partial match. For devices that belong to a group, you can search for them within the list. ## Adding Devices to a Group You add a device to a group from either the list or the individual device screen. A single device can belong to multiple groups. The number of groups you can create within an account depends on your plan. Because a device can belong to multiple groups, the following uses are possible: - Manage a device by placing it in both the "obniz Hospital" and "Kanto Area" groups - Manage a device's status by placing it in both the "obniz Hospital" and "Under Maintenance" groups - Place a device in the "Company A" group, and invite the customer as a guest to the "Company A" group ![](../images/49988436911769.png) --- ## Creating a Group URL: https://obniz.com/reference/obniz-now/devices/create-group You can use the group feature to organize devices by the site where they are installed, so that users at each site can view them. When you open `Devices` > [Groups](https://now.obniz.com/groups) in the sidebar, a list of registered groups is displayed. ![](../images/groups.png) :::info Group Usage The number of groups available depends on your plan. The number of groups in use is shown in the `Group Usage` field. ::: ## Creating a Group From the `Add Group` screen, you can create a group by specifying a name. :::warning You cannot create groups with the same name within an account. ::: ![](../images/49988542263961.png) :::success Adding Devices to a Group You can add devices to or remove them from a group from [the device list](device-list). ::: ## Editing a Group By clicking a group name, you can open the group editing screen. ![](../images/edit-group.png) On the editing screen, in addition to changing the group name, you can search for and register a group to belong to. In the image above, a parent group is being added to a child group. :::info Parent-Child Group Relationships Parent-child relationships between groups affect what users with guest or member permissions can view and operate. A user belonging to a parent group can view and operate not only the parent group and its devices, but also the information of child groups and their devices. ::: --- ## Investigation URL: https://obniz.com/reference/obniz-now/investigation The Investigation feature lets you view device operation history, manage issues, and register and browse site records. --- ## Operation History URL: https://obniz.com/reference/obniz-now/investigation/operation-history The Operation History screen records important events that occurred in the past, such as anomalies in monitored equipment or product usage, in chronological order so you can review them. :::info Which contents are recorded as events and at what level depends on the environment that has been built. ::: ![](../images/49998638143129.png) ## History information Each event that occurs holds the following information. | Item | Description | |:-|:-| | Time | The time at which the event occurred. This may be the sensor's time or a time determined on the cloud side.For example, in a case such as "low voltage continued for 10 minutes or more and the weather forecast was rain," it is the time at which that was determined. | | Device | When a related device exists, it is linked.When the viewer is a guest user, only events whose target is a device they are allowed to view are displayed. | | Target | The type of what the event occurred on. | | Level | Indicates the importance of the event that occurred. | | Event | The name of the event that occurred. | | Value | A value related to the event is recorded.For example, in the case of low voltage, you can record and view a value such as how far the voltage dropped. | | Related issue | When there is an "issue" related to the event, the issue is linked. | ## Search You can search the events that occurred by period or by condition. For guest users, search results are limited to the information within the range they are allowed to view. ![](../images/49998629055513.png) --- ## Issues URL: https://obniz.com/reference/obniz-now/investigation/issues The Issues feature manages problems that require human attention. :::success It keeps track of what problems are occurring, as well as what problems occurred in the past and when they were resolved. ::: ![](../images/49998769030425.png) ## Information an issue holds An issue holds whether it is resolved or unresolved, along with information about the device on which it occurred. For guest users, only issues for devices they are allowed to view are displayed. --- ## Site Records URL: https://obniz.com/reference/obniz-now/investigation/site-records Site Records is a feature that lets workers keep records, such as photos and text, when installing equipment or when a problem occurs. In a chat-like format, each member can post messages with photos such as "I installed it this way," or, when an offline status is reported the day after work and the site is revisited, leave a PDF or photo recording such as "the power was turned off along this route." In this way, you can investigate events that occurred on site. :::info The Site Records feature requires a usage contract. ::: ## Creating a site record (thread) From `Investigation` > [Site Records](https://now.obniz.com/investigations/threads) in the sidebar, you can create a new record with `New`. As if opening a chat channel, you create a topic, post text and files about it, and once finished, close the record (thread). ![](../images/50046922035225.png) A record can be started with a title and a first post. When creating one, you can specify an entity. An entity is something related to the record. You can choose from the following. - Device - Used for installing or repairing a specific obniz device or sensor - Issue - An issue that occurred. Used for recording discovered errors, water leak anomalies on site, and the like - Operation History - A history of operations that occurred. Like issues, used for recording tracking information ![](../images/50046903489305.png) Once a thread is started, you or other members can post to it until it is closed. In a thread, you can carry out problem solving related to the site or equipment, for example by: - Posting multiple photos taken during installation - Posting CSV data from when an error occurred ![](../images/50046903489817.png) --- ## Automation URL: https://obniz.com/reference/obniz-now/automation With Automation, you can define automatic behaviors that use device data. --- ## Notifications URL: https://obniz.com/reference/obniz-now/automation/notifications Based on device data, you can send notifications to the person in charge or to another system. :::success For example, you can notify a contact you have registered in advance by email or phone when a temperature reaches an abnormal level and automatic control is carried out, or when a human intrusion is detected. ::: :::info The types of notifications available and how many you can send vary by plan. For details, please refer to the pricing plan or contact sales. ::: When you open the screen from `Automation` > [Notifications](https://now.obniz.com/automations/notifications) in the sidebar, a list of configured notification destinations is displayed. On this screen, you can view the list of notification destinations, add and edit notifications, and check the notification history. ## Notification Types | Notification method | Configurable destinations | |:-|:-| | Email | You can set To, CC, and BCC.You can specify multiple addresses separated by a comma `,`. | | SMS | You can set SMS (short message). | | Phone | By specifying a phone number, you can receive notifications by phone through an automated voice. | | Webhook | You can configure calls via REST API from an external service. | | Slack | By adding a bot, you can receive notifications in a specific Slack channel. | ## Adding and Editing a Notification You can add a notification from `Add Notification Method`. For any notification method, you can specify a device group for each notification. ![](../images/50047562880665.png) :::warning Notification Content and Groups How the notification content and the configured groups are used is determined by the machine that triggers the notification and by customization work, so it is not finalized within this setting. ::: You can edit a notification you have added later. To change the destination, click the `Edit` button. To edit the notification content, click `Template`; to test the notification, click `Test`; and to delete it, click `Delete`. ## Checking the Notification History From each item under `Notification Setting Name`, you can view the notification history for each destination. ![](../images/notification-history.png) In addition to the destination, you can apply filters such as the date and time range of the notifications, the status (`Success`, `Failure`, and so on), the type (`Email`, `SMS`, and so on), and the sort order to check what notifications were sent in the past. --- ## Intelligence URL: https://obniz.com/reference/obniz-now/automation/intelligence By creating an Intelligence, you can define a script that automatically processes device data. You can add an Intelligence from `Automation` > [Intelligence](https://now.obniz.com/automations/intelligences) in the sidebar. ![](../images/intelligence-empty.png) --- ## Integration URL: https://obniz.com/reference/obniz-now/integration The Integration feature lets you connect obniz Now with external systems. --- ## Integration URL: https://obniz.com/reference/obniz-now/integration/integration An Integration is a service that connects the data of a specific device with an external service. You can easily retrieve device information from obniz Now's external services, HTML, and more. ## Overview of Integration You can set up one or more Integrations for a single device. After configuration, it is applied within one minute and becomes available for forwarding. In an Integration, you define the destination and the format conversion, and set the authentication key and so on. ## Creating an Integration You can add an Integration from `Add Integration` on the sidebar under `Integration` > [Integration](https://demo-now.obniz.com/integrations). ![](../images/50047173125145.png) In an Integration, you can specify the following when creating it: - Destination - You can select REST API, Google Pub/Sub, and others - Machine - The device whose state is to be linked. You can specify multiple devices - Schema - The conversion expression for the state. You can define the keys and value conversions used for JSON linking - Send interval - You can specify the timing when sending from obniz Now ## Destination The available destinations are as follows. | Destination | Overview | Required settings | |:-|:-|:-| | Google Pub/Sub | Publishes data to Google Pub/Sub | The destination topic and authentication information are required | | REST API Push (unreleased feature) | POSTs data via REST API (HTTPS request) | The destination URL setting is required.Headers can be customized. | | REST API Pull (unreleased feature) | Can generate a REST API endpoint.GET requests with an API Key become available. | Issuing an API Key is required. | ### Schema Settings You can configure, as a schema, how the values that each device holds and stores are output, including with what keys and values. You can set the output of each key one by one as a mapping table. The values that exist differ depending on the selected device and its settings. For example, an obniz device includes connection states such as `online`, and a temperature sensor includes a temperature such as `temperature` and the Bluetooth signal strength. You can build the schema by specifying the destination path and adding it. ![](../images/50703716285337.png) For example, for JSON that maps `temperature` to a key named `temp` and `rssi` to `rssi`, apply the following settings. ![](../images/50703716647833.png) With `Transform Data`, you can try out the value conversion on the current device. ![](../images/50703716291353.png) ### Time and Device Identification You can change the `timestamp` format and the `device_id` (the value used to identify the device) at the time of sending. Select the format from `Format`, and if a timezone setting is needed, select it from `Timezone`. ![](../images/50703716651161.png) ![](../images/50703716300953.png) Device identification works as follows: - Send either the machine name or the machine ID - The key used for sending can be set freely. The default is `device_id` By default, the `machine name` is sent as a string with the `device_id` key. --- ## Inbound Source URL: https://obniz.com/reference/obniz-now/integration/inbound-source An Inbound Source receives information such as sensor data from IoT terminals or systems other than obniz devices. In addition to receiving data from a single sensor, an Inbound Source can also receive "information from multiple LoRa sensors sent by a LoRa gateway." :::info A dedicated plan contract is required to use this feature. ::: ## Adding a Source Add a source from `Add Source` on the sidebar under `Integration` > [Inbound Source](https://demo-now.obniz.com/inbound). You can register a source by adding the type of the data source along with its format and authentication information. ![](../images/50047859512601.png) When you create an Inbound Source, an endpoint for sending data is issued. When data is actually received, the information of the receiving device is displayed. In the case of a gateway, the information of the multiple sensors that were sent is displayed. To actually register a device (machine) on obniz Now and save data or perform automation, register it from the screen. ![](../images/50047859513113.png) ## Settings on the IoT Sensor or Gateway Side Set the sending URL issued when the Inbound Source was created on the IoT device side. An API Key is required for sending. From API Key, issue a key that has write permission for the Inbound Source as shown below, and set it as the access token. ![](../images/50047859517337.png) How to set the token in an HTTP request (higher priority from the top) | Type | Key | Example | |:-|:-|:-| | Request header (recommended) | authorization or Authorization | `{"authorization": "Bearer xxxx"}` | | Request query | token | `https://now.obniz.com/xxxx?token=xxxx` | | Body | token | `{"token": "xxxxx"}` | Set it using the method that your IoT device supports. For other API Keys, refer to the API Key page. --- ## Settings URL: https://obniz.com/reference/obniz-now/settings This section explains settings that affect the entire account. --- ## Global IP Restriction URL: https://obniz.com/reference/obniz-now/settings/global-ip-restriction Except for the common login screen, you can restrict the global IP addresses that are allowed to log in to your account. :::info This feature requires a contract for a dedicated plan. ::: ## IP Restriction From `Admin` > [Account](https://now.obniz.com/admin/account) in the sidebar, enter one or more IPv4 addresses, one per line, into the `Allowed IP Address List`. :::danger If the address you specify in the list does not include your current address, you will be unable to change the setting afterward. ::: ![](../images/50047974678681.png) --- ## Navigation Configs URL: https://obniz.com/reference/obniz-now/settings/nav-conf From `Admin` > `Account` > `Navigation View Configuration` in the sidebar, you can toggle the visibility of items shown in the sidebar on a per-account basis. ![](../images/nav-conf.png) :::info Use this when you want to hide features that general users do not need. ::: --- ## API keys URL: https://obniz.com/reference/obniz-now/settings/apikeys You can use API integration to access the data of devices registered in obniz Now from external services. When you open `Admin` > [`API Keys`](https://now.obniz.com/admin/apikeys) in the sidebar, a list of issued API keys is displayed. ![](../images/apikeys.png) ## Creating an API Key By clicking `Add API Key`, you can issue a token for using the API. ![](../images/add-apikey.png) :::info - In `Key Name`, give the key a name to identify it. - In each item of `Authority`, set the permissions you need. - Press the `Create` button to issue it. ::: :::warning Setting Permissions Each item of `Authority` has three types of permissions: `Read`, `Write`, and `Delete` (some items have two or fewer). To prevent accidents caused by unintended operations, keep permissions limited to `Read` as much as possible, and grant `Write` or `Delete` permissions only when necessary. Even if you change a permission later, the token remains unchanged. ::: --- ## Glossaries URL: https://obniz.com/reference/obniz-now/glossary This is a collection of terms related to obniz Now. ### Account The unit of an application that uses obniz Now. There is one per project or solution. You register devices, terminals, and users to an Account opened in obniz Now. ### User You can register multiple users to an Account. Each user can handle data according to the permissions assigned to them. ### Member This can refer to a user, or to the permission—among those granted to a user—that allows viewing and operating the information of the group the user belongs to. ### Team member The same as a user. ### Owner The permission, among those granted to a user, that allows operating all information. ### Guest The permission, among those granted to a user, that allows only viewing the information of the group the user belongs to. ### User account The registration information of a user. This is different from an [Account](#account). ### Sidebar The panel displayed on the left side of the screen. ### Device A device, apparatus, or piece of equipment managed by obniz Now. For example, a refrigerator. ### Machine The same as a Device. ### obniz device A terminal or gateway running obniz OS. Examples include [Intelligent Edge Kilo](/reference/intelligent-edge-kilo), [Intelligent Edge Micro](/reference/intelligent-edge-micro), and [obniz BLE/Wi-Fi Gateway Gen2.0](/reference/obniz-ble-wi-fi-gateway-gen2). ### obniz OS The shared OS installed on obniz devices. ### Device The smallest unit of an apparatus or piece of equipment managed by obniz Now. For example, a single sensor or gateway, or an apparatus fitted with one. ### Automation A definition of automatic behavior based on device data. ### Intelligence A script that automatically processes device data, and the functionality it provides. ### Integration Using device data externally. ### Inbound Source Referencing data from external equipment. ### State Data representing the state of a device. --- ## Intelligent Edge Kilo URL: https://obniz.com/reference/intelligent-edge-kilo Reference documentation for Intelligent Edge Kilo. Covers Setup Guide, Power, Internet Connection, Device & Sensor Connection, Built-in Sensors & Components, Specifications. --- ## Setup Guide URL: https://obniz.com/reference/intelligent-edge-kilo/setup-guide Setup Guide documentation for Intelligent Edge Kilo. Covers Initial Setup, Settings, DIN Rail Mounting. --- ## Initial Setup URL: https://obniz.com/reference/intelligent-edge-kilo/setup-guide/initial-setup * * * > 🎯 > **Goal of this chapter** > Get the Intelligent Edge Kilo ready for use, going through unboxing, registration, making connections, securing the device, and connecting to the internet. > [Flow] Unbox > Register via QR > Connect the antenna (for LTE) > Power and internet connection > > (for wired connections) Connect to devices > Install and secure > Using and configuring Wi-Fi/Ethernet ## Unboxing Take the Intelligent Edge Kilo unit (hereafter abbreviated as Kilo) out of the box and place it on a stable surface, such as a desk. After this, connections are made in the following order. 1. Register via QR 2. (For LTE) Connect the antenna 3. Connect to power and confirm the internet connection 4. Connect to the target devices 5. Secure the Kilo If you want to secure the unit first at the installation site and then configure it, check the mounting instructions. ## Register via QR > ❗ > If you have a contract for obniz Now, registration has already been completed at the factory, so this step is not necessary. > Proceed to the next step, "■ (For LTE) Connect the antenna." The following items are included in the Kilo's outer box. ・obnizID: a unique identification number assigned to each unit XXXX-XXXX (X: single-byte number) ・QR code required for device registration: a QR code that differs for each unit Register the device by scanning the QR code from the device registration screen of obniz Now. > 🚨 > ・Do not share an unregistered QR code with others. > Once it has been registered, the same QR code can no longer be used for registration. > If you register a device by mistake, please contact obniz with the obnizID of the device in question. ## Connect the Antenna (for LTE) Fit the enclosed antenna onto the "LTE-M/NB-IoT" connector and secure it by turning. The antenna can be changed as an option at the time of delivery, but in the case of a rod antenna, it looks like the following. ![](../images/51076553314841.jpg) Once online, you can use various services over the internet. If you are connecting wirelessly to sensors and the like, you are done here. ## (For Wired Connections) Connecting to Devices To connect to devices via RS232, Ethernet, and so on, refer to the page for the connection method that corresponds to each standard. [List of connection methods](../device-connection) ## Install and Secure In addition to simply leaving the Kilo unit in place or fixing it with double-sided tape, the following installation methods are available. - [Mounting on a DIN rail](din-rail-mounting) ## Using and Configuring Wi-Fi/Ethernet By switching the settings, you can use Wi-Fi or Ethernet instead of LTE. For details, see the [settings page](settings). ■ Power and internet connection Power is connected via the connector on the bottom of the Kilo. Using a flathead screwdriver, crimp a DC power source from 5 to 32 V (such as an AC adapter or batteries), and fit the connector onto the Kilo. (For details on power, see the [power explanation page](../power/power).) As soon as power is applied, the white LED next to "ONLINE" begins to blink. This LED indicates the internet connection status, and a steady light means a successful connection to the internet and the obniz cloud. If the blinking state continues, the antenna may not be connected properly, or the unit may be out of service range. For details on the specific lighting states and what each one means, refer to the obnizOS reference below. This applies not only to LTE but is common to Wi-Fi/Ethernet as well. [obnizOS LED status and lighting patterns](../../obnizos-for-esp32/components/led#%E7%8A%B6%E6%85%8B%E3%81%A8%E7%82%B9%E7%81%AF%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3) ## Preparation Checklist Once you have confirmed the following items, the preparation in this chapter is complete. > ⚠️ > - **What if the login screen for the gateway's own Wi-Fi (Wi-Fi) does not appear automatically?** > Access http://192.168.254.1/. > → For details, see "How to display the login screen." > - **What if you configured the unit with a different Wi-Fi than the one for the location where you want to use it?** > It may not work correctly. After resetting, reconfigure it with the name and password of the Wi-Fi that can be used at the actual installation site. > → For details, see "How to reset." > - **What if you cannot register successfully with the QR code?** > You can register by photographing the QR code with your smartphone and displaying that image on a PC screen. > → For details, see "How to register the QR with a PC and smartphone." > - **What if the color of the lamp differs from the description?** > The display may differ depending on the situation. > → For details, see "List of LED statuses." --- ## Settings URL: https://obniz.com/reference/intelligent-edge-kilo/setup-guide/settings To switch the network that obnizOS connects to over to Wi-Fi or Ethernet, you need to put it into setting mode. In setting mode, you can also make detailed configuration changes from JSON, such as the behavior of the LEDs and buttons. ### Setting Mode In normal LTE connection mode, the unit does not transition to setting mode automatically; it is designed so that the settings are not normally changed. Use setting mode in cases such as when LTE is unavailable and you want to use Wi-Fi. To enter the settings, you need to press and hold the setting button for 3 seconds or more. With the power on, prepare a thin pin such as a SIM pin and press and hold the recessed button. The button is small and difficult to press. When the unit enters setting mode, the white LED on the unit begins to blink slowly. In addition, the unit broadcasts a Wi-Fi network for configuration with the SSID "obniz-xxxxxxxx" (x is the obnizID). ![](../images/51076294382233.jpg) ### Configuration Methods The configuration methods supported by the Intelligent Edge Kilo (Kilo) are as follows. For each configuration method, refer to the obnizOS reference. - [Via Wi-Fi](../../obnizos-for-esp32/settings/setting-via-browser) - [Via USB serial](../../obnizos-for-esp32/settings/setting-via-serial) - [Via the internet](../../obnizos-for-esp32/settings/setting-via-cloud) --- ## DIN Rail Mounting URL: https://obniz.com/reference/intelligent-edge-kilo/setup-guide/din-rail-mounting > 🎯 > **Goal** > Understand how to mount the Intelligent Edge Kilo safely and securely on a DIN rail. * * * ## DIN Rail Support The Kilo unit can be used as-is by placing it on a flat surface or by fixing it in place with double-sided tape or similar. In addition, the Intelligent Edge Kilo (Kilo) supports this DIN rail attachment. This means that **by mounting it on a DIN rail,** you can also install multiple units side by side, such as in a distribution board. Even when used in combination with a PLC, the DIN rail attachment lets you install the unit neatly. ![Appearance of DIN rail mounting](../images/51066801442457.jpg) ## How to Mount ### Mounting First hook the top of the attachment onto the DIN rail, then push the bottom into place to mount it. If it feels stiff, gently pull the **release tab** at the bottom while mounting. 👉 Pulling the tab too hard may cause damage. Moving it gently is enough. ![Steps for mounting on a DIN rail](../images/51066801442969.jpg) ### Removal To remove the unit, likewise pull the tab at the bottom while detaching it from the rail. Pulling the tab with one hand while supporting the unit with the other makes removal smooth. * * * --- ## Power URL: https://obniz.com/reference/intelligent-edge-kilo/power Power documentation for Intelligent Edge Kilo. Covers Power. --- ## Power URL: https://obniz.com/reference/intelligent-edge-kilo/power/power * * * ## How to Supply Power The Intelligent Edge Kilo (Kilo) has **no built-in battery**. Supply power from an external DC power source. - Power supply from the bottom connector (detachable terminal) - Power supply from USB ### How to Supply Power from the Connector **1\.** Attach the power cable to the detachable connector. 👉 **Check the polarity (+V / GND)** and tighten the screws **just enough, about as tight as a jam jar lid**. **2\.** Insert the connector **straight in, all the way** into the terminal on the bottom of the Kilo. **3\.** Connect the other end to a power source (an AC adapter, batteries, etc.) to supply power. ![Example of wiring the detachable terminal block and attaching it to the Kilo unit](../images/51077688893209.jpg) ### How to Supply Power from USB (for temporary use, such as during configuration only) **1\.** Connect the USB cable to the **USB Type‑C** connector on the side of the Kilo. **2\.** Connect the other end of the cable to an AC adapter or device to supply power. 👉 USB power depends on the **output capacity of the adapter**. ![Example of a USB Type‑C power connection](../images/51077688894873.jpg) > ❗ > **[Size of the USB Type‑C plug]** > The connector is on the smaller side. Cables with a large plug outer shape may not be able to be inserted, so please check in advance. ## Comparison of Power Supply Methods > ❗ > **[Internal power conversion efficiency]** > **Connector power > USB power**. 👉 For long-term operation or sleep-centric configurations, **connector power is recommended**. | Item | Using the connector | Using USB | | --- | --- | --- | | Voltage range | DC 5 to 32 V (strictly observe the upper limit) 👉 If the supply is unstable, select the **lower, safer voltage** | DC 5.0 to 5.5 V (USB standard range) | | Power consumption | Approximately 0.2 W on average 👉 May spike temporarily during communication, etc. | Same as left | | Protection circuit | Reverse-connection protection + polyfuse (1.5 A) | — | | Voltage measurement on the Kilo | Possible (used for detecting voltage stability or drops, and for estimating remaining charge) | Not possible | ## Behavior at Low Voltage ### Order of Operation Shutdown If the supply voltage drops, the unit shuts down in stages. ① **Below 5 V**: CANBus stops (terminals go to Hi‑Z) ② **Near 3.3 V**: If the 3.3 V bus is maintained, the network and other functions may continue ③ **Below 3.3 V**: Each component stops in turn ### Power Bus Configuration Internally, the unit operates with a **5 V** bus (CAN transceiver, 3.3 V step-down) and a **3.3 V** bus (other components). ### obnizOS Fault Detection and Restart obnizOS performs an automatic restart and reconnection when it detects a fault. 👉 Even when recovering from a partial voltage drop, it attempts to re-establish the network. ### Hardware States Retained When obnizOS Restarts > 🚨 > Even when obnizOS restarts, **the internal power management IC is not reset**. > Therefore, the following **retain their previous state** even after a restart. > ・The operating state of the RS232/422/485 transceivers > ・The operating state of CANBus > ・The open/closed state of the relays * * * --- ## Internet Connection URL: https://obniz.com/reference/intelligent-edge-kilo/internet-connection Internet Connection documentation for Intelligent Edge Kilo. Covers LTE-M / NB-IoT, Ethernet / Wired LAN. --- ## LTE-M / NB-IoT URL: https://obniz.com/reference/intelligent-edge-kilo/internet-connection/lte-m-nb-iot > 🎯 > **Goal** > Understand an overview of LTE-M / NB-IoT antennas and how to choose the optional antennas available for the Kilo. * * * ## LTE-M / NB-IoT The Intelligent Edge Kilo (Kilo) is equipped with cellular network connectivity that supports LTE-M and NB-IoT. This allows it to connect to the internet even in environments without Wi-Fi or Ethernet, or from moving objects. > 🚨 > The Kilo's cellular network feature is provided under a dedicated plan. The SIM / eSIM is configured at the factory, and **your own SIM cannot be used**. ## LTE-M LTE-M is an LPWA (Low Power Wide Area) method that makes use of the existing LTE network. For domestic use, LTE-M is often chosen, while the availability of NB-IoT differs depending on the carrier and region. ### Features - A type of cellular network with wide-area coverage (depending on the carrier and region). - Low power consumption. - Tends to connect relatively easily even inside buildings or in remote areas. - The communication speed is in the low range (rough guide: around several hundred kbps). ## Connecting the Antenna Connect a compatible antenna to the SMA connector printed with "LTE-M / NB-IoT" on the side of the Kilo. Align the antenna straight and tighten it **by hand until it stops** to secure it. 👉 No tools are needed. Tightening it just enough, about as tight as a jam jar lid, is sufficient (avoid over-tightening). ![Side of the Kilo: LTE-M / NB-IoT label and location of the SMA connector](../images/51066339371161.png) ![Example appearance of a rod antenna (SMA)](../images/55403570377113.png) ## Optional LTE-M / NB-IoT Antennas Usable with the Kilo The Kilo comes with an LTE-M / NB-IoT antenna, but you can also use optional antennas depending on your environment. The following are representative examples that can be attached in Japan. > ❗ > RP-SMA (reverse SMA) cannot be used. It looks similar, but the internal pin arrangement is different and it is not compatible. | Part number | Type | Features | Source | | --- | --- | --- | --- | | DELTA1A/X/SMAM/S/S/11![DELTA1A rod antenna](../images/51066339371929.png) | Rod antenna | Temperature range: -20 to +60 ℃ | [Product page (Mouser Japan)](https://www.mouser.jp/ProductDetail/Siretta/DELTA1A-X-SMAM-S-S-11?qs=QNEnbhJQKvZMZQTjGyjQyQ%3D%3D)/ [Sales page (MonotaRO)](https://www.monotaro.com/p/4715/2639/) | | TG.08.0113![TG.08.0113 rod antenna](../images/51066339372441.png) | Rod antenna | Temperature range: -40 to +85 ℃ | [Product page (Mouser Japan)](https://www.mouser.jp/ProductDetail/Taoglas/TG.08.0113?qs=JbASvl9PsS17ajPV2Gadew%3D%3D)/ [Product page (DigiKey Japan)](https://www.digikey.jp/ja/products/detail/taoglas-limited/TG-08-0113/5120279) | | GSA.8822.B.301111![GSA.8822.B.301111 antenna with cable](../images/51066339375641.png) | With cable | Temperature range: -40 to +85 ℃/Cable length: 3 m/Waterproof and dustproof: IP67/Double-sided tape included | [Product page (Mouser Japan)](https://www.mouser.jp/ProductDetail/Taoglas/GSA.8822.B.301111?qs=MLItCLRbWswm8XVZZ6MleQ%3D%3D)/ [Product page (DigiKey Japan)](https://www.digikey.jp/ja/products/detail/taoglas-limited/GSA-8822-B-301111/9972801) | | GA.111.101111![GA.111.101111 antenna with cable](../images/51066339377433.png) | With cable | Cable length: 1 m/Waterproof and dustproof: none/Magnetic mount (vertical 1.8 kgf, horizontal 0.8 kgf) | [Datasheet](https://www.taoglas.com/datasheets/GA.111.101111.pdf)/ [Product page](https://www.taoglas.com/product/ga-111-101111-3dbi-mini-magnetic-mount-698960mhz-17102700mhz/) | ## Checking the Communication Status After power-on, if the LED is blinking **twice per second**, an LTE connection is in progress. If it stays steadily on, communication has not been established. Check the antenna, the installation location, and any surrounding obstructions. --- ## Ethernet / Wired LAN URL: https://obniz.com/reference/intelligent-edge-kilo/internet-connection/ethernet > 🎯 > **Goal** > Connect to the internet via Ethernet. * * * ## How to Wire the Ethernet Cable Connect the Ethernet cable to the RJ45 port on the surface of the Kilo. ![Location of the Kilo's RJ45 port](../images/51066481573401.png) > ❗ > There is no automatic cable type detection (straight-through / crossover). Choose the appropriate cable according to what you are connecting to. > - Straight-through: switching hubs, routers, etc. > - Crossover: direct connection to devices such as PCs or PLCs > The LED on the connector (ONLINE) indicates the status of the internet connection and lights up independently of the software status. > The Kilo is not PoE. Since it cannot be powered or receive power from Ethernet, be sure to provide a separate power source. ## Attaching the Power Source We recommend using the connector on the bottom of the Kilo for power. Using a flathead screwdriver, wire and fix a **5 to 32 V** DC power source (such as an AC adapter or batteries), and attach the connector to the Kilo. 👉 A force **about as tight as a jam jar lid** is enough (avoid over-tightening). 👉 In addition to the connector, you can also supply power via USB. For details, see [here (TBD)](../power/power). ![Photo of the power connector section](../images/55404184819225.jpg) ## Configuring obnizOS To connect to the internet using Ethernet (wired LAN), you need to **enable Ethernet in the obnizOS network settings**. This setting can be made by switching the Kilo unit into **setting mode**. ### Entering Setting Mode With the power on, **press and hold the setting button for 3 seconds or more**. The button is in a hard-to-press location, so press the recessed button with a thin pin or similar. 👉 Tip: Since it is a small button, the trick is to press and hold it gently rather than pressing too hard. When the unit enters setting mode, the white LED on the unit **blinks slowly**. > ⚠️ > During normal operation (while communicating via LTE, etc.), the unit does not enter setting mode automatically. > Switch to setting mode manually only when you want to change the Wi-Fi or Ethernet settings. ### Automatic Broadcast of Its Own Wi-Fi When the unit enters setting mode, the Kilo automatically broadcasts its own Wi-Fi with the ID name "`obniz-xxxxxxxx`" (x is the obnizID). When you connect to this Wi-Fi, you can access the settings screen from a browser. You can connect to the Wi-Fi broadcast by the obniz device from a PC or smartphone and make settings from a browser. ### Enabling Ethernet Once the settings screen opens, select **"Network" → "Ethernet"** from the menu, enter the necessary settings, and click "Connect". ![](../images/viabrowser.png) ### Restart to Apply the Settings When you press the button, the settings are saved and the Kilo restarts. After the restart, it begins connecting to Ethernet. If the white LED begins to **blink quickly** after startup, communication via Ethernet has started, and a steady light indicates the connection status with the cloud. > ⚠️ > If you still cannot communicate after configuring, check the Ethernet cable connection, the LAN link LED, and the IP address settings. > In environments where DHCP is disabled, you need to enter the static IP correctly. Communication methodHTTPS (TLS 1.2) WebSocketStatic IPSupportedNumber of connections1Communication directionRequests from the device side only (the server does not connect to the device)ProxyConfigurable (HTTP or HTTPS)Connection destination domainsobniz.io, *.obniz.io, obniz.com, *.obniz.com (there may be multiple *)Ethernet settings that can be storedOnly 1 ## Checking the LED After Power-On After power-on, the white LED next to "ONLINE" indicates the connection status. | State | Meaning | | --- | --- | | Off | No power supply (check the power and wiring) | | Blinking | Connection in progress (check the network and settings) | | Steady on | Connection to the internet and the cloud service obniz Now complete | ## Troubleshooting Based on the LED State | Condition (LED) | Possible cause | How to respond | | --- | --- | --- | | **The white LED does not light up (off)** | ・No power supplied / insufficient voltage (outside 5 to 32 V) ・Power connector or USB not connected or loose ・Ethernet (internet) is not configured ・LINK not established (cable type / disconnection / port failure) ・DHCP not working / static IP mismatch | Check the power, wiring, and USB, and try a different power source or a different cable. Re-secure the connector with appropriate force (just enough, lightly tightened). Enable Ethernet in the network settings. Check the cable type and that it is plugged in, and retry with a different port / different cable. Confirm that DHCP is running. For static IP, review the IP / GW / DNS. | | **The white LED does not stay steadily on (keeps blinking)** | ・Outbound restriction / 443/TCP blocked by the firewall ・DNS resolution not possible (name resolution of the obniz domain fails) ・Incorrect proxy settings (method / host / authentication) | Allow communication to `obniz.io` / `obniz.com` (and `*.obniz.io`, `*.obniz.com`) over 443/TCP. Review the DNS server settings. Verify with the proxy disabled if it is not required; when using it, reconfigure the method, host, and authentication. | * * * --- ## Via Wi-Fi AP URL: https://obniz.com/reference/intelligent-edge-kilo/internet-connection/wi-fi-ap > 🎯 > **Goal** > Connect the Intelligent Edge Kilo to the internet through a Wi-Fi access point added to an existing Ethernet network when LTE-M / NB-IoT signal is weak. * * * ## Network Topology When LTE-M / NB-IoT signal is weak and an existing Ethernet network is available, add one Wi-Fi router, set it to AP mode (bridge mode), and connect the Intelligent Edge Kilo (Kilo) to that network over Wi-Fi. ```txt Existing Ethernet ↓ Wi-Fi router (AP mode / bridge mode) ↓ Wi-Fi Intelligent Edge Kilo ``` This page uses a Buffalo Wi-Fi router as an example. Screen names, switch names, and port names vary by model. Check the manual for the actual device as well. > ❗ > The Kilo connects to the WAN over Wi-Fi. This is not a procedure for connecting the Kilo Ethernet port to a Wi-Fi bridge or repeater. ## Before You Start | Item | Details | | --- | --- | | Upstream network | Existing Ethernet | | Added device | Wi-Fi router | | Wi-Fi router mode | AP mode (bridge mode) | | Kilo connection method | Wi-Fi | | Kilo Wi-Fi | IEEE 802.11b/g/n (2.4GHz) | | IP address | Configure DHCP or Static IP according to the network administrator's instructions | ## 1. Install the Wi-Fi Access Point Place the Wi-Fi router near the Kilo installation location. 1. Turn on the Wi-Fi router. 2. Place it where the existing Ethernet cable can reach. 3. Place it where the Kilo can connect with sufficient signal strength. > ⚠️ > If the Kilo or the Wi-Fi router is installed inside a metal panel or enclosure, Wi-Fi signal may become weak. Check the signal strength at the Kilo location after installation. The general setup flow is as follows. 1. Connect a PC or smartphone to the Wi-Fi router's factory default SSID. 2. Configure the SSID and Wi-Fi password for Kilo. 3. Connect the existing Ethernet cable to the Wi-Fi router. 4. Switch the Wi-Fi router to AP mode (bridge mode). 5. Confirm that a PC or smartphone can connect to the changed SSID. The procedure for switching to AP mode (bridge mode) varies by vendor and model. Check the setup instructions for the Wi-Fi router you are using. - [Buffalo: Use a Wi-Fi router in AP mode (bridge mode)](https://www.buffalo.jp/support/faq/detail/290.html) - [NEC Aterm: Switch to access point mode (bridge mode)](https://www.aterm.jp/support/qa/qa_external/00017/001.html) - [I-O DATA: Configure AP (access point) mode](https://www.iodata.jp/support/qanda/answer/s19871.htm) - [ELECOM: Use a Wi-Fi router in AP (access point) mode](https://qa.elecom.co.jp/faq_detail.html?category=152&id=4073) ### 1.1. Configure the Buffalo Wi-Fi Router (Example) #### 1.1.1. Connect to the Factory Default Wi-Fi From a PC or smartphone, connect to the Buffalo Wi-Fi router's factory default SSID. Check the router label or setup card for the factory default SSID, Wi-Fi password, and login information for the settings screen. Example: ```txt SSID: Buffalo-XXXX Wi-Fi Password: ************ Settings screen: http://192.168.11.1 ``` After connecting, open the Wi-Fi router settings screen in a browser. > 💡 > Some Buffalo models can be opened at `http://192.168.11.1` in the factory default state. If it does not open, use the AirStation app or check the device manual. #### 1.1.2. Set the SSID and Password for Kilo Set the SSID and password that the Kilo will use. Example: ```txt SSID: kilo-ap Password: any secure password ``` 1. Open the Wi-Fi router settings screen. 2. Open the Wi-Fi, wireless, or SSID settings screen. 3. Set the SSID for Kilo. 4. Set the Wi-Fi password. 5. Save the settings. 6. Reconnect the PC or smartphone to the changed SSID. > ⚠️ > When you change the SSID or Wi-Fi password, the current Wi-Fi connection from the PC or smartphone is disconnected once. Select the changed SSID and reconnect with the new password. #### 1.1.3. Connect Existing Ethernet to the INTERNET Port Connect the existing Ethernet cable to the port labeled `INTERNET` or `WAN` on the Wi-Fi router. ```txt Existing Ethernet ↓ Wi-Fi router INTERNET / WAN port ↓ Wi-Fi for Kilo ``` #### 1.1.4. Switch to AP Mode (Bridge Mode) After changing the SSID and password, switch the Wi-Fi router to AP mode (bridge mode). On some Buffalo models, use the switches on the back or bottom of the unit. Example: ```txt AUTO / MANUAL switch: MANUAL ROUTER / AP / WB switch: AP ``` 1. Turn off the Wi-Fi router. 2. If there is an `AUTO / MANUAL` switch, set it to `MANUAL`. 3. If there is a `ROUTER / AP / WB` switch, set it to `AP`. 4. Turn the Wi-Fi router back on. 5. Reconnect the PC or smartphone to the changed SSID. Some models use a `ROUTER` switch set to `OFF` or `AP` instead. If the switch names differ, check the manual for your router model. > ⚠️ > Set the SSID and password before switching to AP mode. After switching to AP mode, the IP address of the router settings screen may change. If you can no longer open the settings screen, check the IP address assigned by the upstream router or DHCP server. > ❗ > In AP mode, router functions such as the DHCP server, address translation, and packet filtering on the Wi-Fi router are not used. IP addresses are assigned by the upstream router or DHCP server. > 💡 > Buffalo documentation says that, after switching to AP mode, the LAN cable connected to the `INTERNET` port can remain connected. If communication fails, check the port requirements for your specific model. #### 1.1.5. Confirm the Connection from a PC or Smartphone Connect a PC or smartphone to the changed SSID and confirm that it can reach the internet or the upstream network. Example: ```txt 1. Connect a PC or smartphone to kilo-ap 2. Open any web page in a browser 3. Confirm that communication is available ``` Configure the Kilo network settings only after confirming that a PC or smartphone can communicate through the AP. ## 2. Configure the Intelligent Edge Kilo Network ### 2.1. Enter Setting Mode With the Kilo powered on, press and hold the setting button for **3 seconds or longer**. The button is in a recessed location, so use a thin pin to press it. When the Kilo enters setting mode, the white LED blinks slowly. ![Press the setting button](../images/51076294382233.jpg) ### 2.2. Connect to the Wi-Fi Broadcast by the Kilo In setting mode, the Kilo broadcasts a Wi-Fi network with an SSID like `obniz-xxxxxxxx` (where x is the obnizID). Connect a PC or smartphone to this Wi-Fi. When the login screen appears, enter `obniz` as the passkey. ![Login to the settings screen](../images/wi-fi-ap-kilo-login.png) > 💡 > If the login screen does not appear automatically, open `http://192.168.254.1/` in a browser. ### 2.3. Clear Existing Network Settings When the settings screen opens, clear the existing network settings. 1. Open the `Device` tab. 2. Select `Clear All Network Setting` under `Resets`. 3. Press `Execute`. ![Open the Device tab](../images/wi-fi-ap-device-tab.png) ![Execute Clear All Network Setting](../images/wi-fi-ap-clear-network-setting.png) This clears previously configured network settings such as LTE, Ethernet, and Wi-Fi. ### 2.4. Open the Wi-Fi Settings Screen From the `Network` tab, select `Wi-Fi`. ![Select Wi-Fi from the Network tab](../images/wi-fi-ap-network-wifi-tab.png) ### 2.5. Select the SSID Configured on the Buffalo Wi-Fi Router From the Wi-Fi list, select the SSID created on the Buffalo Wi-Fi router and enter the password. Example: ```txt SSID: kilo-ap Password: configured password ``` If the SSID is not shown in the list, select `Other Network` and enter the SSID manually. ### 2.6. Configure Static IP if Required If the network requires a fixed IP address, open `Option Setting` and enter the `Static IP` values. Use the values provided by the network administrator. Example: ```jsx static ip: 192.168.0.101 Netmask: 255.255.255.0 gateway: 192.168.0.1 DNS Server: 192.168.0.1 ``` When using DHCP, Static IP values are not required. ![Static IP input fields](../images/wi-fi-ap-static-ip.png) ### 2.7. Connect Press `Connect` at the bottom of the screen. If `online` is displayed at the end, the connection is successful. The Kilo restarts after saving the settings. ![Online status](../images/wi-fi-ap-online.png) ## 3. Operation Check After configuration, confirm that the Kilo can connect to the network. | Check item | Expected result | | --- | --- | | A PC or smartphone can connect to the AP | It can connect to the changed SSID | | Communication through the AP works | A web page opens, or the upstream network is reachable | | The Kilo settings screen shows the connection result | `online` is displayed | | Restart the Kilo | It reconnects to the same SSID and the LED becomes solid | After power-on, the white LED next to `ONLINE` indicates the connection status. | State | Meaning | | --- | --- | | Off | No power supply (check power and wiring) | | Blinking | Connection in progress (check network and settings) | | Solid | Connected to the internet and the cloud service obniz Now | ## Troubleshooting | State | What to check | | --- | --- | | Cannot open the AP settings screen | Check whether the settings screen IP address changed after switching to AP mode. Check the IP address assigned by the upstream router or DHCP server. | | The changed SSID is not shown | Restart the Wi-Fi router and check SSID settings and whether wireless is enabled. Use a 2.4GHz SSID that the Kilo can connect to. | | PC or smartphone can connect, but Kilo cannot | Check SSID, password, Static IP, gateway, and DNS Server values. | | The Kilo does not become `online` | Check upstream DHCP, duplicate fixed IP addresses, DNS settings, and whether 443/TCP communication is allowed. | | Communication fails after switching to AP mode | Check that AP mode is enabled, existing Ethernet is connected to the INTERNET / WAN port, and there are no model-specific port requirements. | ## References - [Buffalo: How to use a Wi-Fi router in AP mode (bridge mode) without using router functions](https://www.buffalo.jp/support/faq/detail/290.html) - [Buffalo: How to open the Wi-Fi router settings screen](https://www.buffalo.jp/support/faq/detail/124160320.html) - [Buffalo: Wi-Fi router manual list](https://www.buffalo.jp/support/product/search/?bstatus=true&category_id=10&keywords=&small_category_id=101&type=manual) * * * --- ## Device & Sensor Connection URL: https://obniz.com/reference/intelligent-edge-kilo/device-connection Device & Sensor Connection documentation for Intelligent Edge Kilo. Covers RS232, RS485 / RS422, CANBus, Ethernet, Relay, Qwiic, USB (CDC Client). --- ## RS232 URL: https://obniz.com/reference/intelligent-edge-kilo/device-connection/rs232 Intelligent Edge Kilo (Kilo) has a built-in RS232 transceiver, enabling 12V communication rather than TTL. By wiring a DSUB9-pin connector, you can communicate directly. ## Wiring Method Connect TX and RX to the "RS232/422/485" terminal on the side of Kilo. The side labeled OUT is Kilo's TX (Kilo's output side), and the side labeled IN is Kilo's RX (the side Kilo takes input on). **About GND** There is no GND terminal for RS232 on the side panel. If the GND level of Kilo's power supply differs from that of the connected device, connect either the "-" side of Kilo's power section or the GND of the Qwiic terminal to the other device's GND. **Termination Resistor** On Kilo, the RS232/422/485 terminals are shared. If a pin for enabling the RS485 termination resistor is attached, TX and RX will be connected through 120 ohms, so please remove it. ### DSUB9-Pin Connection Example As a wiring example, suppose you connect the following product: [https://www.amazon.co.jp/dp/B0D9NVQKGB](https://www.amazon.co.jp/dp/B0D9NVQKGB) The pin layout is as follows. ![](../images/51065084352537.png) In this case, for a female head: - OUT: brown - IN: red The photo below is an example of wiring that also includes GND (yellow). ![](../images/51065055890969.jpg) Conversely, for a male head, it is reversed: - OUT: red - IN: brown ## About Startup The RS232/422/485 terminal is not enabled during the startup phase and is in a Hi-Z state. No voltage is output from the TX side at the moment of power-on. Only when RS232 is enabled by software does the terminal become ready for input and output, and High is output from TX. It is also equipped with an automatic power-saving feature. When enabled, output may not be applied unless voltage from the other device is detected. This kind of control depends on the software. ![](../images/51065055891481.png) --- ## RS485 / RS422 URL: https://obniz.com/reference/intelligent-edge-kilo/device-connection/rs485-rs422 > 🎯 > **Goal** > Understand the overview of RS-485 and RS-422 on Intelligent Edge Kilo and how to connect to them. * * * ## Overview Intelligent Edge Kilo (Kilo) has a built-in RS-485 (RS-422 compatible) transceiver. Communication method: **differential signaling** (a method that reads the potential difference between two lines; it is noise-resistant and suitable for long-distance communication). ### ⚫︎ What Is RS-485 A half-duplex differential communication method that connects multiple devices using two signal lines (A/B). It is widely used for communication between industrial devices, such as Modbus RTU (the protocol is the application layer; RS-485 is the physical layer). ### ⚫︎ What Is RS-422 A full-duplex differential communication method that handles transmission (TX±) and reception (RX±) on separate lines. On Kilo, only either transmission or reception can be used. It is widely used for communication between industrial devices, such as Modbus RTU (the protocol is the application layer; RS-422 is the physical layer). ### ⚫︎ Shared RS-232/422/485 Terminal Kilo uses a shared RS-232/422/485 terminal. By wiring a D-sub 9-pin (DB9/DSUB9) connector, you can connect directly to external devices. There are 4 terminals: OUT A, IN B, H, and L. ![Shared RS-232/422/485 terminal and 120Ω termination](../images/51065185741721.png) ## Wiring and Connection > ❗ > You can connect sensors and communication cables even while Kilo is powered on. > However, **contact with metal parts or incorrect connection of the power lines may damage the equipment**. > Always check the voltage specifications of the device you are connecting, and work in a safe environment. ### ⚫︎ RS-485 (2-wire: A/B) - **A (485 A)** - **B (485 B)** As printed on the top panel, **A and B are fixed**. It is widely used with industrial protocols such as Modbus RTU (protocol = application layer, RS-485 = physical layer). ### ⚫︎ RS-422 (4-wire: TX±/RX±) This uses the 4 terminals OUT A (485A), IN B (485B), H, and L. For RS-422 communication, Kilo can use either transmission or reception, one side only. **Wiring Assignment** - TX pair: OUT A (TX−)/IN B (TX+) - RX pair: H (RX+)/L (RX−) It is widely used with industrial protocols such as Modbus RTU (protocol = application layer, RS-422 = physical layer). > ❗ > There is no dedicated GND terminal for RS-485/RS-422. > If you need to match GND levels, connect one of the following to the GND of the other device. > - The "−" terminal of Kilo's power section > - The GND of the Qwiic terminal ## Termination Resistor ### ⚫︎ RS-485 Termination Resistor - Kilo has a built-in **120Ω** termination resistor. - It is **enabled** by shorting **RS485** with the "120Ω" pin header on the front. - In a bus configuration, terminate **both ends** with 120Ω (enable it if Kilo is at an end). ### ⚫︎ RS-422 Termination Resistor - A termination of **100–120Ω** on the receiving side is common. - Kilo's built-in terminator is for RS-485/RS422. > ⚠️ > - For **RS-232, disable (remove) the termination resistor** (because RS-232 communicates over a single signal line, it differs from differential communication (RS-485/RS-422)). ## Operation and Control ### ⚫︎ State at Startup | Timing | State | | --- | --- | | Immediately after power-on | **Hi-Z (high impedance)**. No output immediately after startup. However, after a restart, the previous state is retained | | RS-485/RS-422 enabled by software | Communication becomes possible, and input and output are enabled. | ![Waveform image at startup](../images/51065140454297.png) * * * --- ## CANBus URL: https://obniz.com/reference/intelligent-edge-kilo/device-connection/canbus > 🎯 > **Goal** > Understand the overview of the CANBus feature on Intelligent Edge Kilo and how to connect to it. * * * ## Overview Intelligent Edge Kilo (Kilo) has a built-in **CANBus transceiver**. CANBus is a differential signaling communication method that enables stable communication even in noisy mobility environments. It is widely used in fields such as automotive, industrial equipment, and robotics. ## Wiring and Connection > ❗ > You can connect sensors and communication cables even while Kilo is powered on. > However, **contact with metal parts or incorrect connection of the power lines may damage the equipment**. > Always check the voltage specifications of the device you are connecting, and work in a safe environment. ### ⚫︎ CAN Terminals Connect H (high-potential side) and L (low-potential side) to the **CAN terminals** on the side of Kilo. The side panel is labeled "H" and "L". ![Kilo CAN terminals](../images/51065298316185.png) > ❗ > There is no dedicated GND terminal for CAN communication. > If you need to match GND levels, connect one of the following to the GND of the other device. > - The "−" terminal of Kilo's power section > - The GND of the Qwiic terminal ## Can Be Used Together with RS-232/422/485 On Kilo, the CANBus and RS-232/422/485 terminals are physically located side by side, but **CANBus operates independently**. As a result, simultaneous use such as "RS-232 + CANBus" is also possible. ## Termination Resistor - Kilo has a built-in **120Ω** termination resistor. - It is enabled by shorting **CAN** with the "120Ω" pin header on the front. - If Kilo is located at either end of the CAN bus, enable the termination resistor. ## Operation and Control ### ⚫︎ State at Startup | Timing | State | | --- | --- | | Immediately after power-on | **Hi-Z (high impedance)**. No signal is output immediately after startup. However, after a restart, the previous state is retained. | | CANBus enabled by software | Communication starts and the device becomes ready to send and receive. | ## Communication Modes The CANBus communication speed conforms to the product specifications. You can select the following modes via software settings. | Mode | Description | | --- | --- | | normal | Normal operation. Requires an ACK after transmission. | | noack | No error occurs even if there is no ACK after transmission. | | listen | A mode that does not transmit and only receives (suitable for bus monitoring). | ### ⚫︎ ID and Filter Settings - You can choose the ID bit length from two types: "standard" and "extended". - Packet filtering using IDs and masks is possible (without a filter, all packets are received). - By extending the device-side filter through software, you can also reduce traffic. * * * --- ## Ethernet URL: https://obniz.com/reference/intelligent-edge-kilo/device-connection/ethernet > 🎯 > **Goal** > Understand how to safely connect to devices such as PCs, PLCs, and sensors using the Ethernet terminal of Intelligent Edge Kilo. * * * ## Overview Intelligent Edge Kilo (Kilo) is equipped with an **Ethernet (RJ45)** terminal. This page focuses specifically on **local connections to devices (PCs, PLCs, sensors, etc.)**. ## Wiring and Connection > ❗ > You can connect sensors and communication cables even while Kilo is powered on. > However, **contact with metal parts or incorrect connection of the power lines may damage the equipment**. > Always check the voltage specifications of the device you are connecting, and work in a safe environment. Connect an Ethernet cable to the **RJ45 terminal** on the surface of Kilo, and connect the other end to the target device (PC, PLC, sensor, etc.). ![Location of Kilo's RJ45](../images/51065938201625.png) > ❗ > There is no automatic cable-type detection function (straight/crossover). Choose the appropriate cable according to the target device. > - Straight: switching hubs, routers, etc. > - Crossover: direct connection to devices such as PCs and PLCs > The LEDs near the connector (ONLINE, etc.) light up **independently of the software state**. > Kilo **does not support PoE**. It cannot supply or receive power through the Ethernet cable. ## Connecting to Local Devices (PC/PLC/Sensor, etc.) - For the purpose of communicating with local devices, **no special configuration on the obnizOS side is required**. > ⚠️ > ・In this mode, Ethernet is not used for WAN. > If you need an internet connection, use it together with LTE-M/NB-IoT. > ・For **internet connection (using it as a WAN)**, **configuration (enabling) on the obnizOS side** is required. > For the configuration steps, see [“Connecting to the Internet via Ethernet (WAN configuration)”](../internet-connection/ethernet). ## Operation and Control | Timing | Behavior | | --- | --- | | Immediately after startup | The physical link is not yet established. The link is established according to the cable connection and the state of the other device (the LEDs light up independently of the software). | | Local device mode | No additional configuration on the OS side is required. Communication is controlled from the application (cloud, plugin, etc.). | * * * --- ## Relay URL: https://obniz.com/reference/intelligent-edge-kilo/device-connection/relay ## Overview Intelligent Edge Kilo (Kilo) has a built-in **solid state relay (SSR)**. It can perform contact control of external devices and is used as a Form A (normally open) contact. ## Wiring and Connection > ❗ > You can connect sensors and communication cables even while Kilo is powered on. > However, **contact with metal parts or incorrect connection of the power lines may damage the equipment**. > Always check the voltage specifications of the device you are connecting, and work in a safe environment. Connect the device whose contact you want to control to the **"RELAY" terminal**, located in the same block as the power connector on the side of Kilo. ![Kilo RELAY terminal](../images/51065455637273.png) The relay terminal is an **independent, isolated terminal** that is not connected to other terminals or the power lines. It can be used to switch a current path. > ⚠️ > - The **rated voltage is 60V or less**. It supports low-voltage contact control such as 24V PLCs. > - Be sure to check [“Relay Specifications”](../specifications/product-spec) on the specifications page, and pay attention to the allowable current and resistance values. ## Operation and Control ### ⚫︎ State at Startup | Timing | Contact State | | --- | --- | | Immediately after power-on | **OFF (open)**. No current flows and the contact remains open. However, after a restart, the previous state is carried over. | | Relay control enabled by software | If the setting is **ON**, the contact closes and current flows. | ### ⚫︎ Retention of ON/OFF State Once set, the relay state is retained **until it is changed by software or the power is completely cut off**. As a result, the relay remains ON even in situations such as the following. - The internet connection is disconnected - The software or obnizOS restarts - The device enters sleep mode If you want the relay to turn OFF automatically under these conditions, you can handle this with **device-side control via a plugin**. * * * --- ## Qwiic URL: https://obniz.com/reference/intelligent-edge-kilo/device-connection/qwiic > 🎯 > **Goal** > Understand the role of the Qwiic terminal on Intelligent Edge Kilo and how to connect to it. * * * ## Overview Intelligent Edge Kilo (Kilo) is equipped with a **Qwiic terminal for expansion**. In addition to connecting Qwiic and compatible devices, it can also be used as **digital IO** or **analog IN**. ## Wiring and Connection > ❗ > You can connect sensors and communication cables even while Kilo is powered on. > However, **contact with metal parts or incorrect connection of the power lines may damage the equipment**. > Always check the voltage specifications of the device you are connecting, and work in a safe environment. Connect a compatible Qwiic or Qwiic-compatible cable to the **"Qwiic" terminal** on the side of Kilo. ![Kilo Qwiic terminal](../images/51065705922841.png) Qwiic-compatible devices mainly use **I²C communication**, allowing multiple devices to be connected on a single bus. You can use one or multiple Qwiic-compatible sensors and modules sold by various manufacturers. ![Qwiic connection example](../images/51065705924633.jpg) The Qwiic terminal consists of 2 power lines and 2 signal lines. The signal lines are connected directly to the internal microcontroller and can each be used individually as **digital IO** or **analog IN**. ![Qwiic pin configuration diagram](../images/51065705926169.jpg) | Pin | IO Function | | --- | --- | | 1 (black) | GND | | 2 (red) | 3.3V output (supplied from Kilo) | | 3 (blue) | IO1 / AD1 | | 4 (yellow) | IO2 / AD2 | ### ⚫︎ Available Power The Qwiic power line is shared with Kilo's internal power bus. The available current varies depending on Kilo's operating conditions. - Under normal operation (LTE-M connected, Wi-Fi/Bluetooth disabled), approximately **500mA** is available. - Because it varies depending on factors such as signal conditions, use approximately **100mA at most** as a guideline for safety. > ⚠️ > - If too much power is consumed, Kilo's internal protection circuit activates, shutting down the entire power line and causing a restart. ## Operation and Control | Timing | Signal Line State | | --- | --- | | Immediately after startup | **Hi-Z (high impedance)**. The signal lines are disabled. After a restart, the previous state is **not retained**; the lines return to the state they were in after power-on. | | After software configuration | Operates as **output/input/analog input** according to the configuration. | * * * --- ## USB (CDC Client) URL: https://obniz.com/reference/intelligent-edge-kilo/device-connection/usb-cdc-client * * * ## Overview Intelligent Edge Kilo (Kilo) is equipped with a **USB Type-C terminal**. In addition to connecting to a PC for configuration, it operates as a **CDC client (virtual COM port)**. When using it, disable the OS console function (normally OFF by default) and control sending and receiving from software. > ⚠️ > - **Kilo cannot act as a USB host.** It is recognized by the PC as a virtual COM port. ## Wiring and Connection Connect a host device such as a PC to the **USB Type-C terminal** on the side of Kilo. The figure below is an example of a **serial terminal's port configuration screen** (Port / 115200 / 8-N-1 / no Flow Control, etc.). It shows typical setting values, but **the actual port name differs depending on the obniz device.** ![Serial port configuration screen (example)](../images/51066086303513.png) ### ⚫︎ About Power > ❗ > Kilo supports **power supply from USB**. It can be powered while communicating at the same time. However, this is intended for temporary use such as during configuration, and is not recommended for long-term operation. ### ⚫︎ Recognition by the PC When connected, the PC recognizes it as a **USB serial (virtual COM port)**. The standard settings (example) when used with the OS console function are as follows. When controlling from software, change them as needed. | Item | Setting Value (example) | | --- | --- | | Baud rate | 115200 bps | | Data bits | 8 bit | | Parity | None | | Stop bits | 1 bit | ## Operation and Control | Timing | Communication State | | --- | --- | | Immediately after startup | Communication does not start. | | CDC function enabled by software | Communication is enabled, and sending and receiving are possible. | ### ⚫︎ Limitations Regarding OS Rewriting > ⚠️ > - **Rewriting the OS or directly operating the flash memory via USB is not possible.** > - No function is provided to directly access the internal microprocessor from the USB terminal. > - Firmware updates and OS rewriting should be performed from **obniz Cloud**. In the case of obniz Now, the method differs depending on the plan, so please contact us for more detailed information. * * * --- ## Built-in Sensors & Components URL: https://obniz.com/reference/intelligent-edge-kilo/built-in-sensors Built-in Sensors & Components documentation for Intelligent Edge Kilo. Covers Supply Voltage, Vibration & Shock Detection, Orientation, Body Temperature Measurement. --- ## Supply Voltage URL: https://obniz.com/reference/intelligent-edge-kilo/built-in-sensors/supply-voltage * * * ## Supply Voltage On the Intelligent Edge Kilo (Kilo), the supply voltage from the connector can be measured by the Kilo. It can be used to measure voltage stability, detect abnormal voltage drops, and, when running on a battery, estimate the remaining battery level. | Item | Specification | | --- | --- | | Accuracy | ±2% | | Resolution | 32 mV | | Measurable range | 0 to 33.3 V | * * * --- ## Vibration & Shock Detection URL: https://obniz.com/reference/intelligent-edge-kilo/built-in-sensors/vibration-shock ## Accelerometer The Intelligent Edge Kilo (Kilo) has a built-in accelerometer that provides **vibration/shock detection** and **orientation detection** functions. By default, it operates using the analysis algorithms included in obnizOS, and by updating the software, it can perform more detailed detection and advanced analysis. 👉 The accelerometer's algorithms can be switched or updated to suit your specific use case. ### ⚫︎ Vibration/Shock Detection The accelerometer is used to detect vibration and shock applied to the device. From this data, you can determine whether the device is moving or stationary, and detect unusual movements to identify anomalies. #### Use Cases - Determine the operating status of the device from vibration - Detect the start and stop of movement based on changes in vibration, and use this for power saving - Detect unusual vibration to help with the early detection of failures and anomalies --- ## Orientation URL: https://obniz.com/reference/intelligent-edge-kilo/built-in-sensors/orientation ## Accelerometer The Intelligent Edge Kilo (Kilo) has a built-in accelerometer that provides **vibration/shock detection** and **orientation detection** functions. By default, it operates using the analysis algorithms included in obnizOS, and by updating the software, it can perform more detailed detection and advanced analysis. 👉 The accelerometer's algorithms can be switched or updated to suit your specific use case. ### ⚫︎ Orientation Detection The accelerometer is used to detect the tilt or tipping over of the device. With this function, you can check whether the device is installed in the correct orientation or whether it has assumed an abnormal posture. ![Image of orientation detection](../images/51078565693593.png) #### Use Cases - Detect abnormal orientations such as tipping over - Estimate the number of operations or the current orientation from the number of tilt changes --- ## Body Temperature Measurement URL: https://obniz.com/reference/intelligent-edge-kilo/built-in-sensors/body-temperature * * * ## Temperature Sensor The Intelligent Edge Kilo (Kilo) has a built-in temperature sensor that can measure the temperature inside the device. Because it is located near the wireless module, **the displayed temperature may be slightly higher than the surrounding ambient temperature.** This sensor is not intended to measure the ambient temperature; instead, it is used to **monitor the temperature inside the device to assess its condition.** > ⚠️ > - **Body temperature is not a substitute for ambient temperature.** > It is not meant for measuring the surrounding air temperature, but rather for checking temperature changes and heat generation inside the device. | Item | Specification | | --- | --- | | Measurement temperature range | −20 to 85 ℃ | | Resolution | 1 ℃ | #### Use Cases - Monitor the temperature rise inside the device to detect abnormal heat generation early - Observe temperature changes to verify the effectiveness of heat dissipation and cooling - Perform safe operation and temperature control based on the internal temperature * * * --- ## Specifications URL: https://obniz.com/reference/intelligent-edge-kilo/specifications Specifications documentation for Intelligent Edge Kilo. Covers Product Specifications. --- ## Product Specifications URL: https://obniz.com/reference/intelligent-edge-kilo/specifications/product-spec * * * ## Specifications Power supply5 to 32 V (DC)Power consumptionAverage 0.2 WMaximum 5.0 WDuring cloud connection over LTE. No external supply. Varies with the LTE environment.Sleep operationTimer (1 second to 64800 seconds, or 1 minute to 64800 minutes)* Power consumption is higher than the Edge Micro and depends on the connection configuration.Guaranteed operating temperature range−10 to 60 ℃ (the entire unit including the enclosure)(Internal electronic components: −20 to 85 ℃)Mounting method① Place / adhere② DIN rail③ Slide-type attachmentobnizOSobnizOS 5 or laterSupports private key authentication and TLS 1.2 communicationSee the obnizOS guide for details.Wi-FiIEEE 802.11b/g/n (2 GHz)Can be used as WAN or Sniffer.Ethernet10 / 100 MbpsCan be used as WAN or LANNo auto cable detection (use straight-through connection for hubs)No PoE.LTELTE-M / NB-IoTBand 1/3/19/26/28Frequencies: 2100/1800/850/850/700 MHzBluetoothBLE5, Coded PHYGPS/GNSSPlanned for support in a future OS. Currently supported via Qwiic connection.Connector: SMAActive antenna with LNA recommendedSupported satellites: GPS L1 C/A, QZSS L1 C/AUSBUSB (CDC)Digital IO2 outputs / 2 inputsAnalog input2 ch (0–3.0 V)UART1 chSupports CMOS or RS232/422/485 via Qwiic.I2C1 chExpansion terminalQwiic terminalSerial communicationRS232 / RS422 / RS485 1 ch, half-duplex, built-in terminating resistor (120 Ω) configurableTransceivers: SP3485, MAX3221Data bits: 5/6/7/8 bitStop bits: 1/1.5/2Parity: none/even/oddFlow control: none / hardware (RTS/CTS, configurable via Qwiic only)DE/RE control: automatic DE control provided by the OS.CAN1 ch, built-in terminating resistor (120 Ω) configurableSupports 25 to 1000 kbpsTransceiver: ATA6561Relay1 ch SSRBlocking voltage: 60 VOn-resistance: 16 ΩMaximum continuous current: 100 mAMaximum peak current: 350 mAAccessoriesLTE antennaQR stickerTerminating resistor pins ×2 (RS485 / CANBus)4-pin connectors ×2Available countriesJapanVietnam (for Wi-Fi)CertificationsLTE: R 005-102592Wi-Fi/BLE: 007-AM0211 ## Dimensions ![Kilo exterior diagram](../images/51061739667097.png) ### ⚫︎ Front ![Kilo front view](../images/51061739667993.png) ### ⚫︎ Side ![Kilo side view](../images/51061739669657.png) ## Drawings / CAD Data Download the outline drawings (PDF) and CAD data (DXF / STEP) for each model. ### Kilo (with DIN adapter) - Outline drawing: [PDF](../images/IE_Kilo_DIN_outline_drawing.pdf) ・ [DXF](../images/IE_Kilo_DIN_outline_drawing.dxf) ・ [PNG](../images/IE_Kilo_DIN_outline_drawing.png) - 3D assembly: [STEP](../images/IE_Kilo_DIN_assembly.step) - Sketches (DXF): [Front](../images/IE_Kilo_DIN_front_sketch.dxf) ・ [Rear](../images/IE_Kilo_DIN_rear_sketch.dxf) ・ [Side](../images/IE_Kilo_DIN_side_sketch.dxf) ・ [Top](../images/IE_Kilo_DIN_top_sketch.dxf) ### Kilo - Outline drawing: [PDF](../images/IE_Kilo_outline_drawing.pdf) ・ [DXF](../images/IE_Kilo_outline_drawing.dxf) ・ [PNG](../images/IE_Kilo_outline_drawing.png) - 3D assembly: [STEP](../images/IE_Kilo_assembly.step) - Sketches (DXF): [Front](../images/IE_Kilo_front_sketch.dxf) ・ [Rear](../images/IE_Kilo_rear_sketch.dxf) ・ [Side](../images/IE_Kilo_side_sketch.dxf) ・ [Top](../images/IE_Kilo_top_sketch.dxf) * * * --- ## Intelligent Edge Micro URL: https://obniz.com/reference/intelligent-edge-micro Reference documentation for Intelligent Edge Micro. Covers Setup Guide, Power, Internet Connection, Device & Sensor Connection, Built-in Sensors & Components, Specifications. --- ## Setup Guide URL: https://obniz.com/reference/intelligent-edge-micro/setup-guide Setup Guide documentation for Intelligent Edge Micro. Covers Initial Setup, Settings. --- ## Initial Setup URL: https://obniz.com/reference/intelligent-edge-micro/setup-guide/initial-setup * * * > 🎯 > **Goal of This Chapter** > Get the Intelligent Edge Micro ready to use by going through unboxing, the various registrations, the various connections, securing the device, and connecting to the Internet. > [Flow] Unboxing > Register via QR > Connect the antenna (for LTE) > Power and Internet connection > > (for wired) Connect to devices > Install and secure > Use and configure Wi-Fi/Ethernet ## Unboxing Take the Intelligent Edge Micro unit (hereafter abbreviated as Micro) out of the box and place it on a stable location, such as a desk. After this, connect in the following order. 1. Register via QR 2. (For LTE) Connect the antenna 3. Connect to power and confirm the Internet connection 4. (If necessary) Connect to the target device 5. Secure the Micro at the installation location ## Register via QR > ❗ > If you have a contract for obniz Now, registration is already complete at the time of shipment, so this step is unnecessary. > Proceed to the next step, "■ (For LTE) Connect the antenna." The following items are included in the Micro's outer box. ・obnizID: a unique identification number assigned to each device XXXX-XXXX (X: half-width digit) ・QR code required for device registration: a QR code that differs for each device Scan the QR code on the obniz Now device registration screen to register it. > 🚨 > ・Do not share an unregistered QR code with others. > Once it has been registered, the same QR code can no longer be used for registration. > If you register one by mistake, please contact obniz with the obnizID of the device in question. ## Connect the Antenna (for LTE) Fit the enclosed antenna onto the "LTE-M/NB-IoT" connector and secure it by turning it. The antenna can be switched as an option at the time of delivery, but in the case of a rod antenna it looks as follows. ![](../images/56579066992025.jpg) Once online, you can use various services over the Internet. If you are connecting wirelessly to sensors and the like, there is nothing else to do on the unit. This completes the process. ## (For Wired) Connection to Devices To connect to other devices via UART or similar, refer to the page for the connection method corresponding to each standard. The Micro has a ZH8 connector at the bottom of the unit, which can be used as digital and analog terminals such as GPIO/AD/UART. ## Install and Secure It is recommended to either place the Micro unit as is or secure it with screws. ## Use and Configure Wi-Fi/Ethernet By switching the settings, you can use Wi-Fi or Ethernet instead of LTE. For details, see the [settings page](settings). ■ Details on Power and Internet Connection Power is connected via the USB power connector at the bottom of the Micro. Supply power with the dedicated Type-C cable. Alternatively, 5V can be supplied externally via the ZH8 connector. As soon as power is turned on, the white LED next to "ONLINE" begins to blink. This LED indicates the Internet connection status, and a continuously lit state means a successful connection to the Internet and the obniz cloud. If the blinking state continues, the antenna may not be connected properly, or the device may be out of range. For details on the specific lit states and each state, refer to the obnizOS reference below. This is common not only to LTE but also to Wi-Fi/Ethernet. [obnizOS LED status and lighting patterns](../../obnizos-for-esp32/components/led#%E7%8A%B6%E6%85%8B%E3%81%A8%E7%82%B9%E7%81%AF%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3) ## Preparation Checklist When you have confirmed the following items, the preparation for this chapter is complete. > ⚠️ > - **What if the gateway's own Wi-Fi (Wi-Fi) login screen does not appear automatically?** > Go to http://192.168.254.1/. > → For details, see "How to Display the Login Screen." > - **What if you configured it with a different Wi-Fi than the one at the location where you want to use it?** > It may not work correctly. After resetting, reconfigure it with the name and password of the Wi-Fi that can actually be used at the installation location. > → For details, see "How to Reset." > - **What if you cannot register successfully with the QR code?** > You can register by photographing the QR code with a smartphone and displaying that image on the PC screen. > → For details, see "QR Registration Method Using a PC and a Smartphone." > - **What if the lamp color differs from the description?** > The display may differ depending on the situation. > → For details, see "LED Status List." --- ## Settings URL: https://obniz.com/reference/intelligent-edge-micro/setup-guide/settings To switch the network that obnizOS connects to over to Wi-Fi, you need to enter configuration mode. In configuration mode, you can also make detailed setting changes, such as LED and button behavior, from JSON. ### Configuration Mode In the normal LTE connection mode, the device does not automatically transition to configuration mode; it is designed so that settings are not normally switched. Please use configuration mode in cases such as when LTE does not work and you want to use Wi-Fi. To configure, you need to press and hold the configuration button for 3 seconds or longer. With the power on, prepare a thin pin such as a SIM pin and press and hold the recessed button. The button is small and difficult to press. When the device enters configuration mode, the unit's white LED enters a slow blinking state. In addition, the unit broadcasts a Wi-Fi for configuration with the SSID "obniz-xxxxxxxx" (where x is the obnizID). ![](../images/56579268248601.jpg) ### Configuration Methods The configuration methods supported by the Intelligent Edge Micro (Micro) are as follows. For each configuration method, refer to the obnizOS reference. - [Via Wi-Fi](../../obnizos-for-esp32/settings/setting-via-browser) - [Via USB serial](../../obnizos-for-esp32/settings/setting-via-serial) - [Via the Internet](../../obnizos-for-esp32/settings/setting-via-cloud) --- ## Power URL: https://obniz.com/reference/intelligent-edge-micro/power Power documentation for Intelligent Edge Micro. Covers Power. --- ## Power URL: https://obniz.com/reference/intelligent-edge-micro/power/power ## How to Supply Power The Intelligent Edge Micro (Micro) **has no built-in battery**. Supply power from an external DC power source. - Power supply from USB - Power supply from the ZH8 connector ### Power Supply from USB Connect the dedicated Type-C cable to the Micro. Cables other than the dedicated one can be used as long as they fit. The requirements for an AC adapter are as follows. | Item | Requirement | | --- | --- | | Power | 5 W or more | | PD | Not required (no problem if a PD function is present) | * When connecting USB to a PC or similar, it is recognized as a CDC device (serial communication device). ### Power Supply from the Connector Power can be supplied from the ZH8 connector at the bottom. This is a 5V input of the same standard as USB. The connector arrangement is as follows. | Item | Pin Assignment | Comment | | --- | --- | --- | | 0 (product edge side) | VDD IN (5v) | Connect the 5V input here. | | 1 | 3.3V Out | When 5V is input, the output of the internal regulator (3.3V bus) is provided. | | 2 | GND | Connect the 5V input here. | | 3 | GPIO4 | | | 4 | GPIO3 | | | 5 | GPIO2 | | | 6 | GPIO1 | | | 7 (product center side) | GPIO0 | | ## Comparison of Power Supply Methods > ❗ > **[Internal Power Conversion Efficiency]** > **Connector power supply > USB power supply.** 👉 To achieve maximum efficiency in sleep-centric use with solar panels and the like, **connector power supply is recommended.** | Item | Connector Use | USB Use | | --- | --- | --- | | Voltage range | DC 5.0–5.5 V | DC 5.0–5.5 V (USB standard range) | | Power consumption | Approx. 0.2 W on average 👉 May spike temporarily during communication, etc. | Same as left | | Protection circuit | — | Reverse-connection and reverse-current prevention circuit | ## Behavior at Low Voltage ### Order of Operation Shutdown When the power voltage drops, shutdown occurs in stages. ① **Near 3.3 V**: If the 3.3 V bus is maintained, the network and so on may continue ② **Below 3.3 V**: Each component shuts down in sequence ### Anomaly Detection and Restart by obnizOS obnizOS automatically restarts and reconnects when it detects an anomaly. 👉 Even when recovering from a partial voltage drop, it will attempt to re-establish the network. --- ## Internet Connection URL: https://obniz.com/reference/intelligent-edge-micro/internet-connection Internet Connection documentation for Intelligent Edge Micro. Covers Wi-Fi, LTE-M / NB-IoT. --- ## Wi-Fi URL: https://obniz.com/reference/intelligent-edge-micro/internet-connection/wi-fi > 🎯 > **Goal** > Connect to the Internet via Wi-Fi. * * * ## Connecting via Wi-Fi The Intelligent Edge Micro (Micro) has a built-in Wi-Fi antenna and can connect via Wi-Fi (2.4 GHz). Note: When installed inside a metal box, it may become difficult to connect to Wi-Fi. In this case, please consider other connection methods. ## Specifications of Connectable Wi-Fi The following Wi-Fi can be connected to. Please check in advance whether the Wi-Fi you plan to use meets the specifications below. Frequency2.4GHzModulationIEEE 802.11b/g/nStealth SSIDConnectable (for use in Japan, set the country setting to "Japan")AuthenticationSupports WPA2/PSK (AES, TKIP), WEP, WPA-PSK, and WPA2 Enterprise (certificate).WPA2/PSK + Captive portal is not supported. WPA3 may not be supported depending on the environment.Communication methodHTTPS (TLS 1.2) WebSocketNumber of connections1Communication directionRequests from the device only (the server never connects to the device)ProxyConfigurable (HTTP or HTTPS)Connection destination domainsobniz.io, *.obniz.io, obniz.com, *.obniz.com (there may be multiple for *)Wi-Fi settings that can be storedUp to 5 ## Check the LED After Power-On After power-on, the white LED next to "ONLINE" indicates the connection status. | State | Meaning | | --- | --- | | Off | No power supply (check the power and wiring) | | Blinking | Connection in progress (if it continues for a long time, such as 30 seconds or more, check the network and settings) | | Continuously lit | Connection to the Internet and the cloud service obniz Now is complete | ## Troubleshooting from the LED State (Wi-Fi) | Condition (LED) | Possible Cause | How to Respond | | --- | --- | --- | | **The white LED stays off** | ・No power supplied / insufficient voltage (outside 5–32 V) ・Power connector or USB not connected or loose | Check the power, wiring, and USB, and try a different power source or a different cable. Re-secure the connector with appropriate force (about a light tightening). | | **The white LED stays blinking (does not transition to continuously lit)** | ・Mismatched SSID/password (uppercase/lowercase, full-width/half-width characters) ・Stealth SSID set so that it cannot be scanned ・Unsupported encryption/authentication (WPA2/PSK + Captive portal, etc.) ・2.4 GHz disabled, channel interference / weak signal, MAC filter enabled | Re-enter the SSID/password; for a stealth SSID, register it via manual configuration. Enable 2.4 GHz and change the channel (1/6/11 recommended). Change the encryption/authentication to a supported method such as WPA2/PSK (AES). Register the Micro as allowed in the router's MAC filter. | | **The white LED stays blinking (does not transition to continuously lit)** | ・DHCP not working / static IP mismatch (incorrect IP/GW/DNS) ・DNS cannot be resolved, 443/TCP blocked by firewall/proxy ・Insufficient signal quality (frequent packet loss) | Check that DHCP is working / for a static IP, review the IP/GW/DNS. Allow 443/TCP to `obniz.io` / `obniz.com` (and `*.obniz.io`, `*.obniz.com`). When using a proxy, review the method (HTTP/HTTPS) / host / authentication. Move closer to the router, avoid obstacles, and change the channel to improve it. | * * * --- ## LTE-M / NB-IoT URL: https://obniz.com/reference/intelligent-edge-micro/internet-connection/lte-m-nb-iot > 🎯 > **Goal** > Understand the basics of LTE-M / NB-IoT antennas and how to choose the separately sold antennas available for the Micro. * * * ## LTE-M / NB-IoT The Intelligent Edge Micro (Micro) provides cellular network connectivity supporting both LTE-M and NB-IoT. This allows it to connect to the Internet from environments without Wi-Fi or Ethernet, or from moving objects. > 🚨 > The Micro's cellular network function is provided under a dedicated plan. The SIM / eSIM is configured at the factory, and **your own SIM cannot be used.** ## LTE-M LTE-M is an LPWA (Low Power Wide Area) method that leverages the existing LTE network. For domestic use, LTE-M is often chosen, while the availability of NB-IoT varies by carrier and region. ### Features - A type of cellular network with wide-area coverage (depending on carrier and region). - Low power consumption. - Tends to connect relatively easily even inside buildings or in remote areas. - Low communication speed (rough guide: several hundred kbps). ## Antenna Connection Connect a compatible antenna to the SMA connector marked "LTE-M / NB-IoT" on the side of the Micro. Align the antenna straight and **turn it by hand until it stops** to secure it. 👉 No tools are required. Tightening it about as firmly as you would close a jam jar is sufficient (avoid overtightening). ![](../images/56580349931417.jpg) ## Separately Sold LTE-M / NB-IoT Antennas Available for the Micro An LTE-M / NB-IoT antenna is included with the Micro, but separately sold antennas can also be used depending on the environment. The following are representative examples that can be installed in Japan. > ❗ > RP-SMA (reverse SMA) cannot be used. It looks similar, but its internal pin arrangement differs and is not compatible. | Model Number | Type | Features | Source | | --- | --- | --- | --- | | DELTA1A/X/SMAM/S/S/11![DELTA1A rod antenna](../images/56580389992345.png) | Rod antenna | Temperature range: -20 to +60 °C | [Product page (Mouser Japan)](https://www.mouser.jp/ProductDetail/Siretta/DELTA1A-X-SMAM-S-S-11?qs=QNEnbhJQKvZMZQTjGyjQyQ%3D%3D)/ [Sales page (MonotaRO)](https://www.monotaro.com/p/4715/2639/) | | TG.08.0113![TG.08.0113 rod antenna](../images/56580389993113.png) | Rod antenna | Temperature range: -40 to +85 °C | [Product page (Mouser Japan)](https://www.mouser.jp/ProductDetail/Taoglas/TG.08.0113?qs=JbASvl9PsS17ajPV2Gadew%3D%3D)/ [Product page (DigiKey Japan)](https://www.digikey.jp/ja/products/detail/taoglas-limited/TG-08-0113/5120279) | | GSA.8822.B.301111![GSA.8822.B.301111 antenna with cable](../images/56580349940889.png) | With cable | Temperature range: -40 to +85 °C/Cable length: 3 m/Waterproof and dustproof: IP67/Includes double-sided tape | [Product page (Mouser Japan)](https://www.mouser.jp/ProductDetail/Taoglas/GSA.8822.B.301111?qs=MLItCLRbWswm8XVZZ6MleQ%3D%3D)/ [Product page (DigiKey Japan)](https://www.digikey.jp/ja/products/detail/taoglas-limited/GSA-8822-B-301111/9972801) | | GA.111.101111![GA.111.101111 antenna with cable](../images/56580389994265.png) | With cable | Cable length: 1 m/Waterproof and dustproof: none/Magnetic mount (vertical 1.8 kgf, horizontal 0.8 kgf) | [Datasheet](https://www.taoglas.com/datasheets/GA.111.101111.pdf)/ [Product page](https://www.taoglas.com/product/ga-111-101111-3dbi-mini-magnetic-mount-698960mhz-17102700mhz/) | ## Checking the Communication Status After power-on, if the LED is blinking **twice per second**, the LTE connection is in progress. If it stays continuously lit, communication has not been established. Check the antenna, the installation location, and any obstructions in the surroundings. --- ## Device & Sensor Connection URL: https://obniz.com/reference/intelligent-edge-micro/device-connection Device & Sensor Connection documentation for Intelligent Edge Micro. Covers GPIO / AD / UART, USB (CDC Client). --- ## GPIO / AD / UART URL: https://obniz.com/reference/intelligent-edge-micro/device-connection/gpio-ad-uart The Intelligent Edge Micro (Micro) is equipped with a ZH8 connector that allows power supply and wired connection to devices. It is particularly suited for wired connection to devices such as the following. **Example Use Cases** - Analog sensors such as CT sensors - Relays controllable via GPIO, or checking contact input - Communication with various sensors and devices over UART/SPI/I2C/CANBus ## Pin Assignment | Item | Pin Assignment | | --- | --- | | 0 (product edge side) | VDD IN (5v) This supplies power to the Intelligent Edge Micro. | | 1 | 3.3V Out This is the output from the 3.3V bus inside the Intelligent Edge Micro. | | 2 | GND | | 3 | GPIO4 / AD4 | | 4 | GPIO3 / AD3 | | 5 | GPIO2 / AD2 | | 6 | GPIO1 / AD1 | | 7 (product center side) | GPIO0 / AD0 | --- ## USB (CDC Client) URL: https://obniz.com/reference/intelligent-edge-micro/device-connection/usb-cdc-client * * * ## Overview The Intelligent Edge Micro (Micro) is equipped with a **USB Type-C port**. In addition to being usable for configuration when connected to a PC, it operates as a **CDC client (virtual COM port)**. When using it, disable the OS console function (it is normally OFF by default) and control transmission and reception from software. > ⚠️ > - **The Micro cannot act as a USB host.** From the PC side, it is recognized as a virtual COM port. ## Wiring and Connection Connect a host device such as a PC to the **USB Type-C port** on the side of the Micro. The figure below is an example of a **serial terminal port settings screen** (Port / 115200 / 8-N-1 / no Flow Control, etc.). It shows typical setting values, but **the actual Port name varies depending on the obniz device.** ![Serial port settings screen (example)](../images/56580567477913.png) ### ⚫︎ About Power > ❗ > The Micro supports **power supply from USB**. It can be powered while communicating at the same time. ### ⚫︎ Recognition by the PC When connected, the PC recognizes it as a **USB serial (virtual COM port)**. The standard settings (example) when used with the OS console function are as follows. When controlling from software, change them as needed. | Item | Setting Value (example) | | --- | --- | | Communication speed (baud rate) | 115200 bps | | Data bits | 8 bit | | Parity | None | | Stop bits | 1 bit | ## Operation and Control | Timing | Communication State | | --- | --- | | Immediately after startup | Communication does not start. | | After enabling the CDC function from software | Communication is enabled, and transmission and reception are possible. | ### ⚫︎ Restrictions on OS Rewriting > ⚠️ > - **OS rewriting and direct operation of the flash memory over USB are not possible.** > - No function is provided for directly accessing the internal microprocessor from the USB port. > - Perform firmware updates and OS rewriting from **obniz Cloud**. In the case of obniz Now, the method varies depending on the plan, so please contact us for more detailed information. * * * --- ## Built-in Sensors & Components URL: https://obniz.com/reference/intelligent-edge-micro/built-in-sensors Built-in Sensors & Components documentation for Intelligent Edge Micro. Covers Orientation, Vibration & Shock Detection, Body Temperature Measurement. --- ## Orientation URL: https://obniz.com/reference/intelligent-edge-micro/built-in-sensors/orientation ## Accelerometer The Intelligent Edge Micro (Micro) has a built-in accelerometer that provides **vibration/shock detection** and **orientation detection** functions. By default, it operates using the analysis algorithms included in obnizOS, and updating the software enables more detailed detection and advanced analysis. 👉 The accelerometer allows you to switch or update its algorithms to suit your use case. ### ⚫︎ Orientation Detection The accelerometer is used to detect the tilt or fall of the device. This function lets you confirm whether the device is installed in the correct orientation and whether it has entered an abnormal posture. ![Image of orientation detection](../images/56583498217241.png) #### Example Use Cases - Detect abnormal postures such as a fall - Estimate the number of operations or the current orientation from the number of tilt changes --- ## Vibration & Shock Detection URL: https://obniz.com/reference/intelligent-edge-micro/built-in-sensors/vibration-shock ## Accelerometer The Intelligent Edge Micro (Micro) has a built-in accelerometer that provides **vibration/shock detection** and **orientation detection** functions. By default, it operates using the analysis algorithms included in obnizOS, and updating the software enables more detailed detection and advanced analysis. 👉 The accelerometer allows you to switch or update its algorithms to suit your use case. ### ⚫︎ Vibration/Shock Detection The accelerometer is used to detect the vibration and shock applied to the device. From this data, you can determine whether the device is moving or stopped, and detect unusual movements to find anomalies. #### Example Use Cases - Determine the operating status of the device from vibration - Detect the start or stop of movement based on changes in vibration, and use this for power saving - Detect vibration that differs from normal to help with the early discovery of faults or anomalies --- ## Body Temperature Measurement URL: https://obniz.com/reference/intelligent-edge-micro/built-in-sensors/body-temperature * * * ## Temperature Sensor The Intelligent Edge Micro (Micro) has a built-in temperature sensor that measures the temperature inside the device. Because the sensor is located near the wireless module, **the displayed temperature may be slightly higher than the surrounding air temperature.** This sensor is not intended for measuring the ambient temperature; instead, it is used to **check the internal temperature of the device to monitor its operating condition.** > ⚠️ > - **The internal temperature is not a substitute for the ambient temperature.** > Rather than measuring the surrounding air temperature, it is used to check temperature changes and heat generation inside the device. | Item | Specification | | --- | --- | | Measurement temperature range | −20 to 85 °C | | Resolution | 1 °C | #### Example Use Cases - Monitor the temperature rise inside the device to detect abnormal heat generation early - Observe temperature changes to verify the effectiveness of heat dissipation or cooling - Use the internal temperature to ensure safe operation or to perform temperature control * * * --- ## Specifications URL: https://obniz.com/reference/intelligent-edge-micro/specifications Specifications documentation for Intelligent Edge Micro. Covers Specifications. --- ## Specifications URL: https://obniz.com/reference/intelligent-edge-micro/specifications/specifications * * * ## Specifications Power supply5.0-5.5 V (DC)Power consumption0.2 W on average5.0 W maximumDuring cloud connection over LTE. No external supply. Varies with the LTE environment.Sleep operationTimer (1 second to 64800 seconds, or 1 minute to 64800 minutes)Guaranteed operating temperature range−10 to 60 °C (entire unit including the enclosure)(internal electronic components: −20 to 85 °C)Mounting method① Place / adhereDimensions70.3 × 55.0 × 17.0 mm(including protrusions, excluding the antenna)Weight36.0 gobnizOSobnizOS 5 or higherSupports private-key authentication and TLS 1.2 communicationSee the obnizOS guide for details.Wi-FiIEEE 802.11b/g/n (2 GHz)Can be used as WAN or as a Sniffer.LTELTE-M / NB-IoTBand 1/3/19/26/28Frequencies: 2100/1800/850/850/700 MHzBluetoothBLE5, Coded PHYGPS/GNSSPlanned support in a future OS. Currently supported via ZH8 connector connection.Connector: SMAActive antenna with built-in LNA recommendedSupported satellites: GPS L1 C/A, QZSS L1 C/AUSBUSB (CDC)Digital IOOutput 5 / Input 5Analog input5 ch (0–3.0 V)UARTUp to 2 ch※ When using LTE, 1 is used by LTE, andenabling the USB console uses 1 more, so a total of 2 ch are used bythe OS, making them unavailable for user use.Data bits: 5/6/7/8 bitStop bits: 1/1.5/2Parity: none/even/oddFlow control: none / hardware (RTS/CTS)I2C1 chExpansion terminalZH8 connectorCAN1 ch Supports 25–1000 kbpsAn external transceiver and its configuration are required. (e.g., ATA6561)AccessoriesLTE antennaQR stickerAvailable countriesJapanVietnam (in the case of Wi-Fi)CertificationLTE: R 005-102592Wi-Fi/BLE: 007-AM0211 ## External Appearance ![](../images/56583735732633.png) ### ⚫︎ Front ![](../images/56583735734169.png) ## Drawings / CAD Data Download the outline drawing (PDF) and CAD data (DXF / STEP). - Outline drawing: [PDF](../images/IE_Micro_outline_drawing.pdf) ・ [DXF](../images/IE_Micro_outline_drawing.dxf) - 3D assembly: [STEP](../images/IE_Micro_assembly.step) - Sketches (DXF): [Front](../images/IE_Micro_front_sketch.dxf) ・ [Rear](../images/IE_Micro_rear_sketch.dxf) ・ [Side](../images/IE_Micro_side_sketch.dxf) ・ [Top](../images/IE_Micro_top_sketch.dxf) * * * --- ## obniz Board 1Y URL: https://obniz.com/reference/obniz-board-1y ![](images/obniz_board_1y.jpg) ## Image ![](images/hw_1y_details.jpg) --- ## Hardware spec URL: https://obniz.com/reference/obniz-board-1y/hardware-spec Type Value Size w66.6\*h36.3 (mm).including usb and switch Mounting Hole M2\*2 Wi-Fi 802.11 b/g/n (2.4 GHz), up to 150 Mbps (21.5dBm) Protocol Websocket. TLS1.2(regarding account plan) Protocol Setting static ip, dns server, proxy server Bluetooth Compliant with Bluetooth v4.2 BR/EDR and BLE specification Certifications MIC, FCC, IC by ESP-WROOM-32 Power Supply USB TypeC or Power Connector Operation Voltage(vcc) 推奨 5v (3.3-5.5v) Operation Current Ave 120mA @ 5v (Wi-Fi connected, BLE standing by, no parts connected, using Display) Operation Current(Sleep) 20-40uA Main Processor ESP32 Sub Processor PIC16F1 Num of MotorDriver IC 6 (DRV8839) IO num 12 IO output 5V(vcc) push-pull max 1A 3.3V push-pull 3.3v open-drain(5v tolerant) pull-up(3.3v/5v(vcc)) pull-down Peripherals GPIO 12 A/D 12 PWM 6 assignable to everyIO UART 2 assignable to everyIO SPI 2 assignable to everyIO I2C 1 assignable to everyIO Display Black dot 128\*64 Recommended Storage Temperature \-30 to 80 degrees Celsius Recommended Operation Temperature 0 to 70 degrees Celsius Sleep Timer(1 to 64800 sec or 1 to 64800 minutes) or change interrupt for io0 (edge up/down) Soldering Pb free --- ## PinOut URL: https://obniz.com/reference/obniz-board-1y/pinout ## Electrical Specification obniz IO Physical IO Drive Method Internal Weak Pull Up/Down io0 io0 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io1 io1 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io2 io2 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io3 io3 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io4 io4 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io5 io5 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io6 io6 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io7 io7 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io8 io8 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io9 io9 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io10 io10 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io11 io11 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v ## Peripherals ### PINOUT Peripheral function io0 io1 io2 io3 io4 io5 io6 io7 io8 io9 io10 io11 IO output YES YES YES YES YES YES YES YES YES YES YES YES input YES YES YES YES YES YES YES YES YES YES YES YES AD AD YES YES YES YES YES YES YES YES YES YES YES YES PWM IO YES YES YES YES YES YES YES YES YES YES YES YES UART TX YES YES YES YES YES YES YES YES YES YES YES YES RX YES YES YES YES YES YES YES YES YES YES YES YES CTS YES YES YES YES YES YES YES YES YES YES YES YES RTS YES YES YES YES YES YES YES YES YES YES YES YES SPI CLK YES YES YES YES YES YES YES YES YES YES YES YES MOSI YES YES YES YES YES YES YES YES YES YES YES YES MISO YES YES YES YES YES YES YES YES YES YES YES YES I2C SDA YES YES YES YES YES YES YES YES YES YES YES YES SCL YES YES YES YES YES YES YES YES YES YES YES YES LogicAnalyzer IO YES YES YES YES YES YES YES YES YES YES YES YES Measure PULSE YES YES YES YES YES YES YES YES YES YES YES YES ECHO YES YES YES YES YES YES YES YES YES YES YES YES ### Peripherals: IO ##### output Each IO can put out digital values. Drive methods can be selected from the three below. Type Voltage max A max Freq Details push-pull `5v` <=1A <=250khz(recommend) Default. Overcurrent protection push-pull `3v` <=1mA(recommend) <=80Mhz over current detection when using io.output(). open-drain `<=5v` <=1mA(recommend) <=80Mhz Each method can be configured independently for each IO. Not only for io.output(), but also for UART and SPI you can choose your preferred drive method. ##### input There is only one input method. 3v input with 5v tolerant, so the threshold value is CMOS level. Type Level max Freq Detail digital-in `3v(5v tolerant)` <=80Mhz ##### internal weak pull-up/pull-dow Pull up and down can be configured independently for each IO. There are four types as below. Type Pull to Detail floating   Default pull-up `5v` pull-up `3v` pull-down `gnd` ### AD ##### 12ch same time. All 12ch ad can be used. It will not affect the sampling rate. ##### 30 samples/sec or slower Maximum sampling rate depends on your network speed and on obniz Board 1Y firmware version.(with ver1.0.0, max is 30samples/sec) ##### 10bit - VDD calibrated ad also monitors vdd of obniz Board 1Y itself(normally 5v). Each ad result will be calibrated. And ad accuracy is 10bit. Calibration method is depend on firmware version. Firmware version calibration method under 1.2 Always 1.2 or higher Only Vdd is under 4.5v ##### ad can be started even io is used for io-output/uart/spi etc ad converter is independent. It also works while IO is used for another function. ### PWM 6(pwm0 to pwm5) are available. ### UART 2 (uart0 to uart1) are available. Available Configration 1. baud: number (default 115200) 2. stop: stop bit length 1(default)/1.5/2 3. bits: data bits 8(default)/5/6/7 4. parity: parity check "off"(default)/"odd"/"even" 5. flowcontrol: flow control "off"(default)/"rts"/"cts"/"rts-cts" 6. rts: io for rts (optional) 7. cts: io for cts (optional) ### SPI 2 (spi0 to spi1) are available. Only Master mode. ### I2C 1 (i2c0) is available. Max speed is 1Mhz. Master/Slave mode. But slave mode only works with "written" events. You can't set data to be read. ### LogicAnalyzer 1 (logicanalyzer) is available. ### Measure 1 (measure) is available. ## Embeded ### Display 128x64 mono pixel STN display. ### Switch 4 State Digital Switch ### BLE BLE32 embeded Bluetooth Module --- ## obniz Board URL: https://obniz.com/reference/obniz-board ![](images/obniz_board.jpg) ## Image ![](images/hw_details.png) ![](images/obniz_box.jpg) ![](images/obniz_box3.jpg) --- ## Hardware spec URL: https://obniz.com/reference/obniz-board/hardware-spec Type Value Size 69.8\*36.3 mm.including usb and switch Mounting Hole M2\*2 Wi-Fi 802.11 b/g/n (2.4 GHz), up to 150 Mbps (21.5dBm) ([Supported Wi-Fi details](../obnizos-for-esp32/wi-fi/)) Protocol Websocket. TLS1.2(regarding account plan) Protocol Setting static ip, dns server, proxy server Bluetooth Compliant with Bluetooth v4.2 BR/EDR and BLE specification Certifications MIC, FCC, IC by ESP-WROOM-32 Operation Voltage(vcc) Recommended 5v (4.5V-5.5v)(microUSB or J1 pin) Operation Current Ave 170mA @ 5v (Wi-Fi connected, BLE standing by, no parts connected, OLED displayed) Maximum supply via microUSB 1.8A ( If you need more. Please consider using J1 pin. ) Main Processor ESP32 Sub Processor PIC16F1 Num of MotorDriver IC 6 (DRV8839) IO num 12 IO output 5V(vcc) push-pull max 1A 3.3V push-pull 5V/3.3v open-drain pull-up(3.3v/5v(vcc)) pull-down Peripherals GPIO 12 A/D 12 PWM 6 assignable to everyIO UART 2 assignable to everyIO SPI 2 assignable to everyIO I2C 1 assignable to everyIO OLED White dot 128\*64 Recommended Storage Temperature \-30 to 80 degrees Celsius Recommended Operation Temperature 0 to 70 degrees Celsius OTA YES Soldering Pb free ## Dimension [![](images/obniz_dimensions.png)](/images/obniz_dimensions.png) --- ## PinOut URL: https://obniz.com/reference/obniz-board/pinout ## Electrical Specification obniz IO Physical IO Drive Method Internal Weak Pull Up/Down io0 io0 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io1 io1 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io2 io2 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io3 io3 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io4 io4 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io5 io5 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io6 io6 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io7 io7 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io8 io8 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io9 io9 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io10 io10 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v io11 io11 Input 3.3v(5v tolerant)(default) Output push-pull5v(1A mode) Output push-pull3v Output open-drain float(default) pull-up to 5v pull-up to 3v pull-down to 0v ## Peripherals ### PINOUT Peripheral function io0 io1 io2 io3 io4 io5 io6 io7 io8 io9 io10 io11 IO output YES YES YES YES YES YES YES YES YES YES YES YES input YES YES YES YES YES YES YES YES YES YES YES YES AD AD YES YES YES YES YES YES YES YES YES YES YES YES PWM IO YES YES YES YES YES YES YES YES YES YES YES YES UART TX YES YES YES YES YES YES YES YES YES YES YES YES RX YES YES YES YES YES YES YES YES YES YES YES YES CTS YES YES YES YES YES YES YES YES YES YES YES YES RTS YES YES YES YES YES YES YES YES YES YES YES YES SPI CLK YES YES YES YES YES YES YES YES YES YES YES YES MOSI YES YES YES YES YES YES YES YES YES YES YES YES MISO YES YES YES YES YES YES YES YES YES YES YES YES I2C SDA YES YES YES YES YES YES YES YES YES YES YES YES SCL YES YES YES YES YES YES YES YES YES YES YES YES LogicAnalyzer IO YES YES YES YES YES YES YES YES YES YES YES YES Measure PULSE YES YES YES YES YES YES YES YES YES YES YES YES ECHO YES YES YES YES YES YES YES YES YES YES YES YES ### Peripherals: IO ##### output Each IO can put out digital values. Drive methods can be selected from the three below. Type Voltage max A max Freq Details push-pull `5v (vcc)` <=1A <=250khz(recommend) Default. Overcurrent protection push-pull `3v` <=1mA(recommend) <=80Mhz over current detection when using io.output(). open-drain `<=vcc` <=1mA(recommend) <=80Mhz Each method can be configured independently for each IO. Not only for io.output(), but also for UART and SPI you can choose your preferred drive method. ##### input There is only one input method. 3v input with 5v tolerant, so the threshold value is CMOS level. Type Level max Freq Detail digital-in `3v(5v tolerant)` <=80Mhz ##### internal weak pull-up/pull-dow Pull up and down can be configured independently for each IO. There are four types as below. Type Pull to Detail floating   Default pull-up `5v(vcc)` pull-up `3v` pull-down `gnd` ### AD ##### 12ch same time. All 12ch ad can be used. It will not affect the sampling rate. ##### 30 samples/sec or slower Maximum sampling rate depends on your network speed and on obniz Board firmware version.(with ver1.0.0, max is 30samples/sec) ##### 10bit - VDD calibrated ad also monitors vdd of obniz Board itself(normally 5v). Each ad result will be calibrated. And ad accuracy is 10bit. Calibration method is depend on firmware version. Firmware version calibration method under 1.2 Always 1.2 or higher Only Vdd is under 4.5v ##### ad can be started even io is used for io-output/uart/spi etc ad converter is independent. It also works while IO is used for another function. ### PWM 6(pwm0 to pwm5) are available. ### UART 2 (uart0 to uart1) are available. Available Configration 1. baud: number (default 115200) 2. stop: stop bit length 1(default)/1.5/2 3. bits: data bits 8(default)/5/6/7 4. parity: parity check "off"(default)/"odd"/"even" 5. flowcontrol: flow control "off"(default)/"rts"/"cts"/"rts-cts" 6. rts: io for rts (optional) 7. cts: io for cts (optional) ### SPI 2 (spi0 to spi1) are available. Only Master mode. ### I2C 1 (i2c0) is available. Max speed is 1Mhz. Master/Slave mode. But slave mode only works with "written" events. You can't set data to be read. ### LogicAnalyzer 1 (logicanalyzer) is available. ### Measure 1 (measure) is available. ## Embeded ### Display 128x64 mono pixel OLED display. ### Switch 4 State Digital Switch ### BLE BLE32 embeded Bluetooth Module --- ## Ws URL: https://obniz.com/reference/websocket/ws # ws ## request: reset_obniz_on_ws_disconnection | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ws.reset_obniz_on_ws_disconnection` | boolean | required |   | ``` // Json Example [ { "ws": { "reset_obniz_on_ws_disconnection": false } } ] ``` ## response: ready all things ready | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ws.ready` | boolean | requiredconst `true` |   | ``` //Response Example [ { "ws": { "ready": true } } ] ``` ## response: obniz target device information | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ws.obniz.hw` | string | required | Hardware Identifier String of target device  | | `ws.obniz.firmware` | string | required | Installed firmware version of target device  | | `ws.obniz.metadata` | string |   | device metadata user set on cloud  | | `ws.obniz.connected_network.online_at` | number | required | Epoch Unix Timestamp (seconds) at device become online on the cloud  | | `ws.obniz.connected_network.net` | string |   | Current connected network type. Defined in setting json  | | `ws.obniz.connected_network.local_ip` | string |   | Local IP if exist  | | `ws.obniz.connected_network.global_ip` | string |   | Global IP if exist  | | `ws.obniz.connected_network.wifi.ssid` | string | required | Current connected Accespoint SSID  | | `ws.obniz.connected_network.wifi.mac_address` | string | required | Current connected Accespoint MacAddress  | | `ws.obniz.connected_network.wifi.rssi` | number | required | Current RSSI for connected Accesspoint. RSSI is mesured only on connection timing  | | `ws.obniz.connected_network.wifimesh.meshid` | string |   | MESH ID of Currently joined MESH network  | | `ws.obniz.connected_network.wifimesh.parent_obniz_id` | string | required | Id of parent node  | | `ws.obniz.connected_network.wifimesh.root_obniz_id` | string | required | Id of parent node  | | `ws.obniz.connected_network.wifimesh.layer` | number | required | Depth of MESH network. layer=1 is root node of a network.  | | `ws.obniz.connected_network.wifimesh.rssi` | number | required | Current RSSI for connected Accesspoint.  | ``` //Response Example [ { "ws": { "obniz": { "hw": "obnizb1", "firmware": "2.0.0", "metadata": "{\"description\":\"At My Office\"}", "connected_network": { "online_at": 1637685862, "net": "wirelesslan", "local_ip": "192.168.0.100", "global_ip": "201.200.199.198", "wifi": { "ssid": "obniz-wifi", "mac_address": "0123456789AB", "rssi": "-40" }, "wifimesh": { "meshid": "012345678901", "parent_obniz_id": "0000-0000", "root_obniz_id": "0000-0000", "layer": 1, "rssi": "-40" } } } } } ] ``` ## response: redirect If the server required you to connect other endpoint to communicate with your obniz. This json will be sent. | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ws.redirect` | string | required | The url you should redirect to.  | ``` //Response Example [ { "ws": { "redirect": "wss://ws1.obniz.io" } } ] ``` --- ## System URL: https://obniz.com/reference/websocket/system # system ## request: wait | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `system.wait` | integer | required | wait time (ms)  | ``` // Json Example [ { "system": { "wait": 500 } } ] ``` ## request: reset | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `system.reset` | boolean | requiredconst `true` |   | ``` // Json Example [ { "system": { "reset": true } } ] ``` ## request: reboot | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `system.reboot` | boolean | requiredconst `true` |   | ``` // Json Example [ { "system": { "reboot": true } } ] ``` ## request: selfCheck circuit IO check | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `system.self_check` | boolean | requiredconst `true` |   | ``` // Json Example [ { "system": { "self_check": true } } ] ``` ## request: keepWorkingAtOffline reset obniz Board when obniz Board gone to offline. | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `system.keep_working_at_offline` | boolean | required |   | ``` // Json Example [ { "system": { "keep_working_at_offline": true } } ] ``` ## request: ping | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `system.ping.key` | [dataArray](#dataarray) | required |   | ``` // Json Example [ { "system": { "ping": { "key": [16, 34, 242] } } } ] ``` ## request: sleepSeconds | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `system.sleep_seconds` | integer | required | sleep time (seconds)  | ``` // Json Example [ { "system": { "sleep_seconds": 500 } } ] ``` ## request: sleepMinute | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `system.sleep_minute` | integer | required | sleep time (minute)  | ``` // Json Example [ { "system": { "sleep_minute": 500 } } ] ``` ## request: sleepIoTrigger | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `system.sleep_io_trigger` | boolean | required | true:Wake up on rising edge false:Wake up on falling edge  | ``` // Json Example [ { "system": { "sleep_io_trigger": true } } ] ``` ## request: set_clock | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `system.clock` | integer | required | Set the clock (Unix timestamp in milliseconds). This will be set to device immediately and used as device timestamp  | ``` // Json Example [ { "system": { "clock": 1592171234567 } } ] ``` ## request: queue_mode | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `system.queue_mode.interval` | integer |   | Set interval of transmission queue of device. Unit is milliseconds. Default is 0ms  | | `system.queue_mode.timestamp` | string | enum `"none"``"unix_seconds"``"unix_milliseconds"` | Set timestamp mode. In timestamp mode, device add timestamp to every commands. Default is none. sec use 4 bytes and millisec use 8 bytes  | ``` // Json Example [ { "system": { "queue_mode": { "interval": 1000, "timestamp": "none" } } } ] ``` ## response: pong | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `system.pong.key` | [dataArray](#dataarray) | required |   | ``` //Response Example [ { "system": { "pong": { "key": [16, 34, 242] } } } ] ``` ## response: timestamp | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `system.timestamp` | number | required | The timestamp in milliseconds since epoch (1970-01-01T00:00:00Z).  | ``` //Response Example [ { "system": { "timestamp": 1592171234567 } } ] ``` # type defines ## dataArray | type | conditions | examples | description | |:----|:----|:----|:----| | array | items0 ≤ value ≤ 255 | `[16, 34, 242]``[100, 255, 21, 0, 21]` | Binary data array.  | --- ## IO URL: https://obniz.com/reference/websocket/io # io General purpose IO available on each io (io0 to io11). ## request: input Related item - [/response/io/get](#-response-io-get) | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ioX` | string | requiredconst `"get"` |   | ``` // Json Example [ { "io0": "get" } ] ``` ## request: input_detail Related item - [/response/io/get](#-response-io-get) | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ioX.direction` | string | requiredconst `"input"` |   | | `ioX.stream` | boolean |   | enable stream callback when value change  | ``` // Json Example [ { "io0": { "direction": "input", "stream": false } } ] ``` ## request: output | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ioX` | boolean | required |   | ``` // Json Example [ { "io0": true } ] ``` ## request: output_detail | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ioX.direction` | string | requiredconst `"output"` |   | | `ioX.value` | boolean | required |   | ``` // Json Example [ { "io0": { "direction": "output", "value": true } } ] ``` ## request: output_type | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ioX.output_type` | string | requiredenum `"push-pull5v"``"push-pull3v"``"open-drain"` | drive type  | ``` // Json Example [ { "io0": { "output_type": "push-pull5v" } } ] ``` ## request: pull_type | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ioX.pull_type` | string | requiredenum `"pull-up5v"``"pull-up3v"``"pull-down"``"float"` |   | ``` // Json Example [ { "io0": { "pull_type": "pull-up5v" } } ] ``` ## request: deinit | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ioX` | null | required |   | ``` // Json Example [ { "io0": null } ] ``` ## response: get | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ioX` | boolean | required |   | ``` //Response Example [ { "io0": true } ] ``` ## response: warning | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ioX.warning.message` | string | required | io warning  | ``` //Response Example [ { "io0": { "warning": { "message": "Heavy output" } } } ] ``` ## response: error | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ioX.error.message` | string | required | io warning  | ``` //Response Example [ { "io0": { "error": { "message": "Heavy output" } } } ] ``` --- ## IO Animation URL: https://obniz.com/reference/websocket/ioAnimation # ioAnimation io animation is hardware acceleration for serial sequence change of io. now 'loop' animation is available. it loop io changes regarding json array. ## request: init | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `io.animation.name` | string | required1 ≤ length ≤ 254 | Animation name to use pause/resume  | | `io.animation.repeat` | integer | default `undefined`1 ≤ length ≤ 4294967295 | The limitation number of transitions of states  | | `io.animation.status` | string | requiredenum `"loop"``"registrate"` |   | | `io.animation.states[].duration` | integer | required0 ≤ value ≤ 60000 | State duration time(ms)  | | `io.animation.states[].state` | object,array |   | io/pwm commands.  | ``` // Json Example [ { "io": { "animation": { "name": "animation-1", "status": "loop", "states": [ { "duration": 500, "state": { "io0": true } }, { "duration": 500, "state": { "io0": false } } ] } } } ] ``` ## request: changeState | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `io.animation.name` | string | required1 ≤ length ≤ 254 |   | | `io.animation.status` | string | requiredenum `"pause"``"resume"` |   | ``` // Json Example [ { "io": { "animation": { "name": "animation-1", "status": "pause" } } } ] ``` ## response: notify | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `io.animation.name` | string | required1 ≤ length ≤ 254 | animation name which is finished  | | `io.animation.status` | string | requiredconst `"finish"` | status of an registrated animation  | ``` //Response Example [ { "io": { "animation": { "name": "animation-1", "status": "finish" } } } ] ``` --- ## AD URL: https://obniz.com/reference/websocket/ad # ad available ad0~ad11 ## request: get Related item - [/response/ad/get](#-response-ad-get) | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `adX.stream` | boolean | required | true to continuous notifying on voltage change.  | ``` // Json Example [ { "ad0": { "stream": false } } ] ``` ## request: deinit | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `adX` | null | required |   | ``` // Json Example [ { "ad0": null } ] ``` ## response: get current value (volt) | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `adX` | number | required0 ≤ value ≤ 5 | current value (volt)  | ``` //Response Example [ { "ad0": 3.3 } ] ``` --- ## PWM URL: https://obniz.com/reference/websocket/pwm # pwm available 0 to 5 ## request: init | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `pwmX.io` | [pinSetting](#pinsetting) | required |   | ``` // Json Example [ { "pwm0": { "io": 0 } } ] ``` ## request: freq | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `pwmX.freq` | integer | required1 ≤ value ≤ 80000000 | frequency (Hz)  | ``` // Json Example [ { "pwm0": { "freq": 40000000 } } ] ``` ## request: pulse | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `pwmX.pulse` | number | required0 ≤ value | pulse width (ms)  | ``` // Json Example [ { "pwm0": { "pulse": 500 } } ] ``` ## request: modulate | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `pwmX.modulate.type` | string | requiredconst `"am"` |   | | `pwmX.modulate.symbol_length` | number | required0.05 ≤ value ≤ 1000 | symbol width (ms)  | | `pwmX.modulate.data` | [bitArray](#bitarray) | required |   | ``` // Json Example [ { "pwm0": { "modulate": { "type": "am", "symbol_length": 500, "data": [0, 1, 1, 0, 0, 1, 1, 0] } } } ] ``` ## request: deinit | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `pwmX` | null | required |   | ``` // Json Example [ { "pwm0": null } ] ``` # type defines ## bitArray | type | conditions | examples | description | |:----|:----|:----|:----| | array | items0 ≤ value ≤ 1 | `[0, 1, 1, 0, 0, 1, 1, 0]``[0, 0, 1, 0, 0, 0, 0, 0]` | Binary data array represented in 0 1.  | ## pinSetting | type | conditions | examples | description | |:----|:----|:----|:----| | integer | 0 ≤ value ≤ 40 | `0``1``2``3``4``5``6` |   | --- ## UART URL: https://obniz.com/reference/websocket/uart # uart ## request: init available 0 to 1 | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `uartX.rx` | [pinSetting](#pinsetting) | required |   | | `uartX.tx` | [pinSetting](#pinsetting) | required |   | | `uartX.baud` | integer | default `115200`1 ≤ value ≤ 5000000 | baud rate (bps)  | | `uartX.stop` | number | default `1`enum `1``1.5``2` | stop bit width  | | `uartX.bits` | integer | default `8`enum `5``6``7``8` |   | | `uartX.parity` | string | default `off`enum `"off"``"odd"``"even"` |   | | `uartX.flowcontrol` | string | default `off`enum `"off"``"rts"``"cts"``"rts-cts"` |   | | `uartX.rts` | [pinSetting](#pinsetting) |   |   | | `uartX.cts` | [pinSetting](#pinsetting) |   |   | ``` // Json Example [ { "uart0": { "rx": 0, "tx": 1, "baud": 115200, "stop": 1, "bits": 8, "parity": "off", "flowcontrol": "off", "rts": 2, "cts": 3 } } ] ``` ## request: send | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `uartX.data` | [dataArray](#dataarray) | required |   | ``` // Json Example [ { "uart0": { "data": [16, 34, 242] } } ] ``` ## request: deinit | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `uartX` | null | required |   | ``` // Json Example [ { "uart0": null } ] ``` ## response: receive | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `uartX.data` | [dataArray](#dataarray) |   |   | ``` //Response Example [ { "uart0": { "data": [16, 34, 242] } } ] ``` # type defines ## dataArray | type | conditions | examples | description | |:----|:----|:----|:----| | array | items0 ≤ value ≤ 255 | `[16, 34, 242]``[100, 255, 21, 0, 21]` | Binary data array.  | ## pinSetting | type | conditions | examples | description | |:----|:----|:----|:----| | integer | 0 ≤ value ≤ 40 | `0``1``2``3``4``5``6` |   | --- ## SPI URL: https://obniz.com/reference/websocket/spi # spi available spi0, spi1 ## request: init_master clk, miso, mosi are optional, but at least one are required | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `spiX.mode` | string | requiredconst `"master"` |   | | `spiX.clk` | [pinSetting](#pinsetting) |   |   | | `spiX.mosi` | [pinSetting](#pinsetting) |   |   | | `spiX.miso` | [pinSetting](#pinsetting) |   |   | | `spiX.cs` | [pinSetting](#pinsetting) |   |   | | `spiX.clock` | integer | required1 ≤ value ≤ 26000000 |   | ``` // Json Example [ { "spi0": { "mode": "master", "clk": 0, "mosi": 1, "miso": 2, "cs": 3, "clock": 115200 } } ] ``` ## request: deinit | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `spiX` | null | required |   | ``` // Json Example [ { "spi0": null } ] ``` ## request: write Related item - [/response/spi/read](#-response-spi-read) | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `spiX.data` | [dataArray1024](#dataarray1024) | required |   | | `spiX.read` | boolean | required | If false, write without receive  | ``` // Json Example [ { "spi0": { "data": [100, 255, 21, 0, 21], "read": true } } ] ``` ## response: read | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `spiX.data` | [dataArray](#dataarray) | required |   | ``` //Response Example [ { "spi0": { "data": [16, 34, 242] } } ] ``` # type defines ## dataArray | type | conditions | examples | description | |:----|:----|:----|:----| | array | items0 ≤ value ≤ 255 | `[16, 34, 242]``[100, 255, 21, 0, 21]` | Binary data array.  | ## dataArray1024 | type | conditions | examples | description | |:----|:----|:----|:----| | array | length ≤ 1024items0 ≤ value ≤ 255 | `[100, 255, 21, 0, 21]` |   | ## pinSetting | type | conditions | examples | description | |:----|:----|:----|:----| | integer | 0 ≤ value ≤ 40 | `0``1``2``3``4``5``6` |   | --- ## I2C URL: https://obniz.com/reference/websocket/i2c # i2c available only i2c0 ## request: init_master internal pull-up is available. But, We recommend use external pull-up resistor. | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `i2cX.mode` | string | requiredconst `"master"` |   | | `i2cX.sda` | [pinSetting](#pinsetting) | required |   | | `i2cX.scl` | [pinSetting](#pinsetting) | required |   | | `i2cX.clock` | integer | required1 ≤ value ≤ 1000000 | frequency (Hz)  | ``` // Json Example [ { "i2c0": { "mode": "master", "sda": 0, "scl": 1, "clock": 500000 } } ] ``` ## request: init_slave Related item - [/response/i2c/slave](#-response-i2c-slave) | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `i2cX.mode` | string | requiredenum `"master"``"slave"` |   | | `i2cX.sda` | [pinSetting](#pinsetting) | required |   | | `i2cX.scl` | [pinSetting](#pinsetting) | required |   | | `i2cX.slave_address` | integer | required0 ≤ value ≤ 1023 |   | | `i2cX.slave_address_length` | integer | default `7`const `7` |   | | `i2cX.address` | integer | 0 ≤ value ≤ 1023 |   | | `i2cX.address_bits` | integer | default `7`const `7` |   | | `i2cX.data` | [dataArray](#dataarray) |   |   | | `i2cX.read` | integer | 0 ≤ value |   | ``` // Json Example [ { "i2c0": { "mode": "master", "sda": 0, "scl": 1, "slave_address": 511, "slave_address_length": 7, "address": 511, "address_bits": 7, "data": [16, 34, 242], "read": 500 } } ] ``` ## request: write if address over 0b01111111; then address treated as 10bit address automatically. or specify address_bits: 10 to force 10bit address mode. | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `i2cX.address` | integer | required0 ≤ value ≤ 1023 |   | | `i2cX.address_bits` | integer | default `7`const `7` |   | | `i2cX.data` | [dataArray1024](#dataarray1024) | required |   | ``` // Json Example [ { "i2c0": { "address": 511, "address_bits": 7, "data": [100, 255, 21, 0, 21] } } ] ``` ## request: read if address over 0b01111111; then address treated as 10bit address automatically. or specify address_bits: 10 to force 10bit address mode. Related item - [/response/i2c/master](#-response-i2c-master) | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `i2cX.address` | integer | required0 ≤ value ≤ 1023 |   | | `i2cX.address_bits` | integer | default `7`const `7` |   | | `i2cX.read` | integer | required0 ≤ value ≤ 1024 |   | ``` // Json Example [ { "i2c0": { "address": 511, "address_bits": 7, "read": 512 } } ] ``` ## request: deinit | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `i2cX` | null | required |   | ``` // Json Example [ { "i2c0": null } ] ``` ## response: master | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `i2cX.mode` | string | requiredconst `"master"` |   | | `i2cX.address` | integer | required0 ≤ value ≤ 1023 |   | | `i2cX.data` | [dataArray](#dataarray) | required |   | ``` //Response Example [ { "i2c0": { "mode": "master", "address": 511, "data": [16, 34, 242] } } ] ``` ## response: slave | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `i2cX.mode` | string | requiredconst `"slave"` |   | | `i2cX.address` | integer | required0 ≤ value ≤ 1023 |   | | `i2cX.is_fragmented` | boolean | required |   | | `i2cX.data` | [dataArray](#dataarray) | required |   | ``` //Response Example [ { "i2c0": { "mode": "slave", "address": 511, "is_fragmented": true, "data": [16, 34, 242] } } ] ``` ## response: error | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `i2cX.error.message` | string | required | io warning  | ``` //Response Example [ { "i2c0": { "error": { "message": "Heavy output" } } } ] ``` ## response: warning | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `i2cX.warning.message` | string | required | io warning  | ``` //Response Example [ { "i2c0": { "warning": { "message": "Heavy output" } } } ] ``` # type defines ## dataArray | type | conditions | examples | description | |:----|:----|:----|:----| | array | items0 ≤ value ≤ 255 | `[16, 34, 242]``[100, 255, 21, 0, 21]` | Binary data array.  | ## dataArray1024 | type | conditions | examples | description | |:----|:----|:----|:----| | array | length ≤ 1024items0 ≤ value ≤ 255 | `[100, 255, 21, 0, 21]` |   | ## pinSetting | type | conditions | examples | description | |:----|:----|:----|:----| | integer | 0 ≤ value ≤ 40 | `0``1``2``3``4``5``6` |   | --- ## Logic Analyzer URL: https://obniz.com/reference/websocket/logicAnalyzer # logicAnalyzer Monitor io logic level changes by sampling io. ## request: init | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `logic_analyzer.io[]` | [pinSetting](#pinsetting) | required |   | | `logic_analyzer.interval` | number | required0 |   | | `logic_analyzer.duration` | integer | required0 |   | | `logic_analyzer.trigger.value` | boolean | required | start value  | | `logic_analyzer.trigger.samples` | integer | required0 ≤ value | how that values consists  | With below sample code, you will receive only data which start with 'false, false, false' 3bit. ``` // Json Example [ { "logic_analyzer": { "io": [ 0], "interval": 500, "duration": 500, "trigger": { "value": false, "samples": 3 } } } ] ``` ## request: deinit | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `logic_analyzer` | null | required |   | ``` // Json Example [ { "logic_analyzer": null } ] ``` ## response: data | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `logic_analyzer.data` | [bitArray](#bitarray) | required |   | ``` //Response Example [ { "logic_analyzer": { "data": [0, 1, 1, 0, 0, 1, 1, 0] } } ] ``` # type defines ## bitArray | type | conditions | examples | description | |:----|:----|:----|:----| | array | items0 ≤ value ≤ 1 | `[0, 1, 1, 0, 0, 1, 1, 0]``[0, 0, 1, 0, 0, 0, 0, 0]` | Binary data array represented in 0 1.  | ## pinSetting | type | conditions | examples | description | |:----|:----|:----|:----| | integer | 0 ≤ value ≤ 40 | `0``1``2``3``4``5``6` |   | --- ## Measurement URL: https://obniz.com/reference/websocket/measure # measure ## request: echo It measures pulse response. Related item - [/response/measure/echo](#-response-measure-echo) | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `measure.echo.io_pulse` | [pinSetting](#pinsetting) | required |   | | `measure.echo.io_echo` | [pinSetting](#pinsetting) | required |   | | `measure.echo.pulse` | string | default `positive`enum `"positive"``"negative"` |   | | `measure.echo.pulse_width` | number | required0.001 ≤ value ≤ 1000 |   | | `measure.echo.measure_edges` | integer | 1 ≤ value ≤ 4 |   | | `measure.echo.timeout` | number | default `1000`0.001 ≤ value ≤ 1000 |   | ``` // Json Example [ { "measure": { "echo": { "io_pulse": 0, "io_echo": 1, "pulse": "positive", "pulse_width": 500, "measure_edges": 2, "timeout": 1000 } } } ] ``` ## response: echo | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `measure.echo[].edge` | boolean | required | rising = true  | | `measure.echo[].timing` | number | required | milliseconds from end of pulse  | ``` //Response Example [ { "measure": { "echo": [ { "edge": true, "timing": 500 } ] } } ] ``` # type defines ## pinSetting | type | conditions | examples | description | |:----|:----|:----|:----| | integer | 0 ≤ value ≤ 40 | `0``1``2``3``4``5``6` |   | --- ## Display URL: https://obniz.com/reference/websocket/display # display ## request: text | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `display.text` | string | required |   | ``` // Json Example [ { "display": { "text": "Hello, obniz!" } } ] ``` ## request: clear | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `display.clear` | boolean | requiredconst `true` |   | ``` // Json Example [ { "display": { "clear": true } } ] ``` ## request: qr | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `display.qr.text` | string | required |   | | `display.qr.correction` | string | default `M`enum `"L"``"M"``"Q"``"H"` |   | ``` // Json Example [ { "display": { "qr": { "text": "Hello, obniz!", "correction": "M" } } } ] ``` ## request: raw Hardware Dependepend raw level rendering. Default color_depth = 1. Which means 1 bit represents 1 dot. 1 byte is part of one line. Order is same like. Below is obniz baord series example {1byte} {2byte} {3byte}...{16byte} {17byte} {18byte} {19byte}... ..... .....................{1024byte} Number of line and column depends on device. If a device has a color display. You can choose other color_depth mode color_depth = 4 (4 bit color mode). [{4bit for first(left) pixel}, {4bit for next pixel}] 4 bit represents R_G_B_Brightness color_depth = 16 means 16bit color mode. So 2 byte for 1 pixel. It is known as RGB565. [{8-15bit for one pixel}][{0-7bit for one pixel}] | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `display.raw` | [imageDataArray](#imagedataarray) | required |   | | `display.color_depth` | integer | default `1`enum `1``4``16` |   | ``` // Json Example [ { "display": { "raw": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 240, 56, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 224, 120, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 255, 192, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 127, 255, 129, 248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 255, 255, 3, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 255, 254, 7, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 252, 15, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 248, 31, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 255, 240, 63, 255, 224, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 255, 224, 127, 255, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 127, 255, 192, 255, 255, 248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 129, 255, 255, 252, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 255, 255, 3, 255, 255, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 255, 254, 7, 255, 255, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 255, 252, 15, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 248, 31, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 240, 63, 255, 255, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 224, 127, 193, 255, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 15, 252, 64, 255, 128, 255, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 15, 240, 1, 255, 0, 127, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 224, 3, 254, 0, 127, 254, 14, 0, 0, 0, 0, 0, 0, 0, 0, 31, 224, 7, 254, 0, 63, 252, 30, 0, 0, 0, 0, 0, 0, 0, 0, 31, 224, 7, 254, 0, 63, 248, 60, 0, 0, 0, 0, 0, 0, 0, 0, 31, 192, 7, 254, 0, 63, 240, 120, 0, 0, 0, 0, 0, 0, 0, 0, 31, 192, 7, 254, 0, 127, 224, 240, 0, 0, 0, 0, 0, 0, 0, 0, 31, 224, 7, 252, 0, 127, 193, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 224, 15, 248, 0, 255, 131, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 240, 31, 240, 39, 255, 7, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 252, 63, 224, 127, 254, 15, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 255, 192, 255, 252, 31, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 255, 129, 255, 248, 63, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 255, 3, 255, 240, 127, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 254, 7, 255, 224, 255, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 252, 15, 255, 193, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 248, 31, 255, 131, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 240, 63, 255, 7, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 224, 127, 254, 15, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 192, 255, 252, 31, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 129, 255, 0, 63, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 3, 254, 0, 127, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 254, 7, 252, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 252, 15, 252, 0, 255, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 248, 31, 252, 0, 255, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 63, 252, 0, 255, 252, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 224, 127, 252, 0, 255, 252, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 255, 252, 0, 255, 248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 255, 254, 1, 255, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 255, 255, 3, 255, 224, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 255, 255, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 255, 255, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 255, 255, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 255, 255, 255, 252, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 255, 255, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 224, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "color_depth": 1 } } ] ``` ## request: pin_assign | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `display.pin_assign.X.module_name` | string |   |   | | `display.pin_assign.X.pin_name` | string |   |   | ``` // Json Example [ { "display": { "pin_assign": { "0": { "module_name": "io", "pin_name": "output" } } } } ] ``` # type defines ## imageDataArray | type | conditions | examples | description | |:----|:----|:----|:----| | array | 0 ≤ lengthitems0 ≤ value | `[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 240, 56, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 224, 120, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 255, 192, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 127, 255, 129, 248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 255, 255, 3, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 255, 254, 7, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 252, 15, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 248, 31, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 255, 240, 63, 255, 224, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 255, 224, 127, 255, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 127, 255, 192, 255, 255, 248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 129, 255, 255, 252, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 255, 255, 3, 255, 255, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 255, 254, 7, 255, 255, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 255, 252, 15, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 248, 31, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 240, 63, 255, 255, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 224, 127, 193, 255, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 15, 252, 64, 255, 128, 255, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 15, 240, 1, 255, 0, 127, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 224, 3, 254, 0, 127, 254, 14, 0, 0, 0, 0, 0, 0, 0, 0, 31, 224, 7, 254, 0, 63, 252, 30, 0, 0, 0, 0, 0, 0, 0, 0, 31, 224, 7, 254, 0, 63, 248, 60, 0, 0, 0, 0, 0, 0, 0, 0, 31, 192, 7, 254, 0, 63, 240, 120, 0, 0, 0, 0, 0, 0, 0, 0, 31, 192, 7, 254, 0, 127, 224, 240, 0, 0, 0, 0, 0, 0, 0, 0, 31, 224, 7, 252, 0, 127, 193, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 224, 15, 248, 0, 255, 131, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 240, 31, 240, 39, 255, 7, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 252, 63, 224, 127, 254, 15, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 255, 192, 255, 252, 31, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 255, 129, 255, 248, 63, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 255, 3, 255, 240, 127, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 254, 7, 255, 224, 255, 224, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 252, 15, 255, 193, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 248, 31, 255, 131, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 240, 63, 255, 7, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 224, 127, 254, 15, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 192, 255, 252, 31, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 129, 255, 0, 63, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 3, 254, 0, 127, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 254, 7, 252, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 252, 15, 252, 0, 255, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 248, 31, 252, 0, 255, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 63, 252, 0, 255, 252, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 224, 127, 252, 0, 255, 252, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 255, 252, 0, 255, 248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 255, 254, 1, 255, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 255, 255, 3, 255, 224, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 255, 255, 255, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 255, 255, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 255, 255, 255, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 255, 255, 255, 252, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 255, 255, 240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 255, 255, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 224, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]` | Image data bit array.  | --- ## Switch URL: https://obniz.com/reference/websocket/switch # switch the switch embed on obniz Board itself. If it's state is changed, notification will be fired. ## request: get Related item - [/response/switch/change](#-response-switch-change) | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `switch` | string | requiredconst `"get"` |   | ``` // Json Example [ { "switch": "get" } ] ``` ## response: change | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `switch.state` | string | requiredenum `"none"``"push"``"left"``"right"` |   | | `switch.action` | string | const `"get"` | this is optional and added when user request  | ``` //Response Example [ { "switch": { "state": "none", "action": "get" } } ] ``` --- ## Tcp URL: https://obniz.com/reference/websocket/tcp # tcp tcp command ## request: connect | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `tcpX.connect.port` | integer | required0 ≤ value ≤ 65535 | TCP port  | | `tcpX.connect.domain` | string | requiredlength ≤ 30 | Server Domain  | ``` // Json Example [ { "tcp0": { "connect": { "port": 32767, "domain": "obniz.io" } } } ] ``` ## request: disconnect | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `tcpX.disconnect` | boolean | required |   | ``` // Json Example [ { "tcp0": { "disconnect": true } } ] ``` ## request: write | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `tcpX.write.data` | [dataArray](#dataarray) | required | TCP data  | ``` // Json Example [ { "tcp0": { "write": { "data": [16, 34, 242] } } } ] ``` ## response: read | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `tcpX.read.data` | [dataArray](#dataarray) | required |   | ``` //Response Example [ { "tcp0": { "read": { "data": [16, 34, 242] } } } ] ``` ## response: connect | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `tcpX.connect.message` | string | requiredenum `"ok"``"Port Used"``"Port Area Error"``"Lookup Error"``"Error"` |   | | `tcpX.connect.code` | number | required |   | ``` //Response Example [ { "tcp0": { "connect": { "message": "ok", "code": 500 } } } ] ``` ## response: connection | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `tcpX.connection.connected` | boolean | required |   | ``` //Response Example [ { "tcp0": { "connection": { "connected": true } } } ] ``` # type defines ## dataArray | type | conditions | examples | description | |:----|:----|:----|:----| | array | items0 ≤ value ≤ 255 | `[16, 34, 242]``[100, 255, 21, 0, 21]` | Binary data array.  | --- ## Wi-Fi URL: https://obniz.com/reference/websocket/wifi # wifi wifi command ## request: scan | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `wifi.scan` | boolean | requiredconst `true` |   | ``` // Json Example [ { "wifi": { "scan": true } } ] ``` ## response: scan | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `wifi.scan[].ssid` | string | required |   | | `wifi.scan[].macAddress` | string | required |   | | `wifi.scan[].rssi` | integer | required |   | ``` //Response Example [ { "wifi": { "scan": [ { "ssid": "obniz-wifi", "macAddress": "001122aabbcc", "rssi": 500 } ] } } ] ``` --- ## BLE HCI URL: https://obniz.com/reference/websocket/ble_hci # ble.hci ## request: init | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ble.hci.initialize` | boolean | required |   | ``` // Json Example [ { "ble": { "hci": { "initialize": true } } } ] ``` ## request: deinit | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ble.hci` | null | required |   | ``` // Json Example [ { "ble": { "hci": null } } ] ``` ## request: write | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ble.hci.write` | [dataArray](#dataarray) | required |   | ``` // Json Example [ { "ble": { "hci": { "write": [16, 34, 242] } } } ] ``` ## request: advertisement_filter | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ble.hci.advertisement_filter[].range.index` | integer | required0 ≤ value ≤ 255 |   | | `ble.hci.advertisement_filter[].range.length` | integer | required0 ≤ value ≤ 255 |   | | `ble.hci.advertisement_filter[].value` | [dataArray](#dataarray) |   |   | ``` // Json Example [ { "ble": { "hci": { "advertisement_filter": [ { "range": { "index": 127, "length": 127 }, "value": [16, 34, 242] } ] } } } ] ``` ## response: read | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `ble.hci.read.data` | [dataArray](#dataarray) | required | HCI data  | ``` //Response Example [ { "ble": { "hci": { "read": { "data": [16, 34, 242] } } } } ] ``` # type defines ## dataArray | type | conditions | examples | description | |:----|:----|:----|:----| | array | items0 ≤ value ≤ 255 | `[16, 34, 242]``[100, 255, 21, 0, 21]` | Binary data array.  | --- ## Message URL: https://obniz.com/reference/websocket/message # message send/receive with other obniz Board or WebHook ## request: send Related item - [/response/message/receive](#-response-message-receive) | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `message.data` | anyType | required | All type of data is pass.  | | `message.to[]` | [obnizId](#obnizid) | required |   | ``` // Json Example [ { "message": { "data": "button pressed", "to": [ "1234-5678" ] } } ] ``` ## response: receive Related item - [/request/message/send](#-request-message-send) | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `message.data` | anyType | required | All type of data is pass.  | | `message.from` | string,null |   | From obniz id. Null is used when WebHook message.  | ``` //Response Example [ { "message": { "data": "button pressed", "from": "1234-5678" } } ] ``` # type defines ## obnizId | type | conditions | examples | description | |:----|:----|:----|:----| | string,integer | 0 ≤ value ≤ 99999999 | `"1234-5678"``12345678` | Obniz id. It can contain '-' or not.  | --- ## Plugin URL: https://obniz.com/reference/websocket/plugin # plugin plugin command ## request: send | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `plugin.send` | [dataArray](#dataarray) | required |   | ``` // Json Example [ { "plugin": { "send": [16, 34, 242] } } ] ``` ## request: exec_lua | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `plugin.exec_lua` | string | required | Lua script to be run on target device  | ``` // Json Example [ { "plugin": { "exec_lua": "duration = 3" } } ] ``` ## request: reload_lua | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `plugin.reload` | boolean | required | Indicate load Lua from storage. This is reloading. It will lose state.  | ``` // Json Example [ { "plugin": { "reload": true } } ] ``` ## request: call_request | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `plugin.call_request.id` | integer | required0 ≤ value ≤ 4294967295 | transaction id which response will carry back  | | `plugin.call_request.lua` | string | required | Lua script to be run on target device  | ``` // Json Example [ { "plugin": { "call_request": { "id": 2147483647, "lua": "return 'hello'" } } } ] ``` ## request: cloud_transaction_response | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `plugin.cloud_transaction_response.id` | integer | required0 ≤ value ≤ 4294967295 | transaction id which Lua is waiting on  | | `plugin.cloud_transaction_response.success` | boolean | required | whether the transaction succeeded  | | `plugin.cloud_transaction_response.result` | string |   | result string passed back to Lua  | ``` // Json Example [ { "plugin": { "cloud_transaction_response": { "id": 2147483647, "success": true, "result": "" } } } ] ``` ## response: receive | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `plugin.receive` | [dataArray](#dataarray) | required |   | ``` //Response Example [ { "plugin": { "receive": [16, 34, 242] } } ] ``` ## response: frame | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `plugin.frame.start.id` | number |   | Frame Identifer number  | | `plugin.frame.start.length` | number | required | Frame Total length  | | `plugin.frame.end.length` | number |   |   | ``` //Response Example [ { "plugin": { "frame": { "start": { "id": 100, "length": 10000 }, "end": { "length": 500 } } } } ] ``` ## response: error | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `plugin.error.message` | string | required |   | ``` //Response Example [ { "plugin": { "error": { "message": "[string \"e\"]:1: syntax error near 'FAILED'" } } } ] ``` ## response: call_response | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `plugin.call_response.id` | integer | required | transaction id of the matching callWait request  | | `plugin.call_response.status` | integer | required | 0 when Lua finished successfully, 1 on error  | | `plugin.call_response.result` | string |   | value returned by the Lua script (or error message)  | ``` //Response Example [ { "plugin": { "call_response": { "id": 500, "status": 0, "result": "hello from lua" } } } ] ``` ## response: cloud_transaction_request | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `plugin.cloud_transaction_request.id` | integer | required | transaction id that the response must carry back  | | `plugin.cloud_transaction_request.data` | [dataArray](#dataarray) | required |   | ``` //Response Example [ { "plugin": { "cloud_transaction_request": { "id": 500, "data": [16, 34, 242] } } } ] ``` # type defines ## dataArray | type | conditions | examples | description | |:----|:----|:----|:----| | array | items0 ≤ value ≤ 255 | `[16, 34, 242]``[100, 255, 21, 0, 21]` | Binary data array.  | --- ## Debug URL: https://obniz.com/reference/websocket/debug # debug ## response: warning | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `debug.warning.message` | string |   | readable message  | ``` //Response Example [ { "debug": { "warning": { "message": "unknown command" } } } ] ``` ## response: error | path | type | conditions | description | |:---- |:---- |:---- |:---- | | `debug.error.message` | string |   | readable message  | ``` //Response Example [ { "debug": { "error": { "message": "voltage down" } } } ] ``` --- ## obniz Board/obniz Board 1Y URL: https://obniz.com/reference/board-1y About obniz Board. " obniz Board " is a official device designed as specialized hardware for obniz Cloud. #### obniz Board ![](images/obniz_board.jpg) 12 Motor Driver inside. Can drive up to 1A for all 12 IO. Control IO and components via the internet. #### obniz Board 1Y ![](images/obniz_board_1y.jpg) 1Y also has motor drivers. Major unique point is sleep. It work over 1 year with batteries (depends on usage). --- ## Quick start URL: https://obniz.com/reference/board-1y/quick-start This quick start shows how to start obniz Board. Please prepare obniz Board, Smartphone(or PC) and Portable Battery Pack. Function of each part Step1. Start obniz Board Power supply is required from mobile battery or PC. Turn on the obniz Board by plugging in a USB. To shutdown, just unplug the cable. Attention When the startup screen is displayed as a below, obniz Board is an old version of OS. Please refer Quickstart for obniz Board(obnizOS 2.1.1 or earlier), because the display is different. Step2. Connect Wi-Fi 2-1 Select how to set Wi-Fi When Board starts up, Wi-Fi setting method is displayed. SIMPLE METHOD:Set Wi-Fi connection on obniz BoardADVANCED METHOD:Set Wi-Fi connection using a smartphone or PC browser. See below: Wi-Fi(document) Here, proceed with Wi-Fi settings on the Board.Please select [SIMPLE METHOD]. The cursor is moved when turn the dial switch.Click the dial switch to selest. 2-2 Select SSID obniz Board will show a Wi-Fi SSID list on its OLED. Choose one by moving the switch towards left or right, and confirm selection by pressing the switch. 2-3 Enter password Type the password one by one by using the dial switch. When you mistyped, choose [BACK] to delete one character. When you finish, choose [END] to connect. QR code will appear on its OLED when successfully connected to Wi-Fi and obniz Cloud. The 8-digit number displayed is the obnizID. If an error is displayed or startup is not possible → See Troubleshooting. Step3. Run the program Please read the QR code displayed on the obniz Board with your smartphone. The program editor will open. Using PC Please open the Program editor. When prompted for obnizID, please enter your obnizID (the 8-digit number displayed on your obniz Board). Tap (click) [Run] at the top right of the screen to open the run screen and run the program. In the initial state, character input and LED ON / OFF buttons are displayed and can run programs. The program ends by closing the execution screen. ## Registering devices to the cloud You can register devices in the cloud by going to [Register device](/reference/cloud/device-management/registration). Registering to the cloud allows you to increase the level of security and manage your devices at a glance --- ## Run a program URL: https://obniz.com/reference/board-1y/quick-start/quick-start This Lessons show how to start using obniz Board from HTML/JavaScript. How to start obniz Board?: Check the [Quickstart](/quickstart) ## Remote Control obniz Board from the SDK through obniz Cloud An onlined obniz can be controlled from the SDK we provide for some programming languages. obniz.js is javascript one. It's opensource on [Github](https://github.com/obniz/obniz). It will be installed by script tag in HTML or npm in nodejs. It's documet can be seen this website [/sdk/README](/sdk/README)。 IO and Peripheral usages. This lessons explain integration hardwares with HTML UI on [Online HTML Editor](/reference/cloud/online-editor/html-editor). ## Let's try! Let's use obniz from the Web. Let's try below to check if your obniz Board is connected to the internet. ``` Print words on obniz Print on obniz Swtich undefined Turning on a LED LED ON LED OFF Demo Pin assign - io0:LED anode - io0:LED cthode - Switch state will be printed on browser ``` By running with your obniz id, your browser will be connected to your obniz Board. After establish, green bar will be displayed. It mean you can control it from your program. ![](images/quickstart_runexample.png) This program display text what you input at form. Input text then press the button "Print on obniz". The text will be displayed on your obniz Board display. And swtich state is printed on the browser. Toggle the switch on your obniz Board. It is used at Wi-Fi Password typing. The state will be printed at "Switch: unknown" area at realtime. Program will be terminated by closing the page. It's easy to integrate internet and electronics. > If you know about HTML, you may imagine more fun things. Not only this site. Copy this HTML into your local HTML file. Then open it on your browser. It works. ## Start writing your program Let's proceed to next [Lesson First Program](/guides/basics-of-html-and-javascript/first-program). Use obniz from your program! --- ## Troubleshooting URL: https://obniz.com/reference/board-1y/quick-start/troubleshooting If you have any trouble starting or setting up obniz Board, please check the following or see FAQ. Please let us know if you have any questions (Contact). Display on obniz Board Display on obniz Board Problem / Error How to solve Nothing appears on the display. Try the following in order. Reboot(Unplug USB and connect again)Changing the battery or USB cable If it does not improve, there is a possibility of obniz Board failure (initial failure). Products with initial failure will be exchange new Board for free within a month after purchase. Please contact us. [Wrong password]Incorrect password entered (OS 2.1.1 or earlier) Please re-enter your password. [Can’t connect]Passwords do not match or Cannot connect to Wi-Fi(OS 3.0.0 or later) The previously set Wi-Fi may not be found, or the selected SSID or password may be incorrect. Restart Board and set up Wi-Fi connection again. TCP error The connection was not successful, for example Connected to Wi-Fi but not connected to serve, or DNS is not possible etc… MAINTENANCE Displayed during maintenance or update of the server (obniz Cloud). It usually recovers within a few seconds, please wait. XXX INACTIVATED Displayed when the obniz Board or the user who owns it is not active. From Device setting, change the setting to Active. When power up with dial switch being pressed, You will be on setting. About each menu, see blow: Setting Screen About Wi-Fi Wi-Fi should have DHCP and 2Ghz band. If you are unable to connect to the Wi-Fi once connected, it is expected that the network settings has changed. Please check the following in order. Restart obniz Board (Power plug in / out)Restart Wi-Fi routerChange to other Wi-Fi If you have any other problems, please check the FAQ. --- ## Power Supply URL: https://obniz.com/reference/board-1y/power obniz Board can be powered by one of two way. From USBPower pin. Available voltage range is described at Spec. USB obniz Boardobniz Board 1YMicro USBUSB Type-C ## zPower pin(only obniz Board 1Y) Power pin is hided three terminals. + and - share power with USB. So you can get a power from USB or power a obniz Board 1Y without USB. 3.3v is a output from obniz Board 1Y. It is generated inside of obniz Board 1Y. You can get up to 1A but it also used from obniz Board 1Y it self. We recommend 500mA or below. Silk on boardInputOutput+Spec described range5v(Same as USB)3.3vNot Available3.3v–Spec described range0v(Same as USB) --- ## IO URL: https://obniz.com/reference/board-1y/io The 12 external IO of obniz Board have special features including (streaming) 1A. ## IO functions All of the 12 IO have the same functions. Each function can be used through cloud API. - Digital input/output - Use as input/output destination for each digital peripheral(like UART/SPI) - Digital and stand alone analog input - 3.3v digital input of 5v tolerant - Switching between push-pull and open-drain - Switching between 5v/3v for push-pull - Up to 1A in 5v push-pull. Protection from overcurrent/overheat - Protection from unusual voltage level during 3v push-pull static output - Resistence against 5v/3v/0v internal pull-up down ## IO Unit Each IO has the IO unit composition as below. ![](images/iounit.png) Each IO Unit is connected to A/D, MotorDriver and Bus switch. A/D can work independently from others. On the other hand, Motordriver and Bus Switch cannot work at the same time. ## 5v push-pull and protection from overcurrent VCC of a motordriver is supplied from obniz board's power. Output voltage follows it's supply voltage. MotorDriver has internal protection circuit for overcurrent/overheat. So, when using 5v push-pull, protection is enabled for both high side and low side. Once overcurrent is detected, output gets paused (float) and is retried after 1msec. (Overcurrent is detected between 1.9-3.5A.) Overheating is detected when the chip reaches around 160 degrees Celsius. A/D unit always monitors output voltage. When output is static in high or low, the user will be warned of an unusual voltage level via API. This also works with 3v push-pull, not just 5v. We recommend the maximum frequency to be 250kHz when MotorDriver is used. Although it can be run with higher frequency, (the performance becomes sub-optimal.) We tested with 2MHz in digital output at low current, but we cannot guarantee that it would work properly. ## 3v push-pull and open-drain They work through Bus Switch. Since it is not MotorDriver, we recommend using it at under 1mA. It works at the maximum frequency that the obniz Board main processor can generate. As Bus switch with a level-shifter is used, the output voltage tends to go down depending on output current. ## Internal pull-up pull-down Internal pull-up and pull-down can be used at 5v/3v. You may choose to use one or neither of them. --- ## Setting Screen URL: https://obniz.com/reference/board-1y/setting-screen When power up with dial switch being pressed, You will be on setting. You can change or see configrations. Switch dial to move cursor and press to choose.Settings are below. ## Settings > OS3.5.0 or higher Selection | Description ---|--- Normal Launch | Nothing happen. obniz Board will start normally. Clear Setting | Clear All Networks Display Info | Displaying device informatino like Mac Address and version number of obnizOS. > Below OS3.5.0 Selection | Description ---|--- Normal Launch | Nothing happen. obniz Board will start normally. Reset Wi-Fi | Erasing all saved Wi-Fi information. FactoryReset | Re-enabling obnizOS which is installed at our factory. Display Info | Displaying device informatino like Mac Address and version number of obnizOS. --- ## obnizOS URL: https://obniz.com/reference/board-1y/obnizos obniz Board has a obnizOS for cloud connection, which is pre-installed to obniz Board in our factory before shipping. ## Update obnizOS are provided by our company. We may update it at times to add new features and fix bugs. You can install the latest version from [cloud console](/reference/cloud/device-management/) via the internet. See more details on [Remote OS Update (OTA)](/cloud_device/ota). You can check latest obnizOS version below: [/reference/obnizos-for-esp32/changelog/](/reference/obnizos-for-esp32/changelog/) ## Factory reset(deprecated) you can reset obniz Board obnizOS to factory version. - **Function has been deleted since obnizOS 3.5.0**. - **For obnizOS >= 3.0.0, performing a Factory Reset may cause the device to not boot**. This function is only available with obnizOS Connect obniz Board to power while pressing the switch to display the menu. By choosing "Factory reset", the obnizOS will be reset to factory settings. Of course, you can always update to the latest obnizOS again via the internet. --- ## Sleep Function(only obniz Board 1Y) URL: https://obniz.com/reference/board-1y/sleep-function Sleep is entering low power consumption mode by shutting almost all functions. It makes available working with batteries for long time by continueing sleep and wake up. obniz Board 1Y has a sleep function. Depending on usage, It will keep over 1 year. It makes you put obniz Board 1Y where no power supply. Below is example usages - Watering a plant in intervals. - Monitoring a temperature in intervals. - To handle nexpected events like humandetect or exceeding temperature. Integrating with [Serverless Event](/obniz_cloud/about_event) is useful to use sleep function. ![](images/obniz_board_1y_sleep.jpg) ## How to sleep Send a command from obniz.js and other SDKs or websocket. You can do it over the internet. In sleep mode, obniz Board 1Y shutdown 3.3v power line. So you can't get 3.3v output from power pin on obniz Board 1Y. Wi-Fi and Displays and other almost all functions are no loger available while sleep. It will wake up from sleep when specified trigger occured. You can choose on of below triggers. 1. Past time(second) 1sec to 64800sec(18 hours) 2. Past time(minutes) 1min to 64800min(45 days) 3. edge up detection of io0(Level is TTL. But it depend on VCC level) 4. edge down detection of io0(Level is TTL. But it depend on VCC level) When waking up from sleep, obniz Board 1Y start same as first power up. obniz Board 1Y will wake up by cutting and supplying a power again regardless sleep mode. ## How long does it work Power consumption while sleep is 20uA-40uA(VCC=5V). You need to calculate with standard power consumption (120mA avg). Simple method is below. S: average waking up time in minutes in one hour. Q: Capacity of a battery(mA) (Available Time(h)) = Q/(S/60\*120 + (60-s)/60\*0.04) (例) AAA Battery(2000mA)x3 2 minutes in one day(0.083minutes/hour) will work over 1 year. --- ## hardware spec URL: https://obniz.com/reference/board-1y/hardwarespec obniz Board TypeValueSize69.8*36.3 mm.including usb and switchMounting HoleM2*2Wi-Fi802.11 b/g/n (2.4 GHz), up to 150 Mbps (21.5dBm)Supported Wi-Fi detailsProtocolWebsocket. TLS1.2Protocol Settingstatic ip, dns server, proxy serverBluetoothCompliant with Bluetooth v4.2 BR/EDR and BLE specificationCertificationsMIC, FCC, IC by ESP-WROOM-32Operation Voltage(vcc)Recommended 5v (4.5V-5.5v)(microUSB or J1 pin)Operation CurrentAve 170mA @ 5v (Wi-Fi connected, BLE standing by, no parts connected, OLED displayed)Maximum supply via microUSB1.8A ( If you need more. Please consider using J1 pin. )Main ProcessorESP32Sub ProcessorPIC16F1Num of MotorDriver IC6 (DRV8839)IO num12IO output5V(vcc) push-pull max 1A3.3V push-pull5V/3.3v open-drainpull-up(3.3v/5v(vcc))pull-downPeripheralsGPIO 12A/D 12PWM 6 assignable to everyIOUART 2 assignable to everyIOSPI 2 assignable to everyIOI2C 1 assignable to everyIOOLEDWhite dot 128*64RecommendedStorageTemperature-30 to 80 degrees CelsiusRecommendedOperationTemperature0 to 70 degrees CelsiusSolderingPb free Dimension obniz Board 1Y TypeValueSizew66.6*h36.3 (mm).including usb and switchMounting HoleM2*2Wi-Fi802.11 b/g/n (2.4 GHz), up to 150 Mbps (21.5dBm)Supported Wi-Fi detailsProtocolWebsocket. TLS1.2(regarding account plan)Protocol Settingstatic ip, dns server, proxy serverBluetoothCompliant with Bluetooth v4.2 BR/EDR and BLE specificationCertificationsMIC, FCC, IC by ESP-WROOM-32Power SupplyUSB TypeC or Power ConnectorOperation Voltage(vcc)推奨 5v (3.3-5.5v)Operation CurrentAve 120mA @ 5v (Wi-Fi connected, BLE standing by, no parts connected, using Display)Operation Current(Sleep)20-40uAMain ProcessorESP32Sub ProcessorPIC16F1Num of MotorDriver IC6 (DRV8839)IO num12IO output5V(vcc) push-pull max 1A3.3V push-pull3.3v open-drain(5v tolerant)pull-up(3.3v/5v(vcc))pull-downPeripheralsGPIO 12A/D 12PWM 6 assignable to everyIOUART 2 assignable to everyIOSPI 2 assignable to everyIOI2C 1 assignable to everyIODisplayBlack dot 128*64RecommendedStorageTemperature-30 to 80 degrees CelsiusRecommendedOperationTemperature0 to 70 degrees CelsiusSleepTimer(1 to 64800 sec or 1 to 64800 minutes) or change interrupt for io0 (edge up/down)SolderingPb free --- ## Pin Out URL: https://obniz.com/reference/board-1y/pinassign Electrical Specification obniz IOPhysical IODrive MethodInternal Weak Pull Up/Downio0io0Input 3.3v(5v tolerant)(default)Output push-pull5v(1A mode)Output push-pull3vOutput open-drainfloat(default)pull-up to 5vpull-up to 3vpull-down to 0vio1io1Input 3.3v(5v tolerant)(default)Output push-pull5v(1A mode)Output push-pull3vOutput open-drainfloat(default)pull-up to 5vpull-up to 3vpull-down to 0vio2io2Input 3.3v(5v tolerant)(default)Output push-pull5v(1A mode)Output push-pull3vOutput open-drainfloat(default)pull-up to 5vpull-up to 3vpull-down to 0vio3io3Input 3.3v(5v tolerant)(default)Output push-pull5v(1A mode)Output push-pull3vOutput open-drainfloat(default)pull-up to 5vpull-up to 3vpull-down to 0vio4io4Input 3.3v(5v tolerant)(default)Output push-pull5v(1A mode)Output push-pull3vOutput open-drainfloat(default)pull-up to 5vpull-up to 3vpull-down to 0vio5io5Input 3.3v(5v tolerant)(default)Output push-pull5v(1A mode)Output push-pull3vOutput open-drainfloat(default)pull-up to 5vpull-up to 3vpull-down to 0vio6io6Input 3.3v(5v tolerant)(default)Output push-pull5v(1A mode)Output push-pull3vOutput open-drainfloat(default)pull-up to 5vpull-up to 3vpull-down to 0vio7io7Input 3.3v(5v tolerant)(default)Output push-pull5v(1A mode)Output push-pull3vOutput open-drainfloat(default)pull-up to 5vpull-up to 3vpull-down to 0vio8io8Input 3.3v(5v tolerant)(default)Output push-pull5v(1A mode)Output push-pull3vOutput open-drainfloat(default)pull-up to 5vpull-up to 3vpull-down to 0vio9io9Input 3.3v(5v tolerant)(default)Output push-pull5v(1A mode)Output push-pull3vOutput open-drainfloat(default)pull-up to 5vpull-up to 3vpull-down to 0vio10io10Input 3.3v(5v tolerant)(default)Output push-pull5v(1A mode)Output push-pull3vOutput open-drainfloat(default)pull-up to 5vpull-up to 3vpull-down to 0vio11io11Input 3.3v(5v tolerant)(default)Output push-pull5v(1A mode)Output push-pull3vOutput open-drainfloat(default)pull-up to 5vpull-up to 3vpull-down to 0v Peripherals PINOUT Peripheralfunctionio0io1io2io3io4io5io6io7io8io9io10io11IOoutputYESYESYESYESYESYESYESYESYESYESYESYESinputYESYESYESYESYESYESYESYESYESYESYESYESADADYESYESYESYESYESYESYESYESYESYESYESYESPWMIOYESYESYESYESYESYESYESYESYESYESYESYESUARTTXYESYESYESYESYESYESYESYESYESYESYESYESRXYESYESYESYESYESYESYESYESYESYESYESYESCTSYESYESYESYESYESYESYESYESYESYESYESYESRTSYESYESYESYESYESYESYESYESYESYESYESYESSPICLKYESYESYESYESYESYESYESYESYESYESYESYESMOSIYESYESYESYESYESYESYESYESYESYESYESYESMISOYESYESYESYESYESYESYESYESYESYESYESYESI2CSDAYESYESYESYESYESYESYESYESYESYESYESYESSCLYESYESYESYESYESYESYESYESYESYESYESYESLogicAnalyzerIOYESYESYESYESYESYESYESYESYESYESYESYESMeasurePULSEYESYESYESYESYESYESYESYESYESYESYESYESECHOYESYESYESYESYESYESYESYESYESYESYESYES Peripherals: IO output Each IO can put out digital values. Drive methods can be selected from the three below. TypeVoltagemax Amax FreqDetailspush-pull5v<=1A<=250khz(recommend)Default. Overcurrent protectionpush-pull3v<=1mA(recommend)<=80Mhzover current detection when using io.output().open-drain<=5v<=1mA(recommend)<=80Mhz Each method can be configured independently for each IO.Not only for io.output(), but also for UART and SPI you can choose your preferred drive method. input There is only one input method. 3v input with 5v tolerant, so the threshold value is CMOS level. TypeLevelmax FreqDetaildigital-in3v(5v tolerant)<=80Mhz internal weak pull-up/pull-dow Pull up and down can be configured independently for each IO. There are four types as below. TypePull toDetailfloating Defaultpull-up5vpull-up3vpull-downgnd AD 12ch same time. All 12ch ad can be used. It will not affect the sampling rate. 30 samples/sec or slower Maximum sampling rate depends on your network speed and on obniz Board 1Y firmware version.(with ver1.0.0, max is 30samples/sec) 10bit – VDD calibrated ad also monitors vdd of obniz Board 1Y itself(normally 5v). Each ad result will be calibrated. And ad accuracy is 10bit. Calibration method is depend on firmware version. Firmware versioncalibration methodunder 1.2Always1.2 or higherOnly Vdd is under 4.5v ad can be started even io is used for io-output/uart/spi etc ad converter is independent. It also works while IO is used for another function. PWM 6(pwm0 to pwm5) are available. UART 2 (uart0 to uart1) are available. Available Configration baud: number (default 115200)stop: stop bit length 1(default)/1.5/2bits: data bits 8(default)/5/6/7parity: parity check “off”(default)/”odd”/”even”flowcontrol: flow control “off”(default)/”rts”/”cts”/”rts-cts”rts: io for rts (optional)cts: io for cts (optional) SPI 2 (spi0 to spi1) are available. Only Master mode. I2C 1 (i2c0) is available. Max speed is 1Mhz.Master/Slave mode.But slave mode only works with “written” events. You can’t set data to be read. LogicAnalyzer 1 (logicanalyzer) is available. Measure 1 (measure) is available. Embeded Display obniz Board: 128×64 mono pixel OLED display.obniz Board 1Y: 128×64 mono pixel STN display. Switch 4 State Digital Switch BLE BLE32 embeded Bluetooth Module --- ## Device Management URL: https://obniz.com/reference/cloud/device-management Manage your devices in the cloud. You can change settings, generate device keys, configure apps and more. ![](images/devices.png) ## Device List In the device list view, you can view the devices you own and open the settings for each device. You can search for devices that match your criteria with filters and partially sort them (e.g. obnizOS oldest devices). ### Filters and Search You can search only for devices that match your criteria. You can see available filters by clicking the "Filter" button in the search window in the device list. (e.g.) A specific obniz `id:0000-0000` (e.g.) active on a specific creation date `created:2020-01-01 status:active` ![](images/filter.png) ### App You can install and uninstall apps on your device. You can also open the program edit screen, especially if the app is created by you. For apps that run in the cloud, you can check the execution result as "App Status". For details, see [app](../app) for details. --- ## Registration URL: https://obniz.com/reference/cloud/device-management/registration By registering an official device to your account, you can manage the device from obniz cloud and use more features for free (Lite Plan). The registration method depends on your device and how many devices you register. Choose one of the three methods below. :::info Three ways to register - **[Authenticate and register with the number on the display (obniz Board only)](#authenticate-and-register-with-the-number-on-the-display-obniz-board-only)** For devices with a display. You enter the confirmation number shown on the screen to register. - Target: obniz Board / obniz Board 1Y - **[Register multiple devices at once on the registration page](#register-multiple-devices-at-once-on-the-registration-page)** Open the registration page on a PC or smartphone with a camera, and scan QR codes one after another — like a checkout counter — to register multiple devices together. Good for deploying many devices at once. - Target: devices with a QR code on or shown by the body - **[Register one device at a time with a QR code](#register-one-device-at-a-time-with-a-qr-code)** Scan a single QR code with a smartphone, open the dedicated URL, and register just that device. Good for a few devices at hand. - Target: devices with a QR code on or shown by the body ::: ## Authenticate and register with the number on the display (obniz Board only) Register from the "+Add device" button at the top of the device list in [Developer's console](https://console.obniz.com) > [Devices](https://console.obniz.com/devices). ![](images/register_device.png) Click the "Add device" button, then click "obniz Board". ![](images/register_boughtdevice_0.png) The "Add device to your account" page shows the steps you need to get started. Please make sure the official device you want to register is powered on and connected to Wi-Fi. Once an 8-digit number (obnizID) appears on the display, the device is ready. When the device is ready, click "Ready". ![](images/register_device1.png) ### Entering the obnizID Type the obnizID in single-byte alphanumeric characters (the 8-digit number shown on the device display is the obnizID). Hyphens (-) are optional. After entering it, click "Next". - If the ID does not exist, or is already owned by someone else, an error will be displayed. ![](images/register_device2.png) ### Entering the confirmation number Once you enter the obnizID correctly, a confirmation number of a few digits appears on the device screen. Type that number. - The number becomes invalid after a certain time. - If you mistype it once, a new number is issued. After registration finishes, the device reboots once. You can see the registered device as a registered device in the [Device list](https://console.obniz.com/devices) of the [Developer's console](https://console.obniz.com). ## Register multiple devices at once on the registration page This method registers many devices at once. Open [Register multiple devices](https://console.obniz.com/devices/add_by_qr_codes) on a PC or smartphone with a camera. Scan QR codes one after another — like reading items at a checkout counter — to register multiple devices in sequence. Beyond registering to your account, you can add descriptions and install apps in one continuous flow. Use this method when you register several devices or install apps, such as 10 or more devices. Register from the "+Add device" button at the top of the device list in [Developer's console](https://console.obniz.com) > [Devices](https://console.obniz.com/devices). ![](images/register_device.png) Click the "Add device" button, then click "Other devices with a QR code". ![](images/register_boughtdevice_0.png) The registration screen appears, and you can read QR codes from the web camera and register them in sequence. ![](images/add-qr-multiple.png) The steps are as follows. 1. A camera permission dialog appears as soon as the screen opens, so please allow it. Alternatively, allow it from "Start scanning". 2. A high-resolution camera is preferable. Switch cameras as needed. 3. Scan the devices. If your speaker is set to make sound, a sound plays when a scan succeeds. (Devices are not registered at this stage yet.) 4. Scanned devices are added to the list on the right, so name each device as needed. 5. For the scanned list, you can choose "Register only" or "Register and install an app". You can see the registered devices as registered devices in the [Device list](https://console.obniz.com/devices) of the [Developer's console](https://console.obniz.com). :::info What to do when it does not work Try the following. #### Capture at a higher resolution - You can zoom in on just the QR code with "x4" or "x8". - Only on devices that can capture at a higher resolution, pressing "Capture at high resolution and read" captures at a higher resolution and then tries to read the code. ### Import the QR code a different way - You can import an image you captured earlier. Read it with "Read from an image file". - You can read the QR code with a QR code reader, enter that URL, and add it from "Add". - Otherwise, register one by one instead of on this screen. Try "Register one device at a time with a QR code". ::: ## Register one device at a time with a QR code This method registers a device that has a QR code on its body, one at a time, with a smartphone. The device you scan with opens a dedicated URL, and only that device is registered. * The Intelligent Edge series cannot be registered this way. Please use "Register multiple devices at once on the registration page" above. ![](images/serial_code_qr.jpg) Scan the QR code to open the URL. ![](images/register_qr_0.png) Press the "Add this device to your account" button. ![](images/register_qr_1.png) After registration finishes, the device reboots once. You can see the registered device as a registered device in the [Device list](https://console.obniz.com/devices) of the [Developer's console](https://console.obniz.com). --- ## Generate a Device URL: https://obniz.com/reference/cloud/device-management/generate-a-device In addition to the official devices, users can also add obnizOS to compatible devices (microcontrollers) with By installing it, you can create your own obniz device. See [Price](https://). ## How to create You can create a device. Write OS only to supported devices in obniz-cli/obnizWriter and also issue a device license. obnizOS' [See the installation documentation.](/reference/obnizos-for-esp32/quick-start/) --- ## Transfer Devices URL: https://obniz.com/reference/cloud/device-management/transfer You can transfer the devices you own as the property of your team or someone else's account. ## User ⇨ Team he/she belongs to It is possible to transfer devices (transfer management tickets) to your team. The conditions of the devices that can be transferred and the process to complete the transfer are as follows. ### Conditions for devices that can be transferred - A device that has a one-time license written to it and still has no apps installed. ### Flow of transfer 1. select the target device in the device list screen. 2. Click the "Bulk operation" button, and then click "Transfer devices to the team you belong to". 3. Select the name of the team you want to transfer to, and click the "Transfer" button to complete the transfer. ## User ⇨ User You can make a request to an other user that you're intending to transfer your devices to that user. After transferring has completed, you have no longer any authority to devices transferred and cannot install app onto them nor access to their information. Transferable device conditions and the procedure flow follow. ### Transferable Device Conditions The device: - is an official obniz device - doesn't have any installed app ### Procedure Flow 1. Chose target devices on a device list page. 2. Tap "bulk operation" button, then click "Transfer obniz devices to an other user". 3. Input email address you want to transfer devices to and hit the "update" button. 4. If you've input a correct email address, you're going back to a device list page. 5. After step 4, a request email will be sent to a user you've just specified by an email on step 4. If a user approves your request email, transferring process will completely be done. ### Cautions - If app has been installed on devices when a user approves a transferring request, procedure will fail.(Users can do normal operations untill transferring process finishes) - A deadline of approval is 24 hours. - If you don't want to approve, just ignore the email. --- ## Network URL: https://obniz.com/reference/cloud/device-management/network Network allows you to see if the device is currently online and, if so, to which network it is connected. ![](./images/network.png) Item|Contents ---|--- Global IP | The global IP of the network the device is using Local IP | Local IP from which the device is obtained. Access Point | The Wi-Fi information when the device is connected to the network via Wi-Fi, including SSID and MAC Address, as well as the RSSI (radio strength) when the device is first connected. ## Wi-Fi MESH If the device is connected to the cloud with Wi-Fi MESH, the access point information will be different depending on whether it is a Root Node (layer=1) or a Child Node (layer=2 or higher). ### Root Nodeの場合 The information of the connected access point will be displayed. ![](./images/wifimesh_root.png) ### Child Nodeの場合 You can check your own layer, the obnizID of the parent you are connected to, and the signal strength of the parent. ![](./images/wifimesh_child.png) --- ## Connection Logs URL: https://obniz.com/reference/cloud/device-management/log You can check device connection logs to obniz Cloud and Websocket API connection logs. Logs are displayed in ascending order of the date and time they were recorded, with the more recent logs displayed the further down the log. ## Daily bar view The connection rate for a selected day (or the day the page was opened if none is selected) is displayed hourly, covering the past week. ![](./images/logs_default_en.png) ## Detailed history view Below the connection rate view, you can retrieve the detailed logs for the selected date, view them, and download them as CSV. ![](./images/logs_details.png) For devices that use the cloud log sending feature on OS 7.1.0 or later, you can also view the device logs from before the device came online (the information shown on the serial console) within this history. This lets you understand what happened while the device was offline, as well as the connection events that occurred while it was connected. ![](./images/logs_cloudlog.png) ## Manual Fetch / Automatic Fetch ### Manual Fetch Pressing the "Reload" button retrieves all logs newer than the bottom (most recent) log displayed. ### Automatic Fetch When the "Auto Fetch" checkbox in the upper right corner is checked (on by default), it queries for new logs at 10-second intervals. The range of logs retrieved is the same as for a manual fetch. --- ## Offline Notification URL: https://obniz.com/reference/cloud/device-management/offline-notification >OS3.5.0 or later This is a function that notifies you by email or other means when your device goes offline. You can set whether or not to use this function for each device. It can also be linked to "issues", and there is an option to generate an "issue" when offline is detected. ## Timing of offline determination If a device is offline for 5 minutes after being detected as offline, an issue will not be generated. ## Notified to You can change the recipient of notifications when an issue is opened in your account's notification settings. ## Issue You can open issues at the same time to track offline issues. You must have an issue plan to use this feature. When an issue is linked to an issue, you will receive two notifications, one for the offline issue and one for the open issue. If the issue is open and you are notified offline again, you will not be notified about the issue opening. ## How to use To use Offline notifications, you need to sign up to use the function on the cloud. Please [Contact us](https://support.obniz.com/hc/ja/requests/new?ticket_form_id=900000492026) for more details. ### How to change the settings 1. go to [Device List](https://console.obniz.com/devices) in the Developer Console and click on the "obnizID" of the device you want to change. 2. 2. You can configure the settings in the "Offline Notification" tab of the device settings. It will be updated as soon as you click the Update button. ![](images/device-offline-notice-setting.png) ##### \- checked You will be notified when obniz goes offline. ##### \- unchecked You will not be notified when obniz goes offline. --- For more information about the billing timing, please refer to [Rate Calculation and Billing](/reference/cloud/account/billing). Please refer to [Pricing](https://iot.obniz.com/pricing) for the usage fees. --- ## Metadata URL: https://obniz.com/reference/cloud/device-management/metadata You can store multiple values for each device and read them from obniz.js and other sources. Things like sensor read intervals and group numbers can be put into the metadata to switch control of each device in the same program. Metadata can be configured in the device management from the per-device settings screen, and multiple strings can be stored depending on the key values. The description is a special key that is also available in the device list as a device description. ![](images/metadata.png) In obniz.js, it can be read from the metadata property. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { console.log(obniz.metadata.description); if (obniz.metadata.mode === 'debug') { obniz.io0.output(true); console.log(`debug mode`); } } ``` --- ## Active/Inactive URL: https://obniz.com/reference/cloud/device-management/active-inactive You can choose to use or not use a license for a device that you own. You can inactivate or delete licenses you don't need. ### Active A device that is licensed (has its device key written to it) is ready to connect to the cloud and can be used at any time. ### Inactive An inactive device is a device that is still registered, but is no longer available in the cloud. It can be changed to active at any time from the cloud and will be applied immediately. ## Deleting a License A license can be deleted. Once deleted, the license will no longer be able to connect to the cloud and cannot be reactivated. * * * For more information about the billing timing, please refer to [Rate Calculation and Billing](/reference/cloud/account/billing). Please refer to [Pricing](https://iot.obniz.com/pricing) for the usage fees. * * * * * ## How to change the settings 1. Select the device you want to change from the [Device List] (https://console.obniz.com/devices) of the developer console. 2. Select the device you want to change from the list of devices (https://console.obniz.com/devices) in the Developer Console. 3. The changes will be applied immediately. After changing to active, the device will be able to connect immediately, while after inactivity or deletion, the current connection will be disconnected and will not be able to connect immediately. ## Batch Setting Batch settings can be made from the device list. You can save time and effort by selecting a device and operating it from the batch operation menu. --- ## Remote OS Update (OTA) URL: https://obniz.com/reference/cloud/device-management/remote-os-update-ota ## obnizOS Update obniz obnizOS gets updated regularly. Updates can be done through the internet, and it is called "OTA". To change a obnizOS you want to use, choose a obnizOS version on the console and press "Install" button. ( your obniz must be online before this process. )You should update obniz.js upon installing a new version of obnizOS ### Compatibility JSON format for Websocket/REST API has compatibility. The Formats are same. But new functions are not available for old obnizOS. If you call new function to old obnizOS, then error occured. Please keep updated your SDK. SDK don't have compatibility. You need to updated latest SDK regarding update of obnizOS. The latest SDK, especially obniz.js, can use with all version of obnizOS. ## How to start OTA ![](images/img_ota_board02.jpg) Turn on the power of the obniz you want to update and display a screen with a QR code. At this time, the current obnizOS version is shown under obnizID. ##### Attention If it is not obnizBoard, such as obnizOS for ESP32, turn on the power and go online. You can check the version of obnizOS by serial communication with the device. ![](images/ota_step1_en.png) Go to obniz site and click console. ![](images/ota_step2_en.png) Click a device from the menu. If you are not logged in, you will be prompted to log in. ![](images/ota_step3_en.png) Click obniz ID of the device whose firmware you want to update in the device list. ![](images/ota_step4_en.png) In obnizOS remote update, select the version of obnizOS you want to install. (Normally select the newest one.) Then press the install button. ![](images/img_ota_board03.jpg) obnizOS has been updated. Please wait about 20 seconds. ![](images/img_ota_board01.jpg) If the QR code is displayed again and the version under obnizID has changed, you are done. ## How to do batch setting Batch setting is available from the device list. You can save time and effort by selecting a device and operating it from the batch operation menu. --- ## Update network settings remotely URL: https://obniz.com/reference/cloud/device-management/remote-network-settings-update >OS3.5.0 or later You can update your device’s network settings from the developer console. Normally when you intend to write network settings to obniz, you are supposed to be near it. If devices targeted for updating have been set far away and you cannot go there easily, this function comes into play. Here's the procedure. ## Select devices First, go to the device list page and select devices whose network settings you want to update. But please be careful. Make sure inactive devices and offline devices are NOT chosen. ## Import new network settings Then, specify new network settings by importing a JSON file. The format of the JSON file is described below. Current network settings are going to be replaced with the new one. If everything's all right where you've chosen devices correctly and the file format has no problem, you'll return to the device list page. Seems nothing happened but don't worry, the result will be notified via your account email. Normally the result email will be sent after a couple of minutes. If a checking whether or not the device gets updated correctly takes long time, it'll take some time to recieve the result email. When a device doesn't become online after updating operation and we can't check if the device gets updated successfully or not, we'll let you know about that by the result email after 15 minutes. ## Setting JSON JSON format is defined in [Setting JSON](/reference/obnizos-for-esp32/settings/setting-json) ## How to use To use remote updating of network settings, you need to sign up to use the function on the cloud. Please [Contact us](https://support.obniz.com/hc/en-us/requests/new?ticket_form_id=900000492026) for more details. --- ## Security Setting URL: https://obniz.com/reference/cloud/device-management/security-setting ## Access Token By default, obniz API is accessible by anyone. However, you can choose to put on an Access Token to each obniz. Access Token can be disabled and regenerated anytime. ## How to do batch setting Batch setting is available from the device list. You can save time and effort by selecting a device and operating it from the batch operation menu. --- ## Region Setting URL: https://obniz.com/reference/cloud/device-management/region-setting We provide cloud services in multiple regions which obniz can be connected to. Currenty, we provide the services in two regions: 1. East Asia 2. North America By choosing the nearest region, you can reduce network latency. --- ## Online Check Interval URL: https://obniz.com/reference/cloud/device-management/pinginterval > Supported in obnizOS 3.5.2 and later When no data is exchanged between the device and the cloud for a while, a communication is performed to check if the device and the cloud are online. By default, this takes less than a minute, but you can manually set a longer time to reduce the amount of communication in environments where there is not much communication. In return, the time it takes to detect that the user has gone offline will be longer, and the period of time when the user is falsely assumed to be online when he or she should be offline will be longer. ## Usage scenarios If you are performing anomaly detection where not much communication occurs and the amount of communication is important, such as LTE lines, you can increase this value to reduce the amount of communication only for online confirmation. ## How to configure On the console, you can update the details of each device on the screen or batch update in csv. When an update is made, it will be applied immediately. You can set up to 30 minutes. --- ## CSV Import/Export URL: https://obniz.com/reference/cloud/device-management/csv You can export/import device information csv. ## CSV Export Only devices shown at device management page will be exported. The number of devices may vary depending on your searching conditions. There are two CSV formats: "one printed normal device information" and "one printed app installation information". ### CSV Layout #### Normal Device Information | Name | Description | Required | | ----------------- | ------------------------------------------------------- | -------- | | id | Device ID | ✅ | | access_token | Access Token | | | hardware | Name of Hardware | ✅ | | description | Description of a device. This includes in metadata, too | | | metadata | Meta data | | | devicekey | Device key | ✅ | | os | Kind of OS installed on a device | ✅ | | osVersion | Version of OS installed on a device | ✅ | | region | Location of a server to which a device connects | ✅ | | status | Status of device's activeness | ✅ | | wifi_mac_address | MAC address of Wifi | | | ether_mac_address | Mac address of Ethernet | | | pingInterval | [Online Check Interval](./pinginterval) | | | createdAt | Date when a device is registered | ✅ | #### App Installation Information This is the format friendly with CSV import(We mention about this below this page). If you wish to export a CSV in this format, it's required that you've searched devices before and app id contains in searching conditions. From app to app, options required at installation time are different. We want to keep the CSV layout, or say, the number of column consistent. | Name | Description | Available values | | ------------------------------------ | ----------------------------------------------------------------------- | ----------------- | | obniz.id | Device ID | 0000-0000 format | | obniz.metadata.description | Description of a device | | | obniz.activate_status | Status of a device | active / inactive | | obniz.online_check_interval | [Online Check Interval](./pinginterval) | 1 ~ 30 | | obniz.notification.offline.enable | Enable/Disable [offline notification](./offline-notification) | enable / disable | | obniz.notification.offline.add_issue | Whether or not to make it an issue when offline is detected | enable / disable | | install_app[0].id | App ID installed on a device | wa_xxx | | install_app[0].configs.xxx | Option values required for app installation. xxx must match option key. | | ※Different app has different number of options required at installation time. Exaple follows. ##### Temperature Measuring app that needs options of a temperature to send notification(temperature_limit) and notification way(notification_way) | Name | Description | Available values | | ---------------------------------------- | ------------------------------------------------------------- | ----------------- | | obniz.id | Device ID | 0000-0000 format | | obniz.metadata.description | Description of a device | | | obniz.activate_status | Status of a device | active / inactive | | obniz.online_check_interval | [Online Check Interval](./pinginterval) | 1 ~ 30 | | obniz.notification.offline.enable | Enable/Disable [offline notification](./offline-notification) | enable / disable | | obniz.notification.offline.add_issue | Whether or not to make it an issue when offline is detected | enable / disable | | install_app[0].id | App ID installed on a device | wa_xxx | | install_app[0].configs.temperature_limit | Temperature to send notification | | | install_app[0].configs.notification_way | Notification way | | ##### Sample toy app made by your seven year old nephew that takes no options | Name | Description | Available values | | ------------------------------------ | ------------------------------------------------------------- | ----------------- | | obniz.id | Device ID | 0000-0000 format | | obniz.metadata.description | Description of a device | | | obniz.activate_status | Status of a device | active / inactive | | obniz.online_check_interval | [Online Check Interval](./pinginterval) | 1 ~ 30 | | obniz.notification.offline.enable | Enable/Disable [offline notification](./offline-notification) | enable / disable | | obniz.notification.offline.add_issue | Whether or not to make it an issue when offline is detected | enable / disable | | install_app[0].id | App ID installed on a device | wa_xxx | ## CSV Import You can install an app to multiple devices by one single csv import operation. Installation acts like a 'registration' for a device that's not been installed any app and 'updation' for a device that's already installed the very app you're just intending to install. Options that's required at installation time differ from app to app, so before carring out CSV import it's recommended to search devices by conditions including app id and export them as an app information CSV. You can use this CSV to import. ### CSV Layout You can use the csv exported in the "Apps with installation information" section without modification. Please use Shift_JIS character encoding. | Name | Description | Available values | Required | | ------------------------------------ | ----------------------------------------------------------------------- | ----------------- | -------- | | obniz.id | Device ID | 0000-0000 format | ✅ | | obniz.metadata.description | Description of a device | | ✅ | | obniz.activate_status | Status of a device | active / inactive | | | obniz.online_check_interval | [Online Check Interval](./pinginterval) | 1 ~ 30 | | | obniz.notification.offline.enable | Enable/Disable [offline notification](./offline-notification) | enable / disable | | | obniz.notification.offline.add_issue | Whether or not to make it an issue when offline is detected | enable / disable | | | install_app[0].id | App ID installed on a device | wa_xxx | ✅ | | install_app[0].configs.xxx | Option values required for app installation. xxx must match option key. | | | --- ## Facility/Operation URL: https://obniz.com/reference/cloud/facility >OS3.5.0 or later ## When should you use this feature? If you wish to set tons of obniz devices to several facilities, this feature 'Facility' might be your best friend. When doing this kind of operation, we imagine the overall flow would look like these: 1. Get maps of each facilities 2. Get obniz devices 3. Write some sort of IDs on map 4. Put the corresponding ID label on each devices that you want to set to the place the ID points to 5. Do the network configuration for each devices 6. Send pre-configured devices to the facilities along with the map 7. People in charge of setting devices at the facility set the devices with referencing the ID on map and label on devices. Especially pre-configuring each devices may be a tough work. Then this fucntion comes into play. You don't have to recieve devices before sending them to facilities anymore. It's became possible to create a network settings on user console and apply them to each devices on-site by tapping Android smartphone with the specific app to each devices. Then the devices get the network configuration from the Android app and connects to network. ## How to use? >To use Facility / Operation, you need to sign up to use the function on the cloud.Please [Contact us](https://support.obniz.com/hc/en-us/requests/new?ticket_form_id=900000492026) for more details. These are simplified steps. We are going to cover the details later. 1. Go to user console. 2. Open 'Facilities' page from 'Facility Management' section on the left menu. 3. Create a facility. 4. Create an operation which targets to the facility you made on the previous step. 5. You can get a special URL when creating an operation. 6. You tell people on the actual real-world facility building the URL. 7. They click the URL and Android app will open. 8. The app shows them about what to do based on the operatioin you've created on the step 5. We have two important terminologies about this feature. 'Facilities' and 'Operations'. Let's dive into them. --- ## Facility URL: https://obniz.com/reference/cloud/facility/facility This is self-explanatory. Representing the building on which you're willing to set devices. If a device get tapped and connects to network, that means the device belongs to the facility. So possibly many devices can belong to a facility and you can see the online rate of belonging devices on facility list page. The names of facility must be unique. ## Create Clicking 'Create' button on My facilities page will show you a mordal and input a name of a facility. This name in most cases corresponds to the name of the actual real-world building on which you intend to set obniz devices. ![](images/create_facility-en.png) ## Let obniz belong to facility MANUALLY Normally obniz devices become getting belonged to a facility after being operated by an Android app. But you can also let devices belong to a facility manually on the device detail page. ![](images/belong_to_facility-en.png) ## Online Rate You can check the online rate of devices that belong to one facility. We assume green and red bars are shown on the facility list page. ![](images/online_rate-en.png) This picture indicates that there are two devices which belong to a facility with the name of 'Ikebukuro Station' and one device is online but another is not. Device list that belongs to the facility will be shown when clicking the number of devices. --- ## Operation URL: https://obniz.com/reference/cloud/facility/operation This might sound a bit ambiguous. This is a pre-configuring stuff, such as network or app configuration and linking the IDs on maps to labels on devices. Remember the steps 4 to 5 on the overview section and you can think this as you can do the same things without actually touching the devices which means you can send devices directly to the facilities. ### Two ways of creating an operation In a bulk way, you can create an operation with one single network and app settings that's going to be applied to all devices. In an individual way, you can have several different network and app settings that's applied to each devices. ![](images/op_two_ways.png) ### Bulk Creation #### Basic Information ![](images/op_bulk_basic.png) - Criteria of Completion You can set the criteria about when the operation is done. When do you want to say an operation is finished? When a device gets written the network configurations? Or when one connects to network and becomes online? It's required to specify this from one of two. You can choose "becomes online" when network setting was "Wi-Fi" or "Cellular". "Wi-Fi MESh" and "Ethernet" will go to reboot after setting successfully transfered, so online checking not performed. - Picture of operation If you check this, taking a picure of device that's set is required. This can work as a evidence of finishing one operation. - Location Note If you check this, taking a memo about the exact place where a device is set is required. - Due Date The date the operaiton is going to be held. You can skip setting this. #### Bulk Information ![](images/op_indication_id.png) - Indication ID This relates to a future device to which network and app settings linked to this ID is applied. Most of the time, this ID corresponds to ID on map. In bulk creation indication ID will be generated automatically in a specific format. Format is '[prefix]-[number]'. You only input the prefix and the number will be suffixed starting from 0. The end of number is equal to the amount of expected devices - 1. If you wish to operate 100 devices, indication ID would be like 'prefix-0', 'prefix-1', ..., 'prefix-99'. Operators on the building are supposed to pick a specific ID on the map and find out the same ID(which we say indication ID here) on the Android app. Please refer to the Android app document for more details. - Set indication ID to the device description By checking this, the specific format of description will be set on the device's description when a device gets applied an operation. Description would look like this: 'Ikebukuro Station, East Exit Operation, prefix-12'. #### Network Setting There 4 types of network you can select: Wifi, Cellular, Wifi mesh and Ethernet. Each of them has each required and optional parameters. Max number of network settings differ: Wifi and Wifi Mesh are up to 5 and Cellular and Ethernet are up to 1. - Priority Network Network settings specified here are tried out first. If none of them succeeds, other network settings will be tested out. - Wifi Channel Settings of country/region. [Reference](/reference/obnizos-for-esp32/settings/setting-json#wifi_channel) #### App Setting Optionally you can select an app that you want to apply to devices. YOU CANNOT SELECT MORE THAN ONE APP WITHIN ONE OPERATION. If you willing to choose another app, you must consider creating another new operation. ### Individual It's possible to do the same thing as the bulk creation way through individual way. If you'd like to decide each indication ID or parameters for network settings and app settings from device to device, this way will be useful. In bulk creation way, you specify the operation information on the page, but in this way you do the same thing on csv file and import it. #### Basic Information This is the same thing as the one of bulk creation. #### Network Settings and App Settings First, specify the basic information. ![](images/op_select_net_app.png) Then hit the 'Export' button and you will get an csv.This csv works as a template that you can know which columns are required in creating the operation in which you selected a specific network type and a specific app. ![](images/op_csv_before.png) With referencing the header row, you add some of the more data row, each of them carrying a unique Indication ID, hence also containing the information of network configuration parameters and app configuration parameters. If some parameters are missing or invalid, this will cause a trouble. Just make sure you set correct inputs. In the sample csv, network settings are represented in a header row in a form of "[Type of network][Index]-[Name of setting item]". So "cellular1-apn" means apn of first cellular configuration, "wifi1-ssid" ssid of first wifi configuration, "wifi2-ssid" ssid of second wifi configuration and "wifi5-ssid" ssid of fifth wifi configuration. The more the number of network settings increase, the longer a header row will be. ![](images/op_csv_after.png) When you are ready, import the csv. ![](images/op_select_csv.png) ※ Format of Csv Enclosing character is double quote and separating character comma. ##### Full names of network setting header columns It follows [Setting Json](/reference/obnizos-for-esp32/settings/setting-json). #### Import CSV directly ![](images/op_two_ways.png) If you want to reuse csv that's exported before, you can use this function. By selecting a number of network settings and app that are suitable for the csv, you can import csv directly, in which you can skip the process of exporting csv. When you reuse the csv above, you select a cellular as a network setting and humidity sensor as an app, then import the csv. ### See Operation Information Operation information consists of basic information and results. - Basic Information ![](images/op_detail.png) When clicking this URL on the Android smartphone, the app will open. So all you have to do after creating an operation is send a map to the operators on the facility and let them know this URL. - Results ![](images/op_results.png) Operation results are shown below the page and each of them relates to indication ID. If an operation's done successfully, 'Status' is 'Done'. When it fails or hasn't been started yet, 'Status' is 'Not Started' and 'In Progress' means it's being operated right now. --- ## Use android app for operation URL: https://obniz.com/reference/cloud/facility/app Once you have created the facility and operations, you will be able to run the operations in your Android application. ## Requirements ### Android device Required Operating Conditions - Android 10 or higher - Internet connection via Wi-fi or cellular Confirmed devices - [DIGNO BX(901KC)](https://www.softbank.jp/biz/mobile/lineup/smart/digno-bx/) ### obniz device obnizOS 3.5.0 or higher ## Android application installation Please install the obniz device setting app from here. ## How to use Open the operation URL in the browser of the android app, and the device setting app will start automatically. A list of instruction IDs will appear, and press it. Selecting the instruction ID will take you to the actual device settings screen. Follow the instructions on the screen to turn on your obniz device and press the "Start Settings" button. The nearest obniz device will be displayed automatically, so press "Connect". If there are multiple offline obniz devices around, an error will occur because the device to be configured cannot be identified. If there are multiple offline obniz devices around, an error will occur because the device to be configured cannot be identified. If you wait for a while, the settings will be written automatically and the configuration will be completed. If the operation requires a description of the installation location or a photo, an input field will appear if necessary, so please follow the instructions. Once the completion report is sent, you will be able to view it in the cloud. You can also check it in the Work Completed tab of the list. ## When an error occurs If an error occurs during the setup, such as a wrong Wi-Fi password, you can report it. The report can be viewed in the cloud. --- ## Use obnizWriter URL: https://obniz.com/reference/cloud/facility/obnizwriter Once you create a facility and an operation, you can execute the operation with obnizWriter. You can write obnizOS to obniz devices that can communicate with PC via USB and execute operations via GUI. ## Requirements. ## PC terminal Required Operating Conditions / Confirmed Operation Device - MacOS 10.15 or Windows 10 ### obniz device obnizOS 3.5.0 or higher USB communication with PC is required. ### Operations to be created - Only "write success" can be selected for work progress management. - Work photo and installation location description cannot be used. ## Install obnizWriter Please install obnizWriter from this procedure. [obnizWriter](/reference/obnizos-for-esp32/quick-start/obnizwriter) ## Prepare API Key Issue the API Key from the API Key menu. After issuing the key, write down the token. ## Usage Login using Token. Check "Write obnizOS", "Write Config" and select "Using Operation". It will write obnizOS and execute the operation. ![](./images/writer_main.png) If the Indication ID is `next`, the unfinished configuration will be done in order. ### Precautions If you perform the same operation on multiple computers at the same time, `next` may not work properly. If you want to do the same operation on multiple computers at the same time, do not use `next` or separate the operations. --- ## Use obniz-cli URL: https://obniz.com/reference/cloud/facility/cli Once you have created the facility and operations, you will be able to execute the operations with obniz-cli. You can write obnizOS to an obniz device that can communicate with a PC via USB and execute operations simultaneously at high speed. ## Requirements ### PC Required Operating Conditions/Verified Devices - Nodejs12 (MacOS 10.15 / Windows 10) ### obniz Device obnizOS 3.5.0 or higher Must be able to communicate with PC via USB ### Operations to be created - Only "Write Successful" can be selected for Work Progress Management. - Work photos and installation location descriptions cannot be used. ## Install obniz-cli Please install obniz-cli from this procedure. [Preparing obniz-cli](https://obniz.com//reference/obnizos-for-esp32/quick-start/#preparing-obniz-cli) obniz-cli requires version 0.9.0 or higher. Please check the version by using -v to display the version ```shell $ obniz-cli -v version 0.9.0 ``` ## Prepare the API Key Issue the API key from the API Key menu. After issuing the key, write down the token. ## How to use Write obnizOS by typing the following command, followed by the operation. ```shell $ obniz-cli os:flash-create --operation {{operationName}} --indication {{indicationId}} --token {{token}} ``` If the instruction ID is `next`, the incomplete settings will be performed in order. For the token, put the string you got from the API key. ![](./images/cli-op.png) 例 ```shell $ obniz-cli os:flash-create --operation obnizBuilding --indication ob-0 --token token_Bowk7ovadfagcwxJTIxP6WfdX1GOB ``` ```shell $ obniz-cli os:flash-create --operation obnizBuilding --indication next --token token_Bowk7ovadfagcwxJTIxP6WfdX1GOB ``` ### Precautions If you perform the same operation on multiple computers at the same time, there is a possibility that next will not work properly. If you want to run next on multiple computers at the same time, please do not use next or run the operations separately. --- ## Issue Management URL: https://obniz.com/reference/cloud/issue-management With any device-based service, unforeseen things can happen. The Wi-Fi goes out and the obniz device goes offline, a sensor that should be found is not found, or the refrigerator gets too hot. A system that recognizes such problems and manages them until they are solved is called "Issues". ## How to use Issues >To use Issues, you need to sign up to use the function on the cloud.Please [Contact us](https://support.obniz.com/hc/en-us/requests/new?ticket_form_id=900000492026) for more details. You can open issues to obnizCloud from within the program. Open issues can be viewed in the "Issues" section of the console. Also, when an issue is opened, you will be notified of the issue opening to a specified destination (e.g. email). In particular, "automatically generate issues when obniz device goes offline" can be set as "offline notification" for each device from within the console. This allows you to present issues and notifications to your users without asking them for their contact information while they are using your app, not to mention developing the UI. ![](images/issue-list-open.png) ## General Flow 1. a user installs your app on some obniz devices and the service starts 2. The your app program detects a rise in refrigerator temperature and opens an issue. 3. The issue appears in your user's issue list and you get an email notification. 4. Your user recognizes the issue, solves it (e.g. closes the refrigerator), and then closes the issue themself. ## Open and Close Timing Notifications are only issued when an issue is opened. While it is open, no notification will be issued if the issue is opened again. Also, you, the developer, are not notified when an issue is raised (unless it is on a device or app you own). --- ## Open URL: https://obniz.com/reference/cloud/issue-management/create You can create an issue from your device or app. See [Pricing](https://iot.obniz.com/pricing) for more information about the cost of the assignment. ## How to open You can open an issue when obniz goes offline ## obniz goes offline See [Offline Notification Settings](/reference/cloud/device-management/offline-notification) in the console. --- ## Close URL: https://obniz.com/reference/cloud/issue-management/close You can close the issue from your device or app. See [Pricing](https://iot.obniz.com/pricing) for more information about the cost of the assignment. ## How to close You can close the issue in two ways: 1. obniz goes online 2. Close manually. ## 1\. obniz goes online See [Offline Notification Settings](/reference/cloud/device-management/offline-notification) in the console. ## 2\. Close manually Please go to [issues](https://console.obniz.com/issues) and click on an issue to see a pop-up. ![](images/issue-list-open.png) Click "CLOSE" to close the issue. ![](images/issue-close.png) --- ## list URL: https://obniz.com/reference/cloud/issue-management/list You can view the issue from the console. See [Pricing](https://iot.obniz.com/pricing) for more information about the cost of the assignment. ## How to browse You can see it from [Issues](https://console.obniz.com/issues). ## About Open/Closed When an issue is opened, it will be added to the Open list, and closed issues will appear in the Closed list. Please see below for instructions on how to open and close the issue. - [How to open](/reference/cloud/issue-management/create) - [How to close](/reference/cloud/issue-management/close) --- ## Hardware API URL: https://obniz.com/reference/cloud/hardware-api Hardware API let you control devices through obniz Cloud by using API. - Websocket - Bi-directional communication. - REST API - API to device one direction API is common json formats. All things obniz device can do can be controlled from obniz Hardware API from IO on/off to UART/SPI/BLE. Especially Websocket API let you control hardware from HTML bi-directionally. ## SDK We provide SDKs - [obniz.js](/reference/common/) SDK for JavaScript using Websocket API. Works on Browser/Node.js. Github: [https://github.com/obniz/obniz](https://github.com/obniz/obniz) - [obniz.py](https://github.com/obniz/obniz-python-sdk) SDK for Python using Websocket API. - [obniz-node-red](https://github.com/9wick/node-red-contrib-obniz) Node-RED experimental SDK. ## JSON Format See all commands. [Websocket API Reference](/reference/websocket/ws/) --- ## Websocket API URL: https://obniz.com/reference/cloud/hardware-api/websocket-api ## Endpoint ``` wss://obniz.io/obniz/{obniz_id}/ws/1 ``` before issue access token, you can connect above endpoint without it. Below is Available QueryStrings. | Property(query) | Default | Description | | --- | --- | --- | | access\_token | None | An access token issued per device in Device Management. Or an API key or WebApp token or OAuth token with "device control" permission. | ## JSON Use object array to send/receive Websocket API. ## Connection 1. Connect to the endpoint. 2. If [redirect](/reference/websocket/ws/#response-redirect) directive received, you need to close current socket and open new socket to new endpoint. 3. If [ready](/reference/websocket/ws/#response-redirect) received, connection was established. Below is a simple example. ``` ``` --- ## REST API URL: https://obniz.com/reference/cloud/hardware-api/rest-api REST API accept same json as Websocket API. ## Endpoint ``` POST https://obniz.com/obniz/{obniz_id}/api/1 ``` Before access token was issued, You can use API without it. Below is available Request Headers. Property Default Description access\_token None An access token issued per device in Device Management. Or an API key or WebApp token or OAuth token with "device control" permission. Request body is `application/json`. Below is Curl example ``` curl https://obniz.com/obniz/1234-5678/api/1 -H "Content-Type: application/json" -X POST -d '[{"display":{"clear":true, "text":"Works fine."}}]' ``` --- ## obniz Cloud API URL: https://obniz.com/reference/cloud/cloudapi The obniz cloud API is an API for manipulating devices tied to an account, serverless events, etc. You can use it for yourself or other users by creating a WebApp and getting approval from the user. Currently, the following information can be manipulated - WebApp itself - WebApp installation information - User information for approved users - Device owned by the authorized user - Serverless events for approved users ### GraphQL API The obniz cloud API employs [GraphQL](https://graphql.org/learn/). The endpoint is below [https://api.obniz.com/v1/graphql](https://api.obniz.com/v1/graphql) You can get the results by giving a token and query to the endpoint. ``` const graphQLClient = new GraphQLClient(`https://api.obniz.com/v1/graphql`, { headers: { authorization: `Bearer ${token}`, }, }); const query = `{ user { id, name, email } }`; const user = await graphQLClient.request(query); ``` GraphQL communication is done using the HTTPS protocol. Therefore, even if you cannot use a GraphQL client, you can handle it as you would a normal HTTP request. For details, please refer to [here](https://graphql.org/learn/serving-over-http). ### About GraphQL GraphQL is a query language that allows you to retrieve only the data you need, similar to the SELECT statement in SQL. There are two types of GraphQL API, Query and Mutation, and they can be handled as follows. - Query ≒ SELECT statement - Mutation ≒ UPDATE statement For details, please refer to [here](https://graphql.org/learn/). ### Document [https://api.obniz.com/v1/graphql](https://api.obniz.com/v1/graphql) in your browser, you can open the API demo screen along with the documentation. To use the API, you need to add a token to the header, so it cannot be used in the online demo screen. It is convenient to make use of the GraphQL application for the desktop that can give a token to a request header for actual use. [Altair](https://altair.sirmuel.design/) [Apollo](https://github.com/apollographql/apollo-client) ### SDK TypeScript/JavaScript SDK for using GraphQL endpoint is available. https://github.com/obniz/obniz-cloud-sdk Since it is type-defined, you can use IDE completion and TypeScript type checking. Please refer to [README](https://github.com/obniz/obniz-cloud-sdk#readme) for usage. ### Token In order to use the API and access user information, you must create a WebApp and have the user approve the WebApp. A token will be issued upon approval. Also, there are two types of tokens: those issued per user, and those for the WebApp itself. - WebApp token: A token for the WebApp itself. You can get the installation information. - OAuth token: A token for each user that is obtained when the user approves. Information tied to the user can be manipulated. WebApp is required to obtain each. Please see the [App](/reference/cloud/app/) for more information. A token is given in the request header when tapping the GraphQL API. ``` authorization: Bearer oauth_xxxxxxx ``` #### Sample code There is a sample code on GitHub that uses the API. Using OAuth to manipulate user and device information [https://github.com/obniz/obniz-webapp-example-oauth](https://github.com/obniz/obniz-webapp-example-oauth) How to use installation to obtain user-installed application information and develop web services [https://github.com/obniz/obniz-webapp-example-install](https://github.com/obniz/obniz-webapp-example-install) ### Install In IoT development, there are scenes where the same program is used across multiple devices, and each device runs with different settings. With obniz's WebApp, users not only approve and issue access tokens, but they can also "install" multiple WebApps with their settings. ![](images/webapp_install.png) The user installation process is as follows. 1. The server system runs on AWS and other cloud services and is registered as a WebApp on the obniz cloud. 2. Users approve WebApps 3. User installs a WebApp During installation, the user is asked about the settings provided in the WebApp and they are saved during the installation. Also, if a Webhook URL is set in the WebApp, a webhook will be issued upon installation. 4. WebApp calls the obniz cloud API to retrieve all installed WebApps. Execute the program based on the installation information in the WebApp, and in some cases, auto-scale out. 5. Synchronize the WebApp with the user's configuration via a webhook issued at each user installation event (creating/updating/deleting an installation) or a periodic fetch To learn more about installing the WebApp, please see below. [WebApp/Install](/reference/cloud/app/install) ### Error code list | Code | Description | Solution | | :-------------------- | :------------------------------------------------- | :--------------------------------------------------------------------------------------- | | PERMISSION_DENIED | You do not have sufficient access privileges. | Grant the necessary permissions to the API key. | | UNAUTHORIZED | Authentication is required. | Please put the token in the Authorization header. | | BAD_TOKEN_TYPE | Token type is mismatched to one this API requires. | Match the API and token type, e.g. use app tokens for app-related APIs. | | INTERNAL_SERVER_ERROR | An unexpected server error has been occurred. | This is an error on the obniz Cloud side, so please wait a while and it may be resolved. | | BAD_REQUEST | Validation rejected. | Make sure you have not entered incorrect values, such as unusable characters. | | TOO_MANY_REQUESTS | Too many requests. | Please take some time and request again. | | Code | Description | | :---------------------------------- | :----------------------------------------------------------------------------------------------- | | OBNIZ_NOT_FOUND | obniz was not found. | | OBNIZ_INVALID_REGISTRATE_URL | Invalid URL to registrate an obniz. | | OBNIZ_INVALID_SERIAL_CODE | Invalid serial code. | | OBNIZ_INVALID_TOKEN | Invalid registration token. | | OBNIZ_INVALID_ID | Invalid obniz id. | | OBNIZ_INSTALLED_APP | App has already been installed on obniz. | | OBNIZ_ALREADY_OWN | You already own this obniz. | | OBNIZ_UNREGISTERED | This obniz has not been registered. | | OBNIZ_DELETED_ACCESS_TOKEN | The access token has already been deleted. | | OBNIZ_GENERATED_ACCESS_TOKEN | The access token has already been generated. | | OBNIZ_NOT_INSTALLED_APP | App is not installed on this obniz. | | OBNIZ_OWNED_BY_ANOTHER_USER | This obniz is owned by an another user. | | OBNIZ_INACTIVE | This obniz is inactive. | | OBNIZ_MISMATCH_INSTALLED_APP | An app you specified with your request and one that is installed on this obniz must be the same. | | APP_NOT_FOUND | App was not found. | | APP_INVALID_ID | Invalid App id. | | USER_NOT_FOUND | User was not found. | | USER_INVALID_ID | Invalid user id. | | FACILITY_NOT_FOUND | Facility does not exist. | | FACILITY_INVALID_ID | Invalid facility id. | | EVENT_NOT_FOUND | Event was not found. | | EVENT_INVALID_ID | Invalid event id. | | HARDWARE_NOT_FOUND | Hardware was not found. | | FACILITY_OPERATION_NOT_FOUND | Facility operation was not found. | | FACILITY_OPERATION_INVALID_ID | Invalid facility operation id. | | FACILITY_OPERATION_ALREADY_EXIST_ID | Facility operation id already exists. | | TEAM_NOT_ALLOWED_SET_PASSWORD | Team account can not set password. | | SEARCH_OVER_LIMITATION_DEVICE_COUNT | Too many search results. | | SERIALCODE_NOT_FOUND | Serial code was not found. | --- ## HTML Editor URL: https://obniz.com/reference/cloud/online-editor/html-editor Online HTML Editor works on your browser. You can open and edit and run a HTML file. ![](images/htmleditor.png) ## Editable files Editr can edit a file on obniz Cloud. - obniz Public HTML - App HTML - (Legacy)A file in your repository ## obniz Public HTML It Public HTML is parepared programming environment for each device. The address is below. http://obniz.com/obniz/:obniz\_id/program.html or https://obniz.com/obniz/:obniz\_id/program.html ## How to use You can open the editor from "Program" on Developer's console. After opening, You will be asked obniz id to open obniz public html. If you open a file in your repository, Open editor by opening a file in your repository. ## Save the program You can save the program you created or edited by clicking "Save As in Repository" the File menu of the editor screen. ## Program Execusion See the lesson to check how to execute a program. [Lesson](/guides/basics-of-html-and-javascript/first-program) --- ## BlockProgram Editor URL: https://obniz.com/reference/cloud/online-editor/blockprogram-editor Online Block Program Editor works on your browser. You can open and edit and run it. ![](images/blockprogram.png) ## Editable files Editr can edit a file on obniz Cloud. - obniz Public Block Program - App HTML - (Legacy)A file in your repository ## obniz Public Block Program It Block Program is parepared programming environment for each device. ## How to use You can open the editor from "Block Program" on Developer's console. After opening, You will be asked obniz id to open obniz public block program. If you open a file in your repository, Open editor by opening a file in your repository. ## Program Execusion See the lesson to check how to execute a program. [Lesson](/guides/block-programing/start) ## Hiragana Mode 教育用のモードです。 ブロックプログラムに登場する漢字をひらがなやカタカナに切り替えることができます。 日本語で利用している時にエディタ上部の「ファイル」より「ひらがなモード」を選択します。 ![](images/hiragana-mode.png) 元の状態に戻すには「漢字モード」を選択します。 ![](images/kanji-mode.png) --- ## Lua Editor URL: https://obniz.com/reference/cloud/online-editor/lua-editor Devices running obnizOS 7 or later can execute Lua scripts on the device itself. With the Lua Editor on obnizCloud, you can edit Lua in your browser and transfer/run it on your device, all in a single screen. ## Opening the Editor Open "Lua Editor" from the left menu of the developer's console. Sign-in is required. When the editor opens, it automatically connects to your registered obniz device. Switching the device with the selector at the top reconnects to the newly selected device. ![](./images/lua.png) ## Requirements - The device must run obnizOS version 7 or later - When connected to a device with a version lower than 7, the Lua pane becomes read-only. You can update obnizOS (OTA) right from the banner shown at the top of the screen (device owner only) ## Editing and Running Lua Edit Lua in the main editor pane and run it with the following buttons. | Button | Action | |---|---| | Run | Runs the Lua on the device instantly without saving. It is lost after reboot | | Save & run | Saves to the device flash memory and runs it. It runs automatically after reboot | | Save to cloud [Ctrl]+[S] | Saves to the cloud storage tied to the obniz ID. It is restored the next time you open the editor | When you press "Run", the Lua being edited is also saved to the cloud automatically. The `lua>` input below the editor lets you run a single line of Lua on the spot. It is useful for debugging, such as rewriting global variables of the running script. Note that saving to flash (Save & run) is not available on devices without storage. In that case the button shows "No save on this device". ## Inline JavaScript In the JavaScript pane below the Lua editor, you can write and run JavaScript in the browser. The following variables are available in your code. - `obniz` : the connected Obniz instance - `Obniz` : the obniz.js class - `view` : the HTMLElement of the View area at the bottom right, which you can render DOM into `await` is available, and the run finishes when your code completes (registered event handlers keep working afterwards). Pressing "Run JS" also saves the JavaScript to the cloud storage tied to the obniz ID, and it is restored the next time you open the editor. ## Lua and JavaScript Working Together Data sent with `cloud.pluginSend()` on the Lua side can be received with `obniz.plugin.onreceive` on the JavaScript side. In the other direction, JavaScript can execute arbitrary Lua on the device with `obniz.plugin.execLua()`. The default sample code demonstrates this interaction. - Lua: every 3 seconds, measures the io1 voltage, shows it on the display, sends it to JS with `cloud.pluginSend()`, and POSTs it to an external server over HTTP - JavaScript: draws a live graph of the received voltage in the View area, and changes the sending interval with `obniz.plugin.execLua("INTERVAL_MS=...")` via the input and button ## Log The log area at the bottom shows: - Connection state changes - Data received from `cloud.pluginSend()` on the Lua side (`plugin <-`) - Lua runtime errors on the device (`obniz.plugin.onError`) - `console.log` output of the inline JavaScript ## About Storage Lua and JavaScript are each saved to the cloud storage tied to the obniz ID. Unlike HTML programs and block programs, sign-in is required for reading and writing. --- ## App URL: https://obniz.com/reference/cloud/app You can create your own app with certain features like a smartphone app and install it in the cloud. The installation is done to the device. (The program is not transferred to the device). The installed app will run in your browser or on the obniz cloud or on a separate server to enable IoT on the installed device. If you are an obniz developer, you can create an app and offer it to yourself or others. Unlike simple HTML or nodejs software, obniz allows you to develop device-independent software that can be easily distributed to multiple devices and people. ![](./images/devices_app.png) ## Types of Apps. There are two main types of apps. Browser App A browser application is an application created with HTML/JavaScript or a block program. As the name implies, it runs in the browser and can be remotely operated and graphed in real time. In addition, by setting up the "Cloud Execution" function, you can run the application in the obniz cloud as well as in your browser. Hosted App This is used when using obniz devices on a service hosted on another server other than obniz. It allows you to retrieve information of installed devices and manage the devices and accounts of authorized users through OAuth. . ## Browser App. A browser app is one with programs and settings that can be installed on your device. By running the installed app. - The information of the installed devices is captured and executed by the program - The settings you made during installation are incorporated into the program. Both HTML and block programs are described in a device-independent way in the program (do not include the obnizID directly). ```javascript // Example. var obniz = new Obniz("OBNIZ_ID_HERE"); ``` As shown above. By installing this on a device called obnizID 0000-0000 and running it, you will be able to run ```javascript // Example. var obniz = new Obniz("0000-0000", {access_token: "XXXXXX"}); ``` The access token is replaced by a Access tokens are only applied if they are configured.(Block programs do not have access tokens set.) You can also read the installation settings from the program if they are present in the app (HTML only) For example, if you can set the watering interval during installation, it would read like this ```javascript // Example. var obniz = new Obniz("OBNIZ_ID_HERE"); var install_configration = Obniz.App.configs(); var water_interval = install_configration['water_interval']; ``` The browser app can also be configured to run in the obniz cloud. It runs in the cloud based on a trigger and executes in an event-driven manner that finishes within a certain amount of time. Triggers can be webhook calls, every 10 minutes, devices coming online, etc. When executed by the server, the results are recorded and can be viewed in the device list. ![](./images/app_status.png) ```javascript // Example // will replace by installed obnizID and access token var obniz = new Obniz("OBNIZ_ID_HERE"); // read install configrations var install_configration = Obniz.App.configs(); var water_interval = install_configration['water_interval']; if (Obniz.App.isCloudRunning()) { // Cloud Execution const req = Obniz.App.req(); console.log(req.query); // webhook query console.log(req.body); // webhook body // somethig tatsk // record a result Obniz.App.done({ status: 'success', text: `${temp} degree` }); } else { // Runnninng on user's browser } ``` For more information about the browser application, please see [Browser App](./browserapp) for more information about the browser application. ## Hosted App. If you want to create a service that runs on your server, a hosted app is useful. By creating a hosted app, you can get information about the devices that you or other users have installed the app on through the API. You can leave it to the obniz cloud to connect the app to the device and save the settings. You can also manage the accounts and devices of approved users. For more information, please refer to [hosted app](./hostedapp) --- ## Browser App URL: https://obniz.com/reference/cloud/app/browserapp You can create an IoT app to remotely control devices by creating a browser app, using only obniz. You can run the program in the cloud based on a trigger in your browser or in obniz cloud. You don't need to create an app to remotely control an obniz device, but by creating an app, you can control it remotely with - Easily "install" the same app on multiple devices - You can run it on the obniz cloud - It's easy to provide to others. You can use it in a convenient way. ## Program Language The programming language can be HTML/JavaScript or block programs. Block programs are converted to HTML/JavaScript to work in a browser. ### Control Publicity of Your App You can choose the level of publicity of your app. There are three levels and explanations are following below. public: Your app appears on obniz App Store. Anyone can install it or reference its program code. installable: Your app DOES NOT appear on obniz App Store. If you would like to let someone install your app, please share a special URL that's shown on the app detail page. private: Your app DOES NOT appear on obniz App Store. No one but you can install the app. ## How to Create. After creating your account, choose your language from "App Development" and create your app. There are templates for each device, so it's convenient to create an app from the closest template. After creating the app, an online editor will open, so you can start the program as is. ## Installation. The app you create can be used by installing it on your device. ("Installation" is done on the obniz cloud, it does not mean the program is transferred to your device and written. It does not mean that the program is transferred to the device and written.) Only one app can be installed on one device. If you change an app's program after installation, it will be applied instantly to all installed devices (it uses the same app's program. The program will not be copied) If you have "Installation settings" in the app's settings, you will be asked for these settings when you install the app. For example, you can set "watering interval". The set values can be read in both the browser and the cloud. ```javascript const configs = Obniz.App.configs(); console.log(configs.watering_interval); // User configured value ``` ## Browser Execution Apps that are allowed to run in the browser can be run by the user in the browser if the browser execution is allowed in the settings. You can also select your device to run it when you are editing the app's program in the online editor. If you don't allow browser execution, the app will be cloud-executed only and will not be able to - Select obnizID from the program editor and run it on a device you don't have installed, even if you don't have it installed. - Run Now" button under Find Apps --- ## Browser App: Cloud Execution URL: https://obniz.com/reference/cloud/app/browserapp-cloudexec If the app has "Cloud Execution" set in the app, the program will be executed by the server whenever a trigger occurs after installation and the execution result will be saved. When the app is triggered, it will be executed in the cloud. It will run until the `Obniz.App.done()` function is called or times out (30 seconds). The maximum number of times to run the app per day is defined at [Pricing](https://iot.obniz.com/pricing). Triggers can be set as follows, and multiple triggers can be set. Triggers | Description ---|--- Webhook | Webhook issued on each device is launched when it is called. Obniz.App.req()`Obniz.App.req()` allows the app to retrieve the request object. You can retrieve a request object with `Obniz.App.req()`. Specified Time | For example, `everyday/11:11`. Intervally | hourly aperture (e.g. 11:11). You can specify the interval in minutes as `every/10minutes` or in hours as `every/10hours`. When the device comes online | Run when the device comes online. When the switch of the device is pressed (only for the target device) | press the switch for obniz Board / 1Y. Press the "M5" button for M5StickC. ### Cloud Execution Determination and Request You can check if the program is running in the cloud with `Obniz.App.isCloudRunning()`. If the program is running in the cloud, you can use `Obniz.App.isCloudRunning()` to determine if the program is running in the cloud, and if it is running in the browser, you can display the graph. You can get the query and body if the app is running in a webhook. ```javascript if (Obniz.App.isCloudRunning()) { const req = Obniz.App.req(); console.log(req.query); console.log(req.body); } ``` ### The result of the cloud execution. You can save the results of cloud-run app execution. It is used to display the temperature and status obtained by the sensors. (The block program has a dedicated block for this purpose.) ![](./images/app_status.png) ```javascript Obniz.App.done({ status: 'success', text: `${temp} degree` }) ``` The status is - 'success' - 'error' The text can be any string. If you don't specify it, it will be considered a success. ```javascript Obniz.App.done(); ``` --- ## Hosted App URL: https://obniz.com/reference/cloud/app/hostedapp If you want to create a service that uses obniz running on your server, a hosted app is useful. By creating a hosted app, you can retrieve information about the devices on which you or other users have installed the app via the API. It also allows you to manage the accounts and devices of approved users. You can let obniz cloud take care of things like linking apps to devices and saving settings. ## Creating an App. Select "Development" > "App development" from the developer console and enter the required information. After creating the app, you can set up the details. ### Permissions. This is the access rights that this app requests from the user in OAuth. - user: The user's account information such as email address - device: the device you own - repository: files in the repository (this feature is not published in the API) - event: Serverless event - device_control: Hardware API to connect to the devices in your account via obniz.js or other methods. can be set. Set the following permissions for each This will also appear on the user's authorization screen to confirm what this app is allowed to do. - NONE: Not required - read: read only - full: read/update/create These permissions can be operated on the user's account after approval and are not related to the installation. When a user installs an app on a device, regardless of the above permissions, the user will be granted read and device manipulation permissions for the installed device, user and device only. ### WebhookURL. The URL used in Webhook. See more detail at [install](./hosted-install) ### Application URL. Your website can be displayed in an iFrame on the obniz cloud by setting it up. Your URLs will be displayed in the ``` https://yoursite.com/ ``` When a user selects an app from the "In Use" list, a link with the user's oauth token will open the web site. ``` https://yoursite.com/?token=XXXX ``` Also, if you press "Open App" per device, an obniz_id will be added. ``` https://yoursite.com/?token=XXXX&obniz_id=YYYY ``` You can display a web site that addresses these Users will be able to open a specific page on your website right away without having to log in or select a device. ### Installation Settings. This is the setting item for users to install this app. If nothing is set, users can install the app at the touch of a button. For example, you can set the interval between data fetching at the time of installation. You can use the API to retrieve the settings your users have made during the installation process. ## Creation and tokens. Once the app is created, you will be able to see the app's id and token. At this stage, you can use the API whether it's public or private to the store. Even if no one has installed it, you can use it now if it's just an API call to get information about your app. You can also use it right away to get the OAuth Token of a user or let the user install the app. ## SDK We provide the obniz-app-sdk, which contains the basic functions needed to create an app. - Registration of programs for each obniz device - Respond to new installations/updates/deletions in the obniz cloud - Load balancing by multiple servers using Redis Please refer to [README on github](https://github.com/obniz/obniz-app-sdk) for how to use it. --- ## Hosted App: OAuth URL: https://obniz.com/reference/cloud/app/oauth In order to gain access to your App, you need to ask your users to approve it. There is a sample project on Github that demonstrates the sequence of events. [https://github.com/obniz/obniz-webapp-example-oauth](https://github.com/obniz/obniz-webapp-example-oauth) ### Approval flow 1. Have the user open the authorization URL Ask the user to open the following authorization URL. https://obniz.com/login/oauth/authorize?webapp\_id=wa\_NDI=&redirect\_uri=install webapp\_id: Your App id redirect\_uri: URL to redirect upon approval completion If the redirect\_uri is set to 'install', the user will be redirected to the screen to install your App after approval. 2. Getting a Token from code If you set the URL of your service in the redirect\_uri, you will receive a request with a query called code. You can get the OAuthToken for this user by using this code.Send a POST request to the following URL. `https://obniz.com/login/oauth/token?code=${code}` The token included in the response is this user's token. ### Using the API The API can be used by using the OAuthToken obtained. Please refer to the [obniz cloud API](/reference/cloud/cloudapi/) for more information. ### Change of Authority If your app's permissions change after the user approves your app (the repository goes from read to full), the user's permissions will remain the same (read). In this case, the user will have to remove the authorization once and re-approve it. ### Deletion of approval The user can remove the authorization at any time. If the user approves again, the token will be a different value. If it is deleted, the token will be invalid, and if the user approves again, the token will be a different value. --- ## Hosted App: Install URL: https://obniz.com/reference/cloud/app/hosted-install Users who approve your app will be able to "install" the app on their devices. If your app has a configuration item, users will set it during installation. For example, if it was a hosted app that says "Notify Slack if any of the obniz in your account goes offline", the user would first approve the app and install it on a device called obnizID XXXX-XXX and then install it on another device called YYYY-YYY for a total of 2 installations. ! [](images/webapp_install.png) ### Getting Installation Information in the App Token You can get information about installed apps using only the app token, not the OAuth token for each user. ### Development of database-free web services. With this installation, you can leave the management of OAuth and configuration information for each user in the database to obniz cloud instead of your own server. All the users of your app will be able to get all the information that they have installed and set up at once and run your app. This allows you to create an app with the following flow 1. get installation information from obniz cloud by API using app token when the program is launched on server Run the app for each installation information. 3. dynamically add/remove apps with webhooks as users install/uninstall 4. scale out if there are not enough server machines, and vice versa, reduce if there are too many ## Webhook. Webhook lets you know what users are doing to your Spp. ### Setting In the App settings screen, there is an item called webhook. Fill in the URL you want to receive the webhook in this part, and the webhook will be done with the POST method ### Timing The webhook is a POST method and the body is a json and the format is as follows. ``` { type: 'install.create' } ``` - type: key of what prompted this webhook. - data: Data based on type. The type can be one of the following - oauth.create Your user has approved your App - oauth.delete User has removed your App authorization. - install.create The user has installed your App - install.update A user has changed your App settings. - install.delete A user has uninstalled your App. ### About Retry Even if the response to Webhook is not 200 series, we do not retry. --- ## Pipeline App URL: https://obniz.com/reference/cloud/app/pipeline Pipeline apps have the ability to relay data acquired from sensors to a specific server, etc. ## Create an app From the developer console, select "Development" > "App Development" > "Pipeline App" and enter the necessary information. After creation, detailed settings can be configured. ## Connected devices You can add devices you want to connect to and detect from "Add Device". After selecting the devices, you can set the MAC address and other settings, and choose whether to connect to the selected devices unconditionally or only to specific devices. The conditions that can be set are - UUID (iBeacon's UUID) - MAC address (MAC address of the device to connect to) - Local Name (Local name of the device to connect to) You can set any of the above. ## Destination From "Add destination", you can add a destination to send the data acquired from the connected device. ## About Amazon SQS | key | value | | - | - | | accessKeyId | Please enter the key you obtained from IAM | | secretAccessKey | Please enter the key you obtained from IAM | | url | Please enter a key that starts with `https://sqs.`, which will be displayed after the queue is created | ### About Amazon Kinesis You can use Amazon Kinesis Data Streams. | key | value | | - | - | | region | Please select your AWS region | | accessKeyId | Please enter the key you obtained from IAM | | secretAccessKey | Please enter the key you obtained from IAM | | stream | Please enter the data stream name configured in AWS | | shard | Please enter the number of shards to be used | ### About Azure IoT Central | key | value | | - | - | | deviceId | From the side menu of IoT Central, "Devices" > "All devices" > "Device ID" | | scopeId | From the side menu of IoT Central, "Administration" > "Device connection" > "Enrollment groups" > "Enrollment group details" | | sasKey | Enter the primary key, which is located in the same place as the scopeId | ### About MQTT Please enter the connection information of the server you will be using. ### About REST API The REST API is used to send data to the server you specify. It is sent as a POST and contains at least the following information in the header. ``` Content-Type: application/json ``` --- ## WebApp URL: https://obniz.com/reference/cloud/app/webapp By installing an app in the WebApp store, you can use a variety of services without programming them. ## Types of WebApps There are three types of WebApps. HTML An HTML application is an application that runs in a browser. It's an application that utilizes a GUI that can be used while it's open in a browser. サーバーレスイベント It is an application that can be selected as an execution program when a serverless event occurs. The program is executed on the server when the event occurs. ホステッド The app is hosted on a server. When installed, it is always running on the server. In order to use a hosted app, you need to grant the app access to your account. ## Create WebApp ### API Managed It is also possible to create and publish a WebApp (only hosted). The accounts of users (including myself) who have acquired authentication (OAuth) can be acquired and operated via the API. This includes owned devices and serverless events. [See more about obniz Cloud API](/reference/cloud/cloudapi/) ### Use Install You can also have your app installed on your account with the approval of other users. The installation status is managed by the obniz cloud and can be acquired by the above API, making it easy to build and scale out web services. You can easily build a cloud service by releasing your WebApp to the public. ### Sample Codes WebApp sample code is available on GitHub. Using OAuth to manipulate user and device information [https://github.com/obniz/obniz-webapp-example-oauth](https://github.com/obniz/obniz-webapp-example-oauth) How to use Install to obtain user-installed app information and develop web services [https://github.com/obniz/obniz-webapp-example-install](https://github.com/obniz/obniz-webapp-example-install) --- ## Install an App URL: https://obniz.com/reference/cloud/app/install To use the app - Create an account - Register (or create) an account for the device you want to use is required. To create an account, go to [Sign In](https://console.obniz.com/users/signin) in the developer console and register an account. To register a device, register a device to your account if it is an official device, or create a device on the cloud if you want to create it by yourself using obnizOS. For more information about registration, please see [Device Management](/reference/cloud/device-management/). ## Install the public App. Select the app you want to use from [Explore app](https://console.obniz.com/webapp/). Click the install button in the upper right corner of the app details page to go to the app settings screen. When installing the app, fill in the required fields and click the "Install" button. ## Install your own app. You can install the application from "Application Development" by clicking the install button of the application you developed. ## Installation Settings If the app has installation settings, you will need to fill in each of these fields during the installation process. In a program, you can get the settings that the user made and reflect them in the program. For browser apps, you can get them from `Obniz.App.configs()`. ```javascript const configs = Obniz.App.configs(); console.log(configs.watering_interval); // User configured value ``` Hosted apps are included in each installation of the GraphQL API. --- ## Publish an App URL: https://obniz.com/reference/cloud/app/publishment You can publish your WebApp to the [WebApp Store](https://console.obniz.com/webapp). ## How to publish You can publish your app to the WebApp Store by checking the "Publish Program" checkbox in the app settings and updating the settings. When you publish an app, other users can install the app or fork and view the program. WebApps can get tokens and install them with the user's approval even if they are not published on the store. ## Public Information - Program the app - Author Name [Account Name] - Icon [optional / Less than 500KB / JPEG and PNG formats of 150px×150px or more are recommended] - App Overview [optional] - Detailed description of the App [optional] - Preparation and How to use [optional] - Thumbnail Images [optional] - Category [optional] ### Notes Please check [Terms](/support/terms/terms) and [Privacy Policy](/support/terms/privacy_policy) before publishing and using the application. --- ## Paid App URL: https://obniz.com/reference/cloud/app/billing When you install a paid App, you will be charged on a pay-as-you-go basis based on the number of installations. The app is free. Unlike the free Apps, you must register payment information in your account. Currently, the only apps users can create are free. ## Calculation Method As with the obniz device calculation method, you will be charged for the number of installs in the same month. The following is a list of the most important information ### More pay-as-you-go (non-staged) Monthly fee per installation is fixed regardless of the number of installations. For example, if the monthly fee is 100 yen per installation, the monthly fee is 1,000 yen for 10 installations. ### More pay-as-you-go (tiered) Tiered fee structure depending on the number of installations. For example, in the case of 1-100 installs, the fee is 500 yen per month for 1 to 100 installs. The same price is available for the same price of 500 yen per month up to and including --- ## API Key URL: https://obniz.com/reference/cloud/apikeys [API key](https://console.obniz.com/apikeys) is a key to operate the obniz cloud API and is used to access the You will be able Retrieve information about obniz devices in your account from the cloud system or issue devices As well as being able to do so, this key is all you need to connect to the device in obniz.js. devices. ![](./images/apikeylist.png) ## Enabled APIs - [obniz cloud API](/reference/cloud/cloudapi/) - [obniz Hardware Websocket API](/reference/cloud/hardware-api/websocket-api/) - [obniz Hardware REST API](/reference/cloud/hardware-api/rest-api/) You can use the token issued by the API key with each API. ## Privileges API keys can be issued with privileges. **Account** Using the Cloud API, you can use the Do you only read or update or create for user information and serverless events. You can choose how far you can go. **Device Control** Hardware API to connect to the devices in your account via obniz.js or other methods. can be set. ![](./images/apikeyauth.png) ## Change key permissions and delete keys Privilege changes and deletions are reflected immediately. However, if you are connected to a device with the Websocket API, you can't change or delete permissions. If you do, it will be applied to the next connection. --- ## Account URL: https://obniz.com/reference/cloud/account By activating an account on the cloud, a user will be able to access/use cloud functions. Featured Functions - Device Management(obnizOS version up, Issuing an access token) - Event function - Repository function - Webapp ## Create an account An account can be created on [Signup](https://console.obniz.com/users/signin) page by using email or SNS account. ## Adding payment method [Developer's console](https://console.obniz.com) > [Billing](https://console.obniz.com/settings/billing) to add a payment method to your account. Before buying, Your account must have a email. Proceed [Account Setting](https://console.obniz.com/settings/) to configure. --- ## Two Step Authentication URL: https://obniz.com/reference/cloud/account/twostep Two-step verification is available for sign-in using email and password. By setting this up, you can take security measures against brute force attacks and password leaks. ## How to set it up From the developer console, select "Accounts" and you will see an item called "2-step verification". Check the box and update it, and after the next time you sign in, an email will be sent to your registered address after you enter the correct password. You can sign in by typing in the text in the email. --- ## Billing URL: https://obniz.com/reference/cloud/account/billing ## About Payment method ### Credit card payment Payment is generally processed only by credit card. But in some situation you might do a payment by invoice. Please [contact us](https://obniz.zendesk.com/hc/ja/requests/new) for more details. ### Register payment method You can register up to two payment methods on [Billing](https://console.obniz.com/settings/billing). Payment method with "default" mark is subject to be charged. ### Remove payment method You can remove a payment method on [Billing](https://console.obniz.com/settings/billing). But in a case that you have only one payment method registered it's impossible to remove it, because there would be otherwise no payment method. ### Change payment method From the security point of view, you're not allowed to change the information of your payment method. I'm sorry to troble you, but if you wish to do that, please register it as a new payment method and remove the old one. You can update the information by this swapping, such as an expiration date or an address. ### When payment fails to be processed When a payment never finishes successfully for some reason, system will retry that billing process later on. Failing the retry process sometimes results in making a second payment method "default" and billing to that newly-defaulted payment method. ## Pricing **You will be charged monthly based on the number of devices used** Cloud usage fees are paid on a monthly basis for the number of devices used during the month. Devices can be added at any time from the Developer's console. - You can always switch between Active / Inactive on the Device Setting. Please see [Active/Inactive](/reference/cloud/device-management/active-inactive) for how to set. When Inactive, not be charged. - Usage fees vary by device. Please check [Pricing](https://iot.obniz.com/pricing) for details. ## Billing date **Month-end closing with payment the following month** ![](images/account_invoice_period_en.png) ## Cancel **You will be billed when the device key generation is complete** When adding a device, it is registered in an Active state. The maximum number of the device that became Active during the month is eligible for payment. You cannot cancel registered devices. By changing the setting to Inactive status, you will not be charged for the next month. Please see [Active/Inactive](/reference/cloud/device-management/active-inactive) for how to set Active/Inactive. ## About Credit Points Credit Points granted to the account can be used as cloud usage fees (1point = 1 JPY). If there is a Credit Points balance, it is automatically deducted as a usage fee, and when the Credit Points becomes 0, the credit card is charged. ## Other notes - All prices listed on this site are tax-excluded. Taxes according to the country / region to which you belong will be added to the price presented at the time of purchase. - If various tax rates (consumption tax rates, etc.) are changed during the contract period, they will be applied at the next renewal. - The service starts when the purchase process is complete. - The price change will be announced in advance on the website. * * * ## FAQ #### Q. Where can I check the usage status? A.You can check past charges and usage status for the current month on [Billing](https://console.obniz.com/settings/billing). #### Q. Is there any payment method other than credit card? A. We might support invoice payment for you. Please [talk to us](https://obniz.zendesk.com/hc/ja/requests/new). #### Q.What happens when my credit card expires? A. If a card that expires is your "default" payment method and payment never succeeds, then it'll raise a situation that you can't use obniz system. But in a case that you've registered two payment methods, it'll sometimes occur to switch your "default" indication to the other card and try to put a bill on that newly-defaulted card. When a payment is properly done this time, then you can keep using obniz system.(If your credit card issuer is participating in an automatic credit card renewal network, the card expiration date will be automatically updated) --- ## Team URL: https://obniz.com/reference/cloud/account/team Team accounts are useful when managing obniz in an organization. A team account is a single, independent account that allows authorized members of the organization to view and modify the settings of a single device. It can also be used to communicate the status of a device to external members by using read-only permissions. You cannot log in directly to your team account, and team members will have to log in to their own accounts before switching to their team accounts. Featured Functions - Creating a team account - Add / Remove Team Members - Managing team member privileges - Switch to team account Team accounts are independent accounts, so they can be used just like regular accounts. - Adding billing information - Register or add devices - Register and add apps You can also do things like ## Creating a team Log in to the Developer Console with the account of the person who will be the owner of the team account. Select the "Create team" menu item from the user menu in the upper left corner. ![](./images/menu-3.png) Enter the team name and press the create button ![](./images/create-team.png) A team will be created and automatically switched to a team account ## How to switch between team account and personal account You can switch accounts at any time from the user icon in the upper right of the developer console. ![](./images/menu-2.png) ## Member management After switching to a team account, You can manage your team members by selecting "Members" in "Team Settings" from the left navigation bar. ![](./images/member.png) ## Transfer devices If you would like to transfer device owned by your personal account to your team account, please click [here](/reference/cloud/device-management/transfer). ## Transfer apps If you would like to transfer apps owned by your personal account to your team account, please contact our support team. --- ## Repository(Legacy) URL: https://obniz.com/reference/cloud/repository Repository is a storage service. It can be used for storage of html and xml of online editor. It's also can be used for data stroage for serverless event. ## Capacity Cpacity of repository depends on devices an account has. LiteBusiness 5MB × Number of Active device5MB × Number of Active device ## Public and Private Expose setting can be choosed for each file at creation. "Public Page" can see whole public file you have. Anyone can access the page. ![](images/repository-accseelevel.png) ## Repository Page Repository Page is listed in Developer's console. ![](images/repository.png) In the page, You can create/edit/delete a file. You can open and edit on online editor for .html .js .xml file. If you have local file like image, You can upload them from "Upload" to repository. ## REST API Repository API is available. Your program may store and restore data to your repository. [obniz Cloud Repository API](/reference/cloud/repository/api) --- ## API URL: https://obniz.com/reference/cloud/repository/api Cloud users are granted to use cloud data storage. Storage capacity will be increased by devices an account has and other reasons. Also, It provide REST API. ## Upload Uploading a file to repository with a file. ``` POST /users/me/repo/{file_name} ``` ### Request Parameter Name Type Optional Description access\_token Cookie Required String of user's access token file Body/Multipart-form Required The file to be uploaded ### Response json format. Status Description 200 Success 400 Format Error 403 Invalid access token / capacity full ## Download Download a file from repository. ``` GET /users/me/repo/{file_name} ``` or ``` GET /users/{user_id}/repo/{file_name} ``` ### Request Parameter Name Type Optional Description access\_token Cookie Optional String of user's access token ### Response File it self. octet-stream. Status Description 200 Success 403 Invalid access token / capacity full 404 Not Found --- ## Serverless Event URL: https://obniz.com/reference/cloud/serverless-event obniz Cloud runs your program on the cloud automatically using a trigger. Every 1 hours, when webhoook called, when an obniz become online, can be used as trigger. See more at [Triggers](/obniz_cloud/event_triggers) ## Specifications Maximum number of event you can register is depends on kind and number of devices an account has. Each Event can be run up to 150 times per day(10 minutes is the minimal interval). Programs to be registered can only be chosen from the user's repository, or installed web apps. Private files can also be chosen. When a trigger occurs, obniz Event will open the registered HTML on a browser within the server and activate JavaScript. To stop, call `done()` from your js. Otherwise, obniz Event will close HTML automatically after 30 seconds. For Webhook, GET/POST can be used. For query string and post, body can be acquired from js. After execution, execution logs become available on Event detail page. The capacity of the log storage is 1MB for each. See more at [Setup](/obniz_cloud/event_setup). --- ## Serverless Event Triggers URL: https://obniz.com/reference/cloud/serverless-event/triggers You can choose one of triggers from below 1. Webhook 2. Scheduled Time 3. Scheduled Interval 4. obniz online 5. Switch on a device pressed obniz Board: Switch pressed M5StickC: "M5" printed button pressed --- ## Serverless Event Setup URL: https://obniz.com/reference/cloud/serverless-event/setup (Before Start you need [account](/obniz_cloud/about_cloud_account) and having at least one [Device](/reference/cloud/device-management/)) Prepare a program. You can use [Webapp](/reference/cloud/app/). Or write a program on your repository. Program executed on cloud can use two special properties in javascript. - `done()` call when done. - `req` request object passed from Webhook request #### done() Please call done() after your task is done. Below is a convenient way of calling done, which allows you to finish the task smoothly even on the program page. ``` if(typeof done === "function") { done(); } ``` #### req You can get query and body that were called by webhook through req object. ``` let request = {}; if (typeof req === "object") { request = req; } console.log(request.query); console.log(request.body); ``` Query and body are parsed objects. For example, when you access `https://obniz.com/events/X/XXXXXX/run?a=1&b=stringdata`, `request.query` is `{a:1, b:"stirngdata " }`. When the requested body is `{"c":true, "d":100}`, `{c:true, d:100}` gets (parsed) to the body. If the request is not in JSON string, the body ends up being undefined. ## Registrate an event After you finish programming and confirm that it works, register the program in a new Event. Create the Event by clicking "Create New" on [Developer's console](https://console.obniz.com). Type in the names, and select HTML to run as well as a trigger type. ![](images/create_event.png) Press "Create" to complete the process. If you choose webhook, an url for webhook will be shown. ### Test When you want to execute a program right away without a trigger, you can manually execute the program by clicking "Test Run Now" button on the Event page. ![](images/event_testbutton.png) --- ## Event Logs URL: https://obniz.com/reference/cloud/serverless-event/logs You can check every log after execution on the log list on the Event page. To check details, click the files with the execution date you wish to check. ## Storage Limitations Huge log file, around over 10 kbyte, will be discarded. And old over 7days logs will be discarded. --- ## Operating Environment URL: https://obniz.com/reference/cloud/operating-environment obniz Cloud require JavaScript ES 2017. It doesn't work on old browsers. For example [https://caniuse.com/#search=await](https://caniuse.com/#search=await). ## Download Latest Browser If your browser is old, Please consider update/install latest. Modern browser is free. Please download Latest one. [Download Google Chrome](https://www.google.com/chrome/) [Download FireFox](https://www.mozilla.org/) ## Compatible/Tested Versions ### Windows (Windows10) Browser Version Tested Edge 93.0.961.47 93.0.961.47 Google Chrome 93.0.4577.63 93.0.4577.63 FireFox 92.0.1 92.0.1 ### Mac Browser Version Tested Safari 14.1.2 14.1.2 Google Chrome 93.0.4577.63 93.0.4577.63 FireFox 92.0.1 92.0.1 ### iOS Browser Version Tested Safari 14.1.2 14.1.2 ### Android Browser Version Tested Google Chrome 93.0.4577.82 93.0.4577.82 FireFox 92.1.1 92.1.1 --- ## obniz.js URL: https://obniz.com/reference/common SDK for controlling [obniz enabled Devices](https://obniz.com/) using obniz websocket API from JavaScript. It works on both browser and nodejs. ### Source [GitHub](https://github.com/obniz/obniz/) ## Example ```typescript import * as Obniz from 'obniz' const obniz = new Obniz("0000-0000", { access_token: 'xxxx' }); obniz.onconnect = async () => { obniz.display.print("hello!"); obniz.switch.onchange = (state: string) => { console.log(state); } const servo = obniz.wired("ServoMotor", {gnd:0, vcc:1, signal:2}); servo.angle(90); } ``` ### Example: Browser ```html send ``` ## API | Category | Function/Property | Minimum Support OS | Class Reference | |:-----|:--------|:---|:-----------------| | Connection | [new Obniz()](./connection) | 1.0.0 | [obnizcore.Obniz](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#constructor) | | | [obniz.onconnect](./connection) | 1.0.0 | | | | [obniz.onclose](./connection) | 1.0.0 | | | | [obniz.autoConnect()](./) | 1.0.0 | [obnizcore.Obniz](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html) | | | [obniz.connect()](./connection) | 1.0.0 | | | | [obniz.close()](./connection) | 1.0.0 | | | | [obniz.onloop](./connection) | 1.0.0 | | | | [obniz.setLoopInterval()](./connection) | 1.0.0 | | | | [obniz.connected_network](./connected_network) | 1.0.0 | [obnizcore.Obniz#constructor](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#constructor) | | | [obniz.pingWait()](./) | 1.0.0 | [obnizcore.Obniz](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html) | | | [obniz.keepWorkingAtOffline()](./connection) | 1.0.0 | | | | [obniz.resetOnDisconnect()](./connection) | 1.0.0 | | | | [obniz.boot_reason](./connection) | 7.0.0 | | | Queue | [obniz.setClock()](./) | 7.0.0 | | | | [obniz.setQueueMode()](./) | 7.0.0 | | | | [obniz.deviceTimestamp](./) | 7.0.0 | | | Debug | [obniz.debugprint](./) | 2.0.0 | | | Hardware | [obniz.id](./) | 1.0.0 | [obnizcore.Obniz](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html) | | | [obniz.firmware_ver](./) | 1.0.0 | [obnizcore.Obniz](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html) | | | [obniz.version](./) | 1.0.0 | [obnizcore.Obniz](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html) | | | [obniz.reboot()](./) | 1.0.0 | [obnizcore.Obniz](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html) | | | [obniz.wait()](./) | 1.0.0 | [obnizcore.Obniz](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html) | | | [obniz.sleepMinutes()](./sleep) | 2.0.0 | | | | [obniz.sleepSeconds()](./sleep) | 2.0.0 | | | | [obniz.sleepIoTrigger()](./sleep) | 2.0.0 | | | Components | [obniz.components.prepare()](./) | 7.0.0 | | | | [obniz.components.powerOnInterface()](./) | 7.0.0 | | | | [obniz.components.powerOffAllInterfaces()](./) | 7.0.0 | | | | [obniz.components.isRS232HavingTargetWait()](./) | 7.0.0 | | | | [obniz.components.startMonitoringPowerSupply()](./) | 7.0.0 | | | | [obniz.components.getPowerSupplyVoltageWait()](./) | 7.0.0 | | | | [obniz.components.setRelay()](./) | 7.0.0 | | | Motion | [obniz.motion.start()](./) | 7.0.0 | | | | [obniz.motion.onAccelerationUpdate()](./) | 7.0.0 | | | | [obniz.motion.onRecognitionUpdate](./) | 7.0.0 | | | | [obniz.motion.onTemperatureUpdate()](./) | 7.0.0 | | | | [obniz.motion.getAccelerationWait()](./) | 7.0.0 | | | | [obniz.motion.getRecognitionWait()](./) | 7.0.0 | | | | [obniz.motion.getTemperatureWait()](./) | 7.0.0 | | | Location | [obniz.location.start()](./) | 7.0.0 experimental | | | | [obniz.location.onupdate](./) | 7.0.0 experimental | | | obnizCloud | [obniz.metadata](./metadata) | | [obnizcore.Obniz#metadata](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#metadata) | | | [obniz.onmessage](./messaging) | | [obnizcore.Obniz#onmessage](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#onmessage) | | io | [obniz.ioX](./io) | 1.0.0 | [obnizcore.components.peripheralio](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralio.html) | | | [obniz.ioX.output()](./io) | 1.0.0 | | | | [obniz.ioX.inputWait()](./io) | 1.0.0 | | | | [obniz.ioX.input()](./io) | 1.0.0 | | | | [obniz.ioX.pull()](./io) | 1.0.0 | | | | [obniz.ioX.drive()](./io) | 1.0.0 | | | | [obniz.ioX.end()](./io) | 1.0.0 | | | io.animation | [obniz.io.animation()](./io-animation) | 1.0.0 | [obnizcore.components.directive](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.directive.html) | | | [obniz.io.repeatWait()](./io-animation) | 1.0.0 | [obnizcore.components.directive](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.directive.html) | | ad | [obniz.adX.start()](./ad) | 1.0.0 | [obnizcore.components.peripheralad](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralad.html) | | | [obniz.adX.getWait()](./ad) | 1.0.0 | [obnizcore.components.peripheralad](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralad.html) | | pwm | [obniz.pwmX.start()](./pwm) | 1.0.0 | [obnizcore.components.peripheralpwm](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralpwm.html) | | | [obniz.pwmX.freq()](./pwm) | 1.0.0 | [obnizcore.components.peripheralpwm](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralpwm.html) | | | [obniz.pwmX.duty()](./pwm) | 1.0.0 | [obnizcore.components.peripheralpwm](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralpwm.html) | | | [obniz.pwmX.modulate()](./pwm) | 1.0.0 | [obnizcore.components.peripheralpwm](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralpwm.html) | | uart | [obniz.uartX.start()](./uart) | 1.0.0 | [obnizcore.components.peripheraluart](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheraluart.html) | | | [obniz.uartX.send()](./uart) | 1.0.0 | [obnizcore.components.peripheraluart](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheraluart.html) | | | [obniz.uartX.setDE()](./uart) | 1.0.0 | [obnizcore.components.peripheraluart](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheraluart.html) | | | [obniz.uartX.onreceive](./uart) | 1.0.0 | [obnizcore.components.peripheraluart](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheraluart.html) | | spi | [obniz.spiX.start()](./spi) | 1.0.0 | [obnizcore.components.peripheralspi](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralspi.html) | | | [obniz.spiX.write()](./spi) | 1.0.0 | [obnizcore.components.peripheralspi](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralspi.html) | | | [obniz.spiX.writeWait()](./spi) | 1.0.0 | [obnizcore.components.peripheralspi](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralspi.html) | | | [obniz.spiX.end()](./spi) | 1.0.0 | [obnizcore.components.peripheralspi](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralspi.html) | | i2c | [obniz.i2cX.start()](./i2c) | 1.0.0 | [obnizcore.components.peripherali2c](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripherali2c.html) | | | [obniz.i2cX.write()](./i2c) | 1.0.0 | [obnizcore.components.peripherali2c](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripherali2c.html) | | | [obniz.i2cX.readWait()](./i2c) | 1.0.0 | [obnizcore.components.peripherali2c](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripherali2c.html) | | | [obniz.i2cX.onwritten](./i2c) | 1.0.0 | [obnizcore.components.peripherali2c](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripherali2c.html) | | canbus | [obniz.canbusX.start()](./can) | 7.0.0 | [obnizcore.components.peripheralcanbus](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralcanbus.html) | | | [obniz.canbusX.send()](./can) | 7.0.0 | [obnizcore.components.peripheralcanbus](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralcanbus.html) | | | [obniz.canbusX.onreceive](./can) | 7.0.0 | [obnizcore.components.peripheralcanbus](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralcanbus.html) | | ble | [obniz.ble ( See Details )](./ble) | 1.0.0 | [obnizcore.components.ble.hci.obnizble](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.obnizble.html) | | logicAnalyzer | [obniz.logicAnalyzer.start()](./logicanalyzer) | 1.0.0 | [obnizcore.components.logicanalyzer](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.logicanalyzer.html) | | | [obniz.logicAnalyzer.onmeasured](./logicanalyzer) | 1.0.0 | [obnizcore.components.logicanalyzer](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.logicanalyzer.html) | | measure | [obniz.measure.echo()](./measurement) | 1.0.0 | [obnizcore.components.obnizmeasure](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.obnizmeasure.html) | | display | [obniz.display ( See Details )](./display) | 1.0.0 | [obnizcore.components.display](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html) | | switch | [obniz.switch.getWait()](./switch) | 1.0.0 | [obnizcore.components.obnizswitch](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.obnizswitch.html) | | | [obniz.switch.onchange](./switch) | 1.0.0 | [obnizcore.components.obnizswitch](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.obnizswitch.html) | | tcp | [obniz.tcp ( See Details )](./tcp) | - | [obnizcore.components.tcp](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.tcp.html) | | wifi | [obniz.wifi.scanWait()](./wifi) | 2.0.0 | [obnizcore.components.wifi](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.wifi.html) | | plugin | [obniz.plugin.send()](./plugin) | 2.0.0 | [obnizcore.components.plugin](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.plugin.html) | | | [obniz.plugin.onreceive](./plugin) | 2.0.0 | [obnizcore.components.plugin](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.plugin.html) | | | [obniz.plugin.onFrameStart](./plugin) | 7.0.0 | [obnizcore.components.plugin](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.plugin.html) | | | [obniz.plugin.onFrameEnd](./plugin) | 7.0.0 | [obnizcore.components.plugin](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.plugin.html) | | | [obniz.plugin.execLua()](./plugin) | 7.0.0 | [obnizcore.components.plugin](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.plugin.html) | | | [obniz.plugin.reloadLua()](./plugin) | 7.0.0 | [obnizcore.components.plugin](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.plugin.html) | | | [obniz.plugin_name](./plugin) | 7.0.0 | [obnizcore.components.plugin](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.plugin.html) | | storage | [obniz.storage.save()](./plugin) | 7.0.0 | [obnizcore.components.plugin](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.plugin.html) | | | [obniz.storage.savePluginLua()](./plugin) | 7.0.0 | [obnizcore.components.plugin](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.plugin.html) | | | [obniz.storage.readWait()](./plugin) | 7.0.0 | [obnizcore.components.plugin](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.plugin.html) | ## Installation ### Browser Add the following script tag to your html ```html ``` ### Nodejs Install obniz via npm ```shell npm install obniz ``` and import it to js file. ```javascript const Obniz = require('obniz'); ``` ## Connect The details are on [Connection](./connection) To use obniz, instantiate obniz with obniz id, and set onconnect callback function. It will be called when connected to obniz successfully. ```javascript var obniz = new Obniz("0000-0000"); obniz.onconnect = async function () { } ``` You can use everything on obniz Device after connection succeeds. ```javascript var obniz = new Obniz("0000-0000", { access_token: 'xxxx' }); obniz.onconnect = async function () { obniz.display.print("hello!"); obniz.switch.onchange = function(state) { if (state === "push") { obniz.display.print("Button Pressed"); } } } obniz.onloop = async function () { // called continuously } obniz.onclose = async function () { // called after connection lost } ``` and its io peripherals too can be used ```javascript var obniz = new Obniz("0000-0000", { access_token: 'xxxx' }); obniz.onconnect = async function () { obniz.io0.drive("5v"); obniz.io0.output(true) obniz.io1.pull("3v"); obniz.io1.drive("open-drain"); obniz.io1.output(false); obniz.io2.drive("3v"); obniz.io2.output(true); obniz.ad3.start(function(voltage){ console.log("changed to "+voltage+" v") }); var pwm = obniz.getFreePwm(); pwm.start({io: 4}); pwm.freq(1000); pwm.duty(50); var uart = obniz.getFreeUart(); uart.start({tx: 5, rx: 6, baud:9600}); uart.onreceive = function(data, text) { console.log(data); } uart.send("Hello"); } ``` ## Parts library The parts library is embedded in obniz.js. All parts and their details can be found there. [obniz Parts Library](https://obniz.com/sdk/parts/) To use the connected parts, instantiate the parts in onconnect callback function and use it. The function list can be found on [obniz Parts Library](https://obniz.com/sdk/parts/). For example, LED is found here [https://obniz.com/sdk/parts/LED](https://obniz.com/sdk/parts/LED) ```javascript var obniz = new Obniz("0000-0000", { access_token: 'xxxx' }); obniz.onconnect = async function () { var led = obniz.wired("LED", {anode:0, cathode:1}); led.blink(); } ``` HC-SR40(distance measure) [https://obniz.com/sdk/parts/HC-SR04](https://obniz.com/sdk/parts/HC-SR04) ```javascript var obniz = new Obniz("0000-0000"); obniz.onconnect = async function () { var hcsr04 = obniz.wired("HC-SR04", {gnd:0, echo:1, trigger:2, vcc:3}); hcsr04.unit("inch"); hcsr04.measure(function( distance ){ console.log("distance " + distance + " inch") }) } ``` ## Example: browser integrates hardware Easy to integrate UI and hardware on html ```html ``` ## Example: integrate web services Easy to integrate web services like Dropbox and Twitter and hardware. ```javascript // save data from obniz to dropbox var obniz = new Obniz("0000-0000", { access_token: 'xxxx' }); obniz.onconnect = async function () { var dbx = new Dropbox({ accessToken: '' }); var button = obniz.wired("Button", {signal:0, gnd:1}); button.onchange = function(pressed){ if (pressed) {   dbx.filesUpload({path: '/obniz.txt', contents: "[Button Pressed]\n" + new Date(), mode: 'overwrite' }); } }; } ``` ## Example: integrate two or more obniz Two or more device integration. ```javascript // control servomotor from potention meter which connected to another obniz. var obnizA = new Obniz("0000-0000", { access_token: 'xxxx' }); obnizA.onconnect = async function () { var obnizB = new Obniz("0000-0001", { access_token: 'xxxx' }); obnizB.onconnect = async function(){ var meter = obnizA.wired("Potentiometer", 0, 1, 2); var servo = obnizB.wired("ServoMotor", 0, 1, 2); meter.onchange = function(position) { servo.angle(position * 180); }; } } ``` --- ## Class Obniz URL: https://obniz.com/reference/common/class > [Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html) The Obniz class contains all the features of the SDK. In the case of HTML, it is a global variable; in the case of JS and Typescript, the following is the obniz class. ``` var Obniz = require('obniz'); ```` TypeScript ```` import Obniz from 'obniz'; ```` The class reference is available on Github. ## Instances and Devices. An instance that takes the place of an obniz device is instantiated with an Obniz ID and other arguments. After instantiation, the connection to the device is made automatically and onconnect() is called when the connection is completed (see [connection](../connection) for details). ```` var obniz = new Obniz('1234-5678'); obniz.onconnect = async function() { obniz.io0.output(true); } ```` When the connection is complete, the instance receives information about the device (what IOs it has, ADs, etc.) from the obniz cloud and configures itself. It doesn't know what the device is until it is connected, so it doesn't have any properties about the device operation. ``` var obniz = new Obniz('1234-5678'); obniz.io0.output(true); // => error (io0 is undefined) obniz.onconnect = async function() { obniz.io0.output(true); // => If io0 is a device with an io0, it works fine. } ```` ## Predefined devices. Some devices, such as the M5StickC, have their on-board sensors registered in advance, and each sensor is automatically initialized and ready for use as soon as the device is connected. The following is an example of the M5StickC's acceleration and gyroscope sensors. ```` var obniz = new Obniz.M5StickC('1234-5678'); obniz.onconnect = async function() { const data = await obniz.imu.getAllDataWait(); console.log('accelerometer: %o', data.accelerometer); console.log('gyroscope: %o', data.gyroscope); } ```` Pre-defined devices available - [Obniz.M5StickC()](./m5stickc) - [Obniz.M5StackBasic()](./m5stackbasic) --- ## Obniz.M5StickC URL: https://obniz.com/reference/common/class/m5stickc > [クラスリファレンス](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.hardware.m5stickc.html) > [TypeScript](https://github.com/obniz/obniz/blob/master/src/obniz/libs/hw/m5stickc.ts) Obniz.M5StickC is a predefined class for M5StickC by M5. ## Defined Parts In this class, the devices in the [parts library](/ja/sdk/parts) are used to create The electronic components on the device (M5StickC) are pre-registered in the class. They are automatically initialized and ready for use when connected. ### axp Power Management [AXP192](https://obniz.github.io/obniz/obnizjs/classes/parts.axp192.axp192.html) ``` var obniz = new Obniz.M5StickC('OBNIZ_ID_HERE'); obniz.onconnect = async function() { const Vbat = await obniz.axp.getVbat(); } ``` ### buttonA Front [Button](/sdk/parts/Button/README.md) ``` var obniz = new Obniz.M5StickC('OBNIZ_ID_HERE'); obniz.onconnect = async function() { obniz.buttonA.onchange = () => { console.log("changed"); } } ``` ### buttonB Upper [Button](/sdk/parts/Button/README.md) ``` var obniz = new Obniz.M5StickC('OBNIZ_ID_HERE'); obniz.onconnect = async function() { obniz.buttonB.onchange = () => { console.log("changed"); } } ``` ### imu Accelerometer and gyroscope. the M5StickC has different built-in IMUs depending on the version. This library automatically detects and switches components. Only the IMU is not initialized automatically. Call `setupIMUWait()` once. - [MPU6886](/ja/sdk/parts/MPU6886/README.md) - [SH200Q](/ja/sdk/parts/SH200Q/README.md) ```` var obniz = new Obniz.M5StickC("OBNIZ_ID_HERE"); obniz.onconnect = async () => { await obniz.setupIMUWait(); const accel = await obniz.imu.getAccelWait(); const gyro = await obniz.imu.getGyroWait(); } ```` ### ir [Infrared LED](/sdk/parts/InfraredLED/README.md) ``` var obniz = new Obniz.M5StickC('OBNIZ_ID_HERE'); obniz.onconnect = async function() { obniz.ir.send([0x00, 0x01]); } ``` ### led RED [LED](/sdk/parts/LED/README.md) ``` var obniz = new Obniz.M5StickC('OBNIZ_ID_HERE'); obniz.onconnect = async function() { obniz.led.blink(); } ``` ## Interface Below interface is prepared ### grove0 Grove Connector on M5StickC ``` let obniz = new Obniz.M5StickC("OBNIZ_ID"); obniz.onconnect = async () => { const speaker = obniz.wired("Grove_Speaker", {grove: obniz.grove0}); speaker.play(1000); //1000hz await obniz.wait(1000); speaker.stop(); } ``` --- ## Obniz.M5StackBasic URL: https://obniz.com/reference/common/class/m5stackbasic > [Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.hardware.m5stackbasic.html) > [TypeScript](https://github.com/obniz/obniz/blob/master/src/obniz/libs/hw/m5stack_basic.ts) Obniz.M5StackBasic is a predefined class for M5's M5StackBasic. ## Defined Parts In this class, the devices in the [parts library](/ja/sdk/parts) are used to create The electronic components on the device (M5Stack Basic) are pre-registered in the class. They are automatically initialized and ready for use when connected. ### buttonA Left [Button](/sdk/parts/Button/README.md) ``` var obniz = new Obniz.M5StickC('OBNIZ_ID_HERE'); obniz.onconnect = async function() { obniz.buttonA.onchange = () => { console.log("changed"); } } ``` ### buttonB Center [Button](/sdk/parts/Button/README.md) ``` var obniz = new Obniz.M5StickC('OBNIZ_ID_HERE'); obniz.onconnect = async function() { obniz.buttonB.onchange = () => { console.log("changed"); } } ``` ### buttonC Right [Button](/sdk/parts/Button/README.md) ``` var obniz = new Obniz.M5StickC('OBNIZ_ID_HERE'); obniz.onconnect = async function() { obniz.buttonC.onchange = () => { console.log("changed"); } } ``` ## Interface Below interface is prepared ### grove0 Grove Connector on M5Stack Basic. ``` let obniz = new Obniz.M5StickC("OBNIZ_ID"); obniz.onconnect = async () => { const speaker = obniz.wired("Grove_Speaker", {grove: obniz.grove0}); speaker.play(1000); //1000hz await obniz.wait(1000); speaker.stop(); } ``` --- ## Connection URL: https://obniz.com/reference/common/connection > [Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#constructor) > [API Reference](/reference/websocket/ws) ## Connection The `Obniz` class is a class that represents a device created based on obnizID, and automatically starts connecting as soon as it is instantiated, and the function specified for onconnect is called when the connection succeeds, and the function specified for onclose is called when the connection is disconnected. When the connection is successful, the function specified in onconnect is called. Available device specification Type| Example | Description ---|---|--- obniz ID | `new Obniz('1234-5678')` | Simple obnizID in string. hypen is ignored obniz ID | `new Obniz('sn_AAAABBB')` | Specifying serial number. `sn_` prefix is required IP | `new Obniz('192.168.0.100')` | IPv4 of device. Only when device is on-premise mode. ```javascript // Javascript Full Example var obniz = new Obniz('1234-5678'); obniz.onconnect = async function() { } obniz.onclose = async function() { } ``` Operations like turning on/off an io becomes possible only after connection is established, so any operations you want device to undertake must be written in onconnect Operations written in onclose function never delivered to a device because connection is already lost. So you can't turn off a moving motor when disconnected. See more at Disconnection ```javascript // Javascript Full Example var obniz = new Obniz('1234-5678'); obniz.onconnect = async function() { obniz.io0.output(true); } ``` ##### Property You can configure settings at initialization [Reference](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.obnizoptions.html) ```javascript // Javascript Full Example new Obniz('1234-5678', { /* option here */ }) ``` #### AccessToken If the device has been issued an access token, the access token or the API key of the account that owns the device will be required for connection. These connection keys are specified as `access_token` as shown below. ```javascript // Javascript Full Example new Obniz('1234-5678', {access_token: 'your token here'}) ``` > If it is not specified, Websocket will not be able to connect and a 400 series error will occur. In the browser, errors such as `HTTP Authentication faild` will be displayed in the console. ##### Automatic Prompt If obniz id is incorrect, connection will never be established. In nodejs, an error occurs. In HTML, obniz.js shows a prompt message. The user can put in a correct obniz id into it. It shows up only when the format is invalid. If you specify obniz id which doesn't exist, this would never be shown. ![](images/2398be005895817611b2e739022a342b-1.png) ## Connection State Current connection state can be read from [connectionState](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#connectionstate) ```javascript // Javascript Full Example var obniz = new Obniz('1234-5678'); console.log(obniz.connectionState) // => === "connecting" or "closed" obniz.onconnect = async function() { console.log(obniz.connectionState) // => === "connected" } ``` ## Pre-configured Device We recommend you to use pre configured device classes. obniz.js will get device information like how many io it has when first connection established. ```javascript // Javascript Full Example new obniz = new Obniz("1234-5678") obniz.io0 // => undefined obniz.onconnect = async function() { obniz.io0 => exist if device has io0 } ``` obniz Board and M5StickC and other official devices are pre configured in obniz.js. You can find from here. [https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html) And below is M5StickC pre configured class reference. [https://obniz.github.io/obniz/obnizjs/classes/obnizcore.hardware.m5stickc.html](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.hardware.m5stickc.html) You can instantiate it like below method. Params are same as "new Obinz()" ```javascript // Javascript Full Example new obniz = new Obniz.M5StickC("1234-5678") ``` By using it, peripherals and internal sensors are pre configured. --- ## Disconnection And Reset URL: https://obniz.com/reference/common/connection/reset When device is disconnected from the internet or calling close() will cause disconnection. Then onclose will be called. Operations can't be delivered after disconnection, device or cloud will automatically reset the state. #### When device disconnected from the internet. If the device is powered on normally, but disconnected from the network, the device will automatically "reset" and all the IO and other states will return to the same state as after powering on. In such a case, to stop the reset and keep the IO and other states as they were at the end (high ios will remain high), the following settings can be made after the connection, and the device will maintain the IO and other states. It can be used to maintain what is displayed on a connected display without resetting the display. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function() { obniz.keepWorkingAtOffline(true); } ``` IO, etc. will just continue the last state. If it is `io.output(true)`, it will continue outputting, but if it is ```javascript obniz.onconnect = async function() { obniz.keepWorkingAtOffline(true); var val = true; while(true) { obniz.io0.output(val); val = !val; await obniz.wait(1); } } ``` In such a case, it is not clear whether io0 will stop with false or true. #### When obniz.js is disconnected from the cloud. If the device itself is communicating with the cloud normally, but you close the browser running the program or stop the nodejs program, the obniz cloud will tell the device to reset. However, if you have multiple connections and there are still connections from other programs, the reset will not be sent. This setting can be optionally turned off. This setting can be optionally turned off, so that even if you exit the program, the device IO, etc. will remain in its last state. By using this setting, we can connect to the device from obniz.js only when necessary, and keep the device in its last state even if the obniz.js program is stopped after changing the display or turning the motor. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE", { reset_obniz_on_ws_disconnection: false }); obniz.onconnect = async function() { } ``` Alternatively, you can change the settings after the connection as shown below. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function() { obniz.resetOnDisconnect(false); } ``` ## Event-driven by obniz connection state You can receive the firing of events depending on the connection state of the obniz. For example, the `connect` event, which is fired when obniz is connected, can be received by the [on()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#on) and the corresponding processing can be run. Similarly, the `close` event can be received by the `on()` when the connection to obniz is closed. ```Javascript // Javascript Example obniz.on('connect', async() => { console.log("a connect event occurred!"); await obniz.wait(3000); obniz.close(); }); obniz.on('close', () => { console.log("a close event occurred!"); }); ``` The [once()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#once) can also be used as a listener. The `on()` will receive and run any number of events, while the `once()` will only be run the first time. ```Javascript // Javascript Example let isConnectPhase = true; setInterval(async() => { if(isConnectPhase){ obniz.connect(); }else{ obniz.close(); } isConnectPhase = !isConnectPhase }, 3000); obniz.once('connect', () => { console.log("a connect event occurred for the first time!"); }); obniz.on('connect', () => { console.log("a connect event occurred!"); }); ``` --- ## Multiple Connection URL: https://obniz.com/reference/common/connection/multi-connection One device can accept multiple connection until it's limit. So one cloud software and one smartphone software can control one device at once. ##### When local connect exist But If one of obniz.js established a connection to a device, then target device will send datas only via local connect. So other connected obniz.js only can send datas and never receive datas from a device. If you'd like to receive, you need to specify `local_connect: false` at all of obniz.js to disable local connect. --- ## Local Connect URL: https://obniz.com/reference/common/connection/localconnect When obniz Board and the device running obniz.js is expected to be in the same network, obniz.js will try to establish a direct Websocket connection to obniz Board. This is called "local connect". When local connect is avaiable, obniz Board can be controlled with almost all commands without having to go through the cloud. However, the connection to the cloud never gets disconnected even when using local connect. But when cloud connection gets closed, the local connect also gets closed. ![](images/local_connect.png) The timing onconnect() gets called depends on the availability of local connect. obniz.js will wait a little to establish connection via local connect as much as possible. See the flow below. ![](images/onconnect_flow.png) --- ## Server Mode URL: https://obniz.com/reference/common/connection/on-premise If the device is running in a configuration that does not connect to the cloud (Server Mode), the connection with obnizID will not be available; instead of ID, specify IP address (IPv4). ```javascript // Javascript Full Example var obniz = new Obniz("192.168.0.100"); obniz.onconnect = async function() { } ``` ## Reset behavior The device will be reset by being disconnected from the program as in the cloud usage. As with the cloud version, you can turn off resetting when disconnected from javascript with the following command. ```javascript obniz.resetOnDisconnect(false); ``` Like the cloud version, you can also turn off the reset when the device disconnects from a network such as Wi-Fi with the following command. ```javascript // Javascript Full Example obniz.keepWorkingAtOffline(true); ```` --- ## compatibility URL: https://obniz.com/reference/common/connection/compatibility ### obnizOS version and obniz.js version obniz cloud compare your obniz.js version and target device obnizOS version. If your js sdk major number is below from OS version (eg obniz.js is 2.0.0 and obnizOS is 3.0.0) then obniz cloud will alert when connection established. It will work somehow but some functions looses compatibility. --- ## Wait and Repeat URL: https://obniz.com/reference/common/wait-and-loop ## Wait When you want to pause a device like for waiting a response from a sensor use [wait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#wait). It pause both device and program. ```javascript // Javascript Example led.on(); await obniz.wait(1000); // led ON for 1sec. led.off(); ``` Remove await to keep working program side. ```javascript // Javascript Example var time = new Date(); led.on(); obniz.wait(1000); // led ON 1sec. led.off(); console.log((new Date()).getTime() - time.getTime()) // 0 or very few ms. not 1000ms. ``` Or To stop only javascript then ```javascript // Javascript Example var time = new Date(); led.on(); await new Promise((resolve) => { setTimeout(resolve, 1000) }); led.off(); ``` ## Repeat To repeatedly call a function while the device is connected, `obniz.onloop` is useful. A function set here will be called repeatedly as long as the device is online. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { obniz.onloop = async function () { // called while online } } ``` This function calls [pingWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#pingwait) internally every time to check for communication and to ensure that the communication channel does not accumulate a large number of buffers. Therefore, if you want to iterate faster, you can do so by looping or iterating in your program instead of using onloop, but there are some caveats - When disconnected from a device, break a loop. - avoid freeze. Most safety loop is below. ```javascript // Javascript Example while(obniz.connectionState === 'connected') { try { // something code await obniz.pingWait(); // check communication } catch(e) { // break or throw a error } } ``` [connectionState](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#connectionstate) represents connection status for a device. [pingWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#pingwait) send a data and wait for a response. Above code will break a loop if offline and avoiding a freeze and also clean up communication line by using ping. --- ## Queue and Timestamp URL: https://obniz.com/reference/common/queue # obniz Product Manual: Transmission Queue and Clock Settings > **Target Version: OS7 and later** Normally, data is transmitted to the internet in real-time. However, by enabling the **Transmission Queue**, you can achieve the following: * **Reduce Packet Usage**: Group data together and send it at intervals rather than sending each piece individually. * **Accurate Timekeeping**: Attach timestamp information to all outgoing data to track precise timing. * **Offline Data Buffering**: Store data received during offline periods and transmit it once the connection is restored. ## obniz.setQueueMode({ timestamp, interval }) By specifying a value greater than `0` for the `interval`, you can switch from immediate transmission to queued transmission. obnizOS maintains an internal transmission queue. While it attempts to send data as quickly as possible by default, if you set an `interval` (e.g., 10 seconds), the system will buffer the data and only send it every 10 seconds or when the queue becomes full. **Note**: The Queue handles all data sent to the cloud, including command responses. Please be aware that enabling this may cause unexpected latency in various operations. When using the Queue, it can be difficult to determine exactly when the data was generated on the device side. By specifying the `timestamp` option, you can attach time information to each piece of data. This timestamp can be retrieved on the receiving end (e.g., in your application) via `obniz.deviceTimestamp`. Regardless of whether you choose seconds or milliseconds for the setting, `obniz.deviceTimestamp` will provide a Unix timestamp (in milliseconds), similar to `Date.now()`. **Note**: `obniz.deviceTimestamp` is only valid at the moment the data is received. If there is a delay due to `async/await` or other processing, it may be overwritten by the timestamp of the next incoming data. ### Parameters | Key | Type | Default | Value | | --- | --- | --- | --- | | **timestamp** | string | `'none'` | Choose from `'none'`, `'unix_seconds'`, or `'unix_milliseconds'`. Selecting anything other than `none` adds a timestamp to each packet. `unix_seconds` adds 4 bytes long date information; `unix_milliseconds` adds 8 bytes long date information | | **interval** | number | `0` | Transmission interval in milliseconds. | ### Javascript Example ```javascript // Example: Switching between immediate and queued transmission // 1. Set current time to obniz obniz.setClock(); // 2. Default mode: No delay, no timestamp obniz.setQueueMode({ timestamp: 'none', interval: 0 }); await obniz.ble!.initWait(); obniz.ble!.scan.onfind = (peripheral) => { // Access the timestamp of the received data console.log("Data Timestamp:", obniz.deviceTimestamp); console.log("Device Address:", peripheral.address); } await obniz.ble!.scan.startWait(null, { duration: null, duplicate: true }); // 3. Queue mode: Buffer data for 10 seconds with second-level timestamps obniz.setQueueMode({ timestamp: 'unix_seconds', interval: 10 * 1000 // Data is stored for up to 10 seconds or until the buffer is full }); ``` ## obniz.setClock() Since the device's internal clock does not synchronize automatically, you must manually send the current time information. This is required if you wish to use accurate timestamps. You can synchronize the clock using either of the following methods: * Call `obniz.pingWait()` * Call `obniz.setClock()` Both methods will send the current system time to the device and adjust its internal clock. ### Javascript Example ```javascript // Synchronize the device clock with the current system time await obniz.setClock(); ``` --- ## PartsLibrary URL: https://obniz.com/reference/common/parts PartsLibrary is obniz.js included electrical parts software components. By using it, You can use sensors and motors without learning electrical parts. Just use prepared functions and vars. You can find parts in library [Parts Library](/ja/sdk/parts) ## How to use Use [wired()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#wired) to instantiate a parts class. For example, [LED](/ja/sdk/parts/LED/README.md) is below. ```javascript // Javascript Example var led = obniz.wired("LED", {anode:0, cathode:1}); led.on(); ``` ## Code in library Every parts code are on Github. You can see TypeScript / JavaScript code. - TypeScript [https://github.com/obniz/obniz/tree/master/src/parts](https://github.com/obniz/obniz/tree/master/src/parts) - JavaScript [https://github.com/obniz/obniz/tree/master/dist/src/parts](https://github.com/obniz/obniz/tree/master/dist/src/parts) Below is LED example. - TypeScript [https://github.com/obniz/obniz/blob/master/src/parts/Light/LED/index.ts](https://github.com/obniz/obniz/blob/master/src/parts/Light/LED/index.ts) - JavaScript [https://github.com/obniz/obniz/blob/master/dist/src/parts/Light/LED/index.js](https://github.com/obniz/obniz/blob/master/dist/src/parts/Light/LED/index.js) --- ## Import hosted parts URL: https://obniz.com/reference/common/parts/import-parts When hosted parts library is not included officially in obniz.js, you need to import it code and register to obniz.js. [PartsRegistrate()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#partsregistrate) function will do registration. Below is a example of registering MYLED class to Obniz parts library. After that, call wired() to use it. ```javascript // Javascript Example Obniz.PartsRegistrate(MYLED); var led = obniz.wired("MYLED", { anode:0, cathode:1 } ); led.onesec(); ``` --- ## Create owned parts URL: https://obniz.com/reference/common/parts/make-parts Create and Publish your customized and Parts. ## Required function and variables - keys variable: object key names used at wired(). - requiredKeys variable: required object key names used at wired(). - info() class function: parts information like name - wired() function: It is called from obniz.wired(). parts initial code must be written in here. ## Minimum Codes Minimum model of parts is below. ```javascript // Javascript Example class LED { constructor() { this.keys = ['anode', 'cathode']; this.requiredKeys = ['anode']; } static info() { return { name: 'LED', }; } wired(obniz) { } } if (typeof module === 'object') { module.exports = LED; } ``` Below is necessary variables ```javascript // Javascript Example this.keys = ['anode', 'cathode']; ``` When you write requiredKeys, obniz.js will throw error when key does not exist at wired() ```javascript // Javascript Example this.requiredKeys = ['anode']; ``` Object returned by info() tell obniz.js parts name. This is independent from parts class name. ```javascript // Javascript Example static info() { return { name: 'LED', }; } ``` wired() function will be called from obniz.wired(). object passed from obniz.wired() can be access by calling this.params in wired() function. Last parts is not necessary but strongly recommended. It makes your code useful from both browser Node.js. ```javascript // Javascript Example if (typeof module === 'object') { module.exports = LED; } ``` ## Example For example, Below is custom [LED](https://github.com/obniz/obniz/blob/master/dist/src/parts/Light/LED/index.js) class that having new function onesec(). ```javascript // Javascript Example class MYLED { constructor() { this.keys = ['anode', 'cathode']; this.requiredKeys = ['anode', 'cathode']; } static info() { return { name: 'MYLED', }; } wired(obniz) { this.obniz = obniz; this.io_anode = obniz.getIO(this.params.anode); this.io_anode.output(false); this.io_cathode = obniz.getIO(this.params.cathode); this.io_cathode.output(false); } onesec() { this.io_anode.output(true); obniz.wait(1000); this.io_anode.output(false); } } if (typeof module === 'object') { module.exports = MYLED; } ``` ## Publish #### How to publish Use obniz[Repository](/reference/cloud/repository/) or other services like [GitHub](http://github.com/). #### How to use it Include it by using URL on browser. ```javascript // Javascript Example ``` For Node.js You can use npm to include codes from github. ## Use a class #### 1\. register as obniz parts See [This page](/reference/common/parts/import-parts/). ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { Obniz.PartsRegistrate(MYLED); var led = obniz.wired("MYLED", { anode:0, cathode:1 } ); led.onesec(); } ``` #### 2\. Use as standard class You can use without using obniz.js parts registration. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { var led = new MYLED(); led.params = { anode:0, cathode:1 }; led.wired(obniz); led.onesec(); } ``` --- ## GPS/GNSS URL: https://obniz.com/reference/common/location > **OS7 or later** This feature utilizes the built-in GPS/GNSS module of the Intelligent Edge series for positioning. **Note: In OS 7.0.0, this feature is currently in the experimental stage. Positioning may not function correctly, especially when LTE is active.** --- ## obniz.location.start() Starts the positioning process. ```javascript // Javascript Example obniz.location.start(); ``` --- ## obniz.location.onupdate This callback function is triggered whenever new positioning data is successfully retrieved. It returns a location information object. ```javascript // Javascript Example obniz.location.start(); obniz.location.onupdate = ((data) => { console.log(data); /* { latitude: number; longitude: number; altitude: number; accuracy: number; speed: number; } */ }); ``` --- ## Motion URL: https://obniz.com/reference/common/motion The Intelligent Edge series features built-in sensors designed to monitor environmental conditions. By utilizing the `motion` object, you can track the device's physical orientation, movement status, and ambient temperature. ## Features - **Orientation & Motion**: Detect how the device is tilted or moving in real-time. - **Temperature Monitoring**: Keep track of the environmental temperature surrounding the device. ## Usage You can access these data points through the `motion` module in the obniz SDK. This allows for various applications, such as detecting if a device has been moved or monitoring the heat levels in an installation environment. --- ## Acceleration URL: https://obniz.com/reference/common/motion/acceleration Gets the values from the accelerometer directly. ## obniz.motion.start(temperature, accel, recognition) Starts the motion module. You can specify the sensitivity as an argument to determine the threshold for data transmission based on value changes. The sensitivity can be set between `0.0` and `1.0`. If set to `1.0`, even the slightest change in value will trigger a data transmission. Regardless of the specified value, the data will be sent at least once immediately after the module starts. The acceleration sensitivity is specified in the **second argument**. ```javascript // Javascript Example obniz.motion.onAccelerationUpdate = ((r, t, p) => { console.log(`R: ${r}\nTheta: ${t}\nPhi: ${p}`); }); // Starting with 0.97 sensitivity for acceleration obniz.motion.start(0, 0.97, 0); ``` ## obniz.motion.onAccelerationUpdate This callback is triggered whenever an update to the acceleration data is received. The acceleration data is transmitted as **3D spherical coordinates** (r, theta, phi) rather than Cartesian coordinates (x, y, z). ```javascript // Javascript Example obniz.motion.onAccelerationUpdate = ((r, t, p) => { console.log(`R: ${r}\nTheta: ${t}\nPhi: ${p}`); }); obniz.motion.start(0, 0.97, 0); ``` ## obniz.motion.getAccelerationWait() This method performs a single measurement and retrieves the values immediately, rather than continuous monitoring. ```javascript // Javascript Example const acc = await obniz.motion.getAccelerationWait(); console.log(`Acc.R: ${acc.r}\nAcc.Theta: ${acc.t}\nAcc.Phi: ${acc.p}`); ``` --- ## Recognition URL: https://obniz.com/reference/common/motion/recognition Detects the current motion state of the device. ## obniz.motion.start(temperature, accel, recognition) This method initializes the motion module. You can specify the sensitivity for motion detection using arguments. The sensitivity level ranges from `0.0` to `1.0`. Setting it to `0` will cause the module to ignore all movements, consistently resulting in a `none` state. Please note that motion detection requires analyzing multiple data points, so it may take a moment before the first response is retrieved. The motion detection sensitivity is set via the **third argument**. ```javascript // Javascript Example obniz.motion.onRecognitionUpdate = ((motion, possibility) => { console.log(`Motion: ${motion}\nPossibility: ${possibility}`); }); // Start with 0.7 sensitivity for motion recognition obniz.motion.start(0, 0, 0.7); ``` ## obniz.motion.onRecognitionUpdate This callback function is triggered whenever a motion detection update is received. | Key | Description | | --- | --- | | **motion** | The currently detected motion state: `'none'` or `'moving'`. | | **possibility** | The confidence level of the detected motion (ranging from `0` to `1`). | ```javascript // Javascript Example obniz.motion.onRecognitionUpdate = ((motion, possibility) => { console.log(`Motion: ${motion}\nPossibility: ${possibility}`); }); obniz.motion.start(0, 0, 0.7); ``` ## obniz.motion.getRecognitionWait() This method performs a single measurement and retrieves the current value, rather than continuous monitoring. It is an asynchronous function that returns the result once the measurement is complete. ```javascript // Javascript Example const recognition = await obniz.motion.getRecognitionWait(); console.log(`Motion: ${recognition.motion} (${recognition.possibility})`); ``` --- ## Temperature URL: https://obniz.com/reference/common/motion/temperature Retrieves the temperature of the device. **Note:** This measures the temperature of the **internal sensor**, not the ambient air temperature. Due to power consumption and heat dissipation, the recorded value will typically be higher than the actual room temperature. ## obniz.motion.start(temperature, accel, recognition) Initializes the motion module. You can specify the sensitivity via the arguments. Sensitivity is defined from `0.0` to `1.0`. A value of `1.0` will trigger a notification for even the slightest change in temperature. Once `start()` is called, `onTemperatureUpdate` will be triggered at least once. The first argument is used for temperature detection sensitivity. ```javascript // Javascript Example obniz.motion.onTemperatureUpdate = ((temp) => { console.log(`Temp: ${temp} degree`); }); // Start with 0.99 temperature sensitivity obniz.motion.start(0.99, 0, 0); ``` ## obniz.motion.onTemperatureUpdate This callback is triggered whenever a temperature change is detected. The temperature value is provided in **degrees Celsius**. ```javascript // Javascript Example obniz.motion.onTemperatureUpdate = ((temp) => { console.log(`Temp: ${temp} degree`); }); obniz.motion.start(0.99, 0, 0); ``` ## obniz.motion.getTemperatureWait() Performs a single measurement and retrieves the value, rather than continuous monitoring. ```javascript // Javascript Example const temp = await obniz.motion.getTemperatureWait(); console.log(`Temp: ${temp} degree`); ``` --- ## IO URL: https://obniz.com/reference/common/io > [IO Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralio.html) > [IO API Reference](/reference/websocket/io) IO is electrical terminal on a device. IO can output ON/OFF or detect a voltage as ON/OFF. ## Setting and state #### Initial State On startup, All IO is set to initial state. There is a difference between device types but normally initial state is **float** (High impedance without pull-up-down ). You can reset IO state by calling io.end(). #### Using from peripheral When use a terminal from UART and PWM and other peripherals, io.output() and io.input() functions are stopped. IO setting will keep. obniz.js provide io setting property for peripheral initialize. So you shouldn't care last io setting before start peirpheral. ```javascript // Javascript Example obniz.uart0.start({ tx: 0, rx: 1, baud: 9600, drive: "open-drain", // => open-drain pull: "5v" // => pull-up to 5v }); ``` ## Device Difference In each device, The number of IOs and IO functions are different. Please refer to device reference. --- ## Output URL: https://obniz.com/reference/common/io/output IO Output controls voltage of terminal to drive electricity. It light up lights and rotate a motor. [io.output()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralio.html#output) function control output. Each device io has a unique number like 0, 1, 2,,,. For example, output a voltage on io number 0 performs like below. ```javascript // Javascript Example obniz.io0.output(true); ``` Or using [getIO()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obnizsystemmethods.html#getio) by specifying io number. ```javascript // Javascript Example obniz.getIO(0).output(true); ``` Actual output voltage depends on [DriveMethod](./drivemethod/) and device. Normally, default setting is "Push pull with Most powerful voltage". #### Stopping output Call [io.end()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralio.html#end) to stop output. output(false) is not stopping method. It means "output low votlage". ## Overcurrent Detection obniz board series has overcurrent and overheating detection circuit. It will stop and restart output automatically. See more at device reference. When a device detect overcurrent situation, obniz.js will receive below alert. ```javascript // Javascript Example io1: heavy output. output voltage is too low when driving high ``` It means "actual output voltage is too low". So connected parts consume too much energy or wire is short circuit. In that situation circuit might stop and restart output very quickly. Or you might receive below error. ```javascript // Javascript Example [Error] Error: io1: output voltage is too low when driving high. io state has changed output to input ``` In that situation, circuit stop output instantly to protect drive circuit. You should care connected parts and wires. If you need more power, consider below - When target is a power supply, connect another power source directly. - Connect two or more io and drive target from multiple ios. --- ## Input URL: https://obniz.com/reference/common/io/input IO Input detect voltage level as boolean applied to a terminal. "Input" but not receiving something. Input is used for detecting button and other components like sensors stats. ## Input by request [input.Wait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralio.html#inputwait) will ask to a device for current voltage state as a boolean. Below is a example for io0. ```javascript // Javascript Example var value = await obniz.io0.inputWait(); if (value) { // io0 is high level } else { // io0 is low level } ``` ## Input Monitor Change io to input mode for getting notify when changed. It is useful when state change is not expectable and don't want to miss it. set a callback function using [input()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralio.html#input) ```javascript // Javascript Example obniz.io0.input(function(value){ console.log("changed to " + value); }); ``` Frequency is depends on network speed. You may miss some datas when input change is so frequent or fast. #### Ending input Same as io.output(). Call [io.end()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralio.html#end). ```javascript // Javascript Example obniz.io0.input(function(value){ console.log("changed to " + value); }); obniz.io0.end(); ``` ## Level for true/false Voltage level for detecting true/false depends on device. obniz Board Series is "CMOS level". See more at device details. --- ## DriveMethod URL: https://obniz.com/reference/common/io/drivemethod If device IO has multiple drive method, configure it for change output power or voltage. By default, obniz choose "Most powerful push-pull" for output. use [io.drive()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralio.html#drive) to change drive method. Call it before call output(). But you can call io.drive() while output. ```javascript // Javascript Example obniz.io0.pull("5v"); obniz.io0.drive("open-drain"); obniz.io0.output(true); // output open-drain with 5v pull-up ``` ## Drive Method List > [drive class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralio.html#drive) > [drive API Reference](/reference/websocket/io#request-output_type) See drive methods on each device detail. Below is **obniz Board Series drive methods.** drive() argument | Drive method and Voltage | Max Current | Maximum Frequency | Detail ---|---|---|---|--- `5v` | push-pull 5v | 1A | <=250khz(Recommend) | Default. Over-current Over-heating protection `3v` | push-pull 3v | 1mA(Recommend) | <=80Mhz | Best effort over-current protection `open-drain` | open-drain <=5v | 1mA(Recommend) | <=80Mhz |   #### Push Pull Standard output method. It output VCC voltage when true. GND(0v) for false. #### Open Drain When false, same as push-pull. When true, IO changed to High Impedance. This is used for bi-directional communication or different voltage communication. --- ## Pull-up-down URL: https://obniz.com/reference/common/io/pull-up-down > [pull Class リファレンス](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralio.html#pull) > [pull API リファレンス](/reference/websocket/io#request-pull_type) Usage of internal pull-up pull-down Internal pull-up-down can be used with output/input and other peripherals. [io.pull()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralio.html#pull) function will enable/disable it. ```javascript // Javascript Example obniz.io0.pull("3v"); ``` #### List of pull-up pull-down Available type depend on device. Below is example of obniz Board series. See more on each device detail page. ```javascript // Javascript Example obniz.io0.pull(null); // => no pull-up down. float obniz.io0.pull("5v"); // => pull-up to 5v obniz.io0.pull("3v"); // => pull-up to 3.3v obniz.io0.pull("0v"); // => pull-down ``` --- ## IO-Animation URL: https://obniz.com/reference/common/io-animation > [Directive Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.directive.html) > [Directive API Reference](/reference/websocket/ioAnimation) io animation is registering a sequence of io changes for device. It runs regardless program. This is useful when driving dynamic-lightning or stepper motors. ## Unlimited Animation [io.animation()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.directive.html#animation) will register animation. Supply animation name and animations. It runs immidiately without timeout. `obniz.io.animation("animation-1", "pause")`will pause `obniz.io.animation("animation-1", "resume")` resume from pause. An animation state indicate one io states. One state consist of duration time(msec) and io state. Below is a example of io0 and io1 ON-OFF 10msec interval. ```javascript // Javascript Example obniz.io.animation("animation-1", "loop", [ { duration: 10, state: function(index){ // index = 0 obniz.io0.output(false) obniz.io1.output(true) } },{ duration: 10, state: function(index){ // index = 1 obniz.io0.output(true) obniz.io1.output(false) } } ]) ``` ## Limited numbered animation This is used for generating correct and fast io changes. Can be used for rotating stepper motor. animations registered from [repeat.wait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.directive.html#animation) has a run count limitaiton. [repeat.wait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.directive.html#animation) will wait for until done. Below example results 1\. io0 ON for 1000msec 2\. io0 OFF for 1000msec 3\. io0 ON for 1000msec 4\. io0 OFF for 1000msec ```javascript // Javascript Example await obniz.io.repeatWait([ { duration: 1000, state: function(index){ obniz.io0.output(true) } },{ duration: 1000, state: function(index){ obniz.io0.output(false) } } ], 4) ``` --- ## AD URL: https://obniz.com/reference/common/ad > [AD Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralad.html) > [AD API Reference](/reference/websocket/ad) AD reads analog voltage applied on each io. Usage example is reading brightness from light sensor which output light level as voltage. [ad.getWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralad.html#getwait) return current voltage once like io.inputWait(). ad0 means ad for io0. Normally, ad is not available on each io. Please refer to device detail. ```javascript // Javascript Example var voltage = await obniz.ad0.getWait(); ``` Measurable voltage range depends on device. obniz Board series measure 0 to 5v(vcc). And [ad.start()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralad.html#start) function start monitoring and receive voltage changes. ```javascript // Javascript Example obniz.ad0.start(function(voltage){ console.log("changed to "+voltage+" v") }); ``` Frequency depends on network speed. But Maximum is 30 Samples/sec. ## About obniz Board Series AD obniz Board series has specially designed AD circuit. AD is independent. It also works while IO is used for another function. ![](images/ad_0.png) AD also monitors vdd of obniz Board itself(normally 5v). Each ad result will be calibrated regarding below. | obnizOS version | calibration method | | --------------- | ---------------------- | | under 1.2 | Always | | 1.2 or higher | Only Vdd is under 4.5v | --- ## PWM URL: https://obniz.com/reference/common/pwm > [PWM class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralpwm.html) > [PWM API Reference](/reference/websocket/pwm) PWM(pulse width modulation) is a method for repeatedly switching a terminal on and off using fixed frequency. The percentage of on/off time can be changed. This makes it possible to send angle information to the servo motor, or to change the brightness of the LED or the strength of the motor outputting it at very high speed by PWM. Three parameters are required for PWM: - IO to output PWM - Frequency - Pulse width (percentage or time) ![](images/lessons_obnizjs_pwm_0.png) First, go to [obniz.getFreePwm()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#getfreepwm) to get unused PWM. The number of available PWM depends on the device. It is usually less than the IO, and is independent of the PWM number and the IO number. For example, in obniz Board series, there are six PWM from PWM0 to PWM5. PMW0 and IO0 is unrelated, so PWM can be used at IO1. You can start PWM at any IO using [pwm.start()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralpwm.html#start). [pwm.freq()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralpwm.html#freq) sets the frequency. The started PWM can be stopped by [pwm.end()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralpwm.html#end). ```javascript // Javascript Example var pwm = obniz.getFreePwm(); pwm.start({io:0}); pwm.freq(10000); // 10k hz pwm.duty(50) // 50% ``` You can modulate the signal by setting the time the signal is on, using [pwm.duty()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralpwm.html#duty) to set the ratio of the time or [pwm.pulse()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralpwm.html#pulse) to specify the time by msec. Duty cycle is as follows. ![](images/lessons_obnizjs_pwm_1.png) --- ## Modulation URL: https://obniz.com/reference/common/pwm/modulation Modulation is a function to modulate using PWM. obniz implements AM modulation. This is most often used with obniz for infrared remote control signal transmission. As for the infrared remote control, the signal is sent by digitally modulating the 38KHz frequency with the data you want to send. ## AM modulation As shown in the figure below, when the data to be sent is 1, the PWM is output, and when it is 0, nothing is output; the output is false. ![This image has an empty alt attribute; its file name is lessons_obnizjs_pwm_modulate.png](images/lessons_obnizjs_pwm_modulate.png) Modulation starts by calling [pwm.modulate()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralpwm.html#modulate) on the working PWM. The IO and the frequency are fixed, but the duty ratio is 50% output no matter what value is set. [pwm.modulate()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralpwm.html#modulate) sets "am" and then sets the time (msec) for 1 bit. In the example below, it is 1 msec, so it takes 8 msec to send 8 bits. In the end, the data you want to send is written as an array, which is separated by every bits. ```javascript // Javascript Example var pwm = obniz.getFreePwm(); pwm.start({io:0}); pwm.freq(5000); pwm.modulate("am", 1, [1,1,0,0,1,1,1,0]); ``` --- ## UART URL: https://obniz.com/reference/common/uart > [UART class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheraluart.html) > [UART API Reference](/reference/websocket/uart) UART is a method for communication between computers. The features of the UART are as follows: - Only one electric wire + GND are needed to send data. Two wires + GND to send and receive. - Can be used with almost every microcomputer. - Compatible from low to relatively fast speed communication. obniz Board series is up to 115.kbps. - Mainly used for communication between two computers. There is no master-slave system and they can send data at any time each other. - No error-correcting function. Parity check is optional. The UART is the simplest way to exchange data and there are USB-UART conversion cables. It is often used because it is the easiest way to communicate between a PC and a microcomputer. ## Initial settings The number of available UART depends on a devise. In terms of obniz Board series, it is UART0 and UART1. You can use the UART by setting output and input IO. There is no relation between the UART number and the IO number. UART0 can be used at IO1. Set UART using [uart.start()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheraluart.html#start). When you set IO1 as input, settings are as shown below. The IO set by tx is the output of UART itself, and is the IO connected to the rx of the other party. ```javascript // Javascript Example const uart = obniz.getFreeUart(); uart.start({tx: 0, rx: 1, baud:9600 }); ``` `obniz.getFreeUart()` returns unused UART out of several UARTs. If you know the UART certainly not used, you can use it by setting UART. ```javascript // Javascript Example obniz.uart0.start({tx: 0, rx: 1, baud:9600 }); ``` baud means communication speed and the larger the baud, the faster. Transmission and reception are the same speed, and when communicating, it is necessary to match with the other party. You can use any value you like, but there are some commonly used values for UART. 9600 is one of them. It means it can send 9600 bits per second; actually, it is not possible to send the data at bits per second because some control signals other than data are included. Also, you need to connect GND to the communicating party in addition to tx and rx. When connecting GND to the other party using IO and in order to connect IO11 to the other party's GND, you can set as follows: ```javascript // Javascript Example const uart = obniz.getFreeUart(); uart.start({tx: 0, rx: 1, gnd:11, baud:9600 }); ``` The driving method of IO used as tx, rx can be changed. ```javascript // Javascript Example const uart = obniz.getFreeUart(); uart.start({tx: 0, rx: 1, gnd:11, baud:9600, drive:"3v", pull:null }); ``` #### 1 byte at start Unintended data may be sent or received at the start of the UART. This is because when the UART starts, it may have a waveform as if the signal had started, so that the other party or the UART itself misunderstood and performed 1-byte communication. It occurs when starting the UART, not when sending data. #### Parity The start() function can add parity. See [Interface PeripheralUARTOptions](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.peripheraluartoptions.html) for details. #### Flow control Flow control using RTS / CTS is possible. See [Interface PeripheralUARTOptions](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.peripheraluartoptions.html) for details. The type of flow control can be selected by [flowcontrol](https://obniz.github.io/obniz/obnizjs/modules/obnizcore.components.html#flowcontroltype). ```javascript // Javascript Example const uart = obniz.getFreeUart(); uart.start({ tx: 0, rx: 1, cts: 2, rts: 3, flowcontrol: "rts-cts", baud:9600}); ``` #### Send and receive You can send and receive data with the UART you set. - [Send](/reference/common/uart/transmit/) - [Receive](/reference/common/uart/receive/) ## End The started UART can be ended by calling [u](http://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheraluart.html#end(opens in a new tab))[art.end()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheraluart.html#end). ```javascript // Javascript Example obniz.uart0.start({tx:0, rx:1}) obniz.uart0.send("Hi"); obniz.uart0.end(); ``` --- ## Send URL: https://obniz.com/reference/common/uart/transmit To send data via a [started UART](https://www.google.com/search?q=/reference/common/uart/), use the [uart.send()](https://www.google.com/search?q=https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheraluart.html%23send) method. ```javascript // Javascript Example const uart = obniz.getFreeUart(); uart.start({tx: 0, rx: 1, baud: 9600 }); uart.send("Hello"); uart.send([0x00, 0x01, 0x02]); ``` The [uart.send()](https://www.google.com/search?q=https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheraluart.html%23send) method does not wait for the transmission to complete (non-blocking). Additionally, since UART does not verify whether the receiver has actually received the data, no error will occur even if the communication partner is not connected. --- ## DE (Driver Enable) When using UART for RS422 or RS485 communication, you can automatically manage the **DE (Driver Enable)** pin, which indicates the transmission state. For example, if the DE pin of an external transceiver is connected to IO2, you can specify it as follows: ```javascript uart.setDE(2); ``` Once specified, the DE pin will be automatically toggled high/low before and after data is transmitted via the `send()` function. ```javascript // Javascript Example const uart = obniz.getFreeUart(); uart.start({tx: 0, rx: 1, baud: 9600 }); uart.setDE(2); uart.send("Hello"); uart.send([0x00, 0x01, 0x02]); ``` --- ## Receive URL: https://obniz.com/reference/common/uart/receive Data can be received from the other party by calling the [onreceive](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheraluart.html#onreceive) function. In that function, "data" and "text" are passed as arguments. "data" is the received byte sequence and "text" is the data converted to a string as much as possible. If conversion to text fails, text will be "undefined". ```javascript // Javascript Example const uart = obniz.getFreeUart(); uart.start({tx:0, rx:1}) uart.onreceive = function(data, text) { console.log(data); console.log(text); } ``` The UART has no "length" information in the data. Sending 100 bytes of information does not guarantee that 100 bytes will be received. It may be divided into 20 bytes and 80 bytes twice. #### Overflow When the communication speed of the device is insufficient, the received UART data may not be sent. In such a case, no error occurs and the received data will be lost. --- ## SPI URL: https://obniz.com/reference/common/spi > [SPI class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralspi.html) > [SPI API Reference](/reference/websocket/spi) SPI is a communication method for exchanging data between computers. Differences from UART, which is commonly used are as follows: - Steady and high speed communication is possible because of a clock and signal lines. - SPI "exchanges" data, does not just send or receive it. If it sends 1 byte, it always receive 1 byte from the other party. - Communicate using master-slave architecture, and the slave device cannot send by itself. The communication starts when the master device want to. It is used for communication with sensors rather than with computers. The microcomputer tell the sensor what to do and receive data instead, using SPI. It is attractive that the program is easy because the master can communicate at any time it like and that very high speed communication is possible. Connect the other party with three lines; this is the only method obniz uses: CLK to send the time when the master device exchange data, MOSI (Master Out Slave In) to send data from the slave to the master, and MISO for the master to receive data from the slave. MISO may not be connected when the master may not need to receive data from the slave. ![](images/lessons_obnizjs_spi.png) ## Initial settings Available SPI depends on a device. For example, obniz Board has SPI0 and SPI1. The SPI is different from IO, and use it so that each CLK or MOSI of SPI can be used in any of the 12 IO. You can get unused SPI by [obniz.getFreeSpi()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#getfreespi). [spi.start()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralspi.html#start) starts SPI. Set the IO and the frequency. For example, if you set IO1 to MOSI, IO1 to MISO, IO2 to CLK, and the frequency is 100kHz, the code is as follows. ```javascript // Javascript Example var spi = obniz.getFreeSpi(); spi.start({mode:"master", mosi:0, miso:1, clk :2, frequency:100000}); ``` If you know the SPI which is certainly unused, you can use it directly rather than use [obniz.getFreeSpi()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#getfreespi). ```javascript // Javascript Example obniz.spi0.start({mode:"master", mosi:0, miso:1, clk :2, frequency:100000}); ``` As for "mode", set obniz to master so that it can send data by itself. Currently only master mode is supported. "frequency" is the communication frequency, which sent from the master by CLK. Select the speed at which you can communicate with the other party. Available frequencies depend on the device and the drive method of IO. In many cases, push-pull3v enables higher-speed communication such as 2MHz. [The drive method](/reference/common/io/drivemethod/) and [pull-up-down](/reference/common/io/pull-up-down/) of MOSI, MISO and CLK can be changed as shown below. You do not have to use all of MOSI, MISO and CLK, though you need to specify at least one of them; it is possible to use only MOSI and CLK, without MISO. ```javascript // Javascript Example var spi = obniz.getFreeSpi(); spi.start({mode:"master", mosi:0, miso:1, clk :2, frequency:100000, drive:"3v", pull:null}); ``` ''drive" can change the drive method, and "pull" can change pull-up-down. You can specify the same thing as the ones set by `io.drive()` and `io.pull()`. After the setting is completed, communication is possible. - [Master Read/Write](./master-mode) ## End The started SPI ends by [spi.end()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralspi.html#end). ```javascript // Javascript Example var spi = obniz.getFreeSpi(); spi.start({mode:"master", clk :0, mosi:1, miso:2, clock:1000000}); spi.write([0x12, 0x98]); spi.end(); ``` --- ## Master Read/Write URL: https://obniz.com/reference/common/spi/master-mode After [the SPI settings](/reference/common/spi/) are completed, communication is possible. In Master mode, you are master and can send data at any time you like. You will not receive data without doing anything. With SPI, it receives as much data as it transmits. In other words, SPI is a communication method that "exchange data". Use [spi.writeWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralspi.html#writewait) to send data. Set an array of data. In the example below, three bytes of \[0x01, 0x02, 0x03\] are transmitted. Then, the three bytes received from the other party will be the return value. The length of transmitted data and the one of received data are always same. ```javascript // Javascript Example var spi = obniz.getFreeSpi(); spi.start({mode:"master", mosi:0, miso:1, clk :2, frequency:100000}); var ret = await spi.writeWait([0x01, 0x02, 0x03]); console.log(ret.length); //=> 3 ``` Like UART, SPI can communicate even if there is no actual partner. It will send data successfully and receive data that has the same length as the transmitted data, but the data received will be meaningless. The amount of data sent at a time depends on the version of obnizOS or obniz.js. Normally, it is 1KByte. #### Sending not need receiving data [spi.writeWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralspi.html#writewait) sends data and waits until receiving data. In case received data is not needed, such as when the connection destination is a display, use [spi.write()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripheralspi.html#write). ```javascript // Javascript Example var spi = obniz.getFreeSpi(); spi.start({mode:"master", mosi:0, miso:1, clk :2, frequency:100000}); spi.write([0x01, 0x02, 0x03]); ``` The write() function sends data from MOSI like the writeWait() function, but ignores any data coming from MISO. A large amount of data or continuous data can be sent with the SPI of the device via the Internet, because it does not `await`. --- ## I2C URL: https://obniz.com/reference/common/i2c > [I2C class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripherali2c.html) > [I2C API Reference](/reference/websocket/i2c) I2C is a method for communicating with other electronic components. The strongest feature of I2C is that multiple units can be connected to the same wiring. Therefore, if there are many sensors, they can be connected to the same I2C, making wiring easy. Unlike UART and SPI, data is sent while communicating with the other party, so if there is no other party or it refuses, the transmission itself will result in an error. Instead, the communication speed is not so fast as other methods such as SPI. The features of I2C are as follows: - Two-way communication using only two lines, and multiple units can communicate. - There is a master-slave system, and a lots of slave devices can be connected to one master device. - The slave device has its address. - The master device starts communicating with one slave device at any time, and data is written and read. - The slave device always "responds" to the master device for both writing and reading, and an error will occur if there is no reply. - The slave device can respond to the master device, sayings "Wait a minute, I'm preparing now." or "It's impossible." These responses are called NAK. ## The points of wiring I2C communicates on two bidirectional lines, SDA and SCL, so open drain and pull-up resistor are needed. [The internal pull-up resistor](/reference/common/io/pull-up-down/) in the microcomputer is so weak that it may not be enough for I2C. For stable communication, it is necessary to pull up externally with a resistance of several kiloohms. It is weak in communication over long distances than UART and SPI. ## Initial Settings The number of available I2C depends on a device. In terms of obniz Board series, it is only I2C0. Set the I2C by [i2c.start()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripherali2c.html#start). The I2C is different from IO, and specify the IO number for SDA and SCL of I2C in start(). For example, if IO0 is SDA and IO1 is SCL in the master mode, the code is as follows: ```javascript // Javascript Example var i2c = obniz.getFreeI2C(); i2c.start({mode:"master", sda:0, scl:1, clock:400000}); ``` Get unused I2C by [obniz.getFreeI2C()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#getfreei2c), or directly set the I2C. ```javascript // Javascript Example obniz.i2c0.start({mode:"master", sda:0, scl:1, clock:400000}); ``` With pull you can specify internal pull-up for SDA and SCL. What can be set with `io.pull()` can be used. Up to 400kHz when using internal pull-up. In particular, since the internal pull-up with 3V is weak, if you set the internal pull-up with 3V, it will be up to 100kHz. If the voltage is over, an error will occur. Also, if GND is not connected to the other party's circuit or sensor, and you want to connect IO to the other party's GND, you can also specify the IO used in GND. ```javascript // Javascript Example obniz.i2c0.start({mode:"master", sda:0, scl:1, gnd:2, clock:400000, pull:"5v"}); ``` These are for the case of master. The initial settings for slave is different from these. Please check the each page. - [master](./master-read-write) - [slave](./slave-read) ## End The started I2C ends by [i2c.end()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripherali2c.html#end). --- ## Master Read/Write URL: https://obniz.com/reference/common/i2c/master-read-write ## Initial Settings To set master mode when starting I2C by [i2c.start()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripherali2c.html#start), specify master for mode and specify communication frequency. The frequency is generally 100kHz or 400kHz in I2C. The pull-up with a "small" resistor is needed to communicate at high speed. The setting is as shown below to use I2C with only [internal pull-up](/reference/common/io/pull-up-down/) without an external resistor, although this is not recommended. ```javascript // Javascript Example obniz.i2c0.start({mode:"master", sda:0, scl:1, clock:400000, pull:"5v"}); ``` ## Write [i2c.write()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripherali2c.html#write) sends data to device, using addresses and array data. In the program below, the address is 0x50. If writing fails, such as when the connection is not established with the other party, or when other party refuses (NAK), the function set in [onerror](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripherali2c.html#onerror). ```javascript // Javascript Example obniz.i2c0.start({mode: "master",sda:2, scl:3, clock:400000, pull:null}); obniz.i2c0.onerror = function(err) { console.error(err) } obniz.i2c0.write(0x50, [0x00, 0x00, 0x12]); ``` ## Read [i2c.readWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripherali2c.html#readwait) reads data from the device. Set the length of data to read along with the address of the other device. When reading successfully done, it returns data, of which the length is as specified. In case of communication error, error will be thrown ```javascript // Javascript Example obniz.i2c0.start({mode: "master",sda:2, scl:3, clock:400000, pull:null}); try { var ret = await obniz.i2c0.readWait(0x50, 1); console.log("read "+ret); } catch (e) { console.error(e); } ``` --- ## Slave Read URL: https://obniz.com/reference/common/i2c/slave-read By setting mode as slave, the device communicate with the master device as slave. obniz is compatible only with writing from master, and reading from master is always 0. To set slave mode, specify mode for slave in [i2c.start()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripherali2c.html#start). Its own address is also specify in [slave\_address](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.peripherali2coptions.html#slave_address). ```javascript // Javascript Example var i2c = obniz.getFreeI2C(); i2c.start({mode: "slave", sda: 0, scl: 1, slave_address: 0x01}); ``` Data is sent to the slave device at any time when the master device is ready. To receive the data, specify the function using [i2c.onwritten](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.peripherali2c.html#onwritten). ```javascript // Javascript Example var i2c = obniz.getFreeI2C(); i2c.start({mode: "slave", sda: 0, scl: 1, slave_address: 0x01}); i2c.onwritten = function(data){ console.log(data); } ``` The received data is stored in "data" as an array. Currently, data is fragmented in obniz. In other words, one set of data actually has its length, but it may arrives separately in I2C. Same as UART. --- ## CANBus URL: https://obniz.com/reference/common/can CAN (Controller Area Network) is a protocol where multiple devices share a single bus for communication. It is highly resistant to electrical noise and allows any terminal to initiate data transmission at any time. The Intelligent Edge Kilo comes equipped with built-in CANBus support. ## Initial Setup To begin, specify the two pins (**tx** and **rx**) connected to the external transceiver. The following additional parameters can also be configured: | Parameter | Type | Description | | --- | --- | --- | | **mode** | string | Select from `'normal'`, `'noack'`, or `'listen'`. `normal`: Requires an ACK after transmission. `noack`: Does not require an ACK. `listen`: Receive-only mode (no transmission). | | **kbps** | number | Specifies the communication speed in kbps. | | **filter_code** | number | 4-byte code. Packets matching this code (after masking) will be received. (Compliant with ESP32 CANBus Filter) | | **filter_mask** | number | 4-byte mask. Set to `0` for no masking. (Compliant with ESP32 CANBus Filter) | Use the following syntax to initialize the interface. The example below demonstrates the standard `'normal'` mode, configured to send and receive all packets. ```javascript // Javascript Example // Intelligent Edge Kilo obniz.components!.prepare(); obniz.components!.powerOnInterface(KiloInterface.CANBus_On); obniz.canbus0!.start({ tx: 5, rx: 6, mode: 'normal', kbps: 500, filter_code: 0, filter_mask: 0 }); ``` ## Data Transmission and Reception ### Receiving Data When data is received, the function assigned to `onreceive` is automatically triggered. ### Sending Data Data can be sent using the `send()` function. The parameters for transmission are as follows: | Parameter | Type | Description | | --- | --- | --- | | **obj.extended** | boolean | Specifies whether to use an Extended ID. | | **obj.rtr** | boolean | Specifies whether the frame is a Remote Transmission Request (RTR). | | **obj.single_shot** | boolean | Specifies if the message should be sent as a single shot (no retransmission). | | **obj.self_reception** | boolean | Specifies if the message is a Self Reception request. | | **id** | number | The Identifier of the message. | | **data** | number[] | The data payload of the message. | ### Full Code Example ```javascript // Javascript Example // Intelligent Edge Kilo obniz.components!.prepare(); obniz.components!.powerOnInterface(KiloInterface.CANBus_On); // Initialize CANBus obniz.canbus0!.start({ tx: 5, rx: 6, mode: 'normal', kbps: 500, filter_code: 0, filter_mask: 0 }); // Set up Reception Handler obniz.canbus0!.onreceive = async (isExtended: boolean, isRTR: boolean, id: number, data: number[]) => { console.log("Device ID:", obniz.id, "Extended:", isExtended, "RTR:", isRTR, "ID:", id, "Data:", data); }; // Send a Message const target_id = 0x01; obniz.canbus0!.send({ extended: false, rtr: false, single_shot: false, self_reception: false }, target_id, [0x01, 0x02]); ``` --- ## LogicAnalyzer URL: https://obniz.com/reference/common/logicanalyzer > [LogicAnalyzer Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.logicanalyzer.html) > [LogicAnalyzer API Reference](/reference/websocket/logicAnalyzer) LogicAnalyzer records samples read from io periodically. This is useful for digital bus signal check. Only one LogicAnalyzer can be used per obniz Board. ### How it works LogicAnalyzer starts logging by a trigger. The default trigger is "value change". When it occurs, data will be recorded for a desired duration. After that is done, LogicAnalyzer starts monitoring changes in io (= continue working). One sample becomes one 1/0. ![](images/logiana_0.png) Sampling interval and duration can be configured. For example, if interval is 1 ms and duration is 800ms, you will get 800 arrays of data. The data will be in multiples of 8. ### Trigger Option The default trigger is "value change", but it tends to be interrupted by some noise. Configure triggerValue/triggerValueSamples to filter it. 1. triggerValue - desired start value. true/false 2. triggerValueSamples - after how many samples will the recording start. This trigger setting means "trigger when true/(or false) continues for more than X times after io change" ![](images/logiana_1.png) [logicAnalyzer.start()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.logicanalyzer.html#start) starts the logic analyzer on a given io. Interval means a period(second) to read io value. data\_long means for how long the logicAnalyzer will collect the data. For example, if you want to collect the data after io0 changes every 2ms for 1sec long, set as below. ```javascript // Javascript Example obniz.logicAnalyzer.start({io:0, interval:2, duration:1000}); // start on io0. 2ms interval and 1sec long. obniz.logicAnalyzer.onmeasured = function(array) { console.log(array); } ``` The trigger is an optional configuration. Without this, logicAnalyzer recognizes any io level change as trigger and start. Trigger specifies the start position. Value means start value, true/false. Samples means how much that value consists. So, with the below sample code, you will only receive data that start with "0, 0, 0" ```javascript // Javascript Example obniz.logicAnalyzer.start({io:0, interval:2, duration:1000, triggerValue:false, triggerValueSamples:3}); // start on io0. 2ms interval and 1sec long. obniz.logicAnalyzer.onmeasured = function(array) { console.log(array); } ``` ## Ending call [logicAnalyzer.end()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.logicanalyzer.html#end) to end logicAnalyzer --- ## Measurement URL: https://obniz.com/reference/common/measurement > [Measurement Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.obnizmeasure.html) > [Measurement API Reference](/reference/websocket/measure) The measure module provides hardware level measurement. ## measure.echo({}) Some electrical parts or circuits accept "pulse" and echo the "pulse" after delay. This module is best suited for measuring that delay. This module generates one pulse shot on an io, then measures the response time. ![](images/measure.png) ### pulse generation You can choose below to generate a pulse 1. io\_pulse: io number to generate pulse 2. pulse: "positive" or "negative" 3. pulse\_width: pulse duration in values between ms. 0.001 to 1000. ![](images/measure_posneg.png) ### Response measurement You can choose below to measure response 1. io\_echo: io for measuring response 2. measure\_edges: maximum number of edges to detect. 1 to 4. 3. timeout: timeout in ms, and default is 1000. 0.001 to 1000. 4. callback: callback function after measurement or timeout A callback function will be called when the edge count = measure\_edges or timeout. It has an array of edge information. For example, if you get a response like below ![](images/measure_response.png) [measure.echo()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.obnizmeasure.html#echo) starts measurement. ```javascript // Javascript Example obniz.measure.echo({ io_pulse: 0, // io for generate pulse io_echo: 1, // io to be measured pulse: "positive", // generate pulse pattern pulse_width: 0.1, // generate pulse width measure_edges: 3, // 1 to 4. maximum edges to measure timeout: 1000, // this is optional. 1000(1sec) is default callback: function(edges) { // callback function console.log(edges); } }); ``` then, you will get below ```javascript // Javascript Example callback: function(edges) { edges.length // == 2 edges[0].edge // == true edges[0].timing // == t1 edges[1].edge // == false edges[1].timing // == t2 } ``` --- ## Display URL: https://obniz.com/reference/common/display > [Display Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html) > [Display API Reference](/reference/websocket/display) Display available device like obniz Board series, You can draw on a display. ![](./images/display.png) ## Draw Method obniz device can accept binary array which represents each pixel color. [display.raw()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#raw) sends the array. binary array should start from left-top. For monochrome display, each bit for each pixel. For color display, It depends on color depth. You can use [Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) for high-level rendering. obniz.js has helper function to read canvas [display.draw()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#draw). For Nodejs, node-canvas is available. ```javascript // Javascript Example // browser let ctx = $("#canvas")[0].getContext('2d'); // or Node.js // $ npm install canvas ( version 2.0.0 or later required ) // const { createCanvas } = require('canvas'); // const canvas = createCanvas(128, 64); // const ctx = canvas.getContext('2d'); ctx.fillStyle = "white"; ctx.font = "30px Avenir"; ctx.fillText('Avenir', 0, 40); obniz.display.draw(ctx); ``` So UTF8 characters and 3D graphics can be drawn. ![](images/obniz_display_samples0.jpg) ## Simple Drawing obniz.js has support rendering functions. You don't need to use canvas directly. - Draw text ... [display.print()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#print) - Clearing ... [display.clear()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#clear) - Draw a line ... [display.line()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#line) - Draw a rectangle ... [display.rect()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#rect) - Draw a circle ... [display.circle()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#circle) - Draw a QR code ... [display.qr()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#qr) - Specify the font ... [display.font()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#font) - Change text position ... [display.pos()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#pos) - Change drawing color ... [display.setColor()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#setcolor) For Example, [display.print()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#print) draw text immediately. ```javascript // Javascript Example obniz.display.print("Hello World🧡"); ``` ![](images/obniz_display_print.jpg) But, depending on the execution environment, the characters that can be drawn are limited. | Environment | Drawing method | Characters that can be drawn | | --- | --- | --- | | Browser | canvas | All characters supported by the installed font. | | Node.js + canvas | canvas | All characters supported by the installed font. | | Only Node.js (no canvas) | json command | Only alphanumeric (`A-Z`,`a-z`,`0-9`) and symbols (``!"#$%&'()*+,-./:;?@[\]^_`{\|}~``)* Character types in ASCII code | The above example contains a heart symbol, so if you are using Node.js only (no canvas), you will get a warning. Please install canvas manually with `npm install canvas`. The font is set to `Avenir` by default, and can be changed with [display.font()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#font). If fonts are not available (e.g. Running on repl.it), you need to uninstall canvas because canvas can't draw text. Here are some examples of other drawing functions in use. ```javascript // Javascript Example obniz.display.line(30, 30, 100, 30); obniz.display.rect(20, 20, 20, 20); obniz.display.circle(100, 30, 20); obniz.display.line(60, 50, 100, 30); obniz.display.rect(50, 40, 20, 20, true); obniz.display.line(50, 10, 100, 30); obniz.display.circle(50, 10, 10, true); // Changing color will affect only color display models. obniz.display.setColor('#FF0000'); obniz.display.rect(50, 40, 20, 20, true); obniz.display.setColor('blue'); obniz.display.circle(100, 30, 20, true); ``` ![](./images/display_draw.png) ### Color Depth Color drawing is available on devices like M5StickC. ```javascript // Javascript Example obniz.display.font('Avenir',70) obniz.display.print("🧡😁"); ``` ![](images/display.png) By default, it draws most colorful mode. But it takes time to transfer datas. When you need more faster way, use [display.setColorDepth()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#setcolordepth) to reduce bit depth. - 1: 1bit depth. monochrome mode. With obniz Board, this is only option. - 4: 4bit for 16 colors. - 16: 16bit for RGB565 colors. 1bit is 16 times faster compared from 16bit. Changing color is performed in [obniz.display.draw()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#draw) automatically. You don't need to care your canvas datas. ```javascript // Javascript Example obniz.display.setColorDepth(4); obniz.display.font('Avenir',70) obniz.display.print("🧡😁"); ``` ![](./images/display_draw.png) example of 4 bit: 16 color mode ### Buffering Rendering functions draw canvas immediately and transfer datas on each. You may want to just render and transfer once.[display.drawing()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.display.html#drawing) will change drawing mode. for false, It just render on canvas. No transfer. Call drawing(true) to transfer current canvas once. ```javascript // Javascript Example obniz.display.drawing(false); obniz.display.print("Hello"); obniz.display.print("World"); obniz.display.drawing(true); ``` --- ## Switch URL: https://obniz.com/reference/common/switch > [Switch Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.obnizswitch.html) > [Switch API Reference](/reference/websocket/switch) If a device has a switch, you can read or monitor it. For obniz Board series, it's on left-top. [switch.getWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.obnizswitch.html#getwait) read current switch status as a string. [switch state](https://obniz.github.io/obniz/obnizjs/modules/obnizcore.components.html#obnizswitchstate) describe list of stats. And helper function [stateWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.obnizswitch.html#statewait) will wait for until specified state. ```javascript // Javascript Example var state = await obniz.switch.getWait(); if (state === "push") { console.log("pressed") } ``` #### Monitor Register a function to [switch.onchange](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.obnizswitch.html#onchange). The function will receive all switch state changes. ```javascript // Javascript Example obniz.switch.onchange = function(state) { if (state === "push") { console.log("pressed") } } ``` Switch monitoring can't be disabled like io.input(). --- ## Sleep URL: https://obniz.com/reference/common/sleep > [Sleep Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obnizsystemmethods.html#sleep) > [Sleep API Reference](https://www.google.com/search?q=/reference/websocket/system%23request-sleepseconds) On devices equipped with obniz Board 1Y or OS7 (and later), you can reduce power consumption by putting the device into a sleep state. This enables battery-powered, cable-free operation. For more details on sleep behavior for each OS, please refer to the [OS Sleep Page](https://www.google.com/search?q=../obnizos-for-esp32/sleep). ![](images/obniz_board_1y_sleep-1.jpg) ## How Sleep Mode Works When the device enters sleep mode, all functions are suspended to achieve ultra-low power consumption (see the bottom of this page for actual current consumption). This includes the deactivation of Wi-Fi and the onboard display. The device will automatically wake up and restart based on a specific "Trigger" defined when entering sleep mode. You can specify the following triggers: 1. **Elapsed Time (Seconds):** From 1 second up to 64,800 seconds (18 hours). 2. **Elapsed Time (Minutes):** From 1 minute up to 64,800 minutes (45 days). 3. **IO0 Rising Edge (obniz Board 1Y only):** Wakes up when the voltage on pin `io0` rises. (Threshold is TTL level, depending on the supplied voltage). 4. **IO0 Falling Edge (obniz Board 1Y only):** Wakes up when the voltage on pin `io0` falls. (Threshold is TTL level, depending on the supplied voltage). When the sleep period ends or a trigger is activated, the device reboots and reconnects to the cloud, just as if it were power-cycled. If you manually turn the power off and on during sleep, the device will wake up and start immediately. ## obniz.sleepSeconds(number) ## obniz.sleepMinute(number) You can trigger a timed sleep using [obniz.sleepSeconds()](https://www.google.com/search?q=https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html%23sleepseconds) or [obniz.sleepMinute()](https://www.google.com/search?q=https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html%23sleepminute). Additionally, [obniz.sleep()](https://www.google.com/search?q=https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html%23sleep) allows you to use a `Date` object to specify a precise wakeup time. ```javascript // Javascript Example obniz.sleepSeconds(60); // Sleep for 60 seconds (1 min) obniz.sleepMinute(60 * 24); // Sleep for one day const dt = new Date(); dt.setHours(dt.getHours() + 1, 0, 0, 0); // Wake up at the start of the next hour obniz.sleep(dt); ``` ## obniz.sleepIoTrigger(boolean) For the obniz Board 1Y, in addition to time-based triggers, you can use [obniz.sleepIoTrigger()](https://www.google.com/search?q=https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html%23sleepiotrigger) to remain in sleep mode until a change is detected on pin `io0`. ```javascript // Javascript Example obniz.sleepIoTrigger(true); // Wake up on a rising edge on io0 ``` ## Battery Life Estimation (For obniz Board 1Y) Battery life varies depending on the device; please refer to the specific documentation for your hardware. For example, the current consumption of the obniz Board 1Y during sleep is approximately **20uA - 40uA (at 5V)**. You can estimate the total runtime based on the average active power consumption (approx. 120mA) as follows: ```javascript // Simple calculation (ignoring battery self-discharge and voltage drop): // S: Average active time per hour (minutes) // Q: Battery capacity (mAh) // Formula: // Runtime (hours) = Q / ( (S/60 * 120) + ((60-S)/60 * 0.04) ) /* Example: Using 3x AA Alkaline batteries (approx. 2000mAh): If the device wakes up once a day for 2 minutes and sleeps for the rest of the time, it will last for approximately 1 year. */ ``` --- ## TCP URL: https://obniz.com/reference/common/tcp > [TCP class reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.tcp.html) > [TCP API Reference](/reference/websocket/tcp) With TCP, data can be sent and received from a device to a specified IP address or domain using TCP. It can be used to communicate with devices in the same network where the device exists, and can be used to display the router's configuration screen and acquire video footage from network monitoring cameras. ## Connection. One or more TCPs are available and you can get a free one with [obniz.getFreeTcp()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#getfreetcp). If it doesn't exist, it will be thrown. You can use [connectWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.tcp.html#connectwait) to make a connection by specifying the port number and IP or domain name. Do it. If it fails, an error is thrown. ```javascript // JavaScript Example var tcp = obniz.getFreeTcp(); tcp.connectWait(80,"google.com"); ``` You can also use end() to disconnect. ```javascript // JavaScript Example var tcp = obniz.getFreeTcp(); tcp.connectWait(80,"google.com"); await obniz.wait(1000); tcp.end(); ``` ## Reading and writing Use [write](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.tcp.html#write) for writing and [onreceive](https:// obniz.github.io/obniz/obnizjs/classes/obnizcore.components.tcp.html#onreceive) to specify the function. The function specified in [onerror](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.tcp.html#onerror) will be called when some error occurs. ```javascript // JavaScript Example var tcp = obniz.getFreeTcp(); tcp.onerror = state => { console.log(state); }; tcp.onreceive = data => { console.log(data); }; tcp.connectWait(80,"google.com"); tcp.write('hello'); ``` --- ## Wi-Fi URL: https://obniz.com/reference/common/wifi > [Wi-Fi Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.wifi.html) wifi let you control Wi-Fi on obnizOS runnning device ## Scan You can search for access points near your device. Use [obniz.wifi.scanWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.wifi.html#scanwait) to get the name, macAddress and signal strength of the surrounding access points. - Scan Interval: 30seconds - Scan Method: Active Scan ``` console.log(await obniz.wifi.scanWait()) ``` ``` [ {ssid: "testwifi1", macAddress: "280000000009", rssi: -41}, {ssid: "testwifi2", macAddress: "280000000008", rssi: -59}, {ssid: "testwifi3", macAddress: "280000000007", rssi: -82} ] ``` --- ## BLE URL: https://obniz.com/reference/common/ble > [BLE Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.obnizble.html) > [BLE API Reference](/reference/websocket/ble_hci) BLE stands for Bluetooth Low Energy and is a type of Bluetooth. Its features are as follows: - Relatively low power wireless. - A connection mode without pairing is available. - Basically use a profile of GATT, and the other party is used like a database. - Multiple slave devices can be connected to one master device. - Quite popular with smartphones, so can be used from most smartphones. If the device supports BLE, you can use it from obniz. This makes it possible to extract the value from lightning or smart watch that uses BLE, or connect them from a smartphone. ## Central / Peripheral The communication of BLE is one-to-many, and there is a master device. Master is called "central" and slave called "peripheral." obniz work as either central or peripheral; switching after setting is possible. The signal strength and the number of devices that can be connected at the same time depends on the version of obnizOS. ## Initialization Call [ble.initWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.obnizble.html#initwait) once to initialize and start BLE. Some devices may consume more power due to the use of BLE than when it is not used. ```javascript // Javascript Example obniz.ble.initWait(); ``` --- ## Central: Scan URL: https://obniz.com/reference/common/ble/central-scan ## Scan The peripheral device keeps sending a signal called advertisement, that says "I am a device called blah-blah-blah. I am ready to be connected." This enables the central device to find nearby BLE peripheral. Get the advertisement and find all the devices around you. You can start scanning by [ble.scan.startWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blescan.html#startwait) from [ble.scan](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blescan.html). Discovered devices can be received as [bleRemotePeripheral](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremoteperipheral.html) object using the function set in [ble.scan.onfind](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blescan.html#onfind). ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); obniz.ble.scan.onfind = async function(peripheral){ console.log(peripheral.localName) }; obniz.ble.scan.onfinish = async function(peripherals, error){ console.log("scan timeout!") }; await obniz.ble.scan.startWait(); } ``` The scan is completed in a fixed time: initially 30 seconds, and then, the function set in [ble.scan.onfinish](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blescan.html#onfinish) is called. If you want to scan repeatedly, call [ble.scan.startWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blescan.html#startwait) in onfinish or provide null for scan duration option. However, sometimes the scan will stop earlier than the expected time regardless of the specified scan time. In that case, you need to call [ble.scan.startWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blescan.html#startwait) in onfinish to restart the scan. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); obniz.ble.scan.onfind = async function(peripheral){ console.log(peripheral.localName) }; obniz.ble.scan.onfinish = async function(peripherals, error){ console.log("scan again") await obniz.ble.scan.startWait(); }; await obniz.ble.scan.startWait(); } ``` ## Conditional search By specifying parameters when searching, you can narrow down to only specific devices. If you set more than one, only those that match any of them will be detected as search results. By using binary, it is possible to narrow down special beacons. [ScanTarget](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.ble.hci.blescantarget.html) - [uuids](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.ble.hci.blescantarget.html#uuids): Filter by UUID - [localName](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.ble.hci.blescantarget.html#localname): Filter by device name (exact match seatch) - [localNamePrefix](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.ble.hci.blescantarget.html#localnameprefix): Filter by device name (prefix search) (obniz.js 3.4.0 or later) - [deviceAddress](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.ble.hci.blescantarget.html#deviceaddress): Filter by device address (obniz.js 3.4.0 or later) - [binary](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.ble.hci.blescantarget.html#binary): Filter by partial match of binary string included in advertisement (obniz.js 3.4.0 or later) You can also change the scan settings, such as the length of time or switching between Active and Passive. There is a filterOnDevice property that filter on the device side, to lower the cost of communication, in obnizOS 3.2.0 or later. [ScanSetting](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.ble.hci.blescansetting.html) - [duration](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.ble.hci.blescansetting.html#duration): change the scan time (default is 30 seconds) - [duplicate](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.ble.hci.blescansetting.html#duplicate): Notify when receiving a new advertisement on the same device. The following is an example of specifying a name. - [activeScan](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.ble.hci.blescansetting.html#activescan): Specify wether it is an active scan (default is active) - [filterOnDevice](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.ble.hci.blescansetting.html#filterondevice): Specify wether to perform filtering on device (obnizOS 3.2.0 or later / obniz.js 3.4.0 or later) About filterOnDevice Communication cost can be reduced because the filter is executed according to the conditions specified on the device side. When running the filterOnDevice, it may receive the scanResponse of advertisement which is insufficient or vice versa. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var target = { localName: "Blank" }; obniz.ble.scan.onfind = async function(peripheral){ console.log(peripheral.localName) }; obniz.ble.scan.onfinish = async function(peripherals, error){ console.log("scan timeout!") }; await obniz.ble.scan.startWait(target); } ``` Increase the search time and be notified when you receive the advertisement again on the same device. This allows you to know when the data included in the advertisement or RSSI changes. ```javascript // Javascript Example var target = { localName: "Blank" }; var setting = { duration: 60, // 60 sec duplicate: true // allow duplicate } await obniz.ble.scan.startWait(target, setting); ``` You can also specify the UUID in the advertisement in addition to localName as a search condition. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var target = { uuids: ["1111"] }; obniz.ble.scan.onfind = async function(peripheral){ console.log(peripheral.localName) }; obniz.ble.scan.onfinish = function(){ console.log("scan timeout!") }; await obniz.ble.scan.startWait(target); } ``` For more complex search methods, see [Advanced Conditional Scanning](./central-scan-filter) . ## Search one Not only callback form but also waiting is possible. In particular, if you use [startOneWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blescan.html#startonewait), you can search for only one device. [startAllWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blescan.html#startallwait) is also available, which waits until all devices have been scanned without specifying any conditions. ```javascript // Javascript Example await obniz.ble.initWait(); var target = { localName: "Blank" }; var peripheral = await obniz.ble.scan.startOneWait(target); ``` ## Stop scanning [](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blescan.html#end)[ble.scan.endWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blescan.html#endwait) to stop running scan. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var target = { uuids: ["1111"] }; obniz.ble.scan.onfind = async function(peripheral){ console.log(peripheral.localName) }; obniz.ble.scan.onfinish = async function(peripherals, error){ console.log("scan timeout!") }; await obniz.ble.scan.startWait(target); await obniz.wait(1000); await obniz.ble.scan.endWait(); } ``` --- ## Central: Advanced conditional scanning URL: https://obniz.com/reference/common/ble/central-scan-filter # Advanced conditional scanning ## binary filter You can filter by the binary partial match of Advertisement/Scan Response. For example, - Flags LE General Discoverable Mode Simultaneous LE and BR/EDR to Same Device Capable (Controller) Simultaneous LE and BR/EDR to Same Device Capable (Host) - Local Name "Sample" This would be the following array of advertisements with information ```javascript // Javascript Example [0x02, 0x01, 0x1a, 0x07, 0x09, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65] ``` The first `[0x02, 0x01, 0x1a]` is Flags information, the second `[0x07, 0x09, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65]` LocalName. If you want to search only for advertisements with these flags, you can use `[0x02, 0x01, 0x1a]` with the data of `[02, 0x01, 0x1a]` as the filter condition. You can write it here. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var binaryFilter = [0x02, 0x01, 0x0a]; var target = { binary: [binaryFilter] }; obniz.ble.scan.onfind = async function(peripheral){ console.log(peripheral) }; obniz.ble.scan.onfinish = function(){ console.log("scan timeout!") }; await obniz.ble.scan.startWait(target, {filterOnDevice:true}); } ``` When using the binary filter, you need to filter on the device side, so you can use The `filterOnDevice` option is set to true. See also "Filter on device to reduce traffic" below binary filter allows for partial matches, so it is possible to include "ampl" in localName. You can also search for a device. The advertisement when "Sample" is LocalName is `[0x07, 0x09, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65]` was. The "ample" part of this will be `[0x61, 0x6d, 0x70, 0x6c]`, so Set this as a condition. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var binaryFilter = [0x61, 0x6d, 0x70, 0x6c]; //ample var target = { binary: [binaryFilter] }; obniz.ble.scan.onfind = async function(peripheral){ console.log(peripheral) }; obniz.ble.scan.onfinish = function(){ console.log("scan timeout!") }; await obniz.ble.scan.startWait(target, {filterOnDevice:true}); } ``` In this case, I know it's rarely a good idea, but other information in the advertisement (such as If an array of `[0x61, 0x6d, 0x70, 0x6c]` is found in (e.g. UUID) Please note that this applies to you as well. ## Combining multiple conditions The filter can specify more than one condition. In that case, all of the conditions are OR searches. Instead of stating multiple conditions to narrow down the device, the Use this to search for multiple devices at once. To search for a device whose localName is "Blank" or "Beacon", use The You can describe multiple conditions enclosed in an Array as follows. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var target = { localName: ["Blank", "Beacon"] //scan Blank *OR* Beacon }; obniz.ble.scan.onfind = async function(peripheral){ console.log(peripheral.localName) }; obniz.ble.scan.onfinish = async function(peripherals, error){ console.log("scan timeout!") }; await obniz.ble.scan.startWait(target); } ``` In addition to searching by the same local name, you can also add other search criteria, such as a UUID The following information is required. You can get the results that meet any of the following conditions by writing the following. Please note that this is all an OR search. - localNameが"Blank" - localNameが"Beacon" - Service UUID has 1111 - Service UUID has 2222 - binary include [0x02, 0x01, 0x1a] - binary include [0x61, 0x6d, 0x70, 0x6c] ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var target = { localName: ["Blank", "Beacon"], uuids: ["1111", "2222"] , binary: [[0x02, 0x01, 0x1a], [0x61, 0x6d, 0x70, 0x6c]] }; obniz.ble.scan.onfind = async function(peripheral){ console.log(peripheral.localName) }; obniz.ble.scan.onfinish = async function(peripherals, error){ console.log("scan timeout!") }; await obniz.ble.scan.startWait(target); } ``` ## Filtering on devices to reduce traffic BLE filtering is performed by the SDK (obnizjs) if you don't specify anything. In other words, the information is delivered from obnizOS to the SDK, and the SDK filters it out, and `onfind` is called by hand. Turning on the `filterOnDevice` setting will not cause communication to the SDK. You can filter within obnizOS. ![](images/filter.png) ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var binaryFilter = [0x02, 0x01, 0x0a]; var target = { binary: [ binaryFilter ] }; obniz.ble.scan.onfind = async function(peripheral){ console.log(peripheral) }; obniz.ble.scan.onfinish = function(){ console.log("scan timeout!") }; await obniz.ble.scan.startWait(target, {filterOnDevice:true}); } ``` --- ## Central: Connection URL: https://obniz.com/reference/common/ble/central-connect There are two methods to connect to BLE peripheral. - Connect to a peripheral found by scanning. - Connect without scanning by specifying the device address. ### Scanning Use [bleRemotePeripheral.connectWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremoteperipheral.html#connectwait) to connect to the peripheral found by scanning. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var target = { localName: "Blank" }; var peripheral = await obniz.ble.scan.startOneWait(target); if(peripheral) { console.log("found"); try { await peripheral.connectWait(); console.log("connected"); } catch(e) { console.error(e); } } } ``` It is not possible to scan while connecting, so scanning will be stop automatically when connecting starts. After connecting succeeded, you can run scanning again. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var target = { uuids: ["1111"] }; obniz.ble.scan.onfind = async function(peripheral){ try { await peripheral.connectWait(); console.log("connected"); await obniz.ble.scan.startWait(target); } catch(e) { console.error(e); } }; obniz.ble.scan.onfinish = function(){ obniz.ble.scan.start(target); }; await obniz.ble.scan.startWait(target); } ``` Connected peripherals can be access from [getConnectedPeripherals()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.obnizble.html#getconnectedperipherals). ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var target = { uuids: ["1111"] }; obniz.ble.scan.onfind = async function(peripheral){ try { await peripheral.connectWait(); console.log("connected"); console.log(obniz.ble.getConnectedPeripherals()); // => array of peripherals } catch(e) { console.error(e); } }; obniz.ble.scan.onfinish = async function(peripherals, error){ await obniz.ble.scan.startWait(target); }; await obniz.ble.scan.startWait(target); } ``` ### Connect without scanning You can connect a device of which you have the address, for example, you scanned it before, using [directConnectWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.obnizble.html#directconnectwait) function or [directConnect()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.obnizble.html#directconnect) function. It will cause saving time in case there are lots of peripherals. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); try { var peripheral = await obniz.ble.directConnectWait("e4b9efb29218", "random"); console.log("connected"); } catch(e) { console.log("can't connect"); } } ``` ## Automatic search for services and characteristis obniz.js automatically searches for services of the peripheral and characteristics and descriptors associated with it after the BLE connection is completed, and connecting to them is also completed just after searching finished, so it is possible to operate all services and below immediately. If you don't want it to search automatically due to problems such as connection time, set the argument of [bleRemotePeripheral.connectWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremoteperipheral.html#connectwait) to `{autoDiscovery:false}`. In that case, you need to search for services and characteristics manually, so you need to use [bleRemoteService.discoverAllCharacteristicsWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremoteservice.html#discoverallcharacteristicswait) or [bleRemoteCharacteristic.discoverAllDescriptorsWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#discoveralldescriptorswait). ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait({}); obniz.ble.scan.onfind = async function(peripheral){ if(peripheral.localName == "my peripheral"){ peripheral.onconnect = async function(){ console.log("success"); await peripheral.discoverAllServicesWait(); //manually discover let service = peripheral.getService("1800"); await service.discoverAllCharacteristicsWait(); //manually discover let characteristics = service.getCharacteristic("ff00"); await characteristics.discoverAllDescriptorsWait(); //manually discover let descriptor = characteristics.getDescriptor("fff1"); } peripheral.connect({autoDiscovery:false}); } } await obniz.ble.scan.startWait(); } ``` ## LE Secure Connect obniz can handle LE Secure Connect. By default, it is not used. You should enable by providing `secureConnection:true` on `pairingOption`. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var target = { uuids: ["1111"] }; obniz.ble.scan.onfind = async function(peripheral){ try { await peripheral.connectWait({ pairingOption: { secureConnection: true }}); console.log("connected"); } catch(e) { console.error(e); } }; obniz.ble.scan.onfinish = async function(peripherals, error){ await obniz.ble.scan.startWait(target); }; await obniz.ble.scan.startWait(target); } ``` ## Error handling In case the other party left while communication or impossible thing is requested, error will occur. The error that occurred with peripheral is received by the function set in [bleRemotePeripheral.onerror](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremoteperipheral.html#onerror). ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var target = { localName: "Blank" }; var peripheral = await obniz.ble.scan.startOneWait(target); if(peripheral) { console.log("found"); try { await peripheral.connectWait(); peripheral.onerror = function(err){ console.log("error : " + err.message); } console.log("connected"); } catch(e) { console.error(e); } } } ``` ## Disconnection Use [disconnectWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremoteperipheral.html#disconnectwait) to disconnect peripherals. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var target = { localName: "Blank" }; var peripheral = await obniz.ble.scan.startOneWait(target); if(peripheral) { try { console.log("found"); await peripheral.connectWait(); console.log("connected"); await peripheral.disconnectWait(); console.log("disconnected"); } catch(e) { console.error(e); } } } ``` --- ## Central: Pairing URL: https://obniz.com/reference/common/ble/central-pairing ## Automatic pairing Obniz.js includes a mechanism to automate pairing. If an authentication error returns When reading or writing characterisics or descriptor, obniz.js will automatically try to pair it. It's automatic, so no configuration is required. Instead, it is not possible to enter passkey or bind (save key information). The settings for automatic pairing are as follows - IO capability: NoInputNoOutput - OOB data: Authentication data not present - Authentication requirement: Bonding - No MITM - Max encryption key size: 16octet For other settings (such as wanting to enter a passkey), please perform the manual pairing. ### Pairing Flow The pairing is requested by the peripheral when the peripheral deems it needs to be done. This means that when it takes place depends on the peripherals. Pairing can also be done intentionally from the central server. Some peripherals need to be paired at the time of connection. Normally it is done as is, but if you need a passkey, or if you want to save the LTK, or if you want to catch errors, you need to set the `connectWait()` function to do so as an option. The functions specified in `pairingOption` will be called only when pairing is required. In other words, connectWait() itself will be completed as soon as the connection is successful, and the functions in `pairingOption` will be called at any time. ## passkey Some peripherals require a passkey (PIN code) to be entered when pairing, and obniz.js allows you to specify a passkey callback to support it. ```javascript // Javascript Example await obniz.ble.initWait({}); obniz.ble.scan.onfind = async function(peripheral){ if(peripheral.localName == "my peripheral"){ await peripheral.connectWait({ pairingOption: { passkeyCallback: async () => { return 012345; }, onPairedCallback: (keys) => { console.log(`paired ${keys}`) }, onPairingFailed: () => { console.log(`pairing failed`); } }, }); } } await obniz.ble.scan.startWait(); ``` ## LTKを取得 Long Term Key(LTK) can be retrieved on [onPairedCallback](https://obniz.github.io/obniz/obnizjs/interfaces/obnizcore.components.ble.hci.blepairingoptions.html#onpairedcallback) ```javascript // Javascript Example await obniz.ble.initWait({}); obniz.ble.scan.onfind = async function(peripheral){ if(peripheral.localName == "my peripheral"){ await peripheral.connectWait({ pairingOption: { passkeyCallback: async () => { return 012345; }, onPairedCallback: (keys) => { console.log(`paired ${keys}`) }, onPairingFailed: () => { console.log(`pairing failed`); } }, }); } } await obniz.ble.scan.startWait(); ``` Pairing with a saved LTK is done as follows. If it fails, `onPairingFailed()` will be called. However, if it succeeds, `onPairedCallback()` will not be called. ```javascript // Javascript Example await obniz.ble.initWait({}); obniz.ble.scan.onfind = async function(peripheral){ if(peripheral.localName == "my peripheral"){ const keys = '*****'; await peripheral.connectWait({ pairingOption: { keys, }, }); } } await obniz.ble.scan.startWait(); ``` Or use pairingWait() if the peripheral does not need to be paired at connection time. ```javascript // Javascript Example const keys = "xxxxxx"; await obniz.ble.initWait({}); obniz.ble.scan.onfind = async function(peripheral){ if(peripheral.localName == "my peripheral"){ await peripheral.connectWait(); console.log("connected"); await peripheral.pairingWait({ keys }); console.log("paired"); } } await obniz.ble.scan.startWait(); ``` ## Pairing from central Use the peripheral.pairingWait function to intentionally pair from the central side. ```javascript // Javascript Example await obniz.ble.initWait({}); obniz.ble.scan.onfind = async function(peripheral){ if(peripheral.localName == "my peripheral"){ await peripheral.connectWait(); console.log("success"); const keys = await peripheral.pairingWait({ onPairedCallback: (keys) => { console.log(`paired ${keys}`) }, onPairingFailed: () => { console.log(`pairing failed`); } }); // Please store `keys` if you want to bond. } } await obniz.ble.scan.startWait(); ``` --- ## Central: Services and characteristics URL: https://obniz.com/reference/common/ble/central-services-and-characteristics How to access services and characteristics included in BLE peripherals. obniz.js automatically searches for services of the peripheral and characteristics and descriptors associated with it after the BLE connection is completed, and connecting to them is also completed just after searching finished, so it is possible to operate all services and below immediately. ## Services Services associated with peripherals ([bleRemoteService](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremoteservice.html)) are stored in [peripheral.services](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremoteperipheral.html#services) in the form of an a array. By using [peripheral.getService()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremoteperipheral.html#getservice), you can get the services with a certain UUID contained in it. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var target = { uuids: ["fff0"], }; var peripheral = await obniz.ble.scan.startOneWait(target); if(!peripheral) { console.log('no such peripheral') return; } try { await peripheral.connectWait(); console.log("connected"); console.log("number of services=" + peripheral.services.length); var service = peripheral.getService("1800") if (!service) { console.log("service not found") return; } console.log(service.uuid) // => 1800 } catch(e) { console.error(e); } } ``` ## Characteristics You can also get the characteristics associated with the [services](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremoteservice.html) ([bleRemoteCharacteristics](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html)) in a similar way. It is stored in [service.characteristics](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremoteservice.html#characteristics) as an array, and [characteristic](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html) using UUID can be found by [service.getCharacteristic()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremoteservice.html#getcharacteristic). ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var target = { uuids: ["fff0"], }; var peripheral = await obniz.ble.scan.startOneWait(target); if(!peripheral) { console.log('no such peripheral') return; } try { await peripheral.connectWait(); console.log("connected"); console.log("number of services=" + peripheral.services.length); var service = peripheral.getService("1800"); var c = service.getCharacteristic("fff0"); console.log(c.uuid); // => "fff0" } catch(e) { console.error(e); } } ``` --- ## Central: Read and Write URL: https://obniz.com/reference/common/ble/central-read-write [Characteristics](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html) have a value, and some properties allow reading and writing via BLE. [characteristic.properties](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#properties) contains properties that tell you what is permitted. You can check if the property is included using the [canWrite()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#canwrite) function. ```javascript // Javascript Example console.log(characteristics.properties); // => ['read', 'write', 'notify'] characteristics.canWrite(); // => true ``` ## Write - [writeWait(number array)](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#writewait): Write data array. - [writeNumberWait(number)](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#writenumberwait): Receive numbers and write them as a data array. - [writeTextWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#writetextwait): UTF8-encode character strings and write them as a data array. - [readWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#readwait): Read data in an array. ```javascript // Javascript Full Example await obniz.ble.initWait(); var target = { uuids: ["fff0"], }; var peripheral = await obniz.ble.scan.startOneWait(target); if(peripheral){ await peripheral.connectWait(); console.log("connected"); await obniz.wait(1000); var dataArray = [0x02, 0xFF]; await peripheral.getService("FF00").getCharacteristic("FF01").writeWait(dataArray); console.log("write success"); } ``` ## Read characteristicの値の読み込みには[readWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#readwait) を利用します。書き込んだのが文字列や数値だったとしてもバイト列として返ってきます。 Use [readWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#readwait) to read the value of characteristics. Even if what was written is a string or a number, it will be returned as a byte string. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var peripheral = await obniz.ble.scan.startOneWait({ localName: "Blank" }); if(peripheral) { console.log("found"); try{ await peripheral.connectWait(); console.log("connected"); var service = peripheral.getService("1111"); var char = service.getCharacteristic("2222"); var data = await char.readWait(); console.log(data); // => ex [0x02, 0xFF]; }catch(e){ console.log("connection failed"); } } } ``` --- ## Central: Receiving change notifications URL: https://obniz.com/reference/common/ble/central-subscribe In addition to one-way read/write from central, BLE has a system that informs change of value from peripheral devices to central devices; it is called Notify. ## What is Notify? Notify is a function allows peripheral to inform central that the value of this characteristics has changed. You can use this by following steps. 1. Set from central to peripheral that you want to monitor this characteristics. 2. Peripheral can send Notify to central if the value changes (actually, even if it doesn't change). 3. Central receives it and then reads the value to get the latest information. ## Monitoring registration and data reception Use [characteristic.registerNotifyWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#registernotifywait) to register characteristics for Notify. The function specified as an argument is performed when Notify comes from peripheral. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var peripheral = await obniz.ble.scan.startOneWait({ localName: "Blank" }); if(peripheral) { console.log("found"); await peripheral.connectWait(); console.log("connected"); var service = peripheral.getService("1111"); var char = service.getCharacteristic("2222"); await char.registerNotifyWait((data) => { console.log("notify with data " + data.join(',')); }); } } ``` It is also possible to describe in callback format using [characteristic.registerNotify()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#registernotify) and [characteristic.onregisternotify](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#onregisternotify). ## Unregister Use [characteristic.unRegisterNotifyWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#unregisternotifywait) when you don't have to receive Notify. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var peripheral = await obniz.ble.scan.startOneWait({ localName: "Blank" }); if(peripheral) { console.log("found"); await peripheral.connectWait(); console.log("connected"); var service = peripheral.getService("1111"); var char = service.getCharacteristic("2222"); await char.registerNotifyWait(async (data) => { console.log("notify with data " + data.join(','));    await char.unregisterNotifyWait(); }); } } ``` It is also possible to describe in callback format using [characteristic.unRegisterNotify()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#unregisternotify) and [characteristic.onunregisternotify](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleremotecharacteristic.html#onunregisternotify). --- ## Peripheral: Advertisement URL: https://obniz.com/reference/common/ble/peripheral-advertisement Use obniz as a peripheral device of BLE. In other words, obniz is connected by computers or smartphones. Generally, resister services and characteristics, and then send the advertisement according to them, assuming that it will be connected. However, advertisement is one of the strongest feature of BLE, and it makes it possible to run for a long time with battery operation because data such as temperature can be sent without connection. It can also be used in case the existence is all you need, such as a lost tag. For those reasons, in obniz, you don't need characteristics to use only the information of advertisement. ## Two types of advertisement There are two types of advertisement of BLE, normal one and scan response. BLE advertisement continues to send out by itself, but some data may not be sent because its capacity is small. So the central side can ask peripherals whether there is more data, and then, what the peripheral returns is a scan response. LocalName is usually sent as a scan response. The important thing sent in an advertisement is UUID of its services. It can offer the information about the services it has. ## Sending advertisement You can set both the advertisement and the scan response of it to [ble.advertisement](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleadvertisement.html). Specify the advertisement in json format by [ble.advertisement.setAdvData()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleadvertisement.html#setadvdata). When you need a scan response, specify it in json, using [ble.advertisement.setScanRespData()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleadvertisement.html#setscanrespdata). Advertisement starts by [ble.advertisement.start()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleadvertisement.html#start) and continues to send data until [ble.advertisement.end()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleadvertisement.html#end) is called. In the following way, the device transmits that it has the service whose UUID is 1234 by advertisement, and sends the device name "obniz BLE" in the scan response. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); obniz.ble.advertisement.setAdvData({ serviceUuids: ["1234"] }); obniz.ble.advertisement.setScanRespData({ localName : "obniz BLE", }); obniz.ble.advertisement.start(); } ``` The transmission interval of advertisement is fixed at 1.28 seconds. #### Advanced settings You can set not only serviceUuids or localName but also other information of advertisement. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); obniz.ble.advertisement.setAdvData({ flags: ["general_discoverable_mode","br_edr_not_supported"], manufacturerData:{ companyCode : 0x004C, data : [0x02,0x15, 0xC2, 0x8f, 0x0a, 0xd5, 0xa7, 0xfd, 0x48, 0xbe, 0x9f, 0xd0, 0xea, 0xe9, 0xff, 0xd3, 0xa8, 0xbb,0x10,0x00,0x00,0x10,0xFF], }, }); obniz.ble.advertisement.setScanRespData({ localName : "obniz BLE", }); obniz.ble.advertisement.start(); } ``` #### Settings by binary string There are two advertisement that can be directly registered in binary format without using json, [setAdvDataRaw()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleadvertisement.html#setadvdataraw) and [setScanRespDataRaw()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleadvertisement.html#setscanrespdataraw). ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); obniz.ble.advertisement.setAdvDataRaw([0x02, 0x01, 0x1A, 0x07, 0x09, 0x53, 0x61, 0x6D, 0x70, 0x6C, 0x65 ]); obniz.ble.advertisement.setScanRespDataRaw([0x07, 0x09, 0x53, 0x61, 0x6D, 0x70, 0x6C, 0x65 ]); obniz.ble.advertisement.start(); } ``` --- ## Peripheral: Services and characteristics registration URL: https://obniz.com/reference/common/ble/peripheral-service-characteristic To external connection, you have to prepare services and characteristics, and set them to obniz. ## Services and characteristics class Dedicated classes are provided for services and characteristic. - [bleService](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleservice.html) - [bleCharacteristic](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blecharacteristic.html) For example, the services whose UUID is 1234 can be created as follows. ```javascript // Javascript Example var service = new obniz.ble.service({ uuid : "1234" }); ``` [service.advData](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleservice.html#advdata) stores advertisement information necessary to output with [ble.advertisement](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleadvertisement.html), so it can be used as it is. ```javascript // Javascript Example var service = new obniz.ble.service({ uuid : "1234" }); obniz.ble.advertisement.setAdvData(service.advData); ``` In order to generate characteristics, UUID is also needed. Additionally, create a value using "data." ```javascript // Javascript Example var characteristic = new obniz.ble.characteristic({ uuid : "7777", data: [1, 2, 3]}); ``` ## Registration You can add characteristics to a service by [service.addCharacteristic()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleservice.html#addcharacteristic), and services to a peripheral by [peripheral.addService()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleperipheral.html#addservice). By adding it to peripheral, when someone connects to it, they can see, read and write these services and characteristics. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); var service = new obniz.ble.service({ uuid : "1234" }); var characteristic = new obniz.ble.characteristic({ uuid : "7777", data: [1, 2, 3]}); service.addCharacteristic(characteristic); obniz.ble.peripheral.addService(service); obniz.ble.advertisement.setAdvData(service.advData); obniz.ble.advertisement.setScanRespData({ localName : "obniz BLE", }); obniz.ble.advertisement.start(); } ``` ## Connection notification Your peripheral device may actually be connected from another device. Use [peripheral.onconnectionupdates](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.bleperipheral.html#onconnectionupdates) know that it is connected. The function set in this property is called when another device starts connecting. The argument have the address and connection status of the other device. This function is called not only when connecting but also when disconnecting. When the device is connected, data.status="connected." When disconnected, data.status="disconnected." ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); obniz.ble.peripheral.onconnectionupdates = function(data){ if (data.status === "connected") { console.log("connected from remote device ", data.address) } else if (data.status === "disconnected") { console.log("disconnected from remote device ", data.address) } }; var service = new obniz.ble.service({ uuid : "1234" }); var characteristic = new obniz.ble.characteristic({ uuid : "7777", data: [1, 2, 3]}); service.addCharacteristic(characteristic); obniz.ble.peripheral.addService(service); obniz.ble.advertisement.setAdvData(service.advData); obniz.ble.advertisement.setScanRespData({ localName : "obniz BLE", }); obniz.ble.advertisement.start(); } ``` --- ## Peripheral: Monitoring update URL: https://obniz.com/reference/common/ble/peripheral-recognize-updates The other devices can connect to obniz using BLE and read or write the value of characteristics. You can notice read/write by setting a function called when such an event occurs. ## Reading notification By specifying a function in [peripheral.onreadfromremote](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blecharacteristic.html#onreadfromremote), you can know that the value of the characteristics has been read. This function is called every time the value is read. ```javascript // Javascript Example characteristic.onreadfromremote = function(address){} ``` ## Writing notification You can detect writing by specifying a function in [characteristic.onwritefromremote](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blecharacteristic.html#onwritefromremote). "address" stores the address of the central and "newvalue" has the value written by it. ```javascript // Javascript Example characteristic.onwritefromremote = function(address, newvalue){ } ``` --- ## Peripheral: Update values URL: https://obniz.com/reference/common/ble/peripheral-update-values You can rewrite the characteristic values registered, regardless of whether the other party is connected or not. ## Rewrite Some other devices may rewrite the characteristic values via BLE, but you can also change it. You can update the value using [characteristic.writeWait()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blecharacteristic.html#writewait). In following example, the characteristic value is \[1,2,3\] at first, but it is immediately replaced by \[0xFF\]. You can read 0xFF from other devices via BLE. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait(); obniz.ble.peripheral.onconnectionupdates = function(data){ console.log("remote device ", data.address, data.status) }; var service = new obniz.ble.service({ uuid : "1234" }); var characteristic = new obniz.ble.characteristic({ uuid : "7777", data: [1, 2, 3]}); service.addCharacteristic(characteristic); obniz.ble.peripheral.addService(service); obniz.ble.advertisement.setAdvData(service.advData); obniz.ble.advertisement.setScanRespData({ localName : "obniz BLE", }); obniz.ble.advertisement.start(); await characteristic.writeWait([0xFF]) // over write } ``` --- ## Peripheral: Notification of value change URL: https://obniz.com/reference/common/ble/peripheral-notify-updates When obniz is used as a BLE peripheral, other devices connect the obniz device via BLE and read or write values. The value can be rewritten by the device via BLE if it has write permission, or change by itself. However, just change the value is not enough and use Notify to tell the other party that the value has changed. ## Notify changes You can use the [characteristic.notify()](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blecharacteristic.html#notify) function to notify the connected device that a characteristic value has changed. The characteristics must have a property that allows Notify to be sent. To be specific, "notify" is necessary in property, and CCCD in descriptor. You have to set the CCCD in the descriptor item as follows when creating characteristics. It is also necessary that the connected party [subscribe](/reference/common/ble/central-subscribe/) to receive the notify. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { await obniz.ble.initWait();  // create servce & characteristics var service = new obniz.ble.service({ uuid : "1234" }); var characteristic = new obniz.ble.characteristic({ uuid : "7777", data: [1, 2, 3], properties : ["read","write","notify"], // add notify properties descriptors: [ { uuid: '2902', //CCCD data: [0x00, 0x00], //2byte }, ], }); service.addCharacteristic(characteristic); obniz.ble.peripheral.addService(service); // advertisement obniz.ble.advertisement.setAdvData(service.advData); obniz.ble.advertisement.setScanRespData({ localName : "obniz BLE", }); obniz.ble.advertisement.start(); // on connection obniz.ble.peripheral.onconnectionupdates = function(data){ console.log("remote device ", data.address, data.status) setTimeout(async function(){ await characteristic.writeWait([0xFF]) characteristic.notify(); }, 10000) }; } ``` --- ## Connected Network URL: https://obniz.com/reference/common/connected_network > [Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#constructor) > [API Reference](/reference/websocket/ws) > obniz.js v3.18.0 or later Obtains information about the network to which the device is actually connected. You can check the information available in the device management screen. The information that can be obtained depends on the version of obnizOS and the network being connected. Please refer to the reference for details. Information can be retrieved from `connected_networks` after obniz.js has connected to the device. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { console.log(obniz.connected_network); if (obniz.connected_network) { console.log(obniz.connected_network.online_at); // ex) 1637685862 console.log(obniz.connected_network.local_ip); // ex) 192.168.0.100 console.log(obniz.connected_network.global_ip); // ex) 201.200.199.198 if (obniz.connected_network.wifi) { console.log(obniz.connected_network.wifi.ssid); // ex) obniz-wifi console.log(obniz.connected_network.wifi.rssi); // ex) -70 } } } ``` --- ## Metadata URL: https://obniz.com/reference/common/cloud/metadata > [Metadata Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#metadata) > [Metadata API Reference](http://localhost:3000/ja/reference/websocket/ws#response-obniz) Metadata is a per-obniz setting that can be configured by the user on the obniz cloud. Metadata is loaded when connecting to the cloud and can be read from the `metadata` property. Metadata is loaded when connecting to the cloud and can be read from the `metadata` property. It can be used to read information such as the description of the device and the API key, which can be used to make each device work differently. ![](../images/metadata.png) The properties can be read after the connection is completed. Also, all data is of string type. Any metadata changed on the Cloud will be updated the next time you connect. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function () { console.log(obniz.metadata.description); if (obniz.metadata.mode === 'debug') { obniz.io0.output(true); console.log(`debug mode`); } } ``` --- ## Messaging URL: https://obniz.com/reference/common/cloud/messaging > [Message Class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.obniz.html#onmessage) > [Message API Reference](/reference/websocket/message) obniz can receive and transfer data from HTTP request. Using this function you can also send data from one obniz to another. ## [](https://github.com/obniz/obniz/blob/v3.3.0/messaging.md#api---obniz-messaging)API - obniz messaging You can send a message to an obniz by calling the REST API. ```shell GET https://obniz.com/obniz/{obniz_id}/message?data={what you want to send} ``` For example, send "move" text message to obniz 0000-0000 as below. ```shell GET https://obniz.com/obniz/0000-0000/message?data=move ``` And obniz 0000-0000 will get the message as long as it is online. You can do something on that event. 404 is returned when obniz is not online. ```javascript // Javascript Example // Example obniz.onconnect = function() { var motor = obniz.wired("ServoMotor", {gnd:0, vcc:1, signal:2}); motor.angle(0); obniz.onmessage = function(message, from) { if (message === "move") { motor.angle(85); } }; } ``` You can do this with POST method to send to multiple destinations. ```shell POST https://obniz.com/obniz/message ``` Parameters - to: destination separated by "," - data: message ## [](https://github.com/obniz/obniz/blob/v3.3.0/messaging.md#obniz---obniz-messaging)obniz - obniz messaging Below is an example of pressing one button to move the hands of 10 robots aroudn the world simultaneously. First, prepare an obniz with one button connected, and send a message to 10 obniz when that button is pressed. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function(){ var button = obniz.wired("Button", {signal:0, gnd:1}); button.onchange = function(){ var targets = [ "1234-1231", "1234-1232", "1234-1233", "1234-1234", "1234-1235", "1234-1236", "1234-1237", "1234-1238", "1234-1239", "1234-1230"]; obniz.message(targets, "pressed"); }; } ``` obniz ids written in targets are the destinations. and "pressed" is message. The 10 obniz will handle this message with onmessage function. With that function, servomotor attached to each obniz will be moved in response to the message. ```javascript // Javascript Full Example var obniz = new Obniz("OBNIZ_ID_HERE"); obniz.onconnect = async function(){ var motor = obniz.wired("ServoMotor", {gnd:0, vcc:1, signal:2}); motor.angle(0); obniz.onmessage = function(message, from) { if (message === "pressed") { motor.angle(85); } }; } ``` --- ## App URL: https://obniz.com/reference/common/cloud/app > [App Class Reference](https://obniz.github.io/obniz/obnizjs/modules/obnizapp.html) `Obniz.App` is a utility class with useful features in [app](/reference/cloud/app/). > When you create a browser app in obniz cloud and run it in the browser or cloud, some global variables are inserted into the HTML. This class provides a way to handle them conveniently. ## Obniz.App.configs() You can read the settings you made during the installation of the app. It can be used in both the app's browser and cloud execution. ```javascript // JavaScript Example const userconfig = Obniz.App.configs(); console.log(userconfig.watering_interval); // User configured value ``` ## Obniz.App.isCloudRunning() Differentiate whether the app is running in the obniz cloud or in the user's browser. ```javascript // JavaScript Example if (Obniz.App.isCloudRunning()) { const req = Obniz.App.req(); console.log(req.query); console.log(req.body); } ``` ## Obniz.App.req() Contains a request object when executed in the cloud in the wake of a webhook. ```javascript // JavaScript Example if (Obniz.App.isCloudRunning()) { const req = Obniz.App.req(); console.log(req.query); console.log(req.body); } ``` ## Obniz.App.done() Terminate the cloud execution and record the results. You can choose from the following two types of status - 'success'. - 'error' The text can be any string ```javascript // JavaScript Example if (Obniz.App.isCloudRunning()) { var temp = '27' Obniz.App.done({ status: 'success', text: `${tmp} degree` }) } ``` --- ## Plugin / Lua URL: https://obniz.com/reference/common/plugin > [Plug-in class Reference](https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.plugin.html) > [Lua examples on GitHub](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin) > Available for OS7 and later The [Plugin](/reference/obnizos-for-esp32/lua/) is a feature that allows you to expand the functionality of your device by adding code. It can be executed on the device as a small app controlled by the OS, while maintaining the standard operations of obnizOS. This enables advanced optimization directly on the obniz device, such as offline operations and the compression of communication data. **What You Can Do with the Lua Plugin** - Start recording data from the moment the device boots up. - Perform specific actions regardless of whether the device is online or offline. - Send only specific data to the server or perform data compression. - Receive specific data or operate I/O pins at regular intervals. - Monitor device status offline, enter sleep mode, and connect to the internet only when data needs to be sent. ![](./images/lua.png) ## Writing and Execution Lua scripts will start immidiately on startup by OS regardless network connection status. To write Lua scripts from obniz.js (instead of using the serial console), you can send and save a string as shown below. Use `obniz.storage.savePluginLua()` to overwrite the internal flash memory. Note that this method only performs the overwrite; the changes will take effect after a reboot. To apply changes immediately, call `obniz.plugin.reloadLua()`. :::warning The obniz Board series and early obniz BLE/Wi-Fi Gateway models have no internal storage, so they cannot execute `obniz.storage.savePluginLua` or access storage from within Lua. As a result, they cannot read and run Lua from the device itself after a reboot. Lua can only be executed on demand via `obniz.plugin.execLua()` while the device is powered on. Functions such as `loop` will continue to run even when started with `execLua`, until the device is restarted. ::: ```javascript // Javascript Example obniz.storage.savePluginLua(` os.log("Hello World") `); obniz.plugin.reloadLua(); ``` ### Preventing Redundant Writes Rewriting the plugin on every connection will negatively impact the lifespan of the internal flash memory. Therefore, it is important to implement a check to skip writing if the expected Lua script is already present. obnizOS transmits the **name of the Lua script loaded at startup**. You can prevent redundant writes by comparing this name. The property `obniz.plugin_name` contains the name of the plugin used during startup. You can specify this name within the Lua script as the return value of the `plugin_name()` function. ```javascript // Javascript Example if (obniz.plugin_name !== 'my_plugin') { console.log("Must Load Plugin"); obniz.storage.savePluginLua(` function plugin_name() return "my_plugin" -- max 30 chars end `); obniz.plugin.reloadLua(); obniz.reboot(); // Not necessary in every case. } else { console.log("No Need to Load Plugin"); } ``` ## On-the-fly Execution Lua scripts can be executed at any time via the SDK without being saved to the device's permanent storage. ```javascript // Javascript Example obniz.plugin.execLua(` x=1; x=x+2; os.log(x.."\\n") `); // will print "3" on the obnizOS console (requires console to be enabled) obniz.plugin.execLua(`os.log(os.getTick().."\\n")`); obniz.plugin.execLua(`os.log(os.getTick().."\\n")`); ``` By using this feature, you can update necessary functions and variables on demand without rebooting the device. This enables high-speed optimization of device behavior and maximum compression of communication traffic without incurring any downtime. **Example: Changing communication frequency from the cloud based on values** ```javascript // Javascript Example if (temperature > 26) { obniz.plugin.execLua(` interval = 1; `); } else { obniz.plugin.execLua(` interval = 60; `); } ``` **Example: Switching the type of transmitted data based on modes** ```javascript // Javascript Example if (mode == 'temperature') { obniz.plugin.execLua(` function filter(data) if data.temperature == nil then return nil end return data end `); } else { obniz.plugin.execLua(` function filter(data) return data end `); } ``` ## obniz.plugin.onError > Available for OS7.1.0 and later This event handler receives errors raised by the Lua plugin on the device. It is called whenever a script fails, including scripts started with `execLua()` and the plugin loaded at startup. ```javascript // Javascript Example obniz.plugin.onError = (error) => { console.log(`error occurred: ${error.message}`); }; // A failing script triggers onError obniz.plugin.execLua(`MUST FAILED`); ``` The `error` argument is an object with a `message` property describing the Lua error. ## on_low_memory(largestFreeBlock) > Available for OS7.1.0 and later When free memory on the device runs low, the OS calls `on_low_memory()` before an allocation can fail. The argument is the largest contiguous free block, in bytes, which represents the real headroom for the next allocation. Define this handler to release tables, buffers, or other resources you no longer need, so the plugin can recover instead of crashing. ```lua function on_low_memory(largestFreeBlock) os.log("low memory: " .. tostring(largestFreeBlock)); -- Release what you can spare cache = nil; end ``` The OS calls this handler in two cases: proactively, when a garbage collection cannot restore enough memory, and as a last resort, when an allocation has already failed. To avoid recursion, the handler is not called again while it is already running. ## Total of Lua functions ```lua -- System Event Handler function on_event(event) if event == "power_on" then elseif event == "setting_mode" then elseif event == "connecting_to_network" then elseif event == "connecting_to_cloud" then elseif event == "online" then end end -- func(int), module(int), data(string(uint8 array)) function on_upstream(func, module, data) if necessary then return 1; elseif rightnow then return 2; elseif mustDrop then cloud.upstreamEnqueue(1, 2, str); -- change to differenct command cloud.upstreamFlush(); -- optional return 0; end end -- received from obnis.js function on_command(command) cloud.pluginSend("123"); end -- called while online every around 1msec function on_online_loop() -- os.log(\"online_loop\"); end -- called while offline every around 1msec -- You should care about communication because this function will be called -- different thread. function on_offline_loop() -- os.log(\"offline_loop\"); end function on_self_check() os.log(" - self check ok"); end -- called when free memory runs low (OS7.1.0+). -- The argument is the largest contiguous free block in bytes. -- Release resources here to avoid an out-of-memory crash. function on_low_memory(largestFreeBlock) os.log("low memory: " .. tostring(largestFreeBlock)); end function plugin_name() -- will be get by obniz.plugin_name return "my_plugin" end -- Available Functions -- OS os.getTick(); -- system tick in msec os.getUnixTime(); -- get seconds from 1970/1/1. you must adjust time by calling pingWait(); os.log("hello world"); os.wait(1000); -- 1,000msec wait os.reboot(); os.resetOnDisconnect(false); -- It will never reset after disconnection. And queued data never lost when offline. os.sleep(5 * 1000, 0); -- deep sleep + external module sleep. os.sleep(5 * 1000, 1); -- deep sleep + without external module sleep. os.sleep(5 * 1000, 2); -- light sleep + external module sleep. os.sleep(5 * 1000, 3); -- light sleep + without external module os.getVersion(); os.getHW(); -- storage file storage.fileOpen("text.txt") storage.fileWrite("ABC"); storage.fileAppend("abcdefg"); length = storage.fileGetSize(); data = storage.fileRead(0, length); storage.fileClose(); -- storage kvs error = storage.kvsSave({ name = "Yuki", attr = { engineer = true } }) data = storage.kvsLoad(); -- Cloud cloud.connect(); cloud.disconnect(); cloud.upstreamEnqueue(0, 1, data) -- module func data cloud.pluginSend(data); cloud.pluginSendFrameStart(frame_id, length); -- framing cloud.pluginSendFrameEnd(); -- framing cloud.enqueueTimestampByTick(os.getTick()-1000); -- it will enqueue unix timestamp -- cloud transaction (OS7.1.0+, must run inside a coroutine / callWait) local success, result = cloud.transactionWait("ping", 5000); -- data, [callback], [timeout_ms] -- io io.retain(1, true); io.output(1, true); local val = io.input(1); io.drive(1, "5v"); -- OS7.1.0+ : "push-pull3v"(default) / "5v" / "open-drain" io.pull(1, "3v"); -- OS7.1.0+ : "float"(default) / "5v" / "3v" / "0v" -- ad local val = ad.get(1); -- 0.0v~3.3v -- pwm (OS7.1.0+) pwm.start(1); -- start PWM on a logical obniz IO pwm.freq(1, 1000); -- frequency in Hz pwm.duty(1, 50); -- duty cycle 0-100% pwm.stop(1); -- stop and release the IO -- uart uart.start(1, 2, 9600) -- tx:io1 rx:io2 baud:9600 uart.send("hello"); local data = uart.recv() -- uart.recv(1) limit to 1byte max if #data > 1 then os.log(data); -- received end local used = uart.isUsed(); -- OS7.1.0+ : true once uart.start() succeeded -- spi local err = spi.start(20, 21, 19, 8, 100 * 1000); -- MOSI, MISO, CLK, CS(could be null for non shared SPI), baudrate if err > 0 then os.log("SPI Error: " .. err); return end let result = spi.write(string.char(0x40, 0x00, 0xC0)); -- result must be 3bytes if success. local used = spi.isUsed(); -- OS7.1.0+ : true once spi.start() succeeded -- display (OS7.1.0+, no-op on products without a display) display.print("Hello"); -- append a string at the cursor display.clear(); -- clear the screen display.raw({0x00, 0xFF}); -- draw a raw vertical-byte framebuffer -- lte (OS7.1.0+, cellular products) local resp, status = lte.at("AT+CSQ", 10000); -- command, [timeout_ms]; status 0=OK 1=ERROR 2=TIMEOUT 3=FATAL -- net (talk to your own server, bypassing obniz Cloud; blocks until done. plain http only, no TLS. -- use one socket at a time. http/tcp: wifi/lte/ethernet, udp: wifi/ethernet only (no LTE)) local status, body, headers = net.http.get("http://example.com"); local status, body, headers = net.http.post(url, body, "application/json"); local status, body, headers = net.http.request({ url = url, method = "GET", headers = {}, body = "", timeout = 30000 }); local id = net.tcp.connect("example.com", 80); -- host, port local written = net.tcp.write(id, "data"); local data = net.tcp.read(id, 1024); -- "" = no data yet, nil = closed/error net.tcp.close(id); local uid = net.udp.open(0); -- [localPort] local written = net.udp.sendTo(uid, "192.168.0.2", 5000, "data"); local data, ip, port = net.udp.receive(uid, 1024); -- nil = nothing waiting net.udp.close(uid); -- wifi wifi.on(); wifi.off(); wifi.sniffStart(callback); wifi.sniffSetChannel(2); wifi.sniffStop(); -- ble ble.on(); ble.off(); ble.scanStart(onFind, { -- default option values active=true, interval=16, window=16, phy1m=true, phyCoded=true, duplicate=true }); ``` --- ## Context URL: https://obniz.com/reference/common/plugin/context :::info Sample code Browse the Lua plugin examples on GitHub — [nodejs/plugin](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin). ::: ## Execution Lifecycle of Saved Scripts You can save Lua scripts to the device as plugins (extensions). Saved scripts are loaded and executed at the following times: - Upon device startup. - When `obniz.plugin.reloadLua()` is called from the SDK. For example, in the program below, the device is overwritten with a script that sends "Hello" to the cloud (regardless of whether a Lua script already exists on the device). The `reloadLua()` function then reloads the script, causing the data to be received once. When a reload occurs, any Lua script currently running on the device is terminated. All variables and functions are cleared, and the saved Lua script is reloaded from scratch. ```TypeScript obniz.onconnect = async () => { obniz.plugin!.onreceive = (data: any, str: string | null) => { console.log("received", str); }; // Save the script to the device storage obniz.storage.savePluginLua(` cloud.pluginSend("Hello") `); // Reload and execute the saved script obniz.plugin.reloadLua(); } ``` If the device already contains a Lua script that sends data to the cloud, you can clear the current context and restart the execution simply by calling `obniz.plugin.reloadLua()` as shown below: ```TypeScript obniz.onconnect = async () => { obniz.plugin!.onreceive = (data: any, str: string | null) => { console.log("received", str); // You will receive "Hello" if the above Lua script is already saved. }; obniz.plugin.reloadLua(); } ``` ## On-the-fly Execution Even when sending and executing Lua scripts from the JavaScript SDK on the fly without saving them internally, the execution Context remains shared and unique. For instance, assuming there is no Lua script saved on the device, if you run the following program, the variable a is retained in memory. Therefore, a will be incremented every time `a=a+1` is executed. In the program below, onreceive will receive the values `2`, `3`, and `4` sequentially. ```TypeScript obniz.onconnect = async () => { obniz.plugin!.onreceive = (data: any, str: string | null) => { console.log("received", str); // You will receive 2, 3, 4 }; obniz.plugin!.execLua("a=1"); obniz.plugin!.execLua(`a=a+1;cloud.pluginSend(tostring(a))`); obniz.plugin!.execLua(`a=a+1;cloud.pluginSend(tostring(a))`); obniz.plugin!.execLua(`a=a+1;cloud.pluginSend(tostring(a))`); } ``` In addition to variables, you can also transfer functions. If a function with the same name already exists, it will be overwritten. ```TypeScript obniz.onconnect = async () => { obniz.plugin!.onreceive = (data: any, str: string | null) => { console.log("received", str); }; obniz.plugin!.execLua("a=1"); obniz.plugin!.execLua(` function add(value) return value + 1 end a=add(a); cloud.pluginSend(tostring(a)) `); } ``` The `execLua()` method is equivalent to the `eval()` function in JavaScript. The code passed to it is not saved to the device's internal storage; it is executed only for that specific moment. However, the Lua environment itself continues to run inside the device. The Context (memory state) is maintained consistently until the device restarts or `reloadLua()` is called. This means any changes made to variables or functions will persist throughout the session. ## Coexistence of Saved Lua and execLua() The Lua script saved in the device (which runs automatically after startup) and the Lua code executed via `execLua()` share the same Context. This allows you to use `execLua()` to modify variables or functions defined in the pre-installed Lua script. Note that these modifications only affect the current runtime state. If the device is restarted or `reloadLua()` is called, the memory is cleared, and the original Lua script saved in the storage will be executed again from its initial state. In the example below, a variable a is initialized to 0 and an `increment()` function is saved to the device. Although this save operation only needs to be done once, this script ensures it is rewritten upon every connection. Then, `execLua()` is used to call the `increment()` function (stored internally) to increase a and send the result to the cloud. ```TypeScript obniz.onconnect = async () => { obniz.plugin!.onreceive = (data: any, str: string | null) => { console.log("received", str); }; // Saving the base script to storage obniz.storage.savePluginLua(` a=0 function increment() a=a+1 return a end `); obniz.plugin.reloadLua(); // Executing a command that uses the saved function obniz.plugin!.execLua(` increment(); cloud.pluginSend(tostring(a)) `); } ``` Since the Context is persistent, executing the command multiple times will cause the returned value to keep increasing. ```TypeScript obniz.onconnect = async () => { obniz.plugin!.onreceive = (data: any, str: string | null) => { console.log("received", str); }; obniz.storage.savePluginLua(` a=0 function increment() a=a+1 return a end `); obniz.plugin.reloadLua(); // You will receive 1 obniz.plugin!.execLua(` increment(); cloud.pluginSend(tostring(a)) `); // You will receive 2 obniz.plugin!.execLua(` increment(); cloud.pluginSend(tostring(a)) `); } ``` --- ## Internet URL: https://obniz.com/reference/common/plugin/internet :::info Sample code Browse the Lua plugin examples on GitHub — [nodejs/plugin](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin). ::: By default, obnizOS attempts to connect to a saved network immediately after startup and maintains a persistent connection. With the Lua plugin, you can monitor the connection status and programmatically allow or stop connections. This enables advanced behaviors, such as remaining offline until specific data is acquired. ## on_event By defining the `on_event()` function, you can receive callbacks for each step of the connection process. | Event | Description | | --- | --- | | `power_on` | Called only once when the device powers on. | | `setting_mode` | Indicates the device has entered setting mode (e.g., due to connection failure). | | `connecting_to_network` | Attempting to connect to the network via Wi-Fi, LTE, etc. | | `connecting_to_cloud` | Attempting to connect to obnizCloud after a successful network connection. | | `online` | Connection to obnizCloud is established. | If the connection is lost after going `online`, the rollback point in the sequence depends on whether the disconnection occurred at the TCP layer or the physical layer (Wi-Fi/LTE). ```lua function on_event(event) if event == "power_on" then os.log(" - Lua PowerOn"); -- Prevent hardware reset on disconnection os.resetOnDisconnect(false); os.log(" - No Reset On Disconnect"); elseif event == "setting_mode" then -- Handle setting mode elseif event == "connecting_to_network" then -- Handle network connection start elseif event == "connecting_to_cloud" then -- Handle cloud connection start elseif event == "online" then os.log(" - Lua Online"); end end ``` ### Understanding `power_on` vs. Global Scope The behavior of the `power_on` event is similar to code written in the global scope, but there is a key difference: | Location | Behavior | | --- | --- | | **power_on event** | Executed only once at boot. It will **not** be re-executed even if you replace the Lua script and call `obniz.plugin.reloadLua()`. | | **Global Scope** | Executed whenever the Lua script starts. It runs at boot and is **re-executed** every time `obniz.plugin.reloadLua()` is called. | **Best Practice:** Use `power_on` for initialization that must truly happen only once. Use the **global scope** for processes you want to re-run whenever the script is reloaded. --- ## cloud.connect() / disconnect() While obnizOS manages the cloud connection automatically, you can override this via the plugin. The following example turns off the cloud connection at startup. ```lua function on_event(event) if event == "power_on" then os.log(" - Lua PowerOn"); os.resetOnDisconnect(false); cloud.disconnect(); -- Disconnect at startup elseif event == "online" then os.log(" - Lua Online"); end end local lastTick = os.getTick(); local connecting = false; local offlineTick = 0; function on_offline_loop() -- Log message every 1 second if os.getTick() - lastTick > 1000 then lastTick = os.getTick(); os.log("offline loop"); wdt.feed(); -- Prevent Watchdog reset end -- Try to connect after 10 seconds of being offline if os.getTick() - offlineTick > 10 * 1000 and not connecting then os.log("connect to cloud"); cloud.connect(); connecting = true; end end -- Function triggered by a command (example) function on_command(command) os.log("disconnect from cloud"); cloud.disconnect(); connecting = false; offlineTick = os.getTick(); end ``` ### Disconnection Behavior You can stop or cancel a connection by calling `cloud.disconnect()`. However, the behavior depends on the current state: | Timing | Behavior | | --- | --- | | Before `connecting_to_network` | The connection attempt will not start. | | Between `connecting_to_network` and `online` | The connection cannot be stopped immediately; it will be canceled after it briefly reaches the `online` state. | | After reaching `online` | The device performs a disconnection process and goes offline. | > [!TIP] > **os.resetOnDisconnect(false)** > By default (`true`), obnizOS resets peripherals like UART and SPI when the internet connection is lost. Setting this to `false` prevents unexpected hardware resets when managing connections or IO manually via Lua. --- ## Using Watchdog Timer (WDT) in Offline Mode obnizOS includes a "keep-alive" monitoring feature. It considers a constant internet connection and data exchange as the "healthy" state. If the device remains disconnected for a certain period, it will automatically reboot. When intentionally staying offline via a plugin, this can cause unwanted reboots. To prevent this, you must periodically call `wdt.feed()`. ```lua function on_offline_loop() if os.getTick() - lastTick > 1000 then lastTick = os.getTick(); os.log("offline loop"); wdt.feed(); -- Feed the watchdog to prevent reboot end end ``` ### ⚠️ Important Caution **Use `cloud.disconnect()` and `wdt.feed()` with extreme care.** Depending on your Lua logic, you may cause the device to remain offline indefinitely, making it impossible to update the script via the cloud. We **strongly recommend** implementing the following safeguards: * Ensure the device connects to the internet at least once after booting. * Implement logic to force an internet connection after a specific duration. * Stop calling `wdt.feed()` after a certain period to allow a failsafe reboot. --- ## Loop URL: https://obniz.com/reference/common/plugin/loop :::info Sample code Browse the Lua plugin examples on GitHub — [nodejs/plugin](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin). ::: By registering loop functions, you can receive periodic callbacks from the OS. ## on_online_loop() / on_offline_loop() There are two types of loop functions: one called while the device is offline and another while it is online. The system automatically switches between these functions based on the current connection status. ```lua -- Called approximately every 1 msec while online. function on_online_loop() -- os.log("online_loop"); end -- Called approximately every 1 msec while offline. -- Note: This function runs on a different thread; -- please manage communication and data handling carefully. function on_offline_loop() -- os.log("offline_loop"); end ``` A typical use case is handling UART data: you might write logic to buffer incoming UART signals while offline, and then both buffer and transmit them once the device is online. If you wish to execute the same logic regardless of the connection status, define a custom function (e.g., `my_loop()`) and call it from both loop handlers. ```lua function my_loop() -- Common logic here end function on_online_loop() my_loop() end function on_offline_loop() my_loop() end ``` **Note**: The Online loop and Offline loop are called from different threads. Please ensure your implementation accounts for thread safety if necessary. --- ## OS URL: https://obniz.com/reference/common/plugin/os :::info Sample code A working example is available on GitHub — [nodejs/plugin/os_info](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/os_info). ::: ## os.log(text) Outputs a string (data) to the device's serial console. ```lua os.log("hello world"); ``` ## os.wait(milliseconds) Pauses the execution of the OS for a specified duration. Note that this does not put the device into a low-power sleep mode, so power consumption remains unchanged. The internet connection is maintained during the wait. However, if a duration exceeding several tens of seconds is specified, it may be flagged as an anomaly, potentially resulting in a disconnection or a device reboot. ```lua os.wait(1000); -- 1,000msec wait ``` ## os.reboot() Triggers an immediate reboot of the device. ```lua os.reboot(); ``` ## os.getVersion() Returns the OS version as a string (e.g., `"7.0.0"`). ```lua os.getVersion(); ``` ## os.getHW() Returns the hardware type identifier as a string (e.g., `"iekilo1"`). ```lua os.getHW(); ``` ## os.getTick() Returns the number of milliseconds elapsed since the device started as a numeric value. ```lua os.getTick(); -- system tick in msec ``` ## os.getUnixTime() If the system clock has been synchronized via `obniz.setClock()` or `obniz.pingWait()` from JavaScript, this function returns the number of seconds elapsed since the Unix Epoch (January 1, 1970) as a numeric value. ### Important Note on Time Accuracy * **Synchronized:** Returns the standard Unix timestamp (seconds). * **Unsynchronized:** Returns the uptime in seconds (derived from `getTick()`). To ensure accurate time-stamping for your data, please ensure the device has an active network connection for time synchronization or handle the relative tick value accordingly in your application logic. ```lua os.getUnixTime(); ``` ## os.resetOnDisconnect(boolean) Prevents the device from automatically resetting when it goes offline. ```lua os.resetOnDisconnect(false); -- Disabling reset ensures the device won't reboot after disconnection, and queued data is preserved while offline. ``` ## os.sleep(milliseconds, mode) Transitions the device into a sleep state. ```lua -- Mode 0: Deep sleep + External module sleep os.sleep(5 * 1000, 0); -- Mode 1: Deep sleep + Without external module sleep os.sleep(5 * 1000, 1); -- Mode 2: Light sleep + External module sleep os.sleep(5 * 1000, 2); -- Mode 3: Light sleep + Without external module sleep os.sleep(5 * 1000, 3); ``` --- ## Sleep URL: https://obniz.com/reference/common/plugin/sleep :::info Sample code A working example is available on GitHub — [nodejs/plugin/sleep](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/sleep). ::: For information regarding sleep behavior, please refer to the [OS Sleep](https://www.google.com/search?q=/reference/obnizos-for-esp32/sleep/) page. There are two types of sleep modes available. You can choose between **Light Sleep** and **Deep Sleep** depending on your specific use case. | Sleep Mode | Usage & Characteristics | | --- | --- | | **Deep Sleep** | Offers the lowest power consumption. The system performs a full reboot upon waking up. | | **Light Sleep** | Temporarily pauses execution. The program resumes from where it left off after waking. Note that network connections (such as Wi-Fi) may be disconnected. | Additionally, for both modes, you can specify whether to put external communication modems into sleep mode—specifically the LTE modules used in the Intelligent Edge series. Generally, for **Deep Sleep**, the modem is also put to sleep to save power. For **Light Sleep**, you may choose to keep the modem active to maintain a quicker recovery. ## os.sleep(milliseconds, mode) Transitions the device into a sleep state. The following example demonstrates a 3-second Light Sleep immediately after startup, followed by a transition to Deep Sleep upon receiving a command from the cloud. ```lua function on_event(event) if event == "power_on" then os.log(" - Light Sleep Start 3seconds. Tick="..os.getTick()); -- Start Light Sleep for 3000ms (Mode 3) os.sleep(3 * 1000, 3); os.log(" - Light Sleep Ended Tick="..os.getTick()); os.log(" - During light sleep, tick does not counted"); elseif event == "online" then os.log(" - Lua Online."); end end function on_command(command) os.log("Going to deep sleep 1sec"); -- Start Deep Sleep for 1000ms (Mode 0) os.sleep(1 * 1000, 0); end -- Mode Reference: -- os.sleep(5 * 1000, 0); Deep Sleep + External Module Sleep -- os.sleep(5 * 1000, 1); Deep Sleep + WITHOUT External Module Sleep -- os.sleep(5 * 1000, 2); Light Sleep + External Module Sleep -- os.sleep(5 * 1000, 3); Light Sleep + WITHOUT External Module Sleep ``` --- ## Timestamp URL: https://obniz.com/reference/common/plugin/timestamp :::info Sample code A working example is available on GitHub — [nodejs/plugin/timestamp](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/timestamp). ::: You can retrieve the elapsed time or attach timestamp information to data sent to obniz.js. ## cloud.enqueueTimestampByTick(tick) By calling `os.getTick()`, you can determine how many milliseconds have elapsed since the obnizOS started. Normally, when you send data using a method like `cloud.pluginSend("data");`, there is no way to know exactly when that data was generated unless you include the time within the data payload itself. However, by using the `cloud.enqueueTimestampByTick(tick)` function before sending data, you can attach the specific time corresponding to the "tick" as a Unix timestamp (in milliseconds). In the following example, two pieces of data are sent to the cloud every 3 seconds. The first piece is given a timestamp from 1 second ago, and the second piece is given a timestamp of the current time. ### Example Code (Lua) ```lua tick = 0 function on_online_loop() local current = os.getTick() if tick == 0 then tick = current end if current - tick >= 3 * 1000 then tick = current os.log(" - 3 seconds passed"); -- Add old data with a specific timestamp (1 second ago) cloud.enqueueTimestampByTick(current - 1000); cloud.pluginSend("this is 1 sec old data"); -- Add data with the current timestamp cloud.enqueueTimestampByTick(current); cloud.pluginSend("now"); end end ``` ### Receiving Data on the JavaScript Side On the JavaScript side, when data is received via `onreceive`, you can access the timestamp through `obniz.deviceTimestamp`. This value represents the number of milliseconds elapsed since January 1, 1970 (Unix Epoch). **Note**: Since the internal clock of the device may drift unless synchronized, it is necessary to call `obniz.setClock()` at the start and at regular intervals. ### Example Code (JavaScript) ```javascript // Synchronize the device clock obniz.setClock(); obniz.plugin.onreceive = (data) => { // Calculate how old the data is by comparing the current time with deviceTimestamp const ageInSeconds = (Date.now() - obniz.deviceTimestamp) / 1000; console.log(`data "${Buffer.from(data).toString()}" is ${ageInSeconds} seconds old`); }; ``` --- ## Storage URL: https://obniz.com/reference/common/plugin/storage :::info Sample code Working examples on GitHub — [storage_file](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/storage_file), [storage_kvs](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/storage_kvs). ::: Lua operations are reset when the device restarts. However, by using the `storage` library, you can save data to the internal flash memory and retrieve it later. There are two types of storage available: | Type | Features | | --- | --- | | **kvs** | A single storage space for saving simple objects (Key-Value style). | | **file** | A storage system for saving larger data by specifying a filename. | ### Storage Capacity Data is stored within a total capacity of approximately 1 MB, which is shared with your Lua scripts. Please note that the available storage space is very limited. * **kvs**: While easy to use, it loads all data into memory at once. Therefore, you should keep the data size within a few kilobytes. * **file**: This allows for larger data handling but requires more complex programming, such as managing partial access. Even with files, it is recommended to keep the size within approximately 100 KB. ### Read/Write Cycles Writing to flash memory shortens its lifespan. It is essential to design your application to minimize the frequency of write operations as much as possible. --- ## storage.kvsSave() You can save an object using `storage.kvsSave()`. If an error occurs, a return value will indicate the status. ```lua obj = { a=1, b="hello", bool=true, c={ x=10, y=20, z={ foo="bar" } } } result = storage.kvsSave(obj) ``` ## storage.kvsLoad() To read the existing kvs data, use `storage.kvsLoad()`. ```lua data = storage.kvsLoad(); ``` --- ## Writing to a File Whether a file already exists or you are creating a new one, you must first open it by specifying the filename using `storage.fileOpen(filename)`. To write data to an open file, use the following functions: ### storage.fileWrite() The `fileWrite()` function overwrites the file. Any existing data in the file will be deleted and replaced with the new data. ```lua storage.fileWrite("ABC"); ``` ### storage.fileAppend() To add data to the end of the existing content, use `storage.fileAppend(data)`. ```lua storage.fileAppend("appended"); ``` ### storage.fileClose() Finally, call `storage.fileClose()` to close the file and complete the process. ```lua storage.fileClose(); ``` --- ## Reading from a File Reading a file also requires the use of `fileOpen()` and `fileClose()`. ### storage.fileGetSize() You can check the file size (in bytes) using this function. ```lua storage.fileGetSize(); ``` ### storage.fileRead() To read the actual data, specify the offset and the length as shown below. The length must be **1024 bytes or less**. ```lua -- data = storage.fileRead(offset, length); data = storage.fileRead(0, length); ``` --- ## Example ```lua -- Open the file storage.fileOpen("text.txt") -- Write data storage.fileWrite("ABC"); length = storage.fileGetSize(); os.log("File size: " .. length); data = storage.fileRead(0, length); os.log(data); -- Append data storage.fileAppend("abcdefg"); storage.fileAppend("HIJKLKLMN"); length = storage.fileGetSize(); os.log("File size: " .. length); data = storage.fileRead(0, length); os.log(data); -- Ranged Read (Read 7 bytes starting from offset 3) data = storage.fileRead(3, 7); os.log(data); -- Overwrite existing content storage.fileWrite("ZYZ"); length = storage.fileGetSize(); os.log("File size: " .. length); data = storage.fileRead(0, length); os.log(data); -- Close the file storage.fileClose(); ``` --- ## Data Send/Recv URL: https://obniz.com/reference/common/plugin/communication :::info Sample code Working examples on GitHub — [call_wait](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/call_wait), [cloud_transaction](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/cloud_transaction), [command](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/command). ::: This document describes how to exchange data between a Lua plugin running on the obniz OS and the obniz JavaScript SDK. ## Overview You can facilitate communication between a Lua plugin operating on the device OS and the JavaScript SDK. This allows for bidirectional data transfer and efficient handling of large data sets. ## obniz.plugin.send() Sends a binary data sequence from the **obniz.js** side to the **Lua plugin**. ### Javascript Example ```javascript // Send string data obniz.plugin.send("obniz.js send data get device?"); // Send byte array obniz.plugin.send([0x00, 0x01, 0x02]); ``` ### Lua Plugin Side On the Lua side, use the `on_command()` function to receive the data. ```lua function on_command(command) -- 'command' contains the data sent from JS os.log(command) end ``` ## obniz.plugin.onreceive This event handler receives a binary data sequence sent from the **Lua plugin** to the **obniz.js** side. ### Javascript Example ```javascript obniz.plugin.onreceive = (data) => { console.log(data); }; ``` ### Lua Plugin Side Use `cloud.pluginSend()` to send data to the JavaScript SDK. ```lua cloud.pluginSend("123"); ``` ## obniz.plugin.onFrameStart / onFrameEnd These handlers are triggered when frame information is sent from the plugin side. These functions are particularly useful for segmenting and managing large data transfers. * `onFrameStart`: Receives the `frame_id` and the total `length` of the data. * `onreceive`: For large payloads, the data will be received in multiple chunks through this handler. * `onFrameEnd`: Called once all data defined in the frame has been completely received. ### Javascript Example ```javascript // Handle the start of a frame obniz.plugin.onFrameStart = (frame_id, length) => { console.log(`Frame start: ID=${frame_id}, Total Length=${length}`); }; // Handle the end of a frame obniz.plugin.onFrameEnd = () => { console.log("Frame reception completed"); }; // Receive chunks of data obniz.plugin.onreceive = (data) => { console.log(`Received chunk: ${Buffer.from(data).toString()}`); }; ``` ### Lua Plugin Side To use framing in a Lua plugin, use the following commands: ```lua local frame_id = 1 local total_length = 9 cloud.pluginSendFrameStart(frame_id, total_length); -- Start framing cloud.pluginSend("123"); cloud.pluginSend("456"); cloud.pluginSend("789"); cloud.pluginSendFrameEnd(); -- End framing ``` ## obniz.plugin.callWait() > Available for OS7.1.0 and later Runs a Lua script on the device and waits for its return value. While `execLua()` simply fires a script and forgets it, `callWait()` resolves with whatever the script `return`s. The script runs inside a coroutine on the device, which lets the Lua side call `cloud.transactionWait()` (see below) while it runs. ```javascript obniz.plugin.callWait(lua_script, timeout) ``` * `lua_script` (string): The Lua script to run. Its return value is resolved as a string. * `timeout` (number, optional): The time to wait for a result, in milliseconds. Defaults to `30000`. If the script raises an error, the returned Promise is rejected with that error message. ```javascript // Javascript Example // Run Lua and wait for its return value const result = await obniz.plugin.callWait(`return "hello from lua"`); console.log(result); // "hello from lua" // Lua can compute and return a value const sum = await obniz.plugin.callWait(` local x = 0 for i = 1, 10 do x = x + i end return tostring(x) `); console.log(sum); // "55" // An error raised in Lua rejects the Promise try { await obniz.plugin.callWait(`MUST FAILED`); } catch (e) { console.log("lua error:", e.message); } ``` ## cloud.transactionWait() / obniz.plugin.onCloudTransaction > Available for OS7.1.0 and later Unlike `cloud.pluginSend()`, which only sends data one way, `cloud.transactionWait()` sends data to obniz.js and **waits for a reply**. The plugin can therefore ask the cloud a question and continue once the answer arrives. ### Lua Plugin Side `cloud.transactionWait()` sends data and suspends until obniz.js responds, then returns the result. Because it suspends, it must run inside a Lua coroutine. The `obniz.plugin.callWait()` method on the obniz.js side runs the script within a coroutine for you. ```lua cloud.transactionWait(data, callback, timeout_ms) ``` * `data` (string): The data to send to obniz.js. * `callback` (function, optional): Called as `callback(success, result)` when the reply arrives. * `timeout_ms` (number, optional): The time to wait for a reply, in milliseconds. Defaults to `30000`. It returns two values: `success` (boolean) and `result` (string or nil). ```lua os.log("start"); -- Ask the cloud and wait for the reply (timeout 5000ms) local success, result = cloud.transactionWait("ping", 5000) if success then return result else return "transaction failed" end ``` ### Javascript Example Handle the request from the plugin with `obniz.plugin.onCloudTransaction`. Whatever the handler returns is passed back to the waiting Lua coroutine with `success = true`. Throwing an error reports `success = false` to the plugin. ```javascript // Called when the plugin runs cloud.transactionWait(data). obniz.plugin.onCloudTransaction = async (data, str) => { console.log("lua asked cloud:", str); // For example, call an external API here and return its response. return `echo:${str}`; }; // callWait runs the script inside a coroutine so transactionWait can wait. const result = await obniz.plugin.callWait(` local success, result = cloud.transactionWait("ping", 5000) if success then return result else return "transaction failed" end `); console.log("lua got back:", result); // "echo:ping" ``` --- ## IO Retain URL: https://obniz.com/reference/common/plugin/io_semaphore :::info Sample code A working example is available on GitHub — [io_output](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/io_output). ::: ## Conflict of IO Control Since IO and other features can be operated both via the cloud (using **obniz.js**) and locally via **Lua**, conflicts may occur if the same IO is accessed simultaneously. By default, **obniz.js takes priority**. This means that even if an IO is being used by a Lua script, it may be reset depending on the connection status or commands received from obniz.js. --- ## io.retain(io, boolean) To restrict a specific IO for Lua use only and deny access from obniz.js, use the `io.retain()` function. In the following example, **IO 0** is set to Lua-exclusive mode: ```lua io.retain(0, true); ``` When an IO is set to Lua-exclusive mode using the function above, it behaves as follows: * **Access from obniz.js is completely disabled.** * **The IO state is maintained (not reset) even if the internet connection is lost.** It is highly recommended to secure the IOs you intend to use in Lua by calling `io.retain()` beforehand. --- ## About Peripherals In addition to GPIO (io), features such as `uart` and `spi` are also shared resources. Unlike GPIO, these peripherals **automatically become Lua-exclusive** as soon as they are accessed from a Lua script. --- ## IO URL: https://obniz.com/reference/common/plugin/io :::info Sample code Working examples on GitHub — [io_input](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/io_input), [io_output](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/io_output). ::: ## io.output(io, boolean) Changes the state of a specified IO pin between **High** and **Low**. When this function is called, the IO pin—which is in a high-impedance (`Hi-z`) state upon startup—begins push-pull output. ### Arguments | Argument | Type | Description | | :--- | :--- | :--- | | `io` | number | The IO pin number to control. | | `boolean` | boolean | Set to `true` for High voltage, or `false` for Low voltage. | --- ### Example: Alternating LED Blink The following example demonstrates how to blink two LEDs connected to **IO1** and **IO2** alternately. ```lua local tick = 0 local flag = false -- Log message to indicate startup os.log(" - Lua PowerOn"); -- Retain the state of IO1 and IO2 even during sleep or disconnection io.retain(1, true); io.retain(2, true); -- Loop executed when the device is offline function on_offline_loop() loop() end -- Loop executed when the device is online function on_online_loop() loop() end -- Main logic to toggle IO states every 300ms function loop() -- Check if 300ms has passed since the last toggle if tick + 300 Available for OS7.1.0 and later ### Arguments | Argument | Type | Description | | :--- | :--- | :--- | | `io` | number | The IO pin number to control. | | `mode` | string | The drive method (see below). | | Mode | Description | | :--- | :--- | | `"3v"` | Push-pull output at 3V. This is the default. | | `"5v"` | Push-pull output at 5V. | | `"open-drain"` | Open-drain output. | > **Note:** `"5v"` is available only on obniz Board. On the ESP32 family, IO operates at 3V. ```lua io.drive(1, "open-drain"); -- Drive IO1 as open-drain io.output(1, true); ``` --- ## io.pull(io, mode) Selects the pull resistor applied to a pin. > Available for OS7.1.0 and later ### Arguments | Argument | Type | Description | | :--- | :--- | :--- | | `io` | number | The IO pin number to control. | | `mode` | string | The pull setting (see below). | | Mode | Description | | :--- | :--- | | `null` | No pull resistor (floating). This is the default. | | `"5v"` | Pull up to 5V. | | `"3v"` | Pull up to 3V. | | `"0v"` | Pull down to 0V. | > **Note:** `"5v"` is available only on obniz Board. On the ESP32 family, IO operates at 3V. ```lua io.pull(2, "3v"); -- Pull IO2 up to 3V local val = io.input(2); io.pull(2, nil); -- Back to floating (no pull resistor) ``` --- ## AD URL: https://obniz.com/reference/common/plugin/ad :::info Sample code A working example is available on GitHub — [nodejs/plugin/adc](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/adc). ::: This section explains how to use the Analog-to-Digital Converter (ADC) on the obniz IO pins to measure analog voltage. ## Overview By using the `ad.get(IO)` function, you can read the voltage applied to a specific IO pin as a numerical value. This is useful for retrieving data from analog sensors such as temperature, light, or pressure sensors. ## Function Description ### `ad.get(pin_number)` * **Description**: Measures the voltage on the specified IO pin. * **Parameters**: * `pin_number` (number): The ID of the IO pin you wish to measure. * **Return Value**: * Returns the measured voltage in **Volts (V)**. > From OS7.1.0, `ad.get()` also runs on obniz Board. The 10-bit ADC of the obniz Board and the 12-bit ADC of the ESP32 family are both scaled to volts internally, so the same code works across these products. --- ## Code Example The following Lua script demonstrates how to continuously read the analog voltage from **IO Pin 1** and log it to the console. ```lua -- This function runs repeatedly when the device is offline function on_offline_loop() loop() end -- This function runs repeatedly when the device is online function on_online_loop() loop() end -- Initialization os.log(" - Lua Start"); -- Set Pin 1 to retain its state (keep it active for ADC) io.retain(1, true); -- Main Loop function loop() -- Wait for 100ms to prevent excessive processing os.wait(100); -- Retrieve voltage from Pin 1 and log the value -- The value is returned in Volts (e.g., 1.25v) os.log("AD1: " .. ad.get(1) .. "v"); end ``` ## Key Points * **io.retain**: In this script, `io.retain(1, true)` is used to ensure the pin remains in a state where it can be measured consistently. * **Polling Interval**: The `os.wait(100)` is included to manage the sampling rate. You can adjust this value depending on how frequently you need to monitor the sensor data. * **Unit**: Note that the value returned by `ad.get()` is already scaled to Volts, so no complex conversion from raw 10-bit or 12-bit integers is required. --- ## PWM URL: https://obniz.com/reference/common/plugin/pwm :::info Sample code A working example is available on GitHub — [nodejs/plugin/pwm](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/pwm). ::: The `pwm` functions generate a PWM (Pulse Width Modulation) signal on a logical obniz IO pin. Because the pin is specified by its logical obniz IO number, the same code runs on obniz Board as well as on the ESP32 family. The number of PWM channels that can run at the same time is limited. Each call to `pwm.start()` reserves one channel, and `pwm.stop()` releases it. > Available for OS7.1.0 and later --- ## pwm.start(io) Starts PWM output on the specified IO pin. The pin is reserved for PWM, switched to output, and initialized at a default frequency of 1,000 Hz with a duty cycle of 0%. ### Arguments | Argument | Type | Description | | :--- | :--- | :--- | | `io` | number | The logical obniz IO pin number. | ### Return Value Returns a numeric status code. | Value | Meaning | | :--- | :--- | | `0` | Started successfully, or PWM was already running on this pin. | | `1` | The specified IO number is invalid. | | `2` | No free PWM channel is available. | --- ## pwm.freq(io, hz) Sets the frequency of the PWM signal in hertz. The current duty cycle is reapplied automatically after the frequency changes. ### Arguments | Argument | Type | Description | | :--- | :--- | :--- | | `io` | number | The logical obniz IO pin number on which PWM has started. | | `hz` | number | The frequency in hertz. | ### Return Value Returns a numeric status code. | Value | Meaning | | :--- | :--- | | `0` | Set successfully. | | `1` | PWM has not started on the specified pin. | | `2` | The specified frequency is out of range (`0` or greater than 80 MHz). | --- ## pwm.duty(io, percent) Sets the duty cycle of the PWM signal as a percentage. Values below `0` or above `100` are clamped to that range. ### Arguments | Argument | Type | Description | | :--- | :--- | :--- | | `io` | number | The logical obniz IO pin number on which PWM has started. | | `percent` | number | The duty cycle from `0` to `100`. | ### Return Value Returns a numeric status code. | Value | Meaning | | :--- | :--- | | `0` | Set successfully. | | `1` | PWM has not started on the specified pin. | --- ## pwm.stop(io) Stops PWM output on the specified pin and releases both the PWM channel and the IO pin. ### Arguments | Argument | Type | Description | | :--- | :--- | :--- | | `io` | number | The logical obniz IO pin number. | --- ## Example: Breathing LED The following example fades an LED connected to **IO1** up and down by updating the duty cycle every 50 milliseconds. ```lua local io_num = 1 local duty = 0 local step = 5 local tick = 0 os.log(" - Lua PowerOn"); -- Start PWM at 1kHz and a duty cycle of 0% pwm.stop(io_num); pwm.start(io_num); pwm.freq(io_num, 1000); pwm.duty(io_num, duty); function on_offline_loop() loop() end function on_online_loop() loop() end function loop() -- Update the duty cycle every 50ms to fade the LED in and out if tick + 50 = 100 then duty = 100 step = -step elseif duty <= 0 then duty = 0 step = -step end pwm.duty(io_num, duty) end end ``` --- ## UART URL: https://obniz.com/reference/common/plugin/uart :::info Sample code A working example is available on GitHub — [nodejs/plugin/uart](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/uart). ::: ## uart.start(tx, rx, baud) Starts asynchronous communication using UART. To initialize the communication, specify the IO pin numbers for TX (transmit) and RX (receive), along with the baud rate (communication speed). - **tx**: IO pin number for transmission from your obniz Device. - **rx**: IO pin number for reception to your obniz Device. - **baud**: Communication speed (e.g., 9600, 115200). Occupancy and Retention A UART session initiated from Lua is exclusively reserved for Lua, making it unavailable for external use by other interfaces like obniz.js. Additionally, once a UART session is started, it cannot be terminated until the device is rebooted. Therefore, if you call `uart.start()` again from Lua while the device is running, the new settings may not take effect, or it may result in an error. A reboot is required if you wish to change configurations such as the TX pin. If you do not need to change the configurations, the UART interface remains active even if a subsequent `uart.start()` call fails. As a result, you can continue to use UART-related functions such as `uart.send()`. --- ## uart.send(string) Sends data through the initialized UART interface. This function is synchronous; it will wait and block further execution until the data transmission is completely finished. --- ## uart.recv() Received data is automatically stored in an internal buffer. You can retrieve this accumulated data by calling `uart.recv()`. --- ## uart.isUsed() Returns whether the UART interface is currently in use. > Available for OS7.1.0 and later The return value is `true` once `uart.start()` has succeeded, and `false` otherwise. Use it to skip re-initialization, since UART cannot be reconfigured until the device reboots. ```lua if not uart.isUsed() then uart.start(1, 2, 115200); end ``` --- ## Example The following example demonstrates how to receive UART data and send it to the cloud. This script is designed to handle data even if it was received while the device was offline; once the connection is established, the data will be uploaded to the cloud sequentially. ```lua os.log(" - Lua Start"); -- Set IO pins to retain their state io.retain(1, true); io.retain(2, true); -- Initialize UART on IO1 (TX) and IO2 (RX) at 115200 baud uart.start(1, 2, 115200); -- Send initial message uart.send("Hello World"); function on_online_loop() -- Retrieve received data from the buffer local ret = uart.recv(); -- Example: Limit receive buffer to 1 byte -- local ret = uart.recv(1); if #ret > 0 then -- Echo back the received data via UART and also send it to the cloud uart.send(ret); cloud.pluginSend(ret); end end --- ## SPI URL: https://obniz.com/reference/common/plugin/spi :::info Sample code A working example is available on GitHub — [nodejs/plugin/spi](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/spi). ::: ## spi.start(MOSI, MISO, CLK, CS, speed_hz) Starts the SPI in Master Mode. * **MOSI**: MOSI (Master Out Slave In) pin * **MISO**: MISO (Master In Slave Out) pin * **CLK**: Clock pin * **CS**: Chip Select pin * **speed_hz**: Communication speed (e.g., 1 * 1000 * 1000 for 1MHz). Occupancy and Retention An SPI session initiated from Lua is exclusively reserved for Lua, making it unavailable for external use by other interfaces like obniz.js. Additionally, once an SPI session is started, it cannot be terminated until the device is rebooted. Therefore, if you call `spi.start()` again from Lua while the device is running, the new settings may not take effect, or it may result in an error. A reboot is required if you wish to change configurations such as the MOSI pin. If you do not need to change the configurations, the SPI interface remains active even if a subsequent `spi.start()` call fails. As a result, you can continue to use SPI-related functions such as `spi.write()`. ## spi.write(string) Sends and receives data over the SPI bus. Once the process is complete, you can retrieve the values received in the shift register. ## spi.isUsed() Returns whether the SPI interface is currently in use. > Available for OS7.1.0 and later The return value is `true` once `spi.start()` has succeeded, and `false` otherwise. Use it to skip re-initialization, since SPI cannot be reconfigured until the device reboots. ```lua if not spi.isUsed() then spi.start(20, 21, 19, 8, 100 * 1000); end ``` ## Example The following example demonstrates how to periodically control a relay mounted on an **Intelligent Edge Kilo** via SPI. ```lua function plugin_name() return "spi_test" -- max 30 chars end function on_event(event) if event == "power_on" then os.log(" - Lua PowerOn"); init(); end end local tick = 0 local flag = false local initialized = false function init() if initialized then return end initialized = true -- Kilo Internal Shared SPI for MCP23S08 io.retain(8, true); -- CLK -- Parameters: MOSI, MISO, CLK, CS (CS can be null for non-shared SPI), baudrate local err = spi.start(20, 21, 19, 8, 100 * 1000); if err > 0 then os.log("SPI Error: " .. err); return end os.log("SPI Started"); -- Configuration: Write address / Direction Address / Values -- Change I/O Direction spi.write(string.char(0x40, 0x00, 0xC0)); end init(); function on_offline_loop() loop() end function on_online_loop() loop() end tick = 0; function loop() local current = os.getTick() if tick == 0 then tick = current end -- Execute every 3 seconds if current - tick >= 3 * 1000 then tick = current if flag then -- Set Relay to On local ret = spi.write(string.char(0x40, 0x09, 0x3C)); os.log("Relay On"); else -- Set Relay to Off local ret = spi.write(string.char(0x40, 0x09, 0x1C)); os.log("Relay Off"); end flag = not flag end end ``` --- ## Display URL: https://obniz.com/reference/common/plugin/display :::info Sample code A working example is available on GitHub — [nodejs/plugin/display](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/display). ::: The `display` functions draw text and graphics on the screen of products that have a built-in display. On products without a display, every `display` function is simply ignored, so the same script remains safe to run on any device. > Available for OS7.1.0 and later --- ## display.print(string) Appends a string at the current cursor position. The cursor advances as characters are written, so calling `display.print()` repeatedly continues the text from where it left off, much like a typewriter. ### Arguments | Argument | Type | Description | | :--- | :--- | :--- | | `string` | string | The text to draw. | --- ## display.clear() Clears the entire screen. --- ## display.raw(table) Draws a raw framebuffer directly to the screen. The table is a byte array in which each element holds a single byte from `0` to `255`. The bytes are laid out vertically, following the framebuffer format of the display. ### Arguments | Argument | Type | Description | | :--- | :--- | :--- | | `table` | table | A byte array of framebuffer data. Each element is a value from `0` to `255`. | --- ## Example: Typewriter Text The following example reveals each message one character at a time, producing a typewriter effect. ```lua local messages = { "Hello from obniz", "Lua is running on the device.", "Bye!", } local msg_index = 1 local char_index = 0 local tick = 0 local interval = 120 -- milliseconds per character os.log(" - Lua PowerOn"); display.clear(); function on_offline_loop() loop() end function on_online_loop() loop() end function loop() if tick + interval #messages then msg_index = 1 end end end end ``` --- ## Wi-Fi URL: https://obniz.com/reference/common/plugin/wifi :::info Sample code A working example is available on GitHub — [nodejs/plugin/wifi_sniff](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/wifi_sniff). ::: ## wifi.on() Starts the Wi-Fi functionality. **Note**: This function cannot be used if the device is already connected to the internet via Wi-Fi. ```lua wifi.on(); ``` --- ## wifi.off() Stops the Wi-Fi functionality. **Note**: This function cannot be used if the device is already connected to the internet via Wi-Fi. ```lua wifi.off(); ``` --- ## wifi.sniffStart(callback); Starts Wi-Fi sniffing and specifies a callback function to receive captured packets. Sniffing can only be performed on a specific channel at a time. To perform a bulk scan across multiple frequencies, please switch channels sequentially. ```lua function callback(da_addr, sa_addr, bssid_addr, channel, rssi) local da = mac_to_hex(da_addr) local sa = mac_to_hex(sa_addr) local bssid = mac_to_hex(bssid_addr) os.log(string.format( "DA: %s, SA: %s, BSSID: %s, Channel: %d, RSSI: %d", da, sa, bssid, channel, rssi )) end wifi.on(); wifi.sniffStart(callback); wifi.sniffSetChannel(2); ``` --- ## wifi.sniffSetChannel(channel); Changes the target channel after sniffing has started. Please verify the frequencies (channels) allowed for Wi-Fi use in your specific country or region. ```lua wifi.sniffSetChannel(2); ``` --- ## wifi.sniffStop(); Stops the Wi-Fi sniffing process. ```lua wifi.sniffStop(); ``` --- ## BLE URL: https://obniz.com/reference/common/plugin/ble :::info Sample code A working example is available on GitHub — [nodejs/plugin/ble_scan](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/ble_scan). ::: Regarding Bluetooth Low Energy (BLE) functionality, this system supports **scanning only**. Pairing with other devices is not supported. --- ## ble.on() Starts the BLE module. ```lua ble.on() ``` --- ## ble.off() Stops the BLE module. Once stopped, the system resources occupied by the BLE module for Lua are released. --- ## ble.scanStart(callback, options) Starts a BLE scan indefinitely. ### Options | Key | Type | Default | Description | | --- | --- | --- | --- | | active | boolean | `true` | Set to `true` for Active Scanning. | | interval | number | `0x10` | Specifies the scan interval (2-byte numeric value). | | window | number | `0x10` | Specifies the scan window (2-byte numeric value). | | phy1m | boolean | `true` | Set to `true` to scan/receive standard BLE packets. | | phyCoded | boolean | `true` | Set to `true` to scan/receive BLE5 Coded PHY packets. | | duplicate | boolean | `true` | Set to `false` to filter out duplicate signals from the same MAC address. | > **Note: behavior of `duplicate=false`** > > When you set `duplicate=false`, signals from a MAC address that has already been received are not notified again. However, this filter is only effective **until the scan is stopped** or **until the internal buffer becomes full**. > > If you keep scanning without ever stopping, the internal buffer will eventually overflow. When that happens the filter is reset, and signals from devices that were already received will start being received (notified) again. > > For this reason, when using `duplicate=false`, design your code on the assumption that it must be **paired with logic that periodically stops and restarts the scan**. Restarting the scan resets the filter state and avoids unexpected re-notifications caused by buffer overflow. ### callback(peripheral) The callback function receives a table (object) containing the data of the detected advertisement. **Peripheral Object Properties:** | Key | Type | Description | | --- | --- | --- | | address | string | The MAC address of the detected device. | | rssi | number | Received Signal Strength Indicator (signal strength). | | advData | string | The raw advertisement packet data. | | isScanResp | boolean | `true` when the packet is a scan response, `false` when it is an advertisement. (OS7.1.0 and later) | --- ## Example The following example demonstrates how to start a passive scan immediately upon startup and receive all available signals. The received signal details will be output to the serial console. ```lua -- Helper function to convert string to hex format local function tohex(data) local hex = {} for i = 1, #data do hex[#hex+1] = string.format("%02x", data:byte(i)) end return table.concat(hex, "") end -- Callback function triggered when a device is found function onFind(peripheral) os.log("found\n addr: " .. tohex(peripheral.address) .. "\n rssi:" .. tostring(peripheral.rssi) .. "\n data:" .. tohex(peripheral.advData)); end -- Initialize BLE local ret = ble.on(); os.log("ble on ret=" .. tostring(ret)); -- Start scanning with specific options ret = ble.scanStart(onFind, { active=false, -- Passive scan interval=16, window=16, phy1m=true, phyCoded=true, duplicate=true -- Do not filter duplicates }); os.log("scan started ret=" .. tostring(ret)); ``` --- ## LTE URL: https://obniz.com/reference/common/plugin/lte :::info Sample code A working example is available on GitHub — [nodejs/plugin/lte_network_at](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/lte_network_at). ::: The `lte` functions control the cellular modem on products that connect to the internet over LTE. > Available for OS7.1.0 and later --- ## lte.at(command, timeout_ms) Sends an arbitrary AT command to the LTE modem and returns its response. This function is available only while the device is connected through its cellular interface. If the active network interface is not cellular, it returns immediately with a fatal status. ### Arguments | Argument | Type | Description | | :--- | :--- | :--- | | `command` | string | The AT command to send. | | `timeout_ms` | number | Optional. The time to wait for a response, in milliseconds. Defaults to `10000`. | ### Return Value Returns two values: the response and a status code. | Return | Type | Description | | :--- | :--- | :--- | | `response` | string \| nil | The raw response from the modem. `nil` when the command does not complete successfully. | | `status` | number | A status code (see below). | | Status | Meaning | | :--- | :--- | | `0` | OK. | | `1` | The modem returned an error. | | `2` | Timed out. | | `3` | Fatal error (no modem, the interface is not cellular, or the modem is busy). | --- ## Example: Querying Signal Quality The following example sends an `AT+CSQ` command, which asks the modem for its signal quality, whenever a command arrives from obniz.js. ```lua function on_command(command) os.log("command received: " .. command); -- Send the AT command received from obniz.js to the modem local resp, status = lte.at(command); os.log("response: " .. tostring(resp)); os.log("status: " .. tostring(status)); -- Return the response to obniz.js if resp ~= nil then cloud.pluginSend(resp); end end ``` From obniz.js, send the AT command as plugin data. ```javascript // Javascript Example obniz.plugin.send("AT+CSQ"); ``` --- ## Net (HTTP / TCP / UDP) URL: https://obniz.com/reference/common/plugin/net :::info Sample code Working examples on GitHub — [net_http_get](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/net_http_get), [net_http_post](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/net_http_post), [net_mqtt](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/net_mqtt), [net_tcp](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/net_tcp), [net_udp](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/net_udp). ::: The `net` functions let a Lua plugin talk directly to your own server, without going through obniz Cloud. They send and receive data over the network interface that the device is currently connected through, and cover three protocols: HTTP (`net.http`), raw TCP (`net.tcp`), and UDP (`net.udp`). Use them when a device needs to reach an existing API, a private endpoint, or a service that obniz Cloud does not handle. --- ## Common Behavior and Constraints Read this section before using any of the `net` functions. - **They follow the active network interface.** HTTP and TCP run over whichever interface is currently connected — Wi-Fi, Ethernet, or LTE. UDP runs over Wi-Fi or Ethernet only, and is **not available over LTE**. - **They block until they finish.** Each call runs synchronously and does not return until the operation completes, fails, or times out. The communication watchdog is fed during the wait, so a long transfer does not reset the device. The handler that called the function, however, stays blocked in the meantime. Avoid long transfers inside `on_online_loop()` or `on_offline_loop()`, which are expected to return quickly. - **Plain HTTP only — TLS is not supported.** Connections are unencrypted. Use `http://` URLs; `https://` does not work. Send sensitive data only over a network you trust. - **Keep to one socket at a time.** Open a single connection, finish with it, and close it before opening the next. Depending on available memory and the active network interface, a second socket may or may not succeed, so do not rely on holding several open at once. Always close a socket you no longer need. - **Errors are returned, not raised.** On failure, a function returns `nil` followed by a short error string. Check the first return value before using the result. --- ## net.http ### net.http.get(url) Performs an HTTP `GET` request and waits for the full response. | Argument | Type | Description | | :--- | :--- | :--- | | `url` | string | The target URL. Begins with `http://`. `https://` is not supported. | Returns three values on success, or `nil` and an error string on failure. | Return | Type | Description | | :--- | :--- | :--- | | `status` | number | The HTTP status code, such as `200`. | | `body` | string | The response body. | | `headers` | string | The raw response headers. | ### net.http.post(url, body, contentType) Performs an HTTP `POST` request with the given body. | Argument | Type | Description | | :--- | :--- | :--- | | `url` | string | The target URL. | | `body` | string | The request body to send. | | `contentType` | string | Optional. The `Content-Type` header. Defaults to `application/octet-stream`. | The return values are the same as `net.http.get()`. ### net.http.request(options) Performs a request with full control over the method, headers, body, and timeout. `options` is a table. | Field | Type | Description | | :--- | :--- | :--- | | `url` | string | Required. The target URL. | | `method` | string | Optional. The HTTP method. Defaults to `GET`. | | `headers` | table | Optional. Request headers, as `{ ["Key"] = "Value" }` or `{ "Key: Value" }`. | | `body` | string | Optional. The request body. | | `timeout` | number | Optional. The time to wait, in milliseconds. Defaults to `30000`. | The return values are the same as `net.http.get()`. #### HTTP constraints The HTTP client is intentionally small, so be aware of the following limits. - It sends `Connection: close` and reads until the server closes the connection. Keep-alive is not used. - It does not follow redirects. A `3xx` response is returned as is. - It does not decode chunked transfer encoding or decompress `gzip`. The body is returned exactly as received, so request an uncompressed, unchunked response when you can. - The host name must be shorter than 128 characters. --- ## net.tcp ### net.tcp.connect(host, port) Opens a plain TCP connection and returns a socket id. TLS is not supported. | Argument | Type | Description | | :--- | :--- | :--- | | `host` | string | The host name or IP address. | | `port` | number | The port number. | Returns the socket id on success, or `nil` and an error string on failure. Pass the id to the other `net.tcp` functions. ### net.tcp.write(id, data) Sends data over the connection. The call returns once all of the data has been sent, and times out after 30 seconds. | Argument | Type | Description | | :--- | :--- | :--- | | `id` | number | The socket id from `net.tcp.connect()`. | | `data` | string | The data to send. | Returns the number of bytes written, or `nil` and an error string on failure. ### net.tcp.read(id, maxlen) Reads data that has already arrived. This call does not wait for new data. | Argument | Type | Description | | :--- | :--- | :--- | | `id` | number | The socket id. | | `maxlen` | number | Optional. The maximum number of bytes to read. Defaults to `1024`, with an upper limit below `4096`. | | Return | Type | Description | | :--- | :--- | :--- | | `data` | string \| nil | The received data. An empty string (`""`) means no data has arrived yet. `nil` means the connection has closed or an error occurred. | Because `read` returns immediately, poll it across loop iterations rather than expecting a full message in a single call. ### net.tcp.close(id) Closes the connection and releases the socket. --- ## net.udp UDP runs over Wi-Fi or Ethernet only. It is **not available over LTE**: on a cellular connection, `net.udp.open()` fails with `udp not supported on cellular`. ### net.udp.open(localPort) Opens a UDP socket and returns its id. | Argument | Type | Description | | :--- | :--- | :--- | | `localPort` | number | Optional. The local port to bind to. When omitted, the system assigns one. | Returns the socket id on success, or `nil` and an error string on failure. ### net.udp.sendTo(id, host, port, data) Sends a datagram to the given destination. | Argument | Type | Description | | :--- | :--- | :--- | | `id` | number | The socket id. | | `host` | string | The destination host name or IP address. | | `port` | number | The destination port. | | `data` | string | The datagram payload. | Returns the number of bytes sent, or `nil` and an error string on failure. ### net.udp.receive(id, maxlen) Receives one datagram. This call does not wait; it returns `nil` when no datagram is waiting. | Argument | Type | Description | | :--- | :--- | :--- | | `id` | number | The socket id. | | `maxlen` | number | Optional. The maximum number of bytes to read. Defaults to `1024`, with an upper limit below `4096`. | | Return | Type | Description | | :--- | :--- | :--- | | `data` | string \| nil | The received payload, or `nil` when nothing is waiting. | | `ip` | string | The sender's IP address. | | `port` | number | The sender's port. | ### net.udp.close(id) Closes the socket. --- ## Example: Posting an Analog Reading Every Minute The following plugin reads the voltage on IO0 once a minute and sends it directly to your own server as JSON over plain HTTP. It runs entirely on the device and does not go through obniz Cloud. ```lua last = 0; function on_online_loop() -- Run once every 60 seconds if os.getTick() - last < 60 * 1000 then return; end last = os.getTick(); -- Read the analog voltage on IO0 local voltage = ad.get(0); local body = '{"voltage":' .. tostring(voltage) .. '}'; -- POST it to your own server local status, resp = net.http.post("http://example.com/api/measurements", body, "application/json"); if status == nil then -- On failure, the second value holds the error string os.log("post failed: " .. tostring(resp)); return; end os.log("posted, status: " .. tostring(status)); end ``` --- ## Upstream URL: https://obniz.com/reference/common/plugin/upstream :::info Sample code Browse the Lua plugin examples on GitHub — [nodejs/plugin](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin). ::: While obnizOS automatically handles communication with the obnizCloud, you have the flexibility to filter transmitted data, modify its content, or change the transmission timing. **Note**: This section covers advanced, low-level mechanisms of the system. --- ## on_upstream() By defining the `on_upstream()` function, you can intercept data just before obnizOS adds it to the transmission queue for the cloud. The function must return an integer that determines how the data should be processed: | Return Value | Description | | :--- | :--- | | **0** | **Discard**: The data will not be sent. | | **1** | **Normal**: The data is added to the queue and sent according to the standard queue timing. | | **2** | **Immediate**: The data is added to the queue, and the queue is flushed (sent) immediately. | ### Example ```lua -- Parameters: func(int), module(int), data(string as uint8 array) function on_upstream(func, module, data) if necessary then -- Proceed with standard transmission return 1; elseif rightnow then -- Send immediately return 2; elseif mustDrop then -- Discard original data and send custom data instead cloud.upstreamEnqueue(1, 2, "modified data"); cloud.upstreamFlush(); -- Optional: Trigger immediate send return 0; end end ``` --- ## cloud.upstreamEnqueue(function, module, data) This function manually inserts data into the cloud transmission queue. When used in combination with `on_upstream()`, it allows you to filter outgoing data, convert it into different commands, or apply custom compression. ### Usage ```lua -- Inserts specific data into the upstream queue cloud.upstreamEnqueue(1, 2, "my data"); ``` --- ## cloud.upstreamFlush() This function forces the system to immediately transmit all data currently stored in the upstream queue. ### Usage ```lua -- Trigger an immediate upload of the current queue cloud.upstreamFlush() ``` --- ## Self Check URL: https://obniz.com/reference/common/plugin/self_check :::info Sample code A working example is available on GitHub — [nodejs/plugin/self_check](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin/self_check). ::: By defining the `on_self_check()` function, you can specify a custom routine that is executed during a self-check, which can be triggered via the serial console. This feature allows you to verify connections with peripheral devices even without an internet connection. It is highly effective for performing final wiring checks or assembly inspections during the manufacturing or setup process. ### Function Overview * **Purpose**: To provide a standalone diagnostic routine for hardware validation. * **Trigger**: Called manually through the serial console. * **Advantage**: Works offline, making it ideal for factory testing or field maintenance. ### Example Code The following example demonstrates how to check the status of a digital input and log the result to the console. ```lua -- This function runs when a self-check is initiated from the serial console. function on_self_check() -- Check the state of digital input 1 if io.input(1) then -- Log success if the input is detected os.log(" - self check ok"); else -- Log failure if the input is not detected os.log(" - self check failed"); end end ``` ### Usage Tips * **Offline Validation**: Use this function to ensure that sensors and actuators are correctly wired before deploying the device to a network-restricted environment. * **Detailed Logging**: You can add multiple checks within this function to verify all connected components at once. Each `os.log()` output will be visible via the serial monitor. --- ## CHANGELOG URL: https://obniz.com/reference/common/changelog See Release on Github [https://github.com/obniz/obniz/releases](https://github.com/obniz/obniz/releases) --- ## M5Stack Basic URL: https://obniz.com/reference/m5stack A compact product that includes a full-color display, battery and case. ![](images/pdct-m5stack-basic.jpg) --- ## Launch and Wi-Fi Setting URL: https://obniz.com/reference/m5stack/quick-start This section explains how to get the M5Stack up and running and set up. In addition to the enclosed M5Stack (device) and USB cable, please bring your smartphone (or PC), mobile battery or USB adapter. ## Step1. Launching the M5Stack Press the button on the side of the device to start it up, or connect it to the power supply with the USB cable. Once booted, you will see the obniz logo on the display. ![This image has an empty alt attribute; its file name is m5stack-dysplay-1-1.jpg](images/m5stack-dysplay-1-1.jpg) ## Step2. Connect to Wi-Fi. After launching, the M5Stack is waiting for Wi-Fi settings. [Wi-Fi(docs)](/reference/obnizos-for-esp32/settings/setting-via-browser) With the help of the M5Stack, connect to the Wi-Fi provided by the M5Stack with your smartphone or PC and set the SSID and password from your browser. If an error appears or the system fails to start, check [Troubleshooting](/quickstart/troubleshooting). ## Step3. Execution of the program Scan the QR code on the M5Stack display with your smartphone to open the program editor. ![This image has an empty alt attribute; its file name is m5stack-dysplay-2-1.jpg](images/m5stack-dysplay-2-1.jpg) #### If you are using a PC [program editor](https://console.obniz.com/program). When prompted for the obnizID, enter the 8-digit Enter a number. When you tap (or click) on \[Run\] at the top right of the program screen, the Run screen opens and you can see the program is executed. Initially, the text input and LED on/off buttons are displayed, and pressing the button You can change the screen and turn on the LEDs on the M5Stack with ### How to use obniz.js Obniz.js 3.7.0 or later with ``Obniz.M5StackBasic()``. Then you can easily call the M5Stack functions and IO without being aware of them. You can easily use the buttons and Grove. ![](images/m5stack_io.jpg) #### Buttons. ```javascript let obniz = new Obniz.M5StackBasic("OBNIZ_ID"); obniz.onconnect = async () => { obniz.buttonA.onchange = (flg)=>{ console.log(`buttonA state : ${flg}`); }; } ``` #### Grove. ```javascript let obniz = new Obniz.M5StackBasic("OBNIZ_ID"); obniz.onconnect = async () => { const speaker = obniz.wired("Grove_Speaker", { grove: obniz.grove0}) speaker.play(1000); //1000hz await obniz.wait(1000); speaker.stop(); } ``` ## Step4. M5Stack Power OFF You can turn off the power by pressing the button on the side of the unit twice when the power is not being supplied by USB etc. ## Description of each part ![This image has an empty alt attribute; its file name is m5stack-button.jpg](images/m5stack-button.jpg) --- ## hardware spec URL: https://obniz.com/reference/m5stack/spec 内容値Size54.2mm x 5402mm x 17.9mmWi-Fi802.11 b/g/n (2.4 GHz), up to 150 Mbps (21.5dBm)Supported Wi-Fi detailsProtocolWebsocket. TLS1.2Protocol settingstatic ip, dns server, proxy serverBluetoothCompliant with Bluetooth v4.2 BR/EDR and BLE specificationCertificationTelec, FCCVcc5vBattery150mAh Li-PoProcessorESP32IO20 GPIO + Grove PortInternal parts(Available from obniz.js)Button x 3Color Display IPS LCD 320 x 240 pxRecommended operating temperature0 °C to 40 °C --- ## M5stickC URL: https://obniz.com/reference/m5stickc Compact product with full color display, battery and case from M5Stack. ![](images/m5stickc.jpg) ## How to use with obniz M5StickC is available as an "official device" from obniz with the OS and One-Time Cloud License Included written in the factory. Or you can write the device key generated by writing obnizOS for M5StickC to a commercially available M5StickC. ### -Use the official device You can purchase "M5StickC [No Expiry Cloud License(Lite Plan)]" from the official obniz store. After purchasing the product, please start with the [Quick Start](./quick-start) . ### -Install obnizOS for M5StickC Prepare a commercially available M5StickC. Please start with [Install (for OS users only)](/reference/obnizos-for-esp32/quick-start/).Then you can control its IOs from the internet. --- ## How to Get URL: https://obniz.com/reference/m5stickc/howtoget ## One-Time License Included Products This is a product for which obnizOS for M5StickC has been written and includes No Expiry One-Time Cloud License. You can find it in the following stores [Products](https://obniz.com/products) ## M5StickC for general sale If you want to write obnizOS and issue a device key by yourself, you can use the M5StickC that is available for sale. --- ## Launch and Wi-Fi Setting URL: https://obniz.com/reference/m5stickc/quick-start This quick start shows how to start M5StickC. Please prepare M5StickC and cable, Smartphone(or PC) and Portable Battery Pack or AC Adaptor. Step1. Start M5StickC Press right bottom tiny button(power button) to power up. Charge M5StickC before use or stay connected to power supply by USB cable. Step2. Connect Wi-Fi When not Wi-Fi configured yet, you will see Wi-Fi setting screen on your device. See and follow below document to setup Wi-Fi. Prepare smartphone or Laptop to connect Wi-Fi from M5StickC to configure Wi-Fi setting on your browser. Wi-Fi(Document) If an error is displayed or startup is not possible → See Troubleshooting. Step3. Run the program Please read the QR code displayed on the obniz Board with your smartphone. The program editor will open. Using PC Please open the Program editor. When prompted for obnizID, please enter your obnizID (the 8-digit number displayed on your obniz Board). Tap (click) [Run] at the top right of the screen to open the run screen and run the program. In the initial state, character input and LED ON / OFF buttons are displayed and be used. And Press “M5” button on your device then text on browser will be changed. The program ends by closing the execution screen. ### How to use obniz.js In obniz.js 3.4.0 or later, if you specify ``Obniz.M5StickC()``, you can use the Easily call up M5StickC functions and IO without being aware of them. Easy to use buttons, grooves and sensors. ![](images/m5stickc_io.jpg) #### Buttons ```javascript let obniz = new Obniz.M5StickC("OBNIZ_ID"); obniz.onconnect = async () => { obniz.buttonA.onchange = (flg)=>{ console.log(`buttonA state : ${flg}`); }; } ``` #### Grove ```javascript let obniz = new Obniz.M5StickC("OBNIZ_ID"); obniz.onconnect = async () => { const speaker = obniz.wired("Grove_Speaker", { grove: obniz.grove0}); speaker.play(1000); //1000hz await obniz.wait(1000); speaker.stop(); } ``` #### Sensors ```javascript let obniz = new Obniz.M5StickC("OBNIZ_ID"); obniz.onconnect = async () => { await obniz.setupIMUWait(); // or old m5stickC // await obniz.setupIMUWait("SH200Q"); console.log( await obniz.accelerationWait() ); console.log( await obniz.giroWait() ) console.log( await obniz.giroWait() ) } ``` ```javascript let obniz = new Obniz.M5StickC("OBNIZ_ID"); obniz.onconnect = async () => { // LED blink obniz.led.blink(); // IR LED TV and other remote controls can be created. It can only send. // The data from the remote control needs to be analyzed up front using another sensor. // https://obniz.com/sdk/parts/IRSensor/README.md // Send the analyzed data in an array. obniz.ir.send([1,1,1,1]); } ``` Step4. Power off M5StickC Long-Press power button over 5sec. ## Registering devices to the cloud You can register devices in the cloud by going to [Register device](/reference/cloud/device-management/registration). Registering to the cloud allows you to increase the level of security and manage your devices at a glance --- ## Setting screen URL: https://obniz.com/reference/m5stickc/setting The setting screen can be displayed by pressing the small button at the top of the screen (buttonB) and turning it on. From here you can make some settings and view information. Press buttonB to move the cursor and press the large button (buttonA) on the table marked “M5” to make a selection.The setting items are as follows. Normal LaunchIt starts up normally without doing anything.FactoryResetIt reverts the version back to the factory obnizOS.Reset Wi-FiErase all stored Wi-Fi passwords and other information.Display InfoYou can check the version of obnizOS installed and the Mac address of the Wi-Fi. --- ## Power supply URL: https://obniz.com/reference/m5stickc/power The M5StickC can be supplied in three ways - USB (TypeC) - Pin frame (5V) - Built-in battery ### About the battery The M5StickC has a built-in battery and can be operated without power. The battery is automatically recharged when powered by USB or pinframe. --- ## Hardware specs URL: https://obniz.com/reference/m5stickc/spec 内容値Size48.2mm x 25.5mm x 13.7mmWi-Fi802.11 b/g/n (2.4 GHz), up to 150 Mbps (21.5dBm)Supported Wi-Fi detailsCommunication protocolWebsocket. TLS1.2Communication protocol settingsstatic ip, dns server, proxy serverBluetoothCompliant with Bluetooth v4.2 BR/EDR and BLE specificationAuthenticationTechnical Conformity , FCCOperating voltage(vcc)5vBattery80mAh Li-PoMain processorESP32-PICOIO3 GPIO + Grove PortInternal parts(available from obniz.js)Button x 2Color Display IPS LCD 0.96″ 80 x 160 px6-axis acceleration sensor MPU6886LED x 1Infrared LED x 1Recommended operating temperature0 °C to 40 °C --- ## Pinout URL: https://obniz.com/reference/m5stickc/pinout Electrical Specification obniz IOPhysical IODrive MethodInternal Weak Pull Up/DownInternal connectedio0GPIO0Input 3.3v(default)Output push-pull3vOutput open-drain(fixed internal pullup)SPM1423(MIC) SCLio26GPIO26Input 3.3v(default)Output push-pull3vOutput open-drainfloat(default)pull-up to 3vpull-down to 0vio32GPIO32Input 3.3v(default)Output push-pull3vOutput open-drain(fixed internal pulldown)GROVE SDAio33GPIO33Input 3.3v(default)Output push-pull3vOutput open-drainfloat(default)pull-up to 3vpull-down to 0vGROVE SCLio36GPIO36Input 3.3v(default)float(default)pull-up to 3vpull-down to 0v Peripherals PINOUT Peripheralfunctionio0io26io32io33io36IOoutputYESYESYESYES–inputYESYESYESYESYESADAD––YESYESYESPWMIOYESYESYESYES–UARTTXYESYESYESYES–RXYESYESYESYES–CTSYESYESYESYES–RTSYESYESYESYES–SPICLKYESYESYESYES–MOSIYESYESYESYES–MISOYESYESYESYES–I2CSDAYESYESYESYES–SCLYESYESYESYES–LogicAnalyzerIOYESYESYESYESYESMeasurePULSEYESYESYESYES–ECHOYESYESYESYESYES Peripherals: IO output Each IO can put out digital values. Drive method can be configured independently for each IO.Not only for io.output(), but also for UART and SPI you can choose your preferred drive method. input There is only one input method. Threshold is CMOS level. internal weak pull-up/pull-dow Pull up and down can be configured independently for each IO. There are three types as below. TypePull toDetailfloating Defaultpull-up3vpull-downgnd Some io has fixed internel pull up/down for startup configration. AD all channnel same time. All channel ad can be used. It will not affect the sampling rate. 30 samples/sec or slower Maximum sampling rate depends on your network speed and on obnizOS version. 10mV Ad accuracy is 10mV.(calibrated value. obnizOS 3.4.0 and later. before 3.4.0, it is 12bit accuracy and no calibration) PWM 6(pwm0 to pwm5) are available. UART 2 (uart0 to uart1) are available. Available Configration baud: number (default 115200)stop: stop bit length 1(default)/1.5/2bits: data bits 8(default)/5/6/7parity: parity check “off”(default)/”odd”/”even”flowcontrol: flow control “off”(default)/”rts”/”cts”/”rts-cts”rts: io for rts (optional)cts: io for cts (optional) SPI 2 (spi0 to spi1) are available. Only Master mode. I2C 1 (i2c0) is available and used for Grove connector, motion sensors(M5Stack Gray only). Max speed is 1Mhz.Master/Slave mode.But slave mode only works with “written” events. You can’t set data to be read. LogicAnalyzer 1 (logicanalyzer) is available. Measure 1 (measure) is available. Embeded BLE BLE32 embeded Bluetooth Module --- ## obnizOS URL: https://obniz.com/reference/obnizos-for-esp32 obnizOS (obnizOS) is a software that runs on the device. obnizOS works with obnizCloud to enable remote control of the device ## Features of obnizOS ![](./images/lua.png) - Remote control via IO/Peripheral/BLE cloud - Constant two-way communication with the obniz cloud - TLS1.2 encryption and server authentication in the communication channel - Device authentication using public key authentication - Mechanisms for getting online all the time, including ping and WDT - Internet connection via Wi-Fi or Ethernet - Prepared network configuration features (serial communication or softAP) - Proxies and static IPs, with the ability to connect to stealth SSIDs - Own OTA - Execute a Plugin Script --- ## System of OS URL: https://obniz.com/reference/obnizos-for-esp32/bootandreset obnizOS is a software to connect microcontrollers to the cloud and realize remote control. In order to do so, obnizOS manages and operates the following major aspects of the network, network configuration, and control of hardware for configuration - Hardware: management of connected system components (LED, Display, LTE modem, etc.) - Network: Establishing connections on various lines (Wi-Fi, LTE lines using modems, etc.) and constant connections - Remote control: Operation of the microcontroller according to the instructions from the Cloud - Configuration: Acceptance of settings from users. UI for this purpose, etc. - Plug-in: Interaction with user programs running on the same microcontroller. In addition, many mechanisms are incorporated for constant connection to the Cloud and for responding to network anomalies. --- ## How to get online URL: https://obniz.com/reference/obnizos-for-esp32/bootandreset/online-flow The flow between startup and when the device goes online is as follows. ![](../images/diagram_cf.png) --- ## Processor monitoring URL: https://obniz.com/reference/obnizos-for-esp32/bootandreset/connectivity To maintain normal operation, the system is reconnected and restarted at the following times - Time out waiting for input If the system goes into a state of waiting for user input after startup, the system will time out after 30 seconds of no operation and then restart. Even if the power is cut off, it does not stop waiting for input. Even if the power is unexpectedly cut off, such as a power failure, the unit will not stop waiting for input. - Inter-processor monitoring Each of the two cores included in the ESP32 monitors the operation status of each other, and if an error is detected, the ESP32 will be rebooted. Start up. Obniz Board 1Y can also monitor the external MCU and if necessary, it can run the ESP32 in its entirety. It will be reset. --- ## Safemode URL: https://obniz.com/reference/obnizos-for-esp32/bootandreset/safemode # Safe Mode (OS7 or later) If the CPU detects a reboot caused by a system error or internal issue, it will automatically start in **Safe Mode**. In this mode, the device disables certain functions to prioritize and establish a stable connection with the cloud. ## Reasons for Entering Safe Mode The device automatically enters Safe Mode when the following issues occur: - **CPU Operational Issues:** A system crash (e.g., a "Panic") or other critical errors occurred. - **Insufficient Memory:** The system was forced to reboot due to a memory shortage (Out of Memory). In these cases, the CPU restarts automatically and boots into Safe Mode to prevent continuous failure. ## Safe Mode Behavior In Safe Mode, the system's primary goal is to **connect to the cloud server as reliably as possible.** To achieve this, the device disables features that are likely causes of instability. Specifically, the following function is disabled: - **Lua Plugin:** Automatically disabled during startup. --- ## Component URL: https://obniz.com/reference/obnizos-for-esp32/components obnizOS uses some connection components as "system components" independently from user programs. Only `Console` is required to be used and cannot be turned off, the rest are turned off unless configured. If you want to use the connected LED as a system component of obnizOS (i.e., you want the LED to show its status), you can set it as a system component, such as "LED connected to IO4", and the OS will operate the LED automatically. Also, by setting "Ether" and "Modem", you can connect to the Internet not only via Wi-Fi, but also via wired LAN and cell phone lines. You can also set up "Ether" and "Modem" to connect not only to Wi-Fi, but also to wired LANs and mobile phone lines, and obnizOS will automatically initialize and operate them. Component | Optional | User Pin Assign | Description ---|---|---|--- Console | Required | Not Available | UART console for displaying obnizOS status and menu settings LED | Optional | User Can | LED to display internal status such as power and network Switch | Optional | User Can | A switch that can be used to enter configuration mode or programmed Ether | Optional | Partically User Can | Physical PHY component for wired LAN. Optional | Partically User Can | A physical PHY component for wired LAN, which allows you to use Internet connection via wired LAN. Modem | Optional | User Can | This is a modem for 3G/LTE. By specifying this item, you can use the Internet connection with a cell phone line. ## Component settings Component settings can be configured from the Console menu starting from OS 3.5.0. Once the settings are made, they are remembered and will not be lost, even with OTA. For details, please refer to the settings page. ## Presets obniz prepares obnizOS for specific hardware with each component installation. (e.g.) - obnizOS for M5StackBasic (hw=m5stack_basic) - obnizOS for ATOM Lite (hw=atomlite) Just by installing them, you can register LEDs and buttons on the main unit and start using them without any configuration because they have the component information inside. --- ## Console URL: https://obniz.com/reference/obnizos-for-esp32/components/console Some obniz devices allow you to use the UART interface as a console for configuration and monitoring. ## UART Settings The communication settings are fixed as follows: * **Connections:** TX, RX, GND only * **Baud Rate:** 115200 bps * **Flow Control:** None * **Parity:** None ## Output Content The console outputs strings indicating network connection status and other system information. The specific format of these strings varies depending on the OS version. These logs contain internal system information; sharing this output with obniz support when an error occurs can help facilitate a smoother support process. ## Menu You can enter Menu Mode by sending the four-character string `menu` via the console. (For OS versions 3.5.0 or earlier, sending the character `s` immediately after startup will enter Menu Mode.) The system will pause its normal operations and enter a standby state for configuration as soon as it enters Menu Mode. If no user action is taken for a certain period, the device will automatically restart and return to normal operation. Please refer to the Settings page for details on available configuration options. ## Disabling the Console > (OS7 or Later) Since the console utilizes a UART interface, you may want to disable it in certain scenarios. **Example:** If a device has only two UART ports and you need both for LTE communication and another peripheral, you can disable the Console to free up the port. You can disable the terminal console and prevent it from using UART by using the configuration JSON. **Configuration Example:** ```json { "hw": { "terminal": false } } ``` --- ## LED URL: https://obniz.com/reference/obnizos-for-esp32/components/led LEDs are used to indicate the internal status of obniz. There are two types as follows. Type | Description ---|--- Power | Indicates that the obnizOS is running. Signal | Indicates the network connection status of obnizOS and errors. By specifying which LED is connected to the obnizOS, the obnizOS will automatically control the LED. The available LED patterns are as follows. Type | Required Pins | Description ---|---|--- Analog Full Color | 3 | Simple 3-color LED Analog Single Color | 1 | Single Color LED Analog Full Color(Inverted) | 3 | Simple tri-color LED, but connected in the direction that it shines when IO is set to Low. Analog Single Color (Inverted) | 1 | Single color LED, but it is connected in the direction that it shines when IO is set to Low. W2812 | 1 | W2812 full color LED ## Status and lighting pattern ## Signal Status | Single Color | Full Color ---|---|--- Startup(Short Time) | ON | Green Network Connecting | Blink(30 msec ON, 220 msec OFF) | Green Blinking(250 msec) Network Connected & Cloud Connecting | Blink(220 msec ON, 30 msec OFF) | Blue Blinking(250 msec) Online | ON | Blue Setting Mode | Blinking(1000msec) | Purple Blinking(250msec) WPS Mode | Blinking(100msec) | Purple Blinking(100msec) Setting Mode | Blinking(1000msec) | Purple Blinking(250msec) Error | Blinking(50msec) | Red Blinking(100msec) Performing OTA | Blinking(100msec) | Blue Blinking(100msec) ### Power After obnizOS performs the lighting process at startup, the color and status will not change. If it does not light up, it means that the system has not booted normally. Status | Single Color | Full Color ---|---|--- Always | ON | Blue --- ## Switch URL: https://obniz.com/reference/obnizos-for-esp32/components/switch Switches are handled in obniz.js with `obniz.switch`. Up to three of them can be connected and used. ## Wiring Wiring must be done in such a way that the switch is pulled down when it is pressed. ## Primary Switch If you have one or more switches, only the first switch will have the following special function. Trigger | Function ---|--- Press and hold for a few seconds at startup or immediately after startup | Enter setting mode. Press and hold for more than 10 seconds at startup or immediately after startup. | Factory Reset Press and hold for more than 3 seconds while in setting mode | Starts Wi-Fi setting by WPS. Press while online | Sends hardware events to the cloud (e.g. program execution in the cloud). ### Cautions. Press and hold at startup or immediately after startup" depends on the wired IO. - Other than GPIO0 => turn on the power while pressing - GPIO0 => Press and hold after startup confirmation (LED turns green, etc.) --- ## Ethernet URL: https://obniz.com/reference/obnizos-for-esp32/components/ether By connecting an Ethernet PHY, you can connect to the Internet using a wired LAN. ## Available Ether PHYs - W5500 --- ## 3G/LTE Modem URL: https://obniz.com/reference/obnizos-for-esp32/components/modem By connecting a LTE/NB-IoT modem and registering the component, you can connect to the Internet from your cell phone line. ## Available modems - BG96 - nRF9160 --- ## Connection to the Cloud URL: https://obniz.com/reference/obnizos-for-esp32/protocol obnizOS uses Websocket (TCP) to communicate with the cloud. Item| value ---|--- communication | HTTPS(TLS1.2) Websocket Connections | 1 Communication direction | Only request from device side (There is no connection from the server to the device.) Proxy | Configurable (HTTP or HTTPS) Servers | obniz.io, *.obniz.io, obniz.com, *.obniz.com (* can be multiple) --- ## Network URL: https://obniz.com/reference/obnizos-for-esp32/protocol/network obnizOS uses one of the following methods to connect to the Internet - Wi-Fi (b/g/n 2.4GHz) - Wi-Fi MESH (b/g/n 2.4GHz) - Ethernet (component required) - 3G/LTE (component required) ## Configuration The following settings can be configured for obnizOS. Network | Max Settings | Description ---|---|--- Wi-Fi | 5 | Up to 5 Wi-Fi settings, Proxy, etc. can be saved. You cannot store multiple settings for the same SSID. Wi-Fi MESH | 5 | You can save up to 5 Wi-Fi MESH settings, Proxy, etc. Saving the settings will save all of them, even if they are the same settings. Ethernet | 1 | Save only one setting related to Proxy, static IP. 3G/LTE | 1 | Saves only one setting related to apn, id, pass. For more information about network settings, please refer to the configuration page. ## Priority settings Multiple settings can be saved in obnizOS, but you will have to specify the first priority network. If you set the priority to Wi-Fi when configuring Wi-Fi and 3G/LTE settings, you can use network failover, which says "If all settings set for Wi-Fi fail, connect with 3G/LTE". --- ## Network FailOver URL: https://obniz.com/reference/obnizos-for-esp32/protocol/network_failover > OS3.5.0以降 When obnizOS has multiple network settings, it will try to connect to a different network when it fails to connect to the preferred network. This makes it possible to do things like "connect to an LTE line because I can't connect to Wi-Fi anymore". ## How to configure Network failover is always available as long as multiple settings are saved. If you do not want to use it, you need to clear the settings and then save only one network setting. If you are using a browser, follow the steps below to configure. 1. Configure the non-priority network settings. 2. Configure the network settings for the preferred corpse. The above configuration method is used because the priority is given to the last configuration. --- ## Connectivity URL: https://obniz.com/reference/obnizos-for-esp32/protocol/connectivity **Always-on connectivity** - Reconnection at disconnection - Ping-Pong communication check on both the cloud and device side - Reconnect if disconnection occurs. If it repeats, reboot. --- ## Proxy URL: https://obniz.com/reference/obnizos-for-esp32/protocol/proxy > OS3.1.0 and later Proxies may be used in factories, schools and other organizational networks. obnizOS supports proxies. Proxies are available for the following protocols - HTTP - HTTPS See [Configuration](/reference/obnizos-for-esp32/settings/) for information on how to configure the proxy. --- ## TLS URL: https://obniz.com/reference/obnizos-for-esp32/protocol/tls > OS3.1.0 and later The first time the device connects to the cloud, it uses TLS communication. The plan of the account at the time of connection establishment determines whether TLS communication is enabled or not, and if TLS communication is enabled or not. If it is not possible, then the communication will be in plain text afterwards. The version of TLS used is as follows - TLS 1.2 --- ## Device Authentication URL: https://obniz.com/reference/obnizos-for-esp32/protocol/authentication The confirmation that the device is that device is authenticated on the obnizCloud side by key authentication using the secret key stored inside. ## Key Pair Device authentication is done by key authentication of a key pair. The pair is always stored in the following location. - Private key: device (or in the cloud depending on the generation method) - Public key: Cloud There are multiple methods for key generation and registration. Type | Description ---|--- In-device generation | Generated in the device, and the public key is sent to the cloud for registration Generated in obniz-cli | Generated inside obnic-cli, the public key is sent to the cloud, and the private key is sent to the device as a device key from the Console. Cloud generated | Generated in the cloud and downloaded as a string called device key. Only in the case of "cloud generation", both the public key and the private key will exist in the cloud. We recommend users to use `obniz-cli` for device creation. --- ## Self Hosting URL: https://obniz.com/reference/obnizos-for-esp32/self_hosting > OS7 or later "Self-hosting" is a method that allows you to use obniz devices via software in environments where internet access is unavailable. This feature is ideal for the following scenarios: - When you need to operate within a closed network or a specific local site network. - When you cannot use cloud services and want to operate using only your own server, without depending on obnizCloud. **Important Notes** By using self-hosting, your devices will operate outside of the obniz cloud service agreement. You will be responsible for managing connections and device maintenance yourself. Please be aware that the following items will be excluded from our service coverage and will not be supported by obniz: - Device connection management and troubleshooting. - Protection against security attacks on the device. - Prevention of unintended software flashing to the device. - Device OS updates. ## System Architecture Normally, obnizOS establishes a continuous, bidirectional TLS connection with obnizCloud. This allows you to control the device by sending instructions to obnizCloud via the SDK. In a self-hosting setup, you change the device's connection destination from obnizCloud to your own server. By specifying a server you have prepared, you can establish a direct connection with the SDK without using obnizCloud. ![](./images/selfhosting.png) ## Server Setup When developing with [obniz.js](https://github.com/obniz/obniz) or the [AppSDK](https://github.com/obniz/obniz-app-sdk) in a standard cloud environment, the program accesses the obnizCloud API. In a self-hosting environment, the program does not access external services; instead, it waits for incoming connections from the devices. **[obniz-dock](https://github.com/obniz/obniz-dock)** `obniz-dock` acts as the bridge that waits for device connections and establishes a link between the device and the control program using obniz.js. For detailed instructions, please refer to the GitHub page linked above. By hosting a server running `obniz-dock` on a local on-premise server or a private cloud and ensuring its continuous operation, you can maintain control over your devices. ## Connection and Device Configuration For devices running OS7 or later, you can change the connection destination using a [Setting JSON](../settings/setting-json). This can be configured via the serial console or a web browser. Specify the server where the aforementioned `obniz-dock` is running as the destination. The connection uses the `WebSocket` protocol. Please note that **TLS is not supported in self-hosting**, and communications will be sent in plaintext. ### Specifying by IP Address If the server is waiting for connections at a specific IP address, use the format below. If no port is specified, it defaults to port 80. ```json { "ws_server": "ws://192.168.0.2" } ``` ```json { "ws_server": "ws://192.168.0.2:8080" } ``` ### Specifying by Domain To specify the server using a domain name, use the following format. If no port is specified, it defaults to port 80. ```json { "ws_server": "ws://mydomain.com" } ``` ## Security Self-hosting involves different security considerations compared to a standard cloud connection. Please review the table below: | Feature | obnizCloud | Self-Hosting | | --- | --- | --- | | **Vulnerability Patches** | OS can be updated as new versions are released. | OS cannot be updated directly. You must connect to the cloud temporarily to update. | | **Encryption** | Encrypted via TLS 1.2. | Plaintext communication. | | **Server Authentication** | Authenticated via certificates managed by obniz. | Not performed. | | **Device Authentication** | Authenticated via certificates managed by obniz. | Not performed. | To enhance security in a self-hosting environment, we recommend the following measures: * Restrict connecting devices (e.g., by limiting MAC addresses allowed on the network). * Use isolated networks, such as a closed VPN or a private LAN. ## Customization For enterprise customers with specific requirements, obniz offers customization of hardware and OS. Please contact us if you require: * Self-hosting server connections using TLS and certificates. * Additional device authentication layers. --- ## Server Mode URL: https://obniz.com/reference/obnizos-for-esp32/self_hosting/server-mode > OS 3.5.0 or later While "Self-hosting" allows you to switch the device connection destination to another server, **Server Mode (formerly On-Premise Mode)** configures the device to boot as a WebSocket server and wait for connections from the SDK. This mode is available only over Wi-Fi/Ethernet. Please note that it is not possible to toggle this mode on or off via settings; it is available exclusively on dedicated devices purchased specifically for this function. ## Usage Without Cloud obnizOS features "Local Connect," which allows a device to receive commands from a local network while still connected to the cloud. **Server Mode** is an operation mode that utilizes only this local connectivity feature, completely bypassing the cloud. Except for cloud-related functions, all standard features of `obniz.js` (such as IO and BLE operations) are available. ```javascript // Javascript Full Example // Specify the device's IP address instead of the obnizID var obniz = new Obniz("192.168.0.100"); obniz.onconnect = async function() { console.log(`Connected to obniz device`); } ``` ## Operating Conditions The following conditions are required to use this mode: | Target | Requirement | | --- | --- | | **Compatible Networks** | Wi-Fi, Ethernet (Wi-Fi MESH is not supported in OS 3.5.0) | | **Network Configuration** | A Static IP or DHCP Reservation is required. | | **TCP** | Access to Port 80 on the device must be permitted. | | **TLS** | Unlike cloud communication, this mode uses unencrypted communication. | | **SDK** | You must specify the device's IPv4 address in `obniz.js` instead of the obnizID. | Additionally, there are several limitations due to the absence of a cloud connection: * **Status Monitoring:** Online status cannot be checked via the cloud. Server Mode cannot be deactivated via the cloud. * **Network Range:** The program using `obniz.js` must run on the same network (within the range where IPv4 TCP communication with the device is possible). * **OTA Updates:** Over-the-air (OTA) updates must be performed from within the same local network. --- ## Setting URL: https://obniz.com/reference/obnizos-for-esp32/settings ## Setting Mode Devices are not in a state to accept configurations by default. You must switch the device to **Setting Mode** to change network and other settings. [About Setting Mode](./setting-mode) There are several ways to enter Setting Mode: * **Devices with buttons:** Long-press the button, or power on the device while holding the button. * **Via UART (if Console is enabled):** Enter the specific command through UART to switch to Setting Mode. * **Automatic Transition:** If the device fails to connect to any saved networks, it will automatically enter Setting Mode. (This feature can be disabled on OS7 or later by providing `setting_mode` configration ) In Setting Mode, the device broadcasts its own Wi-Fi signal. You can configure the device by connecting to this Wi-Fi network. ### Button Locations and Operations For devices equipped with a configuration button, use the following operations to enter Setting Mode: | Product | Button Location | Operation | | :--- | :--- | :--- | | **obniz Board / 1Y** | Dial | Press and hold the dial while powering on. | | **M5Stack Basic** | Center button | Press and hold the button while powering on. | | **M5StickC** | Button B (Side) | Press and hold the button while powering on. | | **obniz BLE/Wi-Fi Gateway Gen2.0** | Side (marked with □) | Touch and hold for several seconds. | | **obniz BLE/LTE Gateway** | Front square button | Press and hold for several seconds. | > **Note:** The device will automatically restart if it remains inactive for a certain period. --- ## Saved Network Settings In obnizOS, settings to connect to the cloud are needed to be stored on the device. The following non-volatile settings (settings that are saved even when the power is turned off) are available for this purpose. Setting contents | Contents | Setting method ---|---|--- Device Key | Key to recognize the device | Console or Generated by a device Component settings | Wiring information to external LTE modem and etc | Console/Display/Browser/Internet Network settings | Settings like Wi-Fi password for connecting to Network | Console/Display/Browser/Internet ## Device key Save the obnizID and private key. There are two ways to do this, either by pre-installing it in the device or by writing the settings from the console. Once set, it cannot be removed or deleted. ## Component settings This specifies where the system components such as LEDs are connected. If it is specified, obnizOS will use it. In the case of obnizOS for each device, the settings are stored in the OS, but if the user sets the settings, obnizOS will use the settings with priority. ## Network Settings These are the settings for connecting to the network and the Internet. The following information can be saved. The following information can be saved. Network | Max Setting | Settings ---|---|--- Wi-Fi | 5 | SSID・PasswordBSSIDStatic IP SettingsProxy SettingsWPA2 Enterprise Wi-Fi MESH(Deprecated) | 5 | MESH IDSSID/PasswordBSSIDStatic IP SettingsProxy SettingsWPA2 Enterprise Ethernet | 1 | Static IP SettingsProxy Settings 3G/LTE | 1 | APN, ID, Password ### Priority when there is more than one in the same network The Wi-Fi system allows for multiple connection settings. When multiple profiles are available, it will attempt to connect starting from the most recently saved one. If the storage limit is reached, the oldest settings will be deleted first. Please note that for Wi-Fi, if you save a new configuration with an existing SSID, it will overwrite the previous one. Multiple profiles cannot be saved under the same SSID. ### Primary Network If there are multiple settings across networks (e.g. Wi-Fi and 3G/LTE), obnizOS will give priority to the last setting. ## Settings for devices that are not stored on the device There are settings that are stored on the cloud side, not on the device, and these can be manipulated by device management or cloud APIs. (Examples of settings that are not saved on the device) - Device description - Access token - Region settings --- ## Switching to Setting Mode URL: https://obniz.com/reference/obnizos-for-esp32/settings/setting-mode The settings cannot be made at any time. You need to switch to a mode that allows you to do so. The way to switch depends on the configuration method. # Automatic Setup Mode By default, obnizOS automatically enters **Setup Mode** for approximately 30 seconds if it fails to connect to a previously saved network. > **Applicable to OS7 and later** Starting with obnizOS version 7, you can disable this automatic transition to Setup Mode via the configuration JSON file. When this feature is disabled, the device will no longer enter Setup Mode automatically unless there are no existing network settings or Setup Mode is manually triggered by pressing the onboard button. ### Benefits of Disabling Automatic Setup Mode - **Prevents unintended configuration changes**: Avoids accidental access to settings by unauthorized users. - **Minimizes offline time**: Reduces the duration the device stays in a non-functional setup state during network fluctuations. ### Important Considerations Please be cautious when disabling this feature if the device is installed in a hard-to-reach location. In the **default mode**, if the device cannot connect to a network, it automatically launches its own Wi-Fi Access Point (Setup Mode). This allows you to reconfigure the network settings simply by being within Wi-Fi range of the device. If this feature is disabled, changing the network settings on-site will be significantly more difficult if you cannot physically reach the device's buttons. ![](./images/only_initial.png) ## Configuration from console This configuration is done via serial communication (UART). To enter the setting mode, you need to send a command. The characters of the command and the timing of sending it vary depending on the OS version. OS | How to change setting mode ---|--- - If you are unable to connect to any of the stored network settings. When in configuration mode, the obniz device will output a password-free Wi-Fi with the following SSID from itself ``` obniz-XXXXXXXX ``` (XXXXXXXXX is the obnizID of the device) Connecting with a smartphone or PC will automatically launch a browser (OS 3.5.0 or later). If the browser does not open(OS3.5.0 or later). ## Configure from the display If your device has a display component, such as obniz board, it can accept settings from the display under the following conditions. OS | How to change setting mode ---|--- All versions| - Press and hold the button at startup (the startup option will be activated) - If you cannot connect to any of the stored network settings (obniz Board series only) In the case of the display only, holding down the button at startup will activate the startup option that allows you to perform a minimal reset process. For obniz Board series, you can use "Simple Method" which allows you to select SSID and enter password from the screen. ## Wi-Fi Settings with WPS > From OS3.5.0 1. Set the device to the purple flashing setting mode. 2. press and hold the button for 3 seconds. The purple light will blink faster. 3. Press the WPS button on your Wi-Fi router or access point to complete the Wi-Fi setup. 4. the device will reboot once completed, and the blue light will turn on when it connects to Wi-Fi and comes online successfully --- ## WPS URL: https://obniz.com/reference/obnizos-for-esp32/settings/wps > OS3.5.0 or later ## What is WPS? WPS is a method of setting up Wi-Fi without entering any password, etc. By pressing the buttons on the access point (Wi-Fi router) and the device you want to connect to it at the same time, the device will automatically receive the SSID and Password. ## How to set up If the device has a color LED and a button (Primary Switch), you can set it up. 1. Set the device to the purple flashing setting mode. 2. press and hold the button for 3 seconds. The purple light will blink faster. 3. Press the WPS button on your Wi-Fi router or access point to complete the Wi-Fi setup. 4. the device will reboot once completed, and the blue light will turn on when it connects to Wi-Fi and comes online successfully --- ## Setting from Console URL: https://obniz.com/reference/obnizos-for-esp32/settings/setting-via-serial Configuration via serial communication (UART) is possible for devices equipped with the necessary terminals. ![](./images/console.png) ## Connection Connect the serial communication as follows: | Key | Value | | :--- | :--- | | Terminal | Depends on device and configration. See a manual for each products | | Baud Rate | 115200 bps | | Flow Control | None | | Parity | None | **Note:** Some ESP32 devices include automatic flash circuits using DTR and RTS. In such cases, communication may fail upon connection. Try toggling DTR/RTS ON and OFF (in most cases, setting both to OFF allows normal communication). **In OS7 and later, the console can be disabled. If disabled, console functions will not be available upon connection.** If the console is disabled, you can re-enable it by manually entering Setting Mode [using button operations](./). ## Mode Switching You can switch to Setting Mode by sending a command via serial communication. | OS Version | Method to Change to Setting Mode | | :--- | :--- | | OS 3.5.0 or later | Send the four-character string `menu` at any time after startup. No newline is required. | | Older than 3.5.0 | Send the single character `s` during (or immediately after) startup. No newline is required. | ## Main Menu After entering `menu` to switch modes, the Main Menu will appear. You will be prompted to enter a Passkey (OS6 or later). Please enter the appropriate key. The factory default is `obniz`. ``` Passkey Input text >> ``` The menu items displayed vary depending on the OS version. ``` ----- Select ----- 0: Exit ( Reboot ) [default] 1: Configure Network by Typing 2: Configure ALL from Data 3: Clear All Network Settings 4: Configure Plugin 5: Self Check - Input number >> ``` | Setting | Min. OS Version | Description | | :--- | :--- | :--- | | 0: Exit ( Reboot ) | 3.0.0 | Simply reboots the device. This is selected if you press Enter without typing a number. | | 1: Configure Network by Typing | 3.0.0 | Enter network settings via the console, save, and reboot. | | 2: Configure ALL from Data | 3.0.0 | Perform bulk configuration of components and network using [Configuration JSON](./setting-json). This replaces all internal settings with the provided JSON. | | 3: Clear All Settings | 3.0.0 | Clears all saved settings. | | 4: Configure Plugin | 7.0.0 | Overwrites the Lua plugin. | | 5: Self Check | 7.0.0 | Runs the self-check diagnostic program. | ## Console Operation - When presented with numbered options, enter the number (half-width) and press Enter. - When string input is required, type the text directly. - The console does not accept `\r\n` (CRLF) sequences. If your terminal's newline setting is set to CRLF, please switch it to `\r` (CR) or `\n` (LF). While you can configure Wi-Fi and other settings, selecting "Complete" or "Clear Settings" in the console will save the changes and trigger a reboot. ## 1. Configure Network by Typing You can configure various network settings. Entered settings are saved. Like browser-based configuration, if multiple settings are saved, the most recent one takes priority. **Note:** Saved settings cannot be read back via any method. ### MAC Address (BSSID) Specification *Supported from obnizOS 3.5.0.* You can specify a target Access Point by entering its 12-digit alphanumeric MAC address (lowercase). Press Enter without typing anything to leave it unspecified. ### Connecting to Stealth SSIDs *Supported from obnizOS 3.2.0.* You can connect by entering the SSID and Password regardless of whether the SSID is broadcasted or hidden. ### Static IP Configuration For Static IP, you will be asked for four required items in sequence: For a static IP, you will be asked a series of questions about the items required for configuration. All four of the following are required to use a static IP. ``` --- IP Address Input address >> 192.168.0.10 --- Default Gateway --- Input address >> 192.168.0.10 Input address >> 192.168.0.1 --- Subnet Mask --- Input address >> 255.255.255.0 Input address >> 255.255.255.0 --- DNS Address --- Input address >> 192.168.0.1 Input address >> 192.168.0.1 ``` Enter the required values for each, and press enter to move to the next item. ### How to set up Proxy To configure Proxy, you will need the address and port information of your proxy server. ``` --- Proxy Config --- Proxy Address Input text >> 192.168.8.11 --- Proxy Port --- Port Area:0-65535 Port Area:0-65535 Input number >> 8080 Input text ``` Enter the required values in each field and press Enter to move to the next item. ### WPA2 Enterprise If WPA2 Enterprise is enabled, Username, Password, and AnonymousID can be set. ## 2. Configure ALL from Data Allows configuration using [Configuration JSON](./setting-json). You can write all network and hardware settings at once. *Note: Lua scripts for Plugins cannot be written here; use the specific Plugin menu instead.* ## 3. Clear All Network Settings Deletes all saved network and hardware settings. Plugins are not deleted here; use the specific Plugin menu to clear them. ## 4. Configure Plugin Overwrites the Lua Plugin. Since newlines are part of the script, you cannot use Enter to save. Press `Control + D` to save and exit. To delete the plugin entirely, save with no text entered. If you enter this menu by mistake, simply reboot the device without saving. **Warning:** For long scripts, the buffer may overflow and cause data loss. Please split your input into 1kb chunks. ## 5. Self Check Launches the self-check program. This executes: - The default diagnostic program provided for each terminal by obnizOS. - Any self-check programs defined in the Lua Plugin. ## Recommended Factory Settings In OS7 and later, the device no longer reboots automatically after entering individual settings. This allows you to perform multiple configurations in one session: 1. Enter the menu with `menu`. 2. Enter the Passkey. 3. Use option `2` to write Network and Hardware settings via JSON. 4. Use option `4` to set the Lua Plugin. 5. Use option `5` to run the Self Check and diagnose the circuit. 6. Use option `0` to reboot. --- ## Setting from Browser URL: https://obniz.com/reference/obnizos-for-esp32/settings/setting-via-browser You can connect to the Wi-Fi that the obniz device puts out from your PC/smartphone and configure the settings from your browser. ![](./images/viabrowser.png) ## How to connect to the Wi-Fi put out by the device The device does not put out Wi-Fi at any time, but will be in setting mode under the following conditions. OS | How to change the setting mode | Setting screen ---|---|--- 3.5.0 - If unable to connect to any of the stored network settings | Automatically opens after connection. If it will not be opened, open browser and type `http://192.168.254.1/` - If none of the stored network settings can be connected, open `http://1.2.3.4/` in the browser Once in configuration mode, the obniz device will output a password-free Wi-Fi with the following SSID from itself. ``` obniz-XXXXXXXX ``` (XXXXXXXXX is the obnizID of the device) Connecting with a smartphone or PC will automatically launch a browser (OS 3.5.0 or later). If your browser does not open, or if you have an older OS, open the URL described in above table. ## Login > OS3.5.0 or later PassKey is required to login to the configuration page. The factory default setting is `obniz`, which can be changed via browser or cloud after login (contact us for changing from cloud). ![](./images/softap_login.png) ## Network selection > OS3.5.0 or later After logging in, the following Wi-Fi setting screen will open on your smartphone or PC. No matter what device you are using, the Wi-Fi settings screen will always open first, regardless of your current settings. If you want to use a different setting, please select the desired network from "Network" in the upper left corner. ![](./images/viabrowser.png) The behavior of the settings screen may differ depending on the browser specifications. [For Andoroid users](https://support.obniz.com/hc/ja/articles/9765471641113-%E3%83%8D%E3%83%83%E3%83%88%E3%83%AF%E3%83%BC%E3%82%AF%E8%A8%AD%E5%AE%9A%E7%94%BB%E9%9D%A2%E3%81%A7connect%E5%AE%9F%E8%A1%8C%E5%BE%8C-%E8%A8%AD%E5%AE%9A%E3%81%AE%E7%B5%90%E6%9E%9C%E3%82%92%E7%A2%BA%E8%AA%8D%E3%81%99%E3%82%8B%E5%89%8D%E3%81%AB%E3%83%96%E3%83%A9%E3%82%A6%E3%82%B6%E3%81%8C%E9%96%89%E3%81%98%E3%82%8B-Android%E3%81%A7%E9%96%8B%E3%81%84%E3%81%9F%E5%A0%B4%E5%90%88-) ## Network settings You can configure all the network settings of obnizOS from your browser. For details on what to save, see [Top page of settings](./). There are descriptions about multiple settings and priority. ### Display connection status > OS3.5.0 or later From OS3.5.0, you can check the connection status after setting with a browser. Network | After Setting ---|--- Wi-Fi | Pressing the Wi-Fi connect button will save the settings and display the connection status. In case of failure, an error message will be displayed and you will be able to set up again. Ethernet | Pressing the Ethernet button will save the settings and the device will reboot and try to connect after rebooting. Cellular | Pressing the Cellular button will save the settings and display the connection status. In case of failure, an error message will be displayed and you will be able to configure the settings again, and in case of success, the device will go online and reboot once. The following is an example of what will be displayed as the connection status. Network | Status | Description ---|---|--- Wi-Fi | setting_configured | configured or waiting for configuration _ | wifi_connecting | connecting to Wi-Fi _ | wifi_waiting_dhcp | inquiring about DHCP _ | net_resolving_dns | DNS name resolution in progress _ | net_tcp_connecting | connecting to cloud _ | net_tcp_sending | requesting cloud connection _ | net_tcp_waiting_response | waiting for cloud connection request approval _ | online | online Ethernet | setting_configured | configured or waiting for configuration Cellular | setting_configured | configured or waiting for configuration _ | lte_initing | initializing modem Ethernet | setting_configured | waiting for setting or configuration _ | net_resolving_dns | DNS name resolution _ | net_tcp_connecting | connecting to the cloud _ | net_tcp_sending | requesting cloud connection _ | net_tcp_waiting_response | waiting for cloud connection request approval _ | online | online ### Wi-Fi Settings The Wi-Fi Settings page scans for nearby Wi-Fi and displays the choices as you view them. The following items can be set. Settings|Required | Contents ---|---|--- SSID/Password | required | minimum required to connect, if SSID is not in the list, you can select "Other Network" and enter it. BSSID | Not required | Used for connection with a Mac address. Use 12 alphanumeric characters. Fixed IP | Not required | Specify a fixed IP, subnet, DNS, or Gateway. Leaving it blank will use DHCP. Proxy | not required |Specify port and address to use Proxy for Websocket connection. WPA2 Enterprise | not required | Specify Username, Password and AnonymousID Pressing Connect will immediately save the settings and start the connection. While the connection is in progress, the progress status will be displayed below the button. If the connection is successful, the device will reboot once. If the connection fails, the error message will be displayed. Save up to 5 entries. ### Ethernet Settings Save the wired LAN settings. Settings|Required | Description ---|---|--- Fixed IP | Not Required | Specify a fixed IP, subnet, DNS, or Gateway. Leave this blank to use DHCP. Proxy | not required |Specify port and address to use Proxy for Websocket connection. Unlike Wi-Fi settings, pressing Connect will save the settings and reboot immediately. ### LTE Settings > OS3.5.0 or later Save the SIM settings for the modem. Settings|Required | Description ---|---|--- APN Settings | Required | APN, id, password Press Connect to save the settings immediately and start the connection. While connecting, the progress will be displayed below the button. If the connection is successful, the device will reboot once. If the connection fails, the error message will be displayed. ## Display device information and settings By selecting `Device` from the top navigation, you can delete settings and check the Mac address. The available settings are as follows. Settings | Contents ---|--- Delete network settings | Delete all network settings Wi-Fi Region | Set available channels granted by goverment. By default, it is set to `North America (1-11ch)`. It measn obnizOS only scan actively only 1-11 and passively 12-14ch. Especially for Hidden SSID, obnizOS never find hidden SSID on 12-14ch. PassKey | Set the password for login. If you set this, you will not be able to login with `obniz`. ## Batch Configuration via JSON > For OS7 and later You can configure all settings at once using a [Configuration JSON](./setting-json). By entering a single JSON string, you can set up everything from Wi-Fi credentials to self-hosting configurations in one go. ![](./images/ui-settingjson.png) --- ## Setting from Internet URL: https://obniz.com/reference/obnizos-for-esp32/settings/setting-via-cloud obniz Cloud経由でオンラインであるデバイスに対して設定を書き込みます。 書き込める設定は下記のとおりです。 - ネットワーク設定 - コンポーネント設定 ご利用機能の場合はobnizの営業チームにご連絡ください。 --- ## Setting from Display URL: https://obniz.com/reference/obnizos-for-esp32/settings/setting-via-display On obniz Board / obniz board 1Y, you can select the SSID and password for Wi-Fi using the screen and switches on the device. See the device's Quick Start for more information. [/reference/board-1y/quick-start/](/reference/board-1y/quick-start/) --- ## Setting JSON URL: https://obniz.com/reference/obnizos-for-esp32/settings/setting-json > OS3.5.0 or later This is a JSON file used internally by obnizOS. By writing this JSON from the console or the cloud, you can configure the device in a single step. | Key | Type | Description | Required | | :--- | :--- | :--- | :--- | |net|string|Specify the network. For multiple settings, This indicate first priority of network used. "wirelesslan"(wifi), "wifimesh", "wiredlan" "cellularmodule"|required| |wifi|Array of wifi Object ※1| The last one is the one added most recently. Before OS3.5.0 first one is tried out first then the second one. After OS3.5.0 the order is reversed hence the last one is tried out first.|| > **Note:** When both Wi-Fi and cellular are configured, LTE (cellularmodule) is always attempted first regardless of the `net` setting. Wi-Fi cannot be prioritized over cellular. |wifimesh|Array of wifimesh Object※2|This is an array of object.|| |ether|ether Object※3|Settings for "wiredlan"|| |cellular|cellular Object※4|Settings for "cellularmodule"|| |passkey|string|Passkey for Setting via Wi-Fi|| |wifi_channel|string|Wi-Fi Max Active Channel. Default is 11.|| |hw|Object|LED and other hardware related configrations|| |ws_server( OS7 or later ) | string | Destination Endpoint for Self Hosting | ## ※1 wifi Object |Key Name|Type|Description|Required|Format/Example| | :--- | :--- | :--- | :--- | :--- | |ssid|string|SSID|required|| |pass|string|Password|required|| |bssid|string|BSSID of access point||Hex 6 Bytes. ex) 0123456789ab| |ip|string|Static IP||ex) 192.168.0.2| |netmask|string|Subnet mask||ex) 255.255.255.0| |gw|string|Default gateway||ex) 192.168.0.1| |dns|string|DNS server||ex) 8.8.8.8| |e_n|string|WPA2 Enterprise Username||| |e_p|string|WPA2 Enterprise Password||| |e_i|string|WPA2 Enterprise Identity/Anonymous ID||| |addr|string|WPA2 Proxy address||| |port|string|WPA2 Proxy port||| ## ※2 wifimesh Object |Key Name|Type|Description|Required|Format/Example| | :--- | :--- | :--- | :--- | :--- | |ssid|string|SSID|required|| |pass|string|Password|required|| |meshid|string|Mesh ID|required|Hex 6 Bytes. ex) 0123456789ab| |bssid|string|BSSID of access point|Required when target Wi-Fi is hidden. | Hex 6 Bytes. ex) 0123456789ab| |ip|string|Static IP||ex) 192.168.0.2| |netmask|string|Subnet mask||ex) 255.255.255.0| |gw|string|Default gateway||ex) 192.168.0.1| |dns|string|DNS server||ex) 8.8.8.8| |e_n|string|WPA2 Enterprise Username||| |e_p|string|WPA2 Enterprise Password||| |e_i|string|WPA2 Enterprise Identity/Anonymous ID||| |addr|string|WPA2 Proxy address||| |port|string|WPA2 Proxy port||| ## ※3 ether Object |Key Name|Type|Description|Required|Format/Example| | :--- | :--- | :--- | :--- | :--- | |ip|string|Static IP||ex) 192.168.0.2| |netmask|string|Subnet mask||ex) 255.255.255.0| |gw|string|Default gateway||ex) 192.168.0.1| |dns|string|DNS server||ex) 8.8.8.8| |addr|string|WPA2 Proxy address||| |port|string|WPA2 Proxy port||| ## ※4 cellular Object |Key Name|Type|Description|Required|Format/Example| | :--- | :--- | :--- | :--- | :--- | |apn|string|APN|required|| |id|string|ID|required|| |password|string|Password||| ## passkey passkey can be set from this setting json. If it has a key, then default passkey "obniz" will disabled and new passkey will be used. ```json { "passkey": "newpasskey", "net": "wirelesslan", "wifi": [ { "ssid": "your ssid", "pass": "your password" } ] } ``` ## wifi_channel Wi-Fi Channel/Region Setting. By default, "11" will be used. It mean 11 channel is maximum frequency activly scan. Available values are - "11": North America - "13": EU and Almost all the World - "14": Japan ```json { "wifi_channel": "13", "net": "wirelesslan", "wifi": [ { "ssid": "your ssid", "pass": "your password" } ] } ``` ## Component Settings The configuration of [System Components](/reference/obnizos-for-esp32/components/) can be performed within `hw`. The following settings are available: | Key | Type | Description | Required | | :--- | :--- | :--- | :--- | | terminal | boolean | ( OS7 or later ) Specifies whether to enable the Console. The default value is `true`. | | | setting_mode | string | ( OS7 or later ) By specifying `"only_initial"`, you can disable the feature that automatically enters setup mode when a network connection cannot be established. | | ## Connection Target Server for Self-Hosting In OS7 and later versions, it is possible to connect to self-hosting servers other than the obnizCloud. Please specify the target using an IP address or domain name via the WebSocket protocol. ```json { "ws_server": "ws://192.168.0.2" } ``` ```json { "ws_server": "ws://192.168.0.2:8080" } ``` ```json { "ws_server": "ws://mydomain.com" } ``` ## JSON Examples Simple Wi-Fi ```json { "net": "wirelesslan", "wifi": [ { "ssid": "your ssid", "pass": "your password" } ] } ``` Two Wi-Fi Setting and Cellular with cellular primary. ```json { "net": "cellularmodule", "wifi": [ { "ssid": "secondary wifi ssid", "pass": "your password" }, { "ssid": "primary wifi ssid", "pass": "your password" } ], "cellular": { "apn": "apn1", "id": "id1", "password": "pass1" } } ``` Example with keys ```json { "net": "wirelesslan", "wifi": [ { "ssid": "ssid1", "pass": "pass1", "bssid": "", "ip": "", "netmask": "", "gw": "", "dns": "", "e_n": "", "e_p": "", "e_i": "", "addr": "", "port": "" }, { "ssid": "ssid2", "pass": "pass2", "bssid": "", "ip": "", "netmask": "", "gw": "", "dns": "", "e_n": "", "e_p": "", "e_i": "", "addr": "", "port": "" } ], "wifimesh": [{ "ssid": "ssid1", "pass": "pass1", "bssid": "", "ip": "", "netmask": "", "gw": "", "dns": "", "e_n": "", "e_p": "", "e_i": "", "addr": "", "port": "", "meshid": "0123456789ab" }], "ether": { "ip": "", "netmask": "", "gw": "", "dns": "", "addr": "", "port": "" }, "cellular": { "apn": "apn1", "id": "id1", "password": "pass1" }, "hw": { "terminal": false, "setting_mode": "only_initial" }, "ws_server": "ws://mydomain.com" } ``` --- ## Wi-Fi URL: https://obniz.com/reference/obnizos-for-esp32/wi-fi #### Wi-Fi Specifications Item| value ---|--- Wi-Fi | IEEE in the 2.4GHz band 802.11b/g/n stealth SSID | connectable Certification | Open (no password) (v7.0.0+), WPA-PSK/AES, TKIP (v7.0.0+), WPA2/PSK(AES, TKIP), WEP (WPA2 Enterprise and WPA2/PSK + Captive_portal are not supported.) Compatibility | Improved connection stability with some Wi-Fi routers (v7.0.0+) --- ## Exploration and Connections URL: https://obniz.com/reference/obnizos-for-esp32/wi-fi/discoery How to connect to Wi-Fi ## Setting See [Settings](/reference/obnizos-for-esp32/settings/) for instructions on how to set it up. Network settings are stored in non-volatile space on the device. Up to 5 Wi-Fi connection settings are stored on the device, and the oldest settings are deleted when they are added It is. ## Connection Flow 1. (When the startup and network settings are set to "Wi-Fi") 2. active scan for Wi-Fi 3. try to connect to the Wi-Fi information stored in the scan results, starting with the one with the strongest RSSI. 4. try to connect sequentially to the stored Wi-Fi settings that were not in the rest of the scan results but are saved. 5. waiting for Wi-Fi setting if all connections are not made (if not, the system will time out and restart in about 30 seconds) #### Connection Flow(obnizOS3.4.0かそれ以前の接続フロー) 1. (When the startup and network settings are set to "Wi-Fi") 2. Active scan for Wi-Fi 3. Try to connect if there is any Wi-Fi information stored in the scan results. 4. If any of the stored Wi-Fi information has a stealth SSID, try to connect to it sequentially. 5. If you can't connect to all of them, you will have to wait for the Wi-Fi setting (if it is not set, it will take about 30 seconds out and restart) #### Connection Flow for obnizOS 3.3.0 and ealier 1. (When the startup and network settings are set to "Wi-Fi") 2. If there was an SSID that was successfully connected last time 1. Connect without performing a Scan 2. If the connection fails, it is recorded as a failure. 3. Active scan for Wi-Fi 4. Try to connect if there is any Wi-Fi information stored in the scan results. 5. If any of the stored Wi-Fi information has a stealth SSID, try to connect to it sequentially. 6. If you can't connect to all of them, you will have to wait for the Wi-Fi setting (if it is not set, it will take about 30 seconds out and restart) --- ## Country/Region URL: https://obniz.com/reference/obnizos-for-esp32/wi-fi/region > OS3.5.0 or later Available Wi-Fi signals vary depending on the country or region. obnizOS stores the globally available frequency channels (1-11ch) as default settings and does not emit signals from itself except for those channels. Therefore, it may be difficult to find Wi-Fi on channels 12-13 (most of the world) and 12-14 (Japan) due to passive scanning, and it is not possible to find Wi-Fi on stealth SSIDs. ## Change settings The default setting is `North America (1-11ch)`. You can configure the settings from your browser or by using the json configuration method. The Country/Region setting is a setting for the device and applies to both Wi-Fi and Wi-Fi MESH. Once done, it will not be removed by deleting the network settings. --- ## Hidden SSID URL: https://obniz.com/reference/obnizos-for-esp32/wi-fi/hiddenssid obnizOS will search for stored settings so that it can connect whether it is a stealth SSID or not. Therefore, there is no special setting for stealth SSID. ### Notes on the channels used You can use the stealth SSID for channels 1-11, which are available internationally, but you cannot connect to the stealth SSID for channels 12-14, which are available in Japan, because obnizOS does not perform an active scan. Change Wi-Fi Region from setting (OS3.5.0 or later) --- ## WPA2 Enterprise URL: https://obniz.com/reference/obnizos-for-esp32/wi-fi/wpa2-enterprise > OS3.5.0 or later It is possible to connect to WPA2 Enterprise using Username, Password. Can be configured via console or browser. --- ## Wi-Fi MESH URL: https://obniz.com/reference/obnizos-for-esp32/wi-fi-mesh > OS3.5.0 or later Wi-Fi MESH allows obniz devices to automatically network with each other via Wi-Fi. Only the devices closest to the Wi-Fi router (access point) will be connected to the Wi-Fi, and the rest will be connected to the cloud via the network. ![](../images/img-mesh-wifi.png) This allows obniz to be used in places where Wi-Fi cannot be reached without additional Wi-Fi. It can be used in the following situations. - Installation in places where Wi-Fi is difficult to access, such as underground - When there is a limit to the number of access points that can be connected - When devices are frequently moved or the Wi-Fi environment changes ![](../images/img-mesh-faraway.png) This technology is different from "mesh Wi-Fi" which expands Wi-Fi area provided by Wi-Fi routers and other devices. ## Features - Easy to set up, just add your MESH ID to the normal WiFi settings. - MESH network is built automatically. Automatic rebuilding for later addition and deletion. - Up to 100 nodes in the network, up to 6 steps - Mesh network can be separated by MESH ID - No need to change the usage on the cloud or change the obniz.js program - Failover (another Wi-Fi or LTE connection) is possible in case MESH is not connected - There is only one Wi-Fi connection (using only 1 IP) from the router's point of view with only increased bandwidth, and one TCP communication on it. ## How to use To use Wi-Fi MESH, you need to sign up for Wi-Fi MESH usage on the cloud. Please contact us for more details (Service is currently suspended). How to use 1. connect your device to your cloud account and sign up for a plan 2. set up WiFi and MESH ID (any number) on the device 3. After the device is installed, it will be automatically networked and connected to the cloud to go online. 4. You can still use JavaScript to connect and control the device using obnizID. You can still connect to devices, mesh or not, with a program like this ```javascript var obnizA = new Obniz("1234-5678"); var obnizB = new Obniz("0000-0000"); obnizA.onconnect = async function() { console.log(`connected to A`); } ObnizB.onconnect = async function() { console.log(`connected to B`); } ``` --- ## Self-forming URL: https://obniz.com/reference/obnizos-for-esp32/wi-fi-mesh/algorithm Wi-Fi MESH allows devices to communicate with each other and automatically create a network that can communicate with each other. In order to create the same network, the following settings must be in place. - SSID and password of the Wi-Fi access point, and BSSID if specified. - MESH ID Devices with the same settings will automatically create a mesh network, but devices with different settings will not recognize each other, even if they are close to each other. ## RootNode A mesh network is a network of devices that can communicate with each other, but the Root Node is the only one in the network that can connect to Wi-Fi and communicate with the Internet. There can be only one Root Node in a mesh network. The Root Node acts as a proxy and does the packet routing in the mesh network. It propagates the data received from the Internet to other devices and forwards the data coming from the devices to the obnizCloud. By working with obnizCloud, RootNode makes it seem as if each device is directly connected to Wi-Fi instead of MESH, and provides APIs to users. We will provide APIs to users. ![](../images/img-mesh-apone.png) ## Construction flow 1. If no network is established, use radio waves (Wi-Fi) to determine each other's location. 2. the device closest to the Wi-Fi router/access point (Root Node) is determined among the members who know each other. 3. As well as determining the Root Node, we also determine who will be connected to where and how they will be routed to the Root Node. 4. 4. After the decision is made, the Root Node connects to the obnizCloud via the Internet. 5. 5. After the Root Node comes online, the devices in each network connect to the obnizCloud via a pseudo-internet connection and come online respectively. ![](../images/img-mesh-wifi.png) ## Layers In Wi-Fi MESH, devices have a parent-child relationship and a cyclical network is not built. Therefore, the Root Node is called Layer=1, the devices connected to the Root Node are called Layer=2, the devices connected to Layer=2 are called Layer=3, etc. There are up to 6 layers. ![](../images/diagram_mesh.png) In addition, the number of child nodes connected to one device is 5. So, if you have 6 devices in total 1. 1 device is a RootNode and the remaining 5 devices are all connected to the RootNode with Layer=2 2. one device is a RootNode and the rest are connected in a bead-like pattern to Layer=6 3. other These connection patterns are automatically determined based on the location of each other. ## Device authentication Each device communicates with the obniz cloud through a pseudo-internet connection. Authentication of devices will also be done as usual. Therefore, if the number of devices in the mesh network is large, it may take a lot of time for everything to come online even after the mesh network has been built. --- ## Self-healing(ReAdd/Remove) URL: https://obniz.com/reference/obnizos-for-esp32/wi-fi-mesh/add-remove The network is automatically rebuilt when a device with the same configuration is installed locally, or when a device that was running is powered off and on again. ## Partial additions and removals If the Root Node is also connected to the Internet and part of it is moved, only the part that has been changed will be rebuilt. If the Root Node is connected, the current connection will not be disconnected. Even if you feel that it would be better to connect the nodes in this way, the current state will be maintained and additions and deletions will be performed. In the case of addition - After a mesh network is discovered, it is determined where it should be connected and connected to, which may or may not be a Root Node. - It may or may not be a Root Node, but it does not rebuild already connected devices to add them. In case of deletion - If the device does not have any children, it will be deleted as is. - If the device has children, the children will be disconnected from the network and added again. ![](../images/img-mesh-auto.png) ## Root Node switching If the Root Node loses Wi-Fi, all networks are reviewed, and if it is determined that it is not a suitable Root Node, another Node becomes the Root Node, and everything else is rebuilt. If the device that is the Root Node loses its Root Node due to power loss, etc., the entire network will be rebuilt. --- ## Separating Network URL: https://obniz.com/reference/obnizos-for-esp32/wi-fi-mesh/separete-meshid Since there will only be one Root Node, if you want to reduce the number of devices in your network due to high communication volume, such as BLE scanning, you will want to increase the number of devices connected to your Wi-Fi router/access point as much as possible by making them separate networks, even if they are close together. If you want to separate the networks, you can do so by simply changing the MESH ID. For example - 10 devices with MESH ID = `000000000001`. - 10 devices with MESH ID = `000000000002`. If there are 10 obniz devices with MESH ID = `000000000001` and one Wi-Fi access point nearby, the Root Node closest to the Wi-Fi access point will be determined, so two obniz devices will be connected to the Wi-Fi and the other 9 devices will hang from their respective Root Nodes. --- ## Ethernet URL: https://obniz.com/reference/obnizos-for-esp32/ethernet > OS7 and later By connecting an Ethernet physical transceiver to the ESP32, Internet connection via wired LAN can be used. ## Available Phisical PHY Below are availables. By setting system component to obnizOS, obnizOS will recognize and configure then enabled. - W5500 --- ## Ethernet PHY Wiring URL: https://obniz.com/reference/obnizos-for-esp32/ethernet/wiring > Deprecated By connecting an Ethernet PHY such as LAN8720 to the ESP32, the ESP32 can be used via wired LAN. You can connect to the Internet with Available Ethernet PHYs LAN8720TLK110 Wiring LAN8720 Reference Circuit: https://www.olimex.com/Products/IoT/ESP32/ESP32-GATEWAY/open-source-hardware ESP32 GPIOLAN87205RESET(This is not on LAN8720)23MDC18MDIO17CLKIN19EMAC TXD022EMAC TXD121EMAC TX EN25EMAC RXD026EMAC RXD1 TLK110 There are no references. --- ## LTE URL: https://obniz.com/reference/obnizos-for-esp32/cellular > OS3.5.0 and later By connecting a compatible modem to the ESP32, you can connect to obnizCloud via 3G/LTE line. obnizOS receives three pieces of information, APN, id, and password, initializes the modem, and then connects to the Internet. ## Supported modems - Quectel's BG96 (LTE M1/NB-IoT modem) - nRF9160 --- ## Modem Wiring URL: https://obniz.com/reference/obnizos-for-esp32/cellular/wiring ## 設定方法 どちらのモデムをどのピンに配線したかを[シリアル経由設定](/reference/obnizos-for-esp32/settings/setting-via-serial)または[ブラウザ経由設定](/reference/obnizos-for-esp32/settings/setting-via-browser/)で設定することでobnizOSがモデムを利用しインターネット接続を行います。 ## BG96 Quectel製 BG96 はLTE M1/NB-IoTの回線に接続できます。 ### ESP32との配線例 次のように接続してください。 BG96 Function | ESP32 | BG96 --- | --- | --- Power | 14 | PWRKEY Reset | 15 | RESET RX | 12 | RXD1 TX | 13 | TXD1 TX,RX,Power,Resetについては設定側より変更可能なので上記はあくまで配線例となります。 #### M5Stackとの配線例 M5StackからBG96に接続する場合は次のように接続してください。 BG96 Function | ESP32 | BG96 --- | --- | --- Power | 16 | PWRKEY Reset | 15 | RESET RX | 12 | RXD1 TX | 13 | TXD1 TX,RX,Power,Resetについては設定側より変更可能なので上記はあくまで配線例となります。 --- ## Remote OS Update(OTA) URL: https://obniz.com/reference/obnizos-for-esp32/ota obnizOS can be updated remotely via the cloud. This allows for vulnerability patches and the delivery of new features to your devices seamlessly. ## OTA Partition Structure obnizOS is typically stored in two separate partitions within the ESP32's 4MB internal (or external) flash memory. These partitions are used alternately for each Over-The-Air (OTA) update to ensure a safe transition. ## How to Update For detailed instructions on the update process, please refer to the **OTA** section under the [Remote OS Update (OTA)](/reference/cloud/device-management/remote-os-update-ota/) page in [Device Management](/reference/cloud/device-management/). ### Update Process: 1. When an update starts, the new obnizOS is installed into the currently unused OTA partition. 2. Once the download is complete, the boot partition is updated. 3. The device automatically restarts to launch the newly installed version of obnizOS. ## Security and Reliability The update process is designed with safety in mind. If the update is interrupted—for example, due to a lost network connection—the OTA process will be flagged as failed. In such cases, the device will continue its current operation using the existing OS without restarting, preventing any potential "bricking" or unexpected downtime. --- ## Sleep URL: https://obniz.com/reference/obnizos-for-esp32/sleep obnizOS is equipped with a sleep function that stops the CPU operation to minimize power consumption. This feature is ideal for operating devices with batteries or solar panels in environments where a constant power supply is unavailable, such as outdoors. ## Sleep Types and Behavior obnizOS supports the following types of sleep modes: | Type | Compatible OS Version | Behavior | | --- | --- | --- | | Deep Sleep + External Modem Sleep | 7.0.0 or later | System shuts down completely and reboots after waking up. The external modem also enters sleep mode. | | Deep Sleep (Without External Modem Sleep) | 7.0.0 or later | System shuts down completely and reboots after waking up. The external modem remains active. | | Light Sleep + External Modem Sleep | 7.0.0 or later | System pauses temporarily without rebooting. The external modem also enters sleep mode. | | Light Sleep (Without External Modem Sleep) | 7.0.0 or later | System pauses temporarily without rebooting. The external modem remains active. | | obniz Board 1Y Sleep | 2.0.0 or later | Specifically for obniz Board 1Y. Minimizes power by cutting off the 3.3V power line using an external power module. | * **obniz Board 1Y Sleep** is the most power-efficient mode but is hardware-dependent. * Other sleep modes are standard functions of the **ESP32** (on which obnizOS runs) and can be used on any obnizOS-compatible ESP32 device. * **External Modem** refers to an LTE modem connected externally. For the **Intelligent Edge series**, the internal nRF91 modem will enter sleep mode when this option is selected. ## Wake-up Triggers When initiating sleep, you must specify one of the following triggers to wake the device: | Trigger Type | Compatible OS Version | Behavior | | --- | --- | --- | | Timer | 2.0.0 or later | Wakes up after a specified duration. | | IO0 State Change (High/Low) | 2.0.0 or later | Exclusive to **obniz Board 1Y**. Wakes up when the pin state changes. | * **Note on Accuracy:** The timer relies on the internal ESP32 clock or the power module's clock. Please be aware that it may not be perfectly accurate and can be affected by ambient temperature. * **Connection Latency:** The device does not become "Online" immediately after waking up. For example, if you set a 60-second sleep, the internet reconnection process starts *after* those 60 seconds have passed. Therefore, it will take additional time before the device is accessible via the cloud. ## Using Sleep via Javascript SDK (Cloud) When controlling obniz via JavaScript or the Cloud, only the following two modes are available: * **Deep Sleep + External Modem Sleep** * **obniz Board 1Y Sleep** (Automatically selected when using an obniz Board 1Y) ```javascript // Javascript Example obniz.sleepSeconds(60); // Sleep for 60 seconds (1 minute) ``` Since you can trigger sleep at any timing from the cloud, it is particularly useful for periodic monitoring: * Sleep the device after data is successfully uploaded until the next required interval. * Adjust sleep duration dynamically based on battery voltage (e.g., sleep for 5-minute intervals). ## Using Sleep via Lua Plugin The Lua Plugin installed on the device allows for more granular control, including both Light and Deep sleep modes. The duration is specified in milliseconds. ```lua -- Lua Example os.sleep(5 * 1000, 0); -- Deep sleep + External module sleep os.sleep(5 * 1000, 1); -- Deep sleep + Without external module sleep os.sleep(5 * 1000, 2); -- Light sleep + External module sleep os.sleep(5 * 1000, 3); -- Light sleep + Without external module sleep ``` **Edge Computing Advantage:** Using the Lua Plugin allows the device to make decisions and enter sleep mode *before* connecting to the internet. This is highly effective for minimizing battery consumption—for example, checking a sensor value and only connecting to the internet if data transmission is necessary. The following script demonstrates how to connect to the internet only when the voltage on IO1 exceeds 2.0V: ```lua io.retain(1, true); if ad.get(1) < 2.0 then -- If voltage is low, sleep for 1 minute and check again without connecting to the cloud os.sleep(60 * 1000, 0); end ``` **Caution:** When using sleep before an internet connection is established, there is a risk that the device may never connect to the internet if the conditions are not met. Please use this feature with care for remote maintenance. ## Power Consumption during Sleep Power consumption during sleep varies depending on the hardware. For specific values, please refer to the hardware reference manual for your specific product. --- ## Lua Plugin URL: https://obniz.com/reference/obnizos-for-esp32/lua > OS7 or later The **Lua Plugin** is a feature that allows you to embed software directly into the device to control offline behavior and compress data communications. ## Device-Side Software By default, obniz devices only contain the OS and are operated remotely from a server via the SDK and API. By using Lua, you can write and execute programs directly on the device. This is ideal when you need to define device behavior during network outages or when you want to compress communication data. **What you can do with the Lua Plugin:** - Start data logging immediately upon boot. - Perform predefined operations regardless of whether the device is online or offline. - Filter or compress specific data before sending it to the server. - Receive specific data or perform contact/IO operations at regular intervals. - Monitor status while offline, remain in sleep mode, and only connect to the internet when data needs to be sent. ![](./images/lua.png) ## Lua Operation Lua scripts can either be saved to the device for permanent execution or executed on-the-fly via the cloud. Scripts saved on the device are automatically loaded and executed upon startup. *(Note: Lua scripts will not be executed if the device starts in Safe Mode.)* ## Saving Lua Scripts to the Device You can save Lua scripts to the device using one of the following methods: - Via Serial Console - Via obniz.js The following example shows how to save a script using obniz.js. Once executed, the device will output `Hello World` to the serial console every time it boots. ```javascript obniz.storage!.savePluginLua(`os.log("Hello World");`); obniz.plugin!.reloadLua(); ``` ## On-the-Fly Lua Execution You can execute Lua scripts via the SDK without saving them to the device's permanent storage. ```javascript obniz.plugin!.execLua(` x=1; x=x+2; os.log(x.."\\n") `); // will print "3" on obnizOS console (requires console enabled) obniz.plugin!.execLua(`os.log(os.getTick().."\\n")`); obniz.plugin!.execLua(`os.log(os.getTick().."\\n")`); ``` By using this feature, you can update necessary functions and variables in real-time without restarting the device. This allows for rapid optimization of device behavior and maximum reduction of communication volume without any downtime. **Example: Changing communication frequency from the cloud based on values** ```javascript if (temperature > 26) { obniz.plugin!.execLua(` interval = 1; `); } else { obniz.plugin!.execLua(` interval = 60; `); } ``` **Example: Switching the type of data sent based on the mode** ```javascript if (mode == 'temperature') { obniz.plugin!.execLua(` function filter(data) if data.temperature == nil then return nil end return data end `); } else { obniz.plugin!.execLua(` function filter(data) return data end `); } ``` ## Lua Execution Environment Lua runs on the same CPU that runs obnizOS. Please note the following specifications and constraints: | Item | Description | | --- | --- | | **Language** | Lua 5.4.7 (Support varies depending on the obnizOS version) | | **Numeric Precision (int/double)** | 32-bit | | **Flash Storage Capacity** | Max 500 KB (May decrease depending on the device and other stored data) | | **Memory (RAM)** | Max 200 KB (May decrease depending on the device and OS usage) | obnizOS constantly monitors Lua execution. If the OS detects an anomaly, it will automatically stop the script or restart the device in Safe Mode. This safeguards the device from being bricked by faulty scripts and ensures that cloud connectivity is maintained whenever possible. ## Available Lua Functions For more detailed information on programming with Lua, please refer to the obniz.js Guide. --- ## Arduino Plugin(deprecated) URL: https://obniz.com/reference/obnizos-for-esp32/plugin > Deprecated ## What is a Plug-in? Plug-in is to create an obnizOS that contains a user-created program and operate it on a device (plug-in OS), instead of operating it via the cloud. This enables the development of the following software that cannot be handled by the existing obnizOS alone. - Fast and accurate IO operations that are not affected by network delays - Program offline behavior - Arduino libraries can be used for development with ArduinoIDE ## How to develop Create the program you want to run in the Arduino IDE. You can use the plug-in by putting it into the device you want to run. The created plugin OS supports OTA from obnizCloud as well as USB writing from ArduinoIDE, and OTA processing is done by cloud and obnizOS, so you don't need to develop software for it. The OTA process is handled by the cloud and obnizOS. ![](./images/system.png) ## Relationship between obnizOS and plug-ins This is a program to "use obnizOS" from the software you created. You can start and stop obnizOS from the software you create. However, if obnizOS is not running, you cannot use OTA, device management, IO control, and other functions available in obniz. When you start obnizOS, it will create a new task. By doing this, obnizOS will run while the plug-in continues to run. In obnizOS, when you connect to the network or go offline, an event is generated, which can be retrieved by the plug-in. See the reference for details. ```c++ // Example #include . void setup() { Serial.begin(115200); obniz.start(); } void loop() { } ```` --- ## Setup URL: https://obniz.com/reference/obnizos-for-esp32/plugin/arduino-ide > Deprecated ## Setup. Install the plug-in to the Arduino IDE. Please install the Arduino IDE beforehand. This section is written in Windows environment, but there are similar settings for Mac as well. After installing the Arduino IDE, launch it. Open "File" -> "Preferences". ![](images/2020-06-22_23h35_46.png) The Preferences dialog will appear. Look for "Additional Board Manager URL" at the bottom of the dialog. Insert the following URL into the "Additional Board Manager URL" field. ``` https://obniz.github.io/obniz-plugin-arduino/package_obniz_index.json ``` ![](images/2020-06-26_14h05_30.png) When you are done with the settings, click "OK" to close and save the settings. Next, open "Tools" -> "Board" -> "Board Manager". ![](images/2020-06-22_23h45_32.png) When you open the [Board Manager], the process will run and there will be a waiting time. After a while, it will calm down and you can type "obniz" in the search field. You can see the button "Install" in the next picture. ![](images/2020-06-26_14h42_09.png) Once you have installed the device as shown in the image above, you can see multiple devices such as "ESP32 Dev Module" as obniz plug-in in the "Tools" > "Board" option. If you are using DevKitC, choose "ESP32 Dev Module" to proceed with your development. ![](images/2020-06-22_23h50_07.png) Setup is now complete. ## Writing with the Arduino IDE When you write the program, you need to select the appropriate serial port. Select "Tools" -> "Serial Port" -> "Appropriate Port". After you choose, you can write your program by clicking "→" button of Arduino IDE. ![](images/2020-06-26_15h10_17.png) ## What can I do with the obnizOS plug-in? You can check a sample program from Arduino IDE. Click "File" -> "Sketch Examples" -> "Obniz" to see several sample programs. You can start using them from there. ![](images/2020-06-26_15h07_00.png) ### Start obnizOS. ``` obniz.start(); ``` Start obnizOS. ### Exit obnizOS. ``` obniz.end(); ``` Exit obnizOS. ### Get the version of obnizOS. ``` obniz.getOsVersion(); ``` You can get the version of obnizOS. ### Obtain obnizID. ``` obniz.getId(); ``` You can get an obniz ID. ### Send and receive plug-in commands. Sending the command ``` obniz.commandSend(data,length); ``` Receiving Commands ``` void onCommand(uint8_t* data, uint16_t length){ Serial.println("\nonCommand"); Serial.write(data,length); Serial.println("\nEnd onCommand"); } obniz.commandReceive(onCommand); ``` You can exchange data between obniz.js and the device by using commands. ### Occupy and free IOs. Allows you to occupy IO privileges without being controlled by obnizOS, and can be intentionally released. You can also release it intentionally. The following functions occupy IO automatically. - pinMode - wire.begin - analogRead If it is not occupied, there is a possibility that plug-in can't control the system by resetting IO when obnizOS starts up or when disconnecting from the server (if you want to disable resetting on disconnect, you need to set `reset_obniz_on_ws_disconnection: false`). Yes, there is. Occupancy. ``` obniz.pinReserve(io) ``` liberation ``` obniz.pinFree(io) ``` ### obnizOS Events You can get events when you are offline or online. Network events - Network connection `PLUGIN_EVENT_NETWORK_HARDWARE_CONNECTED` - obniz cloud connection `PLUGIN_EVENT_NETWORK_CLOUD_CONNECTED` - Network Disconnect `PLUGIN_EVENT_NETWORK_HARDWARE_DISCONNECTED` - obniz cloud disconnected `PLUGIN_EVENT_NETWORK_CLOUD_DISCONNECTED` - WiFi scanning `PLUGIN_EVENT_NETWORK_WIFI_SCANNING` - WiFi not found `PLUGIN_EVENT_NETWORK_WIFI_NOTFOUND` - WiFi connection `PLUGIN_EVENT_NETWORK_WIFI_CONNECTING` - WiFi access point mode connection event `PLUGIN_EVENT_NETWORK_WIFI_SOFTAP_CONNECTED` - WiFi error `PLUGIN_EVENT_NETWORK_WIFI_FAIL` Other - Other errors `PLUGIN_EVENT_FAIL` - Start OTA `PLUGIN_EVENT_OTA_START` - OTA ends `PLUGIN_EVENT_OTA_END` - OTA error `PLUGIN_EVENT_OTA_ERROR` ``` void onEvent(os_event_t event, uint8_t* data, uint16_t length) { switch (event) { case PLUGIN_EVENT_NETWORK_HARDWARE_CONNECTED: case PLUGIN_EVENT_NETWORK_CLOUD_CONNECTED: case PLUGIN_EVENT_NETWORK_HARDWARE_DISCONNECTED: case PLUGIN_EVENT_NETWORK_CLOUD_CONNECTED: case PLUGIN_EVENT_NETWORK_DISCONNECTED: case PLUGIN_EVENT_NETWORK_CLOUD_DISCONNECTED: case PLUGIN_EVENT_NETWORK_DISCONNECTED: case PLUGIN_EVENT_NETWORK_DISCONNECTED: case PLUGIN_EVENT_NETWORK_WIFI_SCANNING: case PLUGIN_EVENT_NETWORK_WIFI_NOTFOUND: case PLUGIN_EVENT_NETWORK_CLOUD_SCANNING: case PLUGIN_EVENT_NETWORK_SCANNING: case PLUGIN_EVENT_NETWORK_CLOUD_SCANNING: case PLUGIN_EVENT_NETWORK_WIFI_CONNECTING: case PLUGIN_EVENT_NETWORK_WIFI_SOFTAP_CONNECTED: case PLUGIN_EVENT_NETWORK_WIFI_CONNECTING: case PLUGIN_EVENT_NETWORK_CONNECTING: case PLUGIN_EVENT_NETWORK_NOTFOUND: case PLUGIN_EVENT_NETWORK_SOFTAP_CONNECTED: case PLUGIN_EVENT_NETWORK_WIFI_FAIL: case PLUGIN_EVENT_EVENT_FAIL: case PLUGIN_EVENT_OTA_FAIL: case PLUGIN_EVENT_EVENT_OTA_FAIL: case PLUGIN_EVENT_EVENT_FAIL: case PLUGIN_EVENT_OTA_END: case PLUGIN_EVENT_OTA_ERROR: break; } } obniz.onEvent(onEvent); ``` ### Status Check. Running whether or not obnizOS is running. ```` obniz.isRunning() ```` Online status or not Online when true ```` obniz.isOnline() ```` --- ## Commands URL: https://obniz.com/reference/obnizos-for-esp32/plugin/custom-communication > Deprecated ## Plug-in Commands Data can be exchanged between obniz.js and devices by using commands between them. This allows you to send sensor data and instruct plug-in from your browser. ### Plug-in program. You can program the plug-in with the following function Device→JavaScript Send ``` obniz.commandSend(data,length); ``` Device←Receiving JavaScript ``` void onCommand(uint8_t* data, uint16_t length){ Serial.println("\nonCommand"); Serial.write(data,length); Serial.println("\nEnd onCommand"); } obniz.commandReceive(onCommand); ``` ### JavaScript programs. The javascript program can be executed by the following function. Device→Receive JavaScript ``` obniz.plugin.onreceive = data => { console.log(data); }; ``` Device←Send JavaScript ``` obniz.plugin.send("obniz.js send data get device?") ``` --- ## IO URL: https://obniz.com/reference/obnizos-for-esp32/plugin/io > Deprecated ## Default behavior obnizOS takes control of all IO. In particular, it resets the IO in the following cases - After starting obnizOS - When offline - When the client is disconnected (when `reset_obniz_on_ws_disconnection: false` is not set) If you want to use IO from the plugin, you need to tell obnizOS in advance that you want to remove this IO from the management. The following functions can be used to manage the IO to be used. ### Retain by Plugin Software Remove the IO from the management of obnizOS and use it exclusively. ``` obniz.pinReserve(io) ``` ### Release from Plugin Software Return to obnizOS management. ``` obniz.pinFree(io) ``` ### Automatic Retain Calling the following function will automatically occupy the IO. However, it is better to call `pinReserve()` in advance to resolve conflicts with obnizOS. - pinMode - wire.begin - analogRead --- ## Network Control URL: https://obniz.com/reference/obnizos-for-esp32/plugin/network-control > Deprecated ## Network ### Network Connections Only on obnizOS. When you use `obniz.end()`, obnizOS disconnects from the network. If you use `obniz.start()` to start obnizOS on your Wi-Fi, it will connect to the network automatically. You can connect to the network only via serial communication. --- ## PluginKey and OTA URL: https://obniz.com/reference/obnizos-for-esp32/plugin/ota > Deprecated ## OTA You can transfer your plug-ins to obnizOS via obniz Cloud. ### Register your plug-in to the cloud for generate a key In the console, go to "ObnizOS" and select "New Registration" for the plug-in OS. You need to give the plug-in OS a name. It must be the only name in the world. You can use alphanumeric characters and underscores. Then drag and drop the built bin file to start the upload. The bin file is output from the Arduino development environment by "Sketch" -> "Output Compiled Binary" to the same location where the ino file is located. ![](./images/plugin_register.png) If the upload is successful, the date of creation will be displayed as shown in the attachment. ![](./images/plugin_registrated.png) ### Build again The "Plugin Key" displayed in this case is the key used by obniz cloud to recognize the plugins. You register this key in the plug-in program. ```c obniz.setKey("1EfR9nLYGVOkWKP1nf9V8fKEPM194je4"); obniz.onEvent(onEvent); obniz.start(); ``` When you run the program, you will also see the name you just registered in the device management screen. Register the program in the cloud again for use in OTA. ### Update. Plug-in OSs registered in the cloud can be updated. You can overwrite them by dragging and dropping them as well. ![](./images/plugin_registrated.png) ### OTA. OTA is done from the device management screen. Open the configuration screen of the device to which you want to write the plug-in OS. Select the plug-in OS you have created in the "ObnizOS Remote Update" section and press "Install". --- ## Reference URL: https://obniz.com/reference/obnizos-for-esp32/plugin/reference > Deprecated ## start - start() - start(HardwareSerial* serial) Start obnizOS. ### Arguments. - serial : Use this option to print out the log of obnizOS, you can set this option to NULL to disable logging. The default value is Serial. ### Return value There is a return value in int. - 0 : OK - -1 : id value error - -2 : Key value error - -3 : Certified error ## end - end() Terminate obnizOS. Disconnects from the network. ### Arguments. None ### Return value None ## pinReserve - pinReserve(uint8_t pin) Occupy IO without being controlled by obnizOS. The following functions are used to automatically occupy IO - pinMode - wire.begin - analogRead If it is not occupied, there is a possibility that plugins can't control the system by resetting IO when obnizOS starts up or when disconnecting from the server (if you want to disable resetting on disconnect, you need to set `reset_obniz_on_ws_disconnection: false`). There are. ### Arguments. - Pin: Specify the actual IO to be used. 0-40 values are allowed. ### Return value. None ## pinFree - pinFree(uint8_t pin) Releases the right to use IO. ### Arguments. - Pin: Specify the actual IO to be used. 0-40 values are allowed. ### Return value. None ## commandSend - commandSend(uint8_t data, uint16_t length) Sends data for the command. ### Arguments. - data: array of data to be sent - length : length of data to be sent ### Return value None ## commandReceive. - commandReceive(CallbackCommandFunction func) Receive data from the command. Callback function is required. ### Arguments. - func : Set a callback function. void func(uint8\_t data, uint16\t length) ### Return value None ### Sample Programs. ``` void onCommand(uint8_t* data, uint16_t length){ Serial.println("\nonCommand"); Serial.write(data,length); Serial.println("\nEnd onCommand"); } obniz.commandReceive(onCommand); ``` ## onEvent - onEvent(CallbackEventFunction func) You can get the event when you are offline or online. Callback function is required. ### Arguments. - func : Set a callback function. void func(os_event_t event, uint8_t* data, uint16_t length) ### Return value None ### Types of Events. Network Events - Network connection `PLUGIN_EVENT_NETWORK_HARDWARE_CONNECTED` - obniz cloud connection `PLUGIN_EVENT_NETWORK_CLOUD_CONNECTED` - Network Disconnect `PLUGIN_EVENT_NETWORK_HARDWARE_DISCONNECTED` - obniz cloud disconnected `PLUGIN_EVENT_NETWORK_CLOUD_DISCONNECTED` - WiFi scanning `PLUGIN_EVENT_NETWORK_WIFI_SCANNING` - WiFi not found `PLUGIN_EVENT_NETWORK_WIFI_NOTFOUND` - WiFi connection `PLUGIN_EVENT_NETWORK_WIFI_CONNECTING` - WiFi access point mode connection event `PLUGIN_EVENT_NETWORK_WIFI_SOFTAP_CONNECTED` - WiFi error `PLUGIN_EVENT_NETWORK_WIFI_FAIL` Other - Other errors `PLUGIN_EVENT_FAIL` - Start OTA `PLUGIN_EVENT_OTA_START` - OTA ends `PLUGIN_EVENT_OTA_END` - OTA error `PLUGIN_EVENT_OTA_ERROR` ### Sample Programs. ``` void onEvent(os_event_t event, uint8_t* data, uint16_t length) { switch (event) { case PLUGIN_EVENT_NETWORK_HARDWARE_CONNECTED: case PLUGIN_EVENT_NETWORK_CLOUD_CONNECTED: case PLUGIN_EVENT_NETWORK_HARDWARE_DISCONNECTED: case PLUGIN_EVENT_NETWORK_CLOUD_CONNECTED: case PLUGIN_EVENT_NETWORK_DISCONNECTED: case PLUGIN_EVENT_NETWORK_CLOUD_DISCONNECTED: case PLUGIN_EVENT_NETWORK_DISCONNECTED: case PLUGIN_EVENT_NETWORK_DISCONNECTED: case PLUGIN_EVENT_NETWORK_WIFI_SCANNING: case PLUGIN_EVENT_NETWORK_WIFI_NOTFOUND: case PLUGIN_EVENT_NETWORK_CLOUD_SCANNING: case PLUGIN_EVENT_NETWORK_SCANNING: case PLUGIN_EVENT_NETWORK_CLOUD_SCANNING: case PLUGIN_EVENT_NETWORK_WIFI_CONNECTING: case PLUGIN_EVENT_NETWORK_WIFI_SOFTAP_CONNECTED: case PLUGIN_EVENT_NETWORK_WIFI_CONNECTING: case PLUGIN_EVENT_NETWORK_CONNECTING: case PLUGIN_EVENT_NETWORK_NOTFOUND: case PLUGIN_EVENT_NETWORK_SOFTAP_CONNECTED: case PLUGIN_EVENT_NETWORK_WIFI_FAIL: case PLUGIN_EVENT_EVENT_FAIL: case PLUGIN_EVENT_OTA_FAIL: case PLUGIN_EVENT_EVENT_OTA_FAIL: case PLUGIN_EVENT_EVENT_FAIL: case PLUGIN_EVENT_OTA_END: case PLUGIN_EVENT_OTA_ERROR: break; } } obniz.onEvent(onEvent); ``` ## getId - getId() You can get an obnizID, you must have started obnizOS. It returns NULL if executed immediately after start or when not running. ### Arguments. None ### Return value const char char* : obnizID is returned as a string. ## getOsVersion. - getOsVersion() You can get the version of obnizOS. ### Arguments. None ### Return value const char char* : The version of obnizOS is returned as a string. ## isRunning - isRunning() You can retrieve whether obnizOS is running or not. ### Arguments. None ### Return value bool: running when true. ## isOnline. - isOnline() You can retrieve whether it is online or not. ### Arguments. None ### Return value bool : true when online. --- ## CHANGELOG URL: https://obniz.com/reference/obnizos-for-esp32/changelog ## 7.1.0 (Under beta) 2026/x/x This release expands the Lua Plugin with new peripherals and system functions, and improves cellular connectivity and board startup. Several peripheral functions that previously required the ESP32 family now also run on obniz Board, because the Lua peripheral layer was moved onto logical IO mapping. Target OS - obnizOS for Intelligent Edge Kilo ( hw=iekilo1 ) - obnizOS for Intelligent Edge Micro ( hw=iemicro1 ) - obnizOS for obniz BLE/Wi-Fi Gateway Gen 2.0 ( hw=blewifi_gw2 ) - obnizOS for obniz BLE/LTE Gateway (Cat.4) ( hw=blelte_gw2 ) - obnizOS for AK-030 LTE Cat.M1 USB Dongle ( hw=ak030 ) - obnizOS for obniz BLE/Wi-Fi Gateway ( hw=encored ) - obnizOS for IoTBank USB Gateway ( hw=iotbankusbgw ) - obnizOS for M5Stack Basic ( hw=m5stack_basic ) - obnizOS for ESP32 ( hw=esp32w or hw=esp32p ) - obnizOS for obniz Board 1Y ( hw=obnizb2 ) - obnizOS for obniz Board ( hw=obnizb1 ) ### Plugins (Lua) #### New peripherals * **PWM:** Added `pwm.start()`, `pwm.freq()`, `pwm.duty()`, and `pwm.stop()`. Output is specified by logical obniz IO, so the same code runs on obniz Board as well. * **Display:** Added `display.print()`, `display.clear()`, and `display.raw()`. These are ignored on products without a display. * **LTE:** Added `lte.at()` for sending arbitrary AT commands to the cellular modem. #### IO and analog * **IO:** Added `io.drive()` (output drive method) and `io.pull()` (pull resistor). `"5v"` is available only on obniz Board. * **AD:** `ad.get()` now also runs on obniz Board. * **UART / SPI:** Added `uart.isUsed()` and `spi.isUsed()`. UART and SPI now operate through logical IO, so they are available on obniz Board. #### Cloud and communication * **Cloud transaction:** Added `cloud.transactionWait()`, paired with the obniz.js `obniz.plugin.callWait()` method and the `obniz.plugin.onCloudTransaction` handler, for request-and-reply communication. * **Error handling:** Added the `obniz.plugin.onError` event to receive Lua errors on the obniz.js side. #### System * **Low memory:** Added the `on_low_memory()` handler, called before an allocation fails so the plugin can release resources and recover. #### Bluetooth * Added the `isScanResp` flag to BLE scan results, which indicates whether a packet is a scan response. ### Peripherals * **PWM:** Added PWM support for ESP32-C3 and ESP32-C6. ### Internet Connection #### LTE * nRF9160: Enabled the TLS session cache. * nRF9160: Added an LTE-M only mode. * Improved connection compatibility with 1NCE SIM. ### System * Improved the obniz Board startup screen. --- ## 7.0.0 2026/3/23 Target OS * obnizOS for Intelligent Edge Kilo ( hw=iekilo1 ) * obnizOS for Intelligent Edge Micro ( hw=iemicro1 ) * obnizOS for obniz BLE/Wi-Fi Gateway Gen 2.0 ( hw=blewifi_gw2 ) * obnizOS for obniz BLE/LTE Gateway (Cat.4) ( hw=blelte_gw2 ) * obnizOS for AK-030 LTE Cat.M1 USB Dongle ( hw=ak030 ) * obnizOS for obniz BLE/Wi-Fi Gateway ( hw=encored ) * obnizOS for IoTBank USB Gateway ( hw=iotbankusbgw ) * obnizOS for M5Stack Basic ( hw=m5stack_basic ) * obnizOS for ESP32 ( hw=esp32w or hw=esp32p ) ### Internet Connection #### Common Changes * **Added Self-hosting feature** (Connection destination setting feature). * **Added Transmission Queue** functionality. * **Added Timestamp** functionality. #### LTE * Added sleep mode support for the **nRF9160 modem**. #### Wi-Fi * **Fix:** Enhanced connection compatibility and security in mixed **WPA2/WPA3** environments. - New support for WPA-PSK - **Fix** Can't connect to no password Wi-Fi #### Ethernet * Added support for **W5500** (WAN side). ### Settings * Added support for **Configuration JSON** via web browser. * Added **Plugin installation** via serial console. * Added support for **Continuous Configuration** via serial console. * Added **Self-diagnosis feature** via serial console. ### Peripherals * **SPI:** Added Shared SPI functionality. * **CAN:** Added CAN peripheral support. * **UART:** Added **DE (Driver Enable)** function (specifically for RS485 transceivers). #### Bluetooth * **Fix:** Addressed vulnerabilities regarding attacks from malicious devices: **CVE-2025-66409 / CVE-2025-68474**. * **Fix:** Corrected **SDP (Service Discovery Protocol)** processing: **CVE-2025-68473**. ### System * Added **Sleep** functionality for every OS. * Added **Plugin Safemode**. * Added **LIS2DH12** component support. * Added **Disable Console** functionality. ### Plugins * Added **Lua Plugin** ( Lua 5.4.7 ) support. **This version supports the following commands:** ```lua -- System Event Handler function on_event(event) if event == "power_on" then elseif event == "setting_mode" then elseif event == "connecting_to_network" then elseif event == "connecting_to_cloud" then elseif event == "online" then end end -- func(int), module(int), data(string(uint8 array)) function on_upstream(func, module, data) if necessary then return 1; elseif rightnow then return 2; elseif mustDrop then cloud.upstreamEnqueue(1, 2, str); -- change to differenct command cloud.upstreamFlush(); -- optional return 0; end end -- received from obnis.js function on_command(command) cloud.pluginSend("123"); end -- called while online every around 1msec function on_online_loop() -- os.log(\"online_loop\"); end -- called while offline every around 1msec -- You should care about communication because this function will be called -- different thread. function on_offline_loop() -- os.log(\"offline_loop\"); end function on_self_check() os.log(" - self check ok"); end function plugin_name() -- will be get by obniz.plugin_name return "my_plugin" end -- Available Functions -- OS os.getTick(); -- system tick in msec os.getUnixTime(); -- get seconds from 1970/1/1. you must adjust time by calling pingWait(); os.log("hello world"); os.wait(1000); -- 1,000msec wait os.reboot(); os.resetOnDisconnect(false); -- It will never reset after disconnection. And queued data never lost when offline. os.sleep(5 * 1000, 0); -- deep sleep + external module sleep. os.sleep(5 * 1000, 1); -- deep sleep + without external module sleep. os.sleep(5 * 1000, 2); -- light sleep + external module sleep. os.sleep(5 * 1000, 3); -- light sleep + without external module os.getVersion(); os.getHW(); -- storage file storage.fileOpen("text.txt") storage.fileWrite("ABC"); storage.fileAppend("abcdefg"); length = storage.fileGetSize(); data = storage.fileRead(0, length); storage.fileClose(); -- storage kvs error = storage.kvsSave({ name = "Yuki", attr = { engineer = true } }) data = storage.kvsLoad(); -- Cloud cloud.connect(); cloud.disconnect(); cloud.upstreamEnqueue(0, 1, data) -- module func data cloud.pluginSend(data); cloud.pluginSendFrameStart(frame_id, length); -- framing cloud.pluginSendFrameEnd(); -- framing cloud.enqueueTimestampByTick(os.getTick()-1000); -- it will enqueue unix timestamp -- io io.retain(1, true); io.output(1, true); local val = io.input(1); -- ad local val = ad.get(1); -- 0.0v~3.3v -- uart uart.start(1, 2, 9600) -- tx:io1 rx:io2 baud:9600 uart.send("hello"); local data = uart.recv() -- uart.recv(1) limit to 1byte max if #data > 1 then os.log(data); -- received end -- spi local err = spi.start(20, 21, 19, 8, 100 * 1000); -- MOSI, MISO, CLK, CS(could be null for non shared SPI), baudrate if err > 0 then os.log("SPI Error: " .. err); return end let result = spi.write(string.char(0x40, 0x00, 0xC0)); -- result must be 3bytes if success. -- wifi wifi.on(); wifi.off(); wifi.sniffStart(callback); wifi.sniffSetChannel(2); wifi.sniffStop(); -- ble ble.on(); ble.off(); ble.scanStart(onFind, { -- default option values active=true, interval=16, window=16, phy1m=true, phyCoded=true, duplicate=true }); ``` ## 6.0.1 2025/12/9 Target OS - obnizOS for obniz BLE/Wi-Fi Gateway Gen 2.0 ( hw=blewifi_gw2 ) - obnizOS for obniz BLE/LTE Gateway (Cat.4) ( hw=blelte_gw2 ) - obnizOS for AK-030 LTE Cat.M1 USB Dongle ( hw=ak030 ) - obnizOS for obniz BLE/Wi-Fi Gateway ( hw=encored ) - obnizOS for IoTBank USB Gateway ( hw=iotbankusbgw ) - obnizOS for M5Stack Basic ( hw=m5stack_basic ) - obnizOS for ESP32 ( hw=esp32w or hw=esp32p ) - obnizOS for obnizPLC ( hw=plc ) ### Internet Connection Common Changes - Fix: Fixed an issue where detecting Wi-Fi / Ethernet disconnection took a long time. - Fix: Fixed an issue where the device would appear offline when using Wi-Fi / Ethernet in on-premise environments. ### Wi-Fi - Fix: Fixed an issue where the Wi-Fi / Ethernet Proxy was not functioning correctly. - Fix: Fixed an issue where AP association might fail when using WPA3 encryption. - Fix: Fixed an issue in configuration mode where connected devices (e.g., smartphones) were not correctly disconnected after a reboot, causing the connection to persist. - Fix: Fixed an issue where the device might unexpectedly reboot when a Wi-Fi error occurs. ### Bluetooth - Fix: Fixed an issue where the unpairing process for bonded devices was not handled correctly under specific conditions. - Fix: Addressed a security vulnerability that occurred when using a fixed local Identity Resolving Key (IRK). - Fix: Fixed an issue where the controller would trigger an error or stop due to a hardware error when switching connection encryption or performing a role switch. - Fix: Fixed an issue where packet acknowledgments (ACKs) were not received in certain situations, causing infinite retransmissions and communication stalls. ## 5.0.1 2024/07/17 Target OS - obnizOS for obniz BLE/Wi-Fi Gateway Gen 2.0 ( hw=blewifi_gw2 ) - obnizOS for obniz BLE/LTE Gateway (Cat.4) ( hw=blelte_gw2 ) - obnizOS for AK-030 LTE Cat.M1 USB Dongle ( hw=ak030 ) - obnizOS for obniz BLE/Wi-Fi Gateway ( hw=encored ) - obnizOS for IoTBank USB Gateway ( hw=iotbankusbgw ) - obnizOS for M5Stack Basic ( hw=m5stack_basic ) - obnizOS for ESP32 ( hw=esp32w or hw=esp32p ) - obnizOS for obnizPLC ( hw=plc ) - obnizOS for ESP32C3 ( hw=esp32c3 ) (when using obniz Now) ### Internet Connection Common Changes - Faster recovery after disconnection from the cloud - On-premises and dedicated cloud connection function (when using obniz Now) #### Wi-Fi - Support for WPA3 - Continuous update of RSSI values viewable in the cloud - Security measures: CVE-2019-9496, CVE-2022-23304, CVE-2022-23303, CVE-2019-9494, CVE-2017-13077, CVE-2017-13078, CVE-2017-13079, CVE-2017-13080, CVE-2017-13081, CVE-2017-13082, CVE-2020-26142, CVE-2023-52160 #### Ethernet - Support for W5500 modem (HTTP/HTTPS) (when using obniz Now) #### 4G/LTE - Standard support for nRF9160 (when using obniz Now) - Improved communication speed for all modems ### Settings - Added mode to prevent automatic transition to setup mode after connection failure (when using obniz Now) - Added full stop function for the serial console (when using obniz Now) ### Peripherals - Improved Bluetooth connection stability ### System - OTA progress can be viewed in the cloud - Fixed issue where OTA would fail if the app was installed ### Hardware - Allowed use of the same SPI line as the display on M5Stack Basic - Ensured cloud connection is possible even when the main switch is faulty and unable to enter the setup screen ## 4.2.1 Available OS - obnizOS for obniz BLE/Wi-Fi Gateway Gen 2.0 ( hw=blewifi_gw2 ) - obnizOS for AK-030 LTE Cat.M1 USB Dongle ( hw=ak030 ) ### On-premise support - Supported the on-premise enviroment. (ex. wifi network is available but can’t connect to obnizCloud.) ### Network connection - Fixed a bug that take a long time to reconnect after online then disconnect from network. ### Network settings related - Corrected text that is displayed browser setting and E-ink display. ### BLE - Fixed a bug that could cause offline for up to 10 min when device is reconnect to obnizCloud - Fixed a bug where reconnecting to obnizCloud would cause error about BLE to occur and then offline for up to 10 min. ### System - Fixed potential minor bugs. ## 4.1.1 2022/11/20 Available OS - obnizOS for obniz BLE/Wi-Fi Gateway Gen 2.0 ( hw=blewifi_gw2 ) - obnizOS for obniz BLE/LTE Gateway(Cat.4) ( hw=blelte_gw2 ) - obnizOS for AK-030 LTE Cat.M1 USB Dongle ( hw=ak030 ) ### BLE - Resolved issue with device freezing when API connection is lost during BLE scan ## 4.1.0 2022/9/28 Available OS - obnizOS for obniz BLE/Wi-Fi Gateway Gen 2.0 ( hw=blewifi_gw2 ) - obnizOS for obniz BLE/LTE Gateway(Cat.4) ( hw=blelte_gw2 ) - obnizOS for AK-030 LTE Cat.M1 USB Dongle ( hw=ak030 ) ### Network settings related - Added the ability to enter setting mode at any time with a long press of the button after startup Long press timeout 7 seconds, long press beyond the timeout will disable the button and go back to the original operation, and re-enable it by releasing the button. (e.g., if you are online, it will return to online) - Support for obniz BLE/LTE Gateway (Cat.4) browser setting screen ### Network Connection (LTE) - Correction of the phenomenon that AK-030 may keep rebooting due to short communication timeout period when connected to LTE. - Correction of communication command format with LTE modem - Modification of request format to cloud when connecting to LTE - Added "Wake up" status to the status before connection - Fixed the phenomenon that AK-030 reboots with communication error in slow communication speed environment after network connection. - Supported SIM setting that does not require id/password ### BLE - Support scan filter for extended advertising and periodic advertising on BLE devices. ### Network settings (CUI settings screen) - Improved usability by presetting hardware settings for each device and omitting settings. ### Network settings (Browser settings) - Improved stability on android and windows - Disabled double operation of connect button to prevent malfunction - Fixed a bug that no-communication timeout did not work when opening the browser settings screen - Extended restart timeout from 20 seconds to 30 seconds when there is more than one network setting ### System - Fixed to enable port listen for local connect only when necessary - Fixed to connect with WiFi set by WPS when WPS succeeds on a device with cellular settings saved. - Fixed crash and restart after 10 minutes of no connection. - Updated no-communication timeout when disconnected from the cloud from 1.5 minutes to 10 minutes ### Known Issues - The device with Wi-Fi MESH settings is not going online ## 4.0.0 2022/08/01 Available OS - obnizOS for obniz BLE/Wi-Fi Gateway Gen 2.0 ( hw=blewifi_gw2 ) ### Network configuration related - Support for obniz BLE/Wi-Fi Gateway Gen 2.0 browser setting screen - When Wi-Fi setting by WPS is failed, it changes to the setting mode. ### BLE - BLE 5.0 support Extended Advertising and Periodic Advertising do not support scan filter ### Added API - Added API to manipulate the display - API to change ping interval between device and cloud added - Added API for acquiring information on the currently connected Wi-Fi - Add API to operate tcp data cache ## obniz BLE/Wi-Fi Gateway Gen 2.0 Details In normal mode, the following items are displayed on the screen - QR code for device registration (used for linking to an account) - SSID of the connected Wi-Fi - Version of obnizOS - Device connection status In setting mode, the following items are displayed on the screen - QR code for device registration (used for linking to account) - Setup procedure via browser ## 3.5.0 2021/07/21 Available OS - obnizOS for obniz Board ( hw=obnizb1 ) - obnizOS for obniz Board 1Y ( hw=obnizb2 ) - obnizOS for obniz BLE/Wi-Fi Gateway ( hw=encored ) - obnizOS for CONNECT HUB Cellular Model ( hw=encored_lte ) - obnizOS for BLE Stick ( hw=ble_stick ) - obnizOS for M5StickC ( hw=m5stickc ) - obnizOS for M5Stack Basic ( hw=m5stack_basic ) - obnizOS for ATOM Lite ( hw=m5atom_lite ) - obnizOS for obnizPLC ( hw=plc ) - obnizOS for ESP32 ( hw=esp32w or hw=esp32p ) ### Internet Connectivity Commonly Changed Points - Network Failover now available for all connectivity. If one tried (ex Wi-Fi) and failed, then next setting will betried (ex cellular) - obnizOS now connect to obniz.com not obniz.io initiallly. #### Wi-Fi - WPA2 Enterprise Support (Only username, pass, anonymous id authentication) - BSSID option now available to fix Wi-Fi AP connect to. - Startup Wi-Fi scan nerver performed when no Wi-Fi Setting Found - Stop reducing Wi-Fi tx power when reboot after BOR. - Fix Wi-Fi connection tried from old setting. now tried from latest one. #### Wi-Fi MESH - Newly Supported Wi-Fi MESH Obniz device now create MESH network automatically to connect to the internet even if some devices can't reach to an access point. This feature require subscribing Wi-Fi MESH plan on obnizCloud. #### Cellular - Starting BG96 Modem Standard Support - Starting AK030 Modem Standard Support - SARA_U2 Experimental Implementation ### Setting #### Setting via Serial - Typing `menu` let you enter setting mode anytime. - Now support devices which wired ESP32 console Rx and Tx. - Drop supporting typing `s` to enter setting mode on startup. - Drop supporting deleting each network setting. only all delete available. - Drop supporting hardware wiring information setting as CLI. - Now accept raw setting from serial #### Setting via Wi-Fi - Passkey is now required (default `obniz`). - Captive Portal Support. you see the browser automatically when you connect to your obniz device. - The IP of the device has been changed from 192.168.0.1 to 192.168.254.1. - Startup setting (pressing button on startup) and Wi-Fi configration now merged. You can choose from menu on browser. - Drop supporting deleting each network setting. only all delete available. - Drop supporting hardware wiring information setting. - Wi-Fi and Cellular configration now let you see progress and failing results on your screen. and you can retry when failed without rebooting device. - All network configration saves your configration at first regardless success or not. - Connection timeout is longer (2 minutes) when your device has no network configration compared from others (20 seconds) - Wi-Fi now scans everytime user open/reload the Wi-Fi setting page. - MacAddress and MESH ID are now checked for input - The password field is now hidden by the password attribute. - No longer restarts when deleting settings #### Settings via display - Network settings deletion is now a function to delete all network settings, not just Wi-Fi. #### etc - Factory Reset has been removed. - WPS Mode supported. Hold pressing over 3 time while setting mode. The device will enter WPS mode. If succeed, the device save Wi-Fi setting and restart. - Now can accept setting from obniz's Android app - Circuit information can be configured ### System - Startup time faster around 1.5 seconds compared from before. ### Hardware - Dynamic circuit setting now available. You can let your device know and use below components - Seithces - LEDs (power or status) - Ethernet PHY - 3G/LTE Modem When you configured, then obnizOS will recognize and use it. ### Peripheral #### speakers - fix In M5Stack, the speaker IO is now free from being occupied by obnizOS. #### BLE - Internal memory management improved. Better stability for heavy usage while scanning. ## 3.4.5 2021/02/26 Available OS - obnizOS for obniz Board ( hw=obnizb1 ) - obnizOS for obniz Board 1Y ( hw=obnizb2 ) - obnizOS for obniz BLE/Wi-Fi Gateway ( hw=encored ) - obnizOS for CONNECT HUB Cellular Model ( hw=encored_lte ) - obnizOS for BLE Stick ( hw=ble_stick ) - obnizOS for M5StickC ( hw=m5stickc ) - obnizOS for M5Stack Basic ( hw=m5stack_basic ) - obnizOS for ATOM Lite ( hw=m5atom_lite ) - obnizOS for ESP32 ( hw=esp32w or hw=esp32p ) ### Wi-Fi - fix Wi-Fiスッキャンで14chが対象だったのを追加 - Wi-Fi接続成功率の向上 ### BLE - Improve Wi-Fiが弱い環境でのBLEスキャンにおけるクラッシュ率の改善 ### System - Factory Resetによる内部メモリのクリーンアップ - Factory Reset が次のhwで利用可能となります hw=encored, encored_lte - 起動時オプション用のボタンを起動時長押しすることで(10sec以上) FactoryResetの実施 for hw=encored, encored_lte, ble_stick, atom_lite ### Peripheral - 起動時オプション用のボタンが obniz.switch として利用可能に、またクラウド実行のきっかけとして利用可能。対象hw=encored, encored_lte, ble_stick, atom_lite ## 3.4.4 2021/01/24 Available OS - obnizOS for obniz Board ( hw=obnizb1 ) - obnizOS for obniz Board 1Y ( hw=obnizb2 ) - obnizOS for obniz BLE/Wi-Fi Gateway ( hw=encored ) - obnizOS for CONNECT HUB Cellular Model ( hw=encored_lte ) - obnizOS for BLE Stick ( hw=ble_stick ) - obnizOS for M5StickC ( hw=m5stickc ) - obnizOS for M5Stack Basic ( hw=m5stack_basic ) - obnizOS for ATOM Lite ( hw=m5atom_lite ) - obnizOS for ESP32 ( hw=esp32w or hw=esp32p ) ### Wi-Fi **Improves** - Improve reconnection time after disconnection when Wi-Fi Access point was missed at scanned time. - Improve hang monitoring more fast detection. - Improve stop rebooting when Wi-Fi lost. ### Network **Bug Fixes** - Fix Failed to connect static IP on some cases. ### BLE **Bug Fixes** - Fix Crash occures when under heavy communication. ## 3.4.3 2020/11/20 Available OS - obnizOS for obniz Board ( hw=obnizb1 ) - obnizOS for obniz Board 1Y ( hw=obnizb2 ) - obnizOS for obniz BLE/Wi-Fi Gateway ( hw=encored ) - obnizOS for CONNECT HUB Cellular Model ( hw=encored_lte ) - obnizOS for BLE Stick ( hw=ble_stick ) - obnizOS for M5StickC ( hw=m5stickc ) - obnizOS for M5Stack Basic ( hw=m5stack_basic ) - obnizOS for ATOM Lite ( hw=m5atom_lite ) - obnizOS for ESP32 ( hw=esp32w or hw=esp32p ) ### Hardwares **New OS for Hardwares** - obnizOS for CONNECT HUB Cellular Model - obnizOS for BLE Stick - obnizOS for ATOM Lite ### Wi-Fi **Improves** - Connection success rate. - Change Connection LED Status for representing more accurate state. - Security fix: Fixed AP switch to adjacent channel without disconnect (CVE-2020-12638) - Reduce time until wifi setting when some SSID/Passwords stored in a device. - Hide showing connection error while first trying. - Store SSID/Password from Setting via Browser when SSID specified. **Bug Fixes** - Fix Setting via Browser never accept SSID and password space character. - Fix Status LED suddenly stop(red or blank) when connected sation removed from obniz Wi-Fi. - Fix reboot when no SSID found ### BLE **Improves** - Improve Communication Speed. **Bug Fixes** - Fix Crash occures when under heavy communication. ### Cloud **Bug Fixes** - Fix Fails authentication rarely. ### Peripheral **Improves** - block spi1 use for M5StickC/ATOM Lite ## 3.4.2 2020/09/01 Available OS - obnizOS for obniz Board - obnizOS for obniz Board 1Y - obnizOS for obniz BLE/Wi-Fi Gateway - obnizOS for M5StickC - obnizOS for M5Stack Basic - obnizOS for ESP32 #### Improves. - obniz BLE/Wi-Fi Gateway status LED color change - At OTA Red blinking → Blue fast blinking - At the time of web setting: Green blinking → Purple blinking - Heat reduction function was set again. It works more when not using bluetooth. - Wi-Fi, Ethernet Mac Address reporting **Wi-Fi** - Wi-Fi Connection strategy was changed. - Hidden SSID setting was removed. All Wi-Fi treat as hidden Wi-Fi. #### Bug Fixes. - Fix Invalid LED(RED Keeps) for obniz BLE/Wi-Fi Gateway. - Fixed a bug in the plugin command transmission function. - plugin onlineFlg bug fixed. ## 3.4.1 2020/08/18 Available OS - obnizOS for obniz BLE/Wi-Fi Gateway "obnizOS for obniz BLE/Wi-Fi Gateway" below 3.4.1 will be automatically OTA to 3.4.1. #### Improves - Changed Wi-Fi connection method. (hidden SSID setting is removed) #### Bug Fixes - Resolves an issue where the OS would not boot on Gateway under certain conditions. ## 3.4.0 Available OS - Plugin OS 2020/07/22 #### Added - Plug-in Functionality #### Bug Fixes. - Improved Wi-Fi connection stability - M5Stack Display Reversal Support - Improved ADC accuracy - Correcting a typo in the settings screen. ## 3.3.0 2020/07/01 #### Added - Wi-Fi Access Point Information can see on obniz Cloud. #### Bug Fixes - Wi-Fi stability improvement - BLE scan device side filtering fails sometime. - obniz Board 1Y password typing timeout so early. ## 3.2.1 2020/5/28 Network - Update TLS certification ## 3.2.0 2020/03/16 - obnizOS for obniz Board - obnizOS for obniz Board 1Y - obnizOS for obniz BLE/Wi-Fi Gateway - obnizOS for ESP32 **Display** ADD: Color display Support for obniz.display command. This is only for future devices. **BLE** ADD: BLE scan target filter on device side to reduce data transfer   Fix: Sometimes stop ble module on ble first initialize. **Wi-Fi** ADD: Hidden SSID setting and connectivity ADD: Device Setting Mode for obniz BLE/Wi-Fi Gateway ADD: LED show device status for obniz BLE/Wi-Fi Gateway   Fix: Cannot input symbol on Wi-Fi password when using advance mode.   Fix: Unstable communication with obniz cloud at TLS/SSL.   Fix: Unstable behavior when using local connect. ## 3.1.0 2020/01/16 - obnizOS for obniz Board - obnizOS for obniz Board 1Y - obnizOS for obniz BLE/Wi-Fi Gateway - obnizOS for ESP32 #### Added - HTTP/HTTPS Proxy setting via softAP Wi-Fi configration - TLS communication for business plan #### Improves - Add Back slash for text inputs on obnizOS first setup. - Changed softAP Wi-Fi setting ip address from 1.2.3.4 to 192.168.0.1 - Add one more system halt handler to keep obnizOS connected to the Cloud. #### Bug Fixes - fix Too much delay or timeout of 1.2.3.4 access on softAP Wi-Fi setting(this happen only for obnizOS for ESP32 or Encored IoT Hub) - fix unstable behavior when local connect enabled. - fix unstable behavior after wait() called. ## 3.0.2 - obnizOS for obniz Board - obnizOS for obniz Board 1Y - obnizOS for obniz BLE/Wi-Fi Gateway - obnizOS for ESP32 #### Breaking Changes - Old Ble commands from obniz.js(1.X.X and 2.X.X)/python(0.5.1 and early) can’t be accepted. - Websocket/REST API now only accept HCI BLE commands for obnizOS3 series #### Added - add Hardware Support: obniz Board 1Y/ Encored IoT Hub - add Sleep function for obniz Board 1Y - add Bluetooth HCI command #### Improvements - change first setup display UI for obniz Board series. - change error UI more readable. - change Minimum Network Latency from 10msec to 1msec when local connect enabled. It makes better - performance for robot controlling. #### Bug Fix - fix obnizOS disconnect from obniz cloud when wait() called with over 30min. ## 2.1.1 - obnizOS for ESP32 ### Improvements - BLE connection ## 2.1.0 - obnizOS for obniz Board - obnizOS for ESP32 #### Added - Ethernet Mode - Works with ESP32-PICO-D4 - Wi-Fi Configration via Wi-Fi. - Static IP - TCP Command - Reset setting from serial #### Improvements - I2C Clock Stretching accept more longer time. #### Bug Fix - Cloud connection to obniz cloud fails in some case. ## 2.0.2 - obnizOS for ESP32 ### BugFix - change i2c clock stretch time to longer - Fix GPIO32-39 input data ## 2.0.1 - obnizOS for obniz Board #### Fixed - fixed reboot or hang when network state is going invalid - fixed invalid treatment for continuers websocket frame. ## 2.0.0 - obnizOS for obniz Board #### Added - io.animation now accept repeat and finished notification. #### Changed - ad result is more accurate and voltage correction only works vcc under 4.5v ## 1.0.13 - obnizOS for obniz Board ## 1.0.12 - obnizOS for obniz Board #### Fixed - BLE peripheral connection failed ## 1.0.11 - obnizOS for obniz Board #### Fixed - UART RTS, CTS not worked ## 1.0.10 - obnizOS for obniz Board #### Fixed - Fix BLE connection error ## 1.0.9 - obnizOS for obniz Board #### Fixed - UART/SPI/I2C/PWM stability improvement on huge data - BLE connection error during scan ## 1.0.8 - obnizOS for obniz Board #### Added - Display firmware version and mac address ## 1.0.7 - obnizOS for obniz Board #### Fixed - Lost error messages from obniz when after special sequences ## 1.0.6 - obnizOS for obniz Board ### Added - Show cloud connection fail reasons on OLED. #### Fixed - crash when two or more io.animation registrated - Wifi/Bluetooth Stability fix and Improvements ## 1.0.5 - obnizOS for obniz Board #### Fix - fix shutdown bug when ble read/write unknown characteristics/descriptor ## 1.0.4 - obnizOS for obniz Board ### Changed - Better noise treatment of switching 5v/3v on each IO. #### Fix - Few Wi-Fi Bugs ## 1.0.3 - obnizOS for obniz Board #### Add - SPI write max length expands. 32 byte to 1024 bytes ## 1.0.2 - obnizOS for obniz Board #### Fix - Wifi Password can't select some characters like '@' ## 1.0.1 - obnizOS for obniz Board #### Fix - Wifi Password can't select 'X' ## v1.0.0 First Release --- ## obniz BLE/Wi-Fi Gateway Gen2.0 URL: https://obniz.com/reference/obniz-ble-wi-fi-gateway-gen2 ## Overveiw obniz BLE/Wi-Fi Gateway Gen2.0 is a repeater (gateway) that is installed in an indoor 100V outlet to receive Bluetooth signals and transmit information via Wi-Fi signals. Various IoT services can be easily started by combining the gateway with sensors that detect various conditions such as movement of people and objects, temperature, brightness, humidity, and CO2 concentration. ![](images/overview.png) The main unit has a display, touch buttons, and status LEDs. For details, please refer to the [product specifications](spec). ![](images/description.png) ## Caution **This product conforms to the Bluetooth standard defined by the Bluetooth SIG and has been certified. However, it does not guarantee Bluetooth connectivity with all Bluetooth devices.** - The Bluetooth device to be connected must conform to the Bluetooth standard defined by the Bluetooth SIG and be certified. - Even if the device to be connected conforms to the above Bluetooth standard, it may not be possible to connect or the operation method may differ depending on the timing of acquisition, characteristics, or specifications of the device. If you wish to use any of the BLE devices from other manufacturers introduced on the obniz official website, you do so at your own risk, and you should thoroughly review and test them prior to use. obniz Inc. makes no warranty to you regarding the suitability of such devices for any particular purpose, their reliability and accuracy, or any results obtained when used with the products themselves or in combination with obniz products. --- ## Internet Connection Setting URL: https://obniz.com/reference/obniz-ble-wi-fi-gateway-gen2/quick-start The gateway's Wi-Fi settings can be configured either by connecting from a terminal such as a smartphone or PC, or by connecting via WPS. ## Method1:Connection using PC or smartphone Requirements: Smartphone or PC that can be connected to internet Wi-Fi (SSID, password) *2.4GHz band ### (1) Power ON the gateway The obniz BLE gateway can be turned ON by inserting the device in the consent. When the LED turns green, **press and hold the side touch button**. The LED then turns purple and it starts normally and is waiting for the settings. ![](images/doc_qs01.png) ### (2) Wi-Fi Settings / Cloud (Internet) Settings **Check whether the LED is blinking purple and proceed as follows:** See more about settings at [ obnizOS Browser Setting ](/reference/obnizos-for-esp32/settings/setting-via-browser). 1. Connect to the Wi-Fi of the gateway When the LED is blinking purple, it is possible to connect to the Wi-Fi of the gateway. Use a smartphone or a PC to connect to the Wi-Fi named obniz-XXXXXXXX (8 digits obnizID). 2. Login to the Settings screen When connected to the Wi-Fi of the gateway, a pop-up browser window appears displaying a login page. *The first time login passkey is “obniz”. 3. Wi-Fi Settings After logging in, ‘Wi-Fi Settings’ page gets displayed. Enter the SSID and password of the Wi-Fi you wish to connect to. 4. Click on the “Connect” button Press “Connect” to save the network credentials and to start the connection. *The network connection status is displayed below the “Connect” button. On successful completion of the connection, “Online” is displayed. The connection status is also reflected by the LED and is displayed on the display of the gateway. The behavior of the settings screen may differ depending on the browser specifications. For Andoroid users ### (3)Network Settings Completion You have successfully connected to the cloud if **the LED turns blue** and obnizID, SSID and OS ver. are displayed on the gateway display. ## Method1:Setting by WPS Using WPS, the device can automatically receive SSID and Password from the access point (Wi-Fi router). ### Requirements: - Router that supports WPS (2.4GHz band) Flow: 1. Set the device to the purple flashing setting mode. 2. Press the WPS button on your Wi-Fi router or access point to complete the Wi-Fi setup. 3. press and hold the button for 3 seconds. The purple light will blink faster. 4. SSID and Password are automatically set and Wi-Fi setup is complete. 5. the device will reboot once completed, and the blue light will turn on when it connects to Wi-Fi and comes online successfully ## Other Method - [Using the "obniz Device Setting App" smartphone application to set up the device by holding up the smartphone ](/reference/cloud/facility/) *facility/operation function is required - [Batch configuration of peripheral gateways using the CLI application "obniz-cli"](/reference/obnizos-for-esp32/settings/setting-via-obniz-cli) Please refer to [Settings](/reference/obnizos-for-esp32/settings) for available settings in obnizOS. --- ## Device Registration URL: https://obniz.com/reference/obniz-ble-wi-fi-gateway-gen2/registration Use QR code on your device to registe. See [Registration](/reference/cloud/device-management/registration). --- ## BLE Connection Testing Tool URL: https://obniz.com/reference/obniz-ble-wi-fi-gateway-gen2/testtool ## How to use We provide a tool to check if Bluetooth and the gateway can connect. Before adopting a gateway, customers should verify that it can connect and communicate with the sensors and devices they plan to use. [obniz BLE Connection Validation Tool](https://obniz.com/webapp/wa_MTM3NzQ=/run) [How to use(PDF)](images/BLE-connection-testing-tool.pdf) [List of tested devices](https://obniz.com/ja/sdk/parts) ## Caution **This product conforms to the Bluetooth standard defined by the Bluetooth SIG and has been certified. However, it does not guarantee Bluetooth connectivity with all Bluetooth devices.** - The Bluetooth device to be connected must conform to the Bluetooth standard defined by the Bluetooth SIG and be certified. - Even if the device to be connected conforms to the above Bluetooth standard, it may not be possible to connect or the operation method may differ depending on the timing of acquisition, characteristics, or specifications of the device. If you wish to use any of the BLE devices from other manufacturers introduced on the obniz official website, you do so at your own risk, and you should thoroughly review and test them prior to use. obniz Inc. makes no warranty to you regarding the suitability of such devices for any particular purpose, their reliability and accuracy, or any results obtained when used with the products themselves or in combination with obniz products. --- ## Troubleshooting URL: https://obniz.com/reference/obniz-ble-wi-fi-gateway-gen2/troubleshooting - [困った時は](#Troubleshoot) - [Checking the access point and network environment](#APEnvCheck) - [ステータスLED一覧](#LEDStatus) - [Wi-Fi設定のリセット](#ResetWi-Fi) - [OSのバージョン確認方法](#CheckOS) 困った時は 現象| 方法 ---|--- Device failed to turn ON | Please try the following in order.① Unplug and plug from the outlet which will turn the power off and then on again② Try with another outlet obniz’s Wi-Fi SSID is not getting discovered in the scan list on smartphone or PC | Make sure that the gateway is in the settings mode.With the gateway plugged into the outlet, press and hold the touch button on the side (left) for 3 seconds, the LED will blink purple. Release the button and the device will enter the "setting standby state". At this time, Wi-Fi is output from the gateway. The login page does not open automatically even when connected to the Wi-Fi output by the gateway. | If there is no automatic transition to the login page, please access http://192.168.254.1/ (while connected to the Wi-Fi output by GW).If you still cannot access the login screen, please contact us. Failure in connecting to Wi-Fi (LED keeps blinking green and doesn't proceed) | If there is no Wi-Fi available in the surroundings that can be connected to, it will blink or light up in green repeatedly.Please check the following. Please check below also [https://support.obniz.com/hc/ja/articles/50510218693785-Wi-Fi%E6%8E%A5%E7%B6%9A%E3%82%A8%E3%83%A9%E3%83%BC%E3%81%AE%E7%90%86%E7%94%B1%E3%81%A8%E5%AF%BE%E7%AD%96%E3%82%92%E6%95%99%E3%81%88%E3%81%A6%E4%B8%8B%E3%81%95%E3%81%84](https://support.obniz.com/hc/ja/articles/50510218693785-Wi-Fi%E6%8E%A5%E7%B6%9A%E3%82%A8%E3%83%A9%E3%83%BC%E3%81%AE%E7%90%86%E7%94%B1%E3%81%A8%E5%AF%BE%E7%AD%96%E3%82%92%E6%95%99%E3%81%88%E3%81%A6%E4%B8%8B%E3%81%95%E3%81%84) - Gateway can connect to Wi-Fi in only 2.4 GHz band (cannot connect to 5GHz) If it does not improve, delete (reset) the gateway network settings and try the settings again from the beginning. “Failed:No Wi-Fi Found(201)” or ”Failed:(0)” error is displayed | The following reasons are possible.・ Stealth SSID (14ch only in Japan) → Try changing "country setting"・ 5GHz band Wi-Fi → Please prepare 2.4Ghz band Wi-Fi Resetting the Wi-Fi credentials on the device | Please refer the following.[ゲートウェイのWi-Fi設定をリセットしたい](https://support.obniz.com/hc/ja/articles/4411279484441-BLEゲートウェイのWi-Fiをリセットしたい) Checking the access point and network environment When the gateway cannot connect to Wi-Fi, or when the connection is unstable, there are things you can review not only on the gateway but also on the access point (Wi-Fi router) and the network environment. Please check the following in order. Frequency band and channel The gateway can connect only to the 2.4 GHz band (IEEE 802.11b/g/n). It cannot connect to the 5 GHz band. If you use a setting that broadcasts both 2.4 GHz and 5 GHz under a single SSID (band steering), please prepare a separate SSID dedicated to 2.4 GHz. The gateway may be steered to the 5 GHz side and fail to connect. The channel bandwidth is 20 MHz. Specifying 40 MHz or wider has no effect. Signal strength and interference Please move the gateway closer to the access point. A radius of about 15 m is a rough guide. Walls, metal, concrete, and water tanks weaken the signal. Microwave ovens, Bluetooth devices, and other 2.4 GHz radios cause interference. Please change to a less congested channel. If several access points with the same SSID (such as mesh repeaters) are nearby, the connection target may switch frequently and become unstable. Please adjust the placement of the units and repeaters. Authentication and security settings We recommend WPA3 as the authentication method. With a WPA2/WPA3 mixed mode, the access point may take time to establish a connection. Networks that require a web login (captive portal) are not supported. You may not be able to connect on Wi-Fi at hotels, public facilities, or guest networks. If MAC address filtering is enabled, please register the gateway's MAC address in the allow list. Settings that block device-to-device communication (privacy separator, AP isolation) may interfere with connecting to the gateway from a browser during initial setup. Please disable them temporarily while configuring. Path to the internet The gateway communicates outbound toward the obniz cloud (HTTPS / TLS 1.2). Because communication is initiated only from the device side, port opening and port forwarding are not required. If your firewall restricts outbound communication, please allow communication to the destination domains obniz.io and *.obniz.io. The destination IP address is not fixed. In an environment that goes through a proxy, please set the proxy information (HTTP or HTTPS) during initial setup. If you specify a DNS server, only one entry can be registered. Without name resolution, the gateway cannot connect to the cloud. For details, please see the FAQ (About the network). IP address assignment (DHCP) If the number of connected devices has reached the limit, or the addresses that DHCP can hand out are exhausted, the gateway cannot obtain an IP address and cannot connect. Please widen the DHCP address range, or disconnect devices you are not using. If you want a fixed address, you can set a static IP during initial setup. If it is still unstable Please restart the access point. A temporary problem may be resolved. Please update the access point's firmware to the latest version. If a power-saving mode (such as an eco setting) is enabled, please disable it and try again. It can cause the connection to drop intermittently. LED Status LED Status List The status of the network connection can be checked by the lighting of the LED status lamps on the main unit. LED state/color Status Things to do and possible solutions Steady Green State immediately after startup Blinking Green Wi-Fi scan/ connection state The available Wi-Fi is being scanned (or connected). It will automatically change to one of the following statuses. ・ Purple (blinking): Wi-Fi setting standby state ・Blue (blinking): Successful connection to Wi-Fi. Connecting to the cloud. ・Red (steady): Error when connecting to the cloud (Please check the items that are mentioned for the steady read state) If there is no Wi-Fi that can be connected to, the LED status will be blinking / steady green. Please check the availability of Wi-Fi and the specifications of Wi-Fi. Steady Blue Connection complete Device successfully connected to the obniz cloud (setting completed) Blinking Blue Connecting to the cloud The connection to the Wi-Fi is successful and the device is connected to the cloud (Internet). Blinking Purple Waiting for user settings The gateway is outputting Wi-Fi and waiting for user operation. By connecting to the Wi-Fi provided by the gateway from a terminal such as a PC or smartphone, the Wi-Fi credentials can be set or reset. Blinking Purple(Fast Flashing) WPS mode In the normal flashing purple state, long press the touch button (for more than 3 secs) to enter WPS mode (the gateway is waiting for the access point's WPS).Press the WPS button on the access point such as a Wi-Fi router to complete the setting. Steady Red Connection to Wi-Fi completed, cannot connect to cloud It is in a state where some kind of error has occurred. Please try the following in order. ・ Turn the power off and then on again ・Reset the network settings and re-enter the network credentials ・ Reconfigure the settings after a while Blinking Blue(Fast Flashing) Update obnizOS If obnizOS update is in progress, it will restart and return to green (blinking) after completion. LED OFF Device not turned ON Check the power supply outlet.Unplug the device and connect a different device to the same outlet to check the outlet. Wi-Fi reconfiguration If you don’t have any Wi-Fi information or can’t connect to Wi-Fi, you’ll need to set it up again. You will need to reconfigure your Wi-Fi, especially in the following cases: My Wi-Fi password has changed. I want to register an additional Wi-Fi connection that is not currently connected. If you want to set up your new Wi-Fi information, here’s how you can do it Re-configure in a place without connected Wi-Fi button to clear all Wi-Fi settings from device setting mode. How to check OS version The OS version is normally displayed on the unit's display. If you press and hold the button for a few seconds, you will be able to check the information and set the device (purple (flashing)). Again, you can connect with a smartphone or other device to clear the Wi-Fi settings, etc. Learn more --- ## FAQ URL: https://obniz.com/reference/obniz-ble-wi-fi-gateway-gen2/faq ## About Wi-Fi ### How to set up Wi-Fi By turning on the gateway, the unit becomes a Wi-Fi access point. By connecting to it, you can configure the settings from your browser.See [Quick Start](./quick-start) for instructions on how to set it up. ### About Wi-Fi and networks you can connect to See Belows [Wi-Fi](/reference/obnizos-for-esp32/wi-fi/) [Protocol](/reference/obnizos-for-esp32/protocol/) ### I want to set up a firewall.Please tell me the domain and IP of the connection destination. The IP is not fixed. The domain will be obniz.io or *.obniz.io. However, the content is encrypted because it is TLS communication. ### When you talk about remote control of devices, do you need to drill holes in the firewall of the router? No, it does not. Since the device connects to the server, you don't need to configure any port forwarding or other settings on your firewall. ### Can I set up multiple Wi-Fi access points? Yes. The maximum number is 5, but it may be less depending on the remaining memory. ### Can Wi-Fi be RESET? Yes. You can initialize it by pressing the button after power-on to invoke the startup option. See [Quick Start](/reference/obniz-ble-wi-fi-gateway/quick-start#troubleShooting) for reset instructions. ### How can I check the status of my Wi-Fi connection? This can be confirmed by the LED on the gateway itself. See [Quick Start](/reference/obniz-ble-wi-fi-gateway/quick-start) for details. ## About Bluetooth ### How many units can be connected? The maximum number of simultaneous connections is seven. ### Can a gateway be a peripheral? The gateway is a peripheral and can send advertisements and accept connections. ### Can a gateway connect and scan at the same time? It is possible. However, you need to temporarily stop the scan only when the first connection is being processed. Once completed, they can be used simultaneously. ### Is it possible to connect only to devices that support it? We are not limited. The supported devices listed on the website mean that we have developed and provided libraries with SDKs, etc., or that we have confirmed the connection. Other devices can also be used by writing a BLE program. ### Can I set up a filter for advertisement? Yes, the following two types are available: - Programmatic filters (any filter can be created by specifying details such as RSSI, once per minute, etc.) - Device side filters (can reduce communication volume, UUID specification, pattern matching, etc. can be used) ## About the Program ### What languages are available? The SDK we provide is for JavaScript. For other languages, you can use the Websocket API. ### I have a system that we are currently using. Does it need to be modified? You can use our gateway without changing your existing system. If you are currently using a different gateway and have an API to accept, you can use obniz without changing the existing system by creating a server software that operates obniz and hits the existing API. In this case, unlike updating the firmware, you only need to update the server software, which makes operation easier. ## About Security ### Is there a default user or password for SSH? There is no function to connect to the device via SSH. ### If the device is stolen, will the software you developed be stolen? No software is compromised. With obniz's firmwareless technology, the device will not carry your code. ### If my paired obniz is stolen, will they take my pairing key? The pairing key will not be compromised. With obniz's firmware-less technology, nothing is recorded on the device itself, so it cannot be leaked. ### Can anyone connect if they know their obniz ID? Access can be restricted by issuing an access token. An access token can be issued by registering the device to your account. In this case, you will not be able to connect unless you have an access token. ## About Delivery ### What is the delivery format? Tray supply in bulk or individual packaging can be selected. ### Can you link the device to my account in advance? Yes, we can. You can apply for the option. ### I would like to know the Mac address in advance. Can you send it with me? Yes, we can. You can apply for the option. ### Where can I purchase gateways? Our e-commerce site and trading companies also handle this product, so please inquire. For product details and contact information, please see the [Gateway product page](https://obniz.com/products/ble-gateway). --- ## Spec URL: https://obniz.com/reference/obniz-ble-wi-fi-gateway-gen2/spec ## Hardware 項目| 値 ---|--- サイズ | 75mm×48mm×20mm プラグ部除く 重量 | 55g 電源 | AC100V〜240V 50/60Hz 動作環境 | 温度:-10℃〜45℃、湿度〜95% 消費電流 | 最大0.3A 主な素材 | ポリカーボネート(耐火レベルV0) Bluetooth | Bluetooth 5.0 LE Wi-Fi | IEEE 802.11b/g/n (2.4 GHzのみ) ([接続可能なWi-Fi詳細](../obnizos-for-esp32/wi-fi/)) 同時接続数 | 7台(状況により異なります) 付属コンポーネント | ・ディスプレイ(電子ペーパー) ・ボタン(静電容量) ・フルカラーLED(オンライン状態などを示すステータスLED)・赤外線LED 製造 | 株式会社obniz ### 外観 ![](images/drawing-overview.png) ![](images/drawing.png) ## 各種認証 ### 通信認証(Wi-Fi/Bluetooth) 項目| 値 ---|--- TELEC | R 201-210888 FCC | 2A57O-OBNIZ027 ##### FCC This device complies with part 15 of the FCC Rules. Operation is subject to thefollowing two conditions: (1) This device maynot cause harmful interference, and (2) this device must accept any interference received,including interference that may cause unde-sired operation. Changes or modifications to this product not authorized by obniz Inc. could void your authority to use the Product under FCC rules. ### Other Certifications 項目| 値 ---|--- PSE | 丸型 --- ## Internet Connection Setting URL: https://obniz.com/reference/obniz-ble-wi-fi-gateway/quick-start This is a quick start for OS version 3.5.0 or later. Click here for Quick Start for version 3.4.5 and earlier. Turn on the power Power is turned on by connecting the obniz BLE Gateway to a power supply (outlet).When the LED is blinking Green, it is ready to be set.Connect to the Wi-Fi (SSID) output by the Gateway from a PC or tablet. LED status on startup LED status Color Operating State Things to do Purple (blinking) Standby for options at startup Immediately after startup (Green light on), press and hold the button to enter the startup option standby state. You can check the OS version and Mac address of the device. Other than that, you can also delete Wi-Fi settings.Learn more LED does not turn on No power on Check the power supply. To confirm, unplug the device and connect a different device to the same outlet to make sure that the device works. Then we recommend you to plug in the obniz BLE again. LED Display and operating status Wi-Fi Settings You can configure in following way. - Connect to the Wi-Fi provided by the gateway with a smartphone, etc., and set up from a browser. - [Setting by WPS](/reference/obnizos-for-esp32/settings/wps) - [Using the "obniz Device Setting App" smartphone application to set up the device by holding up the smartphone (facility/operation function is required)](/reference/cloud/facility/) - [Batch configuration of peripheral gateways using the CLI application "obniz-cli"](/reference/obnizos-for-esp32/settings/setting-via-obniz-cli) Please refer to [Settings](/reference/obnizos-for-esp32/settings) for available settings in obnizOS. Here is how to configure the settings from a browser that can be used without prior preparation. Procedure for setting up Wi-Fi(Case for Browser setting) When you connect to Wi-Fi for the first time, the gateway will be in the standby state (LED blinking Purple) for Wi-Fi setting. Please follow steps 1-3 of the Wi-Fi setup procedure below to proceed with the setup. If there is a memorized Wi-Fi (SSID), the LED will blink Blue. In this case, you do not need to perform steps 1 to 3 below. LED status when connected to Wi-Fi / Cloud LED status Color Operating State Things to do  Purple (blink)→Green (blink) Wi-Fi connection error You may have made a mistake in your Wi-Fi connection settings. You may need to reset the settings and reconfigure them if necessary.In some cases, please reset the settings. This will resolve after a period of time (about 4 seconds) and then the device will reboot and turn green.  Blue (blink)→Red (light) Cloud connection error Review your network settings. Inadequate proxy settings Restrict access to the network If the above does not solve the problem, please check the following in the cloud. Device is "Inactive" => Change to "Active" Plan Expiration (Disable payment settings) Red (light) Cloud maintenance - For safety reasons, the system will automatically restart after 1 minute of inactivity or 15 minutes of inactivity while not connected to obniz Cloud. LED Display and operating status #### 1. Connect to the BLE gateway Wi-Fi If you are unable to connect to Wi-Fi after purchase, the BLE gateway will flash purple and output Wi-Fi. Connect to the Wi-Fi output by the gateway from your PC, smartphone, or other device. After a short wait, the browser will automatically start up and the login screen will appear. The initial passkey (password) is "obniz". If it does not appear automatically, the cause may be one of the following: - OS version less than 3.5.0 : Try opening the URL [http://192.168.0.1/](http://192.168.0.1/) in your browser and see [here](/reference/obniz-ble-wi-fi-gateway/quick-start/until345) for how to set it up. - The latest OS but it doesn't work : Try opening the URL [http://192.168.254.1/](http://192.168.254.1/) in your browser If it is not new and you cannot login with "obniz", please contact obniz company. ![](../images/softap_login.png) #### 2. Wi-Fi Settings After logging in, you will be taken to the Wi-Fi settings screen. You can select the Wi-Fi that has been scanned in the vicinity. The following settings are also available. For more details, please see [Settings via browser](/reference/obnizos-for-esp32/settings/setting-via-browser). - Stealth SSID - Specify BSSID - Static IP - Proxy - WPA2 Enterprise Username/Password Pressing "Connect" will immediately save the settings and start the connection. The connection status will always be displayed under the button, if successful, "Online" will be displayed and the system will restart once. If it fails, the error message will be displayed in red text. ![](../images/viabrowser.png) The behavior of the settings screen may differ depending on the browser specifications. [For Andoroid users](https://support.obniz.com/hc/ja/articles/9765471641113-%E3%83%8D%E3%83%83%E3%83%88%E3%83%AF%E3%83%BC%E3%82%AF%E8%A8%AD%E5%AE%9A%E7%94%BB%E9%9D%A2%E3%81%A7connect%E5%AE%9F%E8%A1%8C%E5%BE%8C-%E8%A8%AD%E5%AE%9A%E3%81%AE%E7%B5%90%E6%9E%9C%E3%82%92%E7%A2%BA%E8%AA%8D%E3%81%99%E3%82%8B%E5%89%8D%E3%81%AB%E3%83%96%E3%83%A9%E3%82%A6%E3%82%B6%E3%81%8C%E9%96%89%E3%81%98%E3%82%8B-Android%E3%81%A7%E9%96%8B%E3%81%84%E3%81%9F%E5%A0%B4%E5%90%88-) Setup Complete The LED lights up Blue when a constant connection to the cloud is established. If the connection fails, please try again to enter or set the SSID or password. LED Display and operating status LED Display The LED will change depending on the network connection status and other operating conditions. LED status Color (on/blinking) Operating State Things to do Green (lighted) The state immediately after startup Press the button in this state for a few seconds to enter the device setting mode (Purple(blinking)). Green (blinking) Connecting to Wi-Fi In case of a successful connection, the connection will be Blue (blinking). It is in the state of scanning (or connecting) to the surrounding Wi-Fi. It will automatically change to one of the following statuses. Purple (blinking):Wi-Fi setting standby state(How to set) Blue (blinking):Successfully connected to Wi-Fi. Connecting to the cloud. Red (lighted):Cloud connection error (please check the items lit in red) If no Wi-Fi is found in the surrounding area that can be connected, it will repeatedly blink Green/light up. Blue (lighted) Obniz Cloud Connected (Setup complete) Blue (blinking) They're connected to the obniz Cloud The Wi-Fi connection has been successfully established and you are now connected to the cloud (Internet). Purple (blinking) Waiting for user configuration Gateway is outputting Wi-Fi and waiting for the user to operate. You can configure one of the following: ・Wi-Fi settings You can configure the Wi-Fi to connect to. Click here for more information ・Startup Options You can check the OS version and Mac address of the device. You can also set up other settings, such as deleting Wi-Fi settings. Learn more Long Press of button over 3 seconds, then your device enter WPS mode(OS3.5.0 and later) Purple (high-speed blinking) WPS Mode(OS3.5.0) The gateway is waiting for the access point's WPS; press the WPS button on the Wi-Fi router or other access point to complete the setting. Red (lighted) Connected to Wi-Fi, not connected to the obniz Cloud Review your network settings. Inadequate proxy settings Restrict access to the network If the above does not solve the problem, please check the following in the cloud. Device is "Inactive". => Change to "Active". Plan Expiration (Disable payment settings) If it is not the above, the cloud is under maintenance. Please wait until the maintenance is complete. Blue (high-speed blinking) obnizOS is being updated If obnizOS is being updated, it will reboot and turn Green when it is done. LED does not turn on No power on Check the power supply. To confirm, unplug the device and connect a different device to the same outlet to make sure that the device works. Then we recommend you to plug in the obniz BLE again. Wi-Fi reconfiguration If you don’t have any Wi-Fi information or can’t connect to Wi-Fi, you’ll need to set it up again. You will need to reconfigure your Wi-Fi, especially in the following cases My Wi-Fi password has changed.I want to register an additional Wi-Fi connection that is not currently connected. If you want to set up your new Wi-Fi information, here’s how you can do it Re-configure in a place without connected Wi-Fibutton to clear all Wi-Fi settings from device setting mode. Change to device setting mode If you press and hold the button for a few seconds immediately after turning on the power (green), you will be able to check the information and set the device (purple (flashing)). Again, you can connect with a smartphone or other device to clear the Wi-Fi settings, etc. (obnizOS3.4.0 or later) See detail ## Registering devices to the cloud You can register devices in the cloud by going to [Register device](/reference/cloud/device-management/registration). Registering to the cloud allows you to increase the level of security and manage your devices at a glance --- ## Until OS3.4.5 URL: https://obniz.com/reference/obniz-ble-wi-fi-gateway/quick-start/until345 This is a quick start for OS version 3.4.5 or later. Click here for Quick Start for version 3.4.1 and earlier. Turn on the power Power is turned on by connecting the obniz BLE Gateway to a power supply (outlet).When the LED is blinking Green, it is ready to be set.Connect to the Wi-Fi (SSID) output by the Gateway from a PC or tablet. LED status on startup (OS v3.4.5 or later) LED status Color Operating State Things to do Purple (blinking) Standby for options at startup Immediately after startup (Green light on), press and hold the button to enter the startup option standby state. You can check the OS version and Mac address of the device. Other than that, you can also delete Wi-Fi settings.Learn more LED does not turn on No power on Check the power supply. To confirm, unplug the device and connect a different device to the same outlet to make sure that the device works. Then we recommend you to plug in the obniz BLE again. LED Display and operating status Wi-Fi Settings When you connect to Wi-Fi for the first time, the gateway will be in the standby state (LED blinking Purple) for Wi-Fi setting. Please follow steps 1-3 of the Wi-Fi setup procedure below to proceed with the setup. If there is a memorized Wi-Fi (SSID), the LED will blink Blue. In this case, you do not need to perform steps 1 to 3 below. LED status when connected to Wi-Fi / Cloud (OS v3.4.5 or later) LED status Color Operating State Things to do  Purple (blink)→Green (blink) Wi-Fi connection error You may have made a mistake in your Wi-Fi connection settings. You may need to reset the settings and reconfigure them if necessary.In some cases, please reset the settings. This will resolve after a period of time (about 4 seconds) and then the device will reboot and turn green.  Blue (blink)→Red (light) Cloud connection error Review your network settings. Inadequate proxy settings Restrict access to the network If the above does not solve the problem, please check the following in the cloud. Device is "Inactive" => Change to "Active" Plan Expiration (Disable payment settings) Red (light) Cloud maintenance - For safety reasons, the system will automatically restart after 1 minute of inactivity or 15 minutes of inactivity while not connected to obniz Cloud. LED Display and operating status How to set up Wi-Fi 1. Connect to BLE Gateway’s Wi-Fi In the initial state, Wi-Fi is output from the BLE Gateway. Connect to the Wi-Fi (SSID) output by the Gateway from a PC or tablet.SSID: obniz-XXXXXXXX(8 digit number) 2. Selecting the Wi-Fi While connected to Gateway Wi-Fi, go to the Settings page (http://192.168.0.1). Select the SSID of the Wi-Fi you want to use from the pull-down and enter your password. You can connect to the Internet via Wi-Fi (b/g/n 2GHz). 3. Connection After completing the input, click [Connect] to attempt to connect to the network you have set up. Regardless of success or failure, the browser will display the figure. Setup Complete The LED lights up Blue when a constant connection to the cloud is established. If the connection fails, please try again to enter or set the SSID or password. LED Display and operating status LED Display (OS v3.4.5 or later) The LED will change depending on the network connection status and other operating conditions. LED status Color (on/blinking) Operating State Things to do Green (lighted) The state immediately after startup Press the button in this state for a few seconds to enter the device setting mode (Purple(blinking)). Green (blinking) Connecting to Wi-Fi In case of a successful connection, the connection will be Blue (blinking). It is in the state of scanning (or connecting) to the surrounding Wi-Fi. It will automatically change to one of the following statuses. Purple (blinking):Wi-Fi setting standby state(How to set) Blue (blinking):Successfully connected to Wi-Fi. Connecting to the cloud. Red (lighted):Cloud connection error (please check the items lit in red) If no Wi-Fi is found in the surrounding area that can be connected, it will repeatedly blink Green/light up. Blue (lighted) Obniz Cloud Connected (Setup complete) Blue (blinking) They're connected to the obniz Cloud The Wi-Fi connection has been successfully established and you are now connected to the cloud (Internet). Purple (blinking) Waiting for user configuration Gateway is outputting Wi-Fi and waiting for the user to operate. You can configure one of the following: ・Wi-Fi settings You can configure the Wi-Fi to connect to. Click here for more information ・Startup Options You can check the OS version and Mac address of the device. You can also set up other settings, such as deleting Wi-Fi settings. Learn more Red (lighted) Connected to Wi-Fi, not connected to the obniz Cloud Review your network settings. Inadequate proxy settings Restrict access to the network If the above does not solve the problem, please check the following in the cloud. Device is "Inactive". => Change to "Active". Plan Expiration (Disable payment settings) If it is not the above, the cloud is under maintenance. Please wait until the maintenance is complete. Blue (high-speed blinking) obnizOS is being updated If obnizOS is being updated, it will reboot and turn Green when it is done. LED does not turn on No power on Check the power supply. To confirm, unplug the device and connect a different device to the same outlet to make sure that the device works. Then we recommend you to plug in the obniz BLE again. Wi-Fi reconfiguration If you don’t have any Wi-Fi information or can’t connect to Wi-Fi, you’ll need to set it up again. You will need to reconfigure your Wi-Fi, especially in the following cases My Wi-Fi password has changed.I want to register an additional Wi-Fi connection that is not currently connected. If you want to set up your new Wi-Fi information, here’s how you can do it Re-configure in a place without connected Wi-Fibutton to clear all Wi-Fi settings from device setting mode. Change to device setting mode If you press and hold the button for a few seconds immediately after turning on the power (green), you will be able to check the information and set the device (purple (flashing)). Again, you can connect with a smartphone or other device to clear the Wi-Fi settings, etc. (obnizOS3.4.0 or later) See detail ## Registering devices to the cloud You can register devices in the cloud by going to [Register device](/reference/cloud/device-management/registration). Registering to the cloud allows you to increase the level of security and manage your devices at a glance --- ## Until OS3.4.1 URL: https://obniz.com/reference/obniz-ble-wi-fi-gateway/quick-start/until341 This is a quick start for OS version 3.4.1 and earlier. Turn on the power Power is turned on by connecting the obniz BLE Gateway to a power supply (outlet).When the LED is blinking Green, it is ready to be set.Connect to the Wi-Fi (SSID) output by the Gateway from a PC or tablet. LED status on startup (OS v3.4.2 or later) LED status Color Operating State Things to do Purple (blinking) Standby for options at startup Immediately after startup (Green light on), press and hold the button to enter the startup option standby state. You can check the OS version and Mac address of the device. Other than that, you can also delete Wi-Fi settings.Learn more LED does not turn on No power on Check the power supply. To confirm, unplug the device and connect a different device to the same outlet to make sure that the device works. Then we recommend you to plug in the obniz BLE again. LED Display and operating status Wi-Fi Settings When you connect to Wi-Fi for the first time, the gateway will be in the standby state (LED blinking Purple) for Wi-Fi setting. Please follow steps 1-3 of the Wi-Fi setup procedure below to proceed with the setup. If there is a memorized Wi-Fi (SSID), the LED will blink Blue. In this case, you do not need to perform steps 1 to 3 below. LED status when connected to Wi-Fi / Cloud (OS v3.4.2 or later) LED status Color Operating State Things to do  Green (blink)→Red (light) Wi-Fi connection error You may have made a mistake in your Wi-Fi connection settings. You may need to reset the settings and reconfigure them if necessary. In some cases, please reset the settings. This will resolve after a period of time (about 4 seconds) and then the device will reboot and turn green.  Blue (blink)→Red (light) Cloud connection error Review your network settings. Inadequate proxy settings Restrict access to the network If the above does not solve the problem, please check the following in the cloud. Device is "Inactive" => Change to "Active" Plan Expiration (Disable payment settings) Red (light) Cloud maintenance - For safety reasons, the system will automatically restart after 1 minute of inactivity or 15 minutes of inactivity while not connected to obniz Cloud. LED Display and operating status How to set up Wi-Fi 1. Connect to BLE Gateway’s Wi-Fi In the initial state, Wi-Fi is output from the BLE Gateway. Connect to the Wi-Fi (SSID) output by the Gateway from a PC or tablet.SSID: obniz-XXXXXXXX(8 digit number) 2. Selecting the Wi-Fi While connected to Gateway Wi-Fi, go to the Settings page (http://192.168.0.1). Select the SSID of the Wi-Fi you want to use from the pull-down and enter your password. You can connect to the Internet via Wi-Fi (b/g/n 2GHz). 3. Connection After completing the input, click [Connect] to attempt to connect to the network you have set up. Regardless of success or failure, the browser will display the figure. Setup Complete The LED lights up Blue when a constant connection to the cloud is established. If the connection fails, please try again to enter or set the SSID or password. LED Display and operating status LED Display (OS v3.4.2 or later) The LED will change depending on the network connection status and other operating conditions. LED status Color (on/blinking) Operating State Things to do Green (lighted) The state immediately after startup Press the button in this state for a few seconds to enter the device setting mode (Purple(blinking)). Green (blinking) Connecting to Wi-Fi In case of a successful connection, the connection will be Blue (blinking). It is in the state of scanning (or connecting) to the surrounding Wi-Fi. It will automatically change to one of the following statuses. Purple (blinking):Wi-Fi setting standby state(How to set) Blue (blinking):Successfully connected to Wi-Fi. Connecting to the cloud. Red (lighted):Wi-Fi connection or Cloud connection error (please check the items lit in Red) If no Wi-Fi is found in the surrounding area that can be connected, it will repeatedly blink Green/light up. Blue (lighted) Obniz Cloud Connected (Setup complete) Blue (blinking) They're connected to the obniz Cloud The Wi-Fi connection has been successfully established and you are now connected to the cloud (Internet). Purple (blinking) Waiting for user configuration Gateway is outputting Wi-Fi and waiting for the user to operate. You can configure one of the following: ・Wi-Fi settings You can configure the Wi-Fi to connect to. Click here for more information ・Startup Options You can check the OS version and Mac address of the device. You can also set up other settings, such as deleting Wi-Fi settings. Learn more  Green (blink)→Red (lighted) Wi-Fi connection error Please check the following: Make sure the SSID and password are correct. Check network settings In some cases, please reset the settings.  Blue (blink)→Red (lighted) Connected to Wi-Fi, not connected to the obniz Cloud Review your network settings. Inadequate proxy settings Restrict access to the network If the above does not solve the problem, please check the following in the cloud. Device is "Inactive" => Change to "Active" Plan Expiration (Disable payment settings) If it is not the above, the cloud is under maintenance. Please wait until the maintenance is complete. Blue (high-speed blinking) obnizOS is being updated If obnizOS is being updated, it will reboot and turn Green when it is done. LED does not turn on No power on Check the power supply. To confirm, unplug the device and connect a different device to the same outlet to make sure that the device works. Then we recommend you to plug in the obniz BLE again. Wi-Fi reconfiguration If you don’t have any Wi-Fi information or can’t connect to Wi-Fi, you’ll need to set it up again. You will need to reconfigure your Wi-Fi, especially in the following cases My Wi-Fi password has changed.I want to register an additional Wi-Fi connection that is not currently connected. If you want to set up your new Wi-Fi information, here’s how you can do it Re-configure in a place without connected Wi-Fibutton to clear all Wi-Fi settings from device setting mode. Change to device setting mode If you press and hold the button for a few seconds immediately after turning on the power (green), you will be able to check the information and set the device (purple (flashing)). Again, you can connect with a smartphone or other device to clear the Wi-Fi settings, etc. (obnizOS3.4.0 or later) See detail ## Registering devices to the cloud You can register devices in the cloud by going to [Register device](/reference/cloud/device-management/registration). Registering to the cloud allows you to increase the level of security and manage your devices at a glance --- ## FAQ URL: https://obniz.com/reference/obniz-ble-wi-fi-gateway/faq ## About Wi-Fi ### How to set up Wi-Fi By turning on the gateway, the unit becomes a Wi-Fi access point. By connecting to it, you can configure the settings from your browser.See [Quick Start](/reference/obniz-ble-wi-fi-gateway/quick-start) for instructions on how to set it up. ### About Wi-Fi and networks you can connect to See belows [Wi-Fi](/ja/reference/obnizos-for-esp32/wi-fi/) [Protocol](/ja/reference/obnizos-for-esp32/protocol/) ### I want to set up a firewall.Please tell me the domain and IP of the connection destination. The IP is not fixed. The domain will be obniz.io or *.obniz.io. However, the content is encrypted because it is TLS communication. ### When you talk about remote control of devices, do you need to drill holes in the firewall of the router? No, it does not. Since the device connects to the server, you don't need to configure any port forwarding or other settings on your firewall. ### Can I set up multiple Wi-Fi access points? Yes. The maximum number is 5, but it may be less depending on the remaining memory. ### Can Wi-Fi be RESET? Yes. You can initialize it by pressing the button after power-on to invoke the startup option. See [Quick Start](/reference/obniz-ble-wi-fi-gateway/quick-start#troubleShooting) for reset instructions. ### How can I check the status of my Wi-Fi connection? This can be confirmed by the LED on the gateway itself. See [Quick Start](/reference/obniz-ble-wi-fi-gateway/quick-start) for details. ## About Bluetooth ### How many units can be connected? The maximum number of simultaneous connections is seven. ### Can a gateway be a peripheral? The gateway is a peripheral and can send advertisements and accept connections. ### Can a gateway connect and scan at the same time? It is possible. However, you need to temporarily stop the scan only when the first connection is being processed. Once completed, they can be used simultaneously. ### Is it possible to connect only to devices that support it? We are not limited. The supported devices listed on the website mean that we have developed and provided libraries with SDKs, etc., or that we have confirmed the connection. Other devices can also be used by writing a BLE program. ### Can I set up a filter for advertisement? Yes, the following two types are available: - Programmatic filters (any filter can be created by specifying details such as RSSI, once per minute, etc.) - Device side filters (can reduce communication volume, UUID specification, pattern matching, etc. can be used) ## About the Program ### What languages are available? The SDK we provide is for JavaScript. For other languages, you can use the Websocket API. ### I have a system that we are currently using. Does it need to be modified? You can use our gateway without changing your existing system. If you are currently using a different gateway and have an API to accept, you can use obniz without changing the existing system by creating a server software that operates obniz and hits the existing API. In this case, unlike updating the firmware, you only need to update the server software, which makes operation easier. ## About Security ### Is there a default user or password for SSH? There is no function to connect to the device via SSH. ### If the device is stolen, will the software you developed be stolen? No software is compromised. With obniz's firmwareless technology, the device will not carry your code. ### If my paired obniz is stolen, will they take my pairing key? The pairing key will not be compromised. With obniz's firmware-less technology, nothing is recorded on the device itself, so it cannot be leaked. ### Can anyone connect if they know their obniz ID? Access can be restricted by issuing an access token. An access token can be issued by registering the device to your account. In this case, you will not be able to connect unless you have an access token. ## About Delivery ### What is the delivery format? Tray supply in bulk or individual packaging can be selected. ### Can you link the device to my account in advance? Yes, we can. You can apply for the option. ### I would like to know the Mac address in advance. Can you send it with me? Yes, we can. You can apply for the option. ### Where can I purchase gateways? Our e-commerce site and trading companies also handle this product, so please inquire. For product details and contact information, please see the [Gateway product page](https://obniz.com/products/ble-gateway). --- ## Spec URL: https://obniz.com/reference/obniz-ble-wi-fi-gateway/spec ## 形状・電気的仕様 項目| 値 ---|--- サイズ | 50mm×35mm×13mm プラグ部除く 電源 | AC100V 50/60Hz 動作環境 | 温度:0℃〜40℃。湿度10%〜90% 消費電流 | 最大0.1A 主な素材 | 難燃性ポリカーボネート Bluetooth | Bluetooth 4.2 Wi-Fi | IEEE 802.11b/g/n (2.4 GHzのみ) ([接続可能なWi-Fi詳細](../obnizos-for-esp32/wi-fi/)) 同時接続数 | 7台(状況により異なります) 製造 | エンコアードジャパン株式会社(品番CON1-JP) ## 各種認証 項目| 値 ---|--- Wi-Fi/Bluetoothモジュール認証番号 | R 211-171102 S-JET認証 | S19-Y0239 品質マネジメント認証(エンコアードジャパンCON1-JPとして) 項目| 値 ---|--- 品質マネジメント認証 | 取得者:SENKO Co., Ltd. 認証規格:KS Q ISO 9001 : 2009 / ISO 9001 : 2008 --- ## obniz BLE/LTE Gateway (Cat.4) URL: https://obniz.com/reference/obniz-ble-lte-gateway ## Overveiw obniz BLE/LTE Gateway (Cat.4) is a repeater (gateway) that is installed in an indoor 100V outlet to receive Bluetooth signals and transmit information via LTE. Various IoT services can be easily started by combining the gateway with sensors that detect various conditions such as movement of people and objects, temperature, brightness, humidity, and CO2 concentration. The main unit has a display, button, and status LEDs. For details, please refer to the [product specifications](spec). ## Caution **This product conforms to the Bluetooth standard defined by the Bluetooth SIG and has been certified. However, it does not guarantee Bluetooth connectivity with all Bluetooth devices.** - The Bluetooth device to be connected must conform to the Bluetooth standard defined by the Bluetooth SIG and be certified. - Even if the device to be connected conforms to the above Bluetooth standard, it may not be possible to connect or the operation method may differ depending on the timing of acquisition, characteristics, or specifications of the device. If you wish to use any of the BLE devices from other manufacturers introduced on the obniz official website, you do so at your own risk, and you should thoroughly review and test them prior to use. obniz Inc. makes no warranty to you regarding the suitability of such devices for any particular purpose, their reliability and accuracy, or any results obtained when used with the products themselves or in combination with obniz products. --- ## Internet Connection Setting URL: https://obniz.com/reference/obniz-ble-lte-gateway/quick-start ## 電源を入れる ![](./images/outlet.png) Gatewayを電源(コンセント)に接続することで電源が入ります。電源マークが黄色点灯し、LTEマークが緑色に点滅します。 ### コンポーネントについて 本体には3つのLEDと1つのボタンがあります。 #### LED 項目| 意味 ---|--- 電源マーク(上段LED) | 電源オン時は常時点灯します。 LTEマーク(中段LED) | 携帯回線接続状態。青点灯: 携帯回線に接続しています。 Cloud接続マーク(下段LED) | obnizCloudとの接続状況を表示します。青点灯: クラウド接続済み。青点滅: クラウド接続中。緑点滅: Wi-FiまたはLTEに接続中紫点滅: 設定モード ### ネットワーク設定モードへの移行 SIMカードのAPN設定やWi-Fi利用には設定モードに切り替えて設定してください。 ![](./images/image_button.png) ボタンを長押しすることで、ネットワーク設定モードに移行いたします。設定モードに移行すると、LTEマークとCloudマークが紫色に点滅いたします。 ## ネットワーク設定(APN設定/Wi-Fiへの切り替え) [設定方法について、詳しくはブラウザからの設定](https://docs.obniz.com/ja/reference/obnizos-for-esp32/settings/setting-via-browser)を御覧ください。 Gatewayが設定モードに移行すると、本体からWi-Fiを出力いたしますので、スマートフォンやPCで、該当のobniz IDを確認し、接続してください。 Wi-Fi接続が完了すると、ログインページに自動遷移いたします。PassKeyにobnizと入力して、Loginボタンを押してください。 ※自動遷移しない場合、[http://192.168.254.1/](http://web.archive.org/web/20230610004218/http://192.168.254.1/)へアクセスお願いします。 ログイン後、ネットワーク設定の画面が開きます。Networkのタブより、Wi-Fiを選択ください。 詳しくは下記を参照下さい。 [https://obniz.com/ja/doc/reference/obniz-ble-wi-fi-gateway/quick-start/](http://web.archive.org/web/20230610004218/https://obniz.com/ja/doc/reference/obniz-ble-wi-fi-gateway/quick-start/) ## SIMの挿入 obniz Nowではなく自社で用意されたSIMをSIMフリー端末に挿入して利用するには - SIMの挿入 - APNの設定 が必要となります。 SIMは同封のトレーにはめたうえでトレーごと側面より挿入し蓋を締めます。 なお、蓋のテープで蓋の貼付けを行うと取り外すのは困難となります。 ![](./images/sim.png) APNは「ネットワーク設定(APN設定/Wi-Fiへの切り替え)」に記載の設定ページよりAPN/ID/Passを設定し登録してください。APNは1つだけ保存可能です。 --- ## Spec URL: https://obniz.com/reference/obniz-ble-lte-gateway/spec ## ハードウェアスペック 項目| 値 ---|--- サイズ | 幅46mm×奥行25mm×高さ85mm 電源 | AC100V 50/60Hz 動作環境 | 温度:-10~45℃、湿度:80%以下 消費電流 | 最大0.3A 主な素材 | 難燃性ポリカーボネート Bluetooth | Bluetooth 5.0 LE LTE | LTE Cat.4(Band1/3/8/18/19/26) 付属コンポーネント | ・ボタン ・フルカラーLED(オンライン状態などを示すステータスLED) 製造 | 株式会社IoTBank --- ## AK-030 URL: https://obniz.com/reference/ak030 ABIT社の販売するAK-030はESP32を搭載しモデムを利用しLTE CatM1回線からインターネットに接続できるobnizOS対応済み製品です。 USBを電源とし、SIMのAPN設定はシリアル通信経由またはWi-Fiによるブラウザ経由で行なえます。 また、LTEを利用せずWi-Fiでのクラウド接続も可能なためOS3.5.0から利用できるネットワークフェイルオーバーを利用すれば基本Wi-Fiだが、Wi-FiがNGな場合はLTEという切り替えも可能です。 ![](./images/ak030.png) ## 仕様 注意:詳細な仕様や利用注意点はABIT社のマニュアルを参照ください。 項目 | 内容 ---|--- 規格 | LTE Cat M1 通信速度 | 375Kbps (DL), 375Kbps (UL)、最大 アンテナ | 内蔵 U-SIM ソケット | Nano-SIM / 4FF に対応 LED | 2つ(obnizOSでは片方を電源LEDに、片方を接続状態表示に利用します) IO | 5VとGND、そして2つのGPIOがありプログラムから利用可能です。 動作温度 | 0~+40度 保存温度 | -20~+85度 ## セットアップ方法 ### SIMの挿入 AK-030のSIMカードスロットは裏面カバーを取り外したところにあります。 裏面カバーの拡大図 この部分からパチパチと外れます。 強く外すと破損を起こす可能性があります ![](./images/image2.jpg) 裏面カバーを外すと、金具で固定する形式のSIMカードスロットが確認できます。 先端側に向けて水平にスライドするとロックが外れ、金具が持ち上がります。 ![](./images/image3.jpg) SIMには向きがあるので、**切欠きに注意して**SIMをはめ込みます。 はめ込んだ後は、金具をもとのように倒し、ロックを外した時と逆向きにスライドするとロックされます。 裏面カバーを再び取り付けて完了です。 ### 電源投入とAPN設定 電源はUSBで供給します。 電源が入っている限りobnizOSはクラウドと常時接続を行います。 設定がない、または設定されているものにつながらない場合は設定モードとなり自身からWi-Fiを発して設定を受け付けますのでスマートフォンからも設定可能です 設定方法 | 内容 ---|--- コンソール | USBはPCでCOM PORTとして認識されます。[コンソールからの設定方法](/reference/obnizos-for-esp32/settings/setting-via-serial)において設定可能です。注意点として、COM PORTが2つ検出されますが、どちらかがESP32とつながっています。 ブラウザ | AK030が初期または設定したものにつながらない場合は設定モードとなります。[ブラウザからの設定方法](/reference/obnizos-for-esp32/settings/setting-via-browser)で、Ak-030の出すWi-Fiに接続しブラウザから設定を行ってください。 ## LED点灯パターン 片方が電源を示し、常時点灯しますので、点灯していなければ電源が入っておらずobnizOSが全く起動していないことを意味します。 もう片方はobnizOSの「単色(Single Color)シグナルLED」として機能します。詳細は[LEDコンポーネント](/reference/obnizos-for-esp32/components/led)を御覧ください。代表的なものは 点灯パターン|意味 ---|--- 点滅 | 接続中やエラー 1秒の長めの点滅 | 設定モード。Wi-Fiを出力しています。 点灯 | オンライン --- ## obniz PLC URL: https://obniz.com/reference/plc 4つのリレーと光入力を持つPLCです。ESP32が内蔵されていてWi-Fi経由でクラウドからリレーの制御や有線LANの制御が行なえます。 ![](./images/plc.jpg) ## 仕様 項目 | 内容 ---|--- 電源 | 8 - 30 V リレー出力 | 4 (最大電圧/電流 250V/5A) 光絶縁デジタル入力 | 4 (動作電圧 3-30V、 ON arrives form 3V) RS485 | スピード 500Kbps(近距離 Grove | 3.3vの端子が1つ 拡張 | 内部にEPS32のGPIO接続用拡張ピンフレームあり サイズ | 70mm × 92mm × 35mm 重量 | 138g ## ライセンス obnizCloudの無期限ライセンスが付属しています。 本体横のQRコードをobnizCloudにログインした状態のスマートフォンで読み取ることでアカウントに紐付けることが可能です。 登録完了後、クラウド上でIDの確認やオンライン状態の確認が行なえます。 ## セットアップ 電源は本体左下の端子でDC8-30vとなります。 電源投入後LEDが接続状態を示します。 ([LED コンポーネント フルカラーの点灯パターン](/reference/obnizos-for-esp32/components/led)に従います。) Wi-Fiは以下の2つの方法で設定できます。 設定方法 | 内容 ---|--- コンソール | シリアルポートにつなぎ[コンソールからの設定方法](/reference/obnizos-for-esp32/settings/setting-via-serial)において設定可能です。 ブラウザ | 初期または設定したものにつながらない場合は設定モードとなります。[ブラウザからの設定方法](/reference/obnizos-for-esp32/settings/setting-via-browser)で、出力されるWi-Fiに接続しブラウザから設定を行ってください。 ## サンプルプログラム リレーと光入力に関してすぐに試せるサンプルプログラムを用意しております。 [https://codesandbox.io/s/obniz-plc-relay-iele2](https://codesandbox.io/s/obniz-plc-relay-iele2) ## その他技術情報 お気軽にお問い合わせください。 --- ## ATOM Lite URL: https://obniz.com/reference/atom_lite ATOM Liteは、小型のESP32ベースの開発ボードです。 ![](images/pdct-atomlite.jpg) ## クラウドへのデバイス登録 [デバイスの登録](/reference/cloud/device-management/registration) にてクラウドにデバイスを登録することができます。 クラウドに登録することで、セキュリティのレベルを上げたり、所有デバイスを一覧で管理できます --- ## Support URL: https://obniz.com/support Here you can check the terms of service and more. - [Terms] (. /terms) --- ## クラウドサービス利用規約 URL: https://obniz.com/support/terms/terms **第1条(本規約の目的)** 本規約は、株式会社obniz(以下「当社」という。)の提供するクラウドサービス「obnizCloud」(以下「本サービス」といいます。理由の如何を問わずサービスの名称又は内容が変更された場合は、当該変更後のサービスを含みます。)について定めるものとします。 **第2条(用語の定義)** 本規約においては、次の用語はそれぞれ次の意味で使用します。 (1)利用契約:本規約に基づき当社と契約者との間に締結される本サービスの提供に関する契約 (2)申込者:当社に本サービスの提供を申し込む法人、機関等 (3)契約者:利用契約を当社と締結し、本サービスの提供を受ける法人、機関等 (4)端末機器:本サービスを利用するために電気通信回線を経由して当社の指定サーバに接続する端末機器および端末電子基板の総称であり、当社が指定したもの (5)チップセット:本サービスを利用するために電気通信回線を経由して当社の指定サーバに接続する端末電子基板上にあるプロセッサ類の総称であり、当社が指定したもの (6)obniz ID:端末機器を識別するために用いられる符号 (7) obniz SDK:端末機器に接続される電子部品を操作するためのプログラム (8)ユーザID:契約者が指定する利用ユーザを識別するために用いられる符号 (9)利用ユーザ:必要に応じて契約者が承認し、本サービスを利用する者 (10)AIサービス:本サービス内に搭載される機械学習・生成AIに基づく分析・解説・制御支援機能の総称 (11)MCPサーバー:AIエージェントが本サービスに接続し機器情報の取得や操作を行うためのModel Context Protocolに基づくサーバー機能 (12)AI生成コンテンツ:AIサービスが出力する分析結果・グラフ・説明文・操作提案等の一切 (13)保存データ:契約者または契約者の顧客が本サービスにおいて記録、入力または保存したデータの総称 (14)入力データ:契約者がAIサービスに入力するデータ(テキスト、数値、画像等を含みます。) (15)外部AIサービス:AIサービス・MCPサーバーその他の外部のサービスの総称 (16)外部AIサービス事業者:外部AIサービスのサービス提供者 **第3条(本規約の適用)** 1 当社は、利用契約の内容に従って本サービスの提供を行い、契約者は利用契約および当社が定める条件にてこれを利用するものとします。 2 本サービスの詳細については、obniz[サービス説明書](./service)に記載するものとします。obnizサービス説明書は、利用契約の一部を構成するものとします。 **第4条(本規約の変更)** 1 当社は、民法(明治29年法律第89号)第548条の4(定型約款の変更)の規定に基づき、本規約を変更することができます。 2 当社は、前項の規定により本規約を変更する場合、その効力発生日を定め、効力発生日の[14]日前までに、ウェブサイトへの掲載その他の適切な方法により、以下の事項を周知するものとします。 ①本規約を変更する旨 ②変更後の本規約の内容 ③効力発生日 3 契約者は、第31条の規定にかかわらず、前項の規定に従い周知をした日から効力発生日までの間に当社に通知することによって、利用契約を解除することができます。 **第5条(利用契約の申込み)** 1 申込者は、本規約の内容を承詰の上、当社が定める方法により、本サービス利用のための申込みを行うものとします。利用契約は、当社が当社所定の手続によって申込みを承諾したときに成立します。本規約は、利用契約の一部を構成します。 2 当社は、前項の規定にかかわらず、次の場合には、その利用契約の申込みを承諾しない、あるいは承諾を留保することがあります。 (1)申込者が実在しない場合 (2)当社所定の利用申込書に虚偽の記載または記入漏れがある場合 (3)申込者が過去に本サービスの代金支払いを遅延し、 または不正に免れようとしたことがある場合 (4)本サービスの利用目的が、評価、解析その他本来の目的と異なるものであると疑われる場合 (5)申込者またはその代表者、役員において、反社会的勢力(暴力団、暴力団員等をいう。)に該当するときまたはそのおそれがあるとき (6)その他当社が不適当と判断する相当の理由がある場合 3 前項に従い、当社が利用契約の申込みを承諾せず、あるいは承諾を留保する場合は、その旨を申込者(契約者)に通知します。ただし、当社は、承諾をしなかったことあるいは承諾を留保したことによる責任は負いません。 **第6条(利用契約の期間)** 1 利用契約の契約期間は、本サービスの利用開始日(利用開始の申込みに対して当社が承諾した日または当社と契約者との間で合意した日をいいます。)から当社および契約者が別途定める期間とします。 2 利用契約の契約満了日から甲乙が別途定める期間までに、契約者から当社に対して、当社の指定する方法で解約の申込みがなかった場合には、利用契約の契約満了日の翌日を契約更新日として、同一の内容・条件にて利用契約が1項にて定める期間更新されるものとし、以降も同様とします。 **第7条(サービスの範囲)** 1 当社は、当社指定の条件下で、契約者が管理する端末機器から電気通信回線を経由して当社の指定サーバに接続することにより、本サービスを利用することのできる環境を提供します。 2 契約者は、本サービスの利用に必要な端末用ソフトウェア(obnizOS)を、当社が提供するアプリケーション配信サービス(以下「配信サービス」という。)を通じて取得することができます。当社は配信サービスの性能、内容、継続性について何ら保証しません。配信サービスの全部または一部について、不具合その他の理由による中止、停止によって、契約者が端末用ソフトウェアを入手できなくなった場合であっても、当社はその責任を負いません。 3 当社は、端末機器及びチップセットの不具合または販売停止などが生じた場合に、本サービスの提供を保証するものではありません。 4 契約者は、obnizOSのアップデートを行うことが可能ですが、当社はobnizOSが正しくアップデートできることを保証するものではありません。 5 当社は、契約者または利用ユーザが、端末機器にインストールされるobnizOSに付与される秘密鍵を紛失した場合、秘密鍵を再発行しません。 **第8条(利用制限)** 1 本サービスは、契約者自身の用途若しくは契約者自身の製品またはサービスに組込んでの利用を目的として提供されるものであり、利用ユーザに対して本サービスを提供することができます。 2 契約者による本サービスの利用は端末機器から当社指定のURLへ接続することにより行われるものとし、obnizOS及びobniz SDKを除き、本サービスを構成するソフトウェア自体をダウンロードしたり、コピーする等の方法により本サービスを構成するソフトウェアを入手することはできません。 3 契約者は、利用ユーザに対し、本規約に定める条件を周知し、これに従わせるものとします。 **第9条(本サービスの変更)** 当社は、本サービスの機能追加、改善を目的として、当社の裁量により本サービスの一部の追加・変更を行うことがあります。たたし、当該追加・変更によって、変更前の本サービスのすべての機能・性能が維持されることを保証するものではありません。 **第10条(サービスレベル)** 1 当社は、obnizサービス説明書記載の基準を満たすよう、商業的に合理的な努力をもって本サービスを提供します。 2 obnizサービス説明書記載のサービスレベルは、特段の記述がない限り、本サービスに関する当社の努力目標を定めたものであり、サービスレベルを下回った場合でも、当社は損害賠償その他いかなる責任も負わないものとします。 **第11条(obnizID)** 1  obnizIDは、当社が定める方法および使用条件に基づいて当社が付与するものとします。 2 契約者は、自らの管理責任により、obniz IDを不正利用されないよう厳格に管理するものとします。 3 当社は、obniz IDの不正利用によって契約者に生じた損害について責任を負いません。 4 契約者は、利用契約に定めるobnizIDの上限数を、当社が定める方法によって申し込むことにより、追加または減少させることができます。その場合における申込手続等については第5条を準用します。 5 当社が前項の申込みに対して承諾したときは、契約者は、追加・削除後のobnizID数に基づき、本サービスの利用料金を支払うものとします。 **第12条(ユーザIDおよびパスワード)** 1 ユーザIDおよびパスワードは、当社が定める方法および使用条件に基づいて当社が付与するものとします。 2 契約者は、自らの管理責任により、利用ユーザのユーザIDおよびパスワードを不正使用されないよう厳格に管理するものとします。 4 当社は、ユーザIDおよびパスワードの不正利用によって契約者に生じた損害について責任を負いません。当社は、ユーザIDとパスワードの認証を行った後に行われた本サービスの利用行為については、すべて契約者に帰属するものとみなすことができます。 **第13条(利用ユーザ)** 1 契約者は、利用ユーザを定め、利用ユーザに対し、ユーザIDを付与します。 2 契約者は、ユーザIDの付与、および利用ユーザによる本サービスの利用について責任を持ち、責任の及ぶ範囲において不正利用等が発生しないようにします。 **第14条(電気通信回線)** 契約者が使用する端末機器から本サービスに接続する電気通信回線は、契約者自身の責任と費用負担において、確保、維持されるものとし、当社は一切の責任を負いません。 **第15条(データ管理)** 1 契約者は、本サービスの利用に関連して入力、提供または伝送するデータ等について、必要な情報は自己の責任で保全しておくものとします。 2 当社は、契約者が利用する情報に関して、本サービスを提供する設備等の故障等により減失した場合に、その情報を復元する目的でこれを別に記録して一定期間保管しますが、復元の義務を負うものではありません。 3 当社は、障害、誤操作等による減失からの復旧を目的として、契約者の入力、登録したデータを保存するための機能を当社の定める内容にて提供します。ただし、すべてのデータが当該機能によって保存、復元されることを保証するものではありません。なお、当該機能によって復元をする場合は、当社が有償で対応します。 4 AIサービスの精度向上を目的として、契約者のセンサーデータおよびAIへの入力データを匿名化・統計処理した上で利用する場合があります。契約者は設定画面よりこれを拒否することができます。 5 MCPサーバーを経由して外部AIサービスに送信されるデータの内容および範囲は、契約者が設定した接続許可の範囲に基づくものとし、当該データが外部AIサービスにおいてどのように処理、保存または利用されるかについて、当社は関知せず、責任を負いません。契約者は、外部AIサービスの利用規約およびプライバシーポリシーを自ら確認の上、MCPサーバーの接続設定を行うものとします。 6 本サービスにおいて保存期間内に保存されているデータがMCPサーバーまたはAIサービスを経由して外部に送信された場合、当該データの外部における保存期間および削除の時期について、当社は管理する義務を負わず、責任を負いません。 **第16条(個人情報の管理)** 1 当社は、本サービスに入力されるデータに個人情報が含まれていた場合、本サービス提供の目的以外で利用しないものとし、個人情報の保護に関する法律および当社個人情報保護方針に基づいて、紛失・破壊・改竄・漏洩等の危険から保護するための合理的な安全管理措置を講じ、厳重に管理するものとします。 2 当社は、本サービスの提供のため必要がなくなった個人情報に関して、一切のコピーを残すことなく、当社責任のもとで速やかに破棄するものとします。 4 契約者は、利用契約の申込み時に、当社に対して個人情報を提供する場合を除き、AIサービスの利用にあたって、個人情報、機密情報その他の秘匿性の高い情報(以下「個人情報等」といいます。)を入力する等、当社に個人情報等を提供してはならないものとします。契約者がAIサービスの利用にあたり個人情報等を入力したことに起因して生じた損害について当社は一切の責任を負いません。 5 本条の規定は、利用契約が終了した後も有効に存続するものとします。 **第17条(当社による情報の管理・利用)** 1 当社は、本サービスの改良、サービスの維持管理等を目的とする統計調査のため、契約者の本サービスの利用状況、画面・項目の利用頻度等の統計数値を利用し、あるいは統計調査に必要な限度でこれらの情報を解析し、二次加工して活用するものとし、契約者はかかる統計調査、二次加工活用を行うことに同意します。 2 当社は、契約者または利用ユーザが入力したデータ及びobnizOSとサーバ間を経由する通信に関し、善良な管理者による注意をもって機密保持とその管理に努めるものとします。 3 契約者は、当社が、裁判所、その他の法的な権限のある官公庁の命令等により本サービスに関する情報の開示ないし提出を求められた場合は、かかる命令等に従って情報の開示ないし提出をすることがあることを承諸し、かかる開示ないし提出に対して異議を述べないものとします。 4 当社は、契約者が本サービスを利用するに際し、当社に提供、入力またはアップロードした一切の情報及び本サービスにおいて、AIサービスを利用して生成され、契約者に提供された一切の情報その他情報を運営上一定期間保存していた場合であっても、かかる情報を保存する義務を負うものではなく、当社はいつでもこれらの情報を削除できるものとします。なお、当社はこれらの情報を削除したことにつき契約者等に生じた損害について、当社は責任を負いません。 5 当社は、前項で一定期間保存していた情報の削除を要請された場合であっても、これに応じる義務を負いません。ただし、個人情報の保護に関する法律その他の法令により当社が削除義務を負う場合はこの限りではありません。 **第18条(AIサービス)** 1 AIサービスは、契約者によるデータの分析、可視化および操作の意思決定を補助する目的で提供されるものであり、AIサービスの出力に基づく最終的な判断および操作の実行は、契約者の責任において行うものとします。 2 AIサービスの出力内容は、生成AIの技術的特性上、事実と異なる情報、不正確な分析結果または不適切な操作提案を含む可能性があり、当社はその正確性、完全性、再現性、特定目的への適合性その他一切について保証しません。 3 AIサービスの出力に基づいて契約者または利用ユーザが行った操作・判断により、契約者、利用ユーザまたは第三者に生じた損害について、当社は責任を負いません。 4 当社は、AIサービスの提供にあたり、当社が選定する第三者の外部AIプロバイダーのAPI等を利用する場合があります。ただし、本サービスは外部AIサービスとの連携を保証するものではなく、外部AIプロバイダーの仕様変更、サービス停止その他の事由により、AIサービスの全部または一部が利用できなくなった場合であっても、当社は責任を負いません。 5 契約者は外部AIサービスの利用規約を自己の責任で遵守し、契約者と外部AIサービス事業者との間で紛争等が生じた場合であっても、当社は一切の責任を負いません。 6 AI生成コンテンツに関する著作権その他の知的財産権は、法令に別段の定めがある場合を除き、当社に帰属するものとします。ただし、契約者が入力したデータに関する権利は契約者に留保されます。 7 契約者は、AI生成コンテンツが第三者の知的財産権その他の権利を侵害しないことについて当社が保証しないことを了承し、AI生成コンテンツの利用に起因して第三者との間で紛争が生じた場合は、契約者の責任と費用において解決するものとします。 8 AIサービスにおける入力データの取扱い (1) 入力データに関する権利は、契約者に帰属します。 (2) 当社は、入力データを、AIサービスの提供(外部AIプロバイダーへのAPI送信を含みます。)の目的でのみ利用するものとし、契約者の同意なく第三者に開示しません。ただし、第17条第3項に定める場合はこの限りではありません。 (3) 当社は、入力データが外部AIプロバイダーに送信された後の当該プロバイダーにおける取扱いについて、商業的に合理的な範囲で適切なプロバイダーを選定する義務を負いますが、当該プロバイダーによるデータの取扱いについて保証するものではありません。 (4)本サービスにおける保存データがAIサービスの入力として利用される場合、当該保存データに関する第15条の規定は引き続き適用されるものとします。ただし、AIサービスを通じて外部AIプロバイダーに送信された後のデータの取扱いについては、本条の規定が優先して適用されるものとします。 **第19条(MCPサーバーおよびAIエージェントからの利用)** 1 MCPサーバーは、外部のAIエージェントが本サービスに接続し、端末機器の情報取得および操作を行うためのインターフェースとして提供されます。MCPサーバーの利用にあたっては、当社が定める認証方式および利用条件に従うものとします。 2 MCPサーバーへのアクセスに使用する認証情報(APIキー、トークン等)の発行、管理および失効処理は契約者の責任とし、認証情報の漏洩、不正利用等により契約者または第三者に生じた損害について当社は責任を負いません。 3 契約者がMCPサーバー経由での端末機器の操作を許可する設定を行った場合、当該設定に基づきAIエージェントが実行した操作はすべて契約者の指示に基づくものとみなし、その操作結果(機器の誤動作、意図しない制御、データの損失等を含みます。)について当社は責任を負いません。 4 契約者は、MCPサーバーを通じて接続する外部AIサービスの選定、設定および監視について自らの責任で行うものとし、当該外部AIサービスの不具合、誤判断またはセキュリティ上の脆弱性に起因して生じた損害について当社は責任を負いません。 5 当社は、MCPサーバーの安全性確保のため、接続頻度の制限、特定の操作の制限その他必要な措置を事前の通知なく講じることができるものとします。 6 契約者は、MCPサーバーを利用する場合、人の生命、身体または財産に危険を及ぼすおそれのある用途において、AIエージェントによる自律的な操作のみに依存してはならず、適切な人的監視および安全措置を講じるものとし、契約者がかかる適切な人的監視および安全装置を講じることを怠ったことにより損害が発生したとしても、当社は一切の責任を負いません。 7 MCPサーバーを経由した外部AIサービスからのアクセスにより、本サービスにおいて保存されているデータ(保存期間内のセンサーデータ、設定情報等を含みます。)が当該外部AIサービスに送信される場合があります。契約者は、MCPサーバーの接続を許可することにより、当該接続許可の範囲において保存データが外部に送信されることに同意するものとします。 **第20条(利用料金の支払方法)** 1 契約者は、利用契約が成立した日から起算して利用契約の終了日までの期間について、本サービスの利用料金およびこれにかかる消費税等(以下「利用料金等」という。)を支払うものとします。 2 利用契約の契約期間において、本サービスの提供の休止、中止その他の事由により本サービスを利用することができない状態が生じたときであっても、契約者は、契約期間中の利用料金等を支払うものとします。 3 契約者は、本サービスの利用料金等を、当社からの請求書に従い当社が指定する期日までに当社指定の金融機関に支払うものとします。なお、支払いに必要な振込手数料その他の費用は、契約者の負担とします。 4 前各項に定める本サービスの利用料金の支払いは、当社が当社に代理して本サービスの利用料金を受領する第三者を指定した場合には、契約者は当該第三者に前項に準じて本サービスの利用料金の支払いを行うものとします。 5 AIサービスの利用に伴い、当社が利用する外部AIプロバイダーのAPI使用量等に応じて、追加料金が発生する場合があります。料金体系の詳細は別途サービス説明書または当社ウェブサイトに定めるものとし、料金体系を変更する場合は第4条の定めに従うものとします。 6 MCPサーバーを経由した外部AIサービスからのアクセスに伴い、当社が提供する携帯電話回線の通信量が増加した場合、契約プランに定める通信量の上限を超過した分について、別途当社が定める超過料金が発生する場合があります。 **第21条(遅延損害金)** 契約者が、本サービスの利用料金等を所定の支払期日が過ぎてもなお支払わない場合、契約者は、所定の支払期日の翌日から支払日の前日までの日数に、年14.6%の利率で計算した金額を遅延損害金として支払うものとします。 **第22条(委託)** 当社は本サービスの提供に関する業務の全部もしくは一部を契約者の承諾なしに、第三者に委託することができます。ただし、その場合、当社は責任をもって委託先を管理するものとします。 **第23条(禁止行為)** 契約者は、本サービスを利用するにあたり、以下の行為を行わないものとします。 (1)法令に達反する行為またはそのおそれがある行為 (2)公序良俗に反する行為 (3)他の契約者の利用を妨害する行為またはそのおそれがある行為 (4)本サービスを構成するハードウェアまたはソフトウェアヘの不正アクセス行為、クラッキング行為その他設備等に支障を与える等の行為 (5)本サービスの提供を妨害する行為またはそのおそれがある行為 (6)本サービスを構成するソフトウェアの解析、リバースエンジエアリングその他ソースコードを入手しようとする行為 (7)他の契約者のobniz IDを使用する行為またはその入手を試みる行為 (8)他の契約者のデータを閲覧、変更、改竄する行為またはそのおそれがある行為 (9)当社または外部AIサービス事業者その他第三者の知的財産権、肖像権、名誉権、プライバシー権その他権利を侵害する行為 (10)私的利用または内部利用以外の目的でAI生成コンテンツを利用(複製、公衆送信等)する行為 (11)AIサービスを利用して、第三者を誤認させる目的で事実と異なる情報を生成・流布する行為 (12)MCPサーバーを経由して、当社または第三者の機器・システムに対して不当な負荷をかける、または損害を与える行為 (13)AIサービスの出力を、人間による確認を経ずに、人の生命、身体もしくは財産に影響を及ぼしうる機器の制御に直接使用する行為 (14)MCPサーバーを経由して、当社が提供するAPI仕様に定めのない方法により本サービスにアクセスし、またはアクセスを試みる行為 (15)外部AIサービス利用して、当社または第三者のシステムの脆弱性を探知し、またはこれを悪用する行為 (16)AIサービスに対し、本来の利用目的を逸脱した入力(プロンプトインジェクション、ジェイルブレイク等を含みます。)を行い、AIサービスの制御を回避しまたは不正な出力を誘発する行為 (17)MCPサーバーを経由して、本サービスに保存されたデータを大量に抽出し、当社が提供するサービスと競合するサービスの開発または提供に利用する行為 (18)当社が提供する携帯電話回線を、本サービスの利用目的以外の用途に使用する行為 (19)外部AIサービスの利用規約に抵触する行為 **第24条(知的財産権)** 1 本サービスを構成する有形・無形の構成物(端末機器、ソフトウェアプログラム、デー     タベース、AI生成コンテンツ、アイコン、画像、文章マニュアル等の関連ドキュメント等を含む。)に関する   著作権を含む一切の知的財産権、その他の権利は、当社または当社に許諾した第三者に帰  属します。 2 当社は、契約者に対し、前項に規定する知的財産権その他の権利(特許第6439954号および特許第6519765号を含みますが、これに限られません)について、契約者および利用ユーザによる本サービスの利用に必要な限りにおいて、本サービスを非独占的に利用する権利を供与します。なお、前項に規定する知的財産権の一部が消滅・無効となった場合でも、既にお支払いいただいた利用料金の返金、将来的な利用料金の減額はいたしません。 **第25条(侵害の場合の責任)** 1 本サービスの利用に関して、第三者から契約者に対して知的財産にかかるクレーム、その他の請求が発生した場合 契約者はただちに当社に書面で通知するものとし、当社はその責任と負担においてかかるクレーム等を処理するものとします。ただし、かかるクレーム等の発生が契約者自身の責めに帰すべき事由に基づく場合および契約者が当社にクレーム等の発生を速やかに通知しない等の事由により当社が適切な防御を行う機会を逸することになった場合は、この限りではありません。 2 前項の規定にかかわらず、AIサービスに関しては、生成AIの技術的特性上、AI生成コンテンツが第三者の知的財産権を侵害しないことについて当社は保証しません。AI生成コンテンツの利用により第三者から契約者に対してクレームその他の請求がなされた場合、前項に基づく当社の対応義務は適用されないものとし、契約者が自己の責任と費用において対応するものとします。 **第26条(自己責任の原則)** 1 契約者は、契約者および契約者が承認した利用ユーザ(以下本条で「契約者等」といいます。)による本サービスの利用および本サービス内における一切の行為(情報の登録、閲覧、削除、送信等)およびその結果について、一切の責任を負います。 2 契約者は、契約者等による本サービスの利用に伴い、当該契約者等の責めに帰すべき事由で外部AIサービス事業者もしくは第三者に対して損害を与えた場合、または第三者からクレーム等の請求がなされた場合、自己の責任と費用をもって処理、解決するものとします。 3 契約者は、契約者がその故意または過失により当社に損害を与えた場合、当社に対して、当該損害の賠償を行うものとします。 4 当社が、他のユーザ、外部AIサービス事業者または第三者から、契約者の本サービスの利用に関連して、権利侵害その他の他の理由により何らかの請求を受けた場合、契約者は当社が負担すべき当該請求の金額につき、当社に対して賠償する責任を負うものとします。ただし、当社に故意または重過失があった場合にはこの限りではありません。 **第27条(保証の制限)** 1 当社は、本サービスが、重要な点において、実質的に正常に提供されることを保証します。 2 当社は、本サービスを構成する端末機器およびソフトウェアにバグ等の瑕疵のないことや、本サービスが契約者の特定の利用目的に合致することを保証するものではありません。また 当社は、端末機器において他のソフトウェア等が使用ないし併用された場合の、本サービスの正常な動作を保証するものではありません。 3 当社は、本サービスの運用において、通信回線、コンピュータ及び電子回路などの障害によるシステムの中断・遅滞・中止、データの損失、データへの不正アクセスがないことを保証するものではありません。 4 本サービスに重要な瑕疵が認められた場合における当社の責任は、商業的に合理的な範囲内において、本サービスの修正ないし瑕疵の除去の努力をすることに限られるものとします。 5 当社は、AIサービスの出力の正確性、信頼性、適時性、完全性および特定目的への適合性について保証しません。また、当社はMCPサーバーが外部AIサービスとの接続において常時利用可能であること、または特定の応答速度を維持することについても保証しません。 **第28条(免責および損害賠償の制限)** 1 当社は、本規約の各条項に従って制限された限度においてのみ、本サービスについての責任を負うものとします。当社は、本規約の各条項において保証しないとされている事項、責任を負わないとされている事項、契約者の責任とされている事項については、一切の責任を負いません。 2 当社は、当社の責めに帰すべき事由によって本サービスに関して契約者に損害が生じた場合であっても、当社に故意または重過失がある場合を除いて、その賠償責任は、契約者が当社に対して支払った過去6か月分の利用料金を上限とします。 3 当社が責任を負う場合であっても、契約者の事業機会の損失、逸失利益、データ滅失・損壊によって生じた損害については、契約責任、不法行為責任その他請求の原因を問わず、いかなる賠償責任も負いません。 4 AIサービスおよびMCPサーバーの利用に関して契約者に生じた損害については、当社に故意または重過失がある場合を除き、当社は一切の賠償責任を負わないものとします。当社が賠償責任を負う場合であっても、その範囲は第2項に定める上限額の範囲内とします。 8 MCPサーバーを経由した外部AIサービスによるアクセスに起因して、本サービスに保存されたデータの漏洩、改変または消失が生じた場合であっても、契約者がMCPサーバーの接続を許可する設定を行っていたときは、当社は責任を負いません。 **第29条(本サービスの休止)** 1 当社は、定時にまたは必要に応じて、保守作業のために、本サービスを一時的に休止することができるものとします。 2 当社は、保守作業を行う場合には、事前に契約者に対してその旨を通知するものとします。たたし、緊急の場合には、事前の通知をすることなく本サービスを休止し、事後速やかに契約者に通知するものとします。 3 当社は、外部AIサービス事業者の仕様変更、サービス停止その他事由により、本サービスの継続が困難と判断した場合、本サービスの全部または一部を一時的に休止することができるものとします。 4 第1項、第3項及び第5項に定めるほか、当社は、第三者による妨害行為等により本サービスの継続が契約者に重大な支障を与えるおそれがあると判断される場合、その他やむを得ない事由がある場合にも、本サービスを一時的に休止することができるものとします。 5 当社は、MCPサーバーを経由した外部からのアクセスにより本サービスまたは当社のシステムに過度な負荷が生じた場合、当該アクセスに関する本サービスの全部または一部を事前の通知なく休止することができるものとします。 6 当社は、本条に基づいてなされた本サービスの休止によって契約者に生じた不利益、損害について責任を負いません。 **第30条(本サービスの廃止)** 1 当社は、本サービスの一部または全部を何時でも廃止できる権利を有します。 2 本サービスの一部または全部を廃止する場合、当社は廃止する3か月以上前を目標として、最低限1週間前には当該サービスの契約者に対して通知を行います。 3 当社が予期し得ない事由または法令・規則の制定・改廃、天災等のやむを得ない事由で、サービスを廃止する場合において1週間以上前の通知が不能な場合であっても、当社は可能な限り速やかに契約者に対して通知を行います。 4 本条に定める手続に従って通知がなされたときは、当社は本サービスの廃止の結果について何ら責任を負いません。 **第31条(契約者が行う解除)** 1 契約者は、第6条第1項に定める期間は、利用契約を解除することができません。 2 契約者は、第6条第2項によって延長された利用契約の期間内に、契約者の都合により利用契約を解除しようとする場合は、解除しようとする日の1週間までに当社の指定する方法により、その旨を当社に通知するものとします。 **第32条(当社が行う解除)** 1 当社は、契約者が次の各号のいずれかに該当すると判断した場合、契約者への催告を要することなく利用契約の全部もしくは一部を解除することができるものとします。 (1)当社の事業に支障を与える行為を行った場合 (2)重要な財産に対する差押、仮差押、仮処分、租税滞納処分、その他公権力の処分を受け、または破産手続開始、民事再生手続開始、会社更生手続開始もしくは特別清算開始の申立てが行われた場合 (3)解散もしくは事業の全部を譲渡し、またはその決議がなされた場合 (4)自ら振り出しもしくは引き受けた手形または小切手が不渡りとなる等支払停止状態に至った場合 (5)監督官庁から営業停止、または営業免許もしくは営業登録の取消しの処分を受けた場合 (6)第5条第2項各号に掲げる事由の一つがある場合 (7)本サービスの利用にあたって、当社または外部AIサービス事業者その他第三者に損害を生じさせるおそれのある目的・方法で利用したまたは利用しようとした場合 (8)本規約に違反した場合 (9)外部AIサービスの利用規約に違反した場合 2 当社は、契約者が利用契約等に違反し、または契約者の責めに帰すべき事由によって本サービスの提供を継続し難い重大な事由が発生し(以下「違反等」という。)、当該違反等について、電子メールまたは書面による催告をしたにもかかわらず14日以内にこれを是正しないときは、利用契約の全部もしくは一部を解除することができるものとします。 **第33条(契約終了後の処理)** 1 契約者は、理由の如何を問わず利用契約が終了した場合、ただちに本サービスの利用を終了し、以後、本サービスを利用することはできません。 2 当社は、理由の如何を問わず利用契約が終了した場合、本サービスに格納された一切のデータを当社の責任で消去するものとします。 3 当社は、本条に基づいてデータを消去したことによって契約者に生じた損害を賠償する義務を負わないものとします。 4 利用契約の終了前に外部AIサービスに送信されたデータについて、当社は当該外部AIサービスにおける消去の義務を負わないものとします。契約者は、利用契約の終了に先立ち、必要に応じて外部AIサービスにおけるデータの削除を自ら行うものとします。 **第34条(通知)** 本サービスに関する通知その他本規約に定める当社から契約者に対する通知は、電子メールによる方法その他当社の定める方法によって行うものとします。通知は、当社からの発信によってその効力が生ずるものとします。 **第35条(権利義務譲渡の禁止)** 契約者は、利用契約の契約上の地位を第三者に承継させ、または利用契約に基づく権利義務の全部または一部を第三者に譲渡し、承継させ、または担保に供してはならないものとします。 **第36条(不可抗力)** 当社は、天災、法令・規則の制定・改廃、その他の不可抗力によって本サービスの履行が妨げられた場合には、利用契約その他の一切の規定にかかわらず、かかる不可抗力によって契約者に生じた損害について一切の責任を負担しません。 **第37条(協議)** 本規約の解釈について両当事者間に異議、疑義が生じた場合、または本規約に定めのない事項が生じた場合、誠実に協議し、円満にその解決を図るものとします。 **第38条(準拠法および裁判管轄)** 利用契約に関する事項については、日本法を準拠法とし、東京地方裁判所を第一審の専属的合意管轄裁判所とします。 --- 2026年4月6日 改訂 --- ## プライバシーポリシー URL: https://obniz.com/support/terms/privacy_policy 株式会社obniz(住所:東京都豊島区池袋2-36-1 INFINITY IKEBUKURO 6F、代表者:佐藤雄紀)(以下、「弊社」といいます。)はユーザーのプライバシーを尊重し、以下に定める「個人情報の取り扱いに関する方針」に従い、個人情報の取得、利用および保護を適切に行います。 # 個人情報の取り扱いに関する方針 弊社は、個人情報の保護に関する法律等の法令、[「電気通信事業における個人情報保護に関するガイドライン」](http://www.soumu.go.jp/main_content/000254517.pdf)及び社内諸規程等の諸規定を遵守し、企業活動の上で取り扱う個人情報について、これを適切に管理、保護し、お客様、取引先及び株主並びに弊社の役員及び社員等(以下、「従業者」といいます。)の利害関係者(以下、「お客様等」といいます。)が安心できる個人情報保護体制の運用・向上を目的として、プライバシーポリシーを以下のように定めます。 (取得する個人情報) 弊社が取得する個人情報は以下のものがあります。 1. 氏名、生年月日、性別、職業等プロフィールに関する情報 2. メールアドレス、電話番号、住所等連絡先に関する情報 3. クレジットカード情報、銀行口座情報、電子マネー情報等決済手段に関する情報 4. お客様等の肖像を含む静止画情報 5. 入力フォームその他弊社が定める方法を通じてお客様等が入力または送信する情報 6. その他弊社がお客様等の同意に基づき取得する情報 (利用目的の特定及び公表) 弊社は、以下の利用目的で個人情報を取得します。また、以下の目的以外で個人情報を取得する場合には、法令で別段の定めがある場合を除き、予めお客様等に対して利用目的を明示します。 1. 弊社の各サービスや商品(以下、「弊サービス等」といいます。)の提供・販売に伴い必要となる個人認証、利用登録、運用業務、料金等の請求・収納、決済に関する確認、与信管理、ならびに料金等の変更および弊サービス等の変更、追加もしくは廃止に係る事務処理、または通知をするため。また、上記に関わるお客様からのお問合せ対応を行うため。 2. 「サービスの利用状況」「サービス利用料金の課金状況および請求」など、弊サービス等の利用または提供に関する情報の案内を行うため。 3. 弊サービス等の運営や提供および営業活動における関連資料等の送付、または電話・メール・Fax等による弊サービス等に関する各種情報の案内を行うため。 4. 弊サービス等に関する情報の案内を行うため。 5. 弊サービス等を含む、弊社が提供するサービス・商品の改善を図るためのアンケート調査、および分析を行うため。 6. 弊サービス等を含む、弊社に関する新商品、新サービスの検討および開発を行うため。 7. 弊サービス等に関する機器の開発、保守および運用を行うため。 8. 弊サービス等に関するキャンペーンの実施を行うため。 9. 弊サービス等またはそれに付随する各種料金の税務・会計処理および請求収納や債権保全を行うため。(各種料金の請求収納の為、個人情報の取扱いを委託する場合を含みます) 10. 経営分析の為の統計数値作成および分析結果の利用を行うため。 11. 市場調査その他の調査研究を行うため。 12. 個人情報保護法に基づく開示請求などへの対応、ならびに個人情報取り扱いに関する監視および監査を行うため。 13. 第三者(提供する旨の同意を得た提供先に限る)への提供を行うため。 14. 国内外の公的機関からの請求による情報の開示を行うため。 15. その他、弊社がお客様等から事前に同意を得た範囲内での利用を行うため。 (利用目的の範囲内での利用) 弊社は利用目的の達成に必要な範囲内でのみお客様等の個人情報を取り扱い、利用目的の達成に必要な範囲を超えてお客様等の個人情報を取り扱う場合はお客様等の同意を取得します。但し、以下の一に該当する場合は、お客様等の同意なく利用目的の達成に必要な範囲を超えてお客様等の個人情報を取り扱うことがあります。 1. 法令に基づく場合 2. 人の生命、身体又は財産の保護のために必要がある場合であって、本人の同意を得ることが困難であるとき 3. 公衆衛生の向上又は児童の健全な育成の推進のために特に必要がある場合であって、本人の同意を得ることが困難であるとき 4. 国の機関若しくは地方公共団体又はその委託を受けた者が法令の定める事務を遂行することに対して協力する必要がある場合であって、本人の同意を得ることにより当該事務の遂行に支障を及ぼすおそれがあるとき (保存期間) 弊社は、法令で別段の定めがある場合を除き、利用目的に必要な範囲内でお客様等の個人情報の保存期間を定め、保存期間経過後又は利用目的達成後はお客様等の個人情報を遅滞なく消去しするよう努めます。但し、以下の一に該当する場合はこの限りではありません。 1. 法令の規定に基づき、保存しなければならないとき 2. 本人の同意があるとき 3. 電気通信事業者が自己の業務の遂行に必要な限度で個人情報を保存する場合で あって、当該個人情報を消去しないことについて相当な理由があるとき 4. 前3項に掲げる場合のほか、当該個人情報を消去しないことについて特別の理由があるとき (安全管理措置) 弊社は、お客様等の個人情報を正確かつ最新の内容に保つよう努めるとともに、不正なアクセス、改ざん、漏えい、滅失及び毀損から保護するため、必要かつ適切な安全管理措置として以下の措置を講じます。 1. 個人情報の適正な取扱いの確保のため、関係法令・ガイドライン等の遵守、質問及び苦情処理の窓口等を定める本プライバシーポリシーを策定します。 2. 個人情報の取得、利用、保存、提供、削除・廃棄等の段階ごとに、取扱方法、責任者・担当者及びその任務等について定める取扱規程を策定します。 3. 個人情報の取扱いに関する責任者を設置するとともに、個人情報を取り扱う従業者及び当該従業者が取り扱う個人情報の範囲を明確化し、法令や社内規程に違反している事実又は兆候を把握した場合の責任者への報告連絡体制を整備します。 4. お客様等の個人情報の安全管理が図られるよう従業者に対する必要かつ適切な監督をします。また、個人情報についての秘密保持に関する事項を就業規則に記載します。 5. 個人情報を取り扱う区域において、従業者の入退室管理等を行うとともに、権限を有しない者による個人情報の閲覧を防止する措置を実施します。 6. 個人情報を取り扱う情報システムを外部からの不正アクセス又は不正ソフトウェアから保護する仕組みを導入します。 (委託先の監督) 弊社は、お客様等の個人情報の取り扱いの全部又は一部を利用目的の範囲内で第三者に委託する場合があります。委託先の選定にあたっては、委託先が個人情報を適正に取り扱っていることを確認し、お客様等の個人情報の適正な取り扱いを求めます。また、当該契約には個人情報の取り扱いの監査に関する項目を含めるなど委託先に対して必要かつ適切な監督を行います。 (第三者への提供) 弊社は、以下の一に該当する場合、及び法令に別段の定めがある場合を除き、お客様等の同意を得ないで、第三者にお客様等の個人情報を提供することはありません。 1. 法令に基づく場合 2. 人の生命、身体又は財産の保護のために必要がある場合であって、本人の同意を得ることが困難であるとき 3. 公衆衛生の向上又は児童の健全な育成の推進のために特に必要がある場合であって、本人の同意を得ることが困難であるとき 4. 国の機関若しくは地方公共団体又はその委託を受けた者が法令の定める事務を遂行することに対して協力する必要がある場合であって、本人の同意を得ることに より当該事務の遂行に支障を及ぼすおそれがあるとき (共同利用等) 当社から個人情報の提供を受ける者が以下の一に該当する場合、弊社は、当該個人情報の提供を受ける者が「第三者」に該当しないものとして取り扱い、お客様等の同意を得ないで、お客様等の個人情報の取り扱いを第三者に委託し、提供し、又は特定の者と共同利用することがあります。 1. 利用目的の達成に必要な範囲内において個人情報の取扱いの全部又は一部を委託する場合 2. 合併その他の事由による事業の承継に伴って個人情報が提供される場合 3. 個人情報を特定の者との間で共同して利用する場合であって、その旨並びに共同して利用される個人情報の項目、共同して利用する者の範囲、利用する者の利用目的及び当該個人情報の管理について責任を有する者の氏名又は名称について、あらかじめ、本人に通知し、又は本人が容易に知り得る状態に置いているとき (開示等の請求等) お客様等が個人情報の利用目的の通知、個人情報の開示、訂正、追加若しくは削除又は個人情報の利用若しくは第三者への提供の停止を希望される場合は、下記の(苦情処理)の項目にて示すメールアドレスより弊社にご連絡の上弊社所定の手続きに従ってご請求下さい。 (苦情処理) 弊社は、個人情報の取り扱いに関するお客様等からの苦情その他お問合せについて迅速かつ適切に対応します。個人情報の取り扱いに関するご質問・苦情・ご相談・開示等の請求に係るお問い合わせなどがある場合は、以下のメールアドレス宛にご連絡ください。 supportteam@obniz.com (漏えい発生時の対応) お客様等の個人情報の漏えい等が発生した場合には、事実関係の個人情報保護委員会への報告やお客様等への通知などを、法令の求める範囲で迅速かつ適切に実施します。 (継続的改善) 弊社は、個人情報保護に関する内部規定の整備、従業者教育及び内部監査の実施などを通じて、社内における個人情報の取り扱いについて継続的な改善に努めます。 2021年3月1日 改訂 2021年10月1日 改訂 --- ## obnizサービス説明書 URL: https://obniz.com/support/terms/service ### 1. 提供するサービス 「クラウドサービス利用規約」に定めるサービスの期間内で、以下のサービスをご利用いただくことができます。 1. ご購入いただいたサービス - obniz Cloud 2. obnizの付帯サービス ### 2. 付帯サービスの概要 ご購入いただいたサービスに関する付帯サービスをご利用いただくことができます。なお、お客様にお申し込みいただいた各サービスのコース・プランによっては、一部の付帯サービスがご利用いただけない場合がございます。詳しくはobnizの料金表が記載されたWebサイトをご確認ください。 1. オンラインエディタ Web上でHTMLやブロックプログラムを使ってプログラミングを行うための開発環境です。 2. リポジトリ クラウド上にファイルを保存するサービスです。 3. サーバーレスイベント クラウド上で利用者が事前登録したソフトウェアを実行するサービスです。 4. デバイス管理 アカウントに紐づくデバイスに対してソフトウェアアップデートやセキュリティ設定を行えるサービスです。 5. 施設管理 デバイスをグルーピングしたり、設置作業のサポートを行うための設定に関するサービスです。 6. 課題 デバイスやサービスで発生した課題を管理・追跡・解決するためのサービスです。 7. アプリ 作成したソフトウェアを他のobnizユーザーに提供するまたは提供を受けるためのサービスです。 アカウントに紐づくデバイスに特定の働きをさせるためデバイスに対してインストール・アンインストールの操作を行うことで働きを有効・無効化するためのサービスです。アプリの動作条件は常時稼働・定期実行・Webページ閲覧中のみ実行などアプリにより多種多様に異なります。アプリは自アカウントで作成し自身または他のアカウントに対して公開・インストールの許容が可能です。 7.1 ブラウザアプリ ブラウザ上で稼働するアプリで、それをWebページとして開いているユーザーのブラウザ、もしくは指定されたきっかけを元にクラウド上のブラウザで定期または不定期に動作するアプリです。 7.2 ホステッドアプリ obnizCloudの外部で動作するシステム上でプログラムなどによりデバイスの働きを規定するアプリです。動作の内容及び条件は外部システムに依存します。 7.3 pipelineアプリ 指定の機器と指定の外部サービスとのデータ送受信を実現する「pipeline」というサービスを用いて作成・運用される常時稼働アプリです。 8. APIキー 自分がobniz上で管理するリソースを操作するための権限を提供するためのサービスです。 9. Wi-Fi MESH クラウド上で管理するデバイス同士を相互通信可能にし、それらをクラウドから操作可能にするためのサービスです。 10. pipeline 指定の機器と指定のインターネット上の外部サービスとのデータ送受信を含めた接続を行うための常時稼働サービスです。pipelineを利用する「pipelineアプリ」は常時稼働のアプリであり、デバイスにインストールすることで活用できます。 ### 3. テクニカルサポートサービスの概要 ご購入いただいたサービスについて、Webサイトよりお問い合わせいただくことができます。 ### 4. テクニカルサポートサービスの免責事項 テクニカルサポートサービスのご利用にあたり、以下の点についてあらかじめご了承ください。 お客様からのお問い合わせに対応が困難であると判断される場合等、ご要望にお応えしかねる場合がございます。また、弊社が推奨した動作環境でのご使用であっても、お客様のコンピューター内にインストールされている他社のサービスや製品が原因となる等、テクニカルサポートサービスをご利用いただいても動作状況が改善されない場合がございます。 ### サービスのメンテナンスについて 本サービスはサービスレベル目標(SLA)に別途定めるメンテナンスを行うことがあります。メンテナンス時には、提供するサービスのすべてもしくは一部をご利用いただけないことがあります。 [obniz Service Level Agreement](https://docs.google.com/spreadsheets/d/1Gh0kzer-NwbWE7eZv3ctKU9CwKePNIJJPmvsZa_7mAk/edit#gid=1947954971) --- ## 特定商取引に関する法律に基づく表記 URL: https://obniz.com/support/terms/tokusho 販売事業者名 株式会社 obniz 所在地 東京都豊島区池袋2-36-1 INFINITY IKEBUKURO 6F 代表者名 佐藤 雄紀 ホームページ https://obniz.com/ お問い合わせ先 URL:問い合わせフォーム E-Mail:supportteam@obniz.com※営業時間内に順次返信いたします(土日祝日・年末年始は休業)。 販売価格 サービスの料金はそれぞれの製品またはクラウドサービス料金表をご覧ください。 サービスの対価以外に必要な費用 インターネット利用のために必要となる通信料及び接続料(金額は、お客様が契約した各事業者にお問い合わせください。) 消費税 支払い方法 クレジットカード決済または請求書払い 支払い時期 クレジットカードの支払時期はクレジットカード会社の請求に従います。 サービスの提供開始時 有料機能利用への変更承諾、または課金開始承諾の直後となります。 返品・解約の対応 商品の特性上、返品が不可能であるため、手続き完了後のキャンセル・返金についてはお受けできません。 サービスの制限または条件 【手続きの制限】現在、設定期間中の有料機能利用のキャンセルに関わる当月分の利用料返金や日割りは、受け付けておりません。 --- ## obniz Now利用規約 URL: https://obniz.com/support/terms/now_terms **obniz Now利用規約** **第1条(本規約の目的)** 本規約は、株式会社obniz(以下「当社」という。)の提供するサービス「obniz Now」(以下「本サービス」といいます。理由の如何を問わずサービスの名称又は内容が変更された場合は、当該変更後のサービスを含みます。)について定めるものとします。 **第2条(用語の定義)** 本規約においては、次の用語はそれぞれ次の意味で使用します。 (1)利用契約:本規約に基づき当社と契約者との間に締結される本サービスの提供に関する契約 (2)申込者:当社に本サービスの提供を申し込む法人、機関等 (3)契約者:利用契約を当社と締結し、本サービスの提供を受ける法人、機関等 (4)端末機器:本サービスを利用するために電気通信回線を経由して当社の指定サーバに接続する端末機器であって契約者または契約者の顧客が利用するもの (5)ユーザID:契約者または契約者の顧客を識別するために用いられる符号 (6)AIサービス:本サービス内に搭載される機械学習・生成AIに基づく分析・解説・制御支援機能の総称 (7)MCPサーバー:AIエージェントが本サービスに接続し機器情報の取得や操作を行うためのModel Context Protocolに基づくサーバー機能 (8)AI生成コンテンツ:AIサービスが出力する分析結果・グラフ・説明文・操作提案等の一切 (9)保存データ:契約者または契約者の顧客が本サービスにおいて記録、入力または保存したデータの総称 (10)入力データ:契約者がAIサービスに入力するデータ(テキスト、数値、画像等を含みます。) (11)外部AIサービス:AIサービス・MCPサーバーその他の外部のサービスの総称 (12)外部AIサービス事業者:外部AIサービスのサービス提供者 **第3条(本規約の適用)** 1 当社は、利用契約の内容に従って本サービスの提供を行い、契約者は利用契約および当社が定める条件にてこれを利用するものとします。 2 本サービスの詳細については、別途当社が定めるサービスの仕様に従うものとします。 **第4条(本規約の変更)** 1 当社は、民法(明治29年法律第89号)第548条の4(定型約款の変更)の規定に基づき、本規約を変更することができます。 2 当社は、前項の規定により本規約を変更する場合、その効力発生日を定め、効力発生日の[14]日前までに、ウェブサイトへの掲載その他の適切な方法により、以下の事項を周知するものとします。 ①本規約を変更する旨 ②変更後の本規約の内容 ③効力発生日 3 契約者は、第28条の規定にかかわらず、前項の規定に従い周知をした日から効力発生日までの間に当社に通知することによって、利用契約を解除することができます。 **第5条(利用契約の申込み)** 1 申込者は、本規約の内容を承諾の上、当社が定める方法により、本サービス利用のための申込みを行うものとします。利用契約は、当社が当社所定の手続によって申込みを承諾したときに成立します。本規約は、利用契約の一部を構成します。 2 当社は、前項の規定にかかわらず、次の場合には、その利用契約の申込みを承諾しない、あるいは承諾を留保することがあります。 (1)申込者が実在しない場合 (2)当社所定の利用申込書に虚偽の記載または記入漏れがある場合 (3)申込者が過去に本サービスまたは当社が提供する他のサービスの代金支払いを遅延し、 または不正に免れようとしたことがある場合 (4)本サービスの利用目的が、評価、解析その他本来の目的と異なるものであると疑われる場合 (5)申込者またはその代表者、役員において、反社会的勢力(暴力団、暴力団員等をいう。以下、本条において同じ。)に該当するときまたはそのおそれがあるとき (6)その他当社が不適当と判断する相当の理由がある場合 3 前項に従い、当社が利用契約の申込みを承諾せず、あるいは承諾を留保する場合は、その旨を申込者(契約者)に通知します。ただし、当社は、承諾をしなかったことあるいは承諾を留保したことによる責任は負いません。 4 申込者は、反社会的勢力に該当しないことを含め第2項各号のいずれかに該当する場合は、当社に対して、本申込みをしてはならないものとします。また、契約者は利用契約成立後も、申込者自身及びその代表者その他の役員が、過去、現在および将来において反社会的勢力に該当しないことを確約するものとします。 **第6条(利用契約の期間)** 1 利用契約の契約期間は、本サービスの利用開始月(利用開始の申込みに対して当社が承諾した月または当社と契約者との間で合意した月をいいます。)から当社と契約者とで別途定める期間とします。 2 利用契約の解約のためには、契約者は別途当社が指定する手続きを行う必要があるものとし、契約者から解約の申し出のない限り利用契約の契約期間は存続するものとします。 **第7条(サービスの範囲)** 1 当社は、当社指定の条件下で、契約者が管理する端末機器から電気通信回線を経由して当社の指定サーバに接続することにより、本サービスを利用することのできる環境を提供します。 2  当社は、端末機器またはネットワーク回線の不具合などが生じた場合に、本サービスの提供を保証するものではありません。 **第8条(利用制限)** 1 本サービスは、契約者自身の用途若しくは契約者自身の顧客の用途での利用を目的として提供されるものであり、契約者は自ら本サービスを利用し、または顧客に本サービスの一部または全部を利用させることができるものとします。 2 契約者および契約者の顧客による本サービスの利用は端末機器から当社指定のURLへ接続することにより行われるものとし、別途当社が指定する場合を除き、本サービスを構成するソフトウェア自体をダウンロードしたり、コピーする等の方法により本サービスを構成するソフトウェアを入手することはできません。 3 契約者は、本サービスを顧客に利用させる場合、当該顧客に対し、本規約に定める条件を周知し、これに従わせるものとします。 **第9条(本サービスの変更)** 当社は、本サービスの機能追加、改善を目的として、当社の裁量により本サービスの一部の追加・変更を行うことがあります。ただし、当該追加・変更によって、変更前の本サービスのすべての機能・性能が維持されることを保証するものではありません。 **第10条(サービスレベル)** 1 当社は、別途当社が定めるサービスレベルの基準を満たすよう、商業的に合理的な努力をもって本サービスを提供します。 2 前項所定のサービスレベルは、特段の記述がない限り、本サービスに関する当社の努力目標を定めたものであり、不可抗力その他の事情により本サービスの提供が一時的に停止した場合を含め、本サービスの提供の程度がサービスレベルを下回った場合でも、当社は損害賠償その他いかなる責任も負わないものとします。 **第11条(ユーザIDおよびパスワード)** 1 ユーザIDおよびパスワードは、当社が定める方法および使用条件に基づいて当社が付与するものとします。 2 契約者は、自らの管理責任により、自らまたは自らの顧客のユーザIDおよびパスワードを不正使用されないよう厳格に管理するものとします。 3 当社は、ユーザIDおよびパスワードの不正利用によって契約者または契約者の顧客に生じた損害について責任を負いません。当社は、ユーザIDとパスワードの認証を行った後に行われた本サービスの利用行為については、すべて契約者に帰属するものとみなすことができます。 **第12条(顧客のユーザーID)** 契約者は、自らの顧客に本サービスを利用させる場合、顧客のユーザIDの付与、および顧客による本サービスの利用について責任を持ち、責任の及ぶ範囲において不正利用等が発生しないようにします。 **第13条(電気通信回線)** 1 契約者または契約者の顧客が使用する端末機器から本サービスに接続する電気通信回線は、接続する当事者の責任と費用負担において、確保、維持されるものとし、当社は一切の責任を負いません。 2 契約者は、当社が端末機器を提供する場合であっても、当該端末機器の携帯電話回線を利用した接続において、当該携帯電話回線を提供する通信事業者の電波状況やサービスエリア外、回線の輻輳、障害等により、本サービスの提供が困難または不可能となる可能性があることを認識し、同意するものとします。これらの事象により契約者またはその顧客に生じた損害について、当社は一切の責任を負わないものとします。 3 当社は、当社が端末機器を提供する場合であっても、当該端末機器の携帯電話回線を利用した接続において、当該携帯電話回線の通信速度及び品質を保証するものではありません。 4 MCPサーバーを経由した外部AIサービスからの接続に伴う通信量の増加により、当社が提供する携帯電話回線の通信容量の上限に達し、または通信速度が低下する場合があります。これにより本サービスの利用に支障が生じた場合であっても、当社は責任を負いません。 **第14条(データ管理等)** 1 当社は、契約者が本サービスにおいて利用する契約者のデータを第10条に定めるサービスレベルに従って取り扱うよう努めるものとします。 2 契約者または契約者の顧客が本サービスにおいて利用するデータは、本サービスに記録、入力または保存された日から、契約プランまたは個別の見積もりにて別途定める保存期間(以下「保存期間」といいます。)の間、Webブラウザ上で確認が可能です。保存期間を経過したデータについては自動的に消去されますので、契約者においてデータの保存等を定期的に行うことを推奨します。 3 当社は、本サービスを提供する設備等の故障等による場合であるか否かを問わず、契約者が本サービスにおいて利用するデータが滅失または毀損した場合であっても、それが当社の故意または重大な過失により生じた場合を除き、契約者その他第三者に対して賠償等の責任を負わないものとします。また、この場合、当社は、データの復元の義務を負うものではありません。 4 当社は、障害、誤操作等による滅失からの復旧を目的として、契約者の入力、登録したデータを保存するための機能を当社の定める内容にて提供します。ただし、すべてのデータが当該機能によって保存、復元されることを保証するものではありません。なお、当該機能によって復元をする場合は、当社が有償で対応します。 5 当社は、利用契約の有効期間が期間満了その他の理由により終了した場合には、契約者および契約者の顧客が本サービスで利用しているデータを消去します。この場合、再契約など、いかなる理由においても、当社はデータの復旧は行いません。 6 AIサービスの精度向上を目的として、契約者の保存データおよびAIへの入力データを匿名化・統計処理した上で利用する場合があります。契約者は設定画面よりこれを拒否することができます。 7 MCPサーバーを経由して外部AIサービスに送信されるデータの内容および範囲は、契約者が設定した接続許可の範囲に基づくものとし、当該データが外部AIサービスにおいてどのように処理、保存または利用されるかについて、当社は関知せず、責任を負いません。契約者は、外部AIサービスの利用規約およびプライバシーポリシーを自ら確認の上、MCPサーバーの接続設定を行うものとします。 8 本サービスにおいて保存期間内に保存されているデータがMCPサーバーまたはAIサービスを経由して外部に送信された場合、当該データの外部における保存期間および削除の時期について、当社は管理する義務を負わず、責任を負いません。 **第15条(個人情報の管理)** 1 当社は、原則として本サービスに入力または保存されるデータに含まれる個人情報を取り扱わないものとします。 2 当社は、契約者が本サービスの利用を申し込むにあたって当社に提出する個人情報について、本サービス提供の目的以外で利用しないものとし、個人情報の保護に関する法律および当社個人情報保護方針に基づいて、紛失・破壊・改竄・漏洩等の危険から保護するための合理的な安全管理措置を講じ、厳重に管理するものとします。 3 当社は、本サービスの提供のため必要がなくなった前項所定の個人情報に関して、一切のコピーを残すことなく、当社責任のもとで速やかに破棄するものとします。 4 契約者は、本条第2項に定める場合を除き、AIサービスの利用にあたって、個人情報、機密情報その他の秘匿性の高い情報(以下「個人情報等」といいます。)を入力する等、当社に個人情報等を提供してはならないものとします。契約者がAIサービスの利用にあたり個人情報等を入力したことに起因して生じた損害について当社は一切の責任を負いません。 5 本条の規定は、利用契約が終了した後も有効に存続するものとします。 **第16条(当社による情報の管理・利用)** 1 当社は、本サービスの改良、サービスの維持管理等を目的とする統計調査のため、契約者の本サービスの利用状況、画面・項目の利用頻度等の統計数値を利用し、あるいは統計調査に必要な限度でこれらの情報を解析し、二次加工して活用するものとし、契約者はかかる統計調査、二次加工活用を行うことに同意します。 2 当社は、契約者が入力したデータ及び当社が指定するサーバとの通信に関し、善良な管理者による注意をもって機密保持とその管理に努めるものとします。 3 契約者は、当社が、裁判所、その他の法的な権限のある官公庁の命令等により本サービスに関する情報の開示ないし提出を求められた場合は、かかる命令等に従って情報の開示ないし提出をすることがあることを承諾し、かかる開示ないし提出に対して異議を述べないものとします。 4 当社は、契約者が本サービスを利用するに際し、当社に提供、入力またはアップロードした一切の情報及び本サービスにおいて、AIサービスを利用して生成され、契約者に提供された一切の情報その他情報を運営上一定期間保存していた場合であっても、かかる情報を保存する義務を負うものではなく、当社はいつでもこれらの情報を削除できるものとします。なお、当社はこれらの情報を削除したことにつき契約者等に生じた損害について、当社は責任を負いません。 5 当社は、前項で一定期間保存していた情報の削除を要請された場合であっても、これに応じる義務を負いません。ただし、個人情報の保護に関する法律その他の法令により当社が削除義務を負う場合はこの限りではありません。 **第17条(AIサービス)** 1 AIサービスは、契約者によるデータの分析、可視化および操作の意思決定を補助する目的で提供されるものであり、AIサービスの出力に基づく最終的な判断および操作の実行は、契約者の責任において行うものとします。 2 AIサービスの出力内容は、生成AIの技術的特性上、事実と異なる情報、不正確な分析結果または不適切な操作提案を含む可能性があり、当社はその正確性、完全性、再現性、特定目的への適合性その他一切について保証しません。 3 AIサービスの出力に基づいて契約者または契約者の顧客が行った操作・判断により、契約者、契約者の顧客または第三者に生じた損害について、当社は責任を負いません。 4 当社は、AIサービスの提供にあたり、当社が選定する第三者の外部AIプロバイダーのAPI等を利用する場合があります。ただし、本サービスは外部AIサービスとの連携を保証するものではなく、外部AIプロバイダーの仕様変更、サービス停止その他の事由により、AIサービスの全部または一部が利用できなくなった場合であっても、当社は責任を負いません。 5 契約者は外部AIサービスの利用規約を自己の責任で遵守し、契約者と外部AIサービス事業者との間で紛争等が生じた場合であっても、当社は一切の責任を負いません。 6 AI生成コンテンツに関する著作権その他の知的財産権は、法令に別段の定めがある場合を除き、当社に帰属するものとします。ただし、契約者が入力したデータに関する権利は契約者に留保されます 7 契約者は、AI生成コンテンツが第三者の知的財産権その他の権利を侵害しないことについて当社が保証しないことを了承し、AI生成コンテンツの利用に起因して第三者との間で紛争が生じた場合は、契約者の責任と費用において解決するものとします。 **第17条の2(AIサービスにおける入力データの取扱い)** 1 入力データに関する権利は、契約者に帰属します。 2 当社は、入力データを、AIサービスの提供(外部AIプロバイダーへのAPI送信を含みます。)の目的でのみ利用するものとし、契約者の同意なく第三者に開示しません。ただし、第16条第3項に定める場合はこの限りではありません。 3 当社は、入力データが外部AIプロバイダーに送信された後の当該プロバイダーにおける取扱いについて、商業的に合理的な範囲で適切なプロバイダーを選定する義務を負いますが、当該プロバイダーによるデータの取扱いについて保証するものではありません。 4 本サービスにおける保存データがAIサービスの入力として利用される場合、当該保存データに関する第14条の規定は引き続き適用されるものとします。ただし、AIサービスを通じて外部AIプロバイダーに送信された後のデータの取扱いについては、本条の規定が優先して適用されるものとします。 **第18条(MCPサーバーおよびAIエージェントからの利用)** 1 MCPサーバーは、外部のAIエージェントが本サービスに接続し、端末機器の情報取得および操作を行うためのインターフェースとして提供されます。MCPサーバーの利用にあたっては、当社が定める認証方式および利用条件に従うものとします。 2 MCPサーバーへのアクセスに使用する認証情報(APIキー、トークン等)の発行、管理および失効処理は契約者の責任とし、認証情報の漏洩、不正利用等により契約者または第三者に生じた損害について当社は責任を負いません。 3 契約者がMCPサーバー経由での端末機器の操作を許可する設定を行った場合、当該設定に基づきAIエージェントが実行した操作はすべて契約者の指示に基づくものとみなし、その操作結果(機器の誤動作、意図しない制御、データの損失等を含みます。)について当社は責任を負いません。 4 契約者は、MCPサーバーを通じて接続する外部AIサービスの選定、設定および監視について自らの責任で行うものとし、当該外部AIサービスの不具合、誤判断またはセキュリティ上の脆弱性に起因して生じた損害について当社は責任を負いません。 5 当社は、MCPサーバーの安全性確保のため、接続頻度の制限、特定の操作の制限その他必要な措置を事前の通知なく講じることができるものとします。 6 契約者は、MCPサーバーを利用する場合、人の生命、身体または財産に危険を及ぼすおそれのある用途において、AIエージェントによる自律的な操作のみに依存してはならず、適切な人的監視および安全措置を講じるものとし契約者がかかる適切な人的監視および安全装置を講じることを怠ったことにより損害が発生したとしても、当社は一切の責任を負いません。 7 MCPサーバーを経由した外部AIサービスからのアクセスにより、本サービスにおいて保存されているデータ(保存期間内のセンサーデータ、設定情報等を含みます。)が当該外部AIサービスに送信される場合があります。契約者は、MCPサーバーの接続を許可することにより、当該接続許可の範囲において保存データが外部に送信されることに同意するものとします。 **第19条(利用料金の支払方法)** 1 契約者は、利用契約が有効である期間について、本サービスの利用料金およびこれにかかる消費税等(以下「利用料金等」という。)を支払うものとします。 2 利用契約の契約期間において、本サービスの提供の休止、中止その他の事由により本サービスを利用することができない状態が生じたときであっても、契約者は、契約期間中の利用料金等を支払うものとします。 3 契約者は、本サービスの利用料金等を、当社からの請求書に従い当社が指定する期日までに当社指定の金融機関に支払うものとします。なお、支払いに必要な振込手数料その他の費用は、契約者の負担とします。 4 前各項に定める本サービスの利用料金の支払いは、当社が当社に代理して本サービスの利用料金を受領する第三者を指定した場合には、契約者は当該第三者に前項に準じて本サービスの利用料金の支払いを行うものとします。 5 AIサービスの利用に伴い、当社が利用する外部AIプロバイダーのAPI使用量等に応じて、追加料金が発生する場合があります。料金体系の詳細は別途サービス説明書または当社ウェブサイトに定めるものとし、料金体系を変更する場合は第4条の定めに従うものとします。 6 MCPサーバーを経由した外部AIサービスからのアクセスに伴い、当社が提供する携帯電話回線の通信量が増加した場合、契約プランに定める通信量の上限を超過した分について、別途当社が定める超過料金が発生する場合があります。 **第20条(遅延損害金)** 契約者が、本サービスの利用料金等を所定の支払期日が過ぎてもなお支払わない場合、契約者は、所定の支払期日の翌日から支払日の前日までの日数に、年14.6%の利率で計算した金額を遅延損害金として支払うものとします。 **第21条(委託)** 当社は本サービスの提供に関する業務の全部もしくは一部を契約者の承諾なしに、第三者に委託することができます。ただし、その場合、当社は責任をもって委託先を管理するものとします。 **第22条(禁止行為)** 契約者は、本サービスを利用するにあたり、以下の行為を行わないものとします。 (1)法令に違反する行為またはそのおそれがある行為 (2)公序良俗に反する行為 (3)他の契約者の利用を妨害する行為またはそのおそれがある行為 (4)本サービスを構成するハードウェアまたはソフトウェアへの不正アクセス行為、クラッキング行為その他設備等に支障を与える等の行為 (5)本サービスの提供を妨害する行為またはそのおそれがある行為 (6)本サービスを構成するソフトウェアの解析、リバースエンジニアリングその他ソースコードを入手しようとする行為 (7)他の契約者のユーザ IDを使用する行為またはその入手を試みる行為 (8)他の契約者のデータを閲覧、変更、改竄する行為またはそのおそれがある行為 (9)当社または外部AIサービス事業者その他第三者の知的財産権、肖像権、名誉権、プライバシー権その他権利を侵害する行為 (10)私的利用または内部利用以外の目的でAI生成コンテンツを利用(複製、公衆送信等)する行為 (11)AIサービスを利用して、第三者を誤認させる目的で事実と異なる情報を生成・流布する行為 (12)MCPサーバーを経由して、当社または第三者の機器・システムに対して不当な負荷をかける、または損害を与える行為 (13)AIサービスの出力を、人間による確認を経ずに、人の生命、身体もしくは財産に影響を及ぼしうる機器の制御に直接使用する行為 (14)MCPサーバーを経由して、当社が提供するAPI仕様に定めのない方法により本サービスにアクセスし、またはアクセスを試みる行為 (15)外部AIサービスを利用して、当社または第三者のシステムの脆弱性を探知し、またはこれを悪用する行為 (16)AIサービスに対し、本来の利用目的を逸脱した入力(プロンプトインジェクション、ジェイルブレイク等を含みます。)を行い、AIサービスの制御を回避しまたは不正な出力を誘発する行為 (17)MCPサーバーを経由して、本サービスに保存されたデータを大量に抽出し、当社が提供するサービスと競合するサービスの開発または提供に利用する行為 (18)当社が提供する携帯電話回線を、本サービスの利用目的以外の用途に使用する行為 (19)外部AIサービスの利用規約に抵触する行為 **第23条(知的財産権)** 1 本サービスを構成する有形・無形の構成物(端末機器、ソフトウェアプログラム、データベース、AI生成コンテンツ、アイコン、画像、文章マニュアル等の関連ドキュメント等を含む。)に関する著作権を含む一切の知的財産権、その他の権利は、当社または当社に許諾した第三者に帰属します。 2 当社は、契約者に対し、前項に規定する知的財産権その他の権利(特許第6439954号および特許第6519765号を含みますが、これに限られません)について、契約者および契約者の顧客による本サービスの利用に必要な限りにおいて、本サービスを非独占的に利用する権利を供与します。なお、前項に規定する知的財産権の一部が消滅・無効となった場合でも、既にお支払いいただいた利用料金の返金、将来的な利用料金の減額はいたしません。 **第24条(侵害の場合の責任)** 1 本サービスの利用に関して、第三者から契約者に対して知的財産にかかるクレーム、その他の請求が発生した場合、契約者はただちに当社に書面で通知するものとし、当社はその責任と負担においてかかるクレーム等を処理するものとします。ただし、かかるクレーム等の発生が契約者自身の責めに帰すべき事由に基づく場合および契約者が当社にクレーム等の発生を速やかに通知しない等の事由により当社が適切な防御を行う機会を逸することになった場合は、この限りではありません。 2 前項の規定にかかわらず、AIサービスに関しては、生成AIの技術的特性上、AI生成コンテンツが第三者の知的財産権を侵害しないことについて当社は保証しません。AI生成コンテンツの利用により第三者から契約者に対してクレームその他の請求がなされた場合、前項に基づく当社の対応義務は適用されないものとし、契約者が自己の責任と費用において対応するものとします。 **第25条(自己責任の原則)** 1 契約者は、契約者および契約者の顧客(以下本条で「契約者等」といいます。)による本サービスの利用および本サービス内における一切の行為(情報の登録、閲覧、削除、送信等)およびその結果について、一切の責任を負います。 2 契約者は、契約者等による本サービスの利用に伴い、当該契約者等の責めに帰すべき事由で外部AIサービス事業者もしくは第三者に対して損害を与えた場合、または第三者からクレーム等の請求がなされた場合、自己の責任と費用をもって処理、解決するものとします。 3 契約者は、契約者がその故意または過失により当社に損害を与えた場合、当社に対して、当該損害の賠償を行うものとします。 4 当社が、他のユーザ、外部AIサービス事業者または第三者から、契約者の本サービスの利用に関連して、権利侵害その他の他の理由により何らかの請求を受けた場合、契約者は当社が負担すべき当該請求の金額につき、当社に対して賠償する責任を負うものとします。ただし、当社に故意または重過失があった場合にはこの限りではありません。 **第26条(保証の制限)** 1 当社は、本サービスが、重要な点において、実質的に正常に提供されることを保証します。 2 当社は、本サービスを構成する機器およびソフトウェアや契約者またはその顧客が本サービスとともに用いる機器およびソフトウェアにバグ等の瑕疵のないことや、本サービスが契約者の特定の利用目的に合致することを保証するものではありません。また 当社は、端末機器において他のソフトウェア等が使用ないし併用された場合の、本サービスの正常な動作を保証するものではありません。 3 当社は、本サービスの運用において、通信回線、コンピュータ及び電子回路などの障害によるシステムの中断・遅滞・中止、データの損失、データへの不正アクセスがないことを保証するものではありません。その他、契約者またはその顧客若しくは第三者の責に帰すべき事由に起因する本サービスの提供不能、不具合については当社は何らの責任も負いません。 4 本サービスに重要な瑕疵が認められた場合における当社の責任は、商業的に合理的な範囲内において、本サービスの修正ないし瑕疵の除去の努力をすることに限られるものとします。 5 当社は、AIサービスの出力の正確性、信頼性、適時性、完全性および特定目的への適合性について保証しません。また、当社はMCPサーバーが外部AIサービスとの接続において常時利用可能であること、または特定の応答速度を維持することについても保証しません。 6 当社は、当社が提供する携帯電話回線について、MCPサーバーまたはAIサービスの利用に伴う通信量の増加により、契約者が期待する通信速度または通信品質が維持されることを保証しません。 **第27条(免責および損害賠償の制限)** 1 当社は、本規約の各条項に従って制限された限度においてのみ、本サービスについての責任を負うものとします。当社は、本規約の各条項において保証しないとされている事項、責任を負わないとされている事項、契約者の責任とされている事項については、一切の責任を負いません。 2 当社は、当社の責めに帰すべき事由によって本サービスに関して契約者に損害が生じた場合であっても、当社に故意または重過失がある場合を除いて、その賠償責任は、契約者が当社に対して支払った過去6か月分の利用料金を上限とします。 3 当社が責任を負う場合であっても、契約者の事業機会の損失、逸失利益、データ滅失・損壊によって生じた損害については、契約責任、不法行為責任その他請求の原因を問わず、いかなる賠償責任も負いません。 4 当社は、本サービスの提供にあたり、第三者が提供する通信インフラ、クラウドサービス、データセンター等に起因して契約者に生じた損害について、一切の責任を負いません。 5 当社が指定または推奨する他社製のセンサーや機器に関して、製造元による販売又はサポートの終了、性能不良、障害、互換性の喪失等が生じた場合であっても、当社は本サービスの継続提供に責任を負わないものとします。また、契約者は、かかる事象を理由として、利用契約を終了させることはできず、当社に対する本サービスの利用料金の支払いを拒むことはできないものとします。 6 契約者が、本規約のいずれかの条項に違反して当社に損害(弁護士費用も含みます)を発生させたときは、これを賠償する責任を負います。 7 AIサービスおよびMCPサーバーの利用に関して契約者に生じた損害については、当社に故意または重過失がある場合を除き、当社は一切の賠償責任を負わないものとします。当社が賠償責任を負う場合であっても、その範囲は第2項に定める上限額の範囲内とします。 8 MCPサーバーを経由した外部AIサービスによるアクセスに起因して、本サービスに保存されたデータの漏洩、改変または消失が生じた場合であっても、契約者がMCPサーバーの接続を許可する設定を行っていたときは、当社は責任を負いません。 **第28条(本サービスの休止)** 1 当社は、定時にまたは必要に応じて、保守作業のために、本サービスを一時的に休止することができるものとします。 2 当社は、保守作業を行う場合には、事前に契約者に対してその旨を通知するものとします。ただし、緊急の場合には、事前の通知をすることなく本サービスを休止し、事後速やかに契約者に通知するものとします。 3 当社は、外部AIサービス事業者の仕様変更、サービス停止その他事由により、本サービスの継続が困難と判断した場合、本サービスの全部または一部を一時的に休止することができるものとします。 4 第1項、第3項及び第5項に定めるほか、当社は、第三者による妨害行為等により本サービスの継続が契約者に重大な支障を与えるおそれがあると判断される場合、その他やむを得ない事由がある場合にも、本サービスを一時的に休止することができるものとします。 5 当社は、MCPサーバーを経由した外部からのアクセスにより本サービスまたは当社のシステムに過度な負荷が生じた場合、当該アクセスに関する本サービスの全部または一部を事前の通知なく休止することができるものとします。 6 当社は、本条に基づいてなされた本サービスの休止によって契約者に生じた不利益、損害について責任を負いません。 **第29条(本サービスの廃止)** 1 当社は、本サービスの一部または全部を何時でも廃止できる権利を有します。 2 本サービスの一部または全部を廃止する場合、当社は廃止する3か月以上前を目標として、最低限1週間前には当該サービスの契約者に対して通知を行います。 3 当社が予期し得ない事由または法令・規則の制定・改廃、天災等のやむを得ない事由で、サービスを廃止する場合において1週間以上前の通知が不能な場合であっても、当社は可能な限り速やかに契約者に対して通知を行います。 4 本条に定める手続に従って通知がなされたときは、当社は本サービスの廃止の結果について何ら責任を負いません。 **第30条(契約者が行う解除)** 1 契約者は、第6条第1項に定める期間は、利用契約を解除することができません。 2 契約者は、第6条第2項によって延長された利用契約の期間内に、契約者の都合により利用契約を解除しようとする場合は、解除しようとする日の1週間までに当社の指定する方法により、その旨を当社に通知するものとします。 **第31条(当社が行う解除)** 1 当社は、申込者または契約者が次の各号のいずれかに該当すると判断した場合、契約者への催告を要することなく利用契約の全部もしくは一部を解除することができるものとします。 (1)当社の事業に支障を与える行為を行った場合 (2)重要な財産に対する差押、仮差押、仮処分、租税滞納処分、その他公権力の処分を受け、または破産手続開始、民事再生手続開始、会社更生手続開始もしくは特別清算開始の申立てが行われた場合 (3)解散もしくは事業の全部を譲渡し、またはその決議がなされた場合 (4)自ら振り出しもしくは引き受けた手形または小切手が不渡りとなる等支払停止状態に至った場合 (5)監督官庁から営業停止、または営業免許もしくは営業登録の取消しの処分を受けた場合 (6)第5条第2項各号に掲げる事由の一つがある場合 (7)第5条第4項に違反すると当社が判断した場合 (8)本サービスの利用にあたって、当社または外部AIサービス事業者その他第三者に損害を生じさせるおそれのある目的・方法で利用したまたは利用しようとした場合 (9)本規約に違反した場合 (10)外部AIサービスの利用規約に違反した場合 2 当社は、契約者が利用契約等に違反し、または契約者の責めに帰すべき事由によって本サービスの提供を継続し難い重大な事由が発生し(以下「違反等」という。)、当該違反等について、電子メールまたは書面による催告をしたにもかかわらず14日以内にこれを是正しないときは、利用契約の全部もしくは一部を解除することができるものとします。 **第32条(契約終了後の処理)** 1 契約者は、理由の如何を問わず利用契約が終了した場合、ただちに本サービスの利用を終了し、以後、本サービスを利用することはできません。 2 当社は、理由の如何を問わず利用契約が終了した場合、本サービスに格納された一切のデータを当社の責任で消去するものとします。 3 当社は、本条に基づいてデータを消去したことによって契約者に生じた損害を賠償する義務を負わないものとします。 4 利用契約の終了前に外部AIサービスに送信されたデータについて、当社は当該外部AIサービスにおける消去の義務を負わないものとします。契約者は、利用契約の終了に先立ち、必要に応じて外部AIサービスにおけるデータの削除を自ら行うものとします。 **第33条(通知)** 本サービスに関する通知その他本規約に定める当社から契約者に対する通知は、電子メールによる方法その他当社の定める方法によって行うものとします。通知は、当社からの発信によってその効力が生ずるものとします。 **第34条(権利義務譲渡の禁止)** 契約者は、利用契約の契約上の地位を第三者に承継させ、または利用契約に基づく権利義務の全部または一部を第三者に譲渡し、承継させ、または担保に供してはならないものとします。 **第35条(不可抗力)** 当社は、天災、法令・規則の制定・改廃、その他の不可抗力によって本サービスの履行が妨げられた場合には、利用契約その他の一切の規定にかかわらず、かかる不可抗力によって契約者に生じた損害について一切の責任を負担しません。 **第36条(協議)** 本規約の解釈について両当事者間に異議、疑義が生じた場合、または本規約に定めのない事項が生じた場合、誠実に協議し、円満にその解決を図るものとします。 **第37条(準拠法および裁判管轄)** 利用契約に関する事項については、日本法を準拠法とし、東京地方裁判所を第一審の専属的合意管轄裁判所とします。 --- 2022年10月27日 制定 2025年09月19日 改定 2026年4月6日 改定