# 05 - IoT Air-Lock ___ ## Introduction In this lab, we want to illustrate differences and similarities of the two object models offered by LWM2M and OPC UA using the example of an implementation of an air-lock model. ___ ## Learning Aims The goal of this lab is to introduce the students to IoT management and application concepts as typified by the LWM2M and OPC-UA specifications. The students will understand the structure of objects in both frameworks. In the context of LWM2M, students will be learn to initialise new instances of objects and read the attributes of the objects from the server side. In the context of OPC UA, students will be able to implement new objects and read the attributes of the objects from the client side. ___ ## Prerequisites - lab machine or student's laptop (the _development machine_) - the air-lock model The development machine must reside in the laboratory subnet, 172.16.32.0/20. Preferably with all other network interfaces disabled (WLAN, …). ___ ## Getting Started In this laboratory we will use two frameworks to illustrate differences and similarities in their handling. The protocols are briefly described below. Further reading material is provided in each subsection. ___ ## Information ### OMA (Open Media Alliance) Information about OMA - the originators of the Lightweight Machine to Machine specifications [http://openmobilealliance.org/about/](http://openmobilealliance.org/about/). #### OMA LightweightM2M v.10 The motivation of LightweightM2M is to develop a fast deployable client-server specification to provide a machine to machine service. LightweightM2M is in principle a device management protocol, but it is designed to be able to extend to meet the requirements of applications and so can be used to manage and transfer both service and application data. LightweightM2M implements the interface between a client and a server. It provides a choice for the M2M Service Provider to deploy an M2M system to provide service to the M2M user. _Source and further information: [http://technical.openmobilealliance.org/Technical/technical-information/release-program/current-releases/oma-lightweightm2m-v1-0](http://technical.openmobilealliance.org/Technical/technical-information/release-program/current-releases/oma-lightweightm2m-v1-0)_ #### Leshan Leshan is an OMA Lightweight M2M (LWM2M) implementation in Java. Eclipse Leshan relies on the Eclipse IoT Californium project for the CoAP and DTLS implementation. _Source and further information: [https://projects.eclipse.org/projects/iot.leshan](https://projects.eclipse.org/projects/iot.leshan)_ Leshan is based on the Californium and CoAP Framework you should be familiar with since the 2nd laboratory of this course. Eclipse Californium is an open source implementation of the constrained application protocol (CoAP) and is written in Java. ### OPC-UA "OPC" stands for Open Platform Communications and is a communication framework designed for IoT and Industry 4.0 applications. "UA" stands for Unified Architecture and describes the transition from the previous version to the current one by pointing out that this protocol is platform-independent. This is achieved by using TCP/IP communication instead of COM/DCOM. The basic design is a server-client structure, where the server provides the basis for communication and standardized interfaces to the outside world through which clients can communicate with the server. The counterpart is the client, which can access any OPC UA server through the standardized interfaces and exchange data. The OPC UA standard is composed of individual specifications, where each specification specifies a partial function and therefore further the interfaces of server and client to support the function. Not every function has to be supported by the server and client. Depending on the area of application, the server and client can thus be implemented in a more lightweighted manor according the needs. OPC UA is composed of the following specifications: 1. Concepts 2. Security Model 3. Address Space Model 4. Services 5. Information Model 6. Mappings 7. Profiles 8. Data Access 9. Alarms and Conditions 10. Programs 11. Historical Access 12. Discovery 13. Aggregates 14. PubSub **Hint: In this laboratory we use the *Data Access* specification.** The *Data Access* specification describes the classical exchange of data, which is done via data points. For each data point a value can be read or written, whereby a data point consists of the value, a time stamp and the quality of the value. E.g., in the event of a connection interruption, the quality of the value can be declared as not valid. ![opc_ua_system_architecture.png](./doc/uml/opc_ua_system_architecture.png) The different Service models available are: 1. **Discovery Service:** To discover endpoints, each server must have a Discovery Endpoint that clients can access without establishing a session. 2. **Secure Channel Service:** A secure channel is neccessary to open a communication channel that ensures the confidentiality and integrity of all messages with the server. 3. **Session Service:** A Secure Channel is required to establish a session. The session must also be activated before it can be used. 4. **Node Management Service:** This Set defines Services to delete and add Address Space Nodes and references between them. 5. **View Service:** For viewing the nodes only, without any further interaction. 6. **Query Service:** To issue a query to a server to provide a subordinate storage mechanism. 7. **Attribute Service:** To provide read access to the attributes of a node. 8. **Method Service:** Represents the function calls of objects. Methods are called and return after completion. 9. **Monitored Item and Subscription Serivce:** For subscribing to data and events. The Monitored Item identifies the object to be monitored and the Subscription service is used to send notifications. ![opc_ua_client_architecture.png](./doc/uml/opc_ua_client_architecture.png) ![opc_ua_server_architecture.png](./doc/uml/opc_ua_server_architecture.png) _Source and further information: [https://reference.opcfoundation.org/](https://reference.opcfoundation.org/)_ ___ ## Features and Differences OPC-UA vs. LWM2M ### LWM2M The object structures of the two protocols is of main difference. In case of LwM2M an object is a loose collection of resources. The resources can be accessed using a URI defined by numbers indicating object ID, instance of object and resource number. This addressing scheme requires the a priori definition of resources and their semantics. This definition can be made by dint of other specifications. IPSO is one example, or it can be defined by implementers on an ad hoc basis. An example of the latter are objects with a specific ID curated by the Open Media Alliance (OMA). If an object has to be added, one searches the documentation of OMA SpecWorks for an object that best fits the current requirements. An instance of this object is then created in the LwM2M client which then creates the specified resources. Resources may be mandatory or optional. ![lwm2m_object_structure.png](./doc/uml/lwm2m_object_structure.png) The LWM2M server interfaces with these objects/resources in much the same way as the client (dual-ported RAM model) and the objects and resources of the clients can be vuisualised by appropriate web-tools or similar. ### OPC-UA OPC UA provides functionality to design the objects with more freedom and at the choice of the implemter. Objects in OPC UA are referred to as "nodes". Other nodes can be attached to any node. This behaviour applies to all nodes. The nodes themselves can take on different functions. Thus, a node can be an object, a function, a variable, etc. Therefore, the OPC UA objects can exactly map any object. However, the portability from system to system suffers due to the partial definition of the structure in the library. ![opc_ua_object_structure.png](./doc/uml/opc_ua_object_structure.png) The server provides services. The client can connect to a server, find the available services, read the attributes and variables and execute methods. This is in contrast to the structure of LWM2M, where access takes place through the server and not the client. The objects listed in the OMA Object Registry are predefined classes that can be reused. These classes are partly produced by OMA itself or by third parties. These third parties have produced these objects for the development of standards. This group includes, for example, the IPSO Alliance. In 2018, IPSO Alliance merged with OMA to form Oma SpecWorks. Furthermore, there are also objects produced by external vendors or individuals, which are listed in the OMA Object Registry and are released for further use. CloudMinds is an example of this. It is a company that develops cloud-based intelligent robot architecture. ___ ## Scenario of this Laboratory ### Bank Security Lock Application example: The bank lock. ![bank_lock.PNG](./doc/bank_lock.PNG) The lock model represents a security lock in a bank. Access to the bank during its non-regular opening hours is often solved by a security lock. Only people with an appropriate access card (bank card) are allowed to enter. Above a certain security level, it is necessary to identify the bank users individually, i.e. access is not allowed directly to the restricted area, but only through the lock chamber. In the lock chamber, in reality, it is often checked whether the person is alone in the lock and is not being followed (anti tailgating), or is carrying someone piggyback (anti piggybacking). A separation of clients requesting entrance allows individual assessment of access authorization. Only when it is certain that the person is alone, the door is released into the interior. To leave, on the other hand, a push of a button is sufficient. This model is limited to access control via an RFID tag. Exceptional scenarios, such as evacuation in the event of a fire, are not (yet) covered by this model. _Source and further information: [https://www.record.ch/de/produkte/tuersysteme/60/anti_tailgating_piggybacking](https://www.record.ch/de/produkte/tuersysteme/60/anti_tailgating_piggybacking)_ ### The Lock Model In this lab, you will learn how the system-design differs between the paradigms offered by LWM2M and OPC-UA. The design of the lock model itself is important: Three Raspberry Pis are used, two of which have hardware connections via GPIO and will be referred to as *agents*. One gate of the lock is located in the North and one in the South, as labelled on the lock model itself. The two agents do not communicate with each other. The Pi located in the middle, further referred to as *controller*, is also the one that communicates with the two agents. In combination, the three Pis establish the function of the lock. ![controller_agent_communication.png](./doc/uml/controller_agent_communication.png) ___ ## Preparation Connect an Ethernet cable to the switch residing on the bottom of the lock model to the IoT subnet of the ZHAW. The lock models are given fixed IPs and a name via the IoT subnet, this name is *iot-schleuse-XY*. You can now connect to the controller Pi via ssh connection as you know it from previous labs. The credentials are as follows: User: *pi* Password: *raspberry* ```console ssh pi@lock-model-XY-[controller/north/south].lab.iot ``` or ```console # lock-model-07-controller 172.16.34.70 # lock-model-07-north 172.16.34.71 # lock-model-07-south 172.16.34.72 ssh pi@172.16.34.[0/1/2] ``` ![IoT-Laboratory-Network-Situation (1)](https://github.zhaw.ch/storage/user/6287/files/cd86d75b-f5a3-4f23-89c0-13770a7ed2ea) Pay attention to adress the correct adresses for each of the Controller and both agents Pis. HINT: For better visualization open and work in seperate terminal windows for each of the Pis. To finalize the preparations get the latest sources from the repo. ```console git clone https://github.zhaw.ch/IoT/IoT_students.git ``` ___ ## Task 1 - Inspection of the Mechatronic Unit 'Gate' and Completion of the Finite-State Machine **The Lock model consists of two gates modeled as mechatronic units containing a motor, limit switches and LEDs.** Analyze the creation of the gate in the code `gate.py` in the directory `~/IoT_students/lab_05/opc_ua/src/`. Take a look at how the unit is implemented in OpcUA methods in the code `main_server.py` in the directory `~/IoT_students/lab_05/opc_ua/src/`. Pay attention how the OpcUA methods are configured to be available on the North and South agents. To get an overview of the available objects, their methods and variables, or in short, all object nodes that are not server-specific, run the following Python script. You may need to adjust the IP of the server you are logging into in the script. The server the client registers with can be one of the two agents. ```console # eg. start server on the north-pi pi@NorthAgent:~/IoT_students/lab_05/opc_ua/src$ python3 main_server.py # update IP and run tree_inspector on the controller pi@Controller:~/IoT_students/lab_05/opc_ua/src$ python3 tree_inspector.py ``` Now, you shall be able to understand and explain the distribution of methods across the network. Why are the 'open' and 'close' methods implemented on both of the agents? Answer: Execute the lock model by running the following codes on the agents. The agents need to be conncected trough the controller. `X` and `Y` need to be replaced by the IPs of the agents (ng == NorthAgent, sg == SouthAgent). Have a look at the leases file (as shown above). North agent: ```console pi@NorthAgent:~/IoT_students/lab_05/opc_ua/src$ python3 main_server.py ``` South agent: ```console pi@SouthAgent:~/IoT_students/lab_05/opc_ua/src$ python3 main_server.py ``` Controller: ```console pi@Controller:~/IoT_students/lab_05/opc_ua/src$ python3 main_client.py -ng 172.16.34.X -sg 172.16.34.Y ``` **This task needs to be done on the controller** Analyze the state machine diagram shown below. The diagram presents the **final** state of the code `stm_lock.py` in the directory `~/IoT_students/lab_05/opc_ua/src/` and not the **current** one. All of the states are implemented except the emergency state (given in red). Therefore, your task is to implement an emergency state. Please note that the presentation of the state machine has been kept simple. Thus, in the diagram, the start is always at the entrance gate (SouthGate), therefore the RFID reader is placed only on the side of the entrance gate. The lock chamber can be reached through the entrance, and left through the exit. The entrance gate is connected to the south agent and the exit gate is connected to the north agent. Therefore, in the state machine model, the SouthGate refers to the entrance and the NorthGate to the exit gate. The additional state implemented as 'Emergency state' is entered by pressing the button 'N' on the top of the lock model. In the emergency state, both doors should open and remain that way untill the emergency state is exited. The exit of the emergency state is achieved by pressing the same button after which the lock model should return back to the normal execution. Write the code for the function in charge of handling the emergency request defined as '_handle_emergency_request' in the `stm_lock.py` file. To run the state machine, you can execute the state machine directly. In the main method, the state machine runs a mock object of the lock. Please note that the mock object has no hardware delay and additionally gives pseudo-random feedback, so that the state machine is fast and will never stop. Via `CTRL + C` you can stop the execution. If the state machine is stuck in a state, there is an error. ```console python3 stm_lock.py ``` **Finite-State Machine Diagram** ![IoT_05_lock_model_final](https://github.zhaw.ch/storage/user/6287/files/6aa4dd91-21a4-4f53-855f-a6cda144535e) ## Task 2: Briefly consider what your requirements are for an RGB led that you want to turn on and off in one color, i.e. the LED should shine red or be off. Then compare the object "Light Control" from the LwM2M Registry with your requirements. ([https://technical.openmobilealliance.org/OMNA/LwM2M/LwM2MRegistry.html](https://technical.openmobilealliance.org/OMNA/LwM2M/LwM2MRegistry.html)) What differences do you notice? What are the advantages and disadvantages of this from the LwM2M registry provided objects? | | Advantages | Disadvantages | | :-- | :-- | :-- | | 1. | | | | 2. | | | | 3. | | | | 4. | | | | 5. | | | ___ ## Task 3: Leshan Web Interface The Leshan server provides a web interface through which server and clients as well as their objects and the resources of the objects can be accessed. The web interface is bound to port 8080. You can access it by entering \:8080 in a web browser on your development machine. The IP address is the one of the controller in the IoT subnet. You need to start the LwM2M system(see below: **Run LwM2M**). Note that unlike the OPC UA where you had to connect the angents trough the controller, in this case it is the other way around, you have to connect with the controller via the agents. Be aware that you have access to all resources prescribed according to OMA via this web interface. However, not all prescribed object resources are implemented according to the application within the scope of the lock. Since only API requests are sent via the web interface, the server will respond to unimplemented methods with corresponding HTTP responses. **In addition, you can set the lock to an unexpected state.** To gain access to the objects, and their resources, you must specify the full path. Create global variables in `~/IoT_students/lab_05/lwm2m/src/api_lock_control_leshan.py` for the objects, instances and resources to have them ready for the next task. ### Run LWM2M ```console cd ~/IoT_students/lab_05/lwm2m/src ``` Controller: ```console pi@Controller:~/IoT_students/lab_05/lwm2m/src$ java -jar leshan_lock_server.jar -lh 172.16.34.X ``` North agent: ```console pi@NorthAgent:~/IoT_students/lab_05/lwm2m/src$ sudo java -jar leshan_lock_client.jar -u 172.16.34.X -n North ``` South agent: ```console pi@SouthAgent:~/IoT_students/lab_05/lwm2m/src$ sudo java -jar leshan_lock_client.jar -u 172.16.34.X -n South ``` ___ ## Task 4 - Completion of Lock Control via API While only Python code is used for the OPC UA project, Leshan is available as a pure Java implementation, which is why the focus of this lab section is on controlling the existing objects, while new objects are also created for the OPC UA protocol. Read the code `api_lock_control_leshan.py` (`~/IoT_students/lab_05/lwm2m/src/`). Complete the Leshan object for the Red Led by looking up the LwM2M Registry (given in Task 3) from where you shall be able to find the required parameters. Afterwards complete the API request `__handleGate(client, openClose)`. Be sure to use the `post()` method in `__handleGate(client, openClose)`, which is already implemented. ![program_calls_who_communicates_with_whom.png](./doc/uml/program_calls_who_communicates_with_whom.png) For adressing the correct object IDs in the code, use the WEB server for each of the North/South agents where you can find out the correct values for the object instances and resources. ### Run LwM2M + API Lock Control Controller: ```console pi@Controller:~/IoT_students/lab_05/lwm2m/src$ python3 api_lock_control_leshan.py ``` ___ ## Grading 4 points maximum will be awarded for completion of the exercises. ___ ## Version | Version | Date | By | Comments | Class Level | Module | | :-- | :-- | :-- | :-- | :-- | :-- | | V0.9 | 09.2022 | stsh | first version | - | IoT | | V0.9.1 | 10.2023 | veln | second version | - | IoT |