def test_date_copy(self): if _debug: TestDate._debug("test_date_copy") value = (1, 2, 3, 4) obj1 = Date(value) obj2 = Date(obj1) assert obj2.value == value
def test_date_statement(self): if _debug: TestExtendedTagStatements._debug("test_date_statement") assert statement_to_tag("date 1/1/70") == tag_encode(Date((70, 1, 1, 4))) # note that the day of the week is not optional for date statements with a context assert statement_to_tag("date 2015-8-31 1 context 11") == tag_encode(Date((115, 8, 31, 1)), context=11)
def test_date(self): if _debug: TestDate._debug("test_date") # default values is all dont care obj = Date() assert obj.value == (255, 255, 255, 255) with self.assertRaises(ValueError): Date("some string")
def convert_to_datetime(self, value): datetime = None try: if re.search(r"[a-z]\)", str(Date(value))): datetime = Date(value) else: datetime = Time(value) except (TypeError, ValueError): datetime = value return datetime
def do_except(self, args): """except <date> <start> <stop>""" args = args.split() if _debug: TestConsoleCmd._debug("do_except %r", args) date_string, start_string, stop_string = args except_date = Date(date_string).value start_time = Time(start_string).value stop_time = Time(stop_string).value exception_schedule = ArrayOf(SpecialEvent)([ SpecialEvent( period=SpecialEventPeriod(calendarEntry=CalendarEntry( date=except_date)), listOfTimeValues=[ TimeValue(time=start_time, value=Real(999.0)), TimeValue(time=stop_time, value=Null()), ], eventPriority=1, ) ]) if _debug: TestConsoleCmd._debug(" - exception_schedule: %r", exception_schedule) # new exception test_schedule.exceptionSchedule = exception_schedule
def read_log_buffer(self): RECORDS = 10 log_buffer = set() _actual_index = self._total_record_count() start = max(_actual_index - self.properties.record_count, self._last_index) + 1 _count = _actual_index - start steps = int(_count / 10) + int(_count % 10) self._log.debug("Reading log : {} {} {}".format(start, _count, steps)) _from = start for each in range(steps): range_params = ("s", _from, Date("1979-01-01"), Time("00:00"), RECORDS) _chunk = self.properties.device.properties.network.readRange( "{} trendLog {} logBuffer".format( self.properties.device.properties.address, str(self.properties.oid)), range_params=range_params, ) _from += len(_chunk) for chunk in _chunk: log_buffer.add(chunk) self._last_index = _from self.create_dataframe(log_buffer)
def test_Date_from_str(self): for each in self.test_values: new_date = Date(each[0]) y, m, d, dow = new_date.value self.assertEqual(y, each[1]) self.assertEqual(m, each[2]) self.assertEqual(d, each[3]) self.assertEqual(dow, each[4])
def date_decode(tag): """Decode a date application tag into a date.""" if _debug: date_decode._debug("date_decode %r", tag) obj = Date(tag) if _debug: date_decode._debug(" - obj: %r", obj) return obj
def _build_datetime(UTC=False): if UTC: _d = dt.datetime.utcnow().date() _t = dt.datetime.utcnow().time() _date = Date(year=_d.year - 1900, month=_d.month, day=_d.day, day_of_week=_d.isoweekday()).value _time = Time( hour=_t.hour, minute=_t.minute, second=_t.second, hundredth=int(_t.microsecond / 10000), ).value else: _date = Date().now().value _time = Time().now().value return DateTime(date=_date, time=_time)
def test_date_tag(self): if _debug: TestDate._debug("test_date_tag") tag = Tag(Tag.applicationTagClass, Tag.dateAppTag, 4, xtob('01020304')) obj = Date(tag) assert obj.value == (1, 2, 3, 4) tag = Tag(Tag.applicationTagClass, Tag.booleanAppTag, 0, xtob('')) with self.assertRaises(InvalidTag): Date(tag) tag = Tag(Tag.contextTagClass, 0, 1, xtob('ff')) with self.assertRaises(InvalidTag): Date(tag) tag = Tag(Tag.openingTagClass, 0) with self.assertRaises(InvalidTag): Date(tag)
def main(): global this_application # parse the command line arguments args = ConfigArgumentParser(description=__doc__).parse_args() if _debug: _log.debug("initialization") if _debug: _log.debug(" - args: %r", args) # make a device object this_device = LocalDeviceObject(ini=args.ini) if _debug: _log.debug(" - this_device: %r", this_device) # make a sample application this_application = BIPSimpleApplication(this_device, args.ini.address) # make a commandable analog value object, add to the device avo1 = AnalogValueCmdObject(objectIdentifier=("analogValue", 1), objectName="avo1") if _debug: _log.debug(" - avo1: %r", avo1) this_application.add_object(avo1) # make a commandable binary output object, add to the device boo1 = BinaryOutputCmdObject( objectIdentifier=("binaryOutput", 1), objectName="boo1", presentValue="inactive", relinquishDefault="inactive", minimumOnTime=5, # let it warm up minimumOffTime=10, # let it cool off ) if _debug: _log.debug(" - boo1: %r", boo1) this_application.add_object(boo1) # get the current date today = Date().now() # make a commandable date value object, add to the device dvo1 = DateValueCmdObject(objectIdentifier=("dateValue", 1), objectName="dvo1", presentValue=today.value) if _debug: _log.debug(" - dvo1: %r", dvo1) this_application.add_object(dvo1) if _debug: _log.debug("running") run() _log.debug("fini")
def main(): # parse the command line arguments args = ConfigArgumentParser(description=__doc__).parse_args() if _debug: _log.debug("initialization") if _debug: _log.debug(" - args: %r", args) # make a device object this_device = LocalDeviceObject( objectName=args.ini.objectname, objectIdentifier=int(args.ini.objectidentifier), maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted), segmentationSupported=args.ini.segmentationsupported, vendorIdentifier=int(args.ini.vendoridentifier), ) # make a sample application this_application = BIPSimpleApplication(this_device, args.ini.address) # make a commandable analog value object, add to the device avo1 = LocalAnalogValueObjectCmd( objectIdentifier=('analogValue', 1), objectName='avo1', ) if _debug: _log.debug(" - avo1: %r", avo1) this_application.add_object(avo1) # make a commandable binary output object, add to the device boo1 = LocalBinaryOutputObjectCmd( objectIdentifier=('binaryOutput', 1), objectName='boo1', presentValue='inactive', relinquishDefault='inactive', minimumOnTime=5, # let it warm up minimumOffTime=10, # let it cool off ) if _debug: _log.debug(" - boo1: %r", boo1) this_application.add_object(boo1) # get the current date today = Date().now() # make a commandable date value object, add to the device dvo1 = LocalDateValueObjectCmd( objectIdentifier=('dateValue', 1), objectName='dvo1', presentValue=today.value, ) if _debug: _log.debug(" - dvo1: %r", dvo1) this_application.add_object(dvo1) if _debug: _log.debug("running") run() _log.debug("fini")
def create_DateTimeValue(oid=1, date=None, time=None, name="DateTime", pv_writable=False): datetime = DateTimeValueObject(objectIdentifier=("datetimeValue", oid), objectName=name) datetime = _make_mutable(datetime, mutable=pv_writable) datetime.presentValue = DateTime(date=Date(date), time=Time(time)) return datetime
def permutation(**kwargs): for pattern in patterns: test_string = pattern % kwargs try: test_date = Date(test_string) test_value = test_date.value except Exception as why: test_value = str(why) print(test_string + '\t' + str(test_value)) print()
def build_rrange_request( self, args, range_params=None, arr_index=None, vendor_id=0, bacoid=None ): addr, obj_type, obj_inst, prop_id = args[:4] vendor_id = vendor_id bacoid = bacoid if obj_type.isdigit(): obj_type = int(obj_type) elif not get_object_class(obj_type, vendor_id=vendor_id): raise ValueError("Unknown object type {}".format(obj_type)) obj_inst = int(obj_inst) if prop_id.isdigit(): prop_id = int(prop_id) datatype = get_datatype(obj_type, prop_id, vendor_id=vendor_id) if not datatype: raise ValueError("invalid property for object type") # build a request request = ReadRangeRequest( objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id ) request.pduDestination = Address(addr) if range_params is not None: range_type, first, date, time, count = range_params if range_type == "p": rbp = RangeByPosition(referenceIndex=int(first), count=int(count)) request.range = Range(byPosition=rbp) elif range_type == "s": rbs = RangeBySequenceNumber( referenceSequenceNumber=int(first), count=int(count) ) request.range = Range(bySequenceNumber=rbs) elif range_type == "t": rbt = RangeByTime( referenceTime=DateTime( date=Date(date).value, time=Time(time).value ), count=int(count), ) request.range = Range(byTime=rbt) elif range_type == "x": # should be missing required parameter request.range = Range() else: raise ValueError("unknown range type: %r" % (range_type,)) if len(args) == 5: request.propertyArrayIndex = int(args[4]) self._log.debug("{:<20} {!r}".format("REQUEST", request)) return request
def do_test(self, args): """test <date> <time>""" args = args.split() if _debug: TestConsoleCmd._debug("do_test %r", args) date_string, time_string = args test_date = Date(date_string).value test_time = Time(time_string).value for so in schedule_objects: v, t = so._task.eval(test_date, test_time) print(so.objectName + ", " + repr(v and v.value) + " until " + str(t))
def date_endec(v, x): """Pass the value to Date, construct a tag from the hex string, and compare results of encode and decoding each other.""" if _debug: date_endec._debug("date_endec %r %r", v, x) tag = date_tag(x) if _debug: date_endec._debug(" - tag: %r, %r", tag, tag.tagData) obj = Date(v) if _debug: date_endec._debug(" - obj: %r, %r", obj, obj.value) assert date_encode(obj) == tag assert date_decode(tag) == obj
def test_8_10_1(self): """Confirmed Notifications Subscription""" if _debug: TestPulseConverter._debug("test_8_10_1") # create a network anet = ApplicationNetwork("test_8_10_1") # add the ability to accept COV notifications to the TD anet.td.add_capability(COVTestClientServices) # tell the TD how to respond to confirmed notifications anet.td.test_ack = True anet.td.test_reject = None anet.td.test_abort = None # add the service capability to the IUT anet.iut.add_capability(ChangeOfValueServices) # make a pulse converter object test_pc = PulseConverterObject( objectIdentifier=('pulseConverter', 1), objectName='pc', presentValue=0.0, statusFlags=[0, 0, 0, 0], updateTime=DateTime(date=Date().now().value, time=Time().now().value), covIncrement=10.0, covPeriod=10, ) # add it to the implementation anet.iut.add_object(test_pc) # wait for the subscription anet.iut.start_state.doc("8.10.1-1-0") \ .receive(SubscribeCOVRequest).doc("8.10.1-1-1") \ .success() # send the subscription, wait for the ack anet.td.start_state.doc("8.10.1-2-0") \ .send(SubscribeCOVRequest( destination=anet.iut.address, subscriberProcessIdentifier=1, monitoredObjectIdentifier=('pulseConverter', 1), issueConfirmedNotifications=True, lifetime=30, )).doc("8.10.1-2-1") \ .receive(SimpleAckPDU).doc("8.10.1-2-2") \ .success() # run the group anet.run()
def process_task(self): if _debug: PulseTask._debug("process_task") # increment the present value self.accumulator.presentValue += self.increment # update the value change time current_date = Date().now().value current_time = Time().now().value value_change_time = DateTime(date=current_date, time=current_time) if _debug: PulseTask._debug(" - value_change_time: %r", value_change_time) self.accumulator.valueChangeTime = value_change_time
def process_task(self): if _debug: LocalScheduleInterpreter._debug("process_task(%s)", self.sched_obj.objectName) # check for a valid configuration if self.sched_obj.reliability != 'noFaultDetected': if _debug: LocalScheduleInterpreter._debug(" - fault detected") return # get the date and time from the device object in case it provides # some custom functionality if self.sched_obj._app and self.sched_obj._app.localDevice: current_date = self.sched_obj._app.localDevice.localDate if _debug: LocalScheduleInterpreter._debug(" - current_date: %r", current_date) current_time = self.sched_obj._app.localDevice.localTime if _debug: LocalScheduleInterpreter._debug(" - current_time: %r", current_time) else: # get the current date and time, as provided by the task manager current_date = Date().now().value if _debug: LocalScheduleInterpreter._debug(" - current_date: %r", current_date) current_time = Time().now().value if _debug: LocalScheduleInterpreter._debug(" - current_time: %r", current_time) # evaluate the time current_value, next_transition = self.eval(current_date, current_time) if _debug: LocalScheduleInterpreter._debug( " - current_value, next_transition: %r, %r", current_value, next_transition) # set the present value self.sched_obj.presentValue = current_value # compute the time of the next transition transition_time = datetime_to_time(current_date, next_transition) # install this to run again self.install_task(transition_time)
def ReadProperty(self, obj, arrayIndex=None): if _debug: CurrentDateTimeProperty._debug("ReadProperty %r arrayIndex=%r", obj, arrayIndex) # access an array if arrayIndex is not None: raise ExecutionError(errorClass='property', errorCode='propertyIsNotAnArray') # get the value current_date = Date().now().value current_time = Time().now().value value = DateTime(date=current_date, time=current_time) if _debug: CurrentDateTimeProperty._debug(" - value: %r", value) return value
def main(): # parse the command line arguments args = ConfigArgumentParser(description=__doc__).parse_args() if _debug: _log.debug("initialization") if _debug: _log.debug(" - args: %r", args) # make a device object this_device = LocalDeviceObject( objectName=args.ini.objectname, objectIdentifier=int(args.ini.objectidentifier), maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted), segmentationSupported=args.ini.segmentationsupported, vendorIdentifier=int(args.ini.vendoridentifier), ) # make a sample application this_application = BIPSimpleApplication(this_device, args.ini.address) # make a commandable analog value object, add to the device cavo1 = CommandableAnalogValueObject( objectIdentifier=('analogValue', 1), objectName='Commandable1', ) if _debug: _log.debug(" - cavo1: %r", cavo1) this_application.add_object(cavo1) # get the current date today = Date().now() # make a commandable date value object, add to the device cdvo2 = CommandableDateValueObject( objectIdentifier=('dateValue', 1), objectName='Commandable2', presentValue=today.value, ) if _debug: _log.debug(" - cdvo2: %r", cdvo2) this_application.add_object(cdvo2) if _debug: _log.debug("running") run() _log.debug("fini")
def main(): global this_application # parse the command line arguments args = ConfigArgumentParser(description=__doc__).parse_args() if _debug: _log.debug("initialization") if _debug: _log.debug(" - args: %r", args) # make a device object this_device = LocalDeviceObject(ini=args.ini) if _debug: _log.debug(" - this_device: %r", this_device) # make a simple application this_application = ReadRangeApplication(this_device, args.ini.address) timestamp = DateTime(date=Date().now().value, time=Time().now().value) # log_status = LogStatus([0,0,0]) log_record_datum = LogRecordLogDatum(booleanValue=False) status_flags = StatusFlags([0, 0, 0, 0]) log_record = LogRecord(timestamp=timestamp, logDatum=log_record_datum, statusFlags=status_flags) trend_log_object = TrendLogObject( objectIdentifier=("trendLog", 1), objectName="Trend-Log-1", logBuffer=[log_record], ) _log.debug(" - trend_log_object: %r", trend_log_object) this_application.add_object(trend_log_object) _log.debug("running") run() _log.debug("fini")
def test_no_traffic(self): """Test basic configuration of a network.""" if _debug: TestPulseConverter._debug("test_no_traffic") # create a network anet = ApplicationNetwork("test_no_traffic") # add the service capability to the IUT anet.iut.add_capability(ChangeOfValueServices) # make a pulse converter object test_pc = PulseConverterObject( objectIdentifier=('pulseConverter', 1), objectName='pc', presentValue=0.0, statusFlags=[0, 0, 0, 0], updateTime=DateTime(date=Date().now().value, time=Time().now().value), covIncrement=10.0, covPeriod=10, ) # an easy way to change the present value write_test_pc = lambda v: setattr(test_pc, 'presentValue', v) # add it to the implementation anet.iut.add_object(test_pc) # make some transitions anet.iut.start_state.doc("1-1-0") \ .call(write_test_pc, 100.0).doc("1-1-1") \ .timeout(1).doc("1-1-2") \ .call(write_test_pc, 0.0).doc("1-1-3") \ .timeout(1).doc("1-1-4") \ .success() # test device is quiet anet.td.start_state.timeout(5).success() # run the group anet.run()
def sometime(self, klass, now, args): if _debug: TestConsoleCmd._debug("sometime %r %r %r", klass, now, args) try: addr = args[0] # look for a time to send if (len(args) > 1): when = time.strptime(' '.join(args[1:]), TIME_FORMAT) else: when = now if _debug: TestConsoleCmd._debug(" - when: %r", when) # build the date and time primitives when_date = Date( year=when.tm_year - 1900, month=when.tm_mon, day=when.tm_mday, dayOfWeek=when.tm_wday + 1, ) if _debug: TestConsoleCmd._debug(" - when_date: %s", when_date) when_time = Time(hour=when.tm_hour, minute=when.tm_min, second=when.tm_sec, hundredth=0) if _debug: TestConsoleCmd._debug(" - when_time: %s", when_time) # build a request request = klass() request.pduDestination = Address(addr) # only one simple parameter, happens to be the same for both types request.time = DateTime(date=when_date, time=when_time) # give it to the application this_application.request(request) except Exception, e: TestConsoleCmd._exception("exception: %r", e)
def do_readrange(self, args): """readrange <addr> <objid> <prop> [ <indx> ] [ p <indx> <count> ] [ s <seq> <count> ] [ t <date> <time> <count> ] """ args = args.split() if _debug: ReadRangeConsoleCmd._debug("do_readrange %r", args) try: addr = Address(args.pop(0)) obj_id = ObjectIdentifier(args.pop(0)).value prop_id = args.pop(0) datatype = get_datatype(obj_id[0], prop_id) if not datatype: raise ValueError("invalid property for object type") # build a request request = ReadRangeRequest(destination=addr, objectIdentifier=obj_id, propertyIdentifier=prop_id) # index is optional if args: if args[0].isdigit(): if not issubclass(datatype, Array): raise ValueError("property is not an array") request.propertyArrayIndex = int(args.pop(0)) datatype = datatype.subtype if not issubclass(datatype, List): raise ValueError("property is not a list") # range is optional if args: range_type = args.pop(0) if range_type == "p": rbp = RangeByPosition(referenceIndex=int(args[0]), count=int(args[1])) request.range = Range(byPosition=rbp) elif range_type == "s": rbs = RangeBySequenceNumber(referenceSequenceNumber=int( args[0]), count=int(args[1])) request.range = Range(bySequenceNumber=rbs) elif range_type == "t": rbt = RangeByTime( referenceTime=DateTime(date=Date(args[0]), time=Time(args[1])), count=int(args[2]), ) request.range = Range(byTime=rbt) else: raise ValueError("unknown range type: %r" % (range_type, )) if _debug: ReadRangeConsoleCmd._debug(" - request: %r", request) # make an IOCB iocb = IOCB(request) if _debug: ReadRangeConsoleCmd._debug(" - iocb: %r", iocb) # give it to the application deferred(this_application.request_io, iocb) # wait for it to complete iocb.wait() # do something for success if iocb.ioResponse: apdu = iocb.ioResponse if _debug: ReadRangeConsoleCmd._debug(" - apdu: %r", apdu) # should be an ack if not isinstance(apdu, ReadRangeACK): if _debug: ReadRangeConsoleCmd._debug(" - not an ack") return # find the datatype datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier) if _debug: ReadRangeConsoleCmd._debug(" - datatype: %r", datatype) if not datatype: raise TypeError("unknown datatype") sys.stdout.write("firstSequenceNumber: %s\n" % (apdu.firstSequenceNumber, )) sys.stdout.write("resultFlags: %s\n" % (apdu.resultFlags, )) # cast out the data into a list value = apdu.itemData.cast_out(datatype) # dump it out for i, item in enumerate(value): sys.stdout.write("[%d]\n" % (i, )) item.debug_contents(file=sys.stdout, indent=2) sys.stdout.flush() # do something for error/reject/abort if iocb.ioError: sys.stdout.write(str(iocb.ioError) + "\n") except Exception as error: ReadRangeConsoleCmd._exception("exception: %r", error)
def test_date_tuple(self): if _debug: TestDate._debug("test_date_tuple") obj = Date((1, 2, 3, 4)) assert obj.value == (1, 2, 3, 4) assert str(obj) == "Date(1901-2-3 thu)"
def test_Wrong(self): with self.assertRaises(ValueError): for each in self.notEnoughPreciseOrWrong: new_date = Date(each[0])
def test_date_endec(self): if _debug: TestDate._debug("test_date_endec") with self.assertRaises(InvalidTag): obj = Date(date_tag(''))
def update(): app.weather.update() current_humid = app.dev.this_application.get_object_name( "Current_Humidity") current_temp = app.dev.this_application.get_object_name("Current_Temp") current_winddir = app.dev.this_application.get_object_name( "Current_Wind_Dir") current_windspd = app.dev.this_application.get_object_name( "Current_Wind_Speed") current_pressure = app.dev.this_application.get_object_name( "Current_Pressure") current_cloudcov = app.dev.this_application.get_object_name( "Current_Cloud_Cover") last_update = app.dev.this_application.get_object_name("Last_Update") current_location = app.dev.this_application.get_object_name( "Weather_Station_City") current_description = app.dev.this_application.get_object_name( "Current_Weather_Description") current_dewpoint = app.dev.this_application.get_object_name( "Current_Dewpoint") new_temp = app.weather.temp new_hum = app.weather.hum new_winddir = app.weather.winddir new_windspd = app.weather.windspd new_pressure = app.weather.press new_cloudcov = app.weather.cloudcov new_update_date = app.weather.update new_update_time = app.weather.update new_location = app.weather.city new_description = app.weather.descrip new_dewpoint = app.weather.dewpoint last_update.presentValue.date = Date( app.weather.timestamp.date().isoformat()) last_update.presentValue.time = Time( app.weather.timestamp.time().isoformat()) app.dev._log.info("Setting Temp to {}".format(new_temp)) current_temp.presentValue = new_temp app.dev._log.info("Setting Humidity to {}".format(new_hum)) current_humid.presentValue = new_hum app.dev._log.info("Setting Wind Dir to {}".format(new_winddir)) current_winddir.presentValue = new_winddir app.dev._log.info("Setting Wind Spd to {}".format(new_windspd)) current_windspd.presentValue = new_windspd app.dev._log.info("Setting B Press to {}".format(new_pressure)) current_pressure.presentValue = new_pressure app.dev._log.info("Setting Cloud Cov to {}".format(new_cloudcov)) current_cloudcov.presentValue = new_cloudcov app.dev._log.info("Setting Location to {}".format(new_location)) current_location.presentValue = new_location app.dev._log.info("Setting Description to {}".format(new_description)) current_description.presentValue = new_description app.dev._log.info("Setting Dewpoint to {}".format(new_dewpoint)) current_dewpoint.presentValue = new_dewpoint