I have the following code
public static class Post {
public String author;
public String title;
public Post(String author, String title) {
}
}
// Get a reference to our posts
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/saving-data/fireblog/posts");
// Attach a listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Post post = dataSnapshot.getValue(Post.class);
System.out.println(post);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
I would like to write it in python. But it seems that Firebase library for python doesn't support it? Any ideas?
Related
I'm trying to pass data from a Raspberry Pi device to a firebase database. I've been successful on making the Pi side of things workout. But so far I've been unsuccessful on making the data flow to my pc using WinForms and C#.
The expected result would be the data inside the database flow to the GUI in WinForms.
Firebase profile has a parent and that parent has 2 children. The parent is named values and the two children named gyroData and sarjData. One equal to "10" and the other equal to "5". I have had a suspicion that the string values could be the issue but it was not. I've tried changing them to integer values which resulted in another error.
Here is my C# program:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using FireSharp;
using FireSharp.Config;
using FireSharp.Response;
using FireSharp.Interfaces;
namespace databaseGUI
{
public partial class Form1 : Form
{
IFirebaseConfig config = new FirebaseConfig
{
// double checked these in my program, all proper.
BasePath = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
AuthSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
};
IFirebaseClient client;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
client = new FireSharp.FirebaseClient(config);
if (client != null)
{
MessageBox.Show("Connected");
}
}
private void RTBButton_Click(object sender, EventArgs e)
{
FirebaseResponse response = client.Get(#"values");
Dictionary<string, valuesClass> data = JsonConvert.DeserializeObject<Dictionary<string, valuesClass>>(response.Body.ToString());
PopulateRTB(data);
}
private void dataView_Click(object sender, EventArgs e)
{
FirebaseResponse response = client.Get(#"values");
Dictionary<string, valuesClass> data = JsonConvert.DeserializeObject<Dictionary<string, valuesClass>>(response.Body.ToString());
PopulateDataView(data);
}
private void PopulateRTB(Dictionary<string, valuesClass> record)
{
richTextBox1.Clear();
foreach (var item in record)
{
richTextBox1.Text += item.Key + "\n";
richTextBox1.Text += item.Value.gyroData + "\n";
richTextBox1.Text += item.Value.sarjData + "\n";
}
}
private void PopulateDataView(Dictionary<string, valuesClass> record)
{
dataGridView1.Rows.Clear();
dataGridView1.Columns.Clear();
dataGridView1.Columns.Add("gyrodata", "Gyro");
dataGridView1.Columns.Add("sarjdata", "Sarj");
foreach (var item in record)
{
dataGridView1.Rows.Add(item.Key, item.Value.gyroData, item.Value.sarjData);
}
}
}
}
My data class:
namespace databaseGUI
{
class degerlerClass
{
public string gyroData { get; set; }
public string sarjData { get; set; }
}
}
And my python program:
import smbus
import time
from pyrebase import pyrebase
import sys
config = {
"apiKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"authDomain": "xxxxxxxxxxxxxxxxxxxxxxx.com",
"databaseURL": "https://xxxxxxxxxxxxxxx.firebaseio.com",
"storageBucket":""
}
firebase = pyrebase.initialize_app(config)
db = firebase.database()
data = {"sarj": str(10), "gyro": str(5) }
db.child("values").set(data)
print(data)
I am trying to upload multiple files through a Flutter frontend, possibly to a Python server. I have not found any working code on how to upload files through Flutter Web. My frontend code is according an answer here: How to Pick files and Images for upload with flutter web
import 'package:http/http.dart' as http;
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
void main() {
/// your app lunch from here
runApp(new MaterialApp(
//// remove debug logo top left AppBar
debugShowCheckedModeBanner: false,
// application title
title: 'Hello World',
// whole content
home: TabsExample(),
));
}
class TabsExample extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return TabsState();
}
}
class TabsState extends State<TabsExample> {
#override
Widget build(BuildContext context) {
// TODO: implement build
return DefaultTabController(
length: 1,
child: new Scaffold(
appBar: AppBar(
title: Text('Test Tab'),
bottom: TabBar(tabs: [
Tab(
icon: Text(
'Test',
),
),
]),
),
body: TabBarView(children: [
new FileUploadWithHttp(),
]),
));
}
}
class FileUploadWithHttp extends StatefulWidget {
#override
_FileUploadWithHttpState createState() => _FileUploadWithHttpState();
}
class _FileUploadWithHttpState extends State<FileUploadWithHttp> {
PlatformFile objFile;
PlatformFile result;
void chooseFileUsingFilePicker() async {
//-----pick file by file picker,
var result = await FilePicker.platform.pickFiles(
withReadStream:
true, // this will return PlatformFile object with read stream
allowMultiple: true);
print(result.files.length);
print(result.names);
// print(result.files.first.path); //not supported on web
if (result != null) {
setState(() {
objFile = result.files[0];
//print(objFile.readStream);
});
}
}
void uploadSelectedFile() async {
//---Create http package multipart request object
final request = http.MultipartRequest(
"POST",
Uri.parse("http://localhost:8000"), // e.g. localhost
);
//-----add other fields if needed
//request.fields["id"] = "abc";
//-----add selected file with request
request.files.add(new http.MultipartFile(
"file", objFile.readStream, objFile.size,
filename: objFile.name));
//-------Send request
var resp = await request.send();
//------Read response
String result = await resp.stream.bytesToString();
//-------Your response
print(result);
print('Upload successfull!');
}
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
//------Button to choose file using file picker plugin
ElevatedButton(
child: Text("Choose File"),
onPressed: () => chooseFileUsingFilePicker()),
//------Show file name when file is selected
if (objFile != null) Text("File name : ${objFile.name}"),
//------Show file size when file is selected
if (objFile != null) Text("File size : ${objFile.size} bytes"),
//------Show upload utton when file is selected
ElevatedButton(
child: Text("Upload"), onPressed: () => uploadSelectedFile()),
],
),
);
}
}
Running this on a python server according to this suggestion: https://gist.github.com/UniIsland/3346170
Or any other one that i've tried does not work, the server is not able to recieve the file properly. The error message is:
(False, "Can't find out file name...", 'by: ', ('::1', 62868, 0, 0))
Is there any straighforward way (possibly with code) on how to upload the file? Or do you have an idea why this error is coming?
Any help would be greatly appreciated!
follow this, it might help you.
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:path/path.dart';
import 'package:dio/dio.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
File _image;
final GlobalKey<ScaffoldState> _scaffoldstate =
new GlobalKey<ScaffoldState>();
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.camera);
_uploadFile(image);
setState(() {
_image = image;
});
}
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
// Methode for file upload
void _uploadFile(filePath) async {
// Get base file name
String fileName = basename(filePath.path);
print("File base name: $fileName");
try {
FormData formData =
new FormData.from({"file": new UploadFileInfo(filePath, fileName)});
Response response =
await Dio().post("http://192.168.0.101/saveFile.php", data: formData);
print("File upload response: $response");
// Show the incoming message in snakbar
_showSnakBarMsg(response.data['message']);
} catch (e) {
print("Exception Caught: $e");
}
}
// Method for showing snak bar message
void _showSnakBarMsg(String msg) {
_scaffoldstate.currentState
.showSnackBar(new SnackBar(content: new Text(msg)));
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
key: _scaffoldstate,
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: _image == null ? Text('No image selected.') : Image.file(_image),
),
floatingActionButton: FloatingActionButton(
onPressed: getImage,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
The following web-page provides example code for using a predictive endpoint using c#
https://learn.microsoft.com/en-us/azure/cognitive-services/custom-vision-service/use-prediction-api
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace CVSPredictionSample
{
public static class Program
{
public static void Main()
{
Console.Write("Enter image file path: ");
string imageFilePath = Console.ReadLine();
MakePredictionRequest(imageFilePath).Wait();
Console.WriteLine("\n\nHit ENTER to exit...");
Console.ReadLine();
}
public static async Task MakePredictionRequest(string imageFilePath)
{
var client = new HttpClient();
// Request headers - replace this example key with your valid Prediction-Key.
client.DefaultRequestHeaders.Add("Prediction-Key", "<Your prediction key>");
// Prediction URL - replace this example URL with your valid Prediction URL.
string url = "<Your prediction URL>";
HttpResponseMessage response;
// Request body. Try this sample with a locally stored image.
byte[] byteData = GetImageAsByteArray(imageFilePath);
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response = await client.PostAsync(url, content);
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
private static byte[] GetImageAsByteArray(string imageFilePath)
{
FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
return binaryReader.ReadBytes((int)fileStream.Length);
}
}
}
How can it be done using Python code ?
Many thanks
A similar documentation exists for Python:
For classification projects here
For object detection projects here
See language selector in the page:
When the main app is running but not active the service notification click brings it to front, that's Ok.
Another case when I close the app by swiping it out from the recent apps list, the service is restarted and when I click the notification just black screen is shown and that's all.
The one interesting thing I noticed, after some time (an hour or two) it gets working - the main app is started on service notification click!
How can I achieve that once the service restarted?
The app is created with Python+Kivy and built with Buildozer and I run it on Android 10.
I tried setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) for the Intent but it didn't help.
Here is some code.
PythonService.java:
package org.kivy.android;
import android.os.Build;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import android.app.Service;
import android.os.IBinder;
import android.os.Bundle;
import android.content.Intent;
import android.content.Context;
import android.util.Log;
import android.app.Notification;
import android.app.PendingIntent;
import android.os.Process;
import java.io.File;
//imports for channel definition
import android.app.NotificationManager;
import android.app.NotificationChannel;
import android.graphics.Color;
public class PythonService extends Service implements Runnable {
// Thread for Python code
private Thread pythonThread = null;
// Python environment variables
private String androidPrivate;
private String androidArgument;
private String pythonName;
private String pythonHome;
private String pythonPath;
private String serviceEntrypoint;
// Argument to pass to Python code,
private String pythonServiceArgument;
public static PythonService mService = null;
private Intent startIntent = null;
private boolean autoRestartService = false;
public void setAutoRestartService(boolean restart) {
autoRestartService = restart;
}
public int startType() {
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (pythonThread != null) {
Log.v("python service", "service exists, do not start again");
return START_NOT_STICKY;
}
startIntent = intent;
Bundle extras = intent.getExtras();
androidPrivate = extras.getString("androidPrivate");
androidArgument = extras.getString("androidArgument");
serviceEntrypoint = extras.getString("serviceEntrypoint");
pythonName = extras.getString("pythonName");
pythonHome = extras.getString("pythonHome");
pythonPath = extras.getString("pythonPath");
boolean serviceStartAsForeground = (
extras.getString("serviceStartAsForeground").equals("true")
);
pythonServiceArgument = extras.getString("pythonServiceArgument");
pythonThread = new Thread(this);
pythonThread.start();
if (serviceStartAsForeground) {
doStartForeground(extras);
}
return startType();
}
protected int getServiceId() {
return 1;
}
protected void doStartForeground(Bundle extras) {
String serviceTitle = extras.getString("serviceTitle");
String serviceDescription = extras.getString("serviceDescription");
Notification notification;
Context context = getApplicationContext();
Intent contextIntent = new Intent(context, PythonActivity.class);
contextIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // my attempt but it didn't helped
PendingIntent pIntent = PendingIntent.getActivity(context, 0, contextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
notification = new Notification(
context.getApplicationInfo().icon, serviceTitle, System.currentTimeMillis());
try {
// prevent using NotificationCompat, this saves 100kb on apk
Method func = notification.getClass().getMethod(
"setLatestEventInfo", Context.class, CharSequence.class,
CharSequence.class, PendingIntent.class);
func.invoke(notification, context, serviceTitle, serviceDescription, pIntent);
} catch (NoSuchMethodException | IllegalAccessException |
IllegalArgumentException | InvocationTargetException e) {
}
} else {
// for android 8+ we need to create our own channel
// https://stackoverflow.com/questions/47531742/startforeground-fail-after-upgrade-to-android-8-1
String NOTIFICATION_CHANNEL_ID = "org.kivy.p4a"; //TODO: make this configurable
String channelName = "Background Service"; //TODO: make this configurable
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName,
NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(chan);
Notification.Builder builder = new Notification.Builder(context, NOTIFICATION_CHANNEL_ID);
builder.setContentTitle(serviceTitle);
builder.setContentText(serviceDescription);
builder.setContentIntent(pIntent);
builder.setSmallIcon(context.getApplicationInfo().icon);
notification = builder.build();
}
startForeground(getServiceId(), notification);
}
#Override
public void onDestroy() {
super.onDestroy();
pythonThread = null;
if (autoRestartService && startIntent != null) {
Log.v("python service", "service restart requested");
startService(startIntent);
}
Process.killProcess(Process.myPid());
}
/**
* Stops the task gracefully when killed.
* Calling stopSelf() will trigger a onDestroy() call from the system.
*/
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
stopSelf();
}
#Override
public void run(){
String app_root = getFilesDir().getAbsolutePath() + "/app";
File app_root_file = new File(app_root);
PythonUtil.loadLibraries(app_root_file,
new File(getApplicationInfo().nativeLibraryDir));
this.mService = this;
nativeStart(
androidPrivate, androidArgument,
serviceEntrypoint, pythonName,
pythonHome, pythonPath,
pythonServiceArgument);
stopSelf();
}
// Native part
public static native void nativeStart(
String androidPrivate, String androidArgument,
String serviceEntrypoint, String pythonName,
String pythonHome, String pythonPath,
String pythonServiceArgument);
}
and the class extending PythonService:
package org.test.schedules;
import android.content.Intent;
import android.content.Context;
import org.kivy.android.PythonService;
public class ServiceService extends PythonService {
#Override
protected int getServiceId() {
return 1;
}
static public void start(Context ctx, String pythonServiceArgument) {
Intent intent = new Intent(ctx, ServiceService.class);
String argument = ctx.getFilesDir().getAbsolutePath() + "/app";
intent.putExtra("androidPrivate", ctx.getFilesDir().getAbsolutePath());
intent.putExtra("androidArgument", argument);
intent.putExtra("serviceTitle", "Schedules1106fgs_sdk28");
intent.putExtra("serviceDescription", "Service");
intent.putExtra("serviceEntrypoint", "service/main.py");
intent.putExtra("pythonName", "service");
intent.putExtra("serviceStartAsForeground", "true");
intent.putExtra("pythonHome", argument);
intent.putExtra("pythonPath", argument + ":" + argument + "/lib");
intent.putExtra("pythonServiceArgument", pythonServiceArgument);
ctx.startService(intent);
}
static public void stop(Context ctx) {
Intent intent = new Intent(ctx, ServiceService.class);
ctx.stopService(intent);
}
}
Also here is a piece of AndroidManifest.xml
<activity android:name="org.kivy.android.PythonActivity"
android:label="#string/app_name"
android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|fontScale|uiMode|uiMode|screenSize|smallestScreenSize|layoutDirection"
android:screenOrientation="portrait"
android:launchMode="singleTask"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="org.kivy.android.PythonService"
android:process=":pythonservice" />
<service android:name="org.test.schedules.ServiceService"
android:process=":service_service" />
Will be much appreciated for your help
Update
I haven't found the solution yet but noticed but seems the issue is related to background cached process. So if I go to Developer options -> Running services -> Show cached processes and stop the process there manually the app restarts fine.
I guess the solution could be somehow to prevent creating the cached process in the background or to kill that process at some specific moment, on app exit or service restart, I'm not an expert in Android, can anyone help with this?
I have 2 services that are defined in the same thrift file and share a port. I can use any method from serviceA no problem but whenever i try to call any of ServiceB's methods i get the exception.
this is my thrift file (service-a.thrift):
service ServiceA extends common.CommonService {
list<i64> getByIds(1: list<i64> ids)
...
}
service ServiceB extends common.CommonService {
list<i64> getByIds(1: list<i64> ids)
...
}
notes:
I'm working with a python client
Thrift version 0.8.0
Any ideas?
We had this need as well and solved by writing a new implementation of TProcessor that creates a map of multiple processors. The only gotcha is that with this implementation you need to ensure no method names overlap - i.e. don't use nice generic names like Run() in different servers. Apologies on not converting C# to Python...
Example Class:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Thrift;
using Thrift.Protocol;
/// <summary>
/// Processor that allows for multiple services to run under one roof. Requires no method name conflicts across services.
/// </summary>
public class MultiplexProcessor : TProcessor {
public MultiplexProcessor(IEnumerable<TProcessor> processors) {
ProcessorMap = new Dictionary<string, Tuple<TProcessor, Delegate>>();
foreach (var processor in processors) {
var processMap = (IDictionary) processor.GetType().GetField("processMap_", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(processor);
foreach (string pmk in processMap.Keys) {
var imp = (Delegate) processMap[pmk];
try {
ProcessorMap.Add(pmk, new Tuple<TProcessor, Delegate>(processor, imp));
}
catch (ArgumentException) {
throw new ArgumentException(string.Format("Method already exists in process map: {0}", pmk));
}
}
}
}
protected readonly Dictionary<string, Tuple<TProcessor, Delegate>> ProcessorMap;
internal protected Dictionary<string, Tuple<TProcessor, Delegate>> GetProcessorMap() {
return new Dictionary<string, Tuple<TProcessor, Delegate>>(ProcessorMap);
}
public bool Process(TProtocol iprot, TProtocol oprot) {
try {
TMessage msg = iprot.ReadMessageBegin();
Tuple<TProcessor, Delegate> fn;
ProcessorMap.TryGetValue(msg.Name, out fn);
if (fn == null) {
TProtocolUtil.Skip(iprot, TType.Struct);
iprot.ReadMessageEnd();
var x = new TApplicationException(TApplicationException.ExceptionType.UnknownMethod, "Invalid method name: '" + msg.Name + "'");
oprot.WriteMessageBegin(new TMessage(msg.Name, TMessageType.Exception, msg.SeqID));
x.Write(oprot);
oprot.WriteMessageEnd();
oprot.Transport.Flush();
return true;
}
Console.WriteLine("Invoking service method {0}.{1}", fn.Item1, fn.Item2);
fn.Item2.Method.Invoke(fn.Item1, new object[] {msg.SeqID, iprot, oprot});
}
catch (IOException) {
return false;
}
return true;
}
}
Example Usage:
Processor = new MultiplexProcessor(
new List<TProcessor> {
new ReportingService.Processor(new ReportingServer()),
new MetadataService.Processor(new MetadataServer()),
new OtherService.Processor(new OtherService())
}
);
Server = new TThreadPoolServer(Processor, Transport);
As far as I know, there's no straightforward way to bind several services to a single port without adding this field to TMessage and recompiling thrift. If you want to have two services using the same Server, you should reimplement Thrift Server, which it doesn't seem an easy task