Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. import time
  2. import serial
  3. import urllib.request
  4. import json
  5.  
  6. fake_serial_port = False
  7. PORT = '/dev/ttyACM0'
  8.  
  9. serialPort = serial.Serial()
  10. try:
  11.     serialPort = serial.Serial(
  12.             port=PORT,
  13.             baudrate=9600,
  14.             parity=serial.PARITY_ODD,
  15.             stopbits=serial.STOPBITS_TWO,
  16.             bytesize=serial.SEVENBITS
  17.         )
  18. except:
  19.     fake_serial_port = True
  20.  
  21. def post_data(text):
  22.     print("Received data: %s" % text)
  23.     body = {'temperature' : [text]}
  24.     myurl = "http://127.0.0.1:5000/postjson"
  25.     req = urllib.request.Request(myurl)
  26.     req.add_header('Content-Type', 'application/json; charset=utf-8')
  27.     jsondata = json.dumps(body)
  28.     jsondataasbytes = jsondata.encode('utf-8')   # needs to be bytes
  29.     req.add_header('Content-Length', len(jsondataasbytes))
  30.     print (jsondataasbytes)
  31.     response = urllib.request.urlopen(req, jsondataasbytes)
  32.     return
  33.  
  34. if __name__ == "__main__":
  35.     if serialPort.isOpen():
  36.         print("Serial is opened")
  37.     else:
  38.         print("Fake serial port is used")
  39.         fake_serial_port = True
  40.  
  41.     if fake_serial_port:
  42.         while (True):
  43.             post_data("20.0")
  44.             time.sleep(10)
  45.  
  46.     while (True):
  47.         bytesToRead = serialPort.inWaiting()
  48.         if bytesToRead > 0:
  49.             data = serialPort.read(bytesToRead)
  50.             text = data.decode().strip()
  51.             post_data(text)
  52.         time.sleep(0.1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement