# IoT & Architecture
**Hana Osman**
**ho222kd**
## Project Description:
IoT is an important source of information in our day-to-day life.
As an architect, I believe that there is a gap in utilizing the information
gathered through IoT devices to better the design process of our cities.
My project idea is to collect data from IoT device and visulaize this data through 3D modeling software such as Rhino and Grasshopper, The aim is to use the data in order to create more acurate maps and architectural designes.
### Estimated project time:
For a beginner like me the project can take up to one and half or two weeks of full time 8hours work, to gather enough information about IoT, Hardware, software, sensors, connecting to pybytes in order to send data collected from our sensors to the cloud, and then setting up and choosing the right network to send and recieve data from (Lora, Sigfox, Hellium or TTN), Follows that the actual visulalization of data through 3D modeling softwares.
For an expert, I imagine the project can take a day or two. :)
## Objective:
### Why **IoT and Architecture** project?
As I am currently preparing to write my masters' degree thesis in Architecture and Urban Design, I am aiming to develop a mapping method that could give a database for a better and more informed design process of our buildings and our cities.
-This initial idea of the project is an inspiration of three main keywords:
**1. Data visualization**
**2. computatonal design**
**3. 3D Printing**
There are tools that could help us use the data collected from sensors and visualize this Data on a 3D Modeling softwares, By usiang these tools combined with real-time data we can give architects an additional, more accurate-to-site guidline and reference for their design.
### What purpose does this project serve?
IoT devices has been playing an important role in creating a more connected and sustainable world, by collecting live data from users all over the world we can create a more adaptive architecture and city planning of our world.
By using infomration gathard via sensors for a specific prospective site for a building we can uderstand the actual environmental features such as (Sun, Heat, Wind, sound,...etc) of the site, and further more we can map social habits, animals, urban development, political and economical impact on the development of our cities. all of which can create a tool for architects to create a more specific-designes using a more specific data for the task at hand.
Not to mention that If the project was to be developmed properly, it could be used by Urban planner, Landscape architects, Civil engineers...etc
### What insights you think the project will give?
By creating my very first IoT device I can undestand the idea of how data visualization actually works, and then I can manipulate the types of snesors and combination of their data in order to generate architectural proposals for the specific purpose I choose to exersice.
What I am really hoping for is to experiament with the results i get from my IoT device, and use computational design as a tool to visualize this data, There could be much for us to learn from these tools as a method to develop future architecture and cities.
## List of material:
### List of material:
- **Lopy4 and Sensors Bundle:**
https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-lopy4-and-sensors-bundle/
- **25 Module Kit:**
https://www.electrokit.com/produkt/sensor-kit-26-moduler/
- **Lipo battery with JST connector:** Optional, Only if you wish to run your device away from the computer
https://www.electrokit.com/produkt/batteri-lipo-3-7v-4400mah/
### What the different things (sensors, wires, controllers)?
Since the project is still at a young stage it is still fairly simple, for this IoT device you will need:
1. LoPy4 with headers
2. Expansion board
3. Antennae
4. Micro USB cable
5. Jumper wire
6. Breadboard
7. Photoresistor sensor or Light sensor
8.
Last but not least... a Laptop!
### Where to buy the material and how much do they cost?
It was recommended by our course teachers that we can buy our material from Electokit, it is a private company based in Sweden that sell their products all over EU and a number of contries world-side.
https://www.electrokit.com/en/
- **Lopy4 and Sensors Bundle:** costs around 950kr.
https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-lopy4-and-sensors-bundle/
- **25 Module Kit:** costs around 300kr.
https://www.electrokit.com/produkt/sensor-kit-26-moduler/
- **Lipo battery with JST connector:** Optional, costs around 250kr.
https://www.electrokit.com/produkt/batteri-lipo-3-7v-4400mah/
The over all **cost of material** is:
**1250Kr** without battery.
**1500Kr** including battery.
## Computer setup:
with in this section you will learn about how to:
- [x] - Choose IDE
- [x] - How the code is uploaded
- [x] - Steps that you needed to do for your computer. Installation of Node.js, extra drivers, etc.
We are going to start with setting up our computers and our devics.
The **material** we need for this stage is:
* Pycom device (Lopy4)
* Expansion board
* USB cable
To start we need to:
**1.** connect our pycom device to the compute using the USB cable.
**2.** [Update Device Firware](https://https://docs.pycom.io/updatefirmware/device/): updating your device firmware can make it easier for your device to connect to pybytes, you can do this through out any stage of the work process. You can also find download link for the pycom firmwar updater on the same link shown at number **2**
Please note that you might need to update both your **expansion board firmware** and your **device firmware**,
If your expansion board is new (just like mine was) then you don't need to update it, but if it is an old one then you might need to refer to this [tutorial](https://https://docs.pycom.io/updatefirmware/expansionboard/) for updating it.
**3.** Now it's time to set up your computers with the required softwares:
* **Node.js**:
In order to istall Node.js on your computer you need to use this [link](https://https://nodejs.org/en/)
* **Integrated Development Environment: (IDE)**
you can choose between **VSCode** or **Atom**, Both editors contain a number of extentions that are easily controlled, **Atom** might need extensions and third-party applications in order to achieve some features that are otherwise built_in **VSCode**. As far as my knowledge extends, **VSCode** is more efficient for a smoother overall fast excersice. And thus why I chose to work with **VSCode** in this tutorial and will be providing links about **VSCode**. :)
**VS Code**:
-[VSCode & Pymakr Step-By-Step Tutorial For Windows](https://https://hackmd.io/a1Nq_9kqR0CZBrYL1xNJDg)
-[VSCode & Pymakr Step-By-Step Tutorial For Linux](https://https://hackmd.io/@lnu-iot/By-h1SRou)
-[Setting up Visual Studio Code](https://https://code.visualstudio.com/docs/setup/setup-overview):
This stage can have some challenges, Just make sure that your device is connected to the righ USB port as is written in the Global Settings at `"address": "COMxxx",`, and personaly it worked better when I set `"auto_connect": false,` Don't forget to save the file `Ctrl+s` before running the code you modify.
-[Setup Pymakr for Vscode](https://https://docs.pycom.io/gettingstarted/software/vscode/):
This will help you install the [pymakr VSCode extension](https://https://marketplace.visualstudio.com/items?itemName=pycom.Pymakr) and after that you will connect Pymakr to the right serial port (USB port), It is fairly simple, Search for **Pymakr** in Extensions page (on the left bar of the VSCode window) and when you find it press install! :)
If all goes well, Your Pycom device should be up and running and ready to connect your sensors and run your python code file! :D
You can upload your code by creating a New Folder, Pick a name for that folder and add a new file to that folder with the name `main.py` you can then paste your code on the `main.py` foler or write your own code, Note that you can pick an already written code from the library and open the folder to run the code.
## Putting everything together:
In order to understand how electronics connected, we need to understand electrics circuits, According to Ohm's Law, (The most basic law to understand circuits), we need to understand the notions of Voltage, Current and resistance.
`V=IR`
Voltage (V): is potential energy per unit charge.
Current (I): The amount of charge flowing past a point in a cercuit in a unit of time (second).
Resistance ( R): The amount of charge flow impeded.
### Photoresistor sensor:

the image above shows a Photoresistor sensor diagram.
**( R ):** refering to the **resistance**, Resistance preformance is different during full light and full darkness, As the light on the photorresistor increases the resistance decreases.
**( S ):** refers to **pin 1** on the sensor and it should be connected to the P pin on the pycom device. **P** on the circuit refers to the rate of energy within a circuit. and is a pin with ADC capabilities, and it is resposible for recieving the input signal from the sensor and converting it to a digital format that the computer can process.
For the photoresistor sensor I needed to connect My sensor to the **P20** on my Pycom device.
**( - ):** means that **pin 3** on the sensor should be connected to the **GND** pin on the pycom device, **GND** means **Ground** , Which defines the reference point where voltage can be measured from (0V).
**Pin 2** as a positive voltage should be connected to the **3.3V** pin on the pycom device.

In order to start connecting our sensors we need to understand the basics of how a breadboard works, In the image above we can see the red lines indicating which pins are connected to each other, meaning that if i wish to connect my sensor to the pycom device i need to be mindful of the location of my sensor on the breadboad and the way I position my wires, If we aren't careful during this stage we risk damaging our device or sensor. :)

In the Diagram above you can see the exact way to connect your Photoresistor sensor to the breadboard and then to the pycom device.
In order to recive data from the sensor on our computers we need to set our VSCode.
When we create a new folder on VSCode there is a standard structure we should follow:
1- Create a folder with the project name you choose.
2- Create two files inside the main project file you just created and call them `boot.py` and `main.py`.
3- Create a folder inside the main project folder and name it `lib`.
4- Create a file inside `lib` and name it `library.py`.

#### Create a new project:

* you need to open a new folder by clicking File- New folder, From file explorer window you can create your file and press open.
* On the left side of the VSCode window you can find the project manager, you can right click on your mouse and choose to create folders and files according to the standard formate we mentioned earlier. :)
you can refer to the pdf [here](https://https://docs.pycom.io/gitbook/assets/lopy4-pinout.pdf) to understand your lopy4 device pis and functions.
Now to the fun Part! recieving data from our photoresistor sensor on our VSCode software!
Open new folder and choose Light sensor folder from your sensor library downloads.

After choosing the file, the code should open in your VSCode, and when you run the code, you should be able to see data from the sensor on your VSCode.

The numbers ranging around 500 to 600 are indicating the light level in the room I'm sitting in right now, after I blocked the light from the sensor we got 1023 and this number is indicating to a fully dark enviroment.
### Vibration sensor:
To add the vibration sensor you need to follow similar steps to the ones we did for the ligh sesnor.

To run the data from the sensor you open the Vibration Sensor folder from the sensors library, and run the code.

After you run the code you should be able to recieve the data from sensor, If you are still recieving data from Light sensor try pressing `Ctrl+C` multiple times if needed! I also tried restarting VSCode and it worked.

The Highest numbers are indicating that the sensor is stable, The lower the number the higher is the intensity of the vibration.
## Platform:
Now that we succeeded at setting up our computers, devices, and sensors and are recieving data from these sensors, we need to start sending our sensor data to the cloud.
In order to do so we need to choose an **IOT platform**
An **IoT Platform** is a tool that developers use to connect with each other, spread applications, collect data, send data, manage the connected device and control connectivity and manage their sensors.
Choosing the right platform is highly important because it allows you to communicate, collect, store, analyse and manage data from devices of other developers, so that you can have a rich database in which you can build an informative decision about Your IOT device.
Some of the most famous IoT platforms are:
* Google Cloud IoT
* Cisco IoT Cloud Connect
* Amazon AWS IoT Core
* Microsoft Azure IoT Hub
* Datacake
* Pybytes
* Oracle IoT
In the next table you can find a simple comparison between some of these platforms:
| | Communication Protocols | Key offerin and main functions | main use cases |
|:-----------------------:|:---------------------------------:|:----------------------------------------------------------------------------:|:---------------------------------------------------:|
| **Google Cloud** | HTTP, MQTT | Connectivity, Device management | Energy, Smart parking, Transportation and logistics |
| **Amazon AWS IoT Core** | HTTP, MQTT, WebSockets | Connectivity, Authentication, Rules engine, Development environment. | Smart cities, connected home, agriculture |
| **Microsoft Azure** | HTTP, MQTT, WebSockets, AMQP over | Connectivity, Authentication, Device monitoring, Device management, IoT Edge | Healthcare, Retail, Manufacturing |
The table above gives us an idea about the importance of choosing the right platform for the function of our IoT device.
It is important to mention that there are **Low-Code Platforms** such as Pybytes, Ubidots and Datacake, and **Big Data Platforms** such as Amazon Web Services IoT, Google IoT and IBM IoT.
However, and since I am just a begginer at this course I chose to work with **Pybytes** as it is a good platform that will allow me to control my pycome device, and its data stream, Through pybytes I can visualise my sensor data and keep track of my device and battery level (if you choose to use a battery).
### Connect to Pybytes:
In order to connect to pybytes and send and recieve data please follow [these steps](https://https://docs.pycom.io/pybytes/gettingstarted/) published by pycom.
1- Create an accound
2- connect to WiFi (later on we will use sigfox)
3- Choose WiFi in `Device- Configuration- Network`
make sure that your SSID and password are correct.
4- Thn go to `Provisioning- offline firmware updater- create activation token`
5- Firmware Updater. [link](https://https://docs.pycom.io/updatefirmware/device/)
select “Force update pybytes registration” in the updater before continuing

Now its time to **send some data to pybytes**, follow this [tutorial](https://https://docs.pycom.io/pybytes/dashboard/) published by pycom.
1- Create a pymaker project.
2- add a signal from your device.
3- Add a widget for the signal


## The code:
For this project I used the main existing codes from the downloaded sensor library:
* The light sensor code:
``` python=
from machine import ADC
from machine import Pin
import time
LightSensorPin = 'P20' # sensor connected to P16. Valid pins are P13 to P20.
lightPin = Pin(LightSensorPin, mode=Pin.IN) # set up pin mode to input
#
adc = ADC(bits=10) # create an ADC object bits=10 means range 0-1024 the lower value the less light detected
apin = adc.channel(attn=ADC.ATTN_11DB, pin=LightSensorPin) # create an analog pin on P16; attn=ADC.ATTN_11DB measures voltage from 0.1 to 3.3v
while True:
val = apin() # read an analog value
print("Value", val)
time.sleep(1) # wait 1 sec
from network import LoRa
import socket
import time
import ubinascii
```
* Vibration sensor code:
``` python=
from machine import ADC
from machine import Pin
import time
VibSensorPin = 'P16' # sensor connected to P16. Valid pins are P13 to P20.
Pin(VibSensorPin, mode=Pin.IN) # set up pin mode to input
#
adc = ADC(bits=10) # create an ADC object bits=10 means range 0-705 the lower value the more vibration detected
apin = adc.channel(attn=ADC.ATTN_11DB, pin=VibSensorPin) # create an analog pin on P16; attn=ADC.ATTN_11DB measures voltage from 0.1 to 3.3v
while True:
val = apin() # read an analog value
print("Value", val)
time.sleep(1) # wait 1 sec
```
## Transmitting the data / connectivity:
The term connectivity in IoT defines the connection between IoT elements, including the sensors, gateways, platforms, and other systems. There are different types of network solutions that are evaluated according to their **power consumption**, **range** and **bandwidth consumption** (the maximum amount of data transmitted through the network at a chosen amount of time)
**How often the data is sent** and the amount of data sent at a given moment is different between different networks, During this tutorial we will be working with **Sigfox**, **Sigfox** messages can carry data of **12bytes** as a maximum amount, meaning you can send any data size between 0 and 12 bytes.
**EU regulations** states allows devices to occupy **1% of the time per hour** while sending the data, **36 seconds**. and therefore Sigfox can send a limited number of messages per day.
a sigfox message takes 6 secons to send and therefore, the device can send **6 messages per hour**, and **144 messages per day**, 4 messages are for protocol use which leaves **140 message per day**.
### wireless protocols choice:
* The choice between networks is largly based on the network that has best coverage in your area and therefore, the very first step was to check the **coverage maps** for different networks.
**coverage maps**:
[Sigfox](https://https://www.sigfox.com/en/coverage)
* The second step is to connect your device's **Antenna**
A full year of SigFox subscribtion is included in our new Pycom devices and we only need to activate it, in order to
1- **add our device**
2- **send data**
3- **visualize data on Pybytes**.
1- **add our device**:
After registering our device and set our Sigfox ID and password we will should log in to [Sigfox backend](https://https://backend.sigfox.com/auth/login).

2- **send data**:
To send data you need to run a script in `main.py`
you can find the script in this [tutorial](https://https://hackmd.io/@lnu-iot/SyUxJU7pu)

3- **visualize data on Pybytes**:
* Go to your Pybytes page and go to `Device- configuration- networks` and change the network to **Sigfox**.
* run your **Device Firmware updater** and select “Force update pybytes registration” in the updater, you shoudl see `Connected using Sigfox. Only upload stream is supported`.
* go to `Device- Provisioning ` and find the small window titled **Sigfox Registraction**
press `check sigfox status` and now the circles next to **Unknown Sigfox registraction status** and **Callback not created on Sigfox backend** should turn green.

### transport protocols choice:
Pybytes usually uses **MQTT** as it's default transport protocol, MQUTT stands for Message Queuing Telemetry Transporis and it is ideal for sending small packets of data to and from IoT devices.
**MQTT** can have **disadvantages** by having a slower transmit cycle compared to some other transport protocols, Lack of security encryption and scalability problems (Creating a globally scalable network is more difficult with an MQTT protocol compared to other competitors.)
## Presenting the data:
### visual examples on how the dashboard looks:
After connecting our pybytes and SifFox, we were able to visualise data on the dashboard on Pybytes.
Through out this tutorial i have shown different stages of the data shown over the dashboard on Pybytes, using both WiFi and Sigfox.
This dashboard diagram is the latest stage of my data visualization.





### How often is data saved in the database?
The duration of storing the data is really important because for some developers it is important to get collect as much data as possible and build statistics on this data.
## Final results of the project:

**Unfortunatly** i wasn't able to connect the data to the 3D modeling software with in the time limit of the course, It has proven very difficult to find references regarding similar projects. However, I would like to add some projects that has been drived by similar inspiration.
https://www.youtube.com/watch?v=z3D8shNoJpk
https://www.youtube.com/watch?v=knYcB4wWlhw
https://www.youtube.com/watch?v=51851aMqs78&list=LL&index=10
**Thank you so much for reading through my tutorial :) !**