Advertisement
Guest User

Untitled

a guest
Jun 20th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.41 KB | None | 0 0
  1. from threading import Thread
  2. from serial import Serial
  3. import json
  4. import sys
  5. import csv
  6. import re
  7. from time import sleep, clock
  8. from serial.serialutil import SerialException
  9. from serial.tools import list_ports
  10. Arduino = __import__("Arduino").Arduino
  11.  
  12. class DataManager(Thread):
  13.  
  14.     def __init__(self, isOn = True, toWrite = False,
  15.         fileName = None, *sensorsToRead):
  16.         super(DataManager, self).__init__()
  17.         self.isOn = isOn
  18.         self.toWrite = toWrite
  19.         self.sensorsToRead = sensorsToRead
  20.         self.fileName = fileName
  21.         self.procesed = None
  22.         self.Arduino = Arduino()
  23.         self.count = 0
  24.         self.plugged = True
  25.         self.regexp = re.compile(r'{("module":")(DHT22|MQ[379])","(value":\d+(\.\d+)?|temp":\d+(\.\d+)?,"humidity":\d+(\.\d+)?)}')
  26.         self.cond = None
  27.  
  28.     def run(self):
  29.         comport = self._initializeCOMPort()
  30.         fp = False
  31.         if self.toWrite:
  32.             fp = open(self.fileName, "a", newline='')
  33.             csvw = csv.writer(fp, delimiter=',')
  34.             sensors = self.Arduino.getSensors()
  35.         try:
  36.             comport.open()
  37.         except SerialException:
  38.             while(self.reconnect()):
  39.                 pass
  40.             comport.close()
  41.             comport.open()
  42.             self.plugged = True
  43.  
  44.         while(self.getStatus()):
  45.             sleep(0.03)
  46.             try:
  47.                 readed = self._read(comport)
  48.             except SerialException:
  49.                 while(self.reconnect()):
  50.                     pass
  51.                 comport.close()
  52.                 comport.open()
  53.                 self.plugged = True
  54.             try:
  55.                 self.cond = self.regexp.match(str(readed, 'utf-8')).string
  56.             except AttributeError:
  57.                 continue
  58.             self.procesed = self._parse(readed)
  59.             if(self.cond and self.procesed):
  60.                 self.Arduino.updateSensor(self.procesed)
  61.                 s = self.procesed["module"]
  62.                 if self.toWrite:
  63.                     if(s in self.sensorsToRead):
  64.                         if(s == "DHT22"):
  65.                             data = [s, "h", sensors[s].humidity, "t", sensors[s].temperature]
  66.                         else:
  67.                             data = [s,sensors[s].value]
  68.                         csvw.writerow(data)
  69.         print("Saliendo de DM")
  70.         if(fp):
  71.             fp.close()
  72.         comport.close()
  73.  
  74.     def reconnect(self):
  75.         sleep(0.1)
  76.         self.plugged = False
  77.         for dev in list_ports.comports():
  78.             if("Arduino" in dev.description):
  79.                 return False
  80.         else:
  81.             return True
  82.  
  83.     def _read(self, comport):
  84.         raw = comport.readline()
  85.         return raw
  86.  
  87.     def _parse(self, raw):
  88.         try:
  89.             asDict = json.loads(raw)
  90.         except ValueError:
  91.             return False
  92.         return asDict
  93.  
  94.     def load(self, path):
  95.         rows = []
  96.         try:        
  97.             with open(path, 'r') as f:
  98.                 rows = f.readlines()
  99.         except FileNotFoundError:
  100.             return -1
  101.         return rows                
  102.  
  103.     def _initializeCOMPort(self):
  104.         comport = Serial()
  105.         comport.baudrate = 9600
  106.         comport.port = "COM4"
  107.         return comport
  108.    
  109.     def setStatus(self, boolValue):
  110.         self.isOn = boolValue
  111.    
  112.     def getStatus(self):
  113.         return self.isOn
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement