JSR 256 battery events - java-me

How can I detect whenever the power cord is unplugged from electrical socket using JSR 256?

You would add javax.microedition.io.Connector.sensor to the API Permissions tab of the Application Descriptor of the project properties.

From a quick look at the specifications of the JSR:
(you might want to look for code examples, starting with Appendix D of the spec itself, the latest JavaME SDK, Sony Ericsson developer website, then google)
As always, I would be worried about fragmentation in the diverse implementations of the JSR, but here's my first idea:
import javax.microedition.sensor.*;
SensorInfo[] powerSensorInfoArray = SensorManager.findSensors("power","ambient");
//let's assume there is one SensorInfo in the array.
//open a connection to the sensor.
SensorConnection connection = (SensorConnection)Connector.open(powerSensorInfoArray[0].getUrl(), Connector.READ);
// add a DataListener to the connection
connection.setDataListener(new MyDataListener(), 1);
// implement the data listener
public class MyDataListener implements DataListener {
public void dataReceived(SensorConnection aSensor, Data[] aDataArray, boolean isDataLost) {
//let's assume there is only one channel for the sensor and no data was lost.
// figure out what kind of data the channel provides.
int dataType = aDataArray[0].getChannelInfo().getDataType();
//now, I suggest you switch on dataType and print the value on the screen
// experimentation on the JSR256 implementation you're targetting seems to be
// the only way to figure out out power data is formatted and what values mean.
//only one of the following 3 lines will work:
double[] valueArray = aDataArray[0].getDoubleValues();
int[] valueArray = aDataArray[0].getIntValues();
Object[] valueArray = aDataArray[0].getObjectValues();
// let's assume one value in the valueArray
String valueToPrint = "" + valueArray[0];
// see what happens with that and you plug or unplug the power supply cable.
}
}
You'll need to add javax.microedition.io.Connector.sensor to your MIDlet permissions.
-------EDIT------
Documentation from the JSR-256 implementation on Sony-Ericsson Satio phone (S60 5th edition):
The battery charge sensor has the following characteristics:
Quantity: battery_charge
Context type: device
URL: sensor:battery_charge;contextType=device;model=SonyEricsson
Channels: (index: name, range, unit)
0: battery_charge, 0-100, percent
1: charger_state, 0-1, boolean

Related

what code-instrument should be added to register each http event in MeterRegistry with specific tag & minute value. Event requests are in millions

I need to analyse one http event value which should not be greater than 30mins. & 95% event should belong to this bucket. If it fails send the alert.
My first concern is to get the right metrics in /actuator/prometheus
Steps I took:
As in every http request event, I am getting one integer value called eventMinute.
Using micrometer MeterRegistry, I tried below code
// MeterRegistry meterRegistry ...
meterRegistry.summary("MINUTES_ANALYSIS", tags);
where tag = EVENT_MINUTE which receives some integer value in each
http event.
But this way, it floods the metrics due to millions of event.
Guide me a way please, i am beginner to this. Thanks!!
The simplest solution (which I would recommend you start with) would be to just create 2 counters:
int theThing = //getTheThing()
if(theThing > 30) {
meterRegistry.counter("my.request.counter.abovethreshold").inc()
}
meterRegistry.counter("my.request.counter.total").inc()
You would increment the counter that matches your threshold and another that tracks all requests (or reuse another meter that does that for you).
Then it is simple to setup a chart or alarm:
my_request_counter_abovethreshold/my_request_counter_total < .95
(I didn't test the code. It might need a tiny bit of tweaking)
You'll be able to do a similar thing with DistributionSummary by setting various SLOs (I'm not familiar with them to be able to offer one), but start with something simple first and if it is sufficient, you won't need the other complexity.
There are certain ways to solve this problem
1 ; here is a function which receives tags, name of metrics and a value
public void createOrUpdateHistogram(String metricName, Map<String, String> stringTags, double numericValue)
{
DistributionSummary.builder(metricName)
.tags(tags)
//can enforce slo if required
.publishPercentileHistogram()
.minimumExpectedValue(1.0D) // can take this based on how you want your distibution
.maximumExpectedValue(30.0D)
.register(this.meterRegistry)
.record(numericValue);
}
then it produce metrics like
delta_bucket{mode="CURRENT",le="30.0",} 11.0
delta_bucket{mode="CURRENT", le="+Inf",} 11.0
so as infinte also hold the less than value, so subtract the le=30 from le=+Inf
Another ways could be
public void createOrUpdateHistogram(String metricName, Map<String, String> stringTags, double numericValue)
{
Timer.builder(metricName)
.tags(tags)
.publishPercentiles(new double[]{0.5D, 0.95D})
.publishPercentileHistogram()
.serviceLevelObjectives(new Duration[]{Duration.ofMinutes(30L)})
.minimumExpectedValue(Duration.ofMinutes(30L))
.maximumExpectedValue(Duration.ofMinutes(30L))
.register(this.meterRegistry)
.record((long)timeDifference, TimeUnit.MINUTES);
}
it will only have two le, the given time and +inf
it can be change based on our requirements also it gives us quantile.

My segmented picker has normal Int values as tags, How is this passed to and from CoreData?

My SwiftUI segmented control picker uses plain Int ".tag(1)" etc values for its selection.
CoreData only has Int16, Int32 & Int64 options to choose from, and with any of those options it seems my picker selection and CoreData refuse to talk to each other.
How is this (??simple??) task achieved please?
I've tried every numeric based option within CoreData including Int16-64, doubles and floats, all of them break my code or simply just don't work.
Picker(selection: $addDogVM.gender, label: Text("Gender?")) {
Text("Boy ♂").tag(1)
Text("?").tag(2)
Text("Girl ♀").tag(3)
}
I expected any of the 3 CoreData Int options to work out of the box, and to be compatible with the (standard) Int used by the picker.
Each element of a segmented control is represented by an index of type Int, and this index therefore commences at 0.
So using your example of a segmented control with three segments (for example: Boy ♂, ?, Girl ♀), each segment is represented by three indexes 0, 1 & 2.
If the user selects the segmented control that represents Girl ♀, then...
segmentedControl.selectedSegmentIndex = 2
When storing a value using Core Data framework, that is to be represented as a segmented control index in the UI, I therefore always commence with 0.
Everything you read from this point onwards is programmer preference - that is and to be clear - there are a number of ways to achieve the same outcome and you should choose one that best suits you and your coding style. Note also that this can be confusing for a newcomer, so I would encourage patience. My only advice, keep things as simple as possible until you've tested and debugged and tested enough to understand the differences.
So to continue:
The Apple Documentation states that...
...on 64-bit platforms, Int is the same size as Int64.
So in the Core Data model editor (.xcdatamodeld file), I choose to apply an Integer 64 attribute type for any value that will be used as an Int in my code.
Also, somewhere, some time ago, I read that if there is no reason to use Integer 16 or Integer 32, then default to the use of Integer 64 in object model graph. (I assume Integer 16 or Integer 32 are kept for backward compatibility.) If I find that reference I'll link it here.
I could write about the use of scalar attribute types here and manually writing your managed object subclass/es by selecting in the attribute inspector Class Codegen = Manual/None, but honestly I have decided such added detail will only complicate matters.
So your "automatically generated by Core Data" managed object subclass/es (NSManagedObject) will use the optional NSNumber? wrapper...
You will therefore need to convert your persisted/saved data in your code.
I do this in two places... when I access the data and when I persist the data.
(Noting I assume your entity is of type Dog and an instance exists of dog i.e. let dog = Dog())
// access
tempGender = dog.gender as? Int
// save
dog.gender = tempGender as NSNumber?
In between, I use a "temp" var property of type Int to work with the segmented control.
// temporary property to use with segmented control
private var tempGender: Int?
UPDATE
I do the last part a little differently now...
Rather than convert the data in code, I made a simple extension to my managed object subclass to execute the conversion. So rather than accessing the Core Data attribute directly and manipulating the data in code, now I instead use this convenience var.
extension Dog {
var genderAsInt: Int {
get {
guard let gender = self.gender else { return 0 }
return Int(truncating: gender)
}
set {
self.gender = NSNumber(value: newValue)
}
}
}
Your picker code...
Picker(selection: $addDogVM.genderAsInt, label: Text("Gender?")) {
Text("Boy ♂").tag(0)
Text("?").tag(1)
Text("Girl ♀").tag(2)
}
Any questions, ask in the comments.

Register Abstraction Layer Difference Access Type

I am writing a set of register models using uvm_reg class. Individual register size is 8-bit. Register block is created to contains those registers:
class my_reg_block extends uvm_reg_block;
my_byte_reg reg_00;
my_byte_reg reg_01;
my_byte_reg reg_10;
my_byte_reg reg_11;
...
// build()
my_map.add_reg(reg_00, 32'h0000 /*offset*/, ""RW");
my_map.add_reg(reg_01, 32'h0001 /*offset*/, ""RW");
my_map.add_reg(reg_10, 32'h0002 /*offset*/, ""RW");
my_map.add_reg(reg_11, 32'h0003 /*offset*/, ""RW");
...
I have a register adapter that will translate read/write into bus transaction.
So, I am able to do this inside my sequence:
reg_00.write(status, 'hff, .parent(this));
The bus transaction will do write to that specific register: reg_00.
My problem is that the bus has byte_enable that allow it to write accross 4 register in double-word access. Using the existing register model above, is it possible to write/read in 4 register at the same time? Or do I need to create another set of registers (with 32-bit size)?
It would be something like this pseudo-code:
{reg_11,reg_10,reg_01,reg_00}.write(status, 'hffffffff, .parent(this));
Any suggestion?
you could try passing additional information like byte_enable to the adapter using the extension argument in the write function. Then the adapter can decide accordingly if this is a legal double word transaction and assign the bus transaction fields accordingly. see partial example below
virtual function uvm_sequence_item reg2bus(const ref uvm_reg_bus_op rw);
bus_trans trans;
uvm_reg_item item;
regtrans_params params;
item = get_item();
trans = bus_trans::type_id::create("trans");
if(item.extension == null)
`uvm_fatal("", "item.extension==null !!")
if(!$cast(params, item.extension))
`uvm_fatal("", "FAILED $cast(params, item.extension) !!")
trans.dst_chip_addr = params.chip_addr;
in the sequence:
block.reg_00.write(status, 32'hfffffffff .extension(params));

Xamarin Numeric only field

In my Xamarin forms View I have an entry control, to which I have added,
myEntry.Keyboard = Keyboard.Numeric;
to make it decimal only.
In Android devices this code will accept only one decimal point at any given time.
However in IOS, it accepts multiple decimal points?? Is there any way I can restrict only one decimal point in IOS too.
In Xamarin.Forms Entry you have a TextChanged event handler that you can tap into when the entry changes.
You are given both the old text string and also the new text string value.
You can then do a count on the number of decimal points that are in the new text string, check to see if it is greater than 1.
If it is, simply set the Entry.Text to the old value and then you will only ever have one decimal point.
Using the TextChanged event handler you can one of the various TryParse methods. These methods can be given specific cultures and styles also. Example below uses Double's version.
private void Entry_TextChanged(object sender, TextChangedEventArgs e)
{
string newValue = e.NewTextValue;
double value;
if (double.TryParse(newValue, out value))
{
// Do logic for valid value
}
else
{
// Do logic for invalid value
}
}

CLLocation does not have a Coordinates property

I am just working my way through the location services for the first time and everything appears to be working in that it correctly finds my location but I am having trouble extracting the coordinates.
The docs states that CLLocation has a "Coordinates" property and the compiler is happy with this piece of code. However at runtime the CLLocation only appears to return a string description.
I start the location manager
_locationManager = new CLLocationManager ();
_locationManager.DesiredAccuracy = 1000;
// handle the updated location method and update the UI
_locationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
UpdateLocation (e.Locations [e.Locations.Length - 1], _destinationLatitude, _destinationLongitude);
};
if (CLLocationManager.LocationServicesEnabled)
_locationManager.StartUpdatingLocation ();
The event fires correctly
static public void UpdateLocation (CLLocation current, Double destinationLat, Double destinationLng)
{
//Make the start pairing
string start = current.Coordinate.Latitude.ToString() + "," + current.Coordinate.Longitude.ToString();
//Make the destination pairing
string destination = destinationLat.ToString() + "," + destinationLng.ToString();
}
However the app just crashes out. Catching it on a breakpoint I see the following which only appears to have a description property that contains.
Description "<+50.58198902,-3.67661728> +/- 65.00m (speed -1.00 mps / course -1.00) # 25/07/2013 13:11:28 British…" string
I can obviously extract the lat/lng from this text field but I get the feeling I shouldn't need to do this. Any help appreciated.
I moved the exact same code into a different controller and it worked fine. The only difference between the two controllers was that the failing controller was using the monotouch dialog reflection api to bind the screen elements. I can't see why this would make any difference but it is the only difference between the two controllers. Everything is working now, I will try to reproduce in a smaller sample if I get the time.

Resources