Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from threading import Thread
- from serial import Serial
- import json
- import sys
- import csv
- import re
- from time import sleep, clock
- from serial.serialutil import SerialException
- from serial.tools import list_ports
- Arduino = __import__("Arduino").Arduino
- class DataManager(Thread):
- def __init__(self, isOn = True, toWrite = False,
- fileName = None, *sensorsToRead):
- super(DataManager, self).__init__()
- self.isOn = isOn
- self.toWrite = toWrite
- self.sensorsToRead = sensorsToRead
- self.fileName = fileName
- self.procesed = None
- self.Arduino = Arduino()
- self.count = 0
- self.plugged = True
- self.regexp = re.compile(r'{("module":")(DHT22|MQ[379])","(value":\d+(\.\d+)?|temp":\d+(\.\d+)?,"humidity":\d+(\.\d+)?)}')
- self.cond = None
- def run(self):
- comport = self._initializeCOMPort()
- fp = False
- if self.toWrite:
- fp = open(self.fileName, "a", newline='')
- csvw = csv.writer(fp, delimiter=',')
- sensors = self.Arduino.getSensors()
- try:
- comport.open()
- except SerialException:
- while(self.reconnect()):
- pass
- comport.close()
- comport.open()
- self.plugged = True
- while(self.getStatus()):
- sleep(0.03)
- try:
- readed = self._read(comport)
- except SerialException:
- while(self.reconnect()):
- pass
- comport.close()
- comport.open()
- self.plugged = True
- try:
- self.cond = self.regexp.match(str(readed, 'utf-8')).string
- except AttributeError:
- continue
- self.procesed = self._parse(readed)
- if(self.cond and self.procesed):
- self.Arduino.updateSensor(self.procesed)
- s = self.procesed["module"]
- if self.toWrite:
- if(s in self.sensorsToRead):
- if(s == "DHT22"):
- data = [s, "h", sensors[s].humidity, "t", sensors[s].temperature]
- else:
- data = [s,sensors[s].value]
- csvw.writerow(data)
- print("Saliendo de DM")
- if(fp):
- fp.close()
- comport.close()
- def reconnect(self):
- sleep(0.1)
- self.plugged = False
- for dev in list_ports.comports():
- if("Arduino" in dev.description):
- return False
- else:
- return True
- def _read(self, comport):
- raw = comport.readline()
- return raw
- def _parse(self, raw):
- try:
- asDict = json.loads(raw)
- except ValueError:
- return False
- return asDict
- def load(self, path):
- rows = []
- try:
- with open(path, 'r') as f:
- rows = f.readlines()
- except FileNotFoundError:
- return -1
- return rows
- def _initializeCOMPort(self):
- comport = Serial()
- comport.baudrate = 9600
- comport.port = "COM4"
- return comport
- def setStatus(self, boolValue):
- self.isOn = boolValue
- def getStatus(self):
- return self.isOn
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement