-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhicube-pressure.py
More file actions
193 lines (152 loc) · 5.9 KB
/
hicube-pressure.py
File metadata and controls
193 lines (152 loc) · 5.9 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import asyncio
import logging
import socket
from datetime import datetime, timezone
import numpy as np
from asyncua import Client
HOST = "192.168.1.100"
PORT = 4840
URL = f"opc.tcp://{HOST}:{PORT}"
PRESSURE_NODE_ID = "ns=1;s=G3_740_Pressure"
TABLE_NAME = "hicube_pressure"
POLL_INTERVAL = 10.0
CONNECT_TIMEOUT = 30.0
WATCHDOG_INTERVAL = 60.0
RETRY_DELAY = 10.0
# Choose:
# "local" -> timestamp when Python receives the value
# "source" -> OPC UA SourceTimestamp (falls back to ServerTimestamp/local)
TIMESTAMP_MODE = "local"
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[
logging.FileHandler("hicube-neo-pressure.log"),
logging.StreamHandler(),
],
)
logging.getLogger("asyncua.client.client").setLevel(logging.CRITICAL)
logging.getLogger("asyncua.client.ua_client").setLevel(logging.WARNING)
def init_db():
try:
from ida_db import pglogger
import psql_credentials as creds_cloud
db_cloud = pglogger(creds_cloud)
logging.info(f"{format_timestamp(None)} database connected")
return db_cloud
except Exception as exc:
logging.error(f"{format_timestamp(None)} database init failed: {exc!r}")
return None
def reconnect_db():
logging.warning(f"{format_timestamp(None)} reconnecting database")
return init_db()
def tcp_probe(host, port, timeout=3.0):
with socket.create_connection((host, port), timeout=timeout):
return True
async def wait_for_port(host, port, attempts=5, timeout=3.0, delay=1.0):
last_err = None
for _ in range(attempts):
try:
await asyncio.to_thread(tcp_probe, host, port, timeout)
return
except Exception as exc:
last_err = exc
await asyncio.sleep(delay)
raise last_err
def _to_local_aware(dt):
if dt is None:
return datetime.now().astimezone()
if dt.tzinfo is None:
return dt.replace(tzinfo=timezone.utc).astimezone()
return dt.astimezone()
def format_timestamp(dt):
return _to_local_aware(dt).isoformat()
def format_db_timestamp(dt):
local_dt = _to_local_aware(dt).replace(tzinfo=None)
return local_dt.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
def choose_timestamp(data_value):
if TIMESTAMP_MODE == "local":
return datetime.now().astimezone()
if TIMESTAMP_MODE == "source":
return data_value.SourceTimestamp or data_value.ServerTimestamp or datetime.now().astimezone()
raise ValueError("TIMESTAMP_MODE must be 'local' or 'source'")
async def monitor_pressure(table_name):
db_cloud = init_db()
try:
while True:
client = None
try:
await wait_for_port(HOST, PORT, attempts=5, timeout=3.0, delay=1.0)
client = Client(
url=URL,
timeout=CONNECT_TIMEOUT,
watchdog_intervall=WATCHDOG_INTERVAL,
)
client.session_timeout = 600_000
await client.connect()
node = client.get_node(PRESSURE_NODE_ID)
logging.info(f"{format_timestamp(None)} connected")
while True:
data_value = await node.read_data_value()
raw_pressure = float(data_value.Value.Value)
pressure = float(f"{raw_pressure:.3g}")
ts = choose_timestamp(data_value)
logging.info(f"{format_timestamp(ts)} pressure={pressure:.3g}")
if db_cloud is None:
db_cloud = reconnect_db()
if db_cloud is not None:
try:
success = db_cloud.log(
table=table_name,
channels=np.array([pressure], dtype=float),
time=format_db_timestamp(ts),
)
if not success:
logging.warning(
f"{format_timestamp(None)} failed to log pressure data to table '{table_name}'"
)
db_cloud = reconnect_db()
except Exception as exc:
logging.error(f"{format_timestamp(None)} database logging failed: {exc!r}")
db_cloud = reconnect_db()
# No catch-up behavior: always wait after each successful read.
await asyncio.sleep(POLL_INTERVAL)
except asyncio.CancelledError:
raise
except Exception as exc:
logging.warning(f"{format_timestamp(None)} reconnecting after error: {exc!r}")
# No catch-up here either: reconnect and continue on the next loop.
await asyncio.sleep(RETRY_DELAY)
finally:
if client is not None:
try:
await client.disconnect()
except Exception:
pass
finally:
if db_cloud is not None:
try:
db_cloud.close()
except Exception:
pass
def parse_args():
parser = argparse.ArgumentParser(description="Pfeiffer HiCube Neo OPC UA pressure logger")
parser.add_argument(
"--table",
default=TABLE_NAME,
help=f"Database table name for pressure logs (default: {TABLE_NAME})",
)
return parser.parse_args()
def main():
args = parse_args()
if TIMESTAMP_MODE not in {"local", "source"}:
raise ValueError("TIMESTAMP_MODE must be 'local' or 'source'")
try:
asyncio.run(monitor_pressure(args.table))
except KeyboardInterrupt:
logging.info(f"{format_timestamp(None)} keyboard interrupt received; exiting")
if __name__ == "__main__":
main()