Ejemplo n.º 1
0
class TestPubSubscribe(unittest.TestCase):
    def onMessage(self, message):
        self.assertTrue(len(message.payload_objects) > 0)
        msg_body = message.payload_objects[0].content
        self.assertIn(msg_body, MESSAGES)
        self.counter += 1
        if self.counter == len(MESSAGES):
            self.semaphore.release()

    def setUp(self):
        self.counter = 0
        self.semaphore = Semaphore(0)
        self.bw_client = Client()
        self.bw_client.setEntityFromFile(KEY_FILE)
        self.bw_client.overrideAutoChainTo(True)
        self.bw_client.subscribe(URI, self.onMessage)

    def tearDown(self):
        self.bw_client.close()

    def testPublishSubscribe(self):
        for msg in MESSAGES:
            po = PayloadObject((64, 0, 0, 0), None, msg)
            self.bw_client.publish(URI, payload_objects=(po, ))
        self.semaphore.acquire()
Ejemplo n.º 2
0
class TestListQuery(unittest.TestCase):
    def setUp(self):
        self.bw_client = Client()
        self.bw_client.setEntityFromFile(KEY_FILE)
        self.bw_client.overrideAutoChainTo(True)

    def tearDown(self):
        self.bw_client.close()

    def testListQuery(self):
        for planet, probe in PERSISTED_DATA.items():
            po = PayloadObject((64, 0, 0, 0), None, probe)
            uri = BASE_URI + "/persisted/" + planet
            self.bw_client.publish(uri, payload_objects=(po, ), persist=True)

        results = self.bw_client.query(BASE_URI + "/persisted/+")
        self.assertEquals(len(results), len(PERSISTED_DATA))
        probes = [result.payload_objects[0].content for result in results]
        self.assertTrue(
            all([probe in PERSISTED_DATA.values() for probe in probes]))

        children = self.bw_client.list(BASE_URI + "/persisted")
        self.assertEquals(len(children), len(PERSISTED_DATA))
        planets = [child[child.rfind("/") + 1:] for child in children]
        self.assertTrue(
            all([planet in PERSISTED_DATA.keys() for planet in planets]))
class TestPubSubscribe(unittest.TestCase):
    def onMessage(self, message):
        self.assertTrue(len(message.payload_objects) > 0)
        msg_body = message.payload_objects[0].content
        self.assertIn(msg_body, MESSAGES)
        self.counter += 1
        if self.counter == len(MESSAGES):
            self.semaphore.release()

    def setUp(self):
        self.counter = 0
        self.semaphore = Semaphore(0)
        self.bw_client = Client()
        self.bw_client.setEntityFromFile(KEY_FILE)
        self.bw_client.overrideAutoChainTo(True)
        self.bw_client.subscribe(URI, self.onMessage)

    def tearDown(self):
        self.bw_client.close()

    def testPublishSubscribe(self):
        for msg in MESSAGES:
            po = PayloadObject((64, 0, 0, 0), None, msg)
            self.bw_client.publish(URI, payload_objects=(po,))
        self.semaphore.acquire()
Ejemplo n.º 4
0
class TestPubSubFailure(unittest.TestCase):
    def onMessage(self, message):
        pass

    def setUp(self):
        self.bw_client = Client()
        self.bw_client.setEntityFromFile(KEY_FILE)
        self.bw_client.overrideAutoChainTo(True)

    def tearDown(self):
        self.bw_client.close()

    def testSubscribeFailure(self):
        with self.assertRaises(RuntimeError):
            # Unit test key should not have permissions on this URI
            self.bw_client.subscribe("jkolb/test", self.onMessage)

    def testPublishFailure(self):
        with self.assertRaises(RuntimeError):
            # Unit test key should not have permissions on this URI
            po = PayloadObject(ponames.PODFText, None, "Hello, World!")
            self.bw_client.publish("jkolb/test", payload_objects=(po, ))
class TestPubSubFailure(unittest.TestCase):
    def onMessage(self, message):
        pass

    def setUp(self):
        self.bw_client = Client()
        self.bw_client.setEntityFromFile(KEY_FILE)
        self.bw_client.overrideAutoChainTo(True)

    def tearDown(self):
        self.bw_client.close()

    def testSubscribeFailure(self):
        with self.assertRaises(RuntimeError):
            # Unit test key should not have permissions on this URI
            self.bw_client.subscribe("jkolb/test", self.onMessage)

    def testPublishFailure(self):
        with self.assertRaises(RuntimeError):
            # Unit test key should not have permissions on this URI
            po = PayloadObject(ponames.PODFText, None, "Hello, World!")
            self.bw_client.publish("jkolb/test", payload_objects=(po,))
class TestListQuery(unittest.TestCase):
    def setUp(self):
        self.bw_client = Client()
        self.bw_client.setEntityFromFile(KEY_FILE)
        self.bw_client.overrideAutoChainTo(True)

    def tearDown(self):
        self.bw_client.close()

    def testListQuery(self):
        for planet, probe in PERSISTED_DATA.items():
            po = PayloadObject((64, 0, 0, 0), None, probe)
            uri = BASE_URI + "/persisted/" + planet
            self.bw_client.publish(uri, payload_objects=(po,), persist=True)

        results = self.bw_client.query(BASE_URI + "/persisted/+")
        self.assertEquals(len(results), len(PERSISTED_DATA))
        probes = [result.payload_objects[0].content for result in results]
        self.assertTrue(all([probe in PERSISTED_DATA.values() for probe in probes]))

        children = self.bw_client.list(BASE_URI + "/persisted")
        self.assertEquals(len(children), len(PERSISTED_DATA))
        planets = [child[child.rfind("/")+1:] for child in children]
        self.assertTrue(all([planet in PERSISTED_DATA.keys() for planet in planets]))
Ejemplo n.º 7
0
from bw2python import ponames
from bw2python.bwtypes import PayloadObject
from bw2python.client import Client

bw_client = Client()
bw_client.setEntityFromEnviron()
bw_client.overrideAutoChainTo(True)

for i in range(10):
    msg = "{}: Hello, World!".format(i)
    po = PayloadObject(ponames.PODFText, None, msg)
    bw_client.publish("scratch.ns/demo", payload_objects=(po,))
Ejemplo n.º 8
0
    except ValueError:
        print "Invalid parameter file"
        sys.exit(1)

dest_uri = params.get("dest_uri")
if dest_uri is None:
    print "No 'dest_uri' parameter specified"
    sys.exit(1)
message = params.get("message")
if message is None:
    print "No 'message' parameter specified"
    sys.exit(1)

try:
    num_iters = int(sys.argv[1])
except ValueError:
    print "Invalid number of iterations specified"
    sys.exit(1)

bw_client = Client()
bw_client.setEntityFromEnviron()
bw_client.overrideAutoChainTo(True)

for i in range(num_iters):
    msg = "({}) {}".format(i, message)
    po = PayloadObject(ponames.PODFString, None, msg)
    bw_client.publish(dest_uri, payload_objects=(po,))
    time.sleep(1)

print "Emitted {} messages. Terminating".format(num_iters)
Ejemplo n.º 9
0
class Scheduler(object):
    def __init__(self, signal, slot, ssus):
        self.signal = signal
        self.slot = slot
        self.ssu_list = SSU_Link.create_ssu_list(ssus)

        self.bw_client = Client()
        self.bw_client.setEntityFromEnviron()
        self.bw_client.overrideAutoChainTo(True)

        self.last_received_schedule = {
            'kwargs': {
                'temperature': None,
                'relative_humidity': None,
                'heating_setpoint': None,
                'cooling_setpoint': None,
                'override': None,
                'fan': None,
                'mode': None,
                'state': None,
                'time': time.time() * 1e9
            }
        }

    def run(self):
        print "scheduler running"
        self.bw_client.subscribe(self.slot, self.on_message)
        while True:
            #For time-based SSUs. Sends a signal every hour. Publishing will fail if initial SSU is not strictly time-based.
            msg = copy.deepcopy(self.last_received_schedule)
            msg['kwargs']['time'] = time.time() * 1e9
            thread.start_new_thread(self.publish, (), msg)
            time.sleep(3600)
            print "sleeping"

    def publish(self, **kwargs):
        try:
            kwargs = kwargs.get('kwargs')
            sched = self.generate_schedule(kwargs.get('temperature'),
                                           kwargs.get('relative_humidity'),
                                           kwargs.get('heating_setpoint'),
                                           kwargs.get('cooling_setpoint'),
                                           kwargs.get('override'),
                                           kwargs.get('fan'),
                                           kwargs.get('mode'),
                                           kwargs.get('state'),
                                           kwargs.get('time'))
            self.publish_schedule(*sched)
        except Exception as e:
            print "Failed to publish message", e

    def generate_schedule(self, temp, rel_humidity, heating_setpt,
                          cooling_setpt, override, fan, mode, state, time):
        data = (temp, rel_humidity, heating_setpt, cooling_setpt, override,
                fan, mode, state, time)
        curr = self.ssu_list
        while curr is not None:
            data = curr.ssu.generate_schedule(*data)
            curr = curr.rest

        heating_setpt, cooling_setpt = data[2], data[3]

        if temp <= heating_setpt:
            mode = 1
        elif temp >= cooling_setpt:
            mode = 2

        return float(heating_setpt), float(cooling_setpt), override, mode, fan

    def publish_schedule(self, heating_setpt, cooling_setpt, override, mode,
                         fan):
        assert isinstance(heating_setpt, float)
        assert isinstance(cooling_setpt, float)
        assert isinstance(override, bool)
        assert isinstance(mode, int)
        assert isinstance(fan, bool)

        t = {
            'heating_setpoint': heating_setpt,
            'cooling_setpoint': cooling_setpt,
            'override': override,
            'mode': mode,
            'fan': fan
        }
        po = PayloadObject((2, 1, 1, 0), None, msgpack.packb(t))
        print t
        self.bw_client.publish(self.signal, payload_objects=(po, ))

    def on_message(self, bw_message):
        print "msg received"
        try:
            for po in bw_message.payload_objects:
                if po.type_dotted == (2, 1, 1, 0):
                    tstat_data = msgpack.unpackb(po.content)
                    self.last_received_schedule = {'kwargs': tstat_data}
                    thread.start_new_thread(self.publish, (),
                                            self.last_received_schedule)
        except Exception as e:
            print e
Ejemplo n.º 10
0
import smap
import msgpack
import datetime
import time

bw_client = Client()
bw_client.setEntityFromEnviron()
bw_client.overrideAutoChainTo(True)
thermostat = smap.IMT550C()

def toHandle(bw_message):
  for po in bw_message.payload_objects:
    if po.type_dotted == (2, 1, 1, 0):
      to_process = msgpack.unpackb(po.content)
      print to_process
      thermostat.set_state(to_process)

bw_client.subscribe('{0}/slot/state'.format(thermostat.uri), toHandle)

while True:
  msg = thermostat.get_state()
  po = PayloadObject((2, 1, 1, 0), None, msgpack.packb(msg))
  bw_client.publish('{0}/signal/info'.format(thermostat.uri), payload_objects=(po,), persist=True)
  time.sleep(thermostat.sample_rate)

  #RFC 3339 timestamp UTC
  d = datetime.datetime.utcnow()
  timestamp = {'ts': int(time.time()*1e9), 'val': d.isoformat('T')}
  po2 = PayloadObject((2, 0, 3, 1), None, msgpack.packb(timestamp))
  bw_client.publish('{0}/!meta/lastalive'.format(thermostat.uri), payload_objects=(po2,), persist=True)