Co Concurr rrent Programming in in C Constrain ained D Devic - - PowerPoint PPT Presentation

co concurr rrent programming in in c constrain ained d
SMART_READER_LITE
LIVE PREVIEW

Co Concurr rrent Programming in in C Constrain ained D Devic - - PowerPoint PPT Presentation

Co Concurr rrent Programming in in C Constrain ained D Devic vices 01219335 Data Acquisition and Integration Chaiporn J Chaipo n Jaik aikae aeo De Department of f Computer Engineering Kasetsart Unive versity Revised 2020-09-09


slide-1
SLIDE 1

Co Concurr rrent Programming in in C Constrain ained D Devic vices

Chaipo Chaiporn J n Jaik aikae aeo De Department of f Computer Engineering Kasetsart Unive versity

01219335 Data Acquisition and Integration

Revised 2020-09-09

slide-2
SLIDE 2

2

Ou Outline

  • Handling concurrency
  • Example of concurrent tasks
  • Event-driven programming
  • Multithreading
  • Coroutines
  • Concurrency and MQTT
slide-3
SLIDE 3

3

Ha Handl ndling ng C Conc ncur urrenc ency

  • 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
slide-4
SLIDE 4

4

Ex Example: ample: C Conc ncur urren ent T Task asks

  • Create an application that performs the following subtasks

concurrently

  • Subtask #1

repeatedly blinks the red LED for a short time period (100 ms) every 2 seconds

  • Subtask #2

when switch S1 is pressed, toggles the green LED

slide-5
SLIDE 5

5

Su Subtas ask # #1 O Only ly (No C (No Con

  • ncurrency)

blinks red LED shortly (100 ms) every 2 seconds

from machine import Pin import time led_red = Pin(2, Pin.OUT) while True: led_red.value(0) # turn LED on time.sleep_ms(100) led_red.value(1) # turn LED off time.sleep_ms(1900)

Turn red LED on START Wait 100 ms Turn red LED off Wait 1900 ms

slide-6
SLIDE 6

6

Su Subtas ask # #2 O Only ly (No C (No Con

  • ncurrency)

Toggle green LED when S1 is pressed

from machine import Pin led_green = Pin(12, Pin.OUT) sw1 = Pin(16, Pin.IN, Pin.PULL_UP) while True: # wait until S1 is pressed while sw1.value() == 1: pass # toggle LED led_green.value(1-led_green.value()) # wait until S1 is released while sw1.value() == 0: pass

Wait until S1 is pressed START Toggle green LED Wait until S1 is released

slide-7
SLIDE 7

7

  • Cannot just put one subtask after another

from machine import Pin import time led_red = Pin(2, Pin.OUT) led_green = Pin(12, Pin.OUT) sw1 = Pin(16, Pin.IN, Pin.PULL_UP) while True: # subtask #1 led_red.value(0) # turn LED on time.sleep_ms(100) led_red.value(1) # turn LED off time.sleep_ms(1900) # subtask #2 while sw1.value() == 1: # wait until S1 is pressed pass led_green.value(1-led_green.value()) while sw1.value() == 0: # wait until S1 is released pass

At Attempt to Combine Subtasks

blocking blocking blocking blocking This will not work! Why?

slide-8
SLIDE 8

8

Co Concurr rrency y Programming Mo Models

  • Event driven
  • Multithreading
  • Coroutines
slide-9
SLIDE 9

9

(1) E (1) Even ent-Dr Driven Mod

  • del
  • Also known as reactive programming
  • 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

Sensor event handler

sensor event network event

Network event handler

slide-10
SLIDE 10

10

Ev Event Sources

  • Hardware (external) interrupts
  • E.g., pin logic changes
  • Use Pin.irq() method to set up a callback
  • Software interrupts
  • E.g., Timer, incoming network messages

https://lastminuteengineers.com/handling-esp32-gpio-interrupts-tutorial/

slide-11
SLIDE 11

11

Ev Event-Dr Driven Cod

  • de

import time from machine import Timer, Pin led_red = Pin(2, Pin.OUT) led_green = Pin(12, Pin.OUT) sw1 = Pin(16, Pin.IN, Pin.PULL_UP) def blink1(timer): led_red.value(0) # turn LED on timer.init(period=100, mode=Timer.ONE_SHOT, callback=blink2) def blink2(timer): led_red.value(1) # turn LED off timer.init(period=1900, mode=Timer.ONE_SHOT, callback=blink1) def switch_pressed(pin): led_green.value(1-led_green.value()) timer = Timer(0) blink1(timer) sw1.irq(trigger=Pin.IRQ_FALLING, handler=switch_pressed) while True: time.sleep(1)

slide-12
SLIDE 12

12

Pr Problems with Eve vent-Dr Driven Mod

  • del
  • Unstructured code flow
  • Requires global variables to

keep track of task's states

Very much like programming with GOTOs!

slide-13
SLIDE 13

13

(2) M (2) Mult ultit ithr hreading eading M Model del

  • Based on interrupts, context

switching

  • Difficulties
  • Too many context switches
  • Each process required its own stack
  • Not much of a problem on

modern microcontrollers

Execute subtask#1 Execute subtask#2

OS-mediated context switching

slide-14
SLIDE 14

14

import _thread import time from machine import Timer, Pin led_red = Pin(2, Pin.OUT) led_green = Pin(12, Pin.OUT) sw1 = Pin(16, Pin.IN, Pin.PULL_UP) def blink_led(): while True: led_red.value(0) time.sleep_ms(100) led_red.value(1) time.sleep_ms(1900)

Mu Multithreading Co Code

Thread #1

def switch_toggle(): while True: # wait until sw is pressed while sw1.value() == 1: pass # toggle LED led_green.value(1-led_green.value()) # wait until sw1 is released while sw1.value() == 0: pass # create and run threads _thread.start_new_thread(blink_led, []) _thread.start_new_thread(switch_toggle, []) while True: time.sleep(1)

Thread #2

slide-15
SLIDE 15

15

Pr Problems with Threads

  • Code employing multithreads must ensure thread-safe
  • perations
  • A function may be interrupted in the middle of its

execution where it shouldn’t be, causing race conditions

  • Use a Lock object to create a mutex
slide-16
SLIDE 16

16

(3) C (3) Corout utines ines

  • Generalized subroutines
  • Allow multiple entry points for suspending and resuming execution

at certain locations

  • Can be used to implement Cooperative Multitasking
  • As coroutines do not return, tasks' states can be kept

inside local variables

  • No worry about thread-safe operations
  • May be known by different names in some languages:
  • Green threads
  • Fibers
slide-17
SLIDE 17

17

Routine 2

Su Subrou

  • utin

ines v

  • vs. C

. Cor

  • rou
  • utin

ines

Routine 1

Subroutines

Routine 2 Routine 1

Coroutines

call call return return yield yield yield yield “Subroutines are a special case of coroutines.”

  • -Donald Knuth

Fundamental Algorithms. The Art of Computer Programming

slide-18
SLIDE 18

18

Co Coroutines s in Mi MicroPython

  • Can be achieved using the uasyncio module with

async/await pattern

  • The uasyncio module needs to be installed separately
  • Already built into the course's MicroPython firmware
slide-19
SLIDE 19

19

import uasyncio as asyncio import time from machine import Timer, Pin led_red = Pin(2, Pin.OUT) led_green = Pin(12, Pin.OUT) sw1 = Pin(16, Pin.IN, Pin.PULL_UP) async def blink_led(): while True: led_red.value(0) await asyncio.sleep_ms(100) led_red.value(1) await asyncio.sleep_ms(1900) async def switch_toggle(): while True: # wait until sw is pressed while sw1.value() == 1: await asyncio.sleep_ms(0) # toggle LED led_green.value(1-led_green.value()) # wait until sw1 is released while sw1.value() == 0: await asyncio.sleep_ms(0) # create and run coroutines loop = asyncio.get_event_loop() loop.create_task(blink_led()) loop.create_task(switch_toggle()) loop.run_forever()

Co Coroutines: s: Co Code

Coroutine #1 Coroutine #2

slide-20
SLIDE 20

20

Pr Problems with Coroutines/as asyncio io

  • Usually run on a single thread and not employ multiple

cores

  • Due to their cooperative nature, long-running function

calls render all other coroutines unresponsive

  • May miss some hardware events
slide-21
SLIDE 21

21

MQ MQTT T and Co Concurr rrency

  • To handle incoming messages, umqtt requires

check_msg() method to be called regularly

  • A subtask (thread or coroutine) can be created to ensure

check_msg() is continuously called

  • In case of coroutines, do not forget to yield, e.g.,

async def check_mqtt(): while True: mqtt.check_msg() await asyncio.sleep_ms(0)

slide-22
SLIDE 22

22

Co Conclusi sion

  • Complex tasks often require concurrency
  • Three concurrency programming models
  • Event-driven
  • Multithreading
  • Coroutines
slide-23
SLIDE 23

23

As Assignment 5.1: IoT Light Control

  • Make a device to allow lamp control from

(1) a local switch, and (2) the Internet

  • When the local switch is pressed, the lamp's state is

toggled

  • Publish lamp state to ku/daq2020/<nickname>/lamp
  • nly when it is changed
  • Payload 0 → Lamp is off
  • Payload 1 → Lamp is on
  • Also subscribe to ku/daq2020/<nickname>/lamp to

allow controlling the LED from the Internet

http://clipart-library.com/clipart/1168222.htm