# Path: bitsd/listener/notifier.py
# def send_message(text):
# def send_status(value):
# def send_sound(soundid):
# 
# Path: bitsd/persistence/engine.py
# @contextmanager
# def session_scope():
#     """Provide a transactional scope around a series of operations."""
#     session = Session()
#     try:
#         yield session
#         session.commit()
#     except IntegrityError as e:
#         LOG.error("Integrity error in DB, rolling back: %s", e)
#         session.rollback()
#     except:
#         LOG.error("Error in DB, rolling back.")
#         session.rollback()
#         raise
#     finally:
#         session.close()
# 
# Path: bitsd/persistence/models.py
# class Status(Base):
#     """Representation of a logged status change."""
#     __tablename__ = 'Status'
#     __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8mb4'}
# 
#     OPEN = 'open'
#     CLOSED = 'closed'
#     AWAY = 'away'
# 
#     timestamp = Column(DateTime, primary_key=True, default=datetime.now)
#     value = Column(
#         Enum(OPEN, CLOSED, AWAY),
#         nullable=False
#     )
#     modified_by = Column(Enum('BITS', 'web'), nullable=False)
# 
#     def __init__(self, value, modified_by):
#         self.value = value
#         self.modified_by = modified_by
# 
#     def __str__(self):
#         return 'Status {.value}'.format(self)
# 
#     def jsondict(self, wrap=True):
#         """Return a JSON-serializable dictionary representing the object"""
#         data = {
#             "timestamp": self.timestamp.isoformat(' '),
#             "modifiedby": self.modified_by,
#             "value": self.value
#         }
#         if wrap:
#             return {'status': data}
#         else:
#             return data
# 
# Path: bitsd/common.py
# LOG = logging.getLogger('tornado.general')


import base64
import bitsd.persistence.query as query
from bitsd.listener import notifier
from bitsd.persistence.engine import session_scope
from bitsd.persistence.models import Status
from bitsd.common import LOG

def handle_temperature_command(sensorid, value):
    """Receives and log data received from remote sensor."""
    LOG.info('Received temperature: sensorid=%r, value=%r', sensorid, value)
    try:
        sensorid = int(sensorid)
        value = float(value)
    except ValueError:
        LOG.error('Wrong type for parameters in temperature command!')
        return

    with session_scope() as session:
        temp = query.log_temperature(session, value, sensorid, 'BITS')
        broadcast(temp.jsondict())


def handle_status_command(status):
    """Update status.
    Will reject two identical and consecutive updates
    (prevents opening when already open and vice-versa)."""
    LOG.info('Received status: %r', status)
    try:
        status = int(status)
    except ValueError:
        LOG.error('Wrong type for parameters in temperature command')
        return
    if status not in (0, 1):
        LOG.error('Non existent status %r, ignoring.', status)
        return


# Path: bitsd/listener/notifier.py
# def send_message(text):
# def send_status(value):
# def send_sound(soundid):
# 
# Path: bitsd/persistence/engine.py
# @contextmanager
# def session_scope():
#     """Provide a transactional scope around a series of operations."""
#     session = Session()
#     try:
#         yield session
#         session.commit()
#     except IntegrityError as e:
#         LOG.error("Integrity error in DB, rolling back: %s", e)
#         session.rollback()
#     except:
#         LOG.error("Error in DB, rolling back.")
#         session.rollback()
#         raise
#     finally:
#         session.close()
# 
# Path: bitsd/persistence/models.py
# class Status(Base):
#     """Representation of a logged status change."""
#     __tablename__ = 'Status'
#     __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8mb4'}
# 
#     OPEN = 'open'
#     CLOSED = 'closed'
#     AWAY = 'away'
# 
#     timestamp = Column(DateTime, primary_key=True, default=datetime.now)
#     value = Column(
#         Enum(OPEN, CLOSED, AWAY),
#         nullable=False
#     )
#     modified_by = Column(Enum('BITS', 'web'), nullable=False)
# 
#     def __init__(self, value, modified_by):
#         self.value = value
#         self.modified_by = modified_by
# 
#     def __str__(self):
#         return 'Status {.value}'.format(self)
# 
#     def jsondict(self, wrap=True):
#         """Return a JSON-serializable dictionary representing the object"""
#         data = {
#             "timestamp": self.timestamp.isoformat(' '),
#             "modifiedby": self.modified_by,
#             "value": self.value
#         }
#         if wrap:
#             return {'status': data}
#         else:
#             return data
# 
# Path: bitsd/common.py
# LOG = logging.getLogger('tornado.general')


# Path: bitsd/listener/hooks.py
import base64
import bitsd.persistence.query as query
from bitsd.listener import notifier
from bitsd.persistence.engine import session_scope
from bitsd.persistence.models import Status
from bitsd.common import LOG


def handle_temperature_command(sensorid, value):
    """Receives and log data received from remote sensor."""
    LOG.info('Received temperature: sensorid=%r, value=%r', sensorid, value)
    try:
        sensorid = int(sensorid)
        value = float(value)
    except ValueError:
        LOG.error('Wrong type for parameters in temperature command!')
        return

    with session_scope() as session:
        temp = query.log_temperature(session, value, sensorid, 'BITS')
        broadcast(temp.jsondict())


def handle_status_command(status):
    """Update status.
    Will reject two identical and consecutive updates
    (prevents opening when already open and vice-versa)."""
    LOG.info('Received status: %r', status)
    try:
        status = int(status)
    except ValueError:
        LOG.error('Wrong type for parameters in temperature command')
        return
    if status not in (0, 1):
        LOG.error('Non existent status %r, ignoring.', status)
        return


    textstatus = Status.OPEN if status == 1 else Status.CLOSED