Compare commits

...

3 Commits
v2.0.1 ... main

Author SHA1 Message Date
kh.kim 310f0b507d Commit message 2025-04-15 15:11:57 +09:00
kh.kim 5eff7bb7d3 Commit message 2025-04-04 13:59:00 +09:00
kh.kim 9722b2b8d0 Commit message 2025-04-04 13:36:26 +09:00
4 changed files with 437 additions and 272 deletions

View File

@ -6,8 +6,8 @@
] ]
}, },
"ref_zero_point": { "ref_zero_point": {
"oilInFlowRate": 3995, "oilInFlowRate": 4005,
"waterInFlowRate": 3984 "waterInFlowRate": 4000
}, },
"cdu_digital_list": { "cdu_digital_list": {
"valve1OpenStatus": [ "valve1OpenStatus": [
@ -101,6 +101,16 @@
"y" "y"
] ]
}, },
"cdu_pdu_list": {
"pduCDU1": [
1,
"y"
],
"pduCDU2": [
2,
"y"
]
},
"tank_device_list": { "tank_device_list": {
"tankLeftTopFrontTemp": [ "tankLeftTopFrontTemp": [
1, 1,
@ -150,5 +160,23 @@
12, 12,
"y" "y"
] ]
},
"tank_pdu_list": {
"pduTank1": [
1,
"n"
],
"pduTank2": [
2,
"n"
],
"pduTank3": [
3,
"n"
],
"pduTank4": [
4,
"n"
]
} }
} }

View File

@ -1,18 +1,18 @@
{ {
"get_data_interval": 1, "get_data_interval": 2,
"set_zero_temperature": "n", "set_zero_flow": "n",
"valve1": "Off", "valve1": "Off",
"valve2": "Off", "valve2": "Off",
"inverter": { "inverter": {
"inverter1": "Off", "inverter1": "Off",
"inverter1Frq": 30, "inverter1Frq": 50,
"inverter1Acc": 5.0, "inverter1Acc": 5.0,
"inverter1Dec": 10.0, "inverter1Dec": 10.0,
"inverter2": "Off", "inverter2": "Off",
"inverter2Frq": 30, "inverter2Frq": 40,
"inverter2Acc": 5.0, "inverter2Acc": 5.0,
"inverter2Dec": 10.0 "inverter2Dec": 10.0
}, },
"mode": "auto", "mode": "auto",
"cmd": "None" "cmd": "none"
} }

View File

@ -8,5 +8,5 @@ spec:
package: requirements.txt # 설치할 Python 패키지 정보 파일입니다.(기본 값은 requirement.txt 입니다.) package: requirements.txt # 설치할 Python 패키지 정보 파일입니다.(기본 값은 requirement.txt 입니다.)
runtime: python3.9 runtime: python3.9
stackbase: stackbase:
tagName: v2.0.1 # Stackbase(gitea)에 릴리즈 태그명 입니다. tagName: v2.0.4 # Stackbase(gitea)에 릴리즈 태그명 입니다.
repoName: aquarack-sensor-collector # Satackbase(gitea)에 저장될 저장소 이릅니다. repoName: aquarack-sensor-collector # Satackbase(gitea)에 저장될 저장소 이릅니다.

435
main.py
View File

@ -2,28 +2,43 @@ import sdtcloudpubsub
import uuid import uuid
from pymodbus.client import ModbusSerialClient as ModbusClient from pymodbus.client import ModbusSerialClient as ModbusClient
import os, json, sys, time import os, json, sys, time
import threading import threading, struct
import serial
sdtcloud = sdtcloudpubsub.sdtcloudpubsub() sdtcloud = sdtcloudpubsub.sdtcloudpubsub()
sdtcloud.setClient(f"device-app-{uuid.uuid1()}") # parameter is client ID(string) sdtcloud.setClient(f"device-app-{uuid.uuid1()}") # parameter is client ID(string)
def get_modbus(evt, serial_obj, file_path): def get_inverter_errorcode(data):
global isThread, g_zero_point, pub_dict, a_col, d_col, t_col, p_col, S_col error_code = ['Reserved', 'OVT', 'EXT-A', 'ETX(BX)', 'COL', 'GFT', 'OHT', 'ETH', 'OLT', 'Reserved', 'EXT-B', 'EEP', 'FAN', 'POT', 'IOLT', 'LVT']
result = [error_code[i] for i in range(16) if (data & (0x8000 >> i)) and error_code[i] != 'Reserved']
return ','.join(result)
ctl_mode = 'None' def get_modbus(evt, serial_obj):
cmd_status = [0, 0, 0, 0] # global isThread, g_zero_point, pub_dict, a_col, d_col, t_col, p_col, S_col, s_col, path
cmd_sub_status = 'None' global isThread, g_zero_point, pub_dict, a_col, d_col, t_col, p_col, S_col, s_col
cmd_status = 'none'
cmd_sub_status = 'none'
inverter_status = [0] * 6 inverter_status = [0] * 6
valve_status = [False] * 8 valve_status = [False] * 8
pre_dict = {}
init_flag = 0
while isThread: while isThread:
evt.wait() evt.wait()
evt.clear() evt.clear()
# with open(os.path.join(file_path, 'control.json'), 'r') as f: # with open(os.path.join(path, 'control.json'), 'r') as f:
with open('./control.json', 'r') as f: with open('./control.json', 'r') as f:
control_data = json.load(f) control_data = json.load(f)
pre_dict = control_data.copy()
try:
res = serial_obj.read_holding_registers(address=0, count=2, slave=20)
# print(f'humidity: {res.registers[0]/10}% / temperature: {res.registers[1]/10}°C')
for i, j in enumerate(s_col):
pub_dict[j] = res.registers[i] / 10
except Exception as e:
print(f'Humidity/Temperature Senseor Error: {e}')
# CWT-TM-320s # CWT-TM-320s
try: try:
@ -42,8 +57,8 @@ def get_modbus(evt, serial_obj, file_path):
# print(f'cdu_analog:{cdu_analog.registers}') # print(f'cdu_analog:{cdu_analog.registers}')
# print(f'cdu_digital:{cdu_digital.bits}') # print(f'cdu_digital:{cdu_digital.bits}')
if control_data['set_zero_temperature'] == 'y': if control_data['set_zero_flow'] == 'y':
# with open(os.path.join(file_path, 'config.json'), 'r') as f: # with open(os.path.join(path, 'config.json'), 'r') as f:
with open('./config.json', 'r') as f: with open('./config.json', 'r') as f:
config_data = json.load(f) config_data = json.load(f)
@ -51,7 +66,7 @@ def get_modbus(evt, serial_obj, file_path):
if j == 'oilInFlowRate' or j == 'waterInFlowRate': if j == 'oilInFlowRate' or j == 'waterInFlowRate':
config_data['ref_zero_point'][j] = cdu_analog.registers[i] config_data['ref_zero_point'][j] = cdu_analog.registers[i]
control_data['set_zero_temperature'] = 'n' control_data['set_zero_flow'] = 'n'
# with open(os.path.join(path, 'config.json'), 'w') as f: # with open(os.path.join(path, 'config.json'), 'w') as f:
with open('./config.json', 'w') as f: with open('./config.json', 'w') as f:
@ -83,13 +98,26 @@ def get_modbus(evt, serial_obj, file_path):
try: try:
# M100 # M100
res = client1.read_holding_registers(address=9, count=6, slave=10) res = client1.read_holding_registers(address=9, count=6, slave=10)
inverter_status[0] = res.registers[0] inverter_status[0] = res.registers[0] / 100 # frequncy
inverter_status[1] = res.registers[5] inverter_status[1] = get_inverter_errorcode(res.registers[5]) # errorcode
inverter_status[2] = res.registers[4] run_status = res.registers[4] # running status
if run_status & 0x01:
inverter_status[2] = 'stop'
elif run_status & 0x02:
inverter_status[2] = 'running'
elif run_status & 0x08:
inverter_status[2] = 'error'
res = client1.read_holding_registers(address=9, count=6, slave=11) res = client1.read_holding_registers(address=9, count=6, slave=11)
inverter_status[3] = res.registers[0] inverter_status[3] = res.registers[0] / 100 # frequncy
inverter_status[4] = res.registers[5] inverter_status[4] = get_inverter_errorcode(res.registers[5]) # errorcode
inverter_status[5] = res.registers[4] run_status = res.registers[4] # running status
if run_status & 0x01:
inverter_status[5] = 'stop'
elif run_status & 0x02:
inverter_status[5] = 'running'
elif run_status & 0x08:
inverter_status[5] = 'error'
for i, j in enumerate(p_col): for i, j in enumerate(p_col):
pub_dict[j] = inverter_status[i] pub_dict[j] = inverter_status[i]
@ -98,58 +126,88 @@ def get_modbus(evt, serial_obj, file_path):
try: try:
if control_data['mode'] == 'auto': if control_data['mode'] == 'auto':
if control_data['cmd'] == 'init': # 방어코드 필요 if control_data['cmd'] == 'init':
if cmd_sub_status == 'None': if cmd_sub_status != 'workingInit':
valve_status[0], valve_status[1] = True, True valve_status[0], valve_status[1] = True, True
res = serial_obj.write_coils(address=0, values=valve_status, slave=5) res = serial_obj.write_coils(address=0, values=valve_status, slave=5)
client1.write_registers(address=5, values=[193], slave=10) client1.write_registers(address=5, values=[193], slave=10)
client1.write_registers(address=5, values=[193], slave=11) client1.write_registers(address=5, values=[193], slave=11)
cmd_status = 'init'
cmd_sub_status = 'workingInit' cmd_sub_status = 'workingInit'
pub_dict['cmd'] = 'init' pub_dict['cmd'] = 'workingInit'
elif cmd_sub_status == 'workingInit': elif cmd_sub_status == 'workingInit':
if (pub_dict['valve1OpenStatus'] == True if (pub_dict['valve1OpenStatus'] == True
and pub_dict['valve2OpenStatus'] == True and pub_dict['valve2OpenStatus'] == True
and (pub_dict['pump1StatusRunning'] & 0x01) and (pub_dict['pump1StatusRunning'] == 'stop')
and (pub_dict['pump2StatusRunning'] & 0x01)): and (pub_dict['pump2StatusRunning'] == 'stop')):
cmd_sub_status = 'None' cmd_status = 'none'
pub_dict['cmd'] = 'None' cmd_sub_status = 'doneInit'
control_data['cmd'] = 'None' pub_dict['cmd'] = 'doneInit'
control_data['cmd'] = 'none'
init_flag = 1
elif control_data['cmd'] == 'emer': # 어느 조건에서든 입력되면 바로 수행
if cmd_sub_status != 'workingEmer':
valve_status[0], valve_status[1] = False, False
res = serial_obj.write_coils(address=0, values=valve_status, slave=5)
client1.write_registers(address=5, values=[208], slave=10)
client1.write_registers(address=5, values=[208], slave=11)
cmd_status = 'emer'
cmd_sub_status = 'workingEmer'
pub_dict['cmd'] = 'emer'
init_flag = 0
elif cmd_sub_status == 'workingEmer':
if (pub_dict['valve1CloseStatus'] == True
and pub_dict['valve2CloseStatus'] == True
and (pub_dict['pump1StatusRunning'] == 'stop')
and (pub_dict['pump2StatusRunning'] == 'stop')):
cmd_sub_status = 'none'
control_data['cmd'] = 'none'
elif control_data['cmd'] == 'stop' or cmd_status == 'stop':
if init_flag == 0:
continue
if cmd_status == 'none' or cmd_status == 'stop' or cmd_status == 'act1' or cmd_status == 'act2':
client1.write_registers(address=5, values=[193], slave=10)
client1.write_registers(address=5, values=[193], slave=11)
if not ((pub_dict['pump1StatusRunning'] == 'stop')
and (pub_dict['pump2StatusRunning'] == 'stop')):
cmd_status = 'stop'
cmd_sub_status = 'stopping'
pub_dict['cmd'] = 'stopping'
elif ((pub_dict['pump1StatusRunning'] == 'stop')
and (pub_dict['pump2StatusRunning'] == 'stop')):
cmd_status = 'none'
cmd_sub_status = 'stop'
pub_dict['cmd'] = 'stop'
control_data['cmd'] = 'none'
elif control_data['cmd'] == 'act1': elif control_data['cmd'] == 'act1':
if cmd_sub_status == 'None': if init_flag == 0:
if (pub_dict['pump1StatusRunning'] & 0x02 continue
and pub_dict['pump2StatusRunning'] & 0x01 if cmd_status == 'none' or cmd_status == 'act1':
and pub_dict['valve1OpenStatus'] == True if cmd_sub_status == 'doneInit' or cmd_sub_status == 'stop':
and pub_dict['valve2CloseStatus'] == True): cmd_status = 'act1'
cmd_stataus = 'None' cmd_sub_status = 'closeValve2'
control_data['cmd'] = 'None' pub_dict['cmd'] = 'startAct1'
else:
cmd_stataus = 'act1'
pub_dict['cmd'] = 'act1'
cmd_sub_status = 'stopPump1'
elif cmd_sub_status == 'stopPump1': elif cmd_sub_status == 'workingPump2':
if not (pub_dict['pump1StatusRunning'] & 0x01): cmd_status = 'act1'
client1.write_registers(address=5, values=[193], slave=10)
cmd_sub_status = 'stoppingPump1'
else:
cmd_sub_status = 'stopPump2'
elif cmd_sub_status == 'stoppingPump1':
if pub_dict['pump1StatusRunning'] & 0x01:
cmd_sub_status = 'stopPump2' cmd_sub_status = 'stopPump2'
pub_dict['cmd'] = 'startAct1'
elif cmd_sub_status == 'stopPump2': elif cmd_sub_status == 'stopPump2':
if not (pub_dict['pump2StatusRunning'] & 0x01): if not (pub_dict['pump2StatusRunning'] == 'stop'):
client1.write_registers(address=5, values=[193], slave=11) client1.write_registers(address=5, values=[193], slave=11)
cmd_sub_status = 'stoppingPump2' cmd_sub_status = 'stoppingPump2'
else: else:
cmd_sub_status = 'closeValve2' cmd_sub_status = 'closeValve2'
elif cmd_sub_status == 'stoppingPump2': elif cmd_sub_status == 'stoppingPump2':
if pub_dict['pump2StatusRunning'] & 0x01: if pub_dict['pump2StatusRunning'] == 'stop':
cmd_sub_status = 'closeValve2' cmd_sub_status = 'closeValve2'
elif cmd_sub_status == 'closeValve2': elif cmd_sub_status == 'closeValve2':
@ -184,43 +242,42 @@ def get_modbus(evt, serial_obj, file_path):
cmd_sub_status = 'startingPump1' cmd_sub_status = 'startingPump1'
elif cmd_sub_status == 'startingPump1': elif cmd_sub_status == 'startingPump1':
if pub_dict['pump1StatusRunning'] & 0x40: if pub_dict['pump1StatusRunning'] == 'running':
cmd_sub_status = 'None' cmd_status = 'none'
control_data['cmd'] = 'None' cmd_sub_status = 'workingPump1'
pub_dict['cmd'] = 'workingAct1'
control_data['cmd'] = 'none'
else:
client1.write_registers(address=5, values=[193], slave=10)
client1.write_registers(address=5, values=[193], slave=11)
pub_dict['cmd'] = 'errorAct1'
cmd_status = 'errorAct1'
cmd_sub_status = 'errorPump1'
init_flag = 0
elif control_data['cmd'] == 'act2': elif control_data['cmd'] == 'act2':
if cmd_sub_status == 'None': if init_flag == 0:
if (pub_dict['pump1StatusRunning'] & 0x01 continue
and pub_dict['pump2StatusRunning'] & 0x02 if cmd_status == 'none' or cmd_status == 'act2':
and pub_dict['valve1CloseStatus'] == True if cmd_sub_status == 'doneInit' or cmd_sub_status == 'stop':
and pub_dict['valve2OpenStatus'] == True): cmd_status = 'act2'
cmd_stataus = 'None' cmd_sub_status = 'closeValve1'
control_data['cmd'] = 'None' pub_dict['cmd'] = 'startAct2'
else:
cmd_stataus = 'act2' elif cmd_sub_status == 'workingPump1':
pub_dict['cmd'] = 'act2' cmd_status = 'act2'
cmd_sub_status = 'stopPump1' cmd_sub_status = 'stopPump1'
pub_dict['cmd'] = 'startAct2'
elif cmd_sub_status == 'stopPump1': elif cmd_sub_status == 'stopPump1':
if not (pub_dict['pump1StatusRunning'] & 0x01): if not (pub_dict['pump1StatusRunning'] == 'stop'):
client1.write_registers(address=5, values=[193], slave=10) client1.write_registers(address=5, values=[193], slave=10)
cmd_sub_status = 'stoppingPump1' cmd_sub_status = 'stoppingPump1'
else:
cmd_sub_status = 'stopPump2'
elif cmd_sub_status == 'stoppingPump1':
if pub_dict['pump1StatusRunning'] & 0x01:
cmd_sub_status = 'stopPump2'
elif cmd_sub_status == 'stopPump2':
if not (pub_dict['pump2StatusRunning'] & 0x01):
client1.write_registers(address=5, values=[193], slave=11)
cmd_sub_status = 'stoppingPump2'
else: else:
cmd_sub_status = 'closeValve1' cmd_sub_status = 'closeValve1'
elif cmd_sub_status == 'stoppingPump2': elif cmd_sub_status == 'stoppingPump1':
if pub_dict['pump2StatusRunning'] & 0x01: if pub_dict['pump1StatusRunning'] == 'stop':
cmd_sub_status = 'closeValve1' cmd_sub_status = 'closeValve1'
elif cmd_sub_status == 'closeValve1': elif cmd_sub_status == 'closeValve1':
@ -255,30 +312,26 @@ def get_modbus(evt, serial_obj, file_path):
cmd_sub_status = 'startingPump2' cmd_sub_status = 'startingPump2'
elif cmd_sub_status == 'startingPump2': elif cmd_sub_status == 'startingPump2':
if pub_dict['pump2StatusRunning'] & 0x40: if pub_dict['pump2StatusRunning'] == 'running':
cmd_sub_status = 'None' cmd_status = 'none'
control_data['cmd'] = 'None' cmd_sub_status = 'workingPump2'
pub_dict['cmd'] = 'workingAct2'
control_data['cmd'] = 'none'
else:
client1.write_registers(address=5, values=[193], slave=10)
client1.write_registers(address=5, values=[193], slave=11)
pub_dict['cmd'] = 'errorAct2'
cmd_status = 'errorAct2'
cmd_sub_status = 'errorPump2'
init_flag = 0
elif control_data['cmd'] == 'emer': # 어느 조건에서든 입력되면 바로 수행 else:
if cmd_sub_status == 'None': if isinstance(pub_dict['cmd'], (int, float)):
valve_status[0], valve_status[1] = False, False pub_dict['cmd'] = 'none'
res = serial_obj.write_coils(address=0, values=valve_status, slave=5)
client1.write_registers(address=5, values=[208], slave=10)
client1.write_registers(address=5, values=[208], slave=11)
cmd_sub_status = 'workingEmer'
pub_dict['cmd'] = 'emer'
elif cmd_sub_status == 'workingEmer':
if (pub_dict['valve1CloseStatus'] == True
and pub_dict['valve2CloseStatus'] == True
and (pub_dict['pump1StatusRunning'] & 0x01)
and (pub_dict['pump2StatusRunning'] & 0x01)):
cmd_sub_status = 'None'
pub_dict['cmd'] = 'None'
control_data['cmd'] = 'None'
elif control_data['mode'] == 'manual': elif control_data['mode'] == 'manual':
if control_data != pre_dict:
pub_dict['cmd'] = 'manual'
if control_data['inverter']['inverter1'] == 'On' and cmd_status[0] == 0: if control_data['inverter']['inverter1'] == 'On' and cmd_status[0] == 0:
frq = int(control_data['inverter']['inverter1Frq'] * 100) frq = int(control_data['inverter']['inverter1Frq'] * 100)
acc = int(control_data['inverter']['inverter1Acc'] * 10) acc = int(control_data['inverter']['inverter1Acc'] * 10)
@ -314,15 +367,17 @@ def get_modbus(evt, serial_obj, file_path):
cmd_status[3] = 0 cmd_status[3] = 0
res = serial_obj.write_coils(address=0, values=valve_status, slave=5) res = serial_obj.write_coils(address=0, values=valve_status, slave=5)
else:
pre_dict = control_data.copy()
elif control_data['mode'] == 'None': elif control_data['mode'] == 'none':
valve_status[0], valve_status[1] = False, False valve_status[0], valve_status[1] = False, False
res = serial_obj.write_coils(address=0, values=valve_status, slave=5) res = serial_obj.write_coils(address=0, values=valve_status, slave=5)
client1.write_registers(address=5, values=[193], slave=10) client1.write_registers(address=5, values=[193], slave=10)
client1.write_registers(address=5, values=[193], slave=11) client1.write_registers(address=5, values=[193], slave=11)
else: else:
pub_dict['cmd'] = 'None' pub_dict['cmd'] = 'none'
except Exception as e: except Exception as e:
print(f'Device Setting Error: {e}') print(f'Device Setting Error: {e}')
@ -331,6 +386,7 @@ def get_modbus(evt, serial_obj, file_path):
# with open(os.path.join(path, 'control.json'), 'w') as f: # with open(os.path.join(path, 'control.json'), 'w') as f:
with open('./control.json', 'w') as f: with open('./control.json', 'w') as f:
json.dump(control_data, f, indent=4) json.dump(control_data, f, indent=4)
pre_dict = control_data.copy()
def get_sensor(evt, serial_obj): def get_sensor(evt, serial_obj):
global isThread, pub_dict, s_col global isThread, pub_dict, s_col
@ -345,78 +401,129 @@ def get_sensor(evt, serial_obj):
except Exception as e: except Exception as e:
print(f'Error: {e}') print(f'Error: {e}')
def get_pdu(evt, serial_obj):
global isThread, pub_dict, cp_col, tp_col
pdu_dict = {
'pduCDU1': '1E',
'pduCDU2': '1F',
'pduTank1': '28',
'pduTank2': '29',
'pduTank3': '2A',
'pduTank4': '2B'
}
pdu_list = cp_col + tp_col
pdu_list = [col for col in pdu_list if col != 0]
# print(pdu_list)
while isThread:
evt.wait()
evt.clear()
for pdu in pdu_list:
rcv_data = []
sum = 0
cnt = 0
command_hex = f'FEFF{pdu_dict[pdu]}01010000'
# print(command_hex)
command_bytes = bytes.fromhex(command_hex)
for x in command_bytes[2:]:
sum += x
sum = sum & 0xff
sum = struct.pack('>B', sum)
snd_bytes = command_bytes + b'\x00' + sum + b'\xfd'
# print(f'snd_bytes: {snd_bytes}')
serial_obj.write(snd_bytes)
while True:
res = serial_obj.read(1)
# print(res)
if res != b'':
rcv_data.append(res)
else:
cnt += 1
if cnt == 10:
break
if len(rcv_data) >= 2:
if not(rcv_data[0] == b'\xfc' and rcv_data[1] == b'\xff'):
rcv_data = []
break
elif rcv_data[:-1] == b'\xfd':
break
if len(rcv_data):
sum = 0
# print(f'rcv_data: {rcv_data}')
for x in rcv_data[2:-3]:
sum += int.from_bytes(x, byteorder='big')
sum = sum & 0xff
sum = struct.pack('>B', sum)
# print(f'sum: {sum}')
if rcv_data[-2] == sum:
byte_val = rcv_data[10:12]
int_val = int.from_bytes(byte_val[0] + byte_val[1], byteorder='big')
int_val /= 100
pub_dict[pdu] = int_val
else:
continue
def runAction(evt):
global isThread, pub_dict
cnt = 0
while isThread:
evt.wait()
evt.clear()
if cnt:
# print(pub_dict)
sdtcloud.pubMessage(pub_dict)
else:
cnt += 1
def timer_s0(evt): def timer_s0(evt):
global isThread global isThread
while isThread: while isThread:
evt.set() evt.set()
time.sleep(1) time.sleep(0.5)
def timer_s1(evt): def timer_s1(evt):
global isThread global isThread
while isThread: while isThread:
evt.set() evt.set()
time.sleep(5) time.sleep(0.5)
def runAction(): def timer_s2(evt, interval):
global ctl_data, pub_data global isThread
sum_data = {key: 0.0 for key in pub_dict.keys()}
cnt, cnt_limit = 0, 0 while isThread:
interval = int(ctl_data['get_data_interval']) evt.set()
time.sleep(interval)
if interval <= 5:
cnt_limit = 1
elif interval <= 1800:
cnt_limit = 10
else:
cnt_limit = 100
act = 0
while True:
start = int(time.time() * 1000)
for key, value in pub_data.items():
try:
sum_data[key] += value
except:
sum_data[key] = value
end = int(time.time() * 1000)
diff = end - start
sleep_time = int(interval / cnt_limit) - (diff * 0.001)
cnt += 1
if cnt == cnt_limit:
snd_data = {key: value / cnt_limit for key, value in sum_data.items()}
sdtcloud.pubMessage(snd_data)
cnt = 0
sum_data = {key: 0.0 for key in pub_dict.keys()}
time.sleep(sleep_time)
if __name__ == "__main__": if __name__ == "__main__":
os.system(f'chmod 777 /dev/ttyS0') pw = 'Sdt2513!@'
os.system(f'chmod 777 /dev/ttyS1') os.system(f'echo {pw} | sudo -S chmod 777 /dev/ttyS0')
os.system(f'echo {pw} | sudo -S chmod 777 /dev/ttyS1')
port_name_1 = '/dev/ttyS0' port_name_1 = '/dev/ttyS0'
client1 = ModbusClient(port=port_name_1, baudrate=19200, parity='N', stopbits=1, bytesize=8, timeout=0.25) client1 = ModbusClient(port=port_name_1, baudrate=9600, parity='N', stopbits=1, bytesize=8, timeout=0.25)
port_name_2 = '/dev/ttyS1' port_name_2 = '/dev/ttyS1'
client2 = ModbusClient(port=port_name_2, baudrate=9600, parity='N', stopbits=1, bytesize=8, timeout=0.25) client2 = serial.Serial(port=port_name_2, baudrate=19200, parity='N', stopbits=1, bytesize=8, timeout=0.1)
try: try:
client1.connect() client1.connect()
client2.connect()
except: except:
sys.exit(0) sys.exit(0)
g_zero_point = [0] * 2 # path = '/home/sdtadmin/aquarack-sensor-collector'
# path = '/home/ecn-2u/Aquarack/21u'
# with open(os.path.join(path, 'config.json'), 'r') as config: # with open(os.path.join(path, 'config.json'), 'r') as config:
with open('./config.json', 'r') as config: with open('./config.json', 'r') as config:
cfg_data = json.load(config) cfg_data = json.load(config)
g_zero_point = [cfg_data['ref_zero_point']['oilInFlowRate'], cfg_data['ref_zero_point']['waterInFlowRate']]
# with open(os.path.join(path, 'control.json'), 'r') as control: # with open(os.path.join(path, 'control.json'), 'r') as control:
with open('./control.json', 'r') as control: with open('./control.json', 'r') as control:
ctl_data = json.load(control) ctl_data = json.load(control)
@ -427,38 +534,58 @@ if __name__ == "__main__":
len_s_col = len(cfg_data['cdu_sensor_list']) len_s_col = len(cfg_data['cdu_sensor_list'])
len_p_col = len(cfg_data['cdu_device_list']) len_p_col = len(cfg_data['cdu_device_list'])
len_S_col = len(cfg_data['status']) len_S_col = len(cfg_data['status'])
len_cp_col = len(cfg_data['cdu_pdu_list'])
len_tp_col = len(cfg_data['tank_pdu_list'])
a_col = [0] * len_a_col a_col = [0] * len_a_col
t_col = [0] * len_t_col t_col = [0] * len_t_col
d_col = [0] * len_d_col d_col = [0] * len_d_col
s_col = [0] * len_s_col s_col = [0] * len_s_col
p_col = [0] * len_p_col p_col = [0] * len_p_col
S_col = [0] * len_S_col S_col = [0] * len_S_col
cp_col = [0] * len_cp_col
tp_col = [0] * len_tp_col
for key, value in cfg_data['cdu_analog_list'].items(): for key, value in cfg_data['cdu_analog_list'].items():
if value[1] == 'y': if value[1] == 'y':
a_col[value[0] - 1] = key a_col[value[0] - 1] = key
a_col = [col for col in a_col if col != 0]
for key, value in cfg_data['tank_device_list'].items(): for key, value in cfg_data['tank_device_list'].items():
if value[1] == 'y': if value[1] == 'y':
t_col[value[0] - 1] = key t_col[value[0] - 1] = key
t_col = [col for col in t_col if col != 0]
for key, value in cfg_data['cdu_digital_list'].items(): for key, value in cfg_data['cdu_digital_list'].items():
if value[1] == 'y': if value[1] == 'y':
d_col[value[0] - 1] = key d_col[value[0] - 1] = key
d_col = [col for col in d_col if col != 0]
for key, value in cfg_data['cdu_sensor_list'].items(): for key, value in cfg_data['cdu_sensor_list'].items():
if value[1] == 'y': if value[1] == 'y':
s_col[value[0] - 1] = key s_col[value[0] - 1] = key
s_col = [col for col in s_col if col != 0]
for key, value in cfg_data['cdu_device_list'].items(): for key, value in cfg_data['cdu_device_list'].items():
if value[1] == 'y': if value[1] == 'y':
p_col[value[0] - 1] = key p_col[value[0] - 1] = key
p_col = [col for col in p_col if col != 0]
for key, value in cfg_data['status'].items(): for key, value in cfg_data['status'].items():
if value[1] == 'y': if value[1] == 'y':
S_col[value[0] - 1] = key S_col[value[0] - 1] = key
S_col = [col for col in S_col if col != 0]
pub_dict = {key: 0.0 for key in (a_col+t_col+d_col+s_col+p_col+S_col)} for key, value in cfg_data['cdu_pdu_list'].items():
if value[1] == 'y':
cp_col[value[0] - 1] = key
cp_col = [col for col in cp_col if col != 0]
for key, value in cfg_data['tank_pdu_list'].items():
if value[1] == 'y':
tp_col[value[0] - 1] = key
tp_col = [col for col in tp_col if col != 0]
pub_dict = {key: 0.0 for key in (a_col+t_col+d_col+s_col+p_col+S_col+cp_col+tp_col)}
# print(f'a_col: {a_col}') # print(f'a_col: {a_col}')
# print(f't_col: {t_col}') # print(f't_col: {t_col}')
@ -471,19 +598,29 @@ if __name__ == "__main__":
timer_evt_s0 = threading.Event() timer_evt_s0 = threading.Event()
timer_evt_s1 = threading.Event() timer_evt_s1 = threading.Event()
timer_evt_s2 = threading.Event()
timer_evt_s0.set() timer_evt_s0.set()
timer_evt_s1.set() timer_evt_s1.set()
timer_evt_s2.set()
thr_modbus_rtu = threading.Thread(target=get_modbus, args=(timer_evt_s0, client1, path,))
thr_modbus_rtu.start()
thr_get_sensor = threading.Thread(target=get_sensor, args=(timer_evt_s1, client2,))
thr_get_sensor.start()
thr_evt_s0 = threading.Thread(target=timer_s0, args=(timer_evt_s0,)) thr_evt_s0 = threading.Thread(target=timer_s0, args=(timer_evt_s0,))
thr_evt_s1 = threading.Thread(target=timer_s1, args=(timer_evt_s1,)) thr_evt_s1 = threading.Thread(target=timer_s1, args=(timer_evt_s1,))
thr_evt_s2 = threading.Thread(target=timer_s2, args=(timer_evt_s2, ctl_data['get_data_interval'],))
thr_evt_s0.start() thr_evt_s0.start()
thr_evt_s1.start() thr_evt_s1.start()
thr_evt_s2.start()
thr_run = threading.Thread(target=runAction, args=()) thr_modbus_rtu = threading.Thread(target=get_modbus, args=(timer_evt_s0, client1, ))
thr_modbus_rtu.start()
# thr_get_sensor = threading.Thread(target=get_sensor, args=(timer_evt_s1, client2,))
# thr_get_sensor.start()
thr_get_pdu = threading.Thread(target=get_pdu, args=(timer_evt_s1, client2, ))
thr_get_pdu.start()
thr_run = threading.Thread(target=runAction, args=(timer_evt_s2, ))
thr_run.start() thr_run.start()