Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Copyright (c) 2016, Markus Barenhoff and Copyright (c) 2017, Jáchym Hurtík
- #
- # All rights reserved.
- #
- # Redistribution and use in source and binary forms, with or without
- # modification, are permitted provided that the following conditions are met:
- #
- # * Redistributions of source code must retain the above copyright
- # notice, this list of conditions and the following disclaimer.
- #
- # * Redistributions in binary form must reproduce the above
- # copyright notice, this list of conditions and the following
- # disclaimer in the documentation and/or other materials provided
- # with the distribution.
- #
- # * Neither the name of Markus Barenhoff nor the names of other
- # contributors may be used to endorse or promote products derived
- # from this software without specific prior written permission.
- #
- # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- import os
- import time
- import ctypes
- import signal
- import sys
- import configparser
- import math
- import serial
- class Konfigurace:
- def __init__(self):
- self.config = configparser.ConfigParser()
- self.config.read(os.path.abspath("konfigurace.ini"))
- print("\n"+str(self.config))
- for key in self.config:
- print(key)
- print("\n"+str(self.config["HLAVNI"]))
- for key in self.config["HLAVNI"]:
- print(key)
- print("\n"+str(self.config["POSILEJ"]))
- for key in self.config["POSILEJ"]:
- print(key)
- class Raildriver:
- def __init__(self):
- self.init = False
- print("Hledám konfigurační soubor v: "+str(os.path.abspath("konfigurace.ini")))
- try:
- self.konf = Konfigurace()
- except:
- input("\nKonfigurační soubor nebyl nalezen!!!")
- else:
- self.init = True
- print("\nKonfigurační soubor nalezen, čtu")
- self.start(
- dllPathVar = self.konf.config["HLAVNI"]['CestaDLL'],
- sleepTimeVar = 1/int(self.konf.config["HLAVNI"]['UpdateFrekvence']),
- comPort = self.konf.config["HLAVNI"]['COMport'],
- comBaud = int(self.konf.config["HLAVNI"]['Baudrate']),
- comParita = str.lower(self.konf.config["HLAVNI"]['Parita']),
- debugVar = self.konf.config["HLAVNI"]["Debug"]
- )
- def start(self,dllPathVar,sleepTimeVar,comPort,comBaud,comParita,debugVar):
- print("\n\nSTART APLIKACE...")
- self.sleepTime = sleepTimeVar
- self.dllPath = dllPathVar
- self.poleSignalek = []
- self.pocetSignalek = 0
- self.debug = debugVar
- print("\nNacitam nazvy kontrolek z konfiguracniho souboru.")
- for JmenoSignalky in self.konf.config['POSILEJ']:
- self.pocetSignalek = self.pocetSignalek + 1
- self.poleSignalek.append(JmenoSignalky)
- print("\nNacteno %d signalek z konfiguracniho souboru."%(self.pocetSignalek))
- print("\nPrirazuji ID k nazvum kontrolek.")
- i = 0
- self.idSignalek = []
- while i < self.pocetSignalek:
- self.idSignalek.append(self.konf.config['POSILEJ'][self.poleSignalek[i]])
- i = i + 1
- print("\nPrirazeno %d ID signalek."%i)
- if self.pocetSignalek == i:
- print("\nPocet pojmenovanych signalek je stejny jako prirazenych ID.")
- else:
- print("\nPocet pojmenovanych signalek neni stejny jako prirazenych ID!!!\nKriticka chyba pri cteni souboru! Zkontroluj soubor!")
- i = 0
- print("\nNazvy signalek a ID jsou:")
- while i < self.pocetSignalek:
- print(str(self.poleSignalek[i])+"||"+str(self.idSignalek[i]))
- i = i + 1
- print("\nInicializuji aplikaci!")
- paritaDict = {'suda':'E', 'licha':'O', 'zadna':'N'}
- self.ser = serial.Serial()
- self.ser.port = comPort
- self.ser.baudrate = comBaud
- self.ser.parity = paritaDict[comParita]
- self.ser.rtscts = False
- self.comOK = False
- try:
- self.ser.open()
- except Exception as e:
- if str(e).find("FileNotFoundError") != -1:
- input("\nNepovedlo se otevřít port %s, protože takový port nebyl v počítači nalezen! Nelze pokračovat!"%(comPort))
- elif str(e).find("PermissionError") != -1:
- input("\nNepovedlo se otevřít port %s, přístup zamítnut! Nelze pokračovat!"%(comPort))
- else:
- input("\nNepovedlo se otevřít port %s, z neznámého důvodu! Nelze pokračovat!\nChyba: %s"%(comPort,e))
- else:
- print("\nPort %s úspěšně otevřen."%(self.ser.name))
- self.comOK = True
- signal.signal(signal.SIGINT, self.signal_handler)
- def zaokrouhli(self,cislo):
- if cislo % 1 >= 0.5:
- return(math.floor(cislo)+1)
- else:
- return(math.floor(cislo))
- def runRaildriver(self):
- if self.init:
- self.knihovnaOK = False
- try:
- self.api = RaildriverAPI(self.dllPath)
- except OSError:
- input("\nNebyla nalezena potřebná knihovna!!!")
- else:
- self.knihovnaOK = True
- self.valueSignalek = []
- self.valueSignalekStare = []
- a = 0
- while a < self.pocetSignalek:
- a = a + 1
- self.valueSignalek.append(0)
- self.valueSignalekStare.append(0)
- if self.knihovnaOK:
- self.api.SetRailSimConnected(True)
- self.api.SetRailDriverConnected(True)
- print("\nNačtená knihovna: %s" % self.api.rdDll)
- print(self.api.GetLocoName())
- print(self.api.GetControllerList())
- while (self.comOK and self.knihovnaOK):
- a = 0
- while a < self.pocetSignalek:
- self.valueSignalek[a] = self.api.GetControllerValue(int(self.idSignalek[a]),0)
- #if self.valueSignalek[a] != self.valueSignalekStare[a]:
- vystup = str(self.poleSignalek[a])+str(self.zaokrouhli(int(self.valueSignalek[a])))
- if self.debug:
- print(vystup)
- self.ser.write(vystup.encode())
- a = a + 1
- #self.valueSignalekStare = self.valueSignalek[:]
- time.sleep(self.sleepTime)
- def signal_handler(self, signal, frame):
- sys.exit()
- self.ser.close()
- class RaildriverAPI:
- def __init__(self, libpath):
- self.rdDll = ctypes.CDLL(libpath)
- self.SetRailSimConnected_c = self.rdDll.SetRailSimConnected
- self.SetRailSimConnected_c.restype = None
- self.SetRailSimConnected_c.argtypes = [ctypes.c_bool]
- self.SetRailDriverConnected_c = self.rdDll.SetRailDriverConnected
- self.SetRailDriverConnected_c.restype = None
- self.SetRailDriverConnected_c.argtypes = [ctypes.c_bool]
- self.GetRailSimLocoChanged_c = self.rdDll.GetRailSimLocoChanged
- self.GetRailSimLocoChanged_c.restype = ctypes.c_bool
- self.GetRailSimLocoChanged_c.argtypes = None
- self.GetLocoName_c = self.rdDll.GetLocoName
- self.GetLocoName_c.restype = ctypes.c_char_p
- self.GetLocoName_c.argtypes = None
- self.GetControllerList_c = self.rdDll.GetControllerList
- self.GetControllerList_c.restype = ctypes.c_char_p
- self.GetControllerList_c.argtypes = None
- self.GetControllerValue_c = self.rdDll.GetControllerValue
- self.GetControllerValue_c.restype = ctypes.c_float
- self.GetControllerValue_c.argtypes = [ctypes.c_int, ctypes.c_int]
- def SetRailSimConnected(self, connected):
- """connect or disconnect to the API. Must be called first with True"""
- self.SetRailSimConnected_c(connected)
- def SetRailDriverConnected(self, connected):
- """connect or disconnect to Raildriver."""
- self.SetRailDriverConnected_c(connected)
- def GetRailSimLocoChanged(self):
- """returns if Loco has changed since last call"""
- return self.GetRailSimLocoChanged_c()
- def GetLocoName(self):
- """returns a tuple with 3 elements of the loko name [Producer, Product,Loco Name]"""
- resp = self.GetLocoName_c().decode("utf-8")
- if resp: return tuple(resp.split('.:.'))
- else: return None
- def GetControllerList(self):
- """returns a list of all controllers of the current loco"""
- ctls = self.GetControllerList_c().decode("utf-8")
- if ctls: return ctls.split("::")
- else: return []
- def GetControllerValue(self, vid, t):
- """get the next new/changed value, where
- t=0 (value), t=1 (min), t=2 (max)
- """
- return self.GetControllerValue_c(vid, t)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement