Node Programming Models

Slides:



Advertisements
Similar presentations
Slide 2-1 Copyright © 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 2 Using the Operating System 2.
Advertisements

Chung-Ta King National Tsing Hua University
Architectures and Applications for Wireless Sensor Networks ( ) Node Programming Models Chaiporn Jaikaeo Department of Computer.
Interrupts What is an interrupt? What does an interrupt do to the “flow of control” Interrupts used to overlap computation & I/O – Examples would be console.
OS Fall ’ 02 Introduction Operating Systems Fall 2002.
1 Concurrent and Distributed Systems Introduction 8 lectures on concurrency control in centralised systems - interaction of components in main memory -
Process Management. External View of the OS Hardware fork() CreateProcess() CreateThread() close() CloseHandle() sleep() semctl() signal() SetWaitableTimer()
OS Spring’03 Introduction Operating Systems Spring 2003.
OS Spring’04 Introduction Operating Systems Spring 2004.
Slide 6-1 Copyright © 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
What do operating systems do? manage processes manage memory and computer resources provide security features execute user programs make solving user.
Department of Electronic & Electrical Engineering Embedded system Aims: Introduction to: Hardware. Software Ideas for projects ? Robotics/Control/Sensors.
COMP201 Computer Systems Exceptions and Interrupts.
Contact Information Office: 225 Neville Hall Office Hours: Monday and Wednesday 12:00-1:00 and by appointment.
Operating Systems Lecture 2 Processes and Threads Adapted from Operating Systems Lecture Notes, Copyright 1997 Martin C. Rinard. Zhiqing Liu School of.
Recall: Three I/O Methods Synchronous: Wait for I/O operation to complete. Asynchronous: Post I/O request and switch to other work. DMA (Direct Memory.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto OS-Related Hardware.
Operating Systems Lecture 7 OS Potpourri Adapted from Operating Systems Lecture Notes, Copyright 1997 Martin C. Rinard. Zhiqing Liu School of Software.
Background: Operating Systems Brad Karp UCL Computer Science CS GZ03 / M th November, 2008.
ECS642U Embedded Systems Cyclic Execution and Polling William Marsh.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Architectures and Applications for Wireless Sensor Networks (204525) Sensor Node Programming Chaiporn Jaikaeo Department of Computer.
Timers and Interrupts Anurag Dwivedi. Let Us Revise.
We will focus on operating system concepts What does it do? How is it implemented? Apply to Windows, Linux, Unix, Solaris, Mac OS X. Will discuss differences.
1 Computer Systems II Introduction to Processes. 2 First Two Major Computer System Evolution Steps Led to the idea of multiprogramming (multiple concurrent.
Network Kernel Architectures and Implementation ( ) Node Programming Chaiporn Jaikaeo Department of Computer Engineering Kasetsart.
2 Processor(s)Main MemoryDevices Process, Thread & Resource Manager Memory Manager Device Manager File Manager.
Embedded Computer - Definition When a microcomputer is part of a larger product, it is said to be an embedded computer. The embedded computer retrieves.
Slides created by: Professor Ian G. Harris Operating Systems  Allow the processor to perform several tasks at virtually the same time Ex. Web Controlled.
Assembly Language Co-Routines
Atmega328p Introduction for Digital and PWM Output Brion L Fuller II Robotics Club.
CSCI/CMPE 4334 Operating Systems Review: Exam 1 1.
1 Chapter 2: Operating-System Structures Services Interface provided to users & programmers –System calls (programmer access) –User level access to system.
1.1 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9 th Edition Chapter 1: Introduction What Operating Systems Do √ Computer-System Organization.
Case Study #1 Microcontroller System. What is a microcontroller? A microcontroller can be considered a self-contained system with a processor, memory.
Introduction to Operating Systems Concepts
INTRODUCTION TO WIRELESS SENSOR NETWORKS
CS 3214 Computer Systems Lecture 9 Godmar Back.
CS4101 嵌入式系統概論 General Purpose IO
Introduction to Operating Systems
Operating System Overview
Microcontrollers & GPIO
CS4101 Introduction to Embedded Systems Lab 1: General Purpose IO
OPERATING SYSTEMS CS3502 Fall 2017
Protection of System Resources
Computer Architecture
CS4101 嵌入式系統概論 General Purpose IO
Introduction to Operating System (OS)
Introduction to Operating Systems
Module 2: Computer-System Structures
Multithreaded Programming
Lecture Topics: 11/1 General Operating System Concepts Processes
Threads Chapter 4.
CSE 451: Operating Systems Autumn 2003 Lecture 2 Architectural Support for Operating Systems Hank Levy 596 Allen Center 1.
Module 2: Computer-System Structures
CSE 451: Operating Systems Autumn 2001 Lecture 2 Architectural Support for Operating Systems Brian Bershad 310 Sieg Hall 1.
Interrupt handling Explain how interrupts are used to obtain processor time and how processing of interrupted jobs may later be resumed, (typical.
Why Threads Are A Bad Idea (for most purposes)
Implementing Processes, Threads, and Resources
CSE 451: Operating Systems Winter 2003 Lecture 2 Architectural Support for Operating Systems Hank Levy 412 Sieg Hall 1.
Implementing Processes, Threads, and Resources
Module 2: Computer-System Structures
COMP3221: Microprocessors and Embedded Systems
Why Threads Are A Bad Idea (for most purposes)
Contact Information Office: 225 Neville Hall Office Hours: Monday and Wednesday 12:00-1:00 and by appointment. Phone:
Why Threads Are A Bad Idea (for most purposes)
Module 2: Computer-System Structures
Chapter 13: I/O Systems.
Chapter 13: I/O Systems “The two main jobs of a computer are I/O and [CPU] processing. In many cases, the main job is I/O, and the [CPU] processing is.
Presentation transcript:

Node Programming Models 01204525 Wireless Sensor Networks and Internet of Things Chaiporn Jaikaeo (chaiporn.j@ku.ac.th) Department of Computer Engineering Kasetsart University Materials taken from lecture slides by Karl and Willig Cliparts taken from openclipart.org Last updated: 2018-09-08

Outline Microcontroller programming Software development cycle Operating Systems and Execution environments Concurrent programming Event-driven programming model Multithreaded programming model Coroutines

Typical Development Process Firmware flashing with an external chip programmer Source code (C/Assembly) Microcontroller Cross Compiler/Assembler Chip Programmer Serial/USB port Machine code (hex/binary) 010101 011101 110110 Uploader

Typical Development Process Firmware flashing with on-chip bootstrap loader Source code (C/Assembly) Microcontroller Cross Compiler/Assembler flash memory Bootstrap Loader (BSL) Serial/USB port Machine code (hex/binary) 010101 011101 110110 Uploader

Typical Development Process Script uploading with MicroPython firmware Source code (Python) Microcontroller flash memory MicroPython Serial/USB port Uploader

OS and Execution Environments Usual operating system goals Make access to device resources abstract (virtualization) Protect resources from concurrent access Usual means Protected operation modes of the CPU Process with separate address spaces These are not available in microcontrollers No separate protection modes, no MMU Would make devices more expensive, more power-hungry

Levels of Abstraction Direct hardware access (bare-metal) Pure C/C++/Assembly Hardware abstraction layer E.g., C/C++ using Arduino-provided libraries Task scheduling Allows concurrency among multiple tasks in the same app Resource Virtualization Makes some limited resources (e.g., timers) virtually available Memory usually not virtualized

Case Study #1: Tmote Sky

Case Study #2: IWING-MRF Analog/Digital sensor connectors Radio transceiver UART Connector 8-bit AVR Microcontroller USB Connector (for reprogramming and power) External battery connector

Tmote Sky: Schematic

IWING-MRF: Schematic

Tmote Sky: LED Blinking Code #include <msp430x16x.h>   int main() { WDTCTL = WDTPW | WDTHOLD; P5DIR |= (1 << 6); for (;;) P5OUT |= (1 << 6); __delay_cycles(500000L); P5OUT &= ~(1 << 6); } return 0; Stop watchdog timer Make pin P5.6 output Send logic 1 to pin P5.6 Send logic 0 to pin P5.6

IWING-MRF: LED Blinking Code #include <avr/io.h> #include <util/delay.h> #define F_CPU 12000000L main() { DDRD |= (1 << 5); while (1) PORTD &= ~(1 << 5); _delay_ms(500); PORTD |= (1 << 5); } Make pin PD5 output Send logic 0 to pin PD5 Send logic 1 to pin PD5

Tmote Sky: Compiling Tmote Sky uses MSP430 chip by Texas Instruments It requires MSP430 cross-compiler $ msp430-gcc -mmcu=msp430f1611 -o blink.elf blink.c

IWING-MRF: Compiling IWING-MRF uses AVR chip by Atmel/Microchip It requires the AVR cross-compiler $ avr-gcc -mmcu=atmega328p –o blink.elf blink.c

Hardware Abstraction Layer Tmote Sky API Implementation Tmote Sky Hardware

Hardware Abstraction Layer IWING-MRF API Implementation IWING-MRF Hardware

LED Blinking: Arduino Code With appropriate Arduino ports for MSP430 and AVR provided, the following code can be used in both Tmote Sky and IWING-MRF with minimal change #define LED 13 void setup() { pinMode(LED,OUTPUT); } void loop() { digitalWrite(LED,HIGH); delay(500); digitalWrite(LED,LOW);

LED Blinking: MicroPython Code MicroPython provides both a hardware abstraction layer and an execution environment A Python "app" is interpreted by MicroPython firmware from machine import Pin from time import sleep led = Pin(2,Pin.OUT) while True: led.value(1) sleep(0.5) led.value(0)

Concurrent Programming Models IoT applications tend to get too complex to be implemented as a sequential program E.g., the app needs to Monitor various sensor status Wait for and respond to user switch Wait for and respond to requests from the network

Example: Concurrent Tasks Create an application that performs the following subtasks concurrently Subtask#1 repeatedly turns LED on and off every 500 milliseconds Subtask#2 when the switch (IO0) is pressed, displays the number of total switch presses on the OLED display

Setting Up LED and Switch On-board LED (GPIO2) On-board SW (GPIO0) from machine import Pin led = Pin(2, Pin.OUT) led.value(1) # turn LED on led.value(0) # turn LED off from machine import Pin sw = Pin(0, Pin.IN) if sw.value == 0: print("SW is pressed") else: print("SW is released")

Wiring the OLED Display Connect VCC/GND to OLED board Connect Pins GPIO4 and GPIO5 to OLED's SCL and SDA, respectively

Controlling the OLED Display from machine import Pin, I2C import ssd1306 import time i2c = I2C(scl=Pin(4), sda=Pin(5)) oled = ssd1306.SSD1306_I2C(128, 64, i2c) while True: oled.text("Hello",0,0) # display "Hello" at (0,0) time.sleep(1) oled.fill(0) # clear screen oled.text("Goodbye",0,10) # display "Goodbye" at (0,10) oled.show() oled.fill(0) # clear screen

Subtask #1 Only (No Concurrency) repeatedly turns LED on and off every 500 milliseconds from machine import Pin import time led = Pin(2,Pin.OUT) while True: led.value(1) time.sleep(0.5) led.value(0)

Subtask #2 Only (No Concurrency) displays total switch count on OLED from machine import Pin, I2C import ssd1306 import time sw = Pin(0, Pin.IN) i2c = I2C(scl=Pin(4), sda=Pin(5)) oled = ssd1306.SSD1306_I2C(128, 64, i2c) count = 0 while True: while sw.value() != 0: time.sleep(0.01) # wait until switch is pressed count += 1 oled.fill(0) # clear screen oled.text(str(count),0,0) oled.show() while sw.value() != 1: time.sleep(0.01) # wait until switch is released

Attempt to Combine Subtasks Simply combining the two subtasks in a sequential manner will NOT achieve what we expected from machine import Pin, I2C import ssd1306 import time led = Pin(2, Pin.OUT) sw = Pin(0, Pin.IN) i2c = I2C(scl=Pin(4), sda=Pin(5)) oled = ssd1306.SSD1306_I2C(128, 64, i2c) count = 0 while True: # Subtask 1 led.value(1) time.sleep(0.5) led.value(0) # Subtask 2 while sw.value() != 0: time.sleep(0.01) # wait until switch is pressed count += 1 oled.fill(0) # clear screen oled.text(str(count),0,0) oled.show() while sw.value() != 1: time.sleep(0.01) # wait until switch is released blocking blocking blocking blocking

Concurrent Programming Models Event driven Multithreading Coroutines

Idle/regular processing Event-Driven Model Perform regular processing or be idle React to events when they happen immediately To save power, CPU can be put to sleep during idle Idle/regular processing Radio event handler Sensor event handler

Ideally, CPU should go to sleep here instead of idle loop Event-Driven Code import time import micropython from machine import Pin, I2C, Timer import ssd1306 def handle_switch(pin): micropython.schedule(switch_pressed,None) def handle_timer(timer): micropython.schedule(timer_fired,None) def switch_pressed(arg): global count count += 1 oled.fill(0) oled.text(str(count),0,0) oled.show() time.sleep(0.01) # prevent sw bouncing def timer_fired(arg): led.value(1-led.value()) # I/O setup led = Pin(2, Pin.OUT) sw = Pin(0, Pin.IN) i2c = I2C(scl=Pin(4), sda=Pin(5)) oled = ssd1306.SSD1306_I2C(128,64,i2c) count = 0 # initialize event triggers timer = Timer(0) timer.init( period=500, mode=Timer.PERIODIC, callback=handle_timer) sw.irq( trigger=Pin.IRQ_FALLING, handler=handle_switch) while True: pass Ideally, CPU should go to sleep here instead of idle loop

Problem with Event-Driven Model Unstructured code flow Very much like programming with GOTOs!

Multithreading Model Based on interrupts, context switching Handle subtask#1 Handle subtask#2 Based on interrupts, context switching Difficulties Too many context switches Each process required its own stack Not much of a problem on modern microcontrollers OS-mediated process switching

Multithreading Code Thread #1 Thread #2 import _thread from machine import Pin, I2C import ssd1306 import time def blink_led(): while True: led.value(1) time.sleep(.5) led.value(0) def count_switch(): count = 0 while sw.value() != 0: time.sleep(0.01) # wait until sw is pressed count += 1 oled.fill(0) # clear screen oled.text(str(count),0,0) oled.show() while sw.value() != 1: time.sleep(0.01) # wait until sw is released # I/O setup led = Pin(2, Pin.OUT) sw = Pin(0, Pin.IN) i2c = I2C(scl=Pin(4), sda=Pin(5)) oled = ssd1306.SSD1306_I2C(128, 64, i2c) # create and run threads _thread.start_new_thread(blink_led, ()) _thread.start_new_thread(count_switch, ()) while True: pass Thread #1 Thread #2

Problems with Multithreads Each thread requires its own stack to hold local variables Not much of a problem for modern microcontrollers Thread 1 Thread 2 Thread 3 Thread 4

Problems with Multithreads Code employing preemptive threading library must ensure thread-safe operations

Coroutines Generalized subroutines Can be used to implement: Allow multiple entry points for suspending and resuming execution at certain locations Can be used to implement: Cooperative multitasking Actor model of concurrency No worry about thread-safe operations

Subroutines vs. Coroutines “Subroutines are a special case of coroutines.” --Donald Knuth Fundamental Algorithms. The Art of Computer Programming Routine 1 Routine 2 Routine 1 Routine 2 yield yield call return yield return yield call Subroutines Coroutines

Coroutines in MicroPython Can be achieved using The uasyncio module with async/await pattern Generators

Coroutines: Code Require uasyncio module from machine import Pin, I2C import uasyncio as asyncio import ssd1306 async def blink_led(): while True: await asyncio.sleep_ms(500) led.value(1-led.value()) async def count_switch(): count = 0 while sw.value() != 0: await asyncio.sleep_ms(1) count += 1 oled.fill(0) # clear screen oled.text(str(count),0,0) oled.show() while sw.value() == 0: # I/O setup led = Pin(2,Pin.OUT) sw = Pin(0,Pin.IN) i2c = I2C(scl=Pin(4), sda=Pin(5)) oled = ssd1306.SSD1306_I2C(128,64,i2c) # create and run async tasks loop = asyncio.get_event_loop() loop.create_task(blink_led()) loop.create_task(count_switch()) loop.run_forever()

Conclusion Microcontroller programming requires cross-compiler to build a firmware, which must be uploaded to the chip IoT devices usually do not require full-featured operating systems; only hardware abstraction and task scheduling Hardware abstraction allows code reuse across different platforms Complex applications often require concurrency Event-driven programming model Multithreaded programming model Coroutines