initial commit, first structure

This commit is contained in:
Georg Schlisio
2021-02-05 18:55:05 +01:00
commit 244ff34596
5 changed files with 265 additions and 0 deletions

182
MKS_ASCII_Protocol.py Normal file
View File

@@ -0,0 +1,182 @@
"""
Implementation of the MKS ASCII Protocol
as specified in "ASCII Protocol V1.8.pdf"
"""
__author__ = "Georg Schlisio <georg.schlisio@ipp.mpg.de"
__version__ = 0.1
__protocol_version__ = 1.8
#### imports
import time
import sys
import os
import logging
import socket
__softwarename__ = "MKS ASCII server on " + socket.gethostname()
from message import ParseMessage, ComposeMessage
logging.basicConfig(level=logging.INFO)
####
composer = ComposeMessage()
class MKS_ASCII_Protocol():
# networking
_remote_port = 10014 # port on remote device
_local_port = 10000 # local port
_s = None # socket object
# connection state
_connected = False # connection state
_target_state = "disconnected" # target connection state
device_sn = None # device SN currently connected to
# protocol versioning and formatting
_remote_min_protocol_version = None # remote requirement of min protocol, retrieved from remote device
_min_protocol_version = 1.6 # assumed minimum protocol version
_protocol_version = __protocol_version__
format_with_tab = False # whether to request FormatWithTab (reduces networkload slighlty)
# program flow control
loop_min_time = 0.01 # minimum duration of a listener loop in seconds
message_queue = []
# Mass spectrometer properties
filament = None # number of filament in use
def __init__(self, ip, port=10014, local_port=10000, target_state="connected"):
"""
Talk to an MKS mass spectrometer over the ethernet interface.
:param ip:
:param port:
:param local_port:
"""
self._remote_ip = ip
self._remote_port = port
self._local_port = local_port
self._target_state = target_state
def turn_on(self):
self._target_state = "connected"
def turn_off(self):
self._target_state = "disconnected"
def run(self):
"""
Main loop.
:return:
"""
while True:
logging.info(f"starting new loop")
start_time = time.time()
if self._target_state == "connected" and not self._connected:
self._connect()
if self._connected:
self._check_for_messages()
if self._target_state == "disconnected":
self._disconnect()
break
if self._target_state == "exit":
self._disconnect()
exit(0)
end_time = time.time()
if end_time - start_time < self.loop_min_time:
sleeptime = self.loop_min_time - (end_time - start_time)
logging.info(f"sleep for {sleeptime}s")
time.sleep(sleeptime)
def _send(self, msg, args=None):
"""
Wrapper for sending messages
:param msg:
:return:
"""
self._s.send(composer(msg, args=args))
def _connect(self):
"""
Initiate connection
:return:
"""
assert not self._connected, "Cannot connect "
self._s = socket.socket(family=socket.AF_INET)
self._host = socket.gethostname()
self._s.bind((self._host, self._local_port))
self._s.connect((self._remote_ip, self._remote_port))
self.connected = True
self._protocol_version_check()
# control message formatting
if self.format_with_tab:
self._send("FormatWithTab True")
# negotiate protocol version
self._send("AcceptProtocol 1.6") # TODO check if actual protocol needs to be signaled
def _protocol_version_check(self, tries = 10):
"""
Wait for first message and evaluate protocol compatibility
:return:
"""
while True:
self._check_for_messages()
if len(self.message_queue) > 0:
break
time.sleep(1)
tries -= 1
if tries == 0:
logging.error(f"Connection not successfully established: received no greeting. Exiting.")
exit(201)
message = self.message_queue.pop(0)
assert message.type == "MKSRGA", f"Unexpected message type: {message.type}"
assert message.parms[message.type] in ("Single", "Multi"), f"Unexpected connection type: {message.parms[message.type]}"
assert message.parms[message.type] == "Single", f"Connection to QMS Servers of type 'Multi' is not supported." # To support this, implement the commands "Sensors" and "Select"
assert "Protocol_Revision" in message.parms
assert "Min_Compatibility" in message.parms
self._remote_protocol_version = float(message.parms["Protocol_Revision"])
self._remote_min_protocol_version = float(message.parms["Min_Compatibility"])
if self._remote_min_protocol_version > self._protocol_version:
logging.error(f"Version mismatches: remote requires V{self._remote_min_protocol_version} but we have only V{self._protocol_version}, exiting")
exit(202)
def _disconnect(self):
"""
Terminate connection
:return:
"""
# send message "Release"
self._s.send(composer(mtype="Release"))
# TODO: replace sleep with actual check for "Release Ok"
time.sleep(2)
self._s.close()
self._connected = False
def _check_for_messages(self):
"""
Read socket buffer, parse messages and enqueue them into the message queue
:return:
"""
rawinput = self._s.recv(4096).decode("ASCII").split("\r\r")
if len(rawinput) > 1:
logging.info(f"found {len(rawinput) - 1} messages")
for i in range(len(rawinput) - 1):
self.message_queue.append(ParseMessage(rawinput[i]))
if __name__ == "__main__":
p = MKS_ASCII_Protocol(ip="127.0.0.1")
p.run()