Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- import serial
- import urllib.request
- import json
- fake_serial_port = False
- PORT = '/dev/ttyACM0'
- serialPort = serial.Serial()
- try:
- serialPort = serial.Serial(
- port=PORT,
- baudrate=9600,
- parity=serial.PARITY_ODD,
- stopbits=serial.STOPBITS_TWO,
- bytesize=serial.SEVENBITS
- )
- except:
- fake_serial_port = True
- def post_data(text):
- print("Received data: %s" % text)
- body = {'temperature' : [text]}
- myurl = "http://127.0.0.1:5000/postjson"
- req = urllib.request.Request(myurl)
- req.add_header('Content-Type', 'application/json; charset=utf-8')
- jsondata = json.dumps(body)
- jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes
- req.add_header('Content-Length', len(jsondataasbytes))
- print (jsondataasbytes)
- response = urllib.request.urlopen(req, jsondataasbytes)
- return
- if __name__ == "__main__":
- if serialPort.isOpen():
- print("Serial is opened")
- else:
- print("Fake serial port is used")
- fake_serial_port = True
- if fake_serial_port:
- while (True):
- post_data("20.0")
- time.sleep(10)
- while (True):
- bytesToRead = serialPort.inWaiting()
- if bytesToRead > 0:
- data = serialPort.read(bytesToRead)
- text = data.decode().strip()
- post_data(text)
- time.sleep(0.1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement