2

I have an Arduino which sends a JSON packet to a Python process (PP1). This Python process will run continuously. But this process has to invite and receive JSON packets to another Python process (PP2). Basically PP1 has to pass the JSON packet received from Arduino to PP2. And PP1 has to receive commands packets from PP2 (can be in JSON format too).

Link to architecture image:

architecture

Bellow a begin the code of Python process 1

import json

#open port
serialport = serial.Serial('COM5',38400,timeout=1,stopbits=serial.STOPBITS_TWO);
time.sleep(1);

#loop
while(True):
    #receive arduino data
    receive = serialport.readline()

    #vparse json
    try:
        test = json.loads(receive)
    except:
        print Exception.message
    else:
        print json.dumps(test)

Do you know a simple way to do this? Is multithreading necessary?

gre_gor
  • 6,669
  • 9
  • 47
  • 52

1 Answers1

1

You'll need "somewhere" to put your data. The most simple solution would be using multiprocessing.Queue, if you need to scale maybe you can look into some job queue (huey, celery, django_q).

An example using multiprocessing.Queue:

import multiprocessing

def pp1(q, data):
      processed_data = data_processing(data) # do some data processing and its result
      q.put(processed_data)

def pp2(q):
    result = q.get()
    show_results(result) # show results to the user


if __name__ == '__main__':
    queue = multiprocessing.Queue()

    process_1 = multiprocessing.Process(target=pp1, args=(queue,))
    process_1.start()

    process_2 = multiprocessing.Process(target=pp2, args=(queue,))
    process_2.start()

Your loops would be the data_processing and show_results (dummy) functions.

You can read more about process communication here: https://pymotw.com/3/multiprocessing/communication.html

Hope it helps

  • Thanks. The Python Process 2 (pp2) is a django application. The solution above can be applied to a django application? Sorry, but i newbie in python applications – FelipeFonsecabh Jul 12 '17 at 23:08
  • In that case I would use something like django_q or celery, and have Django read from a job queue (or database) instead. If the process rendering the results to the enduser must be real time, maybe you'll need to read about Django Channels – Luis Alberto Santana Jul 13 '17 at 14:40