0

I have two codes and I want to combine Python code into Kivy code. python code:

import csv
import socket
import datetime
import time
from itertools import zip_longest

Time =[]
Price = []
fields = ['Time', 'Price']
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)       
port = 1 
hostMACAddress = ''              
s.bind((hostMACAddress,port))
s.listen(1)
client, address = s.accept()
while(1):
    message_received = client.recv(1024).decode('utf-8')
    data = message_received
    Price.append(float(data))
    Time.append(time.strftime("%a %I:%M:%S %p"))
    item_1 = Time
    item_2 = Price
    data = [item_1, item_2]
    export_data = zip_longest(*data, fillvalue = '')
    with open('data1.csv', 'w',  newline='') as file:
        write = csv.writer(file)
        write.writerow(("Time", "Price"))
        write.writerows(export_data)
s.close()

kivy code:

from kivy.lang import Builder
from kivymd.app import MDApp
from kivy.uix.floatlayout import FloatLayout
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
import matplotlib.pyplot as plt
import socket            
import os
import numpy as np
import datetime
import matplotlib.animation as animation
from matplotlib import style
import csv
import pandas as pd
from matplotlib.animation import FuncAnimation

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
x_values = []
y_values = []

def animate(i):
    data = pd.read_csv('data1.csv')
    x_values = data['Time']
    y_values = data['Price']
    plt.cla()
    plt.plot(x_values, y_values, color='green', linestyle='dashed', linewidth = 3, marker='o', markerfacecolor='blue', markersize=12)
    plt.gcf().autofmt_xdate()
    plt.tight_layout()

   
ani = FuncAnimation(plt.gcf(), animate, 5000)

plt.tight_layout()

class Matty(FloatLayout):
    def __init__(self , **kwargs):
        super(). __init__(**kwargs)
        
        box = self.ids.box
        box.add_widget(FigureCanvasKivyAgg(plt.gcf()))
    def save_it(self):
        pass

class MainApp(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "BlueGray"
        Builder.load_file('matty.kv')
        return Matty()



MainApp().run()

kv file:

<Matty>
    BoxLayout:
        id:box
        size_hint_y: .75
        pos_hint: {'x':0.0 , 'y':0.0}

I want to run the python code in the Kivy code to have a code. Every time I do this, the Kivy program does not respond. How can I get the data from the socket and save it to .csv file and then plot .csv data in kivy continuously.

Fathi
  • 3
  • 2

1 Answers1

0

Since your first code has no classes or methods, it will run its loop forever as soon as it is imported by python. You can still use that code by putting its import in a new thread. You can use something like:

def doit(self, button):
    print('importing')
    threading.Thread(target=self.do_import, daemon=True).start()
    print('imported')

def do_import(self):
    import python_code

where python_code is the name of the python file containing your python code (leave off the .py).

John Anderson
  • 35,991
  • 4
  • 13
  • 36