How to fix No I2c device exists for bus ID1 (GrovePi .net core) - asp.net-core

I'm making a .net core API to control the led lights from my pi, but I'm facing the following error: System.ArgumentException:
No I2C device exists for bus ID 1.
I tried to find some info on how to find the busid of the grovepi but didn't came far. Tried also numbers 1 to 5 also didn't came far.
This is my code:
[1] https://gyazo.com/aa01ab3068201360c3ece14f125b1c45
My error:
[2] https://gyazo.com/6bf3215e4466b02643b6a9eb92d12e52
I expected to turn the light on and get a page with some text but I keep getting the same error.

I can reproduce this issue. I tracked the exception, it is thrown here. I posted an issue(#590) in GitHub.
public Windows10I2cDevice(I2cConnectionSettings settings)
{
_settings = settings;
var winSettings = new WinI2c.I2cConnectionSettings(settings.DeviceAddress);
string busFriendlyName = $"I2C{settings.BusId}";
string deviceSelector = WinI2c.I2cDevice.GetDeviceSelector(busFriendlyName);
DeviceInformationCollection deviceInformationCollection = DeviceInformation.FindAllAsync(deviceSelector).WaitForCompletion();
if (deviceInformationCollection.Count == 0)
{
throw new ArgumentException($"No I2C device exists for bus ID {settings.BusId}.", $"{nameof(settings)}.{nameof(settings.BusId)}");
}
_winI2cDevice = WinI2c.I2cDevice.FromIdAsync(deviceInformationCollection[0].Id, winSettings).WaitForCompletion();
if (_winI2cDevice == null)
{
throw new PlatformNotSupportedException($"I2C devices are not supported.");
}
}
As we know, .net core 3.0 for IoT is preview. May i know why don't you consider to use traditional way to do that? A workaround is, you can host a web server in a UWP app, and you can add the LED control in the UWP app. Please refer to IoTWeb.

Related

system_cpu_usage is Nan when compiled in native

In my quarkus application i'm using micrometer to retrieve metrics (like in this guide : https://quarkus.io/guides/micrometer).
In JVM mode everything works fine, but in native mode system_cpu_usage is "Nan".
I tried bumping micrometer to 1.8.4 and adding :
{
"name":"com.sun.management.OperatingSystemMXBean", "allPublicMethods": true
},
to my reflect-config.json but no luck. I also tried generating the reflect-config (and other native configuration files) with the graalvm tracing agent but still no luck.
This may be a bug.
Micrometer is looking for a few known implementations of the MXBean:
https://github.com/micrometer-metrics/micrometer/blob/b087856355667abf9bf2386265edef8642e0e077/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/ProcessorMetrics.java#L55
private static final List<String> OPERATING_SYSTEM_BEAN_CLASS_NAMES = Arrays.asList(
"com.ibm.lang.management.OperatingSystemMXBean", // J9
"com.sun.management.OperatingSystemMXBean" // HotSpot
);
so that it can find the methods that it should be invoking...
https://github.com/micrometer-metrics/micrometer/blob/b087856355667abf9bf2386265edef8642e0e077/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/ProcessorMetrics.java#L80
this.operatingSystemBean = ManagementFactory.getOperatingSystemMXBean();
this.operatingSystemBeanClass = getFirstClassFound(OPERATING_SYSTEM_BEAN_CLASS_NAMES);
Method getCpuLoad = detectMethod("getCpuLoad");
this.systemCpuUsage = getCpuLoad != null ? getCpuLoad : detectMethod("getSystemCpuLoad");
this.processCpuUsage = detectMethod("getProcessCpuLoad");
(Note specifically "getFirstClassFound", which is constrained against the first list).
Speculation on my part, but I suspect Graal is returning a different type, which is possible from here:
https://github.com/oracle/graal/blob/6ba65dad76a4f54fa59e1ed2a62dedd3afe39928/substratevm/src/com.oracle.svm.core/src/com/oracle/svm/core/jdk/management/ManagementSupport.java#L166
would take some digging to know which, but I would open an issue with Micrometer so we can sort it out.

Why can't local Windows 7 Pro machine read its own WMI values?

As part of a larger .Net 4.0 program I have a piece that queries the WMI for a list of network adapters and from that creates a list<> of physical adapters with MAC addresses.
It works on the machines I've tried it on, but when sent to the client, the list is empty. If they run IPCONFIG /ALL at a command prompt the MACs are listed.
My first thought is that there is a group policy in place preventing the enumeration, but everything I've found so far points to group policies that affects remote access through the firewall.
I've tried it locally as both a standard user and administration user, both provide the same list.
The empty query does not generate an exception.
I could ask them to go to the machines and check individual permissions, but since this seems to be a group issue that seems to be the wrong direction. What am I missing?
public static List<WmiNetworkInterfaceItem> QueryphysicalNetworkInterfaces()
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_NetworkAdapter");
List<WmiNetworkInterfaceItem> result = new List<WmiNetworkInterfaceItem>();
foreach (ManagementObject queryObj in searcher.Get()) {
if (queryObj["PhysicalAdapter"].Equals(true)) {
if (queryObj["AdapterTypeId"] != null) {
if (queryObj["AdapterTypeId"].ToString().Equals("0")) {
WmiNetworkInterfaceItem wmiNetworkInterfaceItem = new WmiNetworkInterfaceItem();
wmiNetworkInterfaceItem.Name = ManagementObjectPropertyString(queryObj["Name"]);
wmiNetworkInterfaceItem.MacAddress = ManagementObjectPropertyString(queryObj["MACAddress"]);
wmiNetworkInterfaceItem.PhysicalAdapter = queryObj["PhysicalAdapter"].Equals(true);
wmiNetworkInterfaceItem.AdapterType = ManagementObjectPropertyString(queryObj["AdapterType"]);
wmiNetworkInterfaceItem.AdapterTypeId = -1;
int.TryParse(ManagementObjectPropertyString(queryObj["AdapterTypeId"]), out wmiNetworkInterfaceItem.AdapterTypeId);
wmiNetworkInterfaceItem.Description = ManagementObjectPropertyString(queryObj["Description"]);
wmiNetworkInterfaceItem.PermanentAddress = ManagementObjectPropertyString(queryObj["PermanentAddress"]);
result.Add(wmiNetworkInterfaceItem);
}
}
}
}
return result;
}
Using the WBEMTest utility included with Windows as suggested by user atp_09 in comments, I was able to have the customer query his machine. Using this query exactly one adapter was returned in both standard and administrative user accounts indicating there was nothing in the machine preventing this from working.
SELECT * FROM Win32_NetworkAdapter where PhysicalAdapter = true
Upon further review there was an error in how I later dealt with the list with a single response.

Read SQL Server Broker messages and publish them using NServiceBus

I am very new to NServiceBus, and in one of our project, we want to accomplish following -
Whenever table data is modified in Sql server, construct a message and insert in sql server broker queue
Read the broker queue message using NServiceBus
Publish the message again as another event so that other subscribers
can handle it.
Now it is point 2, that I do not have much clue, how to get it done.
I have referred the following posts, after which I was able to enter the message in broker queue, but unable to integrate with NServiceBus in our project, as the NServiceBus libraries are of older version and also many methods used are deprecated. So using them with current versions is getting very troublesome, or if I was doing it in improper way.
http://www.nullreference.se/2010/12/06/using-nservicebus-and-servicebroker-net-part-2
https://github.com/jdaigle/servicebroker.net
Any help on the correct way of doing this would be invaluable.
Thanks.
I'm using the current version of nServiceBus (5), VS2013 and SQL Server 2008. I created a Database Change Listener using this tutorial, which uses SQL Server object broker and SQLDependency to monitor the changes to a specific table. (NB This may be deprecated in later versions of SQL Server).
SQL Dependency allows you to use a broad selection of all the basic SQL functionality, although there are some restrictions that you need to be aware of. I modified the code from the tutorial slightly to provide better error information:
void NotifyOnChange(object sender, SqlNotificationEventArgs e)
{
// Check for any errors
if (#"Subscribe|Unknown".Contains(e.Type.ToString())) { throw _DisplayErrorDetails(e); }
var dependency = sender as SqlDependency;
if (dependency != null) dependency.OnChange -= NotifyOnChange;
if (OnChange != null) { OnChange(); }
}
private Exception _DisplayErrorDetails(SqlNotificationEventArgs e)
{
var message = "useful error info";
var messageInner = string.Format("Type:{0}, Source:{1}, Info:{2}", e.Type.ToString(), e.Source.ToString(), e.Info.ToString());
if (#"Subscribe".Contains(e.Type.ToString()) && #"Invalid".Contains(e.Info.ToString()))
messageInner += "\r\n\nThe subscriber says that the statement is invalid - check your SQL statement conforms to specified requirements (http://stackoverflow.com/questions/7588572/what-are-the-limitations-of-sqldependency/7588660#7588660).\n\n";
return new Exception(messageMain, new Exception(messageInner));
}
I also created a project with a "database first" Entity Framework data model to allow me do something with the changed data.
[The relevant part of] My nServiceBus project comprises two "Run as Host" endpoints, one of which publishes event messages. The second endpoint handles the messages. The publisher has been setup to IWantToRunAtStartup, which instantiates the DBListener and passes it the SQL statement I want to run as my change monitor. The onChange() function is passed an anonymous function to read the changed data and publish a message:
using statements
namespace Sample4.TestItemRequest
{
public partial class MyExampleSender : IWantToRunWhenBusStartsAndStops
{
private string NOTIFY_SQL = #"SELECT [id] FROM [dbo].[Test] WITH(NOLOCK) WHERE ISNULL([Status], 'N') = 'N'";
public void Start() { _StartListening(); }
public void Stop() { throw new NotImplementedException(); }
private void _StartListening()
{
var db = new Models.TestEntities();
// Instantiate a new DBListener with the specified connection string
var changeListener = new DatabaseChangeListener(ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString);
// Assign the code within the braces to the DBListener's onChange event
changeListener.OnChange += () =>
{
/* START OF EVENT HANDLING CODE */
//This uses LINQ against the EF data model to get the changed records
IEnumerable<Models.TestItems> _NewTestItems = DataAccessLibrary.GetInitialDataSet(db);
while (_NewTestItems.Count() > 0)
{
foreach (var qq in _NewTestItems)
{
// Do some processing, if required
var newTestItem = new NewTestStarted() { ... set properties from qq object ... };
Bus.Publish(newTestItem);
}
// Because there might be a number of new rows added, I grab them in small batches until finished.
// Probably better to use RX to do this, but this will do for proof of concept
_NewTestItems = DataAccessLibrary.GetNextDataChunk(db);
}
changeListener.Start(string.Format(NOTIFY_SQL));
/* END OF EVENT HANDLING CODE */
};
// Now everything has been set up.... start it running.
changeListener.Start(string.Format(NOTIFY_SQL));
}
}
}
Important The OnChange event firing causes the listener to stop monitoring. It basically is a single event notifier. After you have handled the event, the last thing to do is restart the DBListener. (You can see this in the line preceding the END OF EVENT HANDLING comment).
You need to add a reference to System.Data and possibly System.Data.DataSetExtensions.
The project at the moment is still proof of concept, so I'm well aware that the above can be somewhat improved. Also bear in mind I had to strip out company specific code, so there may be bugs. Treat it as a template, rather than a working example.
I also don't know if this is the right place to put the code - that's partly why I'm on StackOverflow today; to look for better examples of ServiceBus host code. Whatever the failings of my code, the solution works pretty effectively - so far - and meets your goals, too.
Don't worry too much about the ServiceBroker side of things. Once you have set it up, per the tutorial, SQLDependency takes care of the details for you.
The ServiceBroker Transport is very old and not supported anymore, as far as I can remember.
A possible solution would be to "monitor" the interesting tables from the endpoint code using something like a SqlDependency (http://msdn.microsoft.com/en-us/library/62xk7953(v=vs.110).aspx) and then push messages into the relevant queues.
.m

Desktop.isDesktopSupported returning null in windows

I have the following code
desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
url = new URL("http://www.facebook.com");
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(url.toURI());
} catch (Exception e) {
e.printStackTrace();
}
and desktop is returning null for Windows 7. Can anyone suggest what to be done ?
Not sure it's not working with Windows 7 (it worked at me), but Desktop can return false negatives anyway. I had a similar problem and the only way around I could find, is opening the system browser the hard way, using java.lang.Runtime
for windows, your code will be
Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url);
a very nice fully working code that covers OSX and Linux too can be be found here
From the documentation:
public static boolean isDesktopSupported()
Tests whether this class is supported on the current platform. If it's supported, use getDesktop() to retrieve an instance.
Returns:
true if this class is supported on the current platform; false otherwise
To make it short:
Windows 7 does not support this class
See also: similar question
See also: desktop api documentation

Application name is not set. Call Builder#setApplicationName. error

Application: Connecting to BigQuery using BigQuery APIs for Java
Environment: Eclipse, Windows 7
My application was running fine until last night. I've made no changes (except for restarting my computer) and my code is suddenly giving me this error:
Application name is not set. Call Builder#setApplicationName.
Thankfully I had a tar'd version of my workspace from last night. I ran a folder compare and found the local_db.bin file was different. I deleted the existing local_db.bin file and tried to run the program again. And it worked fine!
Any idea why this might have happened?
Hopefully this will help anyone else who stumbles upon this issue.
Try this to set your application name
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential)
.setApplicationName("Your app name")
.build();
If you are working with only Firebase Dynamic Links without Android or iOS app
Try this.
builder.setApplicationName(firebaseUtil.getApplicationName());
FirebaseUtil is custom class add keys and application name to this class
FirebaseDynamicLinks.Builder builder = new FirebaseDynamicLinks.Builder(
GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), null);
// initialize with api key
FirebaseDynamicLinksRequestInitializer firebaseDynamicLinksRequestInitializer = new FirebaseDynamicLinksRequestInitializer(
firebaseUtil.getFirebaseApiKey());
builder.setFirebaseDynamicLinksRequestInitializer(firebaseDynamicLinksRequestInitializer);
builder.setApplicationName(firebaseUtil.getApplicationName());
// build dynamic links
FirebaseDynamicLinks firebasedynamiclinks = builder.build();
// create Firebase Dynamic Links request
CreateShortDynamicLinkRequest createShortLinkRequest = new CreateShortDynamicLinkRequest();
createShortLinkRequest.setLongDynamicLink(firebaseUtil.getFirebaseUrlPrefix() + "?link=" + urlToShorten);
Suffix suffix = new Suffix();
suffix.setOption(firebaseUtil.getShortSuffixOption());
createShortLinkRequest.setSuffix(suffix);
// request short url
FirebaseDynamicLinks.ShortLinks.Create request = firebasedynamiclinks.shortLinks()
.create(createShortLinkRequest);
CreateShortDynamicLinkResponse createShortDynamicLinkResponse = request.execute();