0

I have an app where I'm monitoring the state of a switch while presenting a url for a user to activate another switch:

door="closed"
def switch():
  global door
  #handle GPIO SETUP
  button_state = GPIO.input(#pin)
  if button_state == True:
    if door=="closed":
      door="open"
  if button_state == False:
    door="closed"

def door_loop():
  while True:
    switch()
    #printing door here returns either open or closed
    time.sleep(1);

@app.route("/click", methods=['GET','POST'])
  def clicky():
    command = request.data
    if command:
      #turn other switch on

  return json.dumps({'is_open':door})


if __name__ == '__main__':
  p = Process(target=door_loop)
  p.start()

  app.run(
    host="0.0.0.0",
    port=int("5000"),
    debug=True
  )
  p.join()

If I print out door after the function call to switch() I get the expected output when the door opens or closes (when I push the switch, I see "open" when I let it go, I see "closed"). But when I visit http://myapp.com/click I get {'is_open':'closed'} no matter what the state of the switch is. Is there something that prevents flask from inheriting the modified global variable from the other process?

Ryan
  • 433
  • 1
  • 11
  • 29

1 Answers1

0

Because the variable door is not shared between flask and the Process. You need to use Value from multiprocessing

from multiprocessing import Process, Value
door = Value('i', 0)

def switch():
  global door
  #handle GPIO SETUP
  button_state = GPIO.input(#pin)
  if button_state == True:
      door.value = 1
  else:
      door.value = 2

def door_loop():
  while True:
    switch()
    #printing door here returns either open or closed
    time.sleep(1);

@app.route("/click", methods=['GET','POST'])
def clicky():
    command = request.data
    if command:
      #turn other switch on

    return json.dumps({'is_open': 'open' if door.value else 'closed'})


if __name__ == '__main__':
  p = Process(target=door_loop)
  p.start()

  app.run(
    host="0.0.0.0",
    port=int("5000"),
    debug=True
  )
  p.join()

Note that raspberry pi supports events driven programming, so you might want to try that instead of looping.

e4c5
  • 52,766
  • 11
  • 101
  • 134