-
Notifications
You must be signed in to change notification settings - Fork 1
/
data_collector.py
86 lines (69 loc) · 2.43 KB
/
data_collector.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# -*- coding: utf-8 -*-#
""" xxx.
---- Info ----
C3D Kft. - Minden jog fenntartva a birtoklásra, felhasználásra,
sokszorosításra, szerkesztésre, értékesítésre nézve, valamint az ipari
tulajdonjog hatálya alá eső felhasználások esetén is.
www.C3D.hu
"""
# First import should be the logging module if any!
import logging
import threading
import serial
import platform
from queue import Queue
log = logging.getLogger("Main")
que = Queue()
FLAG = False
log.info("OS: {0}, {1}".format(platform.system(), platform.node()))
# Linux
# uname_result(system='Linux', node='raspberrypi', release='5.10.17-v7+',
# version='#1414 SMP Fri Apr 30 13:18:35 BST 2021',
# machine='armv7l', processor='')
# Windows
# uname_result(system='Windows', node='tm04', release='10',
# version='10.0.19045', machine='AMD64')
if platform.system() == "Windows":
serial_port = 'COM11'
elif platform.system() == "Linux" and platform.node() == "raspberrypi":
serial_port = '/dev/ttyACM0'
# ‘/dev/ttyACM0’
baud_rate = 9600
def main():
# NOTE: Arduino restarts when a new serial comm. is initiated
ser = serial.Serial(serial_port, baud_rate, timeout=5)
while True:
read_serial = ser.readline()
que.put(read_serial)
log.info(read_serial)
if not FLAG:
break
def start_collect():
global FLAG
FLAG = True
secondary_thread = threading.Thread(target=main)
secondary_thread.start()
def stop_collect():
global FLAG
FLAG = False
def save_data(filename):
""" Write the contents of the queue to a specified file. """
with open(filename, "w") as file:
found = False
log.info("Start processing queue...")
while not que.empty(): # Writing data to a file
# NOTE: Arduino serial uses 'raw' encoding, it is defined by the
# code itself
# NOTE: Decoding errors are ignored, otherwise the code breaks
string = que.get().decode("ascii", "ignore")
log.info("Processing: {0}".format(string.rstrip()))
log.debug("Found: {0}".format(found))
# Search for header, and ignore all lines before that
if not found:
idx = string.find("Set")
log.debug("Found 'Set': {0}".format(idx))
if idx != -1:
found = True
if found:
file.write(f"{string}") # Empties the queue
log.info("File saved!")