Compare commits

...

46 Commits
v0.0.5 ... main

Author SHA1 Message Date
support.sampyo 61e7c3d4b7 Commit message 2024-10-10 07:53:25 +00:00
support.sampyo 5297824869 Commit message 2024-10-10 07:00:26 +00:00
support.sampyo 50a6bf2373 Commit message 2024-07-30 05:22:35 +00:00
support.sampyo 5c1d08ee98 Commit message 2024-07-30 04:55:55 +00:00
support.sampyo 95921c49b8 Commit message 2024-07-30 04:50:07 +00:00
support.sampyo 44c6a224c2 Commit message 2024-07-04 06:19:55 +00:00
support.sampyo 797816a6f5 Commit message 2024-07-04 06:14:16 +00:00
support.sampyo 5c41e0664d Commit message 2024-07-04 05:50:25 +00:00
support.sampyo f54f9e7fb5 Commit message 2024-07-04 05:45:11 +00:00
support.sampyo ad62a2f89e Commit message 2024-07-04 05:26:04 +00:00
support.sampyo c566b4070e Commit message 2024-07-04 05:12:08 +00:00
support.sampyo 4239597f8a Commit message 2024-06-12 05:25:29 +00:00
support.sampyo a47d7c2bd9 Commit message 2024-06-12 05:16:08 +00:00
support.sampyo 1a6344fccf Commit message 2024-05-31 01:41:55 +00:00
support.sampyo a493257c17 Commit message 2024-05-30 07:20:05 +00:00
support.sampyo 696cc6f0e8 Commit message 2024-05-30 06:37:40 +00:00
support.sampyo 02a44e8478 Commit message 2024-05-29 08:13:58 +00:00
support.sampyo 3fdb92ae4d Commit message 2024-05-29 08:11:32 +00:00
support.sampyo ddc05f15ee Commit message 2024-05-29 08:09:07 +00:00
support.sampyo 944013c835 Commit message 2024-05-29 06:42:52 +00:00
support.sampyo 8efbc66164 Commit message 2024-05-29 06:30:40 +00:00
support.sampyo d18653ef71 Commit message 2024-05-29 06:15:49 +00:00
support.sampyo 4328027519 Commit message 2024-05-29 06:03:54 +00:00
support.sampyo e5d745c4e1 Commit message 2024-05-29 05:51:51 +00:00
support.sampyo d1a2dd1027 Commit message 2024-05-29 04:27:22 +00:00
support.sampyo c1f26f9340 Commit message 2024-05-24 06:04:38 +00:00
support.sampyo 370d851500 Commit message 2024-05-24 05:17:25 +00:00
support.sampyo e1d1327849 Commit message 2024-05-23 07:15:58 +00:00
support.sampyo b0b16d396c Commit message 2024-05-23 07:09:27 +00:00
support.sampyo ae42726b4d Commit message 2024-05-23 07:03:51 +00:00
support.sampyo e99f5122cb Commit message 2024-05-23 06:47:31 +00:00
support.sampyo f5f155c1bc Commit message 2024-05-23 06:12:49 +00:00
support.sampyo 3a30bba1ef Commit message 2024-05-23 05:50:59 +00:00
support.sampyo 978b40a0c4 Commit message 2024-05-23 05:45:54 +00:00
support.sampyo 0c77a24a40 Commit message 2024-05-23 05:42:56 +00:00
support.sampyo 0a351ca635 Commit message 2024-05-23 05:33:27 +00:00
support.sampyo 0a996b5b66 Commit message 2024-05-23 01:32:45 +00:00
support.sampyo 237ec66789 Commit message 2024-05-03 05:24:53 +00:00
support.sampyo 69dbc3b2e7 Commit message 2024-05-03 05:11:36 +00:00
support.sampyo c35cd3e5e5 Commit message 2024-03-26 11:11:38 +00:00
support.sampyo 1b38b348b5 Commit message 2024-03-26 11:09:36 +00:00
support.sampyo 0cbfb8de48 Commit message 2024-03-26 10:56:40 +00:00
support.sampyo ace959aee5 Commit message 2024-03-26 09:32:33 +00:00
support.sampyo b204963582 Commit message 2024-03-26 09:27:51 +00:00
support.sampyo febe5dcf33 Commit message 2024-03-26 08:41:13 +00:00
support.sampyo 3bb08fbd7b Commit message 2024-03-26 08:16:31 +00:00
16 changed files with 1098 additions and 439 deletions

BIN
.config.json.un~ Normal file

Binary file not shown.

BIN
.control.json.un~ Normal file

Binary file not shown.

Binary file not shown.

BIN
.main.py.swp Normal file

Binary file not shown.

Binary file not shown.

BIN
.test.py.un~ Normal file

Binary file not shown.

View File

@ -1,11 +1,12 @@
{
"appId": "81a695f0-a990-43c8-998f-2ba1bf9c6005",
"modbus-server": {
"address": "25.7.55.237",
"port": 5020
},
"tcp-server": {
"address": "25.7.57.1",
"port": 7007
}
}
{
"appId": "81a695f0-a990-43c8-998f-2ba1bf9c6005",
"modbus-server": {
"address": "172.17.16.202",
"port": 5020
},
"tcp-server": {
"address": "172.17.16.201",
"port": 24
},
"volume-water": 542
}

12
config.json~ Normal file
View File

@ -0,0 +1,12 @@
{
"appId": "81a695f0-a990-43c8-998f-2ba1bf9c6005",
"modbus-server": {
"address": "25.7.55.237",
"port": 5020
},
"tcp-server": {
"address": "25.7.57.1",
"port": 7007
},
"volume-water": 542
}

View File

@ -1,26 +1,49 @@
{
"device": {
"setzero": {
"action": "Off"
},
"measure": {
"action": "On"
},
"mixed": {
"action": "Off",
"duration": 15
},
"pure": {
"action": "Off",
"duration": 15
},
"vent": {
"action": "Off",
"duration": 30
},
"motor": {
"action": "Off"
}
},
"type": "manual"
{
"device": {
"enter": {
"action": "Off"
},
"main": {
"action": "Off",
"duration": 4
},
"measure": {
"action": "On"
},
"mixed": {
"action": "Off"
},
"motor": {
"action": "Off"
},
"pure": {
"action": "Off",
"duration": 4
},
"setzero": {
"action": "Off"
},
"vent": {
"action": "Off"
}
},
"maintenance": {
"clean": {
"duration": 20,
"time": 25
}
},
"type": "manual",
"working-time": {
"step0": 5,
"step1": 10,
"step2": 0.5,
"step3": 4,
"step4": 20,
"step5": 20,
"step6": 0.5,
"step7": 15,
"step8": 10,
"step9": 140
}
}

27
control.json~ Normal file
View File

@ -0,0 +1,27 @@
{
"device": {
"setzero": {
"action": "Off"
},
"measure": {
"action": "On"
},
"mixed": {
"action": "Off",
"duration": 15
},
"pure": {
"action": "Off",
"duration": 15
},
"vent": {
"action": "Off",
"duration": 30
},
"motor": {
"action":
"On"
}
},
"type": "manual"
}

View File

@ -1,11 +1,11 @@
version: bwc/v2 # bwc 버전 정보입니다.
spec:
appName: sampyo-dio-app # 앱의 이름입니다.
runFile: main.py # 앱의 실행 파일입니다.
env:
bin: python3 # 앱을 실행할 바이너라 파일 종류입니다.(장비에 따라 다르므로 확인 후 정의해야 합니다.)
virtualEnv: base # 사용할 가상환경 이름입니다.
package: requirements.txt # 설치할 Python 패키지 정보 파일입니다.(기본 값은 requirement.txt 입니다.)
stackbase:
tagName: v0.0.5 # Stackbase(gitea)에 릴리즈 태그명 입니다.
repoName: sampyo-dio # Stackbase(gitea)에 저장될 저장소 이릅니다.
version: bwc/v2 # bwc 버전 정보입니다.
spec:
appName: sampyo-dio-app # 앱의 이름입니다.
runFile: main.py # 앱의 실행 파일입니다.
env:
bin: python3 # 앱을 실행할 바이너라 파일 종류입니다.(장비에 따라 다르므로 확인 후 정의해야 합니다.)
virtualEnv: base # 사용할 가상환경 이름입니다.
package: requirements.txt # 설치할 Python 패키지 정보 파일입니다.(기본 값은 requirement.txt 입니다.)
stackbase:
tagName: v0.0.51 # Stackbase(gitea)에 릴리즈 태그명 입니다.
repoName: sampyo-dio # Stackbase(gitea)에 저장될 저장소 이릅니다.

View File

@ -5,7 +5,7 @@ spec:
env:
bin: python3 # 앱을 실행할 바이너라 파일 종류입니다.(장비에 따라 다르므로 확인 후 정의해야 합니다.)
virtualEnv: base # 사용할 가상환경 이름입니다.
package: requirement.txt # 설치할 Python 패키지 정보 파일입니다.(기본 값은 requirement.txt 입니다.)
package: requirements.txt # 설치할 Python 패키지 정보 파일입니다.(기본 값은 requirement.txt 입니다.)
stackbase:
tagName: v0.0.1 # Stackbase(gitea)에 릴리즈 태그명 입니다.
tagName: v0.0.13 # Stackbase(gitea)에 릴리즈 태그명 입니다.
repoName: sampyo-dio # Stackbase(gitea)에 저장될 저장소 이릅니다.

1001
main.py

File diff suppressed because it is too large Load Diff

375
test.py Normal file
View File

@ -0,0 +1,375 @@
import ssl
import json
import time
import argparse
import sys, signal
import gpiod
from pymodbus.client import ModbusTcpClient
import AWSIoTPythonSDK.MQTTLib as AWSIoTPyMQTT
import asyncio, pytz
from datetime import datetime
import threading, socket
def Motor(chip, status, action):
if action == 'On':
status[0] = 1
else: # action == 'Off'
status[0] = 0
chip.set_values(status)
def Valve_Vent(chip, status, action):
if action == 'On':
status[1] = 1
else: # action == 'Off'
status[1] = 0
chip.set_values(status)
def Valve_MixedWater(chip, status, action):
if action == 'On':
status[2] = 1
else: # action == 'Off'
status[2] = 0
chip.set_values(status)
def Valve_PureWater(chip, status, action):
if action == 'On':
status[3] = 1
else: # action == 'Off'
status[3] = 0
chip.set_values(status)
def Measure_Weight(client):
# print('In')
try:
result = client.read_holding_registers(1, 1)
if result.isError():
print(f'Error: {result}')
else:
val = result.registers[0]
val -= 1000
val /= 1000
# print(f'value: {val}')
except Exception as e:
pass
return val
def Calculate_Concentration(weight):
global data
data['data']['weight'] = weight
result = (float(weight) * 1.883239171 * 128.5) - 126.11 # 1000 / 531 = 1.883239171
data['data']['concentration'] = result
# print(f'{weight}, {result}')
def Set_Zero(client):
client.write_coil(1, 1)
def Command_Read():
with open('./control.json', 'r') as f:
cmd = json.load(f)
if cmd['type'] == 'auto':
Valve_Vent(chip=output_lines, status=status, action='Off')
Motor(chip=output_lines, status=status, action='Off')
# set zero
# Set_Zero(client=client)
time.sleep(5)
start = Measure_Weight(client=client)
time.sleep(5)
# input mixed water
Valve_MixedWater(chip=output_lines, status=status, action='On')
time.sleep(19)
Valve_MixedWater(chip=output_lines, status=status, action='Off')
# time.sleep(20)
time.sleep(10)
# measure weight
end = Measure_Weight(client=client)
time.sleep(1)
Calculate_Concentration(weight=(float(end)-float(start)))
# vent mixed water
Valve_Vent(chip=output_lines, status=status, action='On')
time.sleep(0.5)
Motor(chip=output_lines, status=status, action='On')
time.sleep(40)
Motor(chip=output_lines, status=status, action='Off')
time.sleep(0.5)
Valve_Vent(chip=output_lines, status=status, action='Off')
# input pure water
Valve_PureWater(chip=output_lines, status=status, action='On')
time.sleep(19)
Valve_PureWater(chip=output_lines, status=status, action='Off')
time.sleep(0.5)
# vent pure water
Valve_Vent(chip=output_lines, status=status, action='On')
time.sleep(0.5)
Motor(chip=output_lines, status=status, action='On')
time.sleep(40)
Motor(chip=output_lines, status=status, action='Off')
time.sleep(0.5)
Valve_Vent(chip=output_lines, status=status, action='Off')
time.sleep(5)
else: # cmd['type'] == 'manual'
Motor(chip=output_lines, status=status, action=cmd['device']['motor']['action'])
Valve_Vent(chip=output_lines, status=status, action=cmd['device']['vent']['action'])
Valve_MixedWater(chip=output_lines, status=status, action=cmd['device']['mixed']['action'])
Valve_PureWater(chip=output_lines, status=status, action=cmd['device']['pure']['action'])
if cmd['device']['measure']['action'] == 'On':
result = Measure_Weight(client=client)
Calculate_Concentration(result)
if cmd['device']['setzero']['action'] == 'On':
Set_Zero(client=client)
def connectMQTT(clientID, projectCode):
CLIENT_ID = clientID
ENDPOINT = "avk03ee629rck-ats.iot.ap-northeast-2.amazonaws.com"
PATH_TO_CERTIFICATE = f"/etc/sdt/cert/{projectCode}-certificate.pem"
PATH_TO_PRIVATE_KEY = f"/etc/sdt/cert/{projectCode}-private.pem"
PATH_TO_AMAZON_ROOT_CA_1 = f"/etc/sdt/cert/AmazonRootCA1.pem"
myAWSIoTMQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient(CLIENT_ID)
myAWSIoTMQTTClient.configureEndpoint(ENDPOINT, 8883)
myAWSIoTMQTTClient.configureCredentials(PATH_TO_AMAZON_ROOT_CA_1, PATH_TO_PRIVATE_KEY, PATH_TO_CERTIFICATE)
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz
return myAWSIoTMQTTClient
def publishMsg(mqttClient, topic, msg):
# Make the copip3 nnect() call
# mqttClient.connect()
while True:
try:
mqttClient.connect()
break
except Exception as e:
print(f'Connection Fail: {e}')
continue
msg['timestamp'] = int(time.time() * 1000)
# Publish message to server desired number of times.
# print('Begin Publish')
mqttClient.publish(topic=topic, payload=json.dumps(msg), QoS=1)
while True:
try:
mqttClient.disconnect()
break
except Exception as e:
print(f'Disconnection Fail: {e}')
continue
def runAction(projectCode, assetCode):
# Write the app's actions in the "runAction" function.
# Connect MQTT Broker
# You have to rename client id. There are special rules.
# Client Name: "device-app-*"
# For Example
# 1. device-app-test -> Good
# 2. device-app-light-app -> Good
# 3. device-test-app -> Bad
mqttClient1 = connectMQTT("device-app-test1", projectCode)
mqttClient2 = connectMQTT("device-app-test2", projectCode)
mqttClient3 = connectMQTT("device-app-test3", projectCode)
mqttClient4 = connectMQTT("device-app-test4", projectCode)
mqttClient5 = connectMQTT("device-app-test5", projectCode)
mqttlist = [mqttClient1, mqttClient2, mqttClient3, mqttClient4, mqttClient5]
# If you have config's value, please make config.json file.
# - Project Code's variable: projectCode(string)
# - Asset Code's variable: assetCode(string)
# - You may need it to create a topic.
with open('./config.json', encoding='UTF-8') as f:
jsonData = json.load(f)
topic = f"sdtcloud/{projectCode}/{assetCode}/app/{jsonData['appId']}/data"
cnt = 0
while True:
start = time.time()
Command_Read()
# publishMsg(mqttlist[cnt], topic, data)
end = time.time()
cnt += 1
if cnt == 5:
cnt = 0
diff = end - start
if diff < 3:
time.sleep(3 - diff)
def handle_client(conn, ip, port):
global data
while True:
try:
recv = conn.recv(100)
if not recv:
# print(f"Connection with {addr} was reset. Waiting for new connection.")
break
message = recv.decode().strip()
if message[:3] != 'STX' or message[-3:] != 'ETX':
err_msg = 'STXERRORETX'
conn.sendall(err_msg.encode("utf8"))
else:
if message[3] == 'R': # Transfer data from SDT to Sampyo
now = datetime.now(pytz.timezone('Asia/Seoul'))
time_str = now.strftime('%Y%m%d%H%M%S')
h_weight = float(data['data']['weight'])
h_concentration = float(data['data']['concentration'])
data_weight = '{:.3f}'.format(h_weight)
data_concent = '{:.3f}'.format(h_concentration)
send_msg = 'STX' + time_str + '|' + data_weight + '|' + data_concent + 'ETX'
try:
with open('./control.json', 'r') as f:
cmd = json.load(f)
cmd['device']['measure']['action'] = 'On'
with open('./control.json', 'w') as f:
json.dump(cmd, f, indent=4)
conn.sendall(send_msg.encode("utf8"))
except Exception as e:
err_msg = 'STXERRORETX'
conn.sendall(err_msg.encode("utf8"))
elif message[3] == 'S': # Start measurement
try:
with open('./control.json', 'r') as f:
cmd = json.load(f)
cmd['type'] = 'auto'
with open('./control.json', 'w') as f:
json.dump(cmd, f, indent=4)
send_msg = 'STXOKETX'
conn.sendall(send_msg.encode("utf8"))
except Exception as e:
err_msg = 'STXERRORETX'
conn.sendall(err_msg.encode("utf8"))
elif message[3] == 'T': # Stop measurement
try:
with open('./control.json', 'r') as f:
cmd = json.load(f)
cmd['type'] = 'manual'
cmd['device']['measure']['action'] = 'Off'
with open('./control.json', 'w') as f:
json.dump(cmd, f, indent=4)
send_msg = 'STXOKETX'
conn.sendall(send_msg.encode("utf8"))
except Exception as e:
err_msg = 'STXERRORETX'
conn.sendall(err_msg.encode("utf8"))
else:
err_msg = 'STXERRORETX'
conn.sendall(err_msg.encode("utf8"))
except ConnectionResetError:
# print("Connection with " + ip + ":" + port + " was reset. Waiting for new connection.")
break
# print("Closing the connection")
def start_server():
host = "25.7.57.1"
port = 5000
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
soc.bind((host, port))
except:
sys.exit()
soc.listen(1) # Only one connection at a time.
while True:
conn, addr = soc.accept()
ip, port = str(addr[0]), str(addr[1])
print("Connected with " + ip + ":" + port)
client_handler = threading.Thread(target=handle_client, args=(conn, ip, port))
client_handler.start()
soc.close()
def exit_handler(signum, frame):
Motor(chip=output_lines, status=status, action='Off')
Valve_Vent(chip=output_lines, status=status, action='Off')
Valve_MixedWater(chip=output_lines, status=status, action='Off')
Valve_PureWater(chip=output_lines, status=status, action='Off')
client.close()
sys.exit(0)
if __name__ == "__main__":
output_chip = gpiod.chip('gpiochip11')
config = gpiod.line_request()
config.consumer = 'output'
config.request_type = gpiod.line_request.DIRECTION_OUTPUT
output_lines = output_chip.get_lines([0, 1, 2, 3, 4, 5, 6, 7])
output_lines.request(config, default_vals=[0, 0, 0, 0, 0, 0, 0, 0])
status = [0, 0, 0, 0, 0, 0, 0, 0]
signal.signal(signal.SIGINT, exit_handler)
client = ModbusTcpClient('25.7.55.237', 5020)
parser = argparse.ArgumentParser()
parser.add_argument('-app',help='')
args = parser.parse_args()
# ROOT_PATH = f'/usr/local/sdt/app/{args.app}'
data = {
"timestamp": 0,
"data":{
"weight": 0,
"concentration": 0
}
}
## Get ProjectCode and AssetCode
with open(f'/etc/sdt/device.config/config.json', encoding='UTF-8') as f:
codeData = json.load(f)
## Execution main funcion
operation_thread = threading.Thread(target=runAction, args=(codeData["projectcode"], codeData["assetcode"]))
operation_thread.start()
## Execution TCP/IP server
start_server()

0
test.py~ Normal file
View File

0
working.log Normal file
View File