-
Notifications
You must be signed in to change notification settings - Fork 1
/
ScreenERWS.py
375 lines (306 loc) · 11.7 KB
/
ScreenERWS.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
from FileActions import *
from TimeHelper import *
from helperTwistedTcp import *
import sys,os,platform
from kivy.core.image import Image
from MyCalculate import MyCalculate, SPoint
from pygeodesy.sphericalTrigonometry import LatLon
from kivymd.app import MDApp
from kivymd.uix.boxlayout import MDBoxLayout
from kivy.uix.widget import Widget
from kivy.graphics import Color, Rectangle
from _functools import partial
from kivy.clock import Clock
from shapely.geometry.multipolygon import MultiPolygon
from shapely.geometry.point import Point
import numpy as np
from shapely.geometry.multipoint import MultiPoint
from DataSaveRestore import DataSR_save, DataSR_restore
from shapely.geometry import polygon
from shapely.geometry.polygon import Polygon
import _thread
class WeatherHelpers:
def __init__(self,
weatherIterEveryMin,
weatherFullPath,
weatherAdress
):
self.th = TimeHelper()
self.fa = FileActions()
self.weatherIterEveryMin = weatherIterEveryMin
self.weatherFullPath = weatherFullPath
self.weatherAdress = weatherAdress
self.eMin = []
for m in range (0,60*61, weatherIterEveryMin*60):
self.eMin.append(m)
print("every:",self.eMin)
self.iterClock = None
def getSleepTimeToNext(self):
tNow = self.th.getDate(resAsDic=True)
sNow = (tNow['M']*60)+(tNow['S'])
nextIn = -1
for m in self.eMin:
if sNow < m:
nextIn = m - sNow
break
if nextIn == -1:
nextIn = 0
print("next is in: [",nextIn,"] sec. in:",self.th.getNiceHowMuchTimeItsTaking(nextIn))
print(" it will be at:",self.th.getNiceDateFromTimestamp(self.th.getTimestamp()+nextIn))
return nextIn
def getFilesInWorkDir(self):
f = {}
for file in self.fa.getFileList(self.weatherFullPath):
#print("file",file)
if file[-4:] == '.gif':
tmp = file.split('_')
dateStr = '{}/{}/{} {}{}{}'.format(
tmp[1],tmp[2],tmp[3],
tmp[4],tmp[5],tmp[6][0:-4]
)
ts = self.th.getTimestampFromStr(dateStr)
f[ts] = {
'file': file
}
pathCasch = self.fa.join(
self.weatherFullPath,
("%s_casch__meshs"%file)
)
if self.fa.isFile(pathCasch):
f[ts]['cascheFile'] = pathCasch
f[ts]['casche'] = 1
else:
f[ts]['casche'] = 0
#print("------------------")
#print(f)
return f
def runDownloadThread(self, callbackOnDownloadDone = None):
print("runDownloadThread")
self.callbackOnDownloadDone = callbackOnDownloadDone
_thread.start_new(self.downloadIter, ())
def downloadIter(self,a=0,b=0,c=0):
while True:
fileName = "%s/wRadar_%s.gif" % (
self.weatherFullPath,
self.th.getNiceFileNameFromTimestamp()
)
DownloadFile( self.weatherAdress, fileName )
fSize = self.fa.getSizeNice( fileName )
print("service Download done !")
print("service file [",fileName,"]")
print("service file size is:",fSize)
print("service is done going to sleep")
if self.callbackOnDownloadDone:
self.callbackOnDownloadDone(fileName)
sleep = self.getSleepTimeToNext()
time.sleep(sleep)
class ScreenERWS:
wImgUrl = 'http://www.pancanal.com/eng/eie/radar/current_image.gif'
wDirName = 'ykWeather'
wIter = 5 # min
wLegend = [
[40,460], #min
[40,6], #max
]
wScale = {
'xy0': [209,168],
'll0': ["09° 21.5461' N", "079° 53.3004' W"],
'xy1': [408,228],
'll1': ["09° 33.3800' N", "078° 56.8303' W"],
}
wMy = ["09° 36.7351' N", "079° 35.1304' W"]
wFrame = [ 48,1, #top left
509,496 #bottom right
]
def __init__(self,gui):
self.gui = gui
self.th = TimeHelper()
self.fa = FileActions()
self.mc = MyCalculate()
if platform.release() == "4.15.0-126-generic":
print("platform my laptop?")
self.wPath = "/home/yoyo"
else:
self.wPath = "/storage/emulated/0"
self.wPath = self.fa.join(self.wPath, self.wDirName)
self.recomputeScaleInfo()
def recomputeScaleInfo(self):
print("recomputeScaleInfo")
pixDist = self.mc.distance(
SPoint( self.wScale['xy0'][0],self.wScale['xy0'][1] ),
SPoint( self.wScale['xy1'][0],self.wScale['xy1'][1] )
)
self.wScale['xyDist'] = pixDist
print("xyDist:",pixDist,'[pixels]')
LL0 = LatLon( self.wScale['ll0'][0], self.wScale['ll0'][1] )
LL1 = LatLon( self.wScale['ll1'][0], self.wScale['ll1'][1] )
llDist = LL0.distanceTo(LL1)
self.wScale['llDist'] = llDist
print("llDist:",llDist,'[meters]')
LLMy = LatLon( self.wMy[0], self.wMy[1] )
self.xyMy = [
self.mc.remap( self.wScale['xy0'][0], self.wScale['xy1'][0], LL0.lon, LL1.lon, LLMy.lon ),
self.mc.remap( self.wScale['xy0'][1], self.wScale['xy1'][1], LL0.lat, LL1.lat, LLMy.lat )
]
print("xyMy",self.xyMy)
def analiseImg(self, imgPath):
print("analiseImg [%s]"%imgPath)
img = Image.load(imgPath,keep_data=True)
size = img.size
self.wSize = size
print("image size:",size)
self.steps = self.analiseSteps(img)
print("found legend steps",len(self.steps))
cPath = "%s_casch_"%imgPath
cCover = "%s_cover"%cPath
cPolis = "%s_polis"%cPath
cMeshs = "%s_meshs"%cPath
if self.fa.isFile(cMeshs):
print("pickle meshs :) ?")
m = DataSR_restore(cMeshs)
self.polis = {}
print("got from cashe file steps",len(m))
for si,k in enumerate(m.keys()):
print("restoring step",k)
print("meshes",len(m[k]))
m0 = Polygon()
meshs = m[k]
for me in meshs:
print("points:",len(me))
#print("->",me)
m1 = Polygon(me).simplify(0.1,preserve_topology=True)
m0 = m0.union( m1 ).simplify(0.1,preserve_topology=True)
self.polis[int(k)] = m0
print("poli DONE area",self.polis[int(k)].area)
else:
self.cover,self.polis,self.meshs = self.analiseCover(img)
DataSR_save(self.meshs, cMeshs)
def analiseCover(self, img):
cover = {}
polis = {}
meshs = {}
for r in range(len(self.steps)):
cover[ r ] = []
polis[ r ] = None
meshs[ str(r) ] = []
for x in range(self.wFrame[0], self.wFrame[2],1):
for y in range(self.wFrame[1], self.wFrame[3],1):
c = img.read_pixel(x,y)
try:
ci = self.steps.index(c)
except:
ci = -1
if ci >= 0:
#print("c",c,' ci',ci)
p = (x,y)
for cc in range(0,ci+1, 1):
cover[cc].append(p)
for r in range(len(self.steps)):
if r >= 0:
print("cover at ",r,' pixels',len(cover[r]))
polis[r] = MultiPoint(cover[r])
polis[r] = polis[r].buffer(1.0).buffer(-3.0).buffer(2.0)
polis[r] = polis[r].simplify(0.75,preserve_topology=True)
print("is valid multipoly",polis[r].is_valid)
print("area",polis[r].area)
try:
print("geoms",len(polis[r].geoms))
haveGeoms = True
except:
haveGeoms = False
print("no geoms but have exterior?")
print(len(polis[r].exterior.coords))
if len(polis[r].exterior.coords):
ta = []
for mp in list(polis[r].exterior.coords[:]):
ta.append( [int(mp[0]), int(mp[1])] )
meshs[str(r)].append( ta )
if haveGeoms:
for g in polis[r].geoms:
ta = []
for mp in list(g.exterior.coords[:]):
ta.append( [int(mp[0]), int(mp[1])] )
meshs[str(r)].append( ta )
#except:
# print("no geoms so one poly ?")
return cover,polis,meshs
def analiseSteps(self, img):
#return legend from max rain to min colors
s = []
x = self.wLegend[0][0]
cLast = None
for y in range(self.wLegend[1][1],self.wLegend[0][1],1):
c = img.read_pixel(x,y)
#print("y:",y," - color",c)
if cLast == None or cLast != c:
cLast = c
s.append(c)
s.reverse()
return s
class ScreenERWSWid(Widget):
pass
class ScreenERWSWidget:
def build(self):
bl = MDBoxLayout(orientation="vertical")
i = ScreenERWSWid(
size_hint = [None,None],
size = [512,512]
)
self.can = i.canvas
bl.add_widget(i)
return bl
def drawSomeStuff(self, ana,a=0,b=0):
self.ana = ana
a = self.ana
with self.can:
Color(0,0,0)
Rectangle(
size=[512,512],
pos=[0,0]
)
#legend
y = 0
for l in a.steps:
Color(l[0],l[1],l[2])
Rectangle(
size=[10,10],
pos=[0,y]
)
y+=10
#cloudCover
for li, l in enumerate(a.steps):
if li in [3,4,7,8]:
Color(l[0],l[1],l[2])
poli = a.polis[li]
for x in range(a.wFrame[0], a.wFrame[2],1):
for y in range(a.wFrame[1], a.wFrame[3],1):
if poli.contains(Point(x,y)):
Rectangle(
size=[1,1],
pos=[x,a.wSize[1]-y]
)
class ScreenERWSAlone(ScreenERWSWidget,MDApp):
pass
if __name__ == "__main__":
print("stand alone")
print("Early Rain Warning System")
args = sys.argv[1:]
argsCount = len( args )
print("args: {0}".format(args))
if len(args) == 1:
file = args[0]
doGui = False
else:
file = '/home/yoyo/ykWeather/wRadar_2020_08_16_08_59_44.gif'
doGui = True
print("file ",file)
#sys.exit(9)
if doGui:
sa = ScreenERWSAlone()
else:
sa = 0
s = ScreenERWS(sa)
s.analiseImg(file)
if doGui:
Clock.schedule_once( partial(sa.drawSomeStuff,(s)), 1 )
sa.run()