|
| 1 | +""" |
| 2 | +Use a handler to automatically persist values to an SQLite3 file database. |
| 3 | +Any values persisted this way will be automatically restored when the |
| 4 | +program is rerun. The details of users (account name and IP address) are |
| 5 | +recorded for puts. |
| 6 | +
|
| 7 | +Try monitoring the PV `demo:pv:optime` then quit, wait, and restart the |
| 8 | +program while continuing to monitor the PV. Compare with the value of |
| 9 | +`demo:pv:uptime` which resets on each program start. Try setting the value of |
| 10 | +demo:pv:optime while continuing to monitor it. It is recommended to |
| 11 | +inspect the persisted file, e.g. `sqlite3 persist_pvs.db "select * from pvs"`. |
| 12 | +
|
| 13 | +There is an important caveat for this simple demo: |
| 14 | +The `PersistHandler` will not work as expected if anything other than the |
| 15 | +value of a field is changed, e.g. if a Control field was added to an NTScalar |
| 16 | +if would not be persisted correctly. This could be resolved by correctly |
| 17 | +merging the pv.current().raw and value.raw appropriately in the post(). |
| 18 | +""" |
| 19 | + |
| 20 | +import json |
| 21 | +import sqlite3 |
| 22 | +import time |
| 23 | + |
| 24 | +from p4p import Value |
| 25 | +from p4p.nt.scalar import NTScalar |
| 26 | +from p4p.server import Server, ServerOperation |
| 27 | +from p4p.server.raw import Handler |
| 28 | +from p4p.server.thread import SharedPV |
| 29 | + |
| 30 | + |
| 31 | +class PersistHandler(Handler): |
| 32 | + """ |
| 33 | + A handler that will allow simple persistence of values and timestamps |
| 34 | + across retarts. It requires a post handler in order to persist values |
| 35 | + set within the program. |
| 36 | + """ |
| 37 | + |
| 38 | + def __init__(self, pv_name: str, conn: sqlite3.Connection, open_restore=True): |
| 39 | + self._conn = conn |
| 40 | + self._pv_name = pv_name |
| 41 | + self._open_restore = open_restore |
| 42 | + |
| 43 | + def open(self, value, **kws): |
| 44 | + # If there is a value already in the database we always use that |
| 45 | + # instead of the supplied initial value, unless the |
| 46 | + # handler_open_restore flag indicates otherwise. |
| 47 | + if not self._open_restore: |
| 48 | + return |
| 49 | + |
| 50 | + # We could, in theory, re-apply authentication here if we queried for |
| 51 | + # that information and then did something with it! |
| 52 | + res = self._conn.execute("SELECT data FROM pvs WHERE id=?", [self._pv_name]) |
| 53 | + query_val = res.fetchone() |
| 54 | + |
| 55 | + if query_val is not None: |
| 56 | + json_val = json.loads(query_val[0]) |
| 57 | + print(f"Will restore to {self._pv_name} value: {json_val['value']}") |
| 58 | + |
| 59 | + # Override initial value |
| 60 | + value["value"] = json_val["value"] |
| 61 | + |
| 62 | + value["timeStamp.secondsPastEpoch"] = json_val["timeStamp"][ |
| 63 | + "secondsPastEpoch" |
| 64 | + ] |
| 65 | + value["timeStamp.nanoseconds"] = json_val["timeStamp"]["nanoseconds"] |
| 66 | + else: |
| 67 | + # We are using an initial value so persist it |
| 68 | + self._upsert(value) |
| 69 | + |
| 70 | + def post( |
| 71 | + self, |
| 72 | + pv: SharedPV, |
| 73 | + value: Value, |
| 74 | + ): |
| 75 | + self._update_timestamp(value) |
| 76 | + |
| 77 | + self._upsert( |
| 78 | + value, |
| 79 | + ) |
| 80 | + |
| 81 | + def put(self, pv: SharedPV, op: ServerOperation): |
| 82 | + # The post does all the real work, we just add info only available |
| 83 | + # from the ServerOperation |
| 84 | + self._update_timestamp(op.value()) |
| 85 | + |
| 86 | + self._upsert( |
| 87 | + op.value(), op.account(), op.peer() |
| 88 | + ) |
| 89 | + |
| 90 | + op.done() |
| 91 | + |
| 92 | + def _update_timestamp(self, value) -> None: |
| 93 | + if not value.changed("timeStamp") or ( |
| 94 | + value["timeStamp.nanoseconds"] == value["timeStamp.nanoseconds"] == 0 |
| 95 | + ): |
| 96 | + now = time.time() |
| 97 | + value["timeStamp.secondsPastEpoch"] = now // 1 |
| 98 | + value["timeStamp.nanoseconds"] = int((now % 1) * 1e9) |
| 99 | + |
| 100 | + def _upsert(self, value, account=None, peer=None) -> None: |
| 101 | + # Persist the data; turn into JSON and write it to the DB |
| 102 | + val_json = json.dumps(value.todict()) |
| 103 | + |
| 104 | + # Use UPSERT: https://sqlite.org/lang_upsert.html |
| 105 | + conn.execute( |
| 106 | + """ |
| 107 | + INSERT INTO pvs (id, data, account, peer) |
| 108 | + VALUES (:name, :json_data, :account, :peer) |
| 109 | + ON CONFLICT(id) |
| 110 | + DO UPDATE SET data = :json_data, account = :account, peer = :peer; |
| 111 | + """, |
| 112 | + { |
| 113 | + "name": self._pv_name, |
| 114 | + "json_data": val_json, |
| 115 | + "account": account, |
| 116 | + "peer": peer, |
| 117 | + }, |
| 118 | + ) |
| 119 | + conn.commit() |
| 120 | + |
| 121 | + |
| 122 | +# Create an SQLite dayabase to function as our persistence store |
| 123 | +conn = sqlite3.connect("persist_pvs.db", check_same_thread=False) |
| 124 | +#conn.execute("DROP TABLE IF EXISTS pvs") |
| 125 | +conn.execute( |
| 126 | + "CREATE TABLE IF NOT EXISTS pvs (id VARCHAR(255), data JSON, account VARCHAR(30), peer VARCHAR(55), PRIMARY KEY (id));" |
| 127 | +) # IPv6 addresses can be long and will contain port number as well! |
| 128 | + |
| 129 | +duplicate_pv = SharedPV( |
| 130 | + nt=NTScalar("i"), handler=PersistHandler("demo:pv:int", conn), initial=12 |
| 131 | +) |
| 132 | +pvs = { |
| 133 | + "demo:pv:optime": SharedPV( |
| 134 | + nt=NTScalar("i"), |
| 135 | + handler=PersistHandler("demo:pv:optime", conn), |
| 136 | + initial=0, |
| 137 | + ), # Operational time; total time running |
| 138 | + "demo:pv:uptime": SharedPV( |
| 139 | + nt=NTScalar("i"), |
| 140 | + handler=PersistHandler("demo:pv:uptime", conn, open_restore=False), |
| 141 | + timestamp=time.time(), |
| 142 | + initial=0, |
| 143 | + ), # Uptime since most recent (re)start |
| 144 | + "demo:pv:int": duplicate_pv, |
| 145 | + "demo:pv:float": SharedPV( |
| 146 | + nt=NTScalar("d"), |
| 147 | + handler=PersistHandler("demo:pv:float", conn), |
| 148 | + initial=9.99, |
| 149 | + ), |
| 150 | + "demo:pv:string": SharedPV( |
| 151 | + nt=NTScalar("s"), |
| 152 | + handler=PersistHandler("demo:pv:string", conn), |
| 153 | + initial="Hello!", |
| 154 | + ), |
| 155 | + "demo:pv:alias_int": duplicate_pv, # It works except for reporting its restore |
| 156 | +} |
| 157 | + |
| 158 | + |
| 159 | +# Make the uptime PV readonly; maybe we want to be able to update optime |
| 160 | +# after major system upgrades? |
| 161 | +uptime_pv = pvs["demo:pv:uptime"] |
| 162 | + |
| 163 | + |
| 164 | +@uptime_pv.put |
| 165 | +def read_only(pv: SharedPV, op: ServerOperation): |
| 166 | + op.done(error="Read-only") |
| 167 | + return |
| 168 | + |
| 169 | + |
| 170 | +print(f"Starting server with the following PVs: {pvs}") |
| 171 | + |
| 172 | +server = None |
| 173 | +try: |
| 174 | + server = Server(providers=[pvs]) |
| 175 | + while True: |
| 176 | + # Every second increment the values of uptime and optime |
| 177 | + time.sleep(1) |
| 178 | + increment_value = pvs["demo:pv:uptime"].current().raw["value"] + 1 |
| 179 | + pvs["demo:pv:uptime"].post(increment_value) |
| 180 | + increment_value = pvs["demo:pv:optime"].current().raw["value"] + 1 |
| 181 | + pvs["demo:pv:optime"].post(increment_value) |
| 182 | +except KeyboardInterrupt: |
| 183 | + pass |
| 184 | +finally: |
| 185 | + if server: |
| 186 | + server.stop() |
| 187 | + conn.close() |
0 commit comments