from pylogix import PLC
from threading import Thread
import time
from datetime import datetime

from inputs.common import Input

localtz = datetime.now().astimezone().tzinfo

class AllenBradleyCPU(Input):
 
  def __init__(self, host):
    super().__init__(self.read_handler)
    self.comm = PLC()
    self.comm.IPAddress = host
    self.tag = "STL"
    self.port = 0
    self.E_offset = 12 + self.port * 48
    self.E_connected_offset = self.E_offset + 32
    self.E_error_offset = self.E_offset + 33

    self.A_offset = 6 + self.port * 32

    self.interval = 0.02

  def read_handler(self):
    timestamp = datetime.now(localtz)
    ret = self.comm.Read(F"{self.tag}:I")
    if ret.Status == "Success":
      raw = ret.Value
      self.queue_ifm_from_bytes("AB", timestamp, raw[self.E_offset:self.E_offset+30])