#!/usr/bin/env python3
"""
#
# PROFIBUS - Telegram sniffer
#
# Copyright (c) 2016-2020 Michael Buesch <m@bues.ch>
#
# Licensed under the terms of the GNU General Public License version 2,
# or (at your option) any later version.
#
"""

from pyprofibus.phy_serial import *
from pyprofibus.fdl import *
from pyprofibus import *

import sys
import getopt


def usage():
	print("PROFIBUS bus sniffer")
	print("")
	print("Usage: profisniff [OPTIONS] DEVICE")
	print("")
	print("DEVICE is the PHY device /dev/ttySx")
	print("")
	print("Options:")
	print(" -h|--help           Show this help.")

def main():
	try:
		(opts, args) = getopt.getopt(sys.argv[1:],
			"h",
			[ "help", ])
	except getopt.GetoptError as e:
		sys.stderr.write(str(e) + "\n")
		usage()
		return 1
	for (o, v) in opts:
		if o in ("-h", "--help"):
			usage()
			return 0
	if len(args) != 1:
		usage()
		return 1
	dev = args[0]

	try:
		phy = CpPhySerial(dev)
		xceiv = FdlTransceiver(phy)
		xceiv.setRXFilter(None)
	except ProfibusError as e:
		sys.stderr.write("ERROR: %s\n" % str(e))
		return 1
	try:
		while True:
			try:
				ok, telegram = xceiv.poll(-1.0)
				if not ok or not telegram:
					continue
				print(telegram)
			except ProfibusError as e:
				sys.stderr.write("ERROR: %s\n" % str(e))
	except KeyboardInterrupt:
		return 0
	return 1

if __name__ == "__main__":
	sys.exit(main())
