def mbus_probe_secondary_address(ser, mask):
    # False -> Collison
    # None -> No reply
    # True -> Single reply
    meterbus.send_select_frame(ser, mask)
    try:
        frame = meterbus.load(meterbus.recv_frame(ser, 1))
    except meterbus.MBusFrameDecodeError as e:
        frame = e.value

    if isinstance(frame, meterbus.TelegramACK):
        meterbus.send_request_frame(ser, meterbus.ADDRESS_NETWORK_LAYER)
        time.sleep(0.5)

        frame = None
        try:
            frame = meterbus.load(
                meterbus.recv_frame(ser))
        except meterbus.MBusFrameDecodeError:
            pass

        if isinstance(frame, meterbus.TelegramLong):
            return True, frame.secondary_address, frame.manufacturer

        return None, None, None

    return frame, None, None
Example #2
0
def mbus_probe_secondary_address(ser, mask):
    # False -> Collison
    # None -> No reply
    # True -> Single reply
    meterbus.send_select_frame(ser, mask)
    try:
        frame = meterbus.load(meterbus.recv_frame(ser, 1))
    except meterbus.MBusFrameDecodeError as e:
        frame = e.value

    if isinstance(frame, meterbus.TelegramACK):
        meterbus.send_request_frame(ser, meterbus.ADDRESS_NETWORK_LAYER)
        time.sleep(0.5)

        frame = None
        try:
            frame = meterbus.load(meterbus.recv_frame(ser))
        except meterbus.MBusFrameDecodeError:
            pass

        if isinstance(frame, meterbus.TelegramLong):
            return True, frame.secondary_address, frame.manufacturer

        return None, None, None

    return frame, None, None
Example #3
0
    def do_char_dev(self, **kwargs):
        address = self.address
        device = self.device
        baudrate = self.baudrate

        try:
            address = int(address)
            if not (0 <= address <= 254):
                address = address
        except ValueError:
            address = address.upper()

        try:
            ibt = meterbus.inter_byte_timeout(baudrate)
            with serial.serial_for_url(device,
                                       baudrate,
                                       8,
                                       'E',
                                       1,
                                       inter_byte_timeout=ibt,
                                       timeout=1) as ser:
                frame = None

                if meterbus.is_primary_address(address):
                    self.ping_address(ser, meterbus.ADDRESS_NETWORK_LAYER, 0)

                    meterbus.send_request_frame(ser, address)
                    frame = meterbus.load(
                        meterbus.recv_frame(ser, meterbus.FRAME_DATA_LENGTH))

                elif meterbus.is_secondary_address(address):
                    meterbus.send_select_frame(ser, address)
                    try:
                        frame = meterbus.load(meterbus.recv_frame(ser, 1))
                    except meterbus.MBusFrameDecodeError as e:
                        frame = e.value

                    assert isinstance(frame, meterbus.TelegramACK)

                    frame = None
                    # ping_address(ser, meterbus.ADDRESS_NETWORK_LAYER, 0)

                    meterbus.send_request_frame(ser,
                                                meterbus.ADDRESS_NETWORK_LAYER)

                    time.sleep(0.3)

                    frame = meterbus.load(
                        meterbus.recv_frame(ser, meterbus.FRAME_DATA_LENGTH))

                if frame is not None:
                    #print(frame.to_JSON())
                    return frame.to_JSON()

        except serial.serialutil.SerialException as e:
            print(e)
Example #4
0
    def test_request_frame(self):
        self.reset()
        frame = meterbus.TelegramShort()
        frame.header.cField.parts = [
            meterbus.CONTROL_MASK_REQ_UD2 | meterbus.CONTROL_MASK_DIR_M2S
        ]
        frame.header.aField.parts = [0]

        meterbus.send_request_frame(self.master, req=frame)

        self.assertEqual(self.slave.read(5), b"\x10\x5B\x00\x5B\x16")
Example #5
0
    def test_request_frame(self):
        self.reset()
        frame = meterbus.TelegramShort()
        frame.header.cField.parts = [
            meterbus.CONTROL_MASK_REQ_UD2 | meterbus.CONTROL_MASK_DIR_M2S
        ]
        frame.header.aField.parts = [0]

        meterbus.send_request_frame(self.master, req=frame)

        self.assertEqual(self.slave.read(5),
                         b"\x10\x5B\x00\x5B\x16")
Example #6
0
def do_char_dev(args):
    address = None

    try:
         address = int(args.address)
         if not (0 <= address <= 254):
             address = args.address
    except ValueError:
        address = args.address.upper()

    try:
        ibt = meterbus.inter_byte_timeout(args.baudrate)
        with serial.serial_for_url(args.device,
                                   args.baudrate, 8, 'E', 1,
                                   inter_byte_timeout=ibt,
                                   timeout=1) as ser:
            frame = None

            if meterbus.is_primary_address(address):
                if ping_address(ser, address, args.retries, args.echofix):
                    meterbus.send_request_frame(ser, address, read_echo=args.echofix)
                    frame = meterbus.load(
                        meterbus.recv_frame(ser, meterbus.FRAME_DATA_LENGTH))

            elif meterbus.is_secondary_address(address):
                if ping_address(ser, meterbus.ADDRESS_NETWORK_LAYER, args.retries, args.echofix):
                    meterbus.send_select_frame(ser, address, args.echofix)
                    try:
                        frame = meterbus.load(meterbus.recv_frame(ser, 1))
                    except meterbus.MBusFrameDecodeError as e:
                        frame = e.value

                    # Ensure that the select frame request was handled by the slave
                    assert isinstance(frame, meterbus.TelegramACK)

                    frame = None

                    meterbus.send_request_frame(
                        ser, meterbus.ADDRESS_NETWORK_LAYER, read_echo=args.echofix)

                    time.sleep(0.3)

                    frame = meterbus.load(
                        meterbus.recv_frame(ser, meterbus.FRAME_DATA_LENGTH))

            if frame is not None:
                return frame

    except serial.serialutil.SerialException as e:
        print(e)

    return None
def do_char_dev(args):
    address = None

    try:
        address = int(args.address)
        if not (0 <= address <= 254):
            address = args.address
    except ValueError:
        address = args.address.upper()

    try:
        ibt = meterbus.inter_byte_timeout(args.baudrate)
        with serial.serial_for_url(args.device,
                           args.baudrate, 8, 'E', 1,
                           inter_byte_timeout=ibt,
                           timeout=1) as ser:
            frame = None

            if meterbus.is_primary_address(address):
                ping_address(ser, meterbus.ADDRESS_NETWORK_LAYER, 0)

                meterbus.send_request_frame(ser, address)
                frame = meterbus.load(
                    meterbus.recv_frame(ser, meterbus.FRAME_DATA_LENGTH))

            elif meterbus.is_secondary_address(address):
                meterbus.send_select_frame(ser, address)
                try:
                    frame = meterbus.load(meterbus.recv_frame(ser, 1))
                except meterbus.MBusFrameDecodeError as e:
                    frame = e.value

                assert isinstance(frame, meterbus.TelegramACK)

                frame = None
                # ping_address(ser, meterbus.ADDRESS_NETWORK_LAYER, 0)

                meterbus.send_request_frame(
                    ser, meterbus.ADDRESS_NETWORK_LAYER)

                time.sleep(0.3)

                frame = meterbus.load(
                    meterbus.recv_frame(ser, meterbus.FRAME_DATA_LENGTH))

            if frame is not None:
                print(frame.to_JSON())

    except serial.serialutil.SerialException as e:
        print(e)
def mbus_query():
  ser = serial.Serial(serial_dev, baud_rate, 8, 'E', 1, 0.5)
  try:
    meterbus.send_ping_frame(ser, slave_address)
    frame = meterbus.load(meterbus.recv_frame(ser, 1))
    assert isinstance(frame, meterbus.TelegramACK)
    meterbus.send_request_frame(ser, slave_address)
    frame = meterbus.load(meterbus.recv_frame(ser, meterbus.FRAME_DATA_LENGTH))
    assert isinstance(frame, meterbus.TelegramLong)
    mbus_json = json.loads(frame.to_JSON())
    manufacturer = mbus_json["body"]["header"]["manufacturer"]
    client.publish(post_topic, "manufacturer " + manufacturer)
  except:
    log('Failed to read data from slave at address %d' % slave_address)
    client.publish(post_topic, "failed")
Example #9
0
def dvh5x_read(address, device, baudrate):

    try:
        ibt = meterbus.inter_byte_timeout(baudrate)

        with serial.Serial(device,
                           baudrate,
                           parity=serial.PARITY_EVEN,
                           rtscts=False,
                           timeout=0.2) as ser:

            frame = None

            ping_address(ser, meterbus.ADDRESS_NETWORK_LAYER, 0)

            if True:
                ret = ping_address(ser, address, 5)
                print("Ping status: %s " % ret)

                if ret:
                    check_reset(ret)
                else:
                    ser.close()
                    check_reset(ret)
                    return

                time.sleep(0.1)
                send_mask_frame(ser, address)
                frame = meterbus.load(meterbus.recv_frame(ser, 1))
                assert isinstance(frame, meterbus.TelegramACK)
                print("custom ok")

                ping_address(ser, meterbus.ADDRESS_NETWORK_LAYER, 0)
                meterbus.send_request_frame(ser, address)
                recv = meterbus.recv_frame(ser, meterbus.FRAME_DATA_LENGTH)
                #	        print("recv", recv)
                frame = meterbus.load(recv)

                ser.close()
                return frame
            if frame is not None:
                print(frame.body.interpreted['records'][0]['value'])
                ser.close()

    except serial.serialutil.SerialException as e:
        print("SerialException")
        print(e)
Example #10
0
 def test_invalid_request_frame_address(self):
     self.reset()
     retval = meterbus.send_request_frame(self.master, 600, None)
     self.assertEqual(retval, False)
Example #11
0
 def test_valid_request(self):
     self.reset()
     meterbus.send_request_frame(self.master, 0)
     self.assertEqual(self.slave.read(5),
                      b"\x10\x5B\x00\x5B\x16")
Example #12
0
 def test_invalid_request_frame_address(self):
     self.reset()
     retval = meterbus.send_request_frame(self.master, 600, None)
     self.assertEqual(retval, False)
Example #13
0
 def test_valid_request(self):
     self.reset()
     meterbus.send_request_frame(self.master, 0)
     self.assertEqual(self.slave.read(5), b"\x10\x5B\x00\x5B\x16")
def do_char_dev(args):
    address = None

    try:
        address = int(args.address)
        if not (0 <= address <= 254):
            address = args.address
    except ValueError:
        address = args.address.upper()

    try:
        ibt = meterbus.inter_byte_timeout(args.baudrate)
        with serial.serial_for_url(args.device,
                                   args.baudrate,
                                   8,
                                   'E',
                                   1,
                                   inter_byte_timeout=ibt,
                                   timeout=1) as ser:
            frame = None
            result = None
            if meterbus.is_primary_address(address):
                if ping_address(ser, address, args.retries, args.echofix):
                    meterbus.send_request_frame(ser,
                                                address,
                                                read_echo=args.echofix)
                    frame = meterbus.load(
                        meterbus.recv_frame(ser, meterbus.FRAME_DATA_LENGTH))
                else:
                    print("no reply")

            elif meterbus.is_secondary_address(address):
                if ping_address(ser, meterbus.ADDRESS_NETWORK_LAYER,
                                args.retries, args.echofix):
                    meterbus.send_select_frame(ser, address, args.echofix)
                    try:
                        frame = meterbus.load(meterbus.recv_frame(ser, 1))
                    except meterbus.MBusFrameDecodeError as e:
                        frame = e.value

                    # Ensure that the select frame request was handled by the slave
                    assert isinstance(frame, meterbus.TelegramACK)

                    frame = None

                    meterbus.send_request_frame(ser,
                                                meterbus.ADDRESS_NETWORK_LAYER,
                                                read_echo=args.echofix)

                    time.sleep(0.3)

                    frame = meterbus.load(
                        meterbus.recv_frame(ser, meterbus.FRAME_DATA_LENGTH))
                else:
                    print("no reply")

            if frame is not None and args.output != 'dump':
                recs = []
                for rec in frame.records:
                    recs.append({'value': rec.value, 'unit': rec.unit})

                ydata = {
                    'manufacturer':
                    frame.body.bodyHeader.manufacturer_field.
                    decodeManufacturer,
                    'identification':
                    ''.join(map('{:02x}'.format, frame.body.bodyHeader.id_nr)),
                    'access_no':
                    frame.body.bodyHeader.acc_nr_field.parts[0],
                    'medium':
                    frame.body.bodyHeader.measure_medium_field.parts[0],
                    'records':
                    recs
                }

                if args.output == 'json':
                    result = json.dumps(ydata, indent=4, sort_keys=True)
                    print(json.dumps(ydata, indent=4, sort_keys=True))

                elif args.output == 'yaml':

                    def float_representer(dumper, value):
                        if int(value) == value:
                            text = '{0:.4f}'.format(value).rstrip('0').rstrip(
                                '.')
                            return dumper.represent_scalar(
                                u'tag:yaml.org,2002:int', text)
                        else:
                            text = '{0:.4f}'.format(value).rstrip('0').rstrip(
                                '.')
                        return dumper.represent_scalar(
                            u'tag:yaml.org,2002:float', text)

                    # Handle float and Decimal representation
                    yaml.add_representer(float, float_representer)
                    yaml.add_representer(Decimal, float_representer)

                    result = yaml.dump(ydata,
                                       default_flow_style=False,
                                       allow_unicode=True,
                                       encoding=None)
                    print(
                        yaml.dump(ydata,
                                  default_flow_style=False,
                                  allow_unicode=True,
                                  encoding=None))

            elif frame is not None:
                result = frame.to_JSON()
                print(frame.to_JSON())
            return result

    except serial.serialutil.SerialException as e:
        print(e)
def do_char_dev(args):
    address = None

    try:
        address = int(args.address)
        if not (0 <= address <= 254):
            address = args.address
    except ValueError:
        address = args.address.upper()

    try:
        #vib_to_show = ['14:0','59:1','59:0','89:0', '93:0', '255.34:0']
        #vib_to_show = ['14:0','59:0','89:0', '93:0']
        filter = {
            ((14, ), 0, 0): "one",
            #((14,), 0, 1): "one_b",
            ((59, ), 0, 0): "FLOW",
            ((62, ), 0, 0): "FLOW",
            ((89, ), 0, 0): "FLOW_TEMPERATURE",
            ((91, ), 0, 0): "FLOW_TEMPERATURE",
            ((93, ), 0, 0): "RETURN_TEMPERATURE",
            ((95, ), 0, 0): "RETURN_TEMPERATURE",
            ((255, 34), 0, 0): "five",
            ((90, ), 0, 0): "FLOW_TEMPERATURE",
            ((94, ), 0, 0): "RETURN_TEMPERATURE",
        }

        ibt = meterbus.inter_byte_timeout(args.baudrate)

        parity = 'E'
        if args.monitor: parity = 'N'

        with serial.serial_for_url(args.device,
                                   args.baudrate,
                                   8,
                                   parity,
                                   1,
                                   inter_byte_timeout=ibt,
                                   timeout=1) as ser:

            if meterbus.is_primary_address(address):
                if not args.monitor:
                    ping_address(ser, address, 0)
                    #ping_address(ser, meterbus.ADDRESS_NETWORK_LAYER, 0)

                    #setG4modern(ser, address)
                    #print("Landis+Gyr needs time")
                    #time.sleep(4)
                    #print("done")

                t_start = time.time() - 3

                try:
                    #ser.read(1)
                    while True:
                        time.sleep(0.1)

                        if not args.monitor:
                            if (time.time() - t_start) <= int(args.sleep):
                                continue
                            t_start = time.time()
                            meterbus.send_request_frame(ser, address)
                            time.sleep(0.2)

                        frame = None
                        #print(ser.inWaiting(), end = ' ')
                        if ser.inWaiting():  # >= 205:
                            #ser.read()
                            framedata = meterbus.recv_frame(
                                ser, meterbus.FRAME_DATA_LENGTH)
                            print("frame:  ", framedata)
                            if framedata:
                                frame = meterbus.load(framedata)

                        if not frame:
                            continue

                        records = frame.body.bodyPayload.records
                        filtered = {
                            "ts": '{:10.0f}'.format(time.time()),
                            "records": [],
                            "framedata": framedata.hex(),
                        }
                        for record in records:
                            vib = tuple(record.vib.parts)
                            func = record.dib.function_type.value
                            storage_number = record.dib.storage_number
                            key = (vib, func, storage_number)
                            if key in filter:
                                #name = filter.get(key,"value")
                                filtered['records'].append(record.interpreted)
                                # print(name)
                                #record = records[vib]
                                #print('{:10},{:30}:{}'.format(vib, record['type'], record['value']))
                                # value = record.value
                                # if type(value) is int:
                                #     print(' {:8} '.format(value), end='')
                                # else:
                                #     print(' {:10.8} '.format(value), end='')
                                #print()
                        import simplejson as json
                        print(
                            json.dumps(filtered,
                                       sort_keys=True,
                                       indent=4,
                                       use_decimal=True))

                except KeyboardInterrupt:
                    pass

            elif meterbus.is_secondary_address(address):
                meterbus.send_select_frame(ser, address)
                try:
                    frame = meterbus.load(meterbus.recv_frame(ser, 1))
                except meterbus.MBusFrameDecodeError as e:
                    frame = e.value

                assert isinstance(frame, meterbus.TelegramACK)

                frame = None
                # ping_address(ser, meterbus.ADDRESS_NETWORK_LAYER, 0)

                meterbus.send_request_frame(ser,
                                            meterbus.ADDRESS_NETWORK_LAYER)

                time.sleep(0.3)

                frame = meterbus.load(
                    meterbus.recv_frame(ser, meterbus.FRAME_DATA_LENGTH))

                if frame is not None:
                    print(frame.to_JSON())

    except serial.serialutil.SerialException as e:
        print(e)
Example #16
0
sendlab.connect("sendlab.nl", 11884, 60)

print("Sending Init message")
sendlab.publish("node/init", json.dumps(sensorInit))

timestamp = datetime.now()
while(1):
    sendlab.loop()

    timediff = datetime.now() - timestamp
    if (timediff.seconds > 10):
      try:
          meterbus.send_ping_frame(ser, slave_address)
          frame = meterbus.load(meterbus.recv_frame(ser, 1))
          assert isinstance(frame, meterbus.TelegramACK)
          meterbus.send_request_frame(ser, slave_address)
          frame = meterbus.load(meterbus.recv_frame(ser, meterbus.FRAME_DATA_LENGTH))
          assert isinstance(frame, meterbus.TelegramLong)
          obj = json.loads(frame.to_JSON())
          records = obj["body"]["records"]
          data = {
            "id": sensorId,
            "timestamp": get_time_stamp(records),
            "measurements": [{
                "timestamp": get_time_stamp(records),
                "heat_energy":          float(records[0]["value"]),
                "cool_energy":          float(records[1]["value"]),
                "energy_E8":            float(records[2]["value"]),
                "vol_d1_t0":            float(records[3]["value"]),
                "vol_d2_t0":            float(records[4]["value"]),
                "vol_d0_t1":            float(records[5]["value"]),